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

运行 DataGrid 客户端自定义日期 sorter 与格式陷阱对比的离线 Chromium 实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-datagrid-datagrid14.py
explore-datagrid-datagrid14.py192 行
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 30: Custom Sorting."""
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 Custom Sorting Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .dg-panel { width: 520px; 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; }
  th[data-sortable="true"] { cursor: pointer; }
</style>
</head>
<body>
<div class="dg-panel">
  <div class="dg-title">Custom Sort</div>
  <table id="tt"><thead></thead><tbody></tbody></table>
</div>
<script>
const INIT_DATA = [
  { itemid: "EST-1", listprice: 38.5, unitcost: 12.0, attr1: "Venomless", date: "15/01/2024", status: "P" },
  { itemid: "EST-2", listprice: 16.5, unitcost: 10.0, attr1: "Large", date: "09/10/2024", status: "P" },
  { itemid: "EST-3", listprice: 158.5, unitcost: 92.0, attr1: "Adult Male", date: "05/03/2023", status: "P" },
  { itemid: "EST-4", listprice: 18.5, unitcost: 11.0, attr1: "Spotted", date: "22/11/2023", status: "P" },
  { itemid: "EST-5", listprice: 26.5, unitcost: 13.0, attr1: "Rattleless", date: "02/01/2024", status: "P" },
];

// True dd/mm/yyyy numeric sorter
function ddMmYyyySorter(a, b) {
  const pa = a.split('/').map(Number);
  const pb = b.split('/').map(Number);
  if (pa[2] !== pb[2]) return pa[2] > pb[2] ? 1 : -1;
  if (pa[1] !== pb[1]) return pa[1] > pb[1] ? 1 : -1;
  if (pa[0] !== pb[0]) return pa[0] > pb[0] ? 1 : -1;
  return 0;
}

// Source-pattern a[2] -> a[0] -> a[1] sorter (matches mm/dd/yyyy)
function sourcePatternSorter(a, b) {
  const pa = a.split('/');
  const pb = b.split('/');
  if (pa[2] === pb[2]) {
    if (pa[0] === pb[0]) {
      return pa[1] > pb[1] ? 1 : -1;
    } else {
      return pa[0] > pb[0] ? 1 : -1;
    }
  } else {
    return pa[2] > pb[2] ? 1 : -1;
  }
}

const COLUMNS = [
  { field: 'itemid', title: 'Item ID', width: 60, sortable: true },
  { field: 'listprice', title: 'List Price', width: 70, align: 'right', sortable: true },
  { field: 'unitcost', title: 'Unit Cost', width: 70, align: 'right', sortable: true },
  { field: 'attr1', title: 'Attribute', width: 120, sortable: true },
  { field: 'date', title: 'Date', width: 80, sortable: true, align: 'center', sorter: ddMmYyyySorter },
  { field: 'status', title: 'Status', width: 40, align: 'center', sortable: false },
];

let rows = INIT_DATA.map(r => ({ ...r }));
const sortState = { field: null, order: 'asc', remoteSort: false };

function render() {
  const thead = document.querySelector('#tt thead');
  const tbody = document.querySelector('#tt tbody');
  thead.innerHTML = '<tr>' + COLUMNS.map(c =>
    `<th data-field="${c.field}" data-sortable="${Boolean(c.sortable)}" style="width:${c.width}px">${c.title}</th>`
  ).join('') + '</tr>';
  tbody.innerHTML = rows.map(r =>
    '<tr>' + COLUMNS.map(c =>
      `<td data-field="${c.field}" style="${c.align ? 'text-align:' + c.align : ''}">${r[c.field]}</td>`
    ).join('') + '</tr>'
  ).join('');
  thead.querySelectorAll('th').forEach(th => {
    th.addEventListener('click', () => {
      const col = COLUMNS.find(c => c.field === th.dataset.field);
      if (!col || !col.sortable) return;
      const order = (sortState.field === col.field && sortState.order === 'asc') ? 'desc' : 'asc';
      sortState.field = col.field;
      sortState.order = order;
      const mult = order === 'asc' ? 1 : -1;
      rows.sort((ra, rb) => {
        const va = ra[col.field];
        const vb = rb[col.field];
        if (col.sorter) return col.sorter(va, vb) * mult;
        if (va === vb) return 0;
        return (va > vb ? 1 : -1) * mult;
      });
      render();
    });
  });
}

window.customSortApi = {
  getDates() { return rows.map(r => r.date); },
  getPrices() { return rows.map(r => r.listprice); },
  getState() { return { ...sortState }; },
  compareDemo() {
    const sample = ["15/01/2024", "09/10/2024", "02/01/2024"];
    return {
      contractGt: ddMmYyyySorter("15/01/2024", "02/01/2024"),
      contractLt: ddMmYyyySorter("02/01/2024", "15/01/2024"),
      contractEq: ddMmYyyySorter("02/01/2024", "02/01/2024"),
      lexicographic: [...sample].sort(),
      sourceA0BeforeA1: [...sample].sort(sourcePatternSorter),
      trueDdMmYyyy: [...sample].sort(ddMmYyyySorter),
    };
  }
};

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

        # Case 1: remoteSort=false local dd/mm/yyyy sorter asc then desc
        page.click('th[data-field="date"]')
        asc_dates = page.evaluate("() => window.customSortApi.getDates()")
        page.click('th[data-field="date"]')
        desc_dates = page.evaluate("() => window.customSortApi.getDates()")
        res1 = {
            "remoteSort": page.evaluate("() => window.customSortApi.getState().remoteSort"),
            "ascDates": asc_dates,
            "descDates": desc_dates,
        }
        exp1 = {
            "remoteSort": False,
            "ascDates": ["05/03/2023", "22/11/2023", "02/01/2024", "15/01/2024", "09/10/2024"],
            "descDates": ["09/10/2024", "15/01/2024", "02/01/2024", "22/11/2023", "05/03/2023"],
        }
        cases.append(dict(name="remote_sort_false_client_sorter_asc_desc", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Sorter return contract (1 / -1 / 0) and dd/mm/yyyy vs mm/dd/yyyy comparison
        res2 = page.evaluate("() => window.customSortApi.compareDemo()")
        exp2 = {
            "contractGt": 1,
            "contractLt": -1,
            "contractEq": 0,
            "lexicographic": ["02/01/2024", "09/10/2024", "15/01/2024"],
            "sourceA0BeforeA1": ["02/01/2024", "09/10/2024", "15/01/2024"],
            "trueDdMmYyyy": ["02/01/2024", "15/01/2024", "09/10/2024"],
        }
        cases.append(dict(name="sorter_return_contract_and_date_format_pitfall", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Numeric listprice sort works while non-sortable status ignores click
        page.click('th[data-field="listprice"]')
        prices_after_sort = page.evaluate("() => window.customSortApi.getPrices()")
        page.click('th[data-field="status"]')
        prices_after_status = page.evaluate("() => window.customSortApi.getPrices()")
        res3 = {
            "sortedPrices": prices_after_sort,
            "unchangedAfterStatusClick": prices_after_status == prices_after_sort,
            "activeField": page.evaluate("() => window.customSortApi.getState().field"),
        }
        exp3 = {
            "sortedPrices": [16.5, 18.5, 26.5, 38.5, 158.5],
            "unchangedAfterStatusClick": True,
            "activeField": "listprice",
        }
        cases.append(dict(name="numeric_and_non_sortable_columns", 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-datagrid14-lab/explore-datagrid-datagrid14.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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