"""Offline Playwright Chromium lab for jQuery EasyUI Ch 55 (tree-tree5): Tree Drag & Drop."""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs
from playwright.sync_api import sync_playwright
TREE_DATA = [
{
"id": 1,
"text": "Foods",
"children": [
{
"id": 2,
"text": "Fruits",
"children": [
{"id": 4, "text": "apple"},
{"id": 5, "text": "orange"},
],
},
{
"id": 3,
"text": "Vegetables",
"children": [
{"id": 6, "text": "tomato"},
{"id": 7, "text": "carrot"},
],
},
],
}
]
def start_server():
drop_events = []
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 == "/tree_data.json":
body = json.dumps(TREE_DATA).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)
def do_POST(self):
if self.path == "/save_drop":
length = int(self.headers.get("Content-Length", "0"))
params = parse_qs(self.rfile.read(length).decode("utf-8"))
rec = {
"id": int(params["id"][0]),
"targetId": int(params["targetId"][0]),
"point": params["point"][0],
}
drop_events.append(rec)
body = json.dumps({"ok": True, "saved": rec}).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_response(404)
self.end_headers()
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], drop_events
HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery EasyUI Tree DnD Offline Lab</title>
<style>
ul { list-style: none; padding-left: 16px; font-family: sans-serif; }
.tree-node { padding: 3px 6px; border: 1px solid transparent; }
</style>
</head>
<body>
<ul id="tt"></ul>
<script>
(function () {
const ul = document.getElementById('tt');
let cfg = { dnd: true, onDrop: null };
function build(container, items) {
for (const item of items) {
const li = document.createElement('li');
li.dataset.nodeId = String(item.id);
const row = document.createElement('div');
row.className = 'tree-node';
row.dataset.id = String(item.id);
row.dataset.text = item.text;
row.textContent = item.text;
li.appendChild(row);
if (item.children && item.children.length) {
const sub = document.createElement('ul');
build(sub, item.children);
li.appendChild(sub);
}
container.appendChild(li);
}
}
function getNode(el) {
return { id: Number(el.dataset.id), text: el.dataset.text, target: el };
}
async function performDrop(sourceId, targetId, point) {
if (!cfg.dnd) return { moved: false, reason: 'dnd_disabled' };
const srcLi = ul.querySelector(`li[data-node-id="${sourceId}"]`);
const tgtLi = ul.querySelector(`li[data-node-id="${targetId}"]`);
if (!srcLi || !tgtLi || srcLi === tgtLi || srcLi.contains(tgtLi)) {
return { moved: false, reason: 'invalid_cycle_or_same' };
}
const source = getNode(srcLi.querySelector(':scope > .tree-node'));
const targetNode = tgtLi.querySelector(':scope > .tree-node');
if (point === 'append') {
let sub = tgtLi.querySelector(':scope > ul');
if (!sub) {
sub = document.createElement('ul');
tgtLi.appendChild(sub);
}
sub.appendChild(srcLi);
} else if (point === 'top') {
tgtLi.parentElement.insertBefore(srcLi, tgtLi);
} else if (point === 'bottom') {
tgtLi.parentElement.insertBefore(srcLi, tgtLi.nextSibling);
}
if (cfg.onDrop) {
await cfg.onDrop(targetNode, source, point);
}
return { moved: true };
}
function childrenTexts(id) {
const li = ul.querySelector(`li[data-node-id="${id}"]`);
const sub = li ? li.querySelector(':scope > ul') : null;
if (!sub) return [];
return Array.from(sub.querySelectorAll(':scope > li > .tree-node')).map(e => e.dataset.text);
}
window.$ = (sel) => ({
tree: (arg1, arg2) => {
if (typeof arg1 === 'object') {
cfg = Object.assign({ dnd: false }, arg1);
return fetch(cfg.url).then(r => r.json()).then(data => build(ul, data));
}
if (arg1 === 'getNode') return getNode(arg2);
if (arg1 === 'options') return cfg;
}
});
window.__dndReady = $('#tt').tree({
dnd: true,
url: '/tree_data.json',
onDrop: async function (targetNode, source, point) {
const targetId = $('#tt').tree('getNode', targetNode).id;
await fetch('/save_drop', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `id=${source.id}&targetId=${targetId}&point=${encodeURIComponent(point)}`
});
}
});
window.__performDrop = performDrop;
window.__childrenTexts = childrenTexts;
window.__setDnd = (flag) => { cfg.dnd = flag; };
})();
</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, drop_events = 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.__dndReady")
# Case 1: Drop apple(4) onto Vegetables(3) with point='append'
r1 = page.evaluate("""async () => {
const status = await window.__performDrop(4, 3, 'append');
return {
status,
fruits: window.__childrenTexts(2),
vegetables: window.__childrenTexts(3)
};
}""")
act1 = {**r1, "server_events": list(drop_events)}
exp1 = {
"status": {"moved": True},
"fruits": ["orange"],
"vegetables": ["tomato", "carrot", "apple"],
"server_events": [{"id": 4, "targetId": 3, "point": "append"}],
}
cases.append({
"name": "tree_dnd_append_reparent_and_post",
"passed": act1 == exp1,
"expected": exp1,
"actual": act1,
})
# Case 2: Drop orange(5) before tomato(6) with point='top'
r2 = page.evaluate("""async () => {
const status = await window.__performDrop(5, 6, 'top');
return {
status,
fruits: window.__childrenTexts(2),
vegetables: window.__childrenTexts(3)
};
}""")
act2 = {**r2, "last_event": drop_events[-1]}
exp2 = {
"status": {"moved": True},
"fruits": [],
"vegetables": ["orange", "tomato", "carrot", "apple"],
"last_event": {"id": 5, "targetId": 6, "point": "top"},
}
cases.append({
"name": "tree_dnd_top_insert_and_onDrop_point",
"passed": act2 == exp2,
"expected": exp2,
"actual": act2,
})
# Case 3: Ancestor-into-descendant cycle blocked & dnd=false guard
r3 = page.evaluate("""async () => {
const cycle = await window.__performDrop(1, 3, 'append');
window.__setDnd(false);
const disabled = await window.__performDrop(6, 2, 'append');
return { cycle, disabled };
}""")
act3 = {**r3, "total_server_events": len(drop_events)}
exp3 = {
"cycle": {"moved": False, "reason": "invalid_cycle_or_same"},
"disabled": {"moved": False, "reason": "dnd_disabled"},
"total_server_events": 2,
}
cases.append({
"name": "tree_dnd_cycle_and_disabled_guards",
"passed": act3 == exp3,
"expected": exp3,
"actual": act3,
})
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-tree5-lab/explore-tree-tree5.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tree-tree5.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1017.zip