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

运行 DataGrid 列 formatter 条件标红与边界值隔离的离线 Chromium 实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-datagrid-datagrid7.py
explore-datagrid-datagrid7.py152 行
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 28: Formatting Columns."""
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 Formatting Columns Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .dg-panel { width: 550px; 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; }
</style>
</head>
<body>
<div class="dg-panel">
  <div class="dg-title">Formatting Columns</div>
  <table id="tt">
    <thead>
      <tr>
        <th field="itemid" width="80">Item ID</th>
        <th field="productid" width="80">Product ID</th>
        <th field="listprice" width="80" align="right" formatter="formatPrice">List Price</th>
        <th field="unitcost" width="80" align="right">Unit Cost</th>
        <th field="attr1" width="100">Attribute</th>
        <th field="status" width="60" align="center">Status</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>
<script>
const ROWS = [
  { itemid: "EST-1", productid: "FI-SW-01", listprice: 16.5, unitcost: 10.0, attr1: "Large", status: "P" },
  { itemid: "EST-10", productid: "K9-DL-01", listprice: 18.5, unitcost: 12.0, attr1: "Spotted", status: "P" },
  { itemid: "EST-20", productid: "K9-BD-01", listprice: 20.0, unitcost: 12.0, attr1: "Boundary", status: "P" },
  { itemid: "EST-11", productid: "RP-SN-01", listprice: 38.5, unitcost: 12.0, attr1: "Venomless", status: "P" },
  { itemid: "EST-12", productid: "RP-LI-02", listprice: 19.99, unitcost: 12.0, attr1: "Green", status: "P" },
];
window.formatterCalls = [];

function formatPrice(val, row, index) {
  window.formatterCalls.push({ val, itemid: row.itemid, index });
  if (val < 20) {
    return '<span style="color:red;">(' + val + ')</span>';
  } else {
    return val;
  }
}

const ths = Array.from(document.querySelectorAll('#tt thead th'));
const tbody = document.querySelector('#tt tbody');
ROWS.forEach((row, index) => {
  const tr = document.createElement('tr');
  ths.forEach(th => {
    const field = th.getAttribute('field');
    const align = th.getAttribute('align');
    const fmtName = th.getAttribute('formatter');
    const td = document.createElement('td');
    td.dataset.field = field;
    if (align) td.style.textAlign = align;
    const raw = row[field];
    if (fmtName && typeof window[fmtName] === 'function') {
      td.innerHTML = String(window[fmtName](raw, row, index));
    } else {
      td.textContent = String(raw);
    }
    tr.appendChild(td);
  });
  tbody.appendChild(tr);
});

window.rawRows = ROWS;
</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": 680, "height": 420})
        page.set_content(HTML_DOC)

        # Case 1: Prices < 20 render red parenthesized span; >= 20 render plain text
        res1 = page.evaluate("""() => Array.from(document.querySelectorAll('#tt tbody td[data-field="listprice"]')).map(td => {
            const span = td.querySelector('span');
            return {
                text: td.textContent.trim(),
                hasRedSpan: Boolean(span),
                color: span ? getComputedStyle(span).color : 'default',
            };
        })""")
        exp1 = [
            {"text": "(16.5)", "hasRedSpan": True, "color": "rgb(255, 0, 0)"},
            {"text": "(18.5)", "hasRedSpan": True, "color": "rgb(255, 0, 0)"},
            {"text": "20", "hasRedSpan": False, "color": "default"},
            {"text": "38.5", "hasRedSpan": False, "color": "default"},
            {"text": "(19.99)", "hasRedSpan": True, "color": "rgb(255, 0, 0)"},
        ]
        cases.append(dict(name="formatter_conditional_red_under_20", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Formatter receives (value, row, index) and leaves raw row numeric values unmutated
        res2 = page.evaluate("""() => ({
            calls: window.formatterCalls,
            rawTypes: window.rawRows.map(r => typeof r.listprice),
            rawValues: window.rawRows.map(r => r.listprice),
        })""")
        exp2 = {
            "calls": [
                {"val": 16.5, "itemid": "EST-1", "index": 0},
                {"val": 18.5, "itemid": "EST-10", "index": 1},
                {"val": 20, "itemid": "EST-20", "index": 2},
                {"val": 38.5, "itemid": "EST-11", "index": 3},
                {"val": 19.99, "itemid": "EST-12", "index": 4},
            ],
            "rawTypes": ["number", "number", "number", "number", "number"],
            "rawValues": [16.5, 18.5, 20, 38.5, 19.99],
        }
        cases.append(dict(name="formatter_receives_value_row_index", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Exact boundary 20.0 stays unformatted and right alignment is preserved
        res3 = page.evaluate("""() => {
            const cells = Array.from(document.querySelectorAll('#tt tbody td[data-field="listprice"]'));
            return {
                boundaryInnerHTML: cells[2].innerHTML,
                allRightAligned: cells.every(td => getComputedStyle(td).textAlign === 'right'),
            };
        }""")
        exp3 = {"boundaryInnerHTML": "20", "allRightAligned": True}
        cases.append(dict(name="boundary_value_exact_20_and_alignment", 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-datagrid7-lab/explore-datagrid-datagrid7.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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