蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 DataGrid 行内编辑(beginEdit/endEdit/cancelEdit/deleteRow)离线 Chromium 实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-datagrid-datagrid12.py
explore-datagrid-datagrid12.py253 行
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 34: Inline Row Editing."""
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 Editable DataGrid Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .dg-panel { width: 680px; 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; }
  input[type="text"], input[type="number"], select { width: 92%; box-sizing: border-box; font-size: 12px; }
</style>
</head>
<body>
<div class="dg-panel">
  <div class="dg-title">Editable DataGrid</div>
  <table id="tt">
    <thead>
      <tr>
        <th width="60">Item ID</th>
        <th width="110">Product</th>
        <th width="80" style="text-align:right">List Price</th>
        <th width="80" style="text-align:right">Unit Cost</th>
        <th width="150">Attribute</th>
        <th width="50" style="text-align:center">Status</th>
        <th width="90" style="text-align:center">Action</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>
<script>
const PRODUCTS = [
  { productid: "FI-SW-01", name: "Koi" },
  { productid: "K9-DL-01", name: "Dalmation" },
  { productid: "RP-SN-01", name: "Rattlesnake" },
];

const ROWS = [
  { itemid: "EST-1", productid: "FI-SW-01", listprice: 16.5, unitcost: 10.0, attr1: "Large", status: "P", editing: false },
  { itemid: "EST-10", productid: "K9-DL-01", listprice: 18.5, unitcost: 12.0, attr1: "Spotted", status: "P", editing: false },
  { itemid: "EST-11", productid: "RP-SN-01", listprice: 28.5, unitcost: 12.0, attr1: "Rattleless", status: "", editing: false },
];

const lifecycleLog = [];
let confirmResult = true;

function productFormatter(val) {
  for (let i = 0; i < PRODUCTS.length; i++) {
    if (PRODUCTS[i].productid === val) return PRODUCTS[i].name;
  }
  return val;
}

function renderAll() {
  const tbody = document.querySelector('#tt tbody');
  tbody.innerHTML = '';
  ROWS.forEach((row, index) => {
    const tr = document.createElement('tr');
    tr.className = 'datagrid-row';
    tr.setAttribute('datagrid-row-index', String(index));
    if (row.editing) {
      const optsHtml = PRODUCTS.map(p =>
        `<option value="${p.productid}" ${p.productid === row.productid ? 'selected' : ''}>${p.name}</option>`
      ).join('');
      tr.innerHTML = `
        <td>${row.itemid}</td>
        <td><select class="ed-productid">${optsHtml}</select></td>
        <td style="text-align:right"><input type="number" step="0.1" class="ed-listprice" value="${row.listprice}"></td>
        <td style="text-align:right"><input type="number" class="ed-unitcost" value="${row.unitcost}"></td>
        <td><input type="text" class="ed-attr1" value="${row.attr1}"></td>
        <td style="text-align:center"><input type="checkbox" class="ed-status" ${row.status === 'P' ? 'checked' : ''}></td>
        <td class="action-cell" style="text-align:center">
          <a href="#" class="act-save" onclick="saverow(this);return false;">Save</a>
          <a href="#" class="act-cancel" onclick="cancelrow(this);return false;">Cancel</a>
        </td>`;
    } else {
      tr.innerHTML = `
        <td>${row.itemid}</td>
        <td class="cell-product">${productFormatter(row.productid)}</td>
        <td class="cell-listprice" style="text-align:right">${row.listprice}</td>
        <td class="cell-unitcost" style="text-align:right">${row.unitcost}</td>
        <td class="cell-attr1">${row.attr1}</td>
        <td class="cell-status" style="text-align:center">${row.status}</td>
        <td class="action-cell" style="text-align:center">
          <a href="#" class="act-edit" onclick="editrow(this);return false;">Edit</a>
          <a href="#" class="act-delete" onclick="deleterow(this);return false;">Delete</a>
        </td>`;
    }
    tbody.appendChild(tr);
  });
}

function getRowIndex(target) {
  const tr = target.closest('tr.datagrid-row');
  return parseInt(tr.getAttribute('datagrid-row-index'), 10);
}

window.editrow = function(target) {
  const idx = getRowIndex(target);
  ROWS[idx].editing = true;
  lifecycleLog.push(`onBeforeEdit:${idx}`);
  renderAll();
};

window.saverow = function(target) {
  const idx = getRowIndex(target);
  const tr = document.querySelector(`tr.datagrid-row[datagrid-row-index="${idx}"]`);
  const row = ROWS[idx];
  row.productid = tr.querySelector('.ed-productid').value;
  row.listprice = Number(parseFloat(tr.querySelector('.ed-listprice').value).toFixed(1));
  row.unitcost = Number(parseFloat(tr.querySelector('.ed-unitcost').value));
  row.attr1 = tr.querySelector('.ed-attr1').value;
  row.status = tr.querySelector('.ed-status').checked ? 'P' : '';
  row.editing = false;
  lifecycleLog.push(`onAfterEdit:${idx}`);
  renderAll();
};

window.cancelrow = function(target) {
  const idx = getRowIndex(target);
  ROWS[idx].editing = false;
  lifecycleLog.push(`onCancelEdit:${idx}`);
  renderAll();
};

window.deleterow = function(target) {
  const idx = getRowIndex(target);
  if (confirmResult) {
    ROWS.splice(idx, 1);
    lifecycleLog.push(`deleteRow:${idx}`);
    renderAll();
  }
};

window.editGridApi = {
  getRows() { return ROWS.map(({ editing, ...rest }) => ({ ...rest, editing })); },
  getLog() { return [...lifecycleLog]; },
};

renderAll();
</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": 760, "height": 420})
        page.set_content(HTML_DOC)

        # Case 1: Click Edit triggers beginEdit -> onBeforeEdit -> renders 4 editor types + Save/Cancel links
        before_actions = page.locator('tr[datagrid-row-index="0"] .action-cell').inner_text().strip()
        page.click('tr[datagrid-row-index="0"] .act-edit')
        res1 = page.evaluate("""(beforeAct) => {
            const tr = document.querySelector('tr[datagrid-row-index="0"]');
            return {
                beforeActions: beforeAct.replace(/\\s+/g, ' '),
                afterActions: tr.querySelector('.action-cell').innerText.trim().replace(/\\s+/g, ' '),
                editorsPresent: {
                    combobox: Boolean(tr.querySelector('select.ed-productid')),
                    numberboxPrice: Boolean(tr.querySelector('input.ed-listprice[type="number"]')),
                    numberboxCost: Boolean(tr.querySelector('input.ed-unitcost[type="number"]')),
                    textAttr: Boolean(tr.querySelector('input.ed-attr1[type="text"]')),
                    checkboxStatus: Boolean(tr.querySelector('input.ed-status[type="checkbox"]')),
                },
                rowEditingFlag: window.editGridApi.getRows()[0].editing,
            };
        }""", before_actions)
        exp1 = {
            "beforeActions": "Edit Delete",
            "afterActions": "Save Cancel",
            "editorsPresent": {
                "combobox": True,
                "numberboxPrice": True,
                "numberboxCost": True,
                "textAttr": True,
                "checkboxStatus": True,
            },
            "rowEditingFlag": True,
        }
        cases.append(dict(name="begin_edit_renders_editors_and_action_links", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Modify editors & click Save -> endEdit rounds precision:1, formats product name, unchecks status->''
        page.select_option('tr[datagrid-row-index="0"] .ed-productid', 'RP-SN-01')
        page.fill('tr[datagrid-row-index="0"] .ed-listprice', '29.46')
        page.fill('tr[datagrid-row-index="0"] .ed-attr1', 'Venomless')
        page.uncheck('tr[datagrid-row-index="0"] .ed-status')
        page.click('tr[datagrid-row-index="0"] .act-save')
        res2 = page.evaluate("""() => {
            const tr = document.querySelector('tr[datagrid-row-index="0"]');
            return {
                savedRow: window.editGridApi.getRows()[0],
                formattedProductText: tr.querySelector('.cell-product').textContent.trim(),
                actionLinks: tr.querySelector('.action-cell').innerText.trim().replace(/\\s+/g, ' '),
            };
        }""")
        exp2 = {
            "savedRow": {
                "itemid": "EST-1",
                "productid": "RP-SN-01",
                "listprice": 29.5,
                "unitcost": 10,
                "attr1": "Venomless",
                "status": "",
                "editing": False,
            },
            "formattedProductText": "Rattlesnake",
            "actionLinks": "Edit Delete",
        }
        cases.append(dict(name="end_edit_saves_changes_and_formats", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Cancel discards inline edit; Delete removes row via deleteRow
        page.click('tr[datagrid-row-index="1"] .act-edit')
        page.fill('tr[datagrid-row-index="1"] .ed-attr1', 'TEMP-DISCARD')
        page.click('tr[datagrid-row-index="1"] .act-cancel')
        attr_after_cancel = page.evaluate("() => window.editGridApi.getRows()[1].attr1")
        page.click('tr[datagrid-row-index="1"] .act-delete')
        res3 = page.evaluate("""(attrCancel) => ({
            attrAfterCancel: attrCancel,
            remainingIds: window.editGridApi.getRows().map(r => r.itemid),
            lifecycleLog: window.editGridApi.getLog(),
        })""", attr_after_cancel)
        exp3 = {
            "attrAfterCancel": "Spotted",
            "remainingIds": ["EST-1", "EST-11"],
            "lifecycleLog": ["onBeforeEdit:0", "onAfterEdit:0", "onBeforeEdit:1", "onCancelEdit:1", "deleteRow:1"],
        }
        cases.append(dict(name="cancel_edit_discards_and_delete_row", 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-datagrid12-lab/explore-datagrid-datagrid12.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-datagrid-datagrid12.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a968.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习