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

运行 jQuery Growl 四类消息卡片渲染、事件冒泡隔离、手动关闭与超时自动消失实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-plugin-message.py
explore-plugin-message.py194 行
"""Offline Playwright Chromium lab for jQuery Ch 36: plugin-message (jQuery Growl notifications)."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery Growl 离线实验</title>
<style>
  #growls { position: fixed; top: 10px; right: 10px; width: 280px; }
  .growl { padding: 10px 14px; margin-bottom: 8px; border-radius: 4px; color: #fff; position: relative; }
  .growl-default { background: rgb(149, 165, 166); }
  .growl-error { background: rgb(192, 57, 43); }
  .growl-notice { background: rgb(46, 204, 113); }
  .growl-warning { background: rgb(243, 156, 18); }
  .growl-close { position: absolute; right: 10px; top: 6px; cursor: pointer; }
</style>
</head>
<body>
  <div id="trigger-wrap">
    <a href="#err" class="error">Error</a>
    <a href="#not" class="notice">Notice</a>
    <a href="#warn" class="warning">Warning</a>
  </div>
  <div id="growls"></div>

  <script>
    const container = document.getElementById('growls');
    function createGrowl(style, opts) {
      const settings = Object.assign({ title: '', message: '', duration: 3200, fixed: false }, opts);
      const card = document.createElement('div');
      card.className = 'growl growl-' + style;
      card.innerHTML =
        '<div class="growl-close">×</div>' +
        '<div class="growl-title"></div>' +
        '<div class="growl-message"></div>';
      card.querySelector('.growl-title').textContent = settings.title;
      card.querySelector('.growl-message').textContent = settings.message;
      container.appendChild(card);

      let timer = null;
      const dismiss = () => {
        if (timer) clearTimeout(timer);
        if (card.parentNode) card.parentNode.removeChild(card);
      };
      const schedule = () => {
        if (!settings.fixed && settings.duration > 0) {
          timer = setTimeout(dismiss, settings.duration);
        }
      };
      card.querySelector('.growl-close').addEventListener('click', dismiss);
      card.addEventListener('mouseenter', () => { if (timer) { clearTimeout(timer); timer = null; } });
      card.addEventListener('mouseleave', () => { schedule(); });
      schedule();
      return card;
    }

    function growl(opts) { return createGrowl('default', opts); }
    growl.error = (opts) => createGrowl('error', opts);
    growl.notice = (opts) => createGrowl('notice', opts);
    growl.warning = (opts) => createGrowl('warning', opts);
    window.$ = { growl };

    window.parentClicks = 0;
    document.getElementById('trigger-wrap').addEventListener('click', () => { window.parentClicks += 1; });

    document.querySelector('.error').addEventListener('click', (ev) => {
      ev.preventDefault();
      ev.stopPropagation();
      growl.error({ title: '错误标题', message: '错误消息内容!', fixed: true });
    });
    document.querySelector('.notice').addEventListener('click', (ev) => {
      ev.preventDefault();
      ev.stopPropagation();
      growl.notice({ title: '提醒标题', message: '提醒消息内容!', fixed: true });
    });
    document.querySelector('.warning').addEventListener('click', (ev) => {
      ev.preventDefault();
      ev.stopPropagation();
      growl.warning({ title: '警告标题', message: '警告消息内容!', fixed: true });
    });
  </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_DOC, wait_until="load")

            # Case 1: Render default, error, notice, warning growl cards with exact classes & colors
            res1 = page.evaluate("""() => {
                $.growl({ title: '消息标题', message: '消息内容!', fixed: true });
                $.growl.error({ title: '错误标题', message: '错误消息内容!', fixed: true });
                $.growl.notice({ title: '提醒标题', message: '提醒消息内容!', fixed: true });
                $.growl.warning({ title: '警告标题', message: '警告消息内容!', fixed: true });
                return Array.from(document.querySelectorAll('#growls .growl')).map(el => ({
                  cls: el.className,
                  title: el.querySelector('.growl-title').textContent,
                  msg: el.querySelector('.growl-message').textContent,
                  bg: getComputedStyle(el).backgroundColor,
                }));
            }""")
            exp1 = [
                {"cls": "growl growl-default", "title": "消息标题", "msg": "消息内容!", "bg": "rgb(149, 165, 166)"},
                {"cls": "growl growl-error", "title": "错误标题", "msg": "错误消息内容!", "bg": "rgb(192, 57, 43)"},
                {"cls": "growl growl-notice", "title": "提醒标题", "msg": "提醒消息内容!", "bg": "rgb(46, 204, 113)"},
                {"cls": "growl growl-warning", "title": "警告标题", "msg": "警告消息内容!", "bg": "rgb(243, 156, 18)"},
            ]
            cases.append(dict(
                name="growl_four_variants_render",
                expected=exp1,
                actual=res1,
                passed=(res1 == exp1),
            ))

            # Case 2: Click triggers with stopPropagation + manual close button dismissal
            page.evaluate("() => { document.getElementById('growls').innerHTML = ''; }")
            page.click(".error")
            page.click(".notice")
            page.click(".warning")
            count_before_close = page.locator("#growls .growl").count()
            page.locator("#growls .growl .growl-close").first.click()
            count_after_close = page.locator("#growls .growl").count()
            parent_clicks = page.evaluate("() => window.parentClicks")
            res2 = {
                "count_before_close": count_before_close,
                "count_after_close": count_after_close,
                "parent_clicks": parent_clicks,
            }
            exp2 = {
                "count_before_close": 3,
                "count_after_close": 2,
                "parent_clicks": 0,
            }
            cases.append(dict(
                name="click_triggers_and_close_button",
                expected=exp2,
                actual=res2,
                passed=(res2 == exp2),
            ))

            # Case 3: Auto-dismiss timeout + hover pause behavior
            page.mouse.move(1, 1)
            page.evaluate("() => { document.getElementById('growls').innerHTML = ''; }")
            res3 = page.evaluate("""() => new Promise(resolve => {
                const c1 = $.growl({ title: '自动消失', message: '120ms', duration: 120 });
                const c2 = $.growl.notice({ title: '悬停暂停', message: 'hover', duration: 120 });
                c2.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }));
                const initialCount = document.querySelectorAll('#growls .growl').length;
                setTimeout(() => {
                  const midCount = document.querySelectorAll('#growls .growl').length;
                  const remainingTitle = document.querySelector('#growls .growl-title').textContent;
                  c2.dispatchEvent(new MouseEvent('mouseleave', { bubbles: true }));
                  setTimeout(() => {
                    const finalCount = document.querySelectorAll('#growls .growl').length;
                    resolve({ initialCount, midCount, remainingTitle, finalCount });
                  }, 180);
                }, 180);
            })""")
            exp3 = {
                "initialCount": 2,
                "midCount": 1,
                "remainingTitle": "悬停暂停",
                "finalCount": 0,
            }
            cases.append(dict(
                name="auto_dismiss_and_hover_pause",
                expected=exp3,
                actual=res3,
                passed=(res3 == exp3),
            ))
        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/jquery-plugin-message-lab/explore-plugin-message.py

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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