"""Offline Playwright Chromium lab for jQuery EasyUI Ch 38: DataGrid Custom Card View."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI DataGrid Card View 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#tt { width: 100%; border-collapse: collapse; }
table#tt th { border: 1px solid #ccc; background: #f4f4f4; padding: 6px; cursor: pointer; }
table#tt tbody tr { border-bottom: 1px solid #ddd; cursor: pointer; }
table#tt tbody tr.selected { background: #ffe48d; }
.c-label { display: inline-block; width: 90px; font-weight: bold; }
p { margin: 2px 0; }
</style>
</head>
<body>
<div class="dg-wrap">
<div class="dg-title">DataGrid - CardView</div>
<table id="tt">
<thead>
<tr>
<th data-field="itemid" data-sortable="true">Item ID</th>
<th data-field="listprice" data-sortable="true">List Price</th>
<th data-field="unitcost" data-sortable="true">Unit Cost</th>
<th data-field="attr1" data-sortable="true">Attribute</th>
<th data-field="status" data-sortable="true">Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
const columnOptions = {
itemid: { field: "itemid", title: "Item ID", sortable: true },
listprice: { field: "listprice", title: "List Price", sortable: true },
unitcost: { field: "unitcost", title: "Unit Cost", sortable: true },
attr1: { field: "attr1", title: "Attribute", sortable: true },
status: { field: "status", title: "Status", sortable: true }
};
const fields = Object.keys(columnOptions);
const data = [
{ itemid: "EST-1", listprice: 16.5, unitcost: 10.0, attr1: "Large", status: "P" },
{ itemid: "EST-2", listprice: 38.5, unitcost: 22.0, attr1: "Medium", status: "P" },
{ itemid: "EST-3", listprice: 18.5, unitcost: 12.0, attr1: "Small", status: "P" },
{ itemid: "EST-4", listprice: 23.5, unitcost: 14.0, attr1: "Spotted", status: "P" }
];
function makeSvgUri(name) {
return "data:image/svg+xml;utf8," + encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' width='150' height='90'><rect width='150' height='90' fill='#e0ecff'/><text x='10' y='50' font-size='14'>${name}</text></svg>`);
}
const defaultView = {
renderRow(target, cols, frozen, rowIndex, rowData) {
return cols.map(f => `<td>${rowData[f]}</td>`).join("");
}
};
// Mirror $.extend({}, $.fn.datagrid.defaults.view, { renderRow: ... })
const cardview = Object.assign({}, defaultView, {
renderRow(target, cols, frozen, rowIndex, rowData) {
const cc = [];
cc.push('<td colspan="' + cols.length + '" style="padding:10px 5px;border:0;">');
if (!frozen) {
const aa = rowData.itemid.split("-");
const img = "shirt" + aa[1] + ".gif";
cc.push('<img data-file="' + img + '" src="' + makeSvgUri(img) + '" style="width:150px;float:left">');
cc.push('<div style="float:left;margin-left:20px;">');
for (let i = 0; i < cols.length; i++) {
const copts = target.getColumnOption(cols[i]);
cc.push('<p><span class="c-label">' + copts.title + ':</span> ' + rowData[cols[i]] + '</p>');
}
cc.push("</div>");
}
cc.push("</td>");
return cc.join("");
}
});
const state = { sortName: "itemid", sortOrder: "desc", selectedIndex: -1 };
const gridApi = {
getColumnOption(f) { return columnOptions[f]; },
render() {
const sorted = [...data].sort((a, b) => {
const va = a[state.sortName], vb = b[state.sortName];
const cmp = typeof va === "number" ? va - vb : String(va).localeCompare(String(vb));
return state.sortOrder === "asc" ? cmp : -cmp;
});
const tbody = document.querySelector("#tt tbody");
tbody.innerHTML = "";
sorted.forEach((row, idx) => {
const tr = document.createElement("tr");
tr.dataset.index = String(idx);
tr.dataset.itemid = row.itemid;
if (idx === state.selectedIndex) tr.classList.add("selected");
tr.innerHTML = cardview.renderRow(gridApi, fields, false, idx, row);
tr.addEventListener("click", () => {
state.selectedIndex = idx;
document.querySelectorAll("#tt tbody tr").forEach((el, i) => {
el.classList.toggle("selected", i === idx);
});
});
tbody.appendChild(tr);
});
}
};
document.querySelectorAll("#tt thead th[data-sortable='true']").forEach(th => {
th.addEventListener("click", () => {
const f = th.dataset.field;
if (state.sortName === f) {
state.sortOrder = state.sortOrder === "asc" ? "desc" : "asc";
} else {
state.sortName = f;
state.sortOrder = "asc";
}
state.selectedIndex = -1;
gridApi.render();
});
});
gridApi.render();
window.lab = { cardview, gridApi, fields, data, state };
</script>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.set_content(HTML_DOC)
# Case 1: Card view renders single colspan=5 td, derived image name, and 5 labeled fields
res1 = page.evaluate("""() => {
const trs = Array.from(document.querySelectorAll("#tt tbody tr"));
const firstTd = trs[0].querySelector("td");
const imgFiles = trs.map(tr => tr.querySelector("img").dataset.file);
const labels = Array.from(trs[0].querySelectorAll(".c-label")).map(el => el.textContent);
return {
rowCount: trs.length,
firstTdColSpan: firstTd.colSpan,
imgFiles,
firstCardLabels: labels
};
}""")
exp1 = {
"rowCount": 4,
"firstTdColSpan": 5,
"imgFiles": ["shirt4.gif", "shirt3.gif", "shirt2.gif", "shirt1.gif"],
"firstCardLabels": ["Item ID:", "List Price:", "Unit Cost:", "Attribute:", "Status:"],
}
cases.append(dict(name="cardview_renderrow_colspan_and_labels", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Clicking column header triggers local sorting (remoteSort: false)
initial_ids = page.evaluate("() => Array.from(document.querySelectorAll('#tt tbody tr')).map(tr => tr.dataset.itemid)")
page.click('#tt thead th[data-field="listprice"]')
asc_ids = page.evaluate("() => Array.from(document.querySelectorAll('#tt tbody tr')).map(tr => tr.dataset.itemid)")
page.click('#tt thead th[data-field="listprice"]')
desc_ids = page.evaluate("() => Array.from(document.querySelectorAll('#tt tbody tr')).map(tr => tr.dataset.itemid)")
res2 = {"initialDescItemid": initial_ids, "priceAsc": asc_ids, "priceDesc": desc_ids}
exp2 = {
"initialDescItemid": ["EST-4", "EST-3", "EST-2", "EST-1"],
"priceAsc": ["EST-1", "EST-3", "EST-4", "EST-2"],
"priceDesc": ["EST-2", "EST-4", "EST-3", "EST-1"],
}
cases.append(dict(name="cardview_header_click_local_sort", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Frozen branch outputs empty colspan cell; singleSelect highlights 1 card
page.click('#tt tbody tr[data-index="1"]')
page.click('#tt tbody tr[data-index="2"]')
res3 = page.evaluate("""() => {
const frozenHtml = window.lab.cardview.renderRow(window.lab.gridApi, window.lab.fields, true, 0, window.lab.data[0]);
const selected = Array.from(document.querySelectorAll("#tt tbody tr.selected")).map(tr => tr.dataset.itemid);
return {
frozenHasImg: frozenHtml.includes("<img"),
frozenHasColspan5: frozenHtml.includes('colspan="5"'),
selectedCards: selected
};
}""")
exp3 = {
"frozenHasImg": False,
"frozenHasColspan5": True,
"selectedCards": ["EST-3"],
}
cases.append(dict(name="cardview_frozen_branch_and_selection", expected=exp3, actual=res3, passed=(res3 == exp3)))
browser.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-datagrid16-lab/explore-datagrid-datagrid16.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-datagrid-datagrid16.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a972.zip