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

在离线 Chromium 中验证 Sortable 列表/网格排序、跨列表联动、延迟占位符与门户组件

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-example-sortable.py
explore-example-sortable.py323 行
"""Offline Playwright Chromium lab for jQuery UI Ch 21: Sortable."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Sortable Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 16px; }
  ul { list-style: none; margin: 0; padding: 4px; border: 1px solid #ccc; }
  li { padding: 6px 10px; margin: 4px 0; background: #f4f4f4; border: 1px solid #aaa; cursor: move; }
  #grid { width: 450px; overflow: hidden; }
  #grid li { float: left; width: 100px; height: 90px; margin: 3px 3px 3px 0; box-sizing: border-box; text-align: center; line-height: 80px; }
  .connected { float: left; width: 150px; min-height: 60px; margin-right: 12px; }
  .ui-state-highlight { background: #fff3cd; border: 1px dashed #d39e00; }
  .ui-state-disabled { opacity: 0.45; cursor: not-allowed; }
  .tab-bar { display: flex; gap: 6px; margin-bottom: 6px; }
  .tab-btn { padding: 6px 12px; border: 1px solid #999; background: #eee; }
  .tab-btn.active { background: #cce5ff; font-weight: bold; }
  .tab-panel { display: none; }
  .tab-panel.active { display: block; }
  .columns { display: flex; gap: 12px; clear: both; margin-top: 12px; }
  .column { width: 170px; min-height: 120px; border: 1px solid #bbb; padding: 6px; }
  .portlet { border: 1px solid #888; margin-bottom: 8px; background: #fff; }
  .portlet-header { background: #e9ecef; padding: 4px 6px; display: flex; justify-content: space-between; }
  .portlet-content { padding: 6px; }
  .portlet-content.collapsed { display: none; }
</style>
</head>
<body>
<ul id="sortable">
  <li data-id="1">Item 1</li>
  <li data-id="2">Item 2</li>
  <li data-id="3">Item 3</li>
  <li data-id="4">Item 4</li>
  <li data-id="5">Item 5</li>
  <li data-id="6">Item 6</li>
  <li data-id="7">Item 7</li>
</ul>

<ul id="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>
</ul>

<div style="overflow:hidden;margin-top:8px;">
  <ul id="conn1" class="connected">
    <li>A1</li><li>A2</li><li>A3</li>
  </ul>
  <ul id="conn2" class="connected">
    <li>B1</li><li>B2</li>
  </ul>
  <ul id="empty-drop-true" class="connected"></ul>
  <ul id="empty-drop-false" class="connected"></ul>
</div>

<div id="tabs" style="margin-top:8px;">
  <div class="tab-bar">
    <button class="tab-btn active" data-tab="t1">Tab 1</button>
    <button class="tab-btn" data-tab="t2">Tab 2</button>
  </div>
  <div id="t1" class="tab-panel active">
    <ul id="tab-list-1"><li>T1-1</li><li>T1-2</li></ul>
  </div>
  <div id="t2" class="tab-panel">
    <ul id="tab-list-2"><li>T2-1</li></ul>
  </div>
</div>

<ul id="filter-items" style="margin-top:8px;">
  <li>Item 1</li>
  <li class="ui-state-disabled">Disabled A</li>
  <li class="ui-state-disabled">Disabled B</li>
  <li>Item 4</li>
</ul>

<ul id="filter-cancel" style="margin-top:8px;">
  <li>Item 1</li>
  <li class="ui-state-disabled">Cancel A</li>
  <li class="ui-state-disabled">Cancel B</li>
  <li>Item 4</li>
</ul>

<div class="columns">
  <div class="column" id="col1">
    <div class="portlet" data-p="feeds">
      <div class="portlet-header"><span>订阅</span><button class="portlet-toggle">-</button></div>
      <div class="portlet-content">Feeds body</div>
    </div>
    <div class="portlet" data-p="news">
      <div class="portlet-header"><span>新闻</span><button class="portlet-toggle">-</button></div>
      <div class="portlet-content">News body</div>
    </div>
  </div>
  <div class="column" id="col2">
    <div class="portlet" data-p="shop">
      <div class="portlet-header"><span>购物</span><button class="portlet-toggle">-</button></div>
      <div class="portlet-content">Shop body</div>
    </div>
  </div>
</div>

<script>
window.SortableLab = {
  moveItem(listId, fromIdx, toIdx) {
    const ul = document.getElementById(listId);
    const items = Array.from(ul.children);
    const el = items[fromIdx];
    const ref = items[toIdx];
    if (!el) return false;
    if (toIdx >= items.length) {
      ul.appendChild(el);
    } else if (fromIdx < toIdx) {
      ul.insertBefore(el, ref.nextSibling);
    } else {
      ul.insertBefore(el, ref);
    }
    return true;
  },
  connectTransfer(srcId, dstId, srcIdx, opts = {}) {
    const src = document.getElementById(srcId);
    const dst = document.getElementById(dstId);
    const dropOnEmpty = opts.dropOnEmpty !== undefined ? opts.dropOnEmpty : true;
    if (dst.children.length === 0 && !dropOnEmpty) {
      return { moved: false, reason: "dropOnEmpty_false" };
    }
    const el = src.children[srcIdx];
    if (!el) return { moved: false, reason: "missing" };
    dst.appendChild(el);
    return { moved: true };
  },
  dropOnTab(srcListId, itemIdx, targetTabId) {
    const src = document.getElementById(srcListId);
    const el = src.children[itemIdx];
    const dstPanel = document.getElementById(targetTabId);
    const dstList = dstPanel.querySelector("ul");
    dstList.appendChild(el);
    document.querySelectorAll(".tab-btn").forEach(b => b.classList.toggle("active", b.dataset.tab === targetTabId));
    document.querySelectorAll(".tab-panel").forEach(p => p.classList.toggle("active", p.id === targetTabId));
    return document.querySelector(".tab-btn.active").dataset.tab;
  },
  checkDelayAndDistance(elapsedMs, movedPx, cfg) {
    const timeOk = cfg.delay ? elapsedMs >= cfg.delay : true;
    const distOk = cfg.distance ? movedPx >= cfg.distance : true;
    return timeOk && distOk;
  },
  createPlaceholder(listId, cls, forceSize) {
    const ul = document.getElementById(listId);
    const first = ul.children[0];
    const h = first.getBoundingClientRect().height;
    const ph = document.createElement("li");
    ph.className = cls;
    ph.style.boxSizing = "border-box";
    if (forceSize) ph.style.height = h + "px";
    ul.insertBefore(ph, ul.children[1]);
    const phH = ph.getBoundingClientRect().height;
    const clsName = ph.className;
    ph.remove();
    return { className: clsName, heightMatches: Math.abs(phH - h) < 2 };
  },
  attemptFilterReorder(listId, mode, fromIdx, toIdx) {
    const ul = document.getElementById(listId);
    const items = Array.from(ul.children);
    const src = items[fromIdx];
    const dst = items[toIdx];
    const srcDisabled = src.classList.contains("ui-state-disabled");
    const dstDisabled = dst.classList.contains("ui-state-disabled");
    if (srcDisabled) return { moved: false, reason: "source_blocked" };
    if (mode === "items" && dstDisabled) return { moved: false, reason: "target_excluded" };
    if (fromIdx < toIdx) ul.insertBefore(src, dst.nextSibling);
    else ul.insertBefore(src, dst);
    return { moved: true };
  },
  movePortlet(portletName, targetColId, dragSelector) {
    if (dragSelector === ".portlet-toggle") return { moved: false, reason: "cancelled_handle" };
    if (dragSelector !== ".portlet-header") return { moved: false, reason: "wrong_handle" };
    const card = document.querySelector(`.portlet[data-p="${portletName}"]`);
    document.getElementById(targetColId).appendChild(card);
    return { moved: true };
  }
};

document.querySelectorAll(".portlet-toggle").forEach(btn => {
  btn.addEventListener("click", () => {
    const content = btn.closest(".portlet").querySelector(".portlet-content");
    const collapsed = content.classList.toggle("collapsed");
    btn.textContent = collapsed ? "+" : "-";
  });
});
</script>
</body>
</html>
"""


def main():
    cases = []
    with sync_playwright() as p:
        try:
            browser = p.chromium.launch(headless=True)
        except Exception:
            browser = p.chromium.launch(headless=True, channel="chrome")
        page = browser.new_page(viewport={"width": 1024, "height": 900})
        page.set_content(HTML_DOC)

        # Case 1: Default list reorder + float grid layout & reorder
        res1 = page.evaluate("""() => {
            SortableLab.moveItem("sortable", 0, 3);
            const listOrder = Array.from(document.querySelectorAll("#sortable li")).map(el => el.textContent);
            const gridRects = Array.from(document.querySelectorAll("#grid li")).slice(0, 5).map(el => {
                const r = el.getBoundingClientRect();
                return { top: Math.round(r.top), left: Math.round(r.left) };
            });
            const row1Count = gridRects.filter(r => r.top === gridRects[0].top).length;
            SortableLab.moveItem("grid", 0, 4);
            const gridHead = Array.from(document.querySelectorAll("#grid li")).slice(0, 5).map(el => el.textContent);
            return { listOrder, row1Count, gridHead };
        }""")
        exp1 = {
            "listOrder": ["Item 2", "Item 3", "Item 4", "Item 1", "Item 5", "Item 6", "Item 7"],
            "row1Count": 4,
            "gridHead": ["2", "3", "4", "5", "1"],
        }
        cases.append(dict(name="sortable_default_and_grid_reorder", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Connected lists + tab-connected list transfer
        res2 = page.evaluate("""() => {
            SortableLab.connectTransfer("conn1", "conn2", 0);
            const conn1 = Array.from(document.querySelectorAll("#conn1 li")).map(e => e.textContent);
            const conn2 = Array.from(document.querySelectorAll("#conn2 li")).map(e => e.textContent);
            const activeTab = SortableLab.dropOnTab("tab-list-1", 0, "t2");
            const t1 = Array.from(document.querySelectorAll("#tab-list-1 li")).map(e => e.textContent);
            const t2 = Array.from(document.querySelectorAll("#tab-list-2 li")).map(e => e.textContent);
            return { conn1, conn2, activeTab, t1, t2 };
        }""")
        exp2 = {
            "conn1": ["A2", "A3"],
            "conn2": ["B1", "B2", "A1"],
            "activeTab": "t2",
            "t1": ["T1-2"],
            "t2": ["T2-1", "T1-1"],
        }
        cases.append(dict(name="sortable_connected_lists_and_tabs", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Delay, distance, placeholder, and dropOnEmpty
        res3 = page.evaluate("""() => {
            const delayShort = SortableLab.checkDelayAndDistance(120, 40, { delay: 300 });
            const delayLong = SortableLab.checkDelayAndDistance(320, 40, { delay: 300 });
            const distShort = SortableLab.checkDelayAndDistance(50, 8, { distance: 15 });
            const distLong = SortableLab.checkDelayAndDistance(50, 20, { distance: 15 });
            const ph = SortableLab.createPlaceholder("sortable", "ui-state-highlight", true);
            const blockedEmpty = SortableLab.connectTransfer("conn1", "empty-drop-false", 0, { dropOnEmpty: false });
            const allowedEmpty = SortableLab.connectTransfer("conn1", "empty-drop-true", 0, { dropOnEmpty: true });
            const emptyTrueLen = document.querySelectorAll("#empty-drop-true li").length;
            const emptyFalseLen = document.querySelectorAll("#empty-drop-false li").length;
            return {
                delayShort, delayLong, distShort, distLong,
                placeholderClass: ph.className, heightMatches: ph.heightMatches,
                blockedEmpty: blockedEmpty.moved, allowedEmpty: allowedEmpty.moved,
                emptyTrueLen, emptyFalseLen
            };
        }""")
        exp3 = {
            "delayShort": False,
            "delayLong": True,
            "distShort": False,
            "distLong": True,
            "placeholderClass": "ui-state-highlight",
            "heightMatches": True,
            "blockedEmpty": False,
            "allowedEmpty": True,
            "emptyTrueLen": 1,
            "emptyFalseLen": 0,
        }
        cases.append(dict(name="sortable_delay_distance_placeholder_empty", expected=exp3, actual=res3, passed=(res3 == exp3)))

        # Case 4: items vs cancel exclusion & Portlets cross-column + collapse toggle
        page.click('#col1 .portlet[data-p="feeds"] .portlet-toggle')
        res4 = page.evaluate("""() => {
            const itemsDropOnDisabled = SortableLab.attemptFilterReorder("filter-items", "items", 0, 1);
            const itemsDragDisabled = SortableLab.attemptFilterReorder("filter-items", "items", 1, 3);
            const cancelDragDisabled = SortableLab.attemptFilterReorder("filter-cancel", "cancel", 1, 3);
            const cancelDropOnDisabled = SortableLab.attemptFilterReorder("filter-cancel", "cancel", 0, 1);
            const cancelOrder = Array.from(document.querySelectorAll("#filter-cancel li")).map(e => e.textContent);
            const portletCancel = SortableLab.movePortlet("news", "col2", ".portlet-toggle");
            const portletMove = SortableLab.movePortlet("news", "col2", ".portlet-header");
            const col2Cards = Array.from(document.querySelectorAll("#col2 .portlet")).map(e => e.dataset.p);
            const feedsCollapsed = document.querySelector('#col1 .portlet[data-p="feeds"] .portlet-content').classList.contains("collapsed");
            return {
                itemsDropOnDisabled: itemsDropOnDisabled.reason,
                itemsDragDisabled: itemsDragDisabled.reason,
                cancelDragDisabled: cancelDragDisabled.reason,
                cancelDropMoved: cancelDropOnDisabled.moved,
                cancelOrder,
                portletCancel: portletCancel.reason,
                portletMoved: portletMove.moved,
                col2Cards,
                feedsCollapsed
            };
        }""")
        exp4 = {
            "itemsDropOnDisabled": "target_excluded",
            "itemsDragDisabled": "source_blocked",
            "cancelDragDisabled": "source_blocked",
            "cancelDropMoved": True,
            "cancelOrder": ["Cancel A", "Item 1", "Cancel B", "Item 4"],
            "portletCancel": "cancelled_handle",
            "portletMoved": True,
            "col2Cards": ["shop", "news"],
            "feedsCollapsed": True,
        }
        cases.append(dict(name="sortable_items_cancel_and_portlets", expected=exp4, actual=res4, passed=(res4 == exp4)))

        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-sortable-lab/explore-example-sortable.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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