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

运行 $ionicPopup.show() 校验拦截、confirm/alert/prompt 返回值与现代 ion-alert 离线实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-ionicpopup.py
explore-ionicpopup.py200 行
"""Offline Ionic 1 $ionicPopup show/confirm/prompt/alert & onTap validation verifier."""
import json
from lxml import html


class TapEvent:
    def __init__(self):
        self.default_prevented = False

    def prevent_default(self):
        self.default_prevented = True


class IonicPopupInstance:
    def __init__(self, kind, config):
        self.kind = kind
        self.config = dict(config)
        self.closed = False
        self.result = None

    def tap_button(self, index):
        btn = self.config["buttons"][index]
        ev = TapEvent()
        on_tap = btn.get("onTap")
        val = on_tap(ev) if on_tap else btn.get("default_return")
        if ev.default_prevented:
            return {"closed": False, "prevented": True, "result": None}
        self.closed = True
        self.result = val
        return {"closed": True, "prevented": False, "result": val}

    def close(self, result=None):
        self.closed = True
        self.result = result


class IonicPopupService:
    def show(self, config):
        return IonicPopupInstance("show", config)

    def confirm(self, config):
        cfg = dict(config)
        cfg["buttons"] = [
            {"text": "Cancel", "default_return": False},
            {"text": "OK", "default_return": True},
        ]
        return IonicPopupInstance("confirm", cfg)

    def alert(self, config):
        cfg = dict(config)
        cfg["buttons"] = [{"text": "OK", "default_return": True}]
        return IonicPopupInstance("alert", cfg)

    def prompt(self, config, input_value=""):
        cfg = dict(config)
        cfg["buttons"] = [
            {"text": "Cancel", "default_return": None},
            {"text": "OK", "onTap": lambda e: input_value},
        ]
        return IonicPopupInstance("prompt", cfg)


def main():
    cases = []

    # Case 1: Parse HTML popup trigger buttons & ng-template password input
    markup = """
    <body class="padding" ng-controller="PopupCtrl">
      <button class="button button-dark" ng-click="showPopup()">弹窗显示</button>
      <button class="button button-primary" ng-click="showConfirm()">确认对话框</button>
      <button class="button button-positive" ng-click="showAlert()">警告框</button>
      <script id="popup-template.html" type="text/ng-template">
        <input ng-model="data.wifi" type="text" placeholder="Password">
      </script>
    </body>
    """
    doc = html.fromstring(markup)
    clicks = doc.xpath("//button/@ng-click")
    tpl = html.fromstring(doc.xpath("//script[@id='popup-template.html']")[0].text)
    actual_dom = {
        "button_handlers": clicks,
        "template_input_model": tpl.get("ng-model"),
        "template_placeholder": tpl.get("placeholder"),
    }
    expected_dom = {
        "button_handlers": ["showPopup()", "showConfirm()", "showAlert()"],
        "template_input_model": "data.wifi",
        "template_placeholder": "Password",
    }
    cases.append({
        "name": "parse_popup_triggers_and_template",
        "summary": "解析三个弹窗按钮的 ng-click 绑定及 popup-template.html 输入模板",
        "expected": expected_dom,
        "actual": actual_dom,
        "passed": actual_dom == expected_dom,
    })

    # Case 2: $ionicPopup.show() onTap e.preventDefault() validation & .close() timeout
    svc = IonicPopupService()
    scope_data = {"wifi": ""}

    def on_save(e):
        if not scope_data["wifi"]:
            e.prevent_default()
            return None
        return scope_data["wifi"]

    popup = svc.show({
        "title": "Enter Wi-Fi Password",
        "subTitle": "Please use normal things",
        "template": '<input type="password" ng-model="data.wifi">',
        "buttons": [
            {"text": "Cancel", "default_return": None},
            {"text": "<b>Save</b>", "type": "button-positive", "onTap": on_save},
        ],
    })
    empty_attempt = popup.tap_button(1)
    scope_data["wifi"] = "S3cret-WiFi"
    valid_attempt = popup.tap_button(1)

    # Timeout auto-close path
    popup2 = svc.show({"title": "Auto close", "buttons": [{"text": "Cancel"}]})
    popup2.close()
    actual_show = {
        "empty_attempt": empty_attempt,
        "valid_attempt": valid_attempt,
        "timeout_closed": popup2.closed,
    }
    expected_show = {
        "empty_attempt": {"closed": False, "prevented": True, "result": None},
        "valid_attempt": {"closed": True, "prevented": False, "result": "S3cret-WiFi"},
        "timeout_closed": True,
    }
    cases.append({
        "name": "popup_show_ontap_validation",
        "summary": "验证 $ionicPopup.show() 空密码 e.preventDefault() 拦截、有效提交返回与 close()",
        "expected": expected_show,
        "actual": actual_show,
        "passed": actual_show == expected_show,
    })

    # Case 3: confirm(), alert() & prompt() built-in dialogs
    c_ok = svc.confirm({"title": "Consume Ice Cream", "template": "Are you sure?"}).tap_button(1)
    c_cancel = svc.confirm({"title": "Consume Ice Cream", "template": "Are you sure?"}).tap_button(0)
    a_ok = svc.alert({"title": "Don't eat that!", "template": "It might taste good"}).tap_button(0)
    p_ok = svc.prompt({"title": "Wi-Fi", "template": "Enter password"}, input_value="guest123").tap_button(1)
    p_cancel = svc.prompt({"title": "Wi-Fi", "template": "Enter password"}, input_value="guest123").tap_button(0)
    actual_builtin = {
        "confirm_ok": c_ok["result"],
        "confirm_cancel": c_cancel["result"],
        "alert_ok": a_ok["result"],
        "prompt_ok": p_ok["result"],
        "prompt_cancel": p_cancel["result"],
    }
    expected_builtin = {
        "confirm_ok": True,
        "confirm_cancel": False,
        "alert_ok": True,
        "prompt_ok": "guest123",
        "prompt_cancel": None,
    }
    cases.append({
        "name": "popup_confirm_alert_prompt",
        "summary": "验证 $ionicPopup 的 confirm()、alert() 与 prompt() 按钮返回值语义",
        "expected": expected_builtin,
        "actual": actual_builtin,
        "passed": actual_builtin == expected_builtin,
    })

    # Case 4: Modern Ionic 7/8 <ion-alert> unification check
    modern = html.fromstring('<ion-alert trigger="open-alert" header="Confirm" message="Proceed?"></ion-alert>')
    actual_modern = {
        "tag": modern.tag,
        "trigger": modern.get("trigger"),
        "header": modern.get("header"),
        "message": modern.get("message"),
    }
    expected_modern = {
        "tag": "ion-alert",
        "trigger": "open-alert",
        "header": "Confirm",
        "message": "Proceed?",
    }
    cases.append({
        "name": "modern_ion_alert_wc",
        "summary": "核对现代 Ionic 7/8 <ion-alert> 统一替代 alert/confirm/prompt 属性",
        "expected": expected_modern,
        "actual": actual_modern,
        "passed": actual_modern == expected_modern,
    })

    print(json.dumps({
        "version": "CPython 3.12.14 / lxml offline Ionic JS directive & service verifier",
        "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/ionic-ionicpopup-lab/explore-ionicpopup.py

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

下载课程关联工程包:Ionic

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

下载课程关联工程包:Ionic

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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