"""Offline Playwright Chromium lab for jQuery EasyUI Ch 56 (tree-tree6): Adjacency List loadFilter."""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from playwright.sync_api import sync_playwright
FLAT_ROWS = [
{"id": 1, "parendId": 0, "name": "Foods"},
{"id": 2, "parentId": 1, "name": "Fruits"},
{"id": 3, "parentId": 1, "name": "Vegetables"},
{"id": 4, "parentId": 2, "name": "apple"},
{"id": 5, "parentId": 2, "name": "orange"},
{"id": 6, "parentId": 3, "name": "tomato"},
{"id": 7, "parentId": 3, "name": "carrot"},
{"id": 8, "parentId": 3, "name": "cabbage"},
{"id": 9, "parentId": 3, "name": "potato"},
{"id": 10, "parentId": 3, "name": "lettuce"},
]
def start_server():
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def do_GET(self):
if self.path == "/":
body = HTML_DOC.encode("utf-8")
ctype = "text/html; charset=utf-8"
elif self.path == "/data/tree6_data.json":
body = json.dumps(FLAT_ROWS).encode("utf-8")
ctype = "application/json; charset=utf-8"
else:
self.send_response(404)
self.end_headers()
return
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
srv = HTTPServer(("127.0.0.1", 0), Handler)
t = threading.Thread(target=srv.serve_forever, daemon=True)
t.start()
return srv, srv.server_address[1]
HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery EasyUI Tree loadFilter Offline Lab</title>
</head>
<body>
<ul id="tt"></ul>
<script>
function convert(rows) {
function exists(list, parentId) {
for (let i = 0; i < list.length; i++) {
if (list[i].id == parentId) return true;
}
return false;
}
const nodes = [];
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
if (!exists(rows, row.parentId)) {
nodes.push({ id: row.id, text: row.name });
}
}
const toDo = [];
for (let i = 0; i < nodes.length; i++) {
toDo.push(nodes[i]);
}
while (toDo.length) {
const node = toDo.shift();
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
if (row.parentId == node.id) {
const child = { id: row.id, text: row.name };
if (node.children) {
node.children.push(child);
} else {
node.children = [child];
}
toDo.push(child);
}
}
}
return nodes;
}
function renderTree(container, nodes) {
container.innerHTML = '';
for (const n of nodes) {
const li = document.createElement('li');
li.dataset.id = String(n.id);
const span = document.createElement('span');
span.textContent = n.text;
li.appendChild(span);
if (n.children && n.children.length) {
const sub = document.createElement('ul');
renderTree(sub, n.children);
li.appendChild(sub);
}
container.appendChild(li);
}
}
window.__convert = convert;
window.__converted = null;
window.__ready = fetch('/data/tree6_data.json')
.then(r => r.json())
.then(rows => {
const treeNodes = convert(rows);
window.__converted = treeNodes;
renderTree(document.getElementById('tt'), treeNodes);
});
</script>
</body>
</html>
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
srv, port = start_server()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.goto(f"http://127.0.0.1:{port}/")
page.evaluate("() => window.__ready")
# Case 1: Flat adjacency list converted via loadFilter into 3-level nested tree
res1 = page.evaluate("""() => {
const root = window.__converted[0];
return {
top_count: window.__converted.length,
root_text: root.text,
lvl2_texts: root.children.map(c => c.text),
fruits_children: root.children[0].children.map(c => c.text),
veg_children: root.children[1].children.map(c => c.text),
dom_li_count: document.querySelectorAll('#tt li').length
};
}""")
exp1 = {
"top_count": 1,
"root_text": "Foods",
"lvl2_texts": ["Fruits", "Vegetables"],
"fruits_children": ["apple", "orange"],
"veg_children": ["tomato", "carrot", "cabbage", "potato", "lettuce"],
"dom_li_count": 10,
}
cases.append({
"name": "loadfilter_convert_flat_adjacency_to_tree",
"passed": res1 == exp1,
"expected": exp1,
"actual": res1,
})
# Case 2: Orphan parentId or missing parentId promoted cleanly to top-level roots
res2 = page.evaluate("""() => {
const sample = [
{ id: 10, parentId: 999, name: 'OrphanRoot' },
{ id: 11, parentId: 10, name: 'ChildA' },
{ id: 12, name: 'NoParentKey' }
];
const out = window.__convert(sample);
return {
root_ids: out.map(n => n.id),
orphan_children: out[0].children.map(c => c.text),
second_has_children: Boolean(out[1].children)
};
}""")
exp2 = {
"root_ids": [10, 12],
"orphan_children": ["ChildA"],
"second_has_children": False,
}
cases.append({
"name": "loadfilter_exists_check_handles_orphan_and_missing_parent",
"passed": res2 == exp2,
"expected": exp2,
"actual": res2,
})
# Case 3: 4-level deep hierarchy conversion preserves exact BFS nesting & order
res3 = page.evaluate("""() => {
const deep = [
{ id: 1, parentId: 0, name: 'L1' },
{ id: 2, parentId: 1, name: 'L2' },
{ id: 3, parentId: 2, name: 'L3' },
{ id: 4, parentId: 3, name: 'L4' }
];
const out = window.__convert(deep);
let cur = out[0], path = [];
while (cur) {
path.push(cur.text);
cur = cur.children ? cur.children[0] : null;
}
return { depth: path.length, path };
}""")
exp3 = {"depth": 4, "path": ["L1", "L2", "L3", "L4"]}
cases.append({
"name": "loadfilter_deep_bfs_nesting",
"passed": res3 == exp3,
"expected": exp3,
"actual": res3,
})
browser.close()
finally:
srv.shutdown()
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/jeasyui-tree-tree6-lab/explore-tree-tree6.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tree-tree6.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1018.zip