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

离线 Chromium 实测关键词监听、300ms 防抖定时器清理与搜索分类叠加过滤

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-blog-search.py
explore-blog-search.py303 行
"""Offline Playwright Chromium lab for React Ch 38: useEffect Keyword Watch, Debounce & Combined Search."""
import json
from playwright.sync_api import sync_playwright


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>React Live Search & Debounce Lab</title>
<style>
.search-bar { position: relative; margin-bottom: 16px; max-width: 480px; }
.search-input { width: 100%; padding: 10px 36px 10px 14px; border: 2px solid #eee; border-radius: 8px; }
.clear-btn { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); cursor: pointer; }
.category-bar { display: flex; gap: 8px; margin-bottom: 12px; }
.category-bar button.active { background: #1976d2; color: #fff; }
mark { background: #fef08a; padding: 0 2px; }
</style>
</head>
<body>
  <section id="sec-watch">
    <input id="watch-input" type="text" placeholder="监听搜索..." />
    <p id="watch-output">当前搜索:</p>
  </section>

  <section id="sec-blog">
    <div class="search-bar">
      <input id="blog-search" class="search-input" type="text" placeholder="搜索文章标题或摘要..." />
      <span id="clear-btn" class="clear-btn" style="display:none">✕</span>
    </div>
    <div id="cat-bar" class="category-bar"></div>
    <p id="result-info"></p>
    <div id="cards-box"></div>
  </section>

<script>
// 1. Direct useEffect([keyword]) watcher
window.__WATCH_LOG = [];
const watchInput = document.getElementById("watch-input");
const watchOutput = document.getElementById("watch-output");
watchInput.addEventListener("input", (e) => {
  const kw = e.target.value;
  window.__WATCH_LOG.push(kw);
  watchOutput.textContent = `当前搜索:${kw}`;
});

// 2. Deterministic virtual-clock useDebounce(value, 300) verification (zero wall-clock flakiness)
window.runDebounceSimulation = () => {
  let now = 0;
  let nextId = 1;
  const timers = new Map();
  let clearedCount = 0;

  function fakeSetTimeout(fn, delay) {
    const id = nextId++;
    timers.set(id, { fn, runAt: now + delay });
    return id;
  }
  function fakeClearTimeout(id) {
    if (timers.delete(id)) clearedCount += 1;
  }
  function advanceTime(ms) {
    now += ms;
    for (const [id, t] of [...timers.entries()]) {
      if (t.runAt <= now) {
        timers.delete(id);
        t.fn();
      }
    }
  }

  let debouncedKeyword = "";
  let searchExecutions = [];
  let cleanup = null;

  function onKeywordChange(nextValue) {
    if (cleanup) cleanup();
    const timer = fakeSetTimeout(() => {
      debouncedKeyword = nextValue;
      if (debouncedKeyword) searchExecutions.push(debouncedKeyword);
    }, 300);
    cleanup = () => fakeClearTimeout(timer);
  }

  // Rapid typing: 4 keystrokes spaced 60ms apart
  onKeywordChange("R");
  advanceTime(60);
  onKeywordChange("Re");
  advanceTime(60);
  onKeywordChange("Rea");
  advanceTime(60);
  onKeywordChange("React");
  // Still only 200ms after last keystroke -> should not fire yet
  advanceTime(200);
  const midExecutions = [...searchExecutions];
  // Cross 300ms quiet window -> fires once with "React"
  advanceTime(100);

  return {
    clearedCount,
    midExecutions,
    finalExecutions: searchExecutions,
    debouncedKeyword
  };
};

// 3 & 4. Combined category + keyword search + highlight + clear button
const ARTICLES = [
  { id: 1, title: "React 入门完全指南", summary: "从零开始学习 React Hooks,涵盖 useState、useEffect。", category: "React", date: "2024-05-10" },
  { id: 2, title: "JavaScript 异步编程详解", summary: "一文搞懂 Promise、async/await 与微任务队列。", category: "JavaScript", date: "2024-05-08" },
  { id: 3, title: "CSS Grid 布局实战", summary: "用 CSS Grid 轻松实现响应式布局。", category: "CSS", date: "2024-05-05" },
  { id: 4, title: "React Hooks 深入解析", summary: "深入理解自定义 Hook 与状态管理。", category: "React", date: "2024-05-03" },
  { id: 5, title: "Flexbox 布局完全指南", summary: "一文掌握弹性盒模型布局技巧。", category: "CSS", date: "2024-05-01" }
];

let activeCategory = "全部";
let keyword = "";

const searchInput = document.getElementById("blog-search");
const clearBtn = document.getElementById("clear-btn");
const catBar = document.getElementById("cat-bar");
const resultInfo = document.getElementById("result-info");
const cardsBox = document.getElementById("cards-box");

function highlight(text, kw) {
  if (!kw) return text;
  const escaped = kw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return text.replace(new RegExp(`(${escaped})`, "gi"), "<mark>$1</mark>");
}

function renderBlogSearch() {
  clearBtn.style.display = keyword ? "inline" : "none";
  const categories = ["全部", ...new Set(ARTICLES.map((a) => a.category))];
  catBar.innerHTML = "";
  categories.forEach((cat) => {
    const btn = document.createElement("button");
    btn.dataset.cat = cat;
    btn.className = activeCategory === cat ? "active" : "";
    btn.textContent = cat;
    btn.addEventListener("click", () => {
      activeCategory = cat;
      renderBlogSearch();
    });
    catBar.appendChild(btn);
  });

  let filtered = ARTICLES;
  if (activeCategory !== "全部") {
    filtered = filtered.filter((a) => a.category === activeCategory);
  }
  const kw = keyword.trim().toLowerCase();
  if (kw) {
    filtered = filtered.filter(
      (a) => a.title.toLowerCase().includes(kw) || a.summary.toLowerCase().includes(kw)
    );
  }

  resultInfo.textContent = `共 ${filtered.length} 篇${keyword ? `,搜索「${keyword}」` : ""}`;
  cardsBox.innerHTML = "";
  if (filtered.length === 0) {
    const p = document.createElement("p");
    p.className = "empty-tip";
    p.textContent = "没有找到匹配的文章";
    cardsBox.appendChild(p);
    return;
  }
  filtered.forEach((a) => {
    const card = document.createElement("div");
    card.className = "article-card";
    card.innerHTML = `<h3>${highlight(a.title, keyword.trim())}</h3><p>${highlight(a.summary, keyword.trim())}</p>`;
    cardsBox.appendChild(card);
  });
}

searchInput.addEventListener("input", (e) => {
  keyword = e.target.value;
  renderBlogSearch();
});

clearBtn.addEventListener("click", () => {
  keyword = "";
  searchInput.value = "";
  renderBlogSearch();
});

renderBlogSearch();
</script>
</body>
</html>
"""


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML)

        # Case 1: useEffect([keyword]) triggers on each keyword change
        page.locator("#watch-input").fill("H")
        page.locator("#watch-input").fill("Hook")
        c1_actual = {
            "watch_log": page.evaluate("() => window.__WATCH_LOG"),
            "watch_output": page.locator("#watch-output").inner_text(),
        }
        c1_expected = {
            "watch_log": ["H", "Hook"],
            "watch_output": "当前搜索:Hook",
        }
        cases.append({
            "name": "effect_dep_keyword_trigger",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        })

        # Case 2: Debounce cleanup cancels intermediate timers and fires once after 300ms
        c2_actual = page.evaluate("() => window.runDebounceSimulation()")
        c2_expected = {
            "clearedCount": 3,
            "midExecutions": [],
            "finalExecutions": ["React"],
            "debouncedKeyword": "React",
        }
        cases.append({
            "name": "debounce_cleanup_timer_reduction",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        })

        # Case 3: Combined category + case-insensitive keyword filter + highlight + empty state
        page.locator("#blog-search").fill("布局")
        layout_info = page.locator("#result-info").inner_text()
        layout_marks = page.locator("#cards-box mark").count()
        page.locator("#blog-search").fill("hooks")
        page.locator('#cat-bar button[data-cat="React"]').click()
        stacked_info = page.locator("#result-info").inner_text()
        stacked_titles = page.locator("#cards-box .article-card h3").all_inner_texts()
        page.locator('#cat-bar button[data-cat="CSS"]').click()
        stacked_empty = page.locator("#cards-box .empty-tip").inner_text()
        c3_actual = {
            "layout_info": layout_info,
            "layout_marks_positive": layout_marks > 0,
            "stacked_info": stacked_info,
            "stacked_titles": stacked_titles,
            "stacked_empty": stacked_empty,
        }
        c3_expected = {
            "layout_info": "共 2 篇,搜索「布局」",
            "layout_marks_positive": True,
            "stacked_info": "共 2 篇,搜索「hooks」",
            "stacked_titles": ["React 入门完全指南", "React Hooks 深入解析"],
            "stacked_empty": "没有找到匹配的文章",
        }
        cases.append({
            "name": "combined_category_and_keyword_filter",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        })

        # Case 4: Clear button visibility & reset
        page.locator('#cat-bar button[data-cat="全部"]').click()
        clear_visible_when_filled = page.locator("#clear-btn").is_visible()
        page.locator("#clear-btn").click()
        clear_visible_after_reset = page.locator("#clear-btn").is_visible()
        reset_info = page.locator("#result-info").inner_text()
        c4_actual = {
            "clear_visible_when_filled": clear_visible_when_filled,
            "clear_visible_after_reset": clear_visible_after_reset,
            "reset_info": reset_info,
            "input_val": page.locator("#blog-search").input_value(),
        }
        c4_expected = {
            "clear_visible_when_filled": True,
            "clear_visible_after_reset": False,
            "reset_info": "共 5 篇",
            "input_val": "",
        }
        cases.append({
            "name": "clear_button_resets_search",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        })

        browser.close()

    print(json.dumps({"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/react-blog-search-lab/explore-blog-search.py

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

下载课程关联工程包:React

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

下载课程关联工程包:React

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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