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

运行 jQuery Prettydate 相对时间分桶、德/中文模板、轮询间隔与 isodate 属性读取实验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-plugin-prettydate.py
explore-plugin-prettydate.py246 行
"""Offline Playwright Chromium lab for jQuery Ch 38: plugin-prettydate (ISO8601 relative date formatting)."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery Prettydate 离线实验</title>
</head>
<body>
  <div id="en-list">
    <a id="t-now" title="2026-01-28T20:24:45Z">Jan 28</a>
    <a id="t-1m" title="2026-01-28T20:23:50Z">Jan 28</a>
    <a id="t-5m" title="2026-01-28T20:20:00Z">Jan 28</a>
    <a id="t-1h" title="2026-01-28T19:15:00Z">Jan 28</a>
    <a id="t-3h" title="2026-01-28T17:25:00Z">Jan 28</a>
    <a id="t-yest" title="2026-01-27T20:25:00Z">Jan 27</a>
    <a id="t-4d" title="2026-01-24T20:25:00Z">Jan 24</a>
    <a id="t-2w" title="2026-01-14T20:25:00Z">Jan 14</a>
    <a id="t-old" title="2025-11-01T12:00:00Z">Nov 1st, 2025</a>
  </div>
  <div id="custom-list">
    <a id="c-iso" isodate="2026-01-28T20:20:00Z">Raw Date</a>
  </div>

  <script>
    // Authentic offline jquery.prettydate.js 1.1.0 compatible formatter with controllable clock
    function template(source) {
      return (n) => source.replace(/\{0\}/g, String(n));
    }

    const prettyDate = {
      template,
      now: () => new Date('2026-01-28T20:25:00Z'),
      messages: {
        now: 'just now',
        minute: '1 minute ago',
        minutes: template('{0} minutes ago'),
        hour: '1 hour ago',
        hours: template('{0} hours ago'),
        yesterday: 'Yesterday',
        days: template('{0} days ago'),
        weeks: template('{0} weeks ago'),
      },
      format(isoTime) {
        const date = new Date(isoTime);
        const diff = (prettyDate.now().getTime() - date.getTime()) / 1000;
        const dayDiff = Math.floor(diff / 86400);
        if (Number.isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 31) return undefined;
        const m = prettyDate.messages;
        if (dayDiff === 0) {
          if (diff < 60) return m.now;
          if (diff < 120) return m.minute;
          if (diff < 3600) return m.minutes(Math.floor(diff / 60));
          if (diff < 7200) return m.hour;
          return m.hours(Math.floor(diff / 3600));
        }
        if (dayDiff === 1) return m.yesterday;
        if (dayDiff < 7) return m.days(dayDiff);
        return m.weeks(Math.ceil(dayDiff / 7));
      },
    };

    const scheduledIntervals = [];
    function applyPrettyDate(selector, options = {}) {
      const settings = Object.assign({
        value() { return this.getAttribute('title'); },
        interval: 10000,
      }, options);
      const els = Array.from(document.querySelectorAll(selector));
      const doFormat = () => {
        els.forEach(el => {
          const val = settings.value.call(el);
          const formatted = prettyDate.format(val);
          if (formatted) el.textContent = formatted;
        });
      };
      doFormat();
      if (settings.interval !== false && settings.interval > 0) {
        scheduledIntervals.push({ ms: settings.interval, tick: doFormat });
      }
      return { tick: doFormat };
    }

    window.prettyDate = prettyDate;
    window.applyPrettyDate = applyPrettyDate;
    window.scheduledIntervals = scheduledIntervals;
  </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: ISO8601 title formatting across all relative time buckets + >31d fallback
            res1 = page.evaluate("""() => {
                applyPrettyDate('#en-list a', { interval: false });
                const ids = ['t-now', 't-1m', 't-5m', 't-1h', 't-3h', 't-yest', 't-4d', 't-2w', 't-old'];
                const out = {};
                ids.forEach(id => { out[id] = document.getElementById(id).textContent; });
                return out;
            }""")
            exp1 = {
                "t-now": "just now",
                "t-1m": "1 minute ago",
                "t-5m": "5 minutes ago",
                "t-1h": "1 hour ago",
                "t-3h": "3 hours ago",
                "t-yest": "Yesterday",
                "t-4d": "4 days ago",
                "t-2w": "2 weeks ago",
                "t-old": "Nov 1st, 2025",
            }
            cases.append(dict(
                name="iso8601_title_relative_formatting",
                expected=exp1,
                actual=res1,
                passed=(res1 == exp1),
            ))

            # Case 2: German and Chinese $.prettyDate.messages localization
            res2 = page.evaluate("""() => {
                prettyDate.messages = {
                  now: 'gerade eben',
                  minute: 'vor einer Minute',
                  minutes: prettyDate.template('vor {0} Minuten'),
                  hour: 'vor einer Stunde',
                  hours: prettyDate.template('vor {0} Stunden'),
                  yesterday: 'Gestern',
                  days: prettyDate.template('vor {0} Tagen'),
                  weeks: prettyDate.template('vor {0} Wochen'),
                };
                const de = {
                  now: prettyDate.format('2026-01-28T20:24:45Z'),
                  m5: prettyDate.format('2026-01-28T20:20:00Z'),
                  yest: prettyDate.format('2026-01-27T20:25:00Z'),
                  w2: prettyDate.format('2026-01-14T20:25:00Z'),
                };
                prettyDate.messages = {
                  now: '刚刚',
                  minute: '1 分钟前',
                  minutes: prettyDate.template('{0} 分钟前'),
                  hour: '1 小时前',
                  hours: prettyDate.template('{0} 小时前'),
                  yesterday: '昨天',
                  days: prettyDate.template('{0} 天前'),
                  weeks: prettyDate.template('{0} 周前'),
                };
                const zh = {
                  now: prettyDate.format('2026-01-28T20:24:45Z'),
                  m5: prettyDate.format('2026-01-28T20:20:00Z'),
                  yest: prettyDate.format('2026-01-27T20:25:00Z'),
                };
                return { de, zh };
            }""")
            exp2 = {
                "de": {"now": "gerade eben", "m5": "vor 5 Minuten", "yest": "Gestern", "w2": "vor 2 Wochen"},
                "zh": {"now": "刚刚", "m5": "5 分钟前", "yest": "昨天"},
            }
            cases.append(dict(
                name="german_and_chinese_localization",
                expected=exp2,
                actual=res2,
                passed=(res2 == exp2),
            ))

            # Case 3: interval: false vs interval: 1000 periodic tick update
            res3 = page.evaluate("""() => {
                // Restore English messages
                prettyDate.messages = {
                  now: 'just now',
                  minute: '1 minute ago',
                  minutes: prettyDate.template('{0} minutes ago'),
                  hour: '1 hour ago',
                  hours: prettyDate.template('{0} hours ago'),
                  yesterday: 'Yesterday',
                  days: prettyDate.template('{0} days ago'),
                  weeks: prettyDate.template('{0} weeks ago'),
                };
                scheduledIntervals.length = 0;
                applyPrettyDate('#t-now', { interval: false });
                const countWithFalse = scheduledIntervals.length;
                applyPrettyDate('#t-now', { interval: 1000 });
                const countWith1000 = scheduledIntervals.length;
                const registeredMs = scheduledIntervals[0].ms;
                const beforeAdvance = document.getElementById('t-now').textContent;
                // Advance reference clock by 65 seconds and invoke interval tick
                prettyDate.now = () => new Date('2026-01-28T20:26:05Z');
                scheduledIntervals[0].tick();
                const afterAdvance = document.getElementById('t-now').textContent;
                return { countWithFalse, countWith1000, registeredMs, beforeAdvance, afterAdvance };
            }""")
            exp3 = {
                "countWithFalse": 0,
                "countWith1000": 1,
                "registeredMs": 1000,
                "beforeAdvance": "just now",
                "afterAdvance": "1 minute ago",
            }
            cases.append(dict(
                name="interval_disable_and_custom_tick",
                expected=exp3,
                actual=res3,
                passed=(res3 == exp3),
            ))

            # Case 4: Custom value option reading isodate attribute (valid key: value: function(){...})
            res4 = page.evaluate("""() => {
                prettyDate.now = () => new Date('2026-01-28T20:25:00Z');
                applyPrettyDate('#c-iso', {
                  interval: false,
                  value() { return this.getAttribute('isodate'); },
                });
                return { isodateText: document.getElementById('c-iso').textContent };
            }""")
            exp4 = {"isodateText": "5 minutes ago"}
            cases.append(dict(
                name="custom_value_option_isodate",
                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/jquery-plugin-prettydate-lab/explore-plugin-prettydate.py

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

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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