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

运行 PropertyGrid 声明式分组折叠与多类型编辑器校验离线实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-datagrid-datagrid20.py
explore-datagrid-datagrid20.py192 行
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 41: PropertyGrid."""
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 PropertyGrid Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 16px; font-size: 13px; }
  .pg-wrap { width: 300px; border: 1px solid #95b8e7; }
  table.pg { width: 100%; border-collapse: collapse; table-layout: fixed; }
  table.pg th, table.pg td { border: 1px solid #ccc; padding: 4px 6px; }
  table.pg th { background: #e0ecff; text-align: left; }
  tr.pg-group td { background: #f4f4f4; font-weight: bold; }
  button.pg-toggle { width: 18px; height: 18px; margin-right: 6px; cursor: pointer; font-size: 11px; padding: 0; }
  tr.pg-row.collapsed { display: none; }
  .pg-invalid { border: 1px solid #d93025; background: #fff0f0; }
</style>
</head>
<body>
<table id="tt" class="easyui-propertygrid" style="width:300px" data-show-group="true" data-scrollbar-size="0"></table>

<script>
const sourceData = [
  { name: "Name", value: "Bill Smith", group: "ID Settings", editor: "text" },
  { name: "Address", value: "", group: "ID Settings", editor: "text" },
  { name: "Age", value: "40", group: "ID Settings", editor: "numberbox" },
  { name: "Birthday", value: "01/02/2012", group: "ID Settings", editor: "datebox" },
  { name: "SSN", value: "123-456-7890", group: "ID Settings", editor: "text" },
  { name: "Email", value: "bill@gmail.com", group: "Marketing Settings", editor: { type: "validatebox", options: { validType: "email" } } },
  { name: "FrequentBuyer", value: "false", group: "Marketing Settings", editor: { type: "checkbox", options: { on: true, off: false } } }
];

// Auto-parser mirrors EasyUI declarative class="easyui-propertygrid"
function parsePropertyGrids() {
  document.querySelectorAll("table.easyui-propertygrid").forEach(tbl => {
    const showGroup = tbl.dataset.showGroup === "true";
    const wrap = document.createElement("div");
    wrap.className = "pg-wrap";
    tbl.parentNode.insertBefore(wrap, tbl);
    wrap.appendChild(tbl);
    tbl.classList.add("pg");
    tbl.innerHTML = '<thead><tr><th style="width:120px">Name</th><th>Value</th></tr></thead><tbody></tbody>';
    const tbody = tbl.querySelector("tbody");
    const groups = new Map();
    sourceData.forEach((item, idx) => {
      const g = showGroup ? item.group : "__all__";
      if (!groups.has(g)) groups.set(g, []);
      groups.get(g).push({ ...item, _idx: idx });
    });

    groups.forEach((items, gName) => {
      if (showGroup) {
        const gtr = document.createElement("tr");
        gtr.className = "pg-group";
        gtr.dataset.group = gName;
        gtr.innerHTML = `<td colspan="2"><button type="button" class="pg-toggle" data-group="${gName}">-</button><span>${gName}</span></td>`;
        tbody.appendChild(gtr);
        gtr.querySelector(".pg-toggle").addEventListener("click", (ev) => {
          const btn = ev.currentTarget;
          const willCollapse = btn.textContent === "-";
          btn.textContent = willCollapse ? "+" : "-";
          tbody.querySelectorAll(`tr.pg-row[data-group="${gName}"]`).forEach(r => {
            r.classList.toggle("collapsed", willCollapse);
          });
        });
      }
      items.forEach(item => {
        const tr = document.createElement("tr");
        tr.className = "pg-row";
        tr.dataset.group = item.group;
        tr.dataset.name = item.name;
        tr.innerHTML = `<td class="pg-name">${item.name}</td><td class="pg-val">${item.value}</td>`;
        tbody.appendChild(tr);
      });
    });
  });
}

function editProperty(name, newValue) {
  const item = sourceData.find(x => x.name === name);
  const tr = document.querySelector(`tr.pg-row[data-name="${name}"]`);
  const valTd = tr.querySelector(".pg-val");
  const edSpec = typeof item.editor === "string" ? { type: item.editor, options: {} } : item.editor;
  valTd.innerHTML = "";
  let valid = true;
  if (edSpec.type === "checkbox") {
    const cb = document.createElement("input");
    cb.type = "checkbox";
    cb.checked = (String(newValue) === String(edSpec.options.on));
    valTd.appendChild(cb);
    item.value = String(cb.checked ? edSpec.options.on : edSpec.options.off);
    valTd.textContent = item.value;
  } else {
    const inp = document.createElement("input");
    inp.type = "text";
    inp.value = String(newValue);
    valTd.appendChild(inp);
    if (edSpec.type === "numberbox") {
      valid = /^-?\d+(\.\d+)?$/.test(inp.value.trim());
    } else if (edSpec.type === "validatebox" && edSpec.options?.validType === "email") {
      valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(inp.value.trim());
    }
    if (!valid) {
      inp.classList.add("pg-invalid");
      return { name, valid: false, value: item.value };
    }
    item.value = inp.value;
    valTd.textContent = item.value;
  }
  return { name, valid, value: item.value };
}

parsePropertyGrids();
window.lab = { editProperty, sourceData };
</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: Declarative class="easyui-propertygrid" with showGroup="true"
        res1 = page.evaluate("""() => {
            const groups = Array.from(document.querySelectorAll("tr.pg-group")).map(tr => tr.dataset.group);
            const counts = groups.map(g => document.querySelectorAll(`tr.pg-row[data-group="${g}"]`).length);
            return {
                groups,
                counts,
                totalRows: document.querySelectorAll("tr.pg-row").length,
                widthPx: Math.round(document.querySelector(".pg-wrap").getBoundingClientRect().width)
            };
        }""")
        exp1 = {
            "groups": ["ID Settings", "Marketing Settings"],
            "counts": [5, 2],
            "totalRows": 7,
            "widthPx": 302,
        }
        cases.append(dict(name="propertygrid_declarative_grouping", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Group collapse/expand toggle button hides/restores only target group rows
        page.click('button.pg-toggle[data-group="ID Settings"]')
        collapsed_state = page.evaluate("""() => ({
            idVisible: Array.from(document.querySelectorAll('tr.pg-row[data-group="ID Settings"]')).filter(r => getComputedStyle(r).display !== "none").length,
            mktVisible: Array.from(document.querySelectorAll('tr.pg-row[data-group="Marketing Settings"]')).filter(r => getComputedStyle(r).display !== "none").length,
            toggleText: document.querySelector('button.pg-toggle[data-group="ID Settings"]').textContent
        })""")
        page.click('button.pg-toggle[data-group="ID Settings"]')
        expanded_visible = page.evaluate("""() => Array.from(document.querySelectorAll('tr.pg-row')).filter(r => getComputedStyle(r).display !== "none").length""")
        res2 = {**collapsed_state, "afterExpandAllVisible": expanded_visible}
        exp2 = {"idVisible": 0, "mktVisible": 2, "toggleText": "+", "afterExpandAllVisible": 7}
        cases.append(dict(name="propertygrid_group_collapse_expand", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Typed editors (numberbox, validatebox email, checkbox)
        res3 = page.evaluate("""() => {
            const ageRes = window.lab.editProperty("Age", "42");
            const badEmail = window.lab.editProperty("Email", "not-an-email");
            const goodEmail = window.lab.editProperty("Email", "bill@example.com");
            const buyerRes = window.lab.editProperty("FrequentBuyer", true);
            return { ageRes, badEmail, goodEmail, buyerRes };
        }""")
        exp3 = {
            "ageRes": {"name": "Age", "valid": True, "value": "42"},
            "badEmail": {"name": "Email", "valid": False, "value": "bill@gmail.com"},
            "goodEmail": {"name": "Email", "valid": True, "value": "bill@example.com"},
            "buyerRes": {"name": "FrequentBuyer", "valid": True, "value": "true"},
        }
        cases.append(dict(name="propertygrid_typed_editors_and_validation", 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-datagrid20-lab/explore-datagrid-datagrid20.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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