"""Offline Playwright Chromium lab for jQuery EasyUI Ch 33: Custom Pagination."""
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 Custom Pagination Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 12px; }
.dg-panel { width: 550px; border: 1px solid #95b8e7; }
.dg-title { background: #e0ecff; padding: 6px 8px; font-weight: 600; font-size: 13px; border-bottom: 1px solid #95b8e7; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th, td { border: 1px solid #ddd; padding: 4px 6px; }
th { background: #efefef; }
.datagrid-pager { padding: 4px 6px; background: #f4f4f4; border-top: 1px solid #ddd; display: flex; align-items: center; gap: 6px; font-size: 12px; }
.pager-custom-btn { padding: 2px 6px; border: 1px solid #bbb; background: #fff; cursor: pointer; font-size: 11px; }
.hidden { display: none; }
</style>
</head>
<body>
<div class="dg-panel">
<div class="dg-title">Load Data</div>
<table id="tt" pagination="true">
<thead>
<tr>
<th field="itemid" width="80">Item ID</th>
<th field="productid" width="80">Product ID</th>
<th field="listprice" width="80" align="right">List Price</th>
<th field="unitcost" width="80" align="right">Unit Cost</th>
<th field="attr1" width="100">Attribute</th>
<th field="status" width="60" align="center">Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div id="pager" class="datagrid-pager">
<select id="page-list"><option value="3">3</option><option value="10">10</option></select>
<button id="btn-prev" type="button">Prev</button>
<span id="page-num">1</span>/<span id="page-total">2</span>
<button id="btn-next" type="button">Next</button>
<button id="btn-refresh" type="button">Refresh</button>
<span id="custom-btns"></span>
</div>
</div>
<script>
const DATA = [
{ itemid: "EST-1", productid: "FI-SW-01", listprice: 16.5, unitcost: 10.0, attr1: "Large", status: "P" },
{ itemid: "EST-2", productid: "K9-DL-01", listprice: 18.5, unitcost: 12.0, attr1: "Spotted", status: "P" },
{ itemid: "EST-3", productid: "RP-SN-01", listprice: 28.5, unitcost: 12.0, attr1: "Venomless", status: "P" },
{ itemid: "EST-4", productid: "RP-SN-01", listprice: 26.5, unitcost: 12.0, attr1: "Rattleless", status: "P" },
{ itemid: "EST-5", productid: "FL-DSH-01", listprice: 58.5, unitcost: 12.0, attr1: "Tailless", status: "P" },
{ itemid: "EST-6", productid: "AV-CB-01", listprice: 193.5, unitcost: 92.0, attr1: "Adult Male", status: "P" },
];
const state = {
page: 1,
pageSize: 3,
buttonLog: [],
beforeRefreshCalls: 0,
refreshExecutions: 0,
onBeforeRefresh: () => true,
};
function renderPage() {
const start = (state.page - 1) * state.pageSize;
const slice = DATA.slice(start, start + state.pageSize);
const tbody = document.querySelector('#tt tbody');
tbody.innerHTML = slice.map(r =>
`<tr><td>${r.itemid}</td><td>${r.productid}</td><td style="text-align:right">${r.listprice}</td><td style="text-align:right">${r.unitcost}</td><td>${r.attr1}</td><td style="text-align:center">${r.status}</td></tr>`
).join('');
document.getElementById('page-num').textContent = String(state.page);
document.getElementById('page-total').textContent = String(Math.ceil(DATA.length / state.pageSize));
}
const pagerObj = {
pagination(opts) {
const pageList = document.getElementById('page-list');
pageList.classList.toggle('hidden', opts.showPageList === false);
const holder = document.getElementById('custom-btns');
holder.innerHTML = '';
(opts.buttons || []).forEach(btn => {
const el = document.createElement('button');
el.type = 'button';
el.className = 'pager-custom-btn';
el.dataset.iconCls = btn.iconCls;
el.textContent = btn.iconCls;
el.addEventListener('click', btn.handler);
holder.appendChild(el);
});
if (typeof opts.onBeforeRefresh === 'function') {
state.onBeforeRefresh = opts.onBeforeRefresh;
}
}
};
document.getElementById('btn-prev').addEventListener('click', () => {
if (state.page > 1) { state.page -= 1; renderPage(); }
});
document.getElementById('btn-next').addEventListener('click', () => {
if (state.page * state.pageSize < DATA.length) { state.page += 1; renderPage(); }
});
document.getElementById('btn-refresh').addEventListener('click', () => {
const proceed = state.onBeforeRefresh(state.page, state.pageSize);
if (proceed !== false) {
state.refreshExecutions += 1;
renderPage();
}
});
// Initialize DataGrid and customize pager
renderPage();
pagerObj.pagination({
showPageList: false,
buttons: [
{ iconCls: 'icon-search', handler: () => state.buttonLog.push('search') },
{ iconCls: 'icon-add', handler: () => state.buttonLog.push('add') },
{ iconCls: 'icon-edit', handler: () => state.buttonLog.push('edit') },
],
onBeforeRefresh: () => {
state.beforeRefreshCalls += 1;
return true;
}
});
window.pagerApi = {
setBlockRefresh() {
pagerObj.pagination({
showPageList: false,
buttons: [
{ iconCls: 'icon-search', handler: () => state.buttonLog.push('search') },
{ iconCls: 'icon-add', handler: () => state.buttonLog.push('add') },
{ iconCls: 'icon-edit', handler: () => state.buttonLog.push('edit') },
],
onBeforeRefresh: () => {
state.beforeRefreshCalls += 1;
return false;
}
});
},
snapshot() {
return {
pageListVisible: getComputedStyle(document.getElementById('page-list')).display !== 'none',
customIcons: Array.from(document.querySelectorAll('.pager-custom-btn')).map(b => b.dataset.iconCls),
buttonLog: [...state.buttonLog],
page: state.page,
visibleIds: Array.from(document.querySelectorAll('#tt tbody tr td:first-child')).map(td => td.textContent),
beforeRefreshCalls: state.beforeRefreshCalls,
refreshExecutions: state.refreshExecutions,
};
}
};
</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(viewport={"width": 680, "height": 420})
page.set_content(HTML_DOC)
# Case 1: getPager hides page list & renders 3 custom buttons
snap1 = page.evaluate("() => window.pagerApi.snapshot()")
res1 = {
"pageListVisible": snap1["pageListVisible"],
"customIcons": snap1["customIcons"],
"page1Ids": snap1["visibleIds"],
}
exp1 = {
"pageListVisible": False,
"customIcons": ["icon-search", "icon-add", "icon-edit"],
"page1Ids": ["EST-1", "EST-2", "EST-3"],
}
cases.append(dict(name="get_pager_hide_page_list_and_custom_buttons", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Custom button handlers fire & Next navigates to page 2
page.click('.pager-custom-btn[data-icon-cls="icon-search"]')
page.click('.pager-custom-btn[data-icon-cls="icon-add"]')
page.click('.pager-custom-btn[data-icon-cls="icon-edit"]')
page.click("#btn-next")
snap2 = page.evaluate("() => window.pagerApi.snapshot()")
res2 = {
"buttonLog": snap2["buttonLog"],
"page": snap2["page"],
"page2Ids": snap2["visibleIds"],
}
exp2 = {
"buttonLog": ["search", "add", "edit"],
"page": 2,
"page2Ids": ["EST-4", "EST-5", "EST-6"],
}
cases.append(dict(name="custom_button_handlers_and_page_navigation", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: onBeforeRefresh returning true proceeds, returning false cancels refresh
page.click("#btn-refresh")
after_true = page.evaluate("() => ({ calls: window.pagerApi.snapshot().beforeRefreshCalls, execs: window.pagerApi.snapshot().refreshExecutions })")
page.evaluate("() => window.pagerApi.setBlockRefresh()")
page.click("#btn-refresh")
after_false = page.evaluate("() => ({ calls: window.pagerApi.snapshot().beforeRefreshCalls, execs: window.pagerApi.snapshot().refreshExecutions })")
res3 = {"afterReturnTrue": after_true, "afterReturnFalse": after_false}
exp3 = {
"afterReturnTrue": {"calls": 1, "execs": 1},
"afterReturnFalse": {"calls": 2, "execs": 1},
}
cases.append(dict(name="on_before_refresh_true_vs_false", 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-datagrid11-lab/explore-datagrid-datagrid11.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-datagrid-datagrid11.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a967.zip
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip