"""Offline Playwright Chromium lab for jQuery EasyUI Ch 43: DataGrid SubGrid."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import threading
from urllib.parse import parse_qs, urlparse
from playwright.sync_api import sync_playwright
ALL_ITEMS = [
{"itemid": "EST-1", "productid": "FI-SW-01", "listprice": "16.50", "unitcost": "10.00", "attr1": "Large", "status": "P"},
{"itemid": "EST-2", "productid": "K9-DL-01", "listprice": "18.50", "unitcost": "12.00", "attr1": "Spotted Adult Female", "status": "P"},
{"itemid": "EST-3", "productid": "RP-SN-01", "listprice": "18.50", "unitcost": "12.00", "attr1": "Venomless", "status": "P"},
{"itemid": "EST-99", "productid": "ORPHAN-01", "listprice": "9.00", "unitcost": "4.00", "attr1": "No Orders", "status": "P"},
]
LINEITEMS = [
{"itemid": "EST-1", "orderid": "ORD-1001", "quantity": 2, "unitprice": "16.50"},
{"itemid": "EST-1", "orderid": "ORD-1002", "quantity": 5, "unitprice": "16.00"},
{"itemid": "EST-1", "orderid": "ORD-1005", "quantity": 1, "unitprice": "16.50"},
{"itemid": "EST-2", "orderid": "ORD-1003", "quantity": 3, "unitprice": "18.50"},
{"itemid": "EST-2", "orderid": "ORD-1004", "quantity": 4, "unitprice": "18.00"},
{"itemid": "EST-3", "orderid": "ORD-1006", "quantity": 2, "unitprice": "18.50"},
]
HTML_PAGE = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI DataGrid SubGrid Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 16px; font-size: 13px; }
.dg-wrap { width: 700px; border: 1px solid #95b8e7; }
.dg-title { background: #e0ecff; padding: 6px 8px; font-weight: bold; }
table#dg, table.ddv { width: 100%; border-collapse: collapse; }
table#dg th, table#dg td, table.ddv th, table.ddv td { border: 1px solid #ccc; padding: 4px 6px; }
table#dg th { background: #f4f4f4; }
table.ddv th { background: #eef6ff; }
table.ddv tbody tr { cursor: pointer; }
table.ddv tbody tr.selected { background: #ffe48d; }
tr.detail-row.hidden { display: none; }
.expander { width: 20px; height: 20px; cursor: pointer; font-weight: bold; }
</style>
</head>
<body>
<div class="dg-wrap">
<div class="dg-title">DataGrid - SubGrid</div>
<table id="dg">
<thead>
<tr>
<th style="width:28px"></th>
<th>Item ID</th><th>Product ID</th><th>List Price</th><th>Unit Cost</th><th>Attribute</th><th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
const fixCalls = [];
function fixDetailRowHeight(index, reason) {
const dtr = document.querySelector(`tr.detail-row[data-index="${index}"]`);
const h = Math.round(dtr.querySelector(".detail-wrap").getBoundingClientRect().height);
dtr.dataset.fixedHeight = String(h);
fixCalls.push({ index, reason, height: h });
}
async function mountSubGrid(tableEl, index, itemid) {
const resp = await fetch(`/datagrid22_getdetail?itemid=${encodeURIComponent(itemid)}`);
const rows = await resp.json();
tableEl.innerHTML = `
<thead><tr><th style="width:28px">#</th><th>Order ID</th><th>Quantity</th><th>Unit Price</th></tr></thead>
<tbody></tbody>`;
const tbody = tableEl.querySelector("tbody");
rows.forEach((r, i) => {
const tr = document.createElement("tr");
tr.dataset.orderid = r.orderid;
tr.innerHTML = `<td>${i + 1}</td><td>${r.orderid}</td><td>${r.quantity}</td><td>${r.unitprice}</td>`;
tr.addEventListener("click", () => {
tbody.querySelectorAll("tr").forEach(el => el.classList.remove("selected"));
tr.classList.add("selected");
});
tbody.appendChild(tr);
});
tableEl.dataset.loaded = "true";
setTimeout(() => fixDetailRowHeight(index, "onLoadSuccess"), 0);
}
async function initMaster() {
const resp = await fetch("/datagrid22_getdata");
const rows = await resp.json();
const tbody = document.querySelector("#dg tbody");
tbody.innerHTML = "";
rows.forEach((row, index) => {
const tr = document.createElement("tr");
tr.className = "master-row";
tr.dataset.index = String(index);
tr.dataset.itemid = row.itemid;
tr.innerHTML = `
<td style="text-align:center"><button type="button" class="expander" data-index="${index}">+</button></td>
<td>${row.itemid}</td><td>${row.productid}</td>
<td style="text-align:right">${row.listprice}</td><td style="text-align:right">${row.unitcost}</td>
<td>${row.attr1}</td><td style="text-align:center">${row.status}</td>`;
const dtr = document.createElement("tr");
dtr.className = "detail-row hidden";
dtr.dataset.index = String(index);
dtr.innerHTML = `<td colspan="7"><div class="detail-wrap" style="padding:2px"><table class="ddv" data-parent="${row.itemid}"></table></div></td>`;
tbody.append(tr, dtr);
tr.querySelector(".expander").addEventListener("click", async (ev) => {
const btn = ev.currentTarget;
if (btn.textContent === "-") {
btn.textContent = "+";
dtr.classList.add("hidden");
return;
}
btn.textContent = "-";
dtr.classList.remove("hidden");
fixDetailRowHeight(index, "onExpandRow");
const subTable = dtr.querySelector("table.ddv");
await mountSubGrid(subTable, index, row.itemid);
});
});
window.__masterReady = true;
}
window.lab = { fixCalls, triggerResize: (index) => fixDetailRowHeight(index, "onResize") };
initMaster();
</script>
</body>
</html>
"""
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def do_GET(self):
parsed = urlparse(self.path)
if parsed.path == "/":
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(HTML_PAGE.encode("utf-8"))
elif parsed.path == "/datagrid22_getdata":
# Mirrors: select * from item where itemid in (select itemid from lineitem)
linked = {li["itemid"] for li in LINEITEMS}
matched = [it for it in ALL_ITEMS if it["itemid"] in linked]
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(matched).encode("utf-8"))
elif parsed.path == "/datagrid22_getdetail":
itemid = parse_qs(parsed.query).get("itemid", [""])[0]
matched = [li for li in LINEITEMS if li["itemid"] == itemid]
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(matched).encode("utf-8"))
else:
self.send_response(404)
self.end_headers()
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
server = HTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.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}/")
page.wait_for_function("() => window.__masterReady === true")
# Case 1: Master grid filters to items having lineitems and embeds table.ddv placeholders
res1 = page.evaluate("""() => ({
masterIds: Array.from(document.querySelectorAll("tr.master-row")).map(r => r.dataset.itemid),
subTableCount: document.querySelectorAll("table.ddv").length
})""")
exp1 = {"masterIds": ["EST-1", "EST-2", "EST-3"], "subTableCount": 3}
cases.append(dict(name="subgrid_master_load_and_detail_formatter", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Expanding row 0 loads 3-column nested DataGrid and triggers fixDetailRowHeight
page.click('.expander[data-index="0"]')
page.wait_for_selector('table.ddv[data-parent="EST-1"][data-loaded="true"]')
page.wait_for_function("() => window.lab.fixCalls.some(c => c.index === 0 && c.reason === 'onLoadSuccess')")
page.evaluate("() => window.lab.triggerResize(0)")
res2 = page.evaluate("""() => {
const sub = document.querySelector('table.ddv[data-parent="EST-1"]');
const headers = Array.from(sub.querySelectorAll(":scope > thead > tr > th")).map(th => th.textContent);
const orderIds = Array.from(sub.querySelectorAll(":scope > tbody > tr")).map(tr => tr.dataset.orderid);
const reasons = window.lab.fixCalls.filter(c => c.index === 0).map(c => c.reason);
return { headers, orderIds, fixReasons: reasons };
}""")
exp2 = {
"headers": ["#", "Order ID", "Quantity", "Unit Price"],
"orderIds": ["ORD-1001", "ORD-1002", "ORD-1005"],
"fixReasons": ["onExpandRow", "onLoadSuccess", "onResize"],
}
cases.append(dict(name="subgrid_expand_loads_nested_datagrid", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Multi-expand keeps independent singleSelect state and distinct detail heights
page.click('.expander[data-index="1"]')
page.wait_for_selector('table.ddv[data-parent="EST-2"][data-loaded="true"]')
page.wait_for_function("() => window.lab.fixCalls.some(c => c.index === 1 && c.reason === 'onLoadSuccess')")
page.click('table.ddv[data-parent="EST-1"] tbody tr[data-orderid="ORD-1002"]')
page.click('table.ddv[data-parent="EST-2"] tbody tr[data-orderid="ORD-1004"]')
res3 = page.evaluate("""() => {
const s0 = document.querySelector('table.ddv[data-parent="EST-1"] tbody tr.selected').dataset.orderid;
const s1 = document.querySelector('table.ddv[data-parent="EST-2"] tbody tr.selected').dataset.orderid;
const h0 = Number(document.querySelector('tr.detail-row[data-index="0"]').dataset.fixedHeight);
const h1 = Number(document.querySelector('tr.detail-row[data-index="1"]').dataset.fixedHeight);
return {
sub0Selected: s0,
sub1Selected: s1,
sub0TallerThanSub1: h0 > h1
};
}""")
exp3 = {"sub0Selected": "ORD-1002", "sub1Selected": "ORD-1004", "sub0TallerThanSub1": True}
cases.append(dict(name="subgrid_independent_selection_and_multi_expand", expected=exp3, actual=res3, passed=(res3 == exp3)))
browser.close()
finally:
server.shutdown()
server.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/jeasyui-datagrid-datagrid22-lab/explore-datagrid-datagrid22.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-datagrid-datagrid22.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a979.zip
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip