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

运行 $ionicActionSheet 触发 DOM、按钮/高危/取消/遮罩回调状态机与平台守卫离线核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-actionsheet.py
explore-actionsheet.py203 行
"""Offline Ionic 1 $ionicActionSheet DOM trigger & button/destructive/cancel/timeout state-machine verifier for Ch18 (actionsheet)."""
from __future__ import annotations

import json
from lxml import html

VERSION = "CPython 3.12.14 / lxml offline Ionic UI & component verifier"


def make_case(name: str, summary: str, expected, actual) -> dict:
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_actionsheet_trigger_dom() -> dict:
    markup = """
    <body ng-app="starter" ng-controller="actionsheetCtl">
      <ion-pane>
        <ion-content>
          <h2 ng-click="show()">Action Sheet</h2>
        </ion-content>
      </ion-pane>
    </body>
    """
    doc = html.document_fromstring(f"<html>{markup}</html>")
    body = doc.xpath("//body")[0]
    h2 = doc.xpath("//ion-pane/ion-content/h2")[0]
    actual = {
        "ng_app": body.get("ng-app"),
        "ng_controller": body.get("ng-controller"),
        "has_ion_pane": bool(doc.xpath("//ion-pane")),
        "trigger_ng_click": h2.get("ng-click"),
        "trigger_text": h2.text_content().strip(),
    }
    expected = {
        "ng_app": "starter",
        "ng_controller": "actionsheetCtl",
        "has_ion_pane": True,
        "trigger_ng_click": "show()",
        "trigger_text": "Action Sheet",
    }
    return make_case(
        "actionsheet_html_trigger_structure",
        "Parse ng-app, actionsheetCtl, <ion-pane>/<ion-content>, and ng-click='show()' trigger",
        expected,
        actual,
    )


def case_actionsheet_callback_state_machine() -> dict:
    class IonicActionSheetSimulator:
        def __init__(self) -> None:
            self.visible = False
            self.config: dict = {}
            self.events: list[str] = []

        def show(self, config: dict):
            self.config = config
            self.visible = True
            self.events.append(f"show:{config['titleText']}")
            return self.hide

        def hide(self) -> None:
            if self.visible:
                self.visible = False
                self.events.append("hide")

        def click_button(self, index: int) -> None:
            if not self.visible:
                return
            btn = self.config["buttons"][index]["text"]
            self.events.append(f"button:{index}:{btn}")
            cb = self.config.get("buttonClicked")
            if cb and cb(index) is True:
                self.hide()

        def click_destructive(self) -> None:
            if not self.visible:
                return
            self.events.append(f"destructive:{self.config['destructiveText']}")
            cb = self.config.get("destructiveButtonClicked")
            if cb is None or cb() is True:
                self.hide()

        def click_cancel_or_backdrop(self, source: str) -> None:
            if not self.visible:
                return
            self.events.append(f"dismiss:{source}")
            cb = self.config.get("cancel")
            if cb:
                cb()
            self.hide()

    sim = IonicActionSheetSimulator()
    cancel_calls = 0

    def on_cancel() -> None:
        nonlocal cancel_calls
        cancel_calls += 1

    cfg = {
        "buttons": [{"text": "<b>Share</b> This"}, {"text": "Move"}],
        "destructiveText": "Delete",
        "titleText": "Modify your album",
        "cancelText": "Cancel",
        "cancel": on_cancel,
        "buttonClicked": lambda idx: idx == 0,  # returns True for Share (closes), False for Move (stays open)
        "destructiveButtonClicked": lambda: True,
    }

    # Flow 1: Move returns False (stays open), then Share returns True (closes)
    hide_fn = sim.show(cfg)
    sim.click_button(1)
    open_after_move = sim.visible
    sim.click_button(0)
    open_after_share = sim.visible

    # Flow 2: Destructive button triggers red delete action and closes
    sim.show(cfg)
    sim.click_destructive()
    open_after_delete = sim.visible

    # Flow 3: Cancel / backdrop tap invokes cancel() and closes
    sim.show(cfg)
    sim.click_cancel_or_backdrop("backdrop")

    # Flow 4: $timeout(hideSheet, 2000) programmatic dismiss
    hide_fn = sim.show(cfg)
    open_before_timeout = sim.visible
    hide_fn()
    open_after_timeout = sim.visible

    actual = {
        "open_after_move_false": open_after_move,
        "open_after_share_true": open_after_share,
        "open_after_destructive": open_after_delete,
        "cancel_calls": cancel_calls,
        "open_before_timeout": open_before_timeout,
        "open_after_timeout": open_after_timeout,
        "event_count": len(sim.events),
    }
    expected = {
        "open_after_move_false": True,
        "open_after_share_true": False,
        "open_after_destructive": False,
        "cancel_calls": 1,
        "open_before_timeout": True,
        "open_after_timeout": False,
        "event_count": 12,
    }
    return make_case(
        "actionsheet_show_callbacks_and_timeout_hide",
        "Verify $ionicActionSheet.show() buttonClicked return semantics, destructive action, cancel/backdrop, and hideSheet() timeout",
        expected,
        actual,
    )


def case_platform_ready_and_modern_mapping() -> dict:
    # Verify Cordova Keyboard / StatusBar feature-detection guards in .run($ionicPlatform)
    def run_platform_ready(env: dict) -> list[str]:
        executed = []
        if env.get("cordova_keyboard"):
            executed.append("hideKeyboardAccessoryBar(true)")
        if env.get("status_bar"):
            executed.append("StatusBar.styleDefault()")
        return executed

    actual = {
        "browser_without_cordova": run_platform_ready({"cordova_keyboard": False, "status_bar": False}),
        "native_with_plugins": run_platform_ready({"cordova_keyboard": True, "status_bar": True}),
        "modern_component": "<ion-action-sheet> / actionSheetController.create({ header, buttons })",
    }
    expected = {
        "browser_without_cordova": [],
        "native_with_plugins": ["hideKeyboardAccessoryBar(true)", "StatusBar.styleDefault()"],
        "modern_component": "<ion-action-sheet> / actionSheetController.create({ header, buttons })",
    }
    return make_case(
        "actionsheet_platform_ready_guards_and_modern_api",
        "Verify $ionicPlatform.ready Cordova plugin guards and Ionic 7/8 <ion-action-sheet> migration",
        expected,
        actual,
    )


def main() -> None:
    cases = [
        case_actionsheet_trigger_dom(),
        case_actionsheet_callback_state_machine(),
        case_platform_ready_and_modern_mapping(),
    ]
    print(json.dumps({"version": VERSION, "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-actionsheet-lab/explore-actionsheet.py

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

下载课程关联工程包:Ionic

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

下载课程关联工程包:Ionic

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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