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

在离线 Chromium 中实测 Selectable 框选、Ctrl 多选、网格框选与 stop 序列化

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-example-selectable.py
explore-example-selectable.py199 行
"""Offline Chromium lab for jQuery UI Ch20: Selectable interactions (default, grid, serialize)."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Selectable Lab</title>
<style>
  * { box-sizing: border-box; }
  body { margin: 8px; font-family: sans-serif; user-select: none; }
  .ui-selecting { background: #FECA40 !important; }
  .ui-selected { background: #F39814 !important; color: white !important; }
  #sel-default, #sel-serialize { list-style: none; margin: 0 0 12px 0; padding: 0; width: 240px; }
  #sel-default li, #sel-serialize li { margin: 3px; padding: 4px 8px; height: 26px; border: 1px solid #bbb; background: #fff; }
  #sel-grid { list-style: none; margin: 0 0 12px 0; padding: 0; width: 440px; overflow: hidden; }
  #sel-grid li { margin: 3px; padding: 1px; float: left; width: 100px; height: 60px; font-size: 24px; text-align: center; line-height: 58px; border: 1px solid #bbb; background: #f8f8f8; }
  #lasso { position: fixed; border: 1px dashed #333; background: rgba(33,150,243,0.12); pointer-events: none; display: none; }
</style>
</head>
<body>
<ol id="sel-default">
  <li>Item 1</li><li>Item 2</li><li>Item 3</li><li>Item 4</li><li>Item 5</li><li>Item 6</li><li>Item 7</li>
</ol>

<ol id="sel-grid">
  <li>1</li><li>2</li><li>3</li><li>4</li>
  <li>5</li><li>6</li><li>7</li><li>8</li>
  <li>9</li><li>10</li><li>11</li><li>12</li>
</ol>

<p id="feedback"><span>您已经选择了:</span><span id="select-result">无</span></p>
<ol id="sel-serialize">
  <li>Item 1</li><li>Item 2</li><li>Item 3</li><li>Item 4</li><li>Item 5</li><li>Item 6</li>
</ol>
<div id="lasso"></div>

<script>
function rectIntersects(a, b) {
  return !(a.right < b.left || a.left > b.right || a.bottom < b.top || a.top > b.bottom);
}
function makeSelectable(ol, opts = {}) {
  const lasso = document.getElementById("lasso");
  let state = null;
  ol.addEventListener("mousedown", e => {
    const items = Array.from(ol.querySelectorAll("li"));
    const keepPrev = e.ctrlKey || e.metaKey;
    state = { sx: e.clientX, sy: e.clientY, keepPrev, moved: false, items };
    if (!keepPrev) {
      items.forEach(li => li.classList.remove("ui-selected", "ui-selecting"));
    }
    const targetLi = e.target.closest("li");
    if (targetLi && ol.contains(targetLi)) {
      targetLi.classList.add("ui-selecting");
      window.__sawSelectingClass = true;
    }
  });
  window.addEventListener("mousemove", e => {
    if (!state) return;
    if (Math.hypot(e.clientX - state.sx, e.clientY - state.sy) >= 3) {
      state.moved = true;
    }
    const left = Math.min(state.sx, e.clientX);
    const top = Math.min(state.sy, e.clientY);
    const width = Math.abs(e.clientX - state.sx);
    const height = Math.abs(e.clientY - state.sy);
    lasso.style.display = "block";
    lasso.style.left = left + "px";
    lasso.style.top = top + "px";
    lasso.style.width = width + "px";
    lasso.style.height = height + "px";
    const lr = { left, top, right: left + width, bottom: top + height };
    state.items.forEach(li => {
      const hit = rectIntersects(lr, li.getBoundingClientRect());
      if (hit) {
        li.classList.add("ui-selecting");
        window.__sawSelectingClass = true;
      } else {
        li.classList.remove("ui-selecting");
      }
    });
  });
  window.addEventListener("mouseup", () => {
    if (!state) return;
    const s = state;
    state = null;
    lasso.style.display = "none";
    s.items.forEach(li => {
      if (li.classList.contains("ui-selecting")) {
        li.classList.remove("ui-selecting");
        li.classList.add("ui-selected");
      }
    });
    if (opts.stop) opts.stop.call(ol);
  });
}

makeSelectable(document.getElementById("sel-default"));
makeSelectable(document.getElementById("sel-grid"));
makeSelectable(document.getElementById("sel-serialize"), {
  stop() {
    const result = document.getElementById("select-result");
    result.textContent = "";
    const all = Array.from(this.querySelectorAll("li"));
    const selected = Array.from(this.querySelectorAll(".ui-selected"));
    const tokens = selected.map(li => "#" + (all.indexOf(li) + 1));
    result.textContent = tokens.join(" ");
  }
});
</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(viewport={"width": 800, "height": 820})
            page.set_content(HTML)

            # Case 1: Default lasso + Ctrl+click multi-select + single click reset
            li2 = page.locator("#sel-default li").nth(1).bounding_box()
            li4 = page.locator("#sel-default li").nth(3).bounding_box()
            page.mouse.move(li2["x"] + 15, li2["y"] + 8)
            page.mouse.down()
            page.mouse.move(li4["x"] + 60, li4["y"] + 14, steps=4)
            page.mouse.up()
            after_lasso = page.evaluate("() => Array.from(document.querySelectorAll('#sel-default li.ui-selected')).map(e => e.textContent)")

            li6 = page.locator("#sel-default li").nth(5).bounding_box()
            page.keyboard.down("Control")
            page.mouse.click(li6["x"] + 20, li6["y"] + 10)
            page.keyboard.up("Control")
            after_ctrl = page.evaluate("() => Array.from(document.querySelectorAll('#sel-default li.ui-selected')).map(e => e.textContent)")

            li1 = page.locator("#sel-default li").nth(0).bounding_box()
            page.mouse.click(li1["x"] + 20, li1["y"] + 10)
            after_single = page.evaluate("() => Array.from(document.querySelectorAll('#sel-default li.ui-selected')).map(e => e.textContent)")
            saw_selecting = page.evaluate("() => Boolean(window.__sawSelectingClass)")

            r1 = {
                "sawSelecting": saw_selecting,
                "afterLasso": after_lasso,
                "afterCtrlClick": after_ctrl,
                "afterSingleClick": after_single,
            }
            exp1 = {
                "sawSelecting": True,
                "afterLasso": ["Item 2", "Item 3", "Item 4"],
                "afterCtrlClick": ["Item 2", "Item 3", "Item 4", "Item 6"],
                "afterSingleClick": ["Item 1"],
            }
            cases.append(dict(name="default_lasso_and_ctrl_multiselect", expected=exp1, actual=r1, passed=(r1 == exp1)))

            # Case 2: Grid layout 2x2 lasso (tiles 1, 2, 5, 6)
            t1 = page.locator("#sel-grid li").nth(0).bounding_box()
            t6 = page.locator("#sel-grid li").nth(5).bounding_box()
            page.mouse.move(t1["x"] + 20, t1["y"] + 15)
            page.mouse.down()
            page.mouse.move(t6["x"] + 50, t6["y"] + 30, steps=4)
            page.mouse.up()
            grid_selected = page.evaluate("() => Array.from(document.querySelectorAll('#sel-grid li.ui-selected')).map(e => e.textContent)")
            r2 = {"gridSelected": grid_selected}
            exp2 = {"gridSelected": ["1", "2", "5", "6"]}
            cases.append(dict(name="grid_layout_lasso_selection", expected=exp2, actual=r2, passed=(r2 == exp2)))

            # Case 3: Serialize stop callback
            s1 = page.locator("#sel-serialize li").nth(0).bounding_box()
            s3 = page.locator("#sel-serialize li").nth(2).bounding_box()
            page.mouse.move(s1["x"] + 20, s1["y"] + 10)
            page.mouse.down()
            page.mouse.move(s3["x"] + 60, s3["y"] + 14, steps=4)
            page.mouse.up()
            s5 = page.locator("#sel-serialize li").nth(4).bounding_box()
            page.keyboard.down("Control")
            page.mouse.click(s5["x"] + 20, s5["y"] + 10)
            page.keyboard.up("Control")
            r3 = {"serialized": page.locator("#select-result").text_content()}
            exp3 = {"serialized": "#1 #2 #3 #5"}
            cases.append(dict(name="serialize_stop_event_feedback", expected=exp3, actual=r3, passed=(r3 == exp3)))
        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/jqueryui-example-selectable-lab/explore-example-selectable.py

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

下载课程关联工程包:jQuery UI

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

下载课程关联工程包:jQuery UI

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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