"""Offline Playwright Chromium lab for Vue3 Ch33: TaskHub core business logic."""
import http.server
import json
import socketserver
import threading
from playwright.sync_api import sync_playwright
HTML = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>TaskHub Core Lab</title>
<style>
:root { --color-brand: #3b82f6; }
body { margin: 0; background: #f8fafc; color: #0f172a; font-family: system-ui, sans-serif; }
.card { max-width: 448px; margin: 24px auto; background: #fff; border-radius: 24px; overflow: hidden; }
.hero { background-image: linear-gradient(to bottom right, #2563eb, #4338ca); padding: 32px; color: #fff; }
.hero-sub { color: rgba(219, 234, 254, 0.8); font-size: 14px; }
.input-row { display: flex; gap: 8px; margin: 20px; }
#new-task { flex: 1; padding: 12px 16px; border: none; border-radius: 16px; background: #f8fafc; outline: none; }
#new-task:focus { box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5); }
#add-btn { background: var(--color-brand); color: #fff; border: none; border-radius: 16px; padding: 0 24px; font-weight: 700; transition: transform 0.15s; }
#add-btn:active { transform: scale(0.95); }
.filters { display: flex; margin: 0 20px 16px; padding: 4px; background: #f1f5f9; border-radius: 12px; }
.filters button { flex: 1; border: none; background: transparent; padding: 6px; font-weight: 700; cursor: pointer; }
.filters button.active { background: #fff; color: var(--color-brand); border-radius: 8px; }
ul { list-style: none; margin: 0 20px 20px; padding: 0; }
li.group { display: flex; justify-content: space-between; align-items: center; padding: 14px; margin-bottom: 10px; background: #f8fafc; border-radius: 16px; }
li.group .del-btn { opacity: 0; border: none; background: transparent; cursor: pointer; }
li.group:hover .del-btn { opacity: 1; }
.done { text-decoration: line-through; opacity: 0.5; }
.list-enter-active, .list-leave-active { transition: all 0.4s cubic-bezier(0.18, 0.89, 0.32, 1.28); }
.list-enter-from, .list-leave-to { opacity: 0; transform: translateX(30px); }
#empty-tip { text-align: center; padding: 32px; color: #94a3b8; display: none; }
</style>
</head>
<body>
<div class="card">
<header class="hero">
<h1>TaskHub</h1>
<p class="hero-sub">Vue 3 + Tailwind v4 实战</p>
</header>
<main>
<div class="input-row">
<input id="new-task" placeholder="今天要完成什么?" />
<button id="add-btn" type="button">+</button>
</div>
<div class="filters">
<button data-f="all" class="active" type="button">all</button>
<button data-f="active" type="button">active</button>
<button data-f="completed" type="button">completed</button>
</div>
<ul id="task-ul"></ul>
<div id="empty-tip">暂无相关任务...</div>
</main>
</div>
<script>
const tasks = [
{ id: '1', title: '体验 Tailwind v4 新特性', isCompleted: false },
{ id: '2', title: '掌握 Composition API', isCompleted: true }
];
let currentFilter = 'all';
let newTaskTitle = '';
let computedRuns = 0;
let dirty = true;
let cachedFiltered = [];
const enteredKeys = [];
function invalidate() { dirty = true; }
function getFilteredTasks() {
if (dirty) {
computedRuns++;
if (currentFilter === 'active') cachedFiltered = tasks.filter(t => !t.isCompleted);
else if (currentFilter === 'completed') cachedFiltered = tasks.filter(t => t.isCompleted);
else cachedFiltered = [...tasks];
dirty = false;
}
return cachedFiltered;
}
const inputEl = document.getElementById('new-task');
inputEl.addEventListener('input', (e) => { newTaskTitle = e.target.value; });
function addTask() {
const title = newTaskTitle.trim();
if (!title) return;
const id = crypto.randomUUID();
tasks.unshift({ id, title, isCompleted: false });
newTaskTitle = '';
inputEl.value = '';
enteredKeys.push(id);
invalidate();
render(id);
}
function removeTask(id) {
const idx = tasks.findIndex(t => t.id === id);
if (idx !== -1) tasks.splice(idx, 1);
invalidate();
render();
}
function toggleTask(id) {
const t = tasks.find(x => x.id === id);
if (t) t.isCompleted = !t.isCompleted;
invalidate();
render();
}
function render(newKey = null) {
const list = getFilteredTasks();
const ul = document.getElementById('task-ul');
const existing = new Map([...ul.children].map(el => [el.dataset.key, el]));
const fragment = document.createDocumentFragment();
for (const task of list) {
let li = existing.get(task.id);
if (!li) {
li = document.createElement('li');
li.className = 'group';
li.dataset.key = task.id;
if (newKey && task.id === newKey) {
li.classList.add('list-enter-from', 'list-enter-active');
}
const left = document.createElement('div');
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.addEventListener('change', () => toggleTask(task.id));
const span = document.createElement('span');
left.append(cb, span);
const del = document.createElement('button');
del.className = 'del-btn';
del.textContent = '✕';
del.addEventListener('click', () => removeTask(task.id));
li.append(left, del);
}
li.querySelector('input[type="checkbox"]').checked = task.isCompleted;
const sp = li.querySelector('span');
sp.textContent = task.title;
sp.className = task.isCompleted ? 'done' : '';
fragment.appendChild(li);
}
ul.innerHTML = '';
ul.appendChild(fragment);
document.getElementById('empty-tip').style.display = list.length === 0 ? 'block' : 'none';
document.querySelectorAll('.filters button').forEach(btn => {
btn.classList.toggle('active', btn.dataset.f === currentFilter);
});
}
inputEl.addEventListener('keyup', (e) => { if (e.key === 'Enter') addTask(); });
document.getElementById('add-btn').addEventListener('click', addTask);
document.querySelectorAll('.filters button').forEach(btn => {
btn.addEventListener('click', () => {
currentFilter = btn.dataset.f;
invalidate();
render();
});
});
window.__metrics = () => {
const before = computedRuns;
const a = getFilteredTasks().length;
const b = getFilteredTasks().length;
return { runsBeforeRepeatedReads: before, runsAfterRepeatedReads: computedRuns, lenA: a, lenB: b };
};
render();
</script>
</body>
</html>
"""
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
data = HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *args):
pass
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
srv = socketserver.TCPServer(("127.0.0.1", 0), Handler)
port = srv.server_address[1]
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.goto(f"http://127.0.0.1:{port}/", wait_until="domcontentloaded")
# Case 1: v-model + @keyup.enter + crypto.randomUUID() + unshift + blank rejection
page.fill("#new-task", " ")
page.press("#new-task", "Enter")
count_after_blank = page.locator("#task-ul li").count()
page.fill("#new-task", "编写单元测试")
page.press("#new-task", "Enter")
first_title = page.locator("#task-ul li").first.locator("span").text_content()
first_key = page.locator("#task-ul li").first.get_attribute("data-key")
input_cleared = page.input_value("#new-task") == ""
has_enter_class = page.locator("#task-ul li").first.evaluate("el => el.classList.contains('list-enter-from')")
act1 = {
"count_after_blank": count_after_blank,
"count_after_add": page.locator("#task-ul li").count(),
"first_title": first_title,
"uuid_len": len(first_key or ""),
"input_cleared": input_cleared,
"has_enter_class": has_enter_class,
}
exp1 = {
"count_after_blank": 2,
"count_after_add": 3,
"first_title": "编写单元测试",
"uuid_len": 36,
"input_cleared": True,
"has_enter_class": True,
}
cases.append({"name": "task_crud_vmodel_enter", "expected": exp1, "actual": act1, "passed": act1 == exp1})
# Case 2: Tailwind v4 styles, group-hover opacity, focus ring
page.focus("#new-task")
styles = page.evaluate("""() => {
const hero = getComputedStyle(document.querySelector('.hero'));
const sub = getComputedStyle(document.querySelector('.hero-sub'));
const btn = getComputedStyle(document.getElementById('add-btn'));
const inp = getComputedStyle(document.getElementById('new-task'));
const delRest = getComputedStyle(document.querySelector('#task-ul li .del-btn')).opacity;
return {
hasGradient: hero.backgroundImage.includes('linear-gradient'),
subAlpha80: sub.color === 'rgba(219, 234, 254, 0.8)',
brandBg: btn.backgroundColor,
hasFocusRing: inp.boxShadow.includes('59, 130, 246'),
delRest
};
}""")
page.locator("#task-ul li").first.hover()
del_hover = page.locator("#task-ul li").first.locator(".del-btn").evaluate("el => getComputedStyle(el).opacity")
act2 = {**styles, "delHover": del_hover}
exp2 = {
"hasGradient": True,
"subAlpha80": True,
"brandBg": "rgb(59, 130, 246)",
"hasFocusRing": True,
"delRest": "0",
"delHover": "1",
}
cases.append({"name": "tailwind_v4_styles_and_hover", "expected": exp2, "actual": act2, "passed": act2 == exp2})
# Case 3: computed filter caching + toggle + delete to empty state
cache_check = page.evaluate("window.__metrics()")
page.click('.filters button[data-f="active"]')
active_cnt = page.locator("#task-ul li").count()
page.click('.filters button[data-f="completed"]')
completed_cnt = page.locator("#task-ul li").count()
page.click('.filters button[data-f="all"]')
page.locator("#task-ul li").first.locator('input[type="checkbox"]').click()
page.click('.filters button[data-f="completed"]')
completed_after_toggle = page.locator("#task-ul li").count()
page.click('.filters button[data-f="all"]')
while page.locator("#task-ul li").count() > 0:
page.locator("#task-ul li").first.hover()
page.locator("#task-ul li").first.locator(".del-btn").click()
empty_visible = page.locator("#empty-tip").is_visible()
empty_text = page.locator("#empty-tip").text_content().strip()
act3 = {
"cache_hit_no_recompute": cache_check["runsBeforeRepeatedReads"] == cache_check["runsAfterRepeatedReads"],
"active_cnt": active_cnt,
"completed_cnt": completed_cnt,
"completed_after_toggle": completed_after_toggle,
"empty_visible": empty_visible,
"empty_text": empty_text,
}
exp3 = {
"cache_hit_no_recompute": True,
"active_cnt": 2,
"completed_cnt": 1,
"completed_after_toggle": 2,
"empty_visible": True,
"empty_text": "暂无相关任务...",
}
cases.append({"name": "computed_filter_and_cache", "expected": exp3, "actual": act3, "passed": act3 == exp3})
browser.close()
finally:
srv.shutdown()
srv.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/vue3-taskhub-task-lab/explore-taskhub-task.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-taskhub-task.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a801.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a839.zip