"""Offline Chromium lab for jQuery UI Ch12: Extending Widgets with the Widget Factory."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html>
<head><meta charset="utf-8"><title>Widget Extend Lab</title></head>
<body>
<div id="host"></div>
<script>
(function(global) {
const dataStore = new WeakMap();
const allTracked = new Set();
function getDataMap(el) {
if (!dataStore.has(el)) dataStore.set(el, {});
return dataStore.get(el);
}
function $(sel) {
if (sel && sel._isJQ) return sel;
let els = [];
if (typeof sel === "string") {
if (sel.trim().startsWith("<")) {
const tmp = document.createElement("div");
tmp.innerHTML = sel.trim();
els = Array.from(tmp.children);
} else if (sel.startsWith(":data(") && sel.endsWith(")")) {
const key = sel.slice(6, -1);
els = Array.from(allTracked).filter(el => getDataMap(el)[key] !== undefined);
} else {
els = Array.from(document.querySelectorAll(sel));
}
} else if (sel instanceof Element) {
els = [sel];
} else if (Array.isArray(sel)) {
els = sel;
}
return Object.assign(Object.create($.fn), { _isJQ: true, length: els.length, els });
}
$.fn = {
each(fn) { this.els.forEach((el, i) => fn.call(el, i, el)); return this; },
appendTo(target) {
const t = typeof target === "string" ? document.querySelector(target) : target;
return this.each(function() { t.appendChild(this); });
},
css(prop, val) {
if (val === undefined) return this.els[0] ? getComputedStyle(this.els[0])[prop] : "";
return this.each(function() { this.style[prop] = val; });
},
data(key, val) {
if (!this.els[0]) return undefined;
const map = getDataMap(this.els[0]);
if (val === undefined) return map[key];
allTracked.add(this.els[0]);
map[key] = val;
return this;
}
};
$.extend = function(target, ...sources) {
const out = target || {};
for (const src of sources) {
if (!src) continue;
for (const k of Object.keys(src)) out[k] = src[k];
}
return out;
};
$.Widget = function() {};
$.Widget.prototype = {
_createWidget(options, element) {
this.element = $(element);
this.options = $.extend({}, this.options, options);
this.element.data(this.widgetFullName, this);
this._create();
this._init();
},
_create() {},
_init() {},
option(key, value) {
if (typeof key === "string") {
if (value === undefined) return this.options[key];
this._setOption(key, value);
} else if (key) {
for (const k of Object.keys(key)) this._setOption(k, key[k]);
}
return this;
},
_setOption(key, value) {
this.options[key] = value;
return this;
}
};
$.widget = function(name, base, prototype) {
if (!prototype) {
prototype = base;
base = $.Widget;
}
const [namespace, widgetName] = name.split(".");
const fullName = namespace + "-" + widgetName;
$[namespace] = $[namespace] || {};
const baseProto = base.prototype;
const proxiedProto = {};
for (const prop of Object.keys(prototype)) {
const value = prototype[prop];
if (typeof value === "function") {
proxiedProto[prop] = (function(key, fn) {
const _super = function(...args) {
return baseProto[key].apply(this, args);
};
const _superApply = function(args) {
return baseProto[key].apply(this, args);
};
return function(...args) {
const prevSuper = this._super;
const prevSuperApply = this._superApply;
this._super = _super;
this._superApply = _superApply;
try {
return fn.apply(this, args);
} finally {
this._super = prevSuper;
this._superApply = prevSuperApply;
}
};
})(prop, value);
} else {
proxiedProto[prop] = value;
}
}
function Ctor(options, element) {
if (!(this instanceof Ctor)) return new Ctor(options, element);
if (arguments.length) this._createWidget(options, element);
}
Ctor.prototype = Object.assign(Object.create(baseProto), {
constructor: Ctor,
widgetName,
namespace,
widgetFullName: fullName,
options: $.extend({}, baseProto.options, prototype.options)
}, proxiedProto);
$[namespace][widgetName] = Ctor;
$.fn[widgetName] = function(options, ...args) {
if (typeof options === "string") {
let returnValue = this;
this.each(function() {
const inst = $(this).data(fullName);
if (!inst) throw new Error("cannot call methods on " + widgetName + " prior to initialization");
if (typeof inst[options] !== "function" || options.startsWith("_")) {
throw new Error("no such method '" + options + "'");
}
const res = inst[options](...args);
if (res !== inst && res !== undefined) returnValue = res;
});
return returnValue;
}
return this.each(function() {
const inst = $(this).data(fullName);
if (inst) inst.option(options || {});
else new Ctor(options, this);
});
};
};
global.$ = global.jQuery = $;
})(window);
// Base $.ui.dialog
$.widget("ui.dialog", {
options: { autoOpen: true, title: "Dialog", width: 300 },
_create() {
this._isOpen = false;
this.element.css("display", "none");
},
_init() {
if (this.options.autoOpen) this.open();
},
open() {
this._isOpen = true;
this.element.css("display", "block");
},
close() {
this._isOpen = false;
this.element.css("display", "none");
},
isOpen() {
return this._isOpen;
}
});
</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()
page.set_content(HTML)
r1 = page.evaluate("""() => {
$.widget("custom.superDialog", $.ui.dialog, {
red() {
this.element.css("color", "red");
}
});
const el = $("<div>I am red</div>").appendTo("#host").superDialog().superDialog("red");
return {
color: el.css("color"),
isOpen: el.superDialog("isOpen"),
isWidgetInstance: el.data("custom-superDialog") instanceof $.custom.superDialog
};
}""")
exp1 = {"color": "rgb(255, 0, 0)", "isOpen": True, "isWidgetInstance": True}
cases.append(dict(name="extend_base_widget_and_custom_method", expected=exp1, actual=r1, passed=(r1 == exp1)))
r2 = page.evaluate("""() => {
const logs = [];
$.widget("custom.silentDialog", $.ui.dialog, {
open() { logs.push("silent-open"); }
});
const silent = $("<div>S</div>").appendTo("#host").silentDialog();
const silentIsOpen = silent.silentDialog("isOpen");
const silentDisplay = silent.css("display");
const setOptionCalls = [];
$.widget("custom.superDialog", $.ui.dialog, {
open() {
logs.push("super-open");
return this._super();
},
_setOption(key, value) {
setOptionCalls.push(key + ":" + value);
this._super(key, value);
this._superApply(arguments);
}
});
const dlg = $("<div>OK</div>").appendTo("#host").superDialog();
dlg.superDialog("option", "title", "Updated");
dlg.superDialog("option", "width", 420);
return {
logs,
silentIsOpen,
silentDisplay,
superIsOpen: dlg.superDialog("isOpen"),
superDisplay: dlg.css("display"),
title: dlg.superDialog("option", "title"),
width: dlg.superDialog("option", "width"),
setOptionCalls
};
}""")
exp2 = {
"logs": ["silent-open", "super-open"],
"silentIsOpen": False,
"silentDisplay": "none",
"superIsOpen": True,
"superDisplay": "block",
"title": "Updated",
"width": 420,
"setOptionCalls": ["title:Updated", "width:420"],
}
cases.append(dict(name="override_vs_super_and_super_apply", expected=exp2, actual=r2, passed=(r2 == exp2)))
r3 = page.evaluate("""() => {
const logs = [];
$.widget("ui.dialog", $.ui.dialog, {
open() {
logs.push("redefined-open");
return this._super();
}
});
const d1 = $("<div>A</div>").appendTo("#host").dialog();
const d2 = $("<div>B</div>").appendTo("#host").dialog();
return {
logCount: logs.length,
logs,
bothOpen: d1.dialog("isOpen") && d2.dialog("isOpen")
};
}""")
exp3 = {"logCount": 2, "logs": ["redefined-open", "redefined-open"], "bothOpen": True}
cases.append(dict(name="redefine_existing_widget", expected=exp3, actual=r3, passed=(r3 == exp3)))
r4 = page.evaluate("""() => {
$.widget("custom.polyDialog", $.ui.dialog, {});
const el = $("<div>P</div>").appendTo("#host").polyDialog();
el.polyDialog("close");
const closedByChild = !el.polyDialog("isOpen");
let parentError = "";
try {
el.dialog("close");
} catch (e) {
parentError = e.message;
}
return { closedByChild, parentError };
}""")
exp4 = {
"closedByChild": True,
"parentError": "cannot call methods on dialog prior to initialization",
}
cases.append(dict(name="widget_polymorphism_isolation", expected=exp4, actual=r4, passed=(r4 == exp4)))
r5 = page.evaluate("""() => {
const customLogs = [];
const dA = $("<div>InstA</div>").appendTo("#host").dialog();
const instA = dA.data("ui-dialog");
instA.close = function() {
customLogs.push("custom-close");
};
const dB = $("<div>InstB</div>").appendTo("#host").dialog();
$(":data(ui-dialog)").dialog("close");
return {
customCloseCount: customLogs.length,
dAStillOpenBecauseCustomSkippedSuper: dA.dialog("isOpen"),
dBClosedByPrototype: !dB.dialog("isOpen")
};
}""")
exp5 = {
"customCloseCount": 1,
"dAStillOpenBecauseCustomSkippedSuper": True,
"dBClosedByPrototype": True,
}
cases.append(dict(name="single_instance_customization", expected=exp5, actual=r5, passed=(r5 == exp5)))
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-widget-extend-lab/explore-widget-extend.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-widget-extend.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a954.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip