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

离线 Chromium 验证 HTML data-options 声明式对话框与 JS 编程式 ComboBox

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-jqueryeasyui-intro.py
explore-jqueryeasyui-intro.py309 行
"""Offline Playwright Chromium verification lab for jQuery EasyUI Intro (Ch02)."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright

COMBO_ITEMS = [
    {"id": "1", "text": "HTML5 Markup"},
    {"id": "2", "text": "JavaScript API"},
    {"id": "3", "text": "DataGrid Plugin"},
]


class ComboHandler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        pass

    def do_GET(self):
        if self.path == "/combo_data.json":
            body = json.dumps(COMBO_ITEMS).encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        if self.path == "/":
            body = HTML_DOC.encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        self.send_response(404)
        self.end_headers()


HTML_DOC = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery EasyUI Intro Lab</title>
<style>
  body { font-family: Arial, sans-serif; margin: 16px; }
  .window { border: 1px solid #95b8e7; box-sizing: border-box; background: #fff; }
  .panel-header { background: #e0ecff; padding: 6px 8px; display: flex; justify-content: space-between; align-items: center; }
  .panel-title { font-weight: bold; }
  .panel-body { padding: 10px; }
  .hidden { display: none; }
  .combo-wrap { position: relative; display: inline-block; margin-top: 16px; }
  .combo-panel { border: 1px solid #95b8e7; background: #fff; position: absolute; left: 0; top: 100%; width: 100%; box-sizing: border-box; }
  .combobox-item { padding: 4px 8px; cursor: pointer; }
  .combobox-item.selected { background: #ffe48d; }
  .validatebox-invalid { border: 1px solid #d9534f; background: #fff3f3; }
</style>
</head>
<body>
  <div id="dlg1" class="easyui-dialog" style="width:400px;height:200px"
       data-options="title:'My Dialog',collapsible:true,iconCls:'icon-ok',onOpen:function(){ window.__openCount += 1; }">
      dialog content.
  </div>

  <div style="margin-top:20px;">
    <input id="cc" style="width:200px" />
  </div>

  <div id="dlg2" style="width:400px;height:200px">programmatic dialog content.</div>

  <script>
    window.__openCount = 0;

    function parseDataOptions(el) {
      const raw = (el.getAttribute('data-options') || '').trim();
      if (!raw) return {};
      return Function('"use strict"; return ({' + raw + '});')();
    }

    function initDialog(el, opts) {
      const cfg = Object.assign({ title: '', collapsible: false, iconCls: '', onOpen: null }, opts || {});
      const content = el.innerHTML.trim();
      el.innerHTML = '';
      el.classList.add('window');
      const header = document.createElement('div');
      header.className = 'panel-header';
      const titleSpan = document.createElement('span');
      titleSpan.className = 'panel-title ' + cfg.iconCls;
      titleSpan.textContent = cfg.title;
      header.appendChild(titleSpan);
      let collapseBtn = null;
      if (cfg.collapsible) {
        collapseBtn = document.createElement('button');
        collapseBtn.type = 'button';
        collapseBtn.className = 'panel-tool-collapse';
        collapseBtn.textContent = '−';
        header.appendChild(collapseBtn);
      }
      const body = document.createElement('div');
      body.className = 'panel-body';
      body.textContent = content;
      el.appendChild(header);
      el.appendChild(body);
      el.__dialogState = { title: cfg.title, iconCls: cfg.iconCls, collapsible: cfg.collapsible, collapsed: false };
      if (collapseBtn) {
        collapseBtn.addEventListener('click', () => {
          el.__dialogState.collapsed = !el.__dialogState.collapsed;
          body.classList.toggle('hidden', el.__dialogState.collapsed);
        });
      }
      if (typeof cfg.onOpen === 'function') cfg.onOpen.call(el);
      return el.__dialogState;
    }

    // Minimal jQuery-like wrapper supporting .dialog() and .combobox()
    function $(sel) {
      const el = typeof sel === 'string' ? document.querySelector(sel) : sel;
      return {
        dialog(arg) {
          if (typeof arg === 'string' && arg === 'options') return el.__dialogState;
          initDialog(el, arg);
          return this;
        },
        combobox(arg) {
          if (arg === 'getValue') return el.__combo.value;
          if (arg === 'getText') return el.__combo.text;
          if (arg === 'isValid') {
            const valid = !el.__combo.required || Boolean(el.__combo.value);
            el.classList.toggle('validatebox-invalid', !valid);
            return valid;
          }
          const cfg = Object.assign({ url: '', required: false, valueField: 'id', textField: 'text' }, arg || {});
          const wrap = document.createElement('div');
          wrap.className = 'combo-wrap';
          el.parentNode.insertBefore(wrap, el);
          wrap.appendChild(el);
          const arrow = document.createElement('button');
          arrow.type = 'button';
          arrow.id = el.id + '-arrow';
          arrow.textContent = '▼';
          wrap.appendChild(arrow);
          const panel = document.createElement('div');
          panel.id = el.id + '-panel';
          panel.className = 'combo-panel hidden';
          wrap.appendChild(panel);
          el.__combo = { value: '', text: '', required: cfg.required, items: [], loaded: false };
          arrow.addEventListener('click', () => panel.classList.toggle('hidden'));
          el.__comboReady = fetch(cfg.url).then(r => r.json()).then(rows => {
            el.__combo.items = rows;
            el.__combo.loaded = true;
            panel.innerHTML = '';
            rows.forEach(item => {
              const div = document.createElement('div');
              div.className = 'combobox-item';
              div.dataset.value = item[cfg.valueField];
              div.textContent = item[cfg.textField];
              div.addEventListener('click', () => {
                el.__combo.value = String(item[cfg.valueField]);
                el.__combo.text = String(item[cfg.textField]);
                el.value = el.__combo.text;
                panel.querySelectorAll('.combobox-item').forEach(x => x.classList.remove('selected'));
                div.classList.add('selected');
                panel.classList.add('hidden');
                el.classList.remove('validatebox-invalid');
              });
              panel.appendChild(div);
            });
          });
          return this;
        }
      };
    }
    window.$ = $;

    // 1. Declarative parser
    document.querySelectorAll('.easyui-dialog').forEach(el => {
      initDialog(el, parseDataOptions(el));
    });

    // 2. Programmatic combobox
    $('#cc').combobox({
      url: '/combo_data.json',
      required: true,
      valueField: 'id',
      textField: 'text'
    });
  </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():
    server = ThreadingHTTPServer(("127.0.0.1", 0), ComboHandler)
    port = server.server_address[1]
    t = threading.Thread(target=server.serve_forever, daemon=True)
    t.start()
    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            page = browser.new_page()
            page.goto(f"http://127.0.0.1:{port}/")
            page.evaluate("() => document.getElementById('cc').__comboReady")

            # Case 1: Declarative HTML dialog parsing & collapse interaction
            before = page.evaluate("""() => {
                const el = document.getElementById('dlg1');
                const rect = el.getBoundingClientRect();
                return {
                    title: el.querySelector('.panel-title').textContent,
                    hasIconOk: el.querySelector('.panel-title').classList.contains('icon-ok'),
                    body: el.querySelector('.panel-body').textContent,
                    width: Math.round(rect.width),
                    height: Math.round(rect.height),
                    openCount: window.__openCount
                };
            }""")
            page.click("#dlg1 .panel-tool-collapse")
            collapsed = page.evaluate("() => document.querySelector('#dlg1 .panel-body').classList.contains('hidden')")
            act1 = dict(before, collapsedAfterClick=collapsed)
            exp1 = {
                "title": "My Dialog",
                "hasIconOk": True,
                "body": "dialog content.",
                "width": 400,
                "height": 200,
                "openCount": 1,
                "collapsedAfterClick": True,
            }
            cases.append({
                "name": "html_declarative_dialog",
                "expected": exp1,
                "actual": act1,
                "passed": act1 == exp1,
            })

            # Case 2: Programmatic JS combobox with required validation & selection
            valid_empty = page.evaluate("() => $('#cc').combobox('isValid')")
            page.click("#cc-arrow")
            page.click('#cc-panel .combobox-item[data-value="2"]')
            act2 = page.evaluate("""(validEmpty) => ({
                validWhenEmpty: validEmpty,
                validAfterSelect: $('#cc').combobox('isValid'),
                value: $('#cc').combobox('getValue'),
                text: $('#cc').combobox('getText'),
                itemCount: document.querySelectorAll('#cc-panel .combobox-item').length
            })""", valid_empty)
            exp2 = {
                "validWhenEmpty": False,
                "validAfterSelect": True,
                "value": "2",
                "text": "JavaScript API",
                "itemCount": 3,
            }
            cases.append({
                "name": "js_programmatic_combobox",
                "expected": exp2,
                "actual": act2,
                "passed": act2 == exp2,
            })

            # Case 3: Declarative vs Programmatic dialog API parity
            act3 = page.evaluate("""() => {
                $('#dlg2').dialog({
                    title: 'My Dialog',
                    collapsible: true,
                    iconCls: 'icon-ok',
                    onOpen: function() { window.__openCount += 1; }
                });
                const d1 = $('#dlg1').dialog('options');
                const d2 = $('#dlg2').dialog('options');
                return {
                    sameTitle: d1.title === d2.title,
                    sameIcon: d1.iconCls === d2.iconCls,
                    sameCollapsible: d1.collapsible === d2.collapsible,
                    totalOpenCalls: window.__openCount
                };
            }""")
            exp3 = {
                "sameTitle": True,
                "sameIcon": True,
                "sameCollapsible": True,
                "totalOpenCalls": 2,
            }
            cases.append({
                "name": "declarative_vs_programmatic_parity",
                "expected": exp3,
                "actual": act3,
                "passed": act3 == exp3,
            })

            browser.close()
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/jeasyui-jqueryeasyui-intro-lab/explore-jqueryeasyui-intro.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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