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

在离线 Chromium 中实测 custom.colorize 部件初始化、回调否决、禁用拦截与销毁清理

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-example-widget.py
explore-example-widget.py312 行
"""Offline Chromium lab for jQuery UI Ch43: Widget Factory custom.colorize widget."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Widget Factory colorize Lab</title>
<style>
  body { margin: 12px; font-family: sans-serif; }
  .custom-colorize { font-size: 20px; position: relative; width: 75px; height: 75px; display: inline-block; margin-right: 10px; }
  .custom-colorize-changer { font-size: 10px; position: absolute; right: 0; bottom: 0; }
</style>
</head>
<body>
<div>
  <div id="my-widget1">改变颜色</div>
  <div id="my-widget2">改变颜色</div>
  <div id="my-widget3">改变颜色</div>
  <button id="disable">切换 disabled 选项</button>
  <button id="black">改为黑色</button>
</div>

<script>
// Minimal faithful Widget Factory core supporting $.widget("custom.colorize", proto)
const widgetStore = new Map();
const widgetRegistry = {};
window.__changeCounts = { "my-widget1": 0, "my-widget2": 0, "my-widget3": 0 };
window.__nextColorsQueue = [];

function createWidgetFactory(fullName, proto) {
  const [ns, name] = fullName.split(".");
  const key = ns + "-" + name;
  widgetRegistry[key] = { ns, name, proto };

  function BaseWidget(element, options) {
    this.element = element;
    this.widgetFullName = key;
    this.options = Object.assign({ disabled: false }, proto.options, options || {});
    this._boundListeners = [];
    widgetStore.set(element, this);
    this._create();
  }

  BaseWidget.prototype._super = function(k, v) {
    this.options[k] = v;
  };
  BaseWidget.prototype._superApply = function(args) {
    const hash = args[0] || {};
    for (const [k, v] of Object.entries(hash)) {
      this._setOption(k, v);
    }
  };
  BaseWidget.prototype._setOptions = function(options) {
    for (const [k, v] of Object.entries(options)) {
      this._setOption(k, v);
    }
  };
  BaseWidget.prototype._setOption = function(key, value) {
    this.options[key] = value;
  };
  BaseWidget.prototype._on = function(target, handlers) {
    for (const [evName, method] of Object.entries(handlers)) {
      const fn = (ev) => {
        if (this.options.disabled) return;
        const handler = typeof method === "string" ? this[method] : method;
        handler.call(this, ev);
      };
      target.addEventListener(evName, fn);
      this._boundListeners.push([target, evName, fn]);
    }
  };
  BaseWidget.prototype._trigger = function(type, ev, data) {
    const cb = this.options[type];
    if (type === "change" && window.__changeCounts[this.element.id] !== undefined) {
      window.__changeCounts[this.element.id]++;
    }
    if (typeof cb === "function") {
      return cb.call(this.element, ev || {}, data || {});
    }
    return true;
  };
  BaseWidget.prototype.option = function(k, v) {
    if (typeof k === "string" && arguments.length === 1) return this.options[k];
    if (typeof k === "string") {
      this._setOptions({ [k]: v });
      return this;
    }
    if (typeof k === "object") {
      this._setOptions(k);
      return this;
    }
    return this.options;
  };
  BaseWidget.prototype.disable = function() {
    this.option("disabled", true);
    this.element.classList.add("ui-state-disabled");
  };
  BaseWidget.prototype.enable = function() {
    this.option("disabled", false);
    this.element.classList.remove("ui-state-disabled");
  };
  BaseWidget.prototype.destroy = function() {
    this._boundListeners.forEach(([t, ev, fn]) => t.removeEventListener(ev, fn));
    this._boundListeners = [];
    if (this._destroy) this._destroy();
    widgetStore.delete(this.element);
  };

  Object.assign(BaseWidget.prototype, proto);
  return BaseWidget;
}

const Colorize = createWidgetFactory("custom.colorize", {
  options: { red: 255, green: 0, blue: 0, change: null, random: null },
  _create() {
    this.element.classList.add("custom-colorize");
    this.element.style.userSelect = "none";
    this.changer = document.createElement("button");
    this.changer.textContent = "改变";
    this.changer.className = "custom-colorize-changer";
    this.element.appendChild(this.changer);
    this._on(this.changer, { click: "random" });
    this._refresh();
  },
  _refresh() {
    this.element.style.backgroundColor = `rgb(${this.options.red}, ${this.options.green}, ${this.options.blue})`;
    this._trigger("change");
  },
  random(event) {
    const colors = window.__nextColorsQueue.length
      ? window.__nextColorsQueue.shift()
      : {
          red: Math.floor(Math.random() * 256),
          green: Math.floor(Math.random() * 256),
          blue: Math.floor(Math.random() * 256)
        };
    if (this._trigger("random", event, colors) !== false) {
      this.option(colors);
    }
  },
  _destroy() {
    this.changer.remove();
    this.element.classList.remove("custom-colorize");
    this.element.style.userSelect = "";
    this.element.style.backgroundColor = "transparent";
  },
  _setOptions() {
    this._superApply(arguments);
    this._refresh();
  },
  _setOption(key, value) {
    if (/red|green|blue/.test(key) && (value < 0 || value > 255)) {
      return;
    }
    this._super(key, value);
  }
});

function queryCustomColorize() {
  return Array.from(widgetStore.keys());
}
window.queryCustomColorize = queryCustomColorize;
window.getWidget = id => widgetStore.get(document.getElementById(id));

// Initialize 3 widgets in 3 distinct ways matching source demo
new Colorize(document.getElementById("my-widget1"));
new Colorize(document.getElementById("my-widget2"), { red: 60, blue: 60 });
new Colorize(document.getElementById("my-widget3"), {
  green: 128,
  random(event, ui) {
    return ui.green > 128;
  }
});

document.getElementById("disable").addEventListener("click", () => {
  const all = queryCustomColorize().map(el => widgetStore.get(el));
  if (all[0].option("disabled")) {
    all.forEach(w => w.enable());
  } else {
    all.forEach(w => w.disable());
  }
});

document.getElementById("black").addEventListener("click", () => {
  queryCustomColorize().forEach(el => {
    widgetStore.get(el).option({ red: 0, green: 0, blue: 0 });
  });
});
</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)
        try:
            page = browser.new_page(viewport={"width": 800, "height": 400})
            page.set_content(HTML)

            # Case 1: 3 initialization modes & initial colors + change events
            r1 = page.evaluate("""() => ({
                colors: ['my-widget1', 'my-widget2', 'my-widget3'].map(id => getComputedStyle(document.getElementById(id)).backgroundColor),
                changerButtons: document.querySelectorAll('.custom-colorize-changer').length,
                initialChangeCounts: Object.assign({}, window.__changeCounts),
                selectorCount: window.queryCustomColorize().length
            })""")
            exp1 = {
                "colors": ["rgb(255, 0, 0)", "rgb(60, 0, 60)", "rgb(255, 128, 0)"],
                "changerButtons": 3,
                "initialChangeCounts": {"my-widget1": 1, "my-widget2": 1, "my-widget3": 1},
                "selectorCount": 3,
            }
            cases.append(dict(name="three_init_modes_and_initial_colors", expected=exp1, actual=r1, passed=(r1 == exp1)))

            # Case 2: random() method & cancelable random callback (ui.green > 128)
            page.evaluate("""() => {
                window.__nextColorsQueue = [
                    { red: 50, green: 100, blue: 150 },
                    { red: 20, green: 80, blue: 40 },
                    { red: 10, green: 200, blue: 30 }
                ];
            }""")
            page.locator("#my-widget1 .custom-colorize-changer").click()
            w1_after = page.evaluate("() => getComputedStyle(document.getElementById('my-widget1')).backgroundColor")
            page.locator("#my-widget3 .custom-colorize-changer").click()
            w3_vetoed = page.evaluate("() => getComputedStyle(document.getElementById('my-widget3')).backgroundColor")
            page.locator("#my-widget3 .custom-colorize-changer").click()
            w3_accepted = page.evaluate("() => getComputedStyle(document.getElementById('my-widget3')).backgroundColor")

            r2 = {"w1Random": w1_after, "w3VetoedLowGreen": w3_vetoed, "w3AcceptedHighGreen": w3_accepted}
            exp2 = {
                "w1Random": "rgb(50, 100, 150)",
                "w3VetoedLowGreen": "rgb(255, 128, 0)",
                "w3AcceptedHighGreen": "rgb(10, 200, 30)",
            }
            cases.append(dict(name="random_method_and_cancelable_callback", expected=exp2, actual=r2, passed=(r2 == exp2)))

            # Case 3: Custom selector :custom-colorize disable/enable & batch black option
            page.click("#disable")
            page.evaluate("() => { window.__nextColorsQueue = [{ red: 1, green: 2, blue: 3 }]; }")
            page.locator("#my-widget1 .custom-colorize-changer").click()
            while_disabled = page.evaluate("""() => ({
                disabledFlag: window.getWidget('my-widget1').option('disabled'),
                colorUnchangedWhileDisabled: getComputedStyle(document.getElementById('my-widget1')).backgroundColor
            })""")
            page.click("#disable")
            enabled_again = page.evaluate("() => window.getWidget('my-widget1').option('disabled')")
            page.click("#black")
            all_black = page.evaluate("() => ['my-widget1', 'my-widget2', 'my-widget3'].map(id => getComputedStyle(document.getElementById(id)).backgroundColor)")

            r3 = {
                "disabledFlag": while_disabled["disabledFlag"],
                "colorUnchangedWhileDisabled": while_disabled["colorUnchangedWhileDisabled"],
                "disabledAfterToggleBack": enabled_again,
                "allBlackColors": all_black,
            }
            exp3 = {
                "disabledFlag": True,
                "colorUnchangedWhileDisabled": "rgb(50, 100, 150)",
                "disabledAfterToggleBack": False,
                "allBlackColors": ["rgb(0, 0, 0)", "rgb(0, 0, 0)", "rgb(0, 0, 0)"],
            }
            cases.append(dict(name="custom_selector_disable_enable_and_black_batch", expected=exp3, actual=r3, passed=(r3 == exp3)))

            # Case 4: _setOption 0..255 validation guard & _destroy cleanup
            r4 = page.evaluate("""() => {
                const w1 = window.getWidget('my-widget1');
                w1.option('red', 300);
                w1.option('green', -10);
                const afterInvalid = getComputedStyle(document.getElementById('my-widget1')).backgroundColor;
                w1.option({ red: 120, green: 180, blue: 240 });
                const afterValid = getComputedStyle(document.getElementById('my-widget1')).backgroundColor;
                w1.destroy();
                const el1 = document.getElementById('my-widget1');
                return {
                    afterInvalid,
                    afterValid,
                    hasClassAfterDestroy: el1.classList.contains('custom-colorize'),
                    hasChangerAfterDestroy: el1.querySelector('.custom-colorize-changer') !== null,
                    bgAfterDestroy: getComputedStyle(el1).backgroundColor,
                    remainingSelectorCount: window.queryCustomColorize().length
                };
            }""")
            exp4 = {
                "afterInvalid": "rgb(0, 0, 0)",
                "afterValid": "rgb(120, 180, 240)",
                "hasClassAfterDestroy": False,
                "hasChangerAfterDestroy": False,
                "bgAfterDestroy": "rgba(0, 0, 0, 0)",
                "remainingSelectorCount": 2,
            }
            cases.append(dict(name="setOption_validation_and_destroy_cleanup", expected=exp4, actual=r4, passed=(r4 == exp4)))
        finally:
            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/jqueryui-example-widget-lab/explore-example-widget.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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