"""Offline Chromium lab for jQuery UI Ch15: How to Use the Widget Factory."""
import json
from playwright.sync_api import sync_playwright
HTML = """<!doctype html>
<html>
<head><meta charset="utf-8"><title>How to Use Widget Factory Lab</title></head>
<body>
<div id="multi-a" class="multi"></div>
<div id="multi-b" class="multi"></div>
<script>
(function(global) {
const dataStore = new WeakMap();
const listenerStore = new WeakMap();
function getDataMap(el) {
if (!dataStore.has(el)) dataStore.set(el, {});
return dataStore.get(el);
}
function getListeners(el) {
if (!listenerStore.has(el)) listenerStore.set(el, []);
return listenerStore.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 {
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); });
},
addClass(cls) { return this.each(function() { this.classList.add(...cls.split(/\\s+/).filter(Boolean)); }); },
removeClass(cls) { return this.each(function() { this.classList.remove(...cls.split(/\\s+/).filter(Boolean)); }); },
hasClass(cls) { return this.els[0] ? this.els[0].classList.contains(cls) : false; },
text(val) {
if (val === undefined) return this.els[0] ? this.els[0].textContent : "";
return this.each(function() { this.textContent = String(val); });
},
data(key, val) {
if (!this.els[0]) return undefined;
const map = getDataMap(this.els[0]);
if (val === undefined) return map[key];
map[key] = val;
return this;
},
removeData(key) { return this.each(function() { delete getDataMap(this)[key]; }); },
bind(eventType, handler) {
return this.each(function() { getListeners(this).push({ eventType, handler }); });
},
unbind(nsSuffix) {
return this.each(function() {
const list = getListeners(this);
for (let i = list.length - 1; i >= 0; i--) {
if (!nsSuffix || list[i].eventType.endsWith(nsSuffix)) list.splice(i, 1);
}
});
},
trigger(evt, data) {
this.each(function() {
for (const item of getListeners(this)) {
if (item.eventType === evt.type) {
const ret = item.handler.call(this, evt, data);
if (ret === false) evt.preventDefault();
}
}
});
return this;
}
};
$.extend = (t, ...ss) => Object.assign(t || {}, ...ss);
$.Widget = function() {};
$.Widget.prototype = {
_createWidget(options, element) {
this.element = $(element);
this.options = $.extend({}, this.options, options);
this.element.data(this.widgetFullName, this);
this.element.data(this.widgetName, this);
this._create();
},
_create() {},
option(key, value) {
if (key === undefined) return $.extend({}, this.options);
if (typeof key === "string") {
if (value === undefined) return this.options[key];
this._setOptions({ [key]: value });
} else {
this._setOptions(key);
}
return this;
},
_setOptions(options) {
for (const k of Object.keys(options)) this._setOption(k, options[k]);
return this;
},
_setOption(key, value) {
this.options[key] = value;
return this;
},
_trigger(type, event, data) {
const callback = this.options[type];
let prevented = false;
const evt = {
type: (this.widgetEventPrefix + type).toLowerCase(),
originalEvent: event || null,
preventDefault() { prevented = true; },
isDefaultPrevented() { return prevented; }
};
this.element.trigger(evt, data);
let cbRet;
if (typeof callback === "function") {
cbRet = callback.call(this.element.els[0], evt, data);
if (cbRet === false) evt.preventDefault();
}
return !(cbRet === false || evt.isDefaultPrevented());
},
destroy() {
this._destroy();
this.element.removeData(this.widgetFullName);
this.element.removeData(this.widgetName);
this.element.unbind("." + this.widgetName);
},
_destroy() {}
};
$.widget = function(name, base, prototype) {
if (!prototype) { prototype = base; base = $.Widget; }
const parts = name.split(".");
if (parts.length !== 2 || !parts[0] || !parts[1]) {
throw new Error("invalid widget name: single-level namespace required");
}
const [namespace, widgetName] = parts;
const fullName = namespace + "-" + widgetName;
$[namespace] = $[namespace] || {};
const baseProto = base.prototype;
const proxied = {};
for (const prop of Object.keys(prototype)) {
const val = prototype[prop];
if (typeof val === "function") {
proxied[prop] = (function(k, fn) {
return function(...args) {
const pS = this._super, pSA = this._superApply;
this._super = (...a) => baseProto[k].apply(this, a);
this._superApply = (a) => baseProto[k].apply(this, a);
try { return fn.apply(this, args); }
finally { this._super = pS; this._superApply = pSA; }
};
})(prop, val);
} else {
proxied[prop] = val;
}
}
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,
widgetEventPrefix: widgetName,
options: $.extend({}, baseProto.options, prototype.options)
}, proxied);
$[namespace][widgetName] = Ctor;
$.fn[widgetName] = function(options, ...args) {
if (typeof options === "string") {
let returnValue = this;
let hasReturn = false;
this.each(function() {
const inst = $(this).data(fullName);
if (!inst) throw new Error("cannot call methods prior to initialization");
if (options.startsWith("_") || typeof inst[options] !== "function") {
throw new Error("no such method '" + options + "'");
}
const res = inst[options](...args);
if (!hasReturn && res !== inst && res !== undefined) {
returnValue = res;
hasReturn = true;
}
});
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);
$.widget("custom.progressbar", {
options: { value: 0 },
_create() {
this.options.value = this._constrain(this.options.value);
this.element.addClass("progressbar");
this.refresh();
},
value(val) {
if (val === undefined) return this.options.value;
this.options.value = this._constrain(val);
this.refresh();
},
_setOption(key, value) {
if (key === "value") value = this._constrain(value);
this._super(key, value);
},
_setOptions(options) {
this._super(options);
this.refresh();
},
refresh() {
const progress = this.options.value + "%";
this.element.text(progress);
if (this.options.value === 100) {
this._lastTriggerAllowed = this._trigger("complete", null, { value: 100 });
}
},
_constrain(val) {
if (val > 100) return 100;
if (val < 0) return 0;
return val;
},
_destroy() {
this.element.removeClass("progressbar").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():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
page.set_content(HTML)
r1 = page.evaluate("""() => {
let nestedErr = "";
try { $.widget("very.custom.progressbar", {}); } catch (e) { nestedErr = e.message; }
$(".multi").progressbar();
const bar20 = $("<div></div>").appendTo("body").progressbar({ value: 20 });
return {
nestedNamespaceRejected: nestedErr.includes("single-level namespace"),
multiIsolated: $("#multi-a").data("custom-progressbar") !== $("#multi-b").data("custom-progressbar"),
defaultText: $("#multi-a").text(),
customText: bar20.text(),
hasClass: bar20.hasClass("progressbar")
};
}""")
exp1 = {
"nestedNamespaceRejected": True,
"multiIsolated": True,
"defaultText": "0%",
"customText": "20%",
"hasClass": True,
}
cases.append(dict(name="create_namespace_and_defaults", expected=exp1, actual=r1, passed=(r1 == exp1)))
r2 = page.evaluate("""() => {
const bar = $("<div></div>").appendTo("body").progressbar({ value: 20 });
const v1 = bar.progressbar("value");
bar.progressbar("value", 50);
const v2 = bar.progressbar("value");
bar.progressbar("value", 150);
const clampedHigh = bar.progressbar("value");
bar.progressbar("value", -15);
const clampedLow = bar.progressbar("value");
let privateErr = "";
try { bar.progressbar("_constrain", 50); } catch (e) { privateErr = e.message; }
return { v1, v2, clampedHigh, clampedLow, privateBlocked: privateErr.includes("no such method") };
}""")
exp2 = {"v1": 20, "v2": 50, "clampedHigh": 100, "clampedLow": 0, "privateBlocked": True}
cases.append(dict(name="public_private_methods_and_constrain", expected=exp2, actual=r2, passed=(r2 == exp2)))
r3 = page.evaluate("""() => {
const bar = $("<div></div>").appendTo("body").progressbar({ value: 10 });
bar.progressbar("option", "value", 120);
const afterHigh = bar.progressbar("option", "value");
const textHigh = bar.text();
bar.progressbar("option", { value: 45 });
return { afterHigh, textHigh, afterHash: bar.progressbar("option", "value"), textHash: bar.text() };
}""")
exp3 = {"afterHigh": 100, "textHigh": "100%", "afterHash": 45, "textHash": "45%"}
cases.append(dict(name="option_setOption_setOptions_refresh", expected=exp3, actual=r3, passed=(r3 == exp3)))
r4 = page.evaluate("""() => {
const log = [];
const bar = $("<div></div>").appendTo("body").progressbar({
complete(evt, data) { log.push("cb:" + evt.type + ":" + data.value); }
}).bind("progressbarcomplete", function(evt, data) {
log.push("ev:" + evt.type + ":" + data.value);
});
bar.progressbar("option", "value", 100);
const allowedNormal = bar.data("custom-progressbar")._lastTriggerAllowed;
const barCancel = $("<div></div>").appendTo("body").progressbar({
complete(evt) { evt.preventDefault(); }
});
barCancel.progressbar("option", "value", 100);
const allowedCanceled = barCancel.data("custom-progressbar")._lastTriggerAllowed;
return { log, allowedNormal, allowedCanceled };
}""")
exp4 = {
"log": ["ev:progressbarcomplete:100", "cb:progressbarcomplete:100"],
"allowedNormal": True,
"allowedCanceled": False,
}
cases.append(dict(name="trigger_callback_event_and_cancel", expected=exp4, actual=r4, passed=(r4 == exp4)))
r5 = page.evaluate("""() => {
const el = $("<div></div>").appendTo("body").progressbar();
const inst = el.data("progressbar");
inst.option("value", 50);
const valAfterDirect = inst.options.value;
const directCtor = $.custom.progressbar({}, $("<div></div>").appendTo("body"));
const ctorDefaultVal = directCtor.options.value;
$.custom.progressbar.prototype.reset = function() {
this._setOption("value", 0);
this.refresh();
};
el.progressbar("reset");
const afterReset = el.progressbar("value");
el.progressbar("destroy");
return {
valAfterDirect,
ctorDefaultVal,
afterReset,
classAfterDestroy: el.hasClass("progressbar"),
textAfterDestroy: el.text(),
dataAfterDestroy: el.data("custom-progressbar") === undefined
};
}""")
exp5 = {
"valAfterDirect": 50,
"ctorDefaultVal": 0,
"afterReset": 0,
"classAfterDestroy": False,
"textAfterDestroy": "",
"dataAfterDestroy": True,
}
cases.append(dict(name="internals_direct_ctor_proto_extend_destroy", 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-factory-how-lab/explore-widget-factory-how.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-widget-factory-how.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a956.zip