"""Offline Playwright Chromium lab for jQuery EasyUI Ch 42: DataGrid Expand Row (detailview)."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import threading
from urllib.parse import parse_qs, urlparse
from playwright.sync_api import sync_playwright
ITEMS = [
{"itemid": "EST-10", "productid": "K9-DL-01", "listprice": "18.50", "unitcost": "12.00", "attr1": "Spotted Adult Female", "status": "P"},
{"itemid": "EST-9", "productid": "K9-RT-02", "listprice": "145.49", "unitcost": "100.00", "attr1": "Adult Female", "status": "P"},
{"itemid": "EST-8", "productid": "RP-SN-01", "listprice": "18.50", "unitcost": "12.00", "attr1": "Rattleless", "status": "P"},
]
HTML_PAGE = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI DataGrid DetailView Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 16px; font-size: 13px; }
.dg-wrap { width: 500px; border: 1px solid #95b8e7; }
.dg-title { background: #e0ecff; padding: 6px 8px; font-weight: bold; }
table#dg { width: 100%; border-collapse: collapse; }
table#dg th, table#dg td { border: 1px solid #ccc; padding: 4px 6px; }
table#dg th { background: #f4f4f4; }
.expander { width: 20px; height: 20px; cursor: pointer; font-weight: bold; }
tr.detail-row.hidden { display: none; }
.dv-table td { border: 0 !important; padding: 3px 6px !important; }
.dv-label { font-weight: bold; color: #15428b; }
</style>
</head>
<body>
<div class="dg-wrap">
<div class="dg-title">DataGrid - Expand Row</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>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
const fixHeightLog = [];
const detailview = {
detailFormatter(index, row) {
return '<div class="ddv" style="padding:5px 0"></div>';
},
fixDetailRowHeight(index) {
const tr = document.querySelector(`tr.detail-row[data-index="${index}"]`);
const ddv = tr.querySelector("div.ddv");
const h = Math.round(ddv.getBoundingClientRect().height);
tr.dataset.fixedHeight = String(h);
fixHeightLog.push({ index, height: h });
}
};
async function initGrid() {
const resp = await fetch("/datagrid8_getdata?sort=itemid&order=desc");
const rows = await resp.json();
const tbody = document.querySelector("#dg tbody");
tbody.innerHTML = "";
rows.forEach((row, index) => {
const tr = document.createElement("tr");
tr.className = "data-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 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="6">${detailview.detailFormatter(index, row)}</td>`;
tbody.append(tr, dtr);
tr.querySelector(".expander").addEventListener("click", async (ev) => {
const btn = ev.currentTarget;
const isExpanded = btn.textContent === "-";
if (isExpanded) {
btn.textContent = "+";
dtr.classList.add("hidden");
return;
}
btn.textContent = "-";
dtr.classList.remove("hidden");
detailview.fixDetailRowHeight(index);
const ddv = dtr.querySelector("div.ddv");
// cache: false -> always reload from server on expand
const htmlResp = await fetch(`/datagrid21_getdetail?itemid=${encodeURIComponent(row.itemid)}&_ts=${Date.now()}`);
ddv.innerHTML = await htmlResp.text();
detailview.fixDetailRowHeight(index);
window.__lastExpanded = { index, itemid: row.itemid };
});
});
window.__gridReady = true;
}
window.lab = { fixHeightLog };
initGrid();
</script>
</body>
</html>
"""
def make_handler(hit_counter):
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def do_GET(self):
parsed = urlparse(self.path)
if parsed.path == "/":
body = HTML_PAGE.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(body)
elif parsed.path == "/datagrid8_getdata":
body = json.dumps(ITEMS).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
elif parsed.path == "/datagrid21_getdetail":
qs = parse_qs(parsed.query)
itemid = qs.get("itemid", [""])[0]
hit_counter[itemid] = hit_counter.get(itemid, 0) + 1
item = next((x for x in ITEMS if x["itemid"] == itemid), ITEMS[0])
serno = item["itemid"].split("-")[1]
svg = f"data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='60' height='60'%3E%3Crect width='60' height='60' fill='%23dbeafe'/%3E%3C/svg%3E"
frag = f"""<table class="dv-table" border="0" style="width:100%;">
<tr>
<td rowspan="3" style="width:60px"><img data-img="images/shirt{serno}.gif" src="{svg}" style="width:60px;height:60px;margin-right:20px" /></td>
<td class="dv-label">Item ID: </td><td>{item['itemid']}</td>
<td class="dv-label">Product ID:</td><td>{item['productid']}</td>
</tr>
<tr>
<td class="dv-label">List Price: </td><td>{item['listprice']}</td>
<td class="dv-label">Unit Cost:</td><td>{item['unitcost']}</td>
</tr>
<tr>
<td class="dv-label">Attribute: </td><td colspan="3">{item['attr1']}</td>
</tr>
</table>"""
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(frag.encode("utf-8"))
else:
self.send_response(404)
self.end_headers()
return Handler
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
hits = {}
server = HTTPServer(("127.0.0.1", 0), make_handler(hits))
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.__gridReady === true")
# Case 1: Initial rows have '+' expander and empty hidden .ddv container
res1 = page.evaluate("""() => ({
itemids: Array.from(document.querySelectorAll("tr.data-row")).map(r => r.dataset.itemid),
expanders: Array.from(document.querySelectorAll(".expander")).map(b => b.textContent),
hiddenDetailRows: Array.from(document.querySelectorAll("tr.detail-row")).filter(r => getComputedStyle(r).display === "none").length,
initialDdvEmpty: Array.from(document.querySelectorAll("div.ddv")).every(d => d.innerHTML === "")
})""")
exp1 = {
"itemids": ["EST-10", "EST-9", "EST-8"],
"expanders": ["+", "+", "+"],
"hiddenDetailRows": 3,
"initialDdvEmpty": True,
}
cases.append(dict(name="detailview_initial_expander_and_empty_container", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Expanding row 0 loads HTML fragment via AJAX and fixes detail row height
page.click('.expander[data-index="0"]')
page.wait_for_selector('tr.detail-row[data-index="0"] table.dv-table')
res2 = page.evaluate("""() => {
const dtr = document.querySelector('tr.detail-row[data-index="0"]');
const img = dtr.querySelector("img");
return {
btnText: document.querySelector('.expander[data-index="0"]').textContent,
detailVisible: getComputedStyle(dtr).display !== "none",
imgRef: img.dataset.img,
hasAttributeText: dtr.textContent.includes("Spotted Adult Female"),
fixedHeightGt60: Number(dtr.dataset.fixedHeight) > 60,
fixCallsForRow0: window.lab.fixHeightLog.filter(x => x.index === 0).length
};
}""")
exp2 = {
"btnText": "-",
"detailVisible": True,
"imgRef": "images/shirt10.gif",
"hasAttributeText": True,
"fixedHeightGt60": True,
"fixCallsForRow0": 2,
}
cases.append(dict(name="detailview_expand_fetches_detail_and_fixes_height", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Collapse hides row; re-expanding with cache=false re-fetches server endpoint
page.click('.expander[data-index="0"]')
collapsed = page.evaluate("""() => ({
btnText: document.querySelector('.expander[data-index="0"]').textContent,
hidden: getComputedStyle(document.querySelector('tr.detail-row[data-index="0"]')).display === "none"
})""")
page.click('.expander[data-index="0"]')
page.wait_for_function("() => window.lab.fixHeightLog.filter(x => x.index === 0).length === 4")
res3 = {**collapsed, "serverFetchCountForEST10": hits.get("EST-10", 0)}
exp3 = {"btnText": "+", "hidden": True, "serverFetchCountForEST10": 2}
cases.append(dict(name="detailview_collapse_and_nocache_reload", 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-datagrid21-lab/explore-datagrid-datagrid21.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-datagrid-datagrid21.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a978.zip
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip