"""Offline Playwright Chromium lab for Foundation Ch 29 (joyride)."""
import json
from playwright.sync_api import sync_playwright
FOUNDATION_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; padding: 30px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 16px; color: #222; background: #fff; }
.stop-target { display: inline-block; margin: 20px 60px 60px 0; padding: 8px 14px; background: #f2f2f2; border: 1px solid #ddd; }
.joyride-list { display: none; }
.joyride-modal-bg {
display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0;
background: rgba(0, 0, 0, 0.5); z-index: 100;
}
.joyride-modal-bg.active { display: block; }
.joyride-tip-guide {
display: none; position: fixed; width: 300px; padding: 18px 20px 24px;
background: #333333; color: #ffffff; z-index: 101;
}
.joyride-tip-guide.active { display: block; }
.joyride-tip-guide h4 { margin: 0 0 8px; color: #ffffff; }
.joyride-tip-guide p { margin: 0 0 14px; font-size: 14px; line-height: 1.4; }
.joyride-next-tip {
display: inline-block; padding: 8px 14px; background: #008cba; color: #ffffff;
text-decoration: none; font-size: 14px; cursor: pointer;
}
.joyride-close-tip {
position: absolute; right: 12px; top: 10px; color: #777777; text-decoration: none;
font-size: 22px; line-height: 1; cursor: pointer;
}
"""
JOYRIDE_JS = """
window.foundationJoyride = (function() {
let guides = [];
let current = -1;
const bg = document.createElement('div');
bg.className = 'joyride-modal-bg';
document.body.appendChild(bg);
function hideAll() {
guides.forEach(g => g.el.classList.remove('active'));
bg.classList.remove('active');
current = -1;
}
function showStep(idx) {
guides.forEach(g => g.el.classList.remove('active'));
if (idx >= guides.length) {
hideAll();
return;
}
current = idx;
const item = guides[idx];
const g = item.el;
g.classList.add('active');
if (item.targetId) {
bg.classList.remove('active');
const target = document.getElementById(item.targetId);
const r = target.getBoundingClientRect();
g.style.left = Math.round(r.left) + 'px';
g.style.top = Math.round(r.bottom + 10) + 'px';
g.dataset.mode = 'anchored';
} else {
bg.classList.add('active');
const gw = g.getBoundingClientRect().width;
const gh = g.getBoundingClientRect().height;
g.style.left = Math.round((window.innerWidth - gw) / 2) + 'px';
g.style.top = Math.round((window.innerHeight - gh) / 2) + 'px';
g.dataset.mode = 'modal';
}
}
function start() {
guides.forEach(g => g.el.remove());
guides = [];
const list = document.querySelector('[data-joyride].joyride-list');
const items = Array.from(list.querySelectorAll('li'));
items.forEach((li, idx) => {
const tip = document.createElement('div');
tip.className = 'joyride-tip-guide';
tip.dataset.index = String(idx);
const btnText = li.getAttribute('data-button') || 'Next';
tip.innerHTML =
'<div class="joyride-content-wrapper">' +
li.innerHTML +
'<a href="#" class="joyride-next-tip">' + btnText + '</a>' +
'<a href="#" class="joyride-close-tip">×</a>' +
'</div>';
tip.querySelector('.joyride-next-tip').addEventListener('click', e => {
e.preventDefault();
showStep(idx + 1);
});
tip.querySelector('.joyride-close-tip').addEventListener('click', e => {
e.preventDefault();
hideAll();
});
document.body.appendChild(tip);
guides.push({ el: tip, targetId: li.getAttribute('data-id') });
});
showStep(0);
}
return { start, getCurrent: () => current };
})();
"""
HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_CSS}</style></head>
<body>
<h3 id="first" class="stop-target">First stop!</h3>
<h3 id="second" class="stop-target">Second stop!</h3>
<ol id="jr-list" class="joyride-list" data-joyride>
<li data-id="first">
<p>First stop. The ride has begun!</p>
</li>
<li data-id="second">
<h4>Second Stop</h4>
<p>Any valid HTML will work inside the Joyride.</p>
</li>
<li data-button="End">
<h4>End Stop</h4>
<p>The tour is over. You can either go back to the previous stop or close it.</p>
</li>
</ol>
<script>
{JOYRIDE_JS}
window.foundationJoyride.start();
</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": 900, "height": 600})
page.set_content(HTML_PAGE)
# Case 1: source list hidden & stop 0 anchored below #first
c1 = page.evaluate("""() => {
const listDisp = getComputedStyle(document.getElementById('jr-list')).display;
const t1 = document.getElementById('first').getBoundingClientRect();
const g0 = document.querySelector('.joyride-tip-guide[data-index="0"]');
const gr = g0.getBoundingClientRect();
return {
source_list_display: listDisp,
active_index: window.foundationJoyride.getCurrent(),
mode: g0.dataset.mode,
positioned_below_first: Math.round(gr.top) === Math.round(t1.bottom + 10),
aligned_left_with_first: Math.round(gr.left) === Math.round(t1.left),
button_label: g0.querySelector('.joyride-next-tip').textContent,
tip_bg: getComputedStyle(g0).backgroundColor,
};
}""")
exp1 = {
"source_list_display": "none",
"active_index": 0,
"mode": "anchored",
"positioned_below_first": True,
"aligned_left_with_first": True,
"button_label": "Next",
"tip_bg": "rgb(51, 51, 51)",
}
cases.append(dict(name="joyride_start_and_first_stop_anchor", passed=(c1 == exp1), expected=exp1, actual=c1))
# Case 2: next step -> stop 1 anchored below #second with rich HTML h4
page.click('.joyride-tip-guide[data-index="0"] .joyride-next-tip')
c2 = page.evaluate("""() => {
const t2 = document.getElementById('second').getBoundingClientRect();
const g0 = document.querySelector('.joyride-tip-guide[data-index="0"]');
const g1 = document.querySelector('.joyride-tip-guide[data-index="1"]');
const gr = g1.getBoundingClientRect();
return {
active_index: window.foundationJoyride.getCurrent(),
step0_hidden: getComputedStyle(g0).display === 'none',
step1_visible: getComputedStyle(g1).display === 'block',
positioned_below_second: Math.round(gr.top) === Math.round(t2.bottom + 10),
h4_heading: g1.querySelector('h4').textContent,
};
}""")
exp2 = {
"active_index": 1,
"step0_hidden": True,
"step1_visible": True,
"positioned_below_second": True,
"h4_heading": "Second Stop",
}
cases.append(dict(name="joyride_step_transition_and_html_content", passed=(c2 == exp2), expected=exp2, actual=c2))
# Case 3: stop 2 has no data-id -> modal mode + custom data-button="End"
page.click('.joyride-tip-guide[data-index="1"] .joyride-next-tip')
c3 = page.evaluate("""() => {
const g2 = document.querySelector('.joyride-tip-guide[data-index="2"]');
const bg = document.querySelector('.joyride-modal-bg');
const gr = g2.getBoundingClientRect();
return {
active_index: window.foundationJoyride.getCurrent(),
mode: g2.dataset.mode,
modal_bg_visible: getComputedStyle(bg).display === 'block',
centered_left: Math.round(gr.left),
button_label: g2.querySelector('.joyride-next-tip').textContent,
};
}""")
exp3 = {
"active_index": 2,
"mode": "modal",
"modal_bg_visible": True,
"centered_left": 300,
"button_label": "End",
}
cases.append(dict(name="joyride_modal_stop_without_data_id_and_custom_button", passed=(c3 == exp3), expected=exp3, actual=c3))
# Case 4: click End finishes tour & restart + close-tip cleanup
page.click('.joyride-tip-guide[data-index="2"] .joyride-next-tip')
after_end = page.evaluate("""() => ({
active_index: window.foundationJoyride.getCurrent(),
visible_guides: document.querySelectorAll('.joyride-tip-guide.active').length,
bg_visible: document.querySelector('.joyride-modal-bg').classList.contains('active'),
})""")
page.evaluate("() => window.foundationJoyride.start()")
page.click('.joyride-tip-guide[data-index="0"] .joyride-close-tip')
after_close = page.evaluate("""() => ({
active_index: window.foundationJoyride.getCurrent(),
visible_guides: document.querySelectorAll('.joyride-tip-guide.active').length,
})""")
c4 = {"after_end": after_end, "after_close_btn": after_close}
exp4 = {
"after_end": {"active_index": -1, "visible_guides": 0, "bg_visible": False},
"after_close_btn": {"active_index": -1, "visible_guides": 0},
}
cases.append(dict(name="joyride_finish_and_close_cleanup", passed=(c4 == exp4), expected=exp4, actual=c4))
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/foundation-joyride-lab/explore-joyride.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-joyride.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a739.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a757.zip