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

离线 Chromium 实测 ngAnimate 类生命周期与 CSS transition/keyframes 动画

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-animations.py
explore-animations.py278 行
"""Offline Playwright Chromium lab for AngularJS Ch 22: animations (ngAnimate, CSS transitions & keyframes)."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>AngularJS ngAnimate 离线实验</title>
<style>
  #box-transition {
    transition: all linear 0.5s;
    background-color: lightblue;
    height: 100px;
    overflow: hidden;
  }
  #box-transition.ng-hide {
    height: 0;
  }

  @keyframes myChange {
    from { height: 100px; }
    to { height: 0; }
  }
  #box-keyframe {
    height: 100px;
    background-color: lightblue;
    overflow: hidden;
  }
  #box-keyframe.ng-hide {
    animation: 0.5s myChange forwards;
  }
</style>
</head>
<body>
  <section id="app-standalone" ng-app="ngAnimate">
    <input id="chk-standalone" type="checkbox">
    <div id="box-standalone"></div>
  </section>

  <section id="app-module" ng-app="myApp">
    <input id="chk-module" type="checkbox">
    <div id="box-module"></div>
  </section>

  <div id="box-lifecycle"></div>
  <ul id="repeat-list">
    <li data-id="a">A</li>
    <li data-id="b">B</li>
  </ul>

  <div id="box-transition"></div>
  <div id="box-keyframe"></div>

  <script>
    // Minimal offline AngularJS 1.x module registry + ngAnimate class hook equivalence runtime
    const modules = {};
    window.angular = {
      module(name, requires) {
        if (requires) {
          modules[name] = { name, requires: requires.slice() };
        }
        return modules[name];
      }
    };
    window.angular.module('myApp', ['ngAnimate']);

    function bindNgHide(chk, target) {
      chk.addEventListener('change', () => {
        target.classList.toggle('ng-hide', chk.checked);
      });
    }
    bindNgHide(document.getElementById('chk-standalone'), document.getElementById('box-standalone'));
    bindNgHide(document.getElementById('chk-module'), document.getElementById('box-module'));

    // Simulate ngAnimate class lifecycle for ng-hide add / remove and structural enter/leave/move
    window.simulateHideLifecycle = function(el, hiding) {
      const snapshots = {};
      if (hiding) {
        el.classList.add('ng-animate', 'ng-hide-animate', 'ng-hide-add');
        snapshots.start = Array.from(el.classList).sort();
        el.classList.add('ng-hide', 'ng-hide-add-active');
        snapshots.active = Array.from(el.classList).sort();
        el.classList.remove('ng-animate', 'ng-hide-animate', 'ng-hide-add', 'ng-hide-add-active');
        snapshots.done = Array.from(el.classList).sort();
      } else {
        el.classList.add('ng-animate', 'ng-hide-animate', 'ng-hide-remove');
        snapshots.start = Array.from(el.classList).sort();
        el.classList.remove('ng-hide');
        el.classList.add('ng-hide-remove-active');
        snapshots.active = Array.from(el.classList).sort();
        el.classList.remove('ng-animate', 'ng-hide-animate', 'ng-hide-remove', 'ng-hide-remove-active');
        snapshots.done = Array.from(el.classList).sort();
      }
      return snapshots;
    };

    window.simulateStructuralHooks = function() {
      const ul = document.getElementById('repeat-list');
      const liNew = document.createElement('li');
      liNew.dataset.id = 'c';
      liNew.textContent = 'C';
      liNew.classList.add('ng-enter', 'ng-enter-active');
      ul.appendChild(liNew);
      const enterClasses = Array.from(liNew.classList).sort();
      liNew.classList.remove('ng-enter', 'ng-enter-active');

      const first = ul.querySelector('[data-id="a"]');
      first.classList.add('ng-move', 'ng-move-active');
      ul.appendChild(first);
      const moveClasses = Array.from(first.classList).sort();
      first.classList.remove('ng-move', 'ng-move-active');

      const leaving = ul.querySelector('[data-id="b"]');
      leaving.classList.add('ng-leave', 'ng-leave-active');
      const leaveClasses = Array.from(leaving.classList).sort();
      leaving.remove();

      const remainingIds = Array.from(ul.querySelectorAll('li')).map(n => n.dataset.id);
      return { enterClasses, moveClasses, leaveClasses, remainingIds };
    };
  </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: ng-app="ngAnimate" standalone and angular.module('myApp', ['ngAnimate']) binding
            page.check("#chk-standalone")
            page.check("#chk-module")
            res1 = page.evaluate("""() => ({
                standalone_app: document.getElementById('app-standalone').getAttribute('ng-app'),
                standalone_hidden: document.getElementById('box-standalone').classList.contains('ng-hide'),
                module_deps: window.angular.module('myApp').requires,
                module_hidden: document.getElementById('box-module').classList.contains('ng-hide')
            })""")
            exp1 = {
                "standalone_app": "ngAnimate",
                "standalone_hidden": True,
                "module_deps": ["ngAnimate"],
                "module_hidden": True,
            }
            cases.append(dict(
                name="ng_hide_checkbox_and_module_dependency",
                expected=exp1,
                actual=res1,
                passed=(res1 == exp1),
            ))

            # Case 2: ngAnimate exact lifecycle class hooks & cleanup + enter/leave/move
            res2 = page.evaluate("""() => {
                const el = document.getElementById('box-lifecycle');
                const hideFlow = window.simulateHideLifecycle(el, true);
                const showFlow = window.simulateHideLifecycle(el, false);
                const structural = window.simulateStructuralHooks();
                return { hideFlow, showFlow, structural };
            }""")
            exp2 = {
                "hideFlow": {
                    "start": ["ng-animate", "ng-hide-add", "ng-hide-animate"],
                    "active": ["ng-animate", "ng-hide", "ng-hide-add", "ng-hide-add-active", "ng-hide-animate"],
                    "done": ["ng-hide"],
                },
                "showFlow": {
                    "start": ["ng-animate", "ng-hide", "ng-hide-animate", "ng-hide-remove"],
                    "active": ["ng-animate", "ng-hide-animate", "ng-hide-remove", "ng-hide-remove-active"],
                    "done": [],
                },
                "structural": {
                    "enterClasses": ["ng-enter", "ng-enter-active"],
                    "moveClasses": ["ng-move", "ng-move-active"],
                    "leaveClasses": ["ng-leave", "ng-leave-active"],
                    "remainingIds": ["c", "a"],
                },
            }
            cases.append(dict(
                name="ng_animate_class_lifecycle_hooks",
                expected=exp2,
                actual=res2,
                passed=(res2 == exp2),
            ))

            # Case 3: Real CSS transition (0.5s linear, height 100px -> 0px)
            res3 = page.evaluate("""() => new Promise((resolve) => {
                const el = document.getElementById('box-transition');
                const before = getComputedStyle(el);
                const initHeight = before.height;
                const duration = before.transitionDuration;
                const bg = before.backgroundColor;
                let endedProp = '';
                el.addEventListener('transitionend', (ev) => {
                    if (ev.propertyName === 'height') {
                        endedProp = ev.propertyName;
                        resolve({
                            init_height: initHeight,
                            transition_duration: duration,
                            background_color: bg,
                            ended_property: endedProp,
                            final_height: getComputedStyle(el).height
                        });
                    }
                }, { once: false });
                // Force style reflow before toggling .ng-hide
                void el.offsetHeight;
                el.classList.add('ng-hide');
            })""")
            exp3 = {
                "init_height": "100px",
                "transition_duration": "0.5s",
                "background_color": "rgb(173, 216, 230)",
                "ended_property": "height",
                "final_height": "0px",
            }
            cases.append(dict(
                name="css_transition_height_animation",
                expected=exp3,
                actual=res3,
                passed=(res3 == exp3),
            ))

            # Case 4: Real CSS @keyframes myChange (0.5s, height 100px -> 0px)
            res4 = page.evaluate("""() => new Promise((resolve) => {
                const el = document.getElementById('box-keyframe');
                const initHeight = getComputedStyle(el).height;
                let startedName = '';
                el.addEventListener('animationstart', (ev) => {
                    startedName = ev.animationName;
                }, { once: true });
                el.addEventListener('animationend', (ev) => {
                    const cs = getComputedStyle(el);
                    resolve({
                        init_height: initHeight,
                        started_animation: startedName,
                        ended_animation: ev.animationName,
                        animation_duration: cs.animationDuration,
                        final_height: cs.height
                    });
                }, { once: true });
                void el.offsetHeight;
                el.classList.add('ng-hide');
            })""")
            exp4 = {
                "init_height": "100px",
                "started_animation": "myChange",
                "ended_animation": "myChange",
                "animation_duration": "0.5s",
                "final_height": "0px",
            }
            cases.append(dict(
                name="css_keyframes_mychange_animation",
                expected=exp4,
                actual=res4,
                passed=(res4 == exp4),
            ))
        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/angularjs-animations-lab/explore-animations.py

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

下载课程关联工程包:AngularJS

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

下载课程关联工程包:AngularJS

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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