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

运行 EasyUI 插件扩展($.fn.methods)与 $.parser.parse 实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-ref-plugins.py
explore-ref-plugins.py312 行
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 67 (ref-plugins): Plugin Architecture & Parser."""
import json
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from playwright.sync_api import sync_playwright

LANG_DATA = [
    {"id": "zh", "text": "Chinese"},
    {"id": "en", "text": "English"},
    {"id": "ja", "text": "Japanese"},
]


def start_server():
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, fmt, *args):
            pass

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

    srv = HTTPServer(("127.0.0.1", 0), Handler)
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    return srv, srv.server_address[1]


HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>jQuery EasyUI Plugin Architecture Offline Lab</title>
  <style>
    .dialog-box { position: absolute; left: 20px; top: 30px; width: 220px; border: 1px solid #64748b; }
    .panel-box { border: 1px solid #94a3b8; margin: 8px 0; }
    .panel-header { background: #e2e8f0; padding: 4px 8px; display: flex; justify-content: space-between; }
    .panel-body { padding: 8px; }
  </style>
</head>
<body>
  <div id="dd" class="dialog-box">Dialog Content</div>

  <div id="p-legacy" class="easyui-panel" style="width:500px;height:200px;padding:10px;"
       title="My Panel" iconCls="icon-save" collapsible="true">The panel content</div>

  <div id="p-html5" class="easyui-panel" style="width:500px;height:200px;padding:10px;"
       title="My Panel" data-options="iconCls:'icon-save',collapsible:true">The panel content</div>

  <input id="lang-cb" class="easyui-combobox" name="language"
         data-options="url:'/combobox_data.json',valueField:'id',textField:'text',panelHeight:'auto',onSelect:function(record){ window.__selectedRecords.push(record.text); }">

  <script>
    window.__selectedRecords = [];

    // Minimal jQuery + EasyUI plugin architecture (defaults, methods, $.extend, $.parser.parse)
    function JQ(els) {
      this.els = els;
    }
    JQ.prototype.each = function (fn) {
      this.els.forEach((el, idx) => fn.call(el, idx, el));
      return this;
    };

    function $(sel) {
      if (typeof sel === 'string') return new JQ(Array.from(document.querySelectorAll(sel)));
      if (sel instanceof HTMLElement) return new JQ([sel]);
      return sel;
    }
    $.fn = JQ.prototype;
    $.extend = function (target, ...sources) {
      return Object.assign(target, ...sources);
    };

    function parseDataOptions(el) {
      const raw = el.getAttribute('data-options');
      if (!raw) return {};
      return new Function('return {' + raw + '};')();
    }

    // 1. Dialog plugin with defaults & methods
    $.fn.dialog = function (methodOrOpts, param) {
      if (typeof methodOrOpts === 'string') {
        const fn = $.fn.dialog.methods[methodOrOpts];
        if (!fn) throw new Error('Unknown dialog method: ' + methodOrOpts);
        return fn(this, param);
      }
      const opts = $.extend({}, $.fn.dialog.defaults, methodOrOpts || {});
      return this.each(function () { this._dialogOpts = opts; });
    };
    $.fn.dialog.defaults = { title: 'New Dialog', modal: false, closed: false, collapsible: false };
    $.fn.dialog.methods = {
      options: (jq) => jq.els[0]._dialogOpts,
      move: (jq, pos) => jq.each(function () {
        if (pos.left !== undefined) this.style.left = pos.left + 'px';
        if (pos.top !== undefined) this.style.top = pos.top + 'px';
      })
    };

    // 2. Panel plugin supporting legacy HTML attrs and 1.3+ data-options
    $.fn.panel = function (methodOrOpts, param) {
      if (typeof methodOrOpts === 'string') {
        return $.fn.panel.methods[methodOrOpts](this, param);
      }
      return this.each(function () {
        const legacy = {};
        if (this.hasAttribute('title')) legacy.title = this.getAttribute('title');
        if (this.hasAttribute('iconCls')) legacy.iconCls = this.getAttribute('iconCls');
        if (this.hasAttribute('collapsible')) legacy.collapsible = this.getAttribute('collapsible') === 'true';
        const dataOpts = parseDataOptions(this);
        const opts = $.extend({}, $.fn.panel.defaults, legacy, dataOpts, methodOrOpts || {});
        this._panelOpts = opts;
        const bodyText = this.textContent.trim();
        this.classList.add('panel-box');
        this.innerHTML = `<div class="panel-header"><span class="panel-title" data-icon="${opts.iconCls}">${opts.title}</span>` +
          (opts.collapsible ? '<button type="button" class="panel-toggle">[-]</button>' : '') +
          `</div><div class="panel-body">${bodyText}</div>`;
        this._collapsed = false;
      });
    };
    $.fn.panel.defaults = { title: '', iconCls: '', collapsible: false };
    $.fn.panel.methods = {
      options: (jq) => jq.els[0]._panelOpts,
      collapse: (jq) => jq.each(function () {
        this._collapsed = true;
        this.querySelector('.panel-body').style.display = 'none';
      }),
      expand: (jq) => jq.each(function () {
        this._collapsed = false;
        this.querySelector('.panel-body').style.display = 'block';
      })
    };

    // 3. Combobox plugin parsed from data-options with onSelect callback
    $.fn.combobox = function (methodOrOpts, param) {
      if (typeof methodOrOpts === 'string') {
        return $.fn.combobox.methods[methodOrOpts](this, param);
      }
      const el = this.els[0];
      const opts = $.extend({}, $.fn.combobox.defaults, parseDataOptions(el), methodOrOpts || {});
      el._cbOpts = opts;
      el._cbReady = fetch(opts.url).then(r => r.json()).then(rows => { el._cbRows = rows; });
      return this;
    };
    $.fn.combobox.defaults = { valueField: 'value', textField: 'text', panelHeight: 200, onSelect: null };
    $.fn.combobox.methods = {
      select: (jq, val) => jq.each(function () {
        const opts = this._cbOpts;
        const rec = (this._cbRows || []).find(r => r[opts.valueField] === val);
        if (rec) {
          this.value = rec[opts.textField];
          this._cbValue = rec[opts.valueField];
          if (typeof opts.onSelect === 'function') opts.onSelect(rec);
        }
      }),
      getValue: (jq) => jq.els[0]._cbValue
    };

    // 4. Parser scans easyui-* classes
    $.parser = {
      plugins: ['panel', 'combobox'],
      parse: function (context) {
        const root = context || document;
        const parsed = [];
        for (const name of $.parser.plugins) {
          root.querySelectorAll('.easyui-' + name).forEach(el => {
            $(el)[name]();
            parsed.push(name + '#' + el.id);
          });
        }
        return parsed;
      }
    };

    window.$ = $;
    window.__parsed = $.parser.parse();
    $('#dd').dialog({ title: 'My Dialog' });
  </script>
</body>
</html>
"""


def launch_browser(pw):
    try:
        return pw.chromium.launch(headless=True)
    except Exception:
        return pw.chromium.launch(headless=True, channel="chrome")


def main():
    srv, port = start_server()
    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('lang-cb')._cbReady")

            # Case 1: Extend $.fn.dialog.methods with mymove(jq, newposition) and invoke $('#dd').dialog('mymove', ...)
            res1 = page.evaluate("""() => {
                $.extend($.fn.dialog.methods, {
                    mymove: function (jq, newposition) {
                        return jq.each(function () {
                            $(this).dialog('move', newposition);
                        });
                    }
                });
                const chained = $('#dd').dialog('mymove', { left: 200, top: 100 });
                const cs = getComputedStyle(document.getElementById('dd'));
                return {
                    default_title: $.fn.dialog.defaults.title,
                    has_mymove: typeof $.fn.dialog.methods.mymove === 'function',
                    chained_ok: chained.els && chained.els[0].id === 'dd',
                    left: cs.left,
                    top: cs.top
                };
            }""")
            exp1 = {
                "default_title": "New Dialog",
                "has_mymove": True,
                "chained_ok": True,
                "left": "200px",
                "top": "100px",
            }
            cases.append({
                "name": "plugin_defaults_and_custom_method_extension",
                "passed": res1 == exp1,
                "expected": exp1,
                "actual": res1,
            })

            # Case 2: $.parser.parse parses legacy attrs and 1.3+ HTML5 data-options into equivalent panel config & collapse behavior
            res2 = page.evaluate("""() => {
                const optLegacy = $('#p-legacy').panel('options');
                const optHtml5 = $('#p-html5').panel('options');
                $('#p-html5').panel('collapse');
                const bodyHidden = getComputedStyle(document.querySelector('#p-html5 .panel-body')).display;
                $('#p-html5').panel('expand');
                const bodyShown = getComputedStyle(document.querySelector('#p-html5 .panel-body')).display;
                return {
                    parsed: window.__parsed,
                    options_identical: JSON.stringify(optLegacy) === JSON.stringify(optHtml5),
                    iconCls: optHtml5.iconCls,
                    collapsible: optHtml5.collapsible,
                    body_hidden: bodyHidden,
                    body_shown: bodyShown
                };
            }""")
            exp2 = {
                "parsed": ["panel#p-legacy", "panel#p-html5", "combobox#lang-cb"],
                "options_identical": True,
                "iconCls": "icon-save",
                "collapsible": True,
                "body_hidden": "none",
                "body_shown": "block",
            }
            cases.append({
                "name": "parser_legacy_markup_vs_html5_data_options",
                "passed": res2 == exp2,
                "expected": exp2,
                "actual": res2,
            })

            # Case 3: Declarative easyui-combobox with data-options onSelect fires callback on selection
            res3 = page.evaluate("""() => {
                $('#lang-cb').combobox('select', 'zh');
                $('#lang-cb').combobox('select', 'en');
                const el = document.getElementById('lang-cb');
                return {
                    panelHeight: el._cbOpts.panelHeight,
                    current_value: $('#lang-cb').combobox('getValue'),
                    input_text: el.value,
                    selected_events: window.__selectedRecords
                };
            }""")
            exp3 = {
                "panelHeight": "auto",
                "current_value": "en",
                "input_text": "English",
                "selected_events": ["Chinese", "English"],
            }
            cases.append({
                "name": "declarative_combobox_data_options_onselect",
                "passed": res3 == exp3,
                "expected": exp3,
                "actual": res3,
            })

            browser.close()
    finally:
        srv.shutdown()
    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-ref-plugins-lab/explore-ref-plugins.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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