"""Offline Playwright Chromium lab for jQuery EasyUI Ch 18: Dynamic Tabs."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI Dynamic Tabs Offline Lab</title>
<style>
body { font-family: sans-serif; margin: 12px; }
.toolbar { margin-bottom: 10px; }
.easyui-linkbutton { display: inline-block; padding: 4px 10px; margin-right: 6px; border: 1px solid #95b8e7; background: #eaf2ff; color: #0e2d5f; text-decoration: none; border-radius: 3px; cursor: pointer; }
.easyui-tabs { border: 1px solid #95b8e7; display: flex; flex-direction: column; box-sizing: border-box; }
.tabs-header { display: flex; background: #e0ecff; border-bottom: 1px solid #95b8e7; padding: 4px 4px 0; gap: 4px; }
.tabs-tab { display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border: 1px solid #95b8e7; border-bottom: none; background: #f4f8ff; cursor: pointer; font-size: 13px; }
.tabs-tab.tabs-selected { background: #fff; font-weight: 600; }
.tabs-close { border: none; background: transparent; cursor: pointer; font-size: 12px; color: #666; padding: 0 2px; }
.tabs-panels { flex: 1; position: relative; }
.tabs-panel { width: 100%; height: 100%; display: none; box-sizing: border-box; }
.tabs-panel.active { display: block; }
</style>
</head>
<body>
<div class="toolbar" style="margin-bottom:10px">
<a href="#" id="btn-google" class="easyui-linkbutton" onclick="addTab('google','data:text/html,<h1>Google Offline</h1>');return false;">google</a>
<a href="#" id="btn-jquery" class="easyui-linkbutton" onclick="addTab('jquery','data:text/html,<h1>jQuery Offline</h1>');return false;">jquery</a>
<a href="#" id="btn-easyui" class="easyui-linkbutton" onclick="addTab('easyui','data:text/html,<h1>EasyUI Offline</h1>');return false;">easyui</a>
</div>
<div id="tt" class="easyui-tabs" style="width:400px;height:250px;">
<div title="Home">Welcome Home</div>
</div>
<script>
(function(){
const container = document.getElementById('tt');
const initialDivs = Array.from(container.children);
container.innerHTML = '<div class="tabs-header"></div><div class="tabs-panels"></div>';
const header = container.querySelector('.tabs-header');
const panelsEl = container.querySelector('.tabs-panels');
const tabList = [];
let selectedTitle = null;
function renderSelect(title) {
selectedTitle = title;
tabList.forEach(item => {
const isSel = item.title === title;
item.tabEl.classList.toggle('tabs-selected', isSel);
item.panelEl.classList.toggle('active', isSel);
});
}
function closeTab(title) {
const idx = tabList.findIndex(t => t.title === title);
if (idx === -1) return;
const [removed] = tabList.splice(idx, 1);
removed.tabEl.remove();
removed.panelEl.remove();
if (selectedTitle === title) {
const next = tabList[Math.max(0, idx - 1)];
renderSelect(next ? next.title : null);
}
}
function createTab(opts) {
const tabEl = document.createElement('div');
tabEl.className = 'tabs-tab';
tabEl.dataset.title = opts.title;
const label = document.createElement('span');
label.textContent = opts.title;
tabEl.appendChild(label);
tabEl.addEventListener('click', () => renderSelect(opts.title));
if (opts.closable) {
const closeBtn = document.createElement('button');
closeBtn.type = 'button';
closeBtn.className = 'tabs-close';
closeBtn.textContent = '×';
closeBtn.dataset.closeTitle = opts.title;
closeBtn.addEventListener('click', e => {
e.stopPropagation();
closeTab(opts.title);
});
tabEl.appendChild(closeBtn);
}
const panelEl = document.createElement('div');
panelEl.className = 'tabs-panel';
panelEl.dataset.title = opts.title;
panelEl.innerHTML = opts.content || '';
header.appendChild(tabEl);
panelsEl.appendChild(panelEl);
tabList.push({ title: opts.title, closable: Boolean(opts.closable), tabEl, panelEl });
renderSelect(opts.title);
}
initialDivs.forEach(div => {
createTab({ title: div.getAttribute('title'), content: div.innerHTML, closable: div.getAttribute('closable') === 'true' });
});
window.tabsApi = {
exists(title) { return tabList.some(t => t.title === title); },
select(title) { if (this.exists(title)) renderSelect(title); },
add(opts) { createTab(opts); },
close(title) { closeTab(title); },
state() {
return {
titles: tabList.map(t => t.title),
closableMap: Object.fromEntries(tabList.map(t => [t.title, t.closable])),
selected: selectedTitle,
iframeCount: panelsEl.querySelectorAll('iframe').length,
};
}
};
window.addTab = function(title, url) {
if (window.tabsApi.exists(title)) {
window.tabsApi.select(title);
} else {
const content = '<iframe scrolling="auto" frameborder="0" src="' + url + '" style="width:100%;height:100%;"></iframe>';
window.tabsApi.add({ title: title, content: content, closable: true });
}
};
})();
</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)
page = browser.new_page(viewport={"width": 800, "height": 500})
page.set_content(HTML_DOC)
# Case 1: Initial Home tab & 3 linkbutton triggers
res1 = page.evaluate("""() => {
const box = document.getElementById('tt').getBoundingClientRect();
const btns = Array.from(document.querySelectorAll('.easyui-linkbutton')).map(a => a.textContent.trim());
const st = window.tabsApi.state();
return {
width: Math.round(box.width),
height: Math.round(box.height),
buttons: btns,
titles: st.titles,
selected: st.selected,
homeClosable: st.closableMap.Home,
};
}""")
exp1 = {
"width": 400,
"height": 250,
"buttons": ["google", "jquery", "easyui"],
"titles": ["Home"],
"selected": "Home",
"homeClosable": False,
}
cases.append(dict(name="initial_home_tab_and_add_buttons", expected=exp1, actual=res1, passed=(res1 == exp1)))
# Case 2: Dynamic add creates closable iframe tabs and activates latest
before_exists = page.evaluate("() => window.tabsApi.exists('jquery')")
page.click("#btn-jquery")
page.click("#btn-easyui")
res2 = page.evaluate("""(beforeExists) => {
const st = window.tabsApi.state();
const iframe = document.querySelector('.tabs-panel[data-title="jquery"] iframe');
return {
beforeExists,
afterExists: window.tabsApi.exists('jquery'),
titles: st.titles,
selected: st.selected,
closableMap: st.closableMap,
iframeCount: st.iframeCount,
iframeAttrs: {
scrolling: iframe.getAttribute('scrolling'),
frameborder: iframe.getAttribute('frameborder'),
widthStyle: iframe.style.width,
heightStyle: iframe.style.height,
}
};
}""", before_exists)
exp2 = {
"beforeExists": False,
"afterExists": True,
"titles": ["Home", "jquery", "easyui"],
"selected": "easyui",
"closableMap": {"Home": False, "jquery": True, "easyui": True},
"iframeCount": 2,
"iframeAttrs": {
"scrolling": "auto",
"frameborder": "0",
"widthStyle": "100%",
"heightStyle": "100%",
},
}
cases.append(dict(name="dynamic_add_iframe_tab_and_closable", expected=exp2, actual=res2, passed=(res2 == exp2)))
# Case 3: Duplicate click selects existing tab without duplicating; close button removes tab
page.click("#btn-jquery")
after_dup = page.evaluate("() => window.tabsApi.state()")
page.click('button.tabs-close[data-close-title="jquery"]')
after_close = page.evaluate("() => ({ state: window.tabsApi.state(), jqueryExists: window.tabsApi.exists('jquery') })")
res3 = {
"afterDuplicateTitles": after_dup["titles"],
"afterDuplicateSelected": after_dup["selected"],
"afterCloseTitles": after_close["state"]["titles"],
"afterCloseSelected": after_close["state"]["selected"],
"jqueryExistsAfterClose": after_close["jqueryExists"],
}
exp3 = {
"afterDuplicateTitles": ["Home", "jquery", "easyui"],
"afterDuplicateSelected": "jquery",
"afterCloseTitles": ["Home", "easyui"],
"afterCloseSelected": "Home",
"jqueryExistsAfterClose": False,
}
cases.append(dict(name="duplicate_tab_activates_and_close_removes", expected=exp3, actual=res3, passed=(res3 == exp3)))
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/jeasyui-layout-tabs2-lab/explore-layout-tabs2.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-layout-tabs2.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1004.zip