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

运行 WAI-ARIA 渐进增强、按需依赖解析与主题/中文语言包切换离线实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-intro.py
explore-intro.py195 行
"""Offline Playwright Chromium lab for jQuery UI Ch 02 (intro)."""
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")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 960, "height": 640})

        # Case 1: WAI-ARIA progressive enhancement
        page.set_content("""<!DOCTYPE html><html><head><style>
.ui-tabs-panel[aria-hidden="true"] { display: none; }
.ui-state-active { font-weight: 700; }
</style></head><body>
<div id="tabs" class="ui-tabs ui-widget">
  <ul role="tablist">
    <li role="presentation"><a id="t1" role="tab" aria-controls="p1" aria-selected="true" class="ui-state-default ui-state-active" href="#p1">Tab 1</a></li>
    <li role="presentation"><a id="t2" role="tab" aria-controls="p2" aria-selected="false" class="ui-state-default" href="#p2">Tab 2</a></li>
  </ul>
  <div id="p1" role="tabpanel" aria-labelledby="t1" aria-hidden="false" class="ui-tabs-panel">Panel 1</div>
  <div id="p2" role="tabpanel" aria-labelledby="t2" aria-hidden="true" class="ui-tabs-panel">Panel 2</div>
</div>
<script>
const tabs = [...document.querySelectorAll('[role="tab"]')];
const panels = [...document.querySelectorAll('[role="tabpanel"]')];
tabs.forEach((tab, idx) => {
  tab.addEventListener('click', (e) => {
    e.preventDefault();
    tabs.forEach((t, i) => {
      t.setAttribute('aria-selected', String(i === idx));
      t.classList.toggle('ui-state-active', i === idx);
    });
    panels.forEach((p, i) => p.setAttribute('aria-hidden', String(i !== idx)));
  });
});
</script></body></html>""")
        page.click("#t2")
        act1 = page.evaluate("""() => ({
          t1_selected: document.getElementById('t1').getAttribute('aria-selected'),
          t2_selected: document.getElementById('t2').getAttribute('aria-selected'),
          p1_display: getComputedStyle(document.getElementById('p1')).display,
          p2_display: getComputedStyle(document.getElementById('p2')).display,
          p2_aria_hidden: document.getElementById('p2').getAttribute('aria-hidden')
        })""")
        exp1 = {
            "t1_selected": "false",
            "t2_selected": "true",
            "p1_display": "none",
            "p2_display": "block",
            "p2_aria_hidden": "false",
        }
        cases.append({
            "name": "wai_aria_progressive_enhancement",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        })

        # Case 2: Modular on-demand loading vs full bundle
        page.set_content("""<!DOCTYPE html><html><body><script>
const DEPS = {
  core: [], widget: [], mouse: ['core', 'widget'], position: [],
  draggable: ['core', 'widget', 'mouse'],
  droppable: ['core', 'widget', 'mouse', 'draggable'],
  resizable: ['core', 'widget', 'mouse'],
  accordion: ['core', 'widget'],
  datepicker: ['core'],
  dialog: ['core', 'widget', 'mouse', 'position', 'draggable', 'resizable'],
  slider: ['core', 'widget', 'mouse'],
  tabs: ['core', 'widget']
};
function resolve(selected) {
  const out = new Set();
  function visit(m) {
    if (out.has(m)) return;
    (DEPS[m] || []).forEach(visit);
    out.add(m);
  }
  selected.forEach(visit);
  return [...out].sort();
}
window.__mod = {
  total_modules: Object.keys(DEPS).length,
  datepicker_only: resolve(['datepicker']),
  dialog_deps: resolve(['dialog']),
};
</script></body></html>""")
        act2 = page.evaluate("() => window.__mod")
        exp2 = {
            "total_modules": 12,
            "datepicker_only": ["core", "datepicker"],
            "dialog_deps": ["core", "dialog", "draggable", "mouse", "position", "resizable", "widget"],
        }
        cases.append({
            "name": "modular_on_demand_loading",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        })

        # Case 3: Theme presets + i18n locale pack switching (en-US vs zh-CN)
        page.set_content("""<!DOCTYPE html><html><head><style>
.theme-smoothness .ui-widget-header { background: rgb(204, 204, 204); border-radius: 4px; }
.theme-redmond .ui-widget-header { background: rgb(92, 156, 204); border-radius: 6px; }
</style></head><body class="theme-smoothness">
<div class="ui-datepicker ui-widget">
  <div class="ui-widget-header"><span id="month">January</span></div>
  <div id="weekdays">Su,Mo,Tu,We,Th,Fr,Sa</div>
</div>
<script>
const LOCALES = {
  'en-US': { month: 'January', days: 'Su,Mo,Tu,We,Th,Fr,Sa' },
  'zh-CN': { month: '一月', days: '日,一,二,三,四,五,六' }
};
window.applyConfig = (theme, lang) => {
  document.body.className = 'theme-' + theme;
  document.getElementById('month').textContent = LOCALES[lang].month;
  document.getElementById('weekdays').textContent = LOCALES[lang].days;
};
</script></body></html>""")
        before3 = page.evaluate("""() => ({
          bg: getComputedStyle(document.querySelector('.ui-widget-header')).backgroundColor,
          radius: getComputedStyle(document.querySelector('.ui-widget-header')).borderRadius,
          month: document.getElementById('month').textContent
        })""")
        page.evaluate("() => window.applyConfig('redmond', 'zh-CN')")
        after3 = page.evaluate("""() => ({
          bg: getComputedStyle(document.querySelector('.ui-widget-header')).backgroundColor,
          radius: getComputedStyle(document.querySelector('.ui-widget-header')).borderRadius,
          month: document.getElementById('month').textContent,
          days: document.getElementById('weekdays').textContent
        })""")
        act3 = {"before": before3, "after": after3}
        exp3 = {
            "before": {"bg": "rgb(204, 204, 204)", "radius": "4px", "month": "January"},
            "after": {"bg": "rgb(92, 156, 204)", "radius": "6px", "month": "一月", "days": "日,一,二,三,四,五,六"},
        }
        cases.append({
            "name": "theme_preset_and_i18n_locale_switch",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        })

        # Case 4: Widget count & multi-widget event coordination check
        page.set_content("""<!DOCTYPE html><html><body>
<div id="slider" data-value="20"></div><div id="progress" data-value="20"></div>
<script>
const slider = document.getElementById('slider');
const progress = document.getElementById('progress');
let synced = 0;
slider.addEventListener('slidechange', (e) => {
  progress.dataset.value = String(e.detail.value);
  synced += 1;
});
slider.dataset.value = '65';
slider.dispatchEvent(new CustomEvent('slidechange', { detail: { value: 65 } }));
window.__coord = {
  slider_value: Number(slider.dataset.value),
  progress_value: Number(progress.dataset.value),
  bridge_events: synced,
  license_dual: ['MIT', 'GPL']
};
</script></body></html>""")
        act4 = page.evaluate("() => window.__coord")
        exp4 = {
            "slider_value": 65,
            "progress_value": 65,
            "bridge_events": 1,
            "license_dual": ["MIT", "GPL"],
        }
        cases.append({
            "name": "architecture_tradeoff_check",
            "expected": exp4,
            "actual": act4,
            "passed": act4 == exp4,
        })

        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-intro-lab/explore-intro.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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