"""Offline Playwright Chromium lab for jQuery EasyUI Ch 44: Virtual ScrollView (10,000 rows)."""
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import threading
from urllib.parse import parse_qs
from playwright.sync_api import sync_playwright
TOTAL_ROWS = 10000
HTML_PAGE = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI DataGrid VirtualScrollView Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 16px; font-size: 12px; }
.dg-wrap { width: 700px; border: 1px solid #95b8e7; }
.dg-title { background: #e0ecff; padding: 6px 8px; font-weight: bold; }
table.dg-head, table.dg-body { width: 100%; border-collapse: collapse; table-layout: fixed; }
table.dg-head th { background: #f4f4f4; border: 1px solid #ccc; padding: 4px; }
.viewport { height: 250px; overflow-y: auto; position: relative; }
.spacer { position: relative; width: 100%; }
table.dg-body { position: absolute; left: 0; top: 0; }
table.dg-body tr { height: 25px; }
table.dg-body td { border: 1px solid #ddd; padding: 0 5px; height: 25px; line-height: 25px; box-sizing: border-box; overflow: hidden; white-space: nowrap; }
</style>
</head>
<body>
<div class="dg-wrap" data-view="scrollview" data-pagination="false" data-page-size="50" data-auto-row-height="false">
<div class="dg-title">DataGrid - VirtualScrollView</div>
<table class="dg-head">
<thead><tr>
<th style="width:48px">#</th>
<th style="width:80px">Inv No</th><th style="width:90px">Date</th>
<th style="width:80px">Name</th><th style="width:70px;text-align:right">Amount</th>
<th style="width:70px;text-align:right">Price</th><th style="width:90px;text-align:right">Cost</th>
<th>Note</th>
</tr></thead>
</table>
<div id="viewport" class="viewport">
<div id="spacer" class="spacer">
<table id="tt" class="dg-body"><tbody></tbody></table>
</div>
</div>
</div>
<script>
const ROW_H = 25;
const PAGE_SIZE = 50;
let currentPage = 0;
let total = 0;
let pending = null;
const requestLog = [];
async function fetchPage(pageNum) {
currentPage = pageNum;
requestLog.push({ page: pageNum, rows: PAGE_SIZE });
const body = `page=${pageNum}&rows=${PAGE_SIZE}`;
const resp = await fetch("/datagrid27_getdata", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body
});
const data = await resp.json();
total = data.total;
document.getElementById("spacer").style.height = (total * ROW_H) + "px";
const topOffset = (pageNum - 1) * PAGE_SIZE * ROW_H;
const tbl = document.getElementById("tt");
tbl.style.top = topOffset + "px";
const tbody = tbl.querySelector("tbody");
const baseIdx = (pageNum - 1) * PAGE_SIZE;
tbody.innerHTML = data.rows.map((r, i) => `
<tr data-inv="${r.inv}" data-rownum="${baseIdx + i + 1}">
<td>${baseIdx + i + 1}</td><td>${r.inv}</td><td>${r.date}</td><td>${r.name}</td>
<td style="text-align:right">${r.amount}</td><td style="text-align:right">${r.price}</td>
<td style="text-align:right">${r.cost}</td><td>${r.note}</td>
</tr>`).join("");
window.__renderedPage = pageNum;
}
const vp = document.getElementById("viewport");
vp.addEventListener("scroll", () => {
const topRow = Math.floor(vp.scrollTop / ROW_H);
const maxPage = Math.max(1, Math.ceil(total / PAGE_SIZE));
const targetPage = Math.min(maxPage, Math.floor(topRow / PAGE_SIZE) + 1);
if (targetPage !== currentPage) {
pending = fetchPage(targetPage);
}
});
window.lab = { requestLog, getTotal: () => total };
fetchPage(1);
</script>
</body>
</html>
"""
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
pass
def do_GET(self):
if self.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"))
else:
self.send_response(404)
self.end_headers()
def do_POST(self):
if self.path == "/datagrid27_getdata":
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length).decode("utf-8")
qs = parse_qs(raw)
page = int(qs.get("page", ["1"])[0])
rows_n = int(qs.get("rows", ["50"])[0])
items = []
for i in range(1, rows_n + 1):
idx = i + (page - 1) * rows_n
if idx > TOTAL_ROWS:
break
amount = 50 + (idx % 51)
price = round(100.0 + ((idx * 37) % 10000) / 100.0, 2)
items.append({
"inv": f"INV{idx:04d}",
"date": f"2026-01-{(i % 28) + 1:02d}",
"name": f"Name{idx}",
"note": f"Note{idx}",
"amount": amount,
"price": f"{price:.2f}",
"cost": f"{amount * price:.2f}",
})
payload = {"total": TOTAL_ROWS, "rows": items}
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(payload).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.__renderedPage === 1")
# Case 1: Initial pageSize=50 without pagination bar, 250000px virtual spacer for 10,000 rows
res1 = page.evaluate("""() => {
const trs = document.querySelectorAll("#tt tbody tr");
return {
hasPager: document.querySelector(".datagrid-pager") !== null,
total: window.lab.getTotal(),
spacerHeightPx: parseInt(document.getElementById("spacer").style.height, 10),
domRowCount: trs.length,
firstInv: trs[0].dataset.inv,
lastInv: trs[trs.length - 1].dataset.inv,
firstReq: window.lab.requestLog[0]
};
}""")
exp1 = {
"hasPager": False,
"total": 10000,
"spacerHeightPx": 250000,
"domRowCount": 50,
"firstInv": "INV0001",
"lastInv": "INV0050",
"firstReq": {"page": 1, "rows": 50},
}
cases.append(dict(name="scrollview_initial_window_and_no_pagination", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Vertical scroll to middle (row 5001 -> page 101) swaps DOM window smoothly
page.evaluate("""() => {
const vp = document.getElementById("viewport");
vp.scrollTop = 125000;
vp.dispatchEvent(new Event("scroll"));
}""")
page.wait_for_function("() => window.__renderedPage === 101")
res2 = page.evaluate("""() => {
const trs = document.querySelectorAll("#tt tbody tr");
return {
domRowCount: trs.length,
firstRowNum: Number(trs[0].dataset.rownum),
firstInv: trs[0].dataset.inv,
lastInv: trs[trs.length - 1].dataset.inv,
tableTopPx: parseInt(document.getElementById("tt").style.top, 10),
lastReq: window.lab.requestLog[window.lab.requestLog.length - 1]
};
}""")
exp2 = {
"domRowCount": 50,
"firstRowNum": 5001,
"firstInv": "INV5001",
"lastInv": "INV5050",
"tableTopPx": 125000,
"lastReq": {"page": 101, "rows": 50},
}
cases.append(dict(name="scrollview_vertical_scroll_fetches_middle_page", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Scroll to tail (page 200) renders INV10000 and verifies amount*price==cost
page.evaluate("""() => {
const vp = document.getElementById("viewport");
vp.scrollTop = 249700;
vp.dispatchEvent(new Event("scroll"));
}""")
page.wait_for_function("() => window.__renderedPage === 200")
res3 = page.evaluate("""() => {
const trs = document.querySelectorAll("#tt tbody tr");
const last = trs[trs.length - 1];
const cells = Array.from(last.querySelectorAll("td")).map(td => td.textContent);
const amount = Number(cells[4]);
const price = Number(cells[5]);
const cost = cells[6];
return {
domRowCount: trs.length,
lastRowNum: Number(last.dataset.rownum),
lastInv: last.dataset.inv,
costMatchesProduct: cost === (amount * price).toFixed(2),
totalRequestsMade: window.lab.requestLog.length
};
}""")
exp3 = {
"domRowCount": 50,
"lastRowNum": 10000,
"lastInv": "INV10000",
"costMatchesProduct": True,
"totalRequestsMade": 3,
}
cases.append(dict(name="scrollview_tail_scroll_and_cost_calculation", 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-datagrid27-lab/explore-datagrid-datagrid27.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-datagrid-datagrid27.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a982.zip
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip