"""Offline Playwright Chromium lab for jQuery EasyUI Ch 35: Extend DataGrid Editors (numberspinner)."""
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 Extend Editor Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 16px; font-size: 13px; }
.datagrid-wrap { width: 600px; border: 1px solid #95b8e7; }
.datagrid-title { background: #e0ecff; padding: 6px 8px; font-weight: bold; border-bottom: 1px solid #95b8e7; }
table.dg { width: 100%; border-collapse: collapse; table-layout: fixed; }
table.dg th, table.dg td { border: 1px solid #ccc; padding: 4px 6px; overflow: hidden; }
table.dg th { background: #f4f4f4; }
.spinner-wrap { display: inline-flex; align-items: center; border: 1px solid #95b8e7; box-sizing: border-box; }
.spinner-wrap input { border: 0; width: calc(100% - 20px); outline: none; text-align: right; font-size: 12px; }
.spinner-btns { display: flex; flex-direction: column; width: 18px; }
.spinner-btns button { font-size: 9px; line-height: 9px; padding: 0; border: 0; border-left: 1px solid #ccc; cursor: pointer; background: #eee; }
</style>
</head>
<body>
<div class="datagrid-wrap">
<div class="datagrid-title">Editable DataGrid</div>
<table id="tt" class="dg" data-id-field="itemid">
<thead>
<tr>
<th data-field="itemid" style="width:60px">Item ID</th>
<th data-field="listprice" style="width:80px;text-align:right">List Price</th>
<th data-field="unitcost" style="width:80px;text-align:right">Unit Cost</th>
<th data-field="attr1" style="width:180px">Attribute</th>
<th data-field="status" style="width:60px;text-align:center">Status</th>
<th data-field="action" style="width:80px;text-align:center">Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div id="unit-sandbox" style="margin-top:12px;"></div>
<script>
const lifecycleLog = [];
const EasyUI = {
fn: {
datagrid: {
defaults: {
editors: {
text: {
init(container) {
const inp = document.createElement("input");
inp.type = "text";
inp.className = "dg-ed-text";
container.appendChild(inp);
return inp;
},
destroy(target) { target.remove(); },
getValue(target) { return target.value; },
setValue(target, value) { target.value = value ?? ""; },
resize(target, width) { target.style.width = width + "px"; }
},
numberbox: {
init(container, options = {}) {
const inp = document.createElement("input");
inp.type = "text";
inp.className = "dg-ed-numberbox";
inp._precision = options.precision ?? 0;
container.appendChild(inp);
return inp;
},
destroy(target) { target.remove(); },
getValue(target) {
const n = parseFloat(target.value);
return Number.isNaN(n) ? "" : n.toFixed(target._precision);
},
setValue(target, value) {
const n = parseFloat(value);
target.value = Number.isNaN(n) ? "" : n.toFixed(target._precision);
},
resize(target, width) { target.style.width = width + "px"; }
},
checkbox: {
init(container, options = { on: "P", off: "" }) {
const inp = document.createElement("input");
inp.type = "checkbox";
inp.className = "dg-ed-checkbox";
inp._opts = options;
container.appendChild(inp);
return inp;
},
destroy(target) { target.remove(); },
getValue(target) { return target.checked ? target._opts.on : target._opts.off; },
setValue(target, value) { target.checked = (value === target._opts.on); },
resize() {}
}
}
}
}
}
};
// Mirror $.extend($.fn.datagrid.defaults.editors, { numberspinner: ... })
Object.assign(EasyUI.fn.datagrid.defaults.editors, {
numberspinner: {
init(container, options = {}) {
lifecycleLog.push("numberspinner:init");
const wrap = document.createElement("span");
wrap.className = "spinner-wrap";
const input = document.createElement("input");
input.type = "text";
input.className = "dg-ed-numberspinner";
const btns = document.createElement("span");
btns.className = "spinner-btns";
const up = document.createElement("button");
up.type = "button";
up.className = "spin-up";
up.textContent = "+";
const down = document.createElement("button");
down.type = "button";
down.className = "spin-down";
down.textContent = "-";
const inc = options.increment ?? 1;
up.addEventListener("click", () => {
const cur = parseFloat(input.value) || 0;
input.value = String(cur + inc);
});
down.addEventListener("click", () => {
const cur = parseFloat(input.value) || 0;
input.value = String(cur - inc);
});
btns.append(up, down);
wrap.append(input, btns);
container.appendChild(wrap);
input._wrap = wrap;
return input;
},
destroy(target) {
lifecycleLog.push("numberspinner:destroy");
if (target._wrap) target._wrap.remove();
},
getValue(target) {
return target.value;
},
setValue(target, value) {
target.value = value == null ? "" : String(value);
},
resize(target, width) {
if (target._wrap) target._wrap.style.width = width + "px";
}
}
});
const columns = [
{ field: "itemid", align: "left", editor: null },
{ field: "listprice", align: "right", editor: { type: "numberbox", options: { precision: 1 } } },
{ field: "unitcost", align: "right", editor: "numberspinner" },
{ field: "attr1", align: "left", editor: "text" },
{ field: "status", align: "center", editor: { type: "checkbox", options: { on: "P", off: "" } } },
{ field: "action", align: "center", editor: null }
];
const rows = [
{ itemid: "EST-1", listprice: "16.5", unitcost: "10", attr1: "Large", status: "P" },
{ itemid: "EST-10", listprice: "18.5", unitcost: "12", attr1: "Spotted Adult Female", status: "P" }
];
const editingMap = new Map();
function renderGrid() {
const tbody = document.querySelector("#tt tbody");
tbody.innerHTML = "";
rows.forEach((row, idx) => {
const tr = document.createElement("tr");
tr.dataset.index = String(idx);
columns.forEach(col => {
const td = document.createElement("td");
td.dataset.field = col.field;
td.style.textAlign = col.align;
if (col.field === "action") {
td.textContent = editingMap.has(idx) ? "Save | Cancel" : "Edit";
} else {
td.textContent = row[col.field];
}
tr.appendChild(td);
});
tbody.appendChild(tr);
});
}
function resolveEditor(spec) {
if (!spec) return null;
if (typeof spec === "string") return { type: spec, options: {} };
return { type: spec.type, options: spec.options || {} };
}
function beginEdit(idx) {
if (editingMap.has(idx)) return;
const tr = document.querySelector(`#tt tbody tr[data-index="${idx}"]`);
const active = [];
columns.forEach(col => {
const spec = resolveEditor(col.editor);
if (!spec) return;
const def = EasyUI.fn.datagrid.defaults.editors[spec.type];
const td = tr.querySelector(`td[data-field="${col.field}"]`);
td.innerHTML = "";
const target = def.init(td, spec.options);
def.setValue(target, rows[idx][col.field]);
def.resize(target, 74);
active.push({ field: col.field, def, target });
});
editingMap.set(idx, active);
tr.querySelector('td[data-field="action"]').textContent = "Save | Cancel";
}
function endEdit(idx) {
const active = editingMap.get(idx);
if (!active) return;
active.forEach(({ field, def, target }) => {
rows[idx][field] = def.getValue(target);
def.destroy(target);
});
editingMap.delete(idx);
renderGrid();
}
function cancelEdit(idx) {
const active = editingMap.get(idx);
if (!active) return;
active.forEach(({ def, target }) => {
def.destroy(target);
});
editingMap.delete(idx);
renderGrid();
}
renderGrid();
window.lab = { EasyUI, rows, beginEdit, endEdit, cancelEdit, lifecycleLog };
</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: Standalone numberspinner editor contract
res1 = page.evaluate("""() => {
const box = document.getElementById("unit-sandbox");
const ed = window.lab.EasyUI.fn.datagrid.defaults.editors.numberspinner;
const target = ed.init(box, { increment: 2 });
ed.setValue(target, "25.5");
ed.resize(target, 110);
const val = ed.getValue(target);
const width = target._wrap.style.width;
const mountedBeforeDestroy = box.querySelectorAll(".spinner-wrap").length;
ed.destroy(target);
const mountedAfterDestroy = box.querySelectorAll(".spinner-wrap").length;
return {
methods: Object.keys(ed).sort(),
value: val,
width,
mountedBeforeDestroy,
mountedAfterDestroy
};
}""")
exp1 = {
"methods": ["destroy", "getValue", "init", "resize", "setValue"],
"value": "25.5",
"width": "110px",
"mountedBeforeDestroy": 1,
"mountedAfterDestroy": 0,
}
cases.append(dict(name="extend_numberspinner_editor_contract", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: DataGrid inline edit using extended numberspinner on unitcost + numberbox/checkbox
page.evaluate("() => window.lab.beginEdit(0)")
page.click('#tt tbody tr[data-index="0"] td[data-field="unitcost"] .spin-up')
page.click('#tt tbody tr[data-index="0"] td[data-field="unitcost"] .spin-up')
page.fill('#tt tbody tr[data-index="0"] td[data-field="listprice"] input', "18.56")
page.uncheck('#tt tbody tr[data-index="0"] td[data-field="status"] input')
page.evaluate("() => window.lab.endEdit(0)")
res2 = page.evaluate("""() => ({
row0: window.lab.rows[0],
cellUnitCost: document.querySelector('#tt tbody tr[data-index="0"] td[data-field="unitcost"]').textContent,
cellListPrice: document.querySelector('#tt tbody tr[data-index="0"] td[data-field="listprice"]').textContent,
cellStatus: document.querySelector('#tt tbody tr[data-index="0"] td[data-field="status"]').textContent
})""")
exp2 = {
"row0": {"itemid": "EST-1", "listprice": "18.6", "unitcost": "12", "attr1": "Large", "status": ""},
"cellUnitCost": "12",
"cellListPrice": "18.6",
"cellStatus": "",
}
cases.append(dict(name="datagrid_inline_edit_with_numberspinner", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Cancel edit triggers destroy and preserves original unitcost
page.evaluate("() => window.lab.beginEdit(1)")
page.fill('#tt tbody tr[data-index="1"] td[data-field="unitcost"] input', "99")
in_edit_count = page.locator('#tt tbody tr[data-index="1"] .spinner-wrap').count()
page.evaluate("() => window.lab.cancelEdit(1)")
res3 = page.evaluate("""(inEditCount) => ({
inEditCount,
afterCancelSpinnerCount: document.querySelectorAll('#tt tbody tr[data-index="1"] .spinner-wrap').length,
preservedUnitCost: window.lab.rows[1].unitcost,
destroyCount: window.lab.lifecycleLog.filter(x => x === "numberspinner:destroy").length
})""", in_edit_count)
exp3 = {
"inEditCount": 1,
"afterCancelSpinnerCount": 0,
"preservedUnitCost": "12",
"destroyCount": 3,
}
cases.append(dict(name="cancel_and_destroy_editor_lifecycle", 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-datagrid23-lab/explore-datagrid-datagrid23.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-datagrid-datagrid23.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a980.zip
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip