"""Offline Playwright Chromium lab for jQuery UI Ch 06 (work)."""
import json
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
PROGRESSBAR_HTML = """<!DOCTYPE html><html><head><style>
.ui-progressbar { height: 24px; border: 1px solid #aaa; background: #fff; overflow: hidden; }
.ui-progressbar-value { height: 100%; background: #cccccc; width: 0%; }
.ui-state-disabled { opacity: 0.35; }
.almost-done .ui-progressbar-value { background: #4caf50; }
</style></head><body>
<div id="elem"></div>
<div id="wrapped">Dialog Body</div>
<script>
const instances = new WeakMap();
function makeWrapper(el) {
const api = {
0: el,
length: 1,
addClass(cls) { el.classList.add(cls); return api; },
hasClass(cls) { return el.classList.contains(cls); },
bind(evt, fn) { el.addEventListener(evt, fn); return api; },
empty() {
[...el.querySelectorAll('*')].forEach(c => {
if (instances.has(c)) makeWrapper(c).progressbar('destroy');
});
el.innerHTML = '';
return api;
},
remove() {
if (instances.has(el)) api.progressbar('destroy');
el.remove();
return api;
},
progressbar(arg1, arg2, arg3) {
if (typeof arg1 === 'string') {
const inst = instances.get(el);
if (!inst) throw new Error('cannot call methods on progressbar prior to initialization');
if (arg1 === 'value') {
if (arg2 === undefined) return inst.options.value;
inst.setValue(arg2);
return api;
}
if (arg1 === 'option') {
if (typeof arg2 === 'object' && arg2 !== null) {
for (const [k, v] of Object.entries(arg2)) inst.setOption(k, v);
return api;
}
if (arg3 === undefined) return inst.options[arg2];
inst.setOption(arg2, arg3);
return api;
}
if (arg1 === 'disable') { inst.setOption('disabled', true); return api; }
if (arg1 === 'enable') { inst.setOption('disabled', false); return api; }
if (arg1 === 'widget') { return api; }
if (arg1 === 'destroy') {
el.classList.remove('ui-progressbar', 'ui-widget', 'ui-widget-content', 'ui-state-disabled');
el.removeAttribute('role');
el.removeAttribute('aria-valuemin');
el.removeAttribute('aria-valuemax');
el.removeAttribute('aria-valuenow');
el.innerHTML = '';
instances.delete(el);
return api;
}
throw new Error('no such method: ' + arg1);
}
// Initialize or re-configure
let inst = instances.get(el);
const opts = Object.assign({ value: 0, max: 100, disabled: false, create: null, change: null }, arg1 || {});
if (!inst) {
const valDiv = document.createElement('div');
valDiv.className = 'ui-progressbar-value ui-widget-header';
el.innerHTML = '';
el.appendChild(valDiv);
el.classList.add('ui-progressbar', 'ui-widget', 'ui-widget-content');
el.setAttribute('role', 'progressbar');
el.setAttribute('aria-valuemin', '0');
inst = {
options: opts,
valDiv,
sync() {
const pct = Math.min(100, Math.max(0, (inst.options.value / inst.options.max) * 100));
valDiv.style.width = pct + '%';
el.setAttribute('aria-valuemax', String(inst.options.max));
el.setAttribute('aria-valuenow', String(inst.options.value));
el.classList.toggle('ui-state-disabled', Boolean(inst.options.disabled));
},
trigger(type) {
const cb = inst.options[type];
if (typeof cb === 'function') cb.call(el, { type: 'progressbar' + type });
el.dispatchEvent(new CustomEvent('progressbar' + type, { detail: { value: inst.options.value } }));
},
setValue(v) {
const prev = inst.options.value;
inst.options.value = Math.min(inst.options.max, Math.max(0, v));
inst.sync();
if (inst.options.value !== prev) inst.trigger('change');
},
setOption(k, v) {
if (k === 'value') { inst.setValue(v); return; }
inst.options[k] = v;
inst.sync();
}
};
instances.set(el, inst);
inst.sync();
inst.trigger('create');
} else {
for (const [k, v] of Object.entries(arg1 || {})) inst.setOption(k, v);
}
return api;
}
};
return api;
}
window.$ = (sel) => makeWrapper(typeof sel === 'string' ? document.querySelector(sel) : sel);
</script></body></html>"""
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 960, "height": 640})
# Case 1: Install (default & options), value getter/setter, chaining
page.set_content(PROGRESSBAR_HTML)
act1 = page.evaluate("""() => {
$( "#elem" ).progressbar();
const defVal = $( "#elem" ).progressbar( "value" );
$( "#elem" ).progressbar( "destroy" );
$( "#elem" ).progressbar({ value: 20 });
const init20 = $( "#elem" ).progressbar( "value" );
$( "#elem" ).progressbar( "value", 40 );
const after40 = document.querySelector('#elem .ui-progressbar-value').style.width;
$( "#elem" ).progressbar( "value", 90 ).addClass( "almost-done" );
return {
default_value: defVal,
init_option_20: init20,
after_set_40_width: after40,
chained_value: $( "#elem" ).progressbar( "value" ),
chained_width: document.querySelector('#elem .ui-progressbar-value').style.width,
has_almost_done: document.getElementById('elem').classList.contains('almost-done')
};
}""")
exp1 = {
"default_value": 0,
"init_option_20": 20,
"after_set_40_width": "40%",
"chained_value": 90,
"chained_width": "90%",
"has_almost_done": True,
}
cases.append({
"name": "progressbar_install_and_value_chaining",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
})
# Case 2: Common method - option (set, get, object multi-set)
page.set_content(PROGRESSBAR_HTML)
act2 = page.evaluate("""() => {
$( "#elem" ).progressbar();
$( "#elem" ).progressbar( "option", "value", 30 );
const val30 = $( "#elem" ).progressbar( "option", "value" );
$( "#elem" ).progressbar( "option", { value: 100, disabled: true } );
return {
after_option_30: val30,
batch_value: $( "#elem" ).progressbar( "option", "value" ),
batch_disabled: $( "#elem" ).progressbar( "option", "disabled" ),
aria_valuenow: document.getElementById('elem').getAttribute('aria-valuenow'),
has_disabled_cls: document.getElementById('elem').classList.contains('ui-state-disabled')
};
}""")
exp2 = {
"after_option_30": 30,
"batch_value": 100,
"batch_disabled": True,
"aria_valuenow": "100",
"has_disabled_cls": True,
}
cases.append({
"name": "progressbar_option_method",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
})
# Case 3: Common methods - disable & enable
page.set_content(PROGRESSBAR_HTML)
act3 = page.evaluate("""() => {
$( "#elem" ).progressbar({ value: 50 });
$( "#elem" ).progressbar( "disable" );
const dis = {
opt: $( "#elem" ).progressbar( "option", "disabled" ),
cls: document.getElementById('elem').classList.contains('ui-state-disabled'),
opacity: getComputedStyle(document.getElementById('elem')).opacity
};
$( "#elem" ).progressbar( "enable" );
const ena = {
opt: $( "#elem" ).progressbar( "option", "disabled" ),
cls: document.getElementById('elem').classList.contains('ui-state-disabled'),
opacity: getComputedStyle(document.getElementById('elem')).opacity
};
return { disabled: dis, enabled: ena };
}""")
exp3 = {
"disabled": {"opt": True, "cls": True, "opacity": "0.35"},
"enabled": {"opt": False, "cls": False, "opacity": "1"},
}
cases.append({
"name": "progressbar_disable_and_enable",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
})
# Case 4: Common methods - widget & destroy (plus remove/empty auto-teardown)
page.set_content(PROGRESSBAR_HTML)
act4 = page.evaluate("""() => {
$( "#elem" ).progressbar({ value: 25 });
const w = $( "#elem" ).progressbar( "widget" )[0];
const sameEl = (w === document.getElementById('elem'));
$( "#elem" ).progressbar( "destroy" );
const classesAfterDestroy = [...document.getElementById('elem').classList];
let errAfterDestroy = '';
try { $( "#elem" ).progressbar( "value" ); } catch (e) { errAfterDestroy = e.message; }
// Verify auto-destroy on container empty()
const host = document.createElement('div');
const child = document.createElement('div');
host.appendChild(child);
document.body.appendChild(host);
$(child).progressbar({ value: 10 });
$(host).empty();
let errAfterEmpty = '';
try { $(child).progressbar( "value" ); } catch (e) { errAfterEmpty = e.message; }
return {
widget_returns_original_elem: sameEl,
classes_after_destroy: classesAfterDestroy,
method_after_destroy_blocked: errAfterDestroy.includes('prior to initialization'),
method_after_empty_blocked: errAfterEmpty.includes('prior to initialization')
};
}""")
exp4 = {
"widget_returns_original_elem": True,
"classes_after_destroy": [],
"method_after_destroy_blocked": True,
"method_after_empty_blocked": True,
}
cases.append({
"name": "progressbar_destroy_and_widget",
"expected": exp4,
"actual": act4,
"passed": act4 == exp4,
})
# Case 5: Events - create common event, bind("progressbarchange") & option change callback
page.set_content(PROGRESSBAR_HTML)
act5 = page.evaluate("""() => {
const log = [];
$( "#elem" ).bind( "progressbarchange", function(e) {
log.push( "bind:" + e.detail.value );
});
$( "#elem" ).progressbar({
value: 10,
create: function() { log.push( "create" ); },
change: function() { log.push( "option_change:" + $( "#elem" ).progressbar( "value" ) ); }
});
$( "#elem" ).progressbar( "value", 65 );
$( "#elem" ).progressbar( "value", 65 ); // unchanged value should not fire change
return { events: log };
}""")
exp5 = {"events": ["create", "option_change:65", "bind:65"]}
cases.append({
"name": "progressbar_events_create_and_change",
"expected": exp5,
"actual": act5,
"passed": act5 == exp5,
})
browser.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/jqueryui-work-lab/explore-work.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-work.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a959.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip