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

运行全部 15 个 Ionic 手势指令解析、按压阈值、四向拖拽/轻扫与 $ionicGesture 注册注销离线实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-gesture-event.py
explore-gesture-event.py171 行
"""Offline Ionic 1 gesture directive & $ionicGesture service verifier."""
import json
from lxml import html


GESTURE_DIRECTIVES = [
    ("on-hold", "onHold()"),
    ("on-tap", "onTap()"),
    ("on-double-tap", "onDoubleTap()"),
    ("on-touch", "onTouch()"),
    ("on-release", "onRelease()"),
    ("on-drag", "onDrag()"),
    ("on-drag-up", "onDragUp()"),
    ("on-drag-right", "onDragRight()"),
    ("on-drag-down", "onDragDown()"),
    ("on-drag-left", "onDragLeft()"),
    ("on-swipe", "onSwipe()"),
    ("on-swipe-up", "onSwipeUp()"),
    ("on-swipe-right", "onSwipeRight()"),
    ("on-swipe-down", "onSwipeDown()"),
    ("on-swipe-left", "onSwipeLeft()"),
]


class IonicGestureService:
    """Models $ionicGesture.on / off listener registry."""

    def __init__(self):
        self._listeners = []

    def on(self, event_type, callback, element_id, options=None):
        handle = {
            "eventType": event_type,
            "callback": callback,
            "element": element_id,
            "options": options or {},
        }
        self._listeners.append(handle)
        return handle

    def off(self, gesture_or_type, event_type=None, callback=None):
        if isinstance(gesture_or_type, dict):
            self._listeners = [h for h in self._listeners if h is not gesture_or_type]
        else:
            self._listeners = [
                h for h in self._listeners
                if not (h["eventType"] == gesture_or_type and h["callback"] == event_type)
            ]

    def dispatch(self, element_id, event_type, payload):
        fired = []
        for h in list(self._listeners):
            if h["element"] == element_id and h["eventType"] == event_type:
                fired.append(h["callback"](payload))
        return fired


def classify_press(duration_ms: int, tap_count: int = 1) -> str:
    if tap_count >= 2 and duration_ms <= 250:
        return "double-tap"
    if duration_ms >= 500:
        return "hold"
    if duration_ms <= 250:
        return "tap"
    return "release-only"


def classify_motion(dx: int, dy: int, velocity: float):
    if abs(dx) >= abs(dy):
        direction = "right" if dx > 0 else "left"
    else:
        direction = "down" if dy > 0 else "up"
    kind = "swipe" if velocity >= 0.6 else "drag"
    return [kind, f"{kind}-{direction}"]


def main():
    cases = []

    # Case 1: Parse all 15 gesture directive button snippets
    parsed = {}
    for attr, expr in GESTURE_DIRECTIVES:
        el = html.fromstring(f'<button {attr}="{expr}" class="button">Test</button>')
        parsed[attr] = el.get(attr)
    expected_parsed = dict(GESTURE_DIRECTIVES)
    cases.append({
        "name": "parse_all_15_gesture_directives",
        "summary": "解析全部 15 个 Ionic 手势指令(touch/release/tap/hold/drag*/swipe*)",
        "expected": expected_parsed,
        "actual": parsed,
        "passed": parsed == expected_parsed,
    })

    # Case 2: Press threshold classification (touch -> tap <= 250ms, hold >= 500ms, double-tap)
    actual_press = {
        "short_120ms": classify_press(120, 1),
        "double_100ms": classify_press(100, 2),
        "mid_350ms": classify_press(350, 1),
        "long_500ms": classify_press(500, 1),
        "long_650ms": classify_press(650, 1),
    }
    expected_press = {
        "short_120ms": "tap",
        "double_100ms": "double-tap",
        "mid_350ms": "release-only",
        "long_500ms": "hold",
        "long_650ms": "hold",
    }
    cases.append({
        "name": "tap_hold_threshold_rules",
        "summary": "验证轻击(<=250ms)、双击与长按(>=500ms)时间阈值判定",
        "expected": expected_press,
        "actual": actual_press,
        "passed": actual_press == expected_press,
    })

    # Case 3: Drag & swipe directional dispatch across all 4 axes
    actual_dir = {
        "drag_up": classify_motion(0, -40, 0.2),
        "drag_right": classify_motion(50, 5, 0.25),
        "drag_down": classify_motion(4, 60, 0.3),
        "drag_left": classify_motion(-45, 2, 0.2),
        "swipe_up": classify_motion(0, -80, 1.1),
        "swipe_right": classify_motion(90, 0, 1.2),
        "swipe_down": classify_motion(0, 85, 0.9),
        "swipe_left": classify_motion(-95, 5, 1.4),
    }
    expected_dir = {
        "drag_up": ["drag", "drag-up"],
        "drag_right": ["drag", "drag-right"],
        "drag_down": ["drag", "drag-down"],
        "drag_left": ["drag", "drag-left"],
        "swipe_up": ["swipe", "swipe-up"],
        "swipe_right": ["swipe", "swipe-right"],
        "swipe_down": ["swipe", "swipe-down"],
        "swipe_left": ["swipe", "swipe-left"],
    }
    cases.append({
        "name": "drag_and_swipe_directions",
        "summary": "验证 drag 与 swipe 通用事件及上下左右四方向事件分类",
        "expected": expected_dir,
        "actual": actual_dir,
        "passed": actual_dir == expected_dir,
    })

    # Case 4: $ionicGesture.on() and off() registration/removal lifecycle
    svc = IonicGestureService()
    cb = lambda e: f"held:{e['target']}"
    gesture_handle = svc.on("hold", cb, "btn-1", {"prevent_default": True})
    before_off = svc.dispatch("btn-1", "hold", {"target": "btn-1"})
    svc.off(gesture_handle, "hold", cb)
    after_off = svc.dispatch("btn-1", "hold", {"target": "btn-1"})
    actual_svc = {"before_off": before_off, "after_off": after_off, "remaining": len(svc._listeners)}
    expected_svc = {"before_off": ["held:btn-1"], "after_off": [], "remaining": 0}
    cases.append({
        "name": "ionic_gesture_on_off_service",
        "summary": "验证 $ionicGesture.on 注册监听、派发回调与 off 注销清理",
        "expected": expected_svc,
        "actual": actual_svc,
        "passed": actual_svc == expected_svc,
    })

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

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

下载课程关联工程包:Ionic

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

下载课程关联工程包:Ionic

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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