"""Offline Playwright Chromium lab for jQuery UI Ch 30: Spinner."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Spinner Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 16px; }
.spin-wrap { display: inline-flex; align-items: center; gap: 4px; margin: 6px 0; }
</style>
</head>
<body>
<div class="spin-wrap">
<input id="sp-basic" type="text" value="">
<button id="sp-up">▲</button><button id="sp-down">▼</button>
</div>
<button id="btn-disable">切换禁用/启用</button>
<button id="btn-destroy">切换部件</button>
<button id="btn-set5">设置值为 5</button>
<input id="sp-currency" type="text">
<input id="sp-decimal" type="text" value="5.06">
<input id="sp-overflow" type="text" value="10">
<input id="sp-lat" type="text" value="44.797">
<input id="sp-lng" type="text" value="-93.278">
<input id="sp-time" type="text" value="08:30 PM">
<script>
const spBasicEl = document.getElementById("sp-basic");
window.basicSpinner = { active: true, disabled: false, val: null };
function syncBasic() { spBasicEl.value = window.basicSpinner.val === null ? "" : String(window.basicSpinner.val); }
function stepBasic(delta) {
if (!window.basicSpinner.active || window.basicSpinner.disabled) return;
window.basicSpinner.val = (window.basicSpinner.val ?? 0) + delta;
syncBasic();
}
document.getElementById("sp-up").addEventListener("click", () => stepBasic(1));
document.getElementById("sp-down").addEventListener("click", () => stepBasic(-1));
spBasicEl.addEventListener("keydown", e => {
if (e.key === "ArrowUp") { e.preventDefault(); stepBasic(1); }
else if (e.key === "ArrowDown") { e.preventDefault(); stepBasic(-1); }
});
document.getElementById("btn-disable").addEventListener("click", () => {
window.basicSpinner.disabled = !window.basicSpinner.disabled;
spBasicEl.disabled = window.basicSpinner.disabled;
});
document.getElementById("btn-destroy").addEventListener("click", () => {
window.basicSpinner.active = !window.basicSpinner.active;
});
document.getElementById("btn-set5").addEventListener("click", () => {
if (!window.basicSpinner.active) return;
window.basicSpinner.val = 5;
syncBasic();
});
function formatCurrency(val, culture) {
const fixed2 = val.toFixed(2);
const [intPart, decPart] = fixed2.split(".");
if (culture === "en-US") {
return "$" + intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "." + decPart;
}
if (culture === "de-DE") {
return intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ".") + "," + decPart + " €";
}
return "¥" + String(Math.round(val)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function formatDecimal(val, culture) {
const s = val.toFixed(2);
return culture === "de-DE" ? s.replace(".", ",") : s;
}
window.SpinnerLab = {
testCurrencyAndDecimal() {
let curVal = 1000;
const min = 5, max = 2500, step = 25;
curVal = Math.min(max, Math.max(min, curVal + step)); // 1025
const fmtUS = formatCurrency(curVal, "en-US");
const fmtDE = formatCurrency(curVal, "de-DE");
const fmtJP = formatCurrency(curVal, "ja-JP");
const clampedMax = Math.min(max, curVal + 2000);
const clampedMin = Math.max(min, 0);
let decVal = 5.06;
decVal = Math.round((decVal + 0.01) * 100) / 100;
const decEN = formatDecimal(decVal, "en-EN");
const decDE = formatDecimal(decVal, "de-DE");
return { curVal, fmtUS, fmtDE, fmtJP, clampedMax, clampedMin, decVal, decEN, decDE };
},
testOverflow() {
let val = 10;
function spin(delta) {
const next = val + delta;
if (next > 10) { val = -10; return val; }
if (next < -10) { val = 10; return val; }
val = next;
return val;
}
const overHigh = spin(1); // 10 -> -10
const overLow = spin(-1); // -10 -> 10
val = 0;
const normalUp = spin(1); // 0 -> 1
return { overHigh, overLow, normalUp };
},
testLatLongAndTime() {
let lat = 44.797, lng = -93.278;
const centers = [];
const syncCenter = () => centers.push([Number(lat.toFixed(3)), Number(lng.toFixed(3))]);
lat = Number((lat + 0.001).toFixed(3)); syncCenter();
lng = Number((lng + 0.001).toFixed(3)); syncCenter();
// Custom timespinner: step = 60*1000 (1 min), page = 60 (1 hour)
function parseTime(str) {
const m = str.match(/^(\d{2}):(\d{2})\s*(AM|PM)$/i);
let h = parseInt(m[1], 10) % 12;
if (m[3].toUpperCase() === "PM") h += 12;
const min = parseInt(m[2], 10);
return (h * 60 + min) * 60 * 1000;
}
function formatTime(ms, culture) {
const totalMin = ((Math.floor(ms / 60000) % 1440) + 1440) % 1440;
const h24 = Math.floor(totalMin / 60);
const min = totalMin % 60;
if (culture === "de-DE") {
return String(h24).padStart(2, "0") + ":" + String(min).padStart(2, "0");
}
const ampm = h24 >= 12 ? "PM" : "AM";
const h12 = h24 % 12 === 0 ? 12 : h24 % 12;
return String(h12).padStart(2, "0") + ":" + String(min).padStart(2, "0") + " " + ampm;
}
const stepMs = 60 * 1000;
const pageSteps = 60;
let ts = parseTime("08:30 PM");
ts += stepMs; // ArrowUp -> +1 min
const afterMinUp = formatTime(ts, "en-EN");
ts += stepMs * pageSteps; // PageUp -> +1 hour
const afterHourUp = formatTime(ts, "en-EN");
const afterDeFormat = formatTime(ts, "de-DE");
return { centers, afterMinUp, afterHourUp, afterDeFormat };
}
};
</script>
</body>
</html>
"""
def main():
cases = []
with sync_playwright() as p:
try:
browser = p.chromium.launch(headless=True)
except Exception:
browser = p.chromium.launch(headless=True, channel="chrome")
page = browser.new_page()
page.set_content(HTML_DOC)
# Case 1: Default spinner set value, button & keyboard step, disable/enable, destroy/re-init
page.click("#btn-set5")
page.click("#sp-up")
page.focus("#sp-basic")
page.keyboard.press("ArrowDown")
val_after_keys = page.input_value("#sp-basic")
page.click("#btn-disable")
page.click("#sp-up")
val_while_disabled = page.input_value("#sp-basic")
page.click("#btn-disable") # re-enable
page.click("#btn-destroy") # destroy
page.click("#sp-up")
val_while_destroyed = page.input_value("#sp-basic")
page.click("#btn-destroy") # re-init
page.click("#sp-up")
val_after_reinit = page.input_value("#sp-basic")
res1 = {
"afterSet5UpDown": val_after_keys,
"ignoredWhenDisabled": val_while_disabled,
"ignoredWhenDestroyed": val_while_destroyed,
"afterReinitUp": val_after_reinit,
}
exp1 = {
"afterSet5UpDown": "5",
"ignoredWhenDisabled": "5",
"ignoredWhenDestroyed": "5",
"afterReinitUp": "6",
}
cases.append(dict(name="spinner_default_lifecycle_and_keys", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Currency min/max/step/start/culture + decimal step=0.01 culture switch
res2 = page.evaluate("() => SpinnerLab.testCurrencyAndDecimal()")
exp2 = {
"curVal": 1025,
"fmtUS": "$1,025.00",
"fmtDE": "1.025,00 €",
"fmtJP": "¥1,025",
"clampedMax": 2500,
"clampedMin": 5,
"decVal": 5.07,
"decEN": "5.07",
"decDE": "5,07",
}
cases.append(dict(name="spinner_currency_and_decimal_culture", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Overflow spinner wrapping [-10, 10]
res3 = page.evaluate("() => SpinnerLab.testOverflow()")
exp3 = {"overHigh": -10, "overLow": 10, "normalUp": 1}
cases.append(dict(name="spinner_overflow_wrap", expected=exp3, actual=res3, passed=(res3 == exp3)))
# Case 4: Lat/Lng step=0.001 map center sync + custom timespinner step/page & culture
res4 = page.evaluate("() => SpinnerLab.testLatLongAndTime()")
exp4 = {
"centers": [[44.798, -93.278], [44.798, -93.277]],
"afterMinUp": "08:31 PM",
"afterHourUp": "09:31 PM",
"afterDeFormat": "21:31",
}
cases.append(dict(name="spinner_latlong_and_timespinner", expected=exp4, actual=res4, passed=(res4 == exp4)))
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-spinner-lab/explore-example-spinner.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-example-spinner.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a939.zip
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a916.zip