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

运行 DataGrid rowStyler 条件行着色与边界重载离线实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-datagrid-datagrid18.py
explore-datagrid-datagrid18.py160 行
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 40: DataGrid Conditional rowStyler."""
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 rowStyler Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 16px; font-size: 13px; }
  table#tt { width: 600px; border-collapse: collapse; }
  table#tt th, table#tt td { border: 1px solid #ccc; padding: 4px 6px; }
  table#tt th { background: #e0ecff; }
  table#tt tr.high-row { background-color: rgb(255, 240, 200); color: rgb(153, 51, 0); }
</style>
</head>
<body>
<table id="tt">
  <thead>
    <tr>
      <th>Item ID</th><th>Product ID</th><th>List Price</th><th>Unit Cost</th><th>Attribute</th><th>Status</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

<script>
const fields = ["itemid", "productid", "listprice", "unitcost", "attr1", "status"];
let currentStyler = function(index, row) {
  if (row.listprice > 50) {
    return "background-color:pink;color:blue;font-weight:bold;";
  }
};

function renderGrid(rows, stylerFn = currentStyler) {
  currentStyler = stylerFn;
  const tbody = document.querySelector("#tt tbody");
  tbody.innerHTML = "";
  rows.forEach((row, idx) => {
    const tr = document.createElement("tr");
    tr.dataset.index = String(idx);
    if (stylerFn) {
      const styled = stylerFn(idx, row);
      if (typeof styled === "string") {
        tr.setAttribute("style", styled);
      } else if (styled && typeof styled === "object") {
        if (styled.class) tr.classList.add(styled.class);
        if (styled.style) tr.setAttribute("style", styled.style);
      }
    }
    fields.forEach(f => {
      const td = document.createElement("td");
      td.textContent = String(row[f]);
      tr.appendChild(td);
    });
    tbody.appendChild(tr);
  });
}

const initialRows = [
  { itemid: "EST-1", productid: "FI-SW-01", listprice: 16.5, unitcost: 10, attr1: "Large", status: "P" },
  { itemid: "EST-2", productid: "K9-BD-01", listprice: 50.0, unitcost: 30, attr1: "Boundary", status: "P" },
  { itemid: "EST-3", productid: "FL-DSH-01", listprice: 50.1, unitcost: 32, attr1: "Over 50", status: "P" },
  { itemid: "EST-4", productid: "AV-CB-01", listprice: 88.0, unitcost: 48, attr1: "Adult Male", status: "P" },
  { itemid: "EST-5", productid: "RP-SN-01", listprice: 35.5, unitcost: 18, attr1: "Venomless", status: "P" }
];

renderGrid(initialRows);
window.lab = { renderGrid, initialRows };
</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: Strict > 50 threshold sets pink bg, blue text, bold font weight
        res1 = page.evaluate("""() => {
            const trs = Array.from(document.querySelectorAll("#tt tbody tr"));
            const styledIndices = [];
            const styles = {};
            trs.forEach((tr, i) => {
                const cs = getComputedStyle(tr);
                if (cs.backgroundColor === "rgb(255, 192, 203)") {
                    styledIndices.push(i);
                }
                if (i === 1 || i === 2 || i === 3) {
                    styles[i] = { bg: cs.backgroundColor, color: cs.color, weight: cs.fontWeight };
                }
            });
            return { styledIndices, boundary50Bg: styles[1].bg, row2: styles[2], row3: styles[3] };
        }""")
        exp1 = {
            "styledIndices": [2, 3],
            "boundary50Bg": "rgba(0, 0, 0, 0)",
            "row2": {"bg": "rgb(255, 192, 203)", "color": "rgb(0, 0, 255)", "weight": "700"},
            "row3": {"bg": "rgb(255, 192, 203)", "color": "rgb(0, 0, 255)", "weight": "700"},
        }
        cases.append(dict(name="rowstyler_threshold_above_50", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Object return {class, style} in rowStyler
        res2 = page.evaluate("""() => {
            window.lab.renderGrid(window.lab.initialRows, (index, row) => {
                if (row.listprice >= 50) return { class: "high-row", style: "font-style:italic;" };
            });
            const row1 = document.querySelector('#tt tbody tr[data-index="1"]');
            const cs = getComputedStyle(row1);
            return {
                matchedCount: document.querySelectorAll("#tt tbody tr.high-row").length,
                row1HasClass: row1.classList.contains("high-row"),
                row1Bg: cs.backgroundColor,
                row1FontStyle: cs.fontStyle
            };
        }""")
        exp2 = {
            "matchedCount": 3,
            "row1HasClass": True,
            "row1Bg": "rgb(255, 240, 200)",
            "row1FontStyle": "italic",
        }
        cases.append(dict(name="rowstyler_class_and_inline_variants", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Reloading updated data reapplies rowStyler cleanly
        res3 = page.evaluate("""() => {
            const nextRows = window.lab.initialRows.map(r => ({ ...r }));
            nextRows[0].listprice = 65.0;
            nextRows[2].listprice = 42.0;
            window.lab.renderGrid(nextRows, (index, row) => {
                if (row.listprice > 50) return "background-color:pink;color:blue;font-weight:bold;";
            });
            const highlighted = Array.from(document.querySelectorAll("#tt tbody tr"))
                .map((tr, i) => ({ i, bg: getComputedStyle(tr).backgroundColor }))
                .filter(x => x.bg === "rgb(255, 192, 203)")
                .map(x => x.i);
            return { highlighted };
        }""")
        exp3 = {"highlighted": [0, 3]}
        cases.append(dict(name="rowstyler_reapplies_on_reload", 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-datagrid18-lab/explore-datagrid-datagrid18.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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