index.html 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Animal.js Documentation</title>
  7. <link rel="stylesheet" href="../xjs.css">
  8. <style>
  9. :root {
  10. --sidebar-bg: #111;
  11. --main-bg: #111;
  12. --border-color: #222;
  13. --text-color: #888;
  14. --text-hover: #ccc;
  15. --active-color: #ff4b4b; /* Red/Orange for active item */
  16. --header-color: #666;
  17. --middle-col-bg: #161616;
  18. --tree-line-color: #333;
  19. --accent-color: #ff9f43;
  20. }
  21. body {
  22. margin: 0;
  23. padding: 0;
  24. height: 100vh;
  25. display: flex;
  26. background: var(--main-bg);
  27. color: var(--text-color);
  28. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  29. overflow: hidden;
  30. font-size: 14px;
  31. }
  32. /* 1. LEFT SIDEBAR - MAIN NAVIGATION */
  33. .sidebar-left {
  34. width: 260px;
  35. background: var(--sidebar-bg);
  36. display: flex;
  37. flex-direction: column;
  38. overflow-y: auto;
  39. flex-shrink: 0;
  40. padding-bottom: 40px;
  41. }
  42. .logo-area {
  43. padding: 24px 20px;
  44. font-size: 18px;
  45. font-weight: bold;
  46. color: #fff;
  47. display: flex;
  48. align-items: center;
  49. gap: 10px;
  50. margin-bottom: 10px;
  51. }
  52. .logo-circle {
  53. width: 10px;
  54. height: 10px;
  55. background: #fff;
  56. border-radius: 50%;
  57. }
  58. /* Tree Structure */
  59. .nav-tree {
  60. padding: 0 20px;
  61. }
  62. .tree-group {
  63. margin-bottom: 5px;
  64. }
  65. .tree-header {
  66. padding: 8px 0;
  67. color: var(--header-color);
  68. font-weight: 600;
  69. cursor: pointer;
  70. transition: color 0.2s;
  71. display: flex;
  72. align-items: center;
  73. justify-content: space-between;
  74. }
  75. .tree-header:hover {
  76. color: var(--text-hover);
  77. }
  78. .tree-header.active-header {
  79. color: #e69f3c; /* Highlight parent if needed, usually just children */
  80. }
  81. .tree-children {
  82. padding-left: 14px; /* Indent */
  83. border-left: 1px solid var(--tree-line-color);
  84. margin-left: 2px;
  85. display: none; /* Collapsed by default */
  86. flex-direction: column;
  87. }
  88. .tree-children.expanded {
  89. display: flex;
  90. }
  91. .nav-item {
  92. display: block;
  93. padding: 6px 0 6px 15px;
  94. color: var(--text-color);
  95. text-decoration: none;
  96. cursor: pointer;
  97. transition: all 0.2s;
  98. position: relative;
  99. }
  100. .nav-item:hover {
  101. color: var(--text-hover);
  102. }
  103. /* Active Item Style (Reference: Red text, maybe red border left overlaying the gray line?) */
  104. .nav-item.active {
  105. color: var(--active-color);
  106. }
  107. /* Optional: Active marker on the left line */
  108. .nav-item.active::before {
  109. content: '';
  110. position: absolute;
  111. left: -1px; /* Overlap the border */
  112. top: 0;
  113. bottom: 0;
  114. width: 2px;
  115. background: var(--active-color);
  116. }
  117. /* Flat menu section title */
  118. .nav-section-title {
  119. margin-top: 18px;
  120. padding: 10px 0 6px 0;
  121. color: #7a7a7a;
  122. font-size: 11px;
  123. font-weight: 800;
  124. letter-spacing: 1px;
  125. text-transform: uppercase;
  126. opacity: 0.9;
  127. }
  128. /* Search Box in sidebar */
  129. .sidebar-search {
  130. margin: 0 20px 20px 20px;
  131. background: #1a1a1a;
  132. border: 1px solid #333;
  133. border-radius: 4px;
  134. padding: 8px 12px;
  135. color: #fff;
  136. font-size: 13px;
  137. cursor: pointer;
  138. }
  139. .sidebar-search:hover {
  140. border-color: #555;
  141. }
  142. /* 2. MIDDLE SIDEBAR */
  143. .sidebar-middle {
  144. width: 320px;
  145. background: var(--middle-col-bg);
  146. display: flex;
  147. flex-direction: column;
  148. overflow: hidden;
  149. flex-shrink: 0;
  150. }
  151. #middle-frame {
  152. width: 100%;
  153. height: 100%;
  154. border: none;
  155. background: transparent;
  156. }
  157. /* 3. RIGHT CONTENT */
  158. .content-right {
  159. flex: 1;
  160. display: flex;
  161. flex-direction: column;
  162. background: #000;
  163. overflow: hidden;
  164. }
  165. #content-frame {
  166. flex: 1;
  167. border: none;
  168. width: 100%;
  169. height: 100%;
  170. }
  171. /* Connection line between middle and right columns */
  172. .column-connection-line {
  173. position: fixed;
  174. inset: 0;
  175. width: 100vw;
  176. height: 100vh;
  177. pointer-events: none;
  178. z-index: 20;
  179. opacity: 0.85;
  180. }
  181. .column-connection-path {
  182. stroke: var(--accent-color);
  183. stroke-width: 2;
  184. stroke-dasharray: 6 6;
  185. stroke-linecap: round;
  186. fill: none;
  187. opacity: 0.35;
  188. animation: dashFlow 1.1s linear infinite;
  189. filter: drop-shadow(0 0 2px rgba(255, 159, 67, 0.25));
  190. }
  191. @keyframes dashFlow {
  192. to { stroke-dashoffset: -12; }
  193. }
  194. </style>
  195. </head>
  196. <body>
  197. <!-- 1. Left Sidebar -->
  198. <div class="sidebar-left">
  199. <div class="logo-area">
  200. <div class="logo-circle"></div>
  201. Animal.js
  202. </div>
  203. <div class="sidebar-search" onclick="selectCategory('search.html', 'test_on_update.html', null)">
  204. Search
  205. </div>
  206. <div class="nav-tree" aria-label="主菜单(扁平化)">
  207. <div class="nav-section-title">Animal.js 动画</div>
  208. <div class="nav-item active" data-list="targets/list.html" data-default="targets/overview.html" onclick="selectCategory('targets/list.html', 'targets/overview.html', this)">目标 Targets</div>
  209. <div class="nav-item" data-list="animatable_properties/list.html" data-default="animatable_properties/test_transforms.html" onclick="selectCategory('animatable_properties/list.html', 'animatable_properties/test_transforms.html', this)">可动画属性 Properties</div>
  210. <div class="nav-item" data-list="tween_value_types/list.html" data-default="tween_value_types/test_numerical.html" onclick="selectCategory('tween_value_types/list.html', 'tween_value_types/test_numerical.html', this)">补间值类型 Tween 值</div>
  211. <div class="nav-item" data-list="tween_parameters/list.html" data-default="tween_parameters/overview.html" onclick="selectCategory('tween_parameters/list.html', 'tween_parameters/overview.html', this)">补间参数 Tween 参数</div>
  212. <div class="nav-item" data-list="svg/list.html" data-default="svg/overview.html" onclick="selectCategory('svg/list.html', 'svg/overview.html', this)">SVG 动画</div>
  213. <div class="nav-item" data-list="list_callbacks.html" data-default="test_on_update.html" onclick="selectCategory('list_callbacks.html', 'test_on_update.html', this)">回调 Callbacks</div>
  214. <div class="nav-item" data-list="examples/list.html" data-default="examples/controls.html" onclick="selectCategory('examples/list.html', 'examples/controls.html', this)">示例 Examples</div>
  215. <div class="nav-section-title">Layer 弹窗</div>
  216. <div class="nav-item" data-list="layer/list.html" data-default="layer/overview.html" onclick="selectCategory('layer/list.html', 'layer/overview.html', this)">Layer API / Tests</div>
  217. <div class="nav-item" data-list="examples/list.html" data-default="examples/layer.html" onclick="selectCategory('examples/list.html', 'examples/layer.html', this)">交互示例(Layer + 动画)</div>
  218. <div class="nav-section-title">开发者</div>
  219. <div class="nav-item" data-list="search.html" data-default="module.html" onclick="selectCategory('search.html', 'module.html', this)">模块开发与测试指南</div>
  220. </div>
  221. </div>
  222. <!-- 2. Middle Sidebar -->
  223. <div class="sidebar-middle">
  224. <iframe id="middle-frame" src="targets/list.html"></iframe>
  225. </div>
  226. <!-- 3. Right Content -->
  227. <div class="content-right">
  228. <iframe id="content-frame" src="targets/test_css_selector.html"></iframe>
  229. </div>
  230. <!-- SVG overlay for the middle→right connection line -->
  231. <svg id="column-connection-line" class="column-connection-line" aria-hidden="true">
  232. <path id="column-connection-path" class="column-connection-path" d=""></path>
  233. </svg>
  234. <script>
  235. // Bump this when you want to force-refresh iframe pages
  236. const DOC_CACHE_VERSION = '2';
  237. // =========================================================
  238. // URL state (hash routing)
  239. // - When navigating: write selected content page into URL: #p=<encoded>
  240. // - On refresh / back-forward: restore the same content page + sync left/middle
  241. // =========================================================
  242. let _docApplyingRoute = false;
  243. function ensureHtmlPath(u) {
  244. const n = normalizeDocUrl(u);
  245. if (!n) return null;
  246. return n.endsWith('.html') ? n : (n + '.html');
  247. }
  248. // New readable token:
  249. // - omit ".html"
  250. // - "/" becomes "_" (separator)
  251. // - existing "_" becomes "__" (escape), so it's reversible
  252. function routeTokenFromContentUrl(contentUrl) {
  253. let u = normalizeDocUrl(contentUrl);
  254. if (!u) return '';
  255. if (u.endsWith('.html')) u = u.slice(0, -5);
  256. // escape "_" first, then turn "/" into "_"
  257. return u.replace(/_/g, '__').replace(/\//g, '_');
  258. }
  259. function contentUrlFromRouteToken(token) {
  260. let t = String(token || '');
  261. if (!t) return null;
  262. // In case someone pasted an encoded token, be tolerant.
  263. try { t = decodeURIComponent(t); } catch {}
  264. // If it already looks like a path (legacy), keep it.
  265. if (t.includes('/')) return ensureHtmlPath(t);
  266. // Decode: "_" => "/", "__" => "_"
  267. let out = '';
  268. for (let i = 0; i < t.length; i++) {
  269. const ch = t[i];
  270. if (ch === '_') {
  271. if (t[i + 1] === '_') { out += '_'; i++; }
  272. else out += '/';
  273. } else {
  274. out += ch;
  275. }
  276. }
  277. return ensureHtmlPath(out);
  278. }
  279. function getRouteContentUrl() {
  280. const h = String(location.hash || '');
  281. if (!h) return null;
  282. const hash = h.startsWith('#') ? h.slice(1) : h;
  283. // Legacy-friendly:
  284. // - "#p=<encoded path>"
  285. // - "#/path/to/page.html"
  286. // New:
  287. // - "#layer_overview" / "#layer_test__confirm__flow"
  288. if (hash.startsWith('/')) {
  289. const p = hash.slice(1);
  290. return p ? ensureHtmlPath(p) : null;
  291. }
  292. if (hash.startsWith('p=')) {
  293. const params = new URLSearchParams(hash);
  294. const p = params.get('p');
  295. return p ? ensureHtmlPath(p) : null;
  296. }
  297. return contentUrlFromRouteToken(hash);
  298. }
  299. function setRouteContentUrl(contentUrl, { replace = false } = {}) {
  300. const token = routeTokenFromContentUrl(contentUrl);
  301. if (!token) return;
  302. const nextHash = '#' + token;
  303. if (location.hash === nextHash) return;
  304. if (replace) history.replaceState(null, '', nextHash);
  305. else location.hash = nextHash;
  306. }
  307. function baseDocPath(url) {
  308. return normalizeDocUrl(url);
  309. }
  310. function guessListUrlByContent(contentUrl) {
  311. const u = normalizeDocUrl(contentUrl);
  312. if (!u) return null;
  313. if (u === 'module.html' || u === 'search.html') return 'search.html';
  314. if (u === 'test_on_update.html') return 'list_callbacks.html';
  315. if (u.startsWith('targets/')) return 'targets/list.html';
  316. if (u.startsWith('animatable_properties/')) return 'animatable_properties/list.html';
  317. if (u.startsWith('tween_value_types/')) return 'tween_value_types/list.html';
  318. if (u.startsWith('tween_parameters/')) return 'tween_parameters/list.html';
  319. if (u.startsWith('svg/')) return 'svg/list.html';
  320. if (u.startsWith('layer/')) return 'layer/list.html';
  321. if (u.startsWith('examples/')) return 'examples/list.html';
  322. return null;
  323. }
  324. function syncLeftActiveByListUrl(listUrl, contentUrl) {
  325. const u = normalizeDocUrl(listUrl);
  326. if (!u) return;
  327. const items = Array.from(document.querySelectorAll('.nav-item'));
  328. items.forEach(i => i.classList.remove('active'));
  329. // Prefer exact (list + default) match, then fall back to first list match
  330. const normContent = normalizeDocUrl(contentUrl);
  331. const exact = items.find(i =>
  332. normalizeDocUrl(i.getAttribute('data-list')) === u &&
  333. normalizeDocUrl(i.getAttribute('data-default')) === normContent
  334. );
  335. const any = items.find(i => normalizeDocUrl(i.getAttribute('data-list')) === u);
  336. (exact || any)?.classList.add('active');
  337. }
  338. function ensureCategoryForContent(contentUrl) {
  339. const listUrl = guessListUrlByContent(contentUrl);
  340. if (!listUrl) return;
  341. // Left highlight
  342. syncLeftActiveByListUrl(listUrl, contentUrl);
  343. // Middle list
  344. const middleFrame = document.getElementById('middle-frame');
  345. if (middleFrame) {
  346. const current = baseDocPath(middleFrame.getAttribute('src') || '');
  347. if (current !== normalizeDocUrl(listUrl)) {
  348. middleFrame.src = withDocVersion(listUrl);
  349. }
  350. }
  351. }
  352. function selectCategory(listUrl, defaultContentUrl, el) {
  353. // 1. Highlight Nav Item
  354. document.querySelectorAll('.nav-item').forEach(item => item.classList.remove('active'));
  355. if (el) el.classList.add('active');
  356. // 2. Load Middle Column (List)
  357. const middleFrame = document.getElementById('middle-frame');
  358. const listUrlV = withDocVersion(listUrl);
  359. if (middleFrame.getAttribute('src') !== listUrlV) {
  360. middleFrame.src = listUrlV;
  361. }
  362. // 3. Load Right Column (Default Content)
  363. loadContent(defaultContentUrl, { updateRoute: true });
  364. }
  365. function withDocVersion(url) {
  366. const u = String(url || '');
  367. if (!u) return u;
  368. // keep explicit query params if present
  369. if (u.includes('?')) return u;
  370. return u + '?v=' + encodeURIComponent(DOC_CACHE_VERSION);
  371. }
  372. function loadContent(url, opts = {}) {
  373. const { updateRoute = true, replaceRoute = false } = opts || {};
  374. const contentFrame = document.getElementById('content-frame');
  375. const urlV = withDocVersion(url);
  376. if (contentFrame.getAttribute('src') !== urlV) {
  377. contentFrame.src = urlV;
  378. }
  379. // Keep middle list selection in sync when possible
  380. try {
  381. setMiddleActive(url);
  382. } catch {}
  383. // Keep left + middle category consistent even if navigation came from middle list / prev-next
  384. try {
  385. ensureCategoryForContent(url);
  386. } catch {}
  387. // Persist current selection in URL (so refresh stays on same page)
  388. if (updateRoute) {
  389. try { setRouteContentUrl(url, { replace: !!replaceRoute }); } catch {}
  390. }
  391. // Update connection line after navigation
  392. scheduleConnectionLineUpdate();
  393. }
  394. // Called by content iframe pages (and also internally after navigation)
  395. function setMiddleActive(contentUrl) {
  396. const middleFrame = document.getElementById('middle-frame');
  397. if (!middleFrame) return;
  398. const win = middleFrame.contentWindow;
  399. if (win && typeof win.setActiveByContentUrl === 'function') {
  400. win.setActiveByContentUrl(contentUrl);
  401. }
  402. // Update connection line when active item changes
  403. scheduleConnectionLineUpdate();
  404. }
  405. // =========================================================
  406. // Global Prev/Next(组内顺序 + 跨组跳转,由路由表统一驱动)
  407. // =========================================================
  408. const DOC_PAGES = [
  409. // Targets
  410. { group: 'Targets', title: 'Targets 概览', url: 'targets/overview.html' },
  411. { group: 'Targets', title: 'CSS Selector', url: 'targets/test_css_selector.html' },
  412. { group: 'Targets', title: 'DOM Elements', url: 'targets/test_dom_elements.html' },
  413. { group: 'Targets', title: 'JavaScript Objects', url: 'targets/test_js_objects.html' },
  414. { group: 'Targets', title: 'Array of targets', url: 'targets/test_array_targets.html' },
  415. // Animatable properties
  416. { group: 'Properties', title: 'Transforms', url: 'animatable_properties/test_transforms.html' },
  417. { group: 'Properties', title: 'CSS Properties', url: 'animatable_properties/test_css_props.html' },
  418. { group: 'Properties', title: 'CSS Variables', url: 'animatable_properties/test_css_vars.html' },
  419. { group: 'Properties', title: 'JS Properties', url: 'animatable_properties/test_js_props.html' },
  420. // Tween value types
  421. { group: 'Tween 值', title: 'Numerical', url: 'tween_value_types/test_numerical.html' },
  422. { group: 'Tween 值', title: 'Unit', url: 'tween_value_types/test_unit.html' },
  423. { group: 'Tween 值', title: 'Relative', url: 'tween_value_types/test_relative.html' },
  424. { group: 'Tween 值', title: 'Colors', url: 'tween_value_types/test_colors.html' },
  425. // Tween parameters
  426. { group: 'Tween 参数', title: 'Tween parameters 概览', url: 'tween_parameters/overview.html' },
  427. { group: 'Tween 参数', title: 'duration / delay', url: 'tween_parameters/test_duration_delay.html' },
  428. // SVG
  429. { group: 'SVG', title: 'SVG 概览', url: 'svg/overview.html' },
  430. { group: 'SVG', title: 'draw() 路径描边', url: 'svg/test_draw_path.html' },
  431. { group: 'SVG', title: 'Motion Path', url: 'svg/test_motion_path.html' },
  432. { group: 'SVG', title: 'SVG 属性动画', url: 'svg/test_svg_attributes.html' },
  433. { group: 'SVG', title: 'SVG transform', url: 'svg/test_svg_transforms.html' },
  434. { group: 'SVG', title: 'Morph(points)', url: 'svg/test_morph_points.html' },
  435. { group: 'SVG', title: 'Morph(path d)', url: 'svg/test_morph_path.html' },
  436. // Callbacks
  437. { group: 'Callbacks', title: 'onUpdate', url: 'test_on_update.html' },
  438. // Examples
  439. { group: 'Examples', title: 'Controls', url: 'examples/controls.html' },
  440. { group: 'Examples', title: 'Layer', url: 'examples/layer.html' },
  441. // Layer
  442. { group: 'Layer', title: 'Layer 概览', url: 'layer/overview.html' },
  443. { group: 'Layer', title: 'SVG Icon animation', url: 'layer/test_icons_svg_animation.html' },
  444. { group: 'Layer', title: 'Confirm flow', url: 'layer/test_confirm_flow.html' },
  445. { group: 'Layer', title: 'Selection.layer + dataset', url: 'layer/test_selection_layer_dataset.html' },
  446. { group: 'Layer', title: 'Static API / Builder API', url: 'layer/test_static_fire.html' },
  447. { group: 'Layer', title: 'DOM content + Step flow', url: 'layer/test_dom_steps.html' },
  448. // Developer
  449. { group: 'Developer', title: '模块开发与测试指南', url: 'module.html' }
  450. ];
  451. function normalizeDocUrl(url) {
  452. const raw = String(url || '');
  453. const noHash = raw.split('#')[0];
  454. const noQuery = noHash.split('?')[0];
  455. return String(noQuery || '')
  456. .replace(/^[#/]+/, '')
  457. .replace(/^\.\//, '')
  458. .replace(/^\/+/, '');
  459. }
  460. function docFindIndex(currentUrl) {
  461. const u = normalizeDocUrl(currentUrl);
  462. if (!u) return -1;
  463. return DOC_PAGES.findIndex(p => u === p.url || u.endsWith(p.url));
  464. }
  465. function docGetPrevNext(currentUrl) {
  466. const idx = docFindIndex(currentUrl);
  467. if (idx < 0) return { idx: -1, prev: null, next: null, current: null };
  468. const prev = (idx > 0) ? DOC_PAGES[idx - 1] : null;
  469. const next = (idx < DOC_PAGES.length - 1) ? DOC_PAGES[idx + 1] : null;
  470. return { idx, prev, next, current: DOC_PAGES[idx] };
  471. }
  472. function docNavigatePrev(currentUrl) {
  473. const { prev } = docGetPrevNext(currentUrl);
  474. if (prev) loadContent(prev.url);
  475. }
  476. function docNavigateNext(currentUrl) {
  477. const { next } = docGetPrevNext(currentUrl);
  478. if (next) loadContent(next.url);
  479. }
  480. // Expose to iframes (same origin)
  481. window.docGetPrevNext = docGetPrevNext;
  482. window.docNavigatePrev = docNavigatePrev;
  483. window.docNavigateNext = docNavigateNext;
  484. // =============================
  485. // Middle ↔ Right connection line
  486. // =============================
  487. const connectionSvg = document.getElementById('column-connection-line');
  488. const connectionPath = document.getElementById('column-connection-path');
  489. let _connRaf = 0;
  490. function scheduleConnectionLineUpdate() {
  491. if (_connRaf) return;
  492. _connRaf = requestAnimationFrame(() => {
  493. _connRaf = 0;
  494. updateConnectionLine();
  495. });
  496. }
  497. function getActiveElementInFrame(frameEl) {
  498. try {
  499. const doc = frameEl?.contentDocument;
  500. if (!doc) return null;
  501. // Middle list pages use .card.active / .header-card.active; fall back to .active
  502. return (
  503. doc.querySelector('.card.active') ||
  504. doc.querySelector('.header-card.active') ||
  505. doc.querySelector('.nav-item.active') ||
  506. doc.querySelector('.active')
  507. );
  508. } catch {
  509. return null;
  510. }
  511. }
  512. function getAnchorElementInContentFrame(frameEl) {
  513. try {
  514. const doc = frameEl?.contentDocument;
  515. if (!doc) return null;
  516. // Prefer a *visible* code area anchor (in-viewport), then fall back
  517. const candidates = [
  518. '.box-container .box-header',
  519. '.code-view.active, .html-view.active, .css-view.active',
  520. '.box-container',
  521. 'h1',
  522. '.container',
  523. 'body'
  524. ];
  525. for (const sel of candidates) {
  526. const el = doc.querySelector(sel);
  527. if (!el) continue;
  528. // If it's visible in the iframe viewport, use it; else keep looking
  529. const r = el.getBoundingClientRect();
  530. const vh = frameEl?.clientHeight || 0;
  531. if (!vh) return el;
  532. const visibleTop = Math.max(0, r.top);
  533. const visibleBottom = Math.min(vh, r.bottom);
  534. if (visibleBottom - visibleTop > 8) return el;
  535. }
  536. return doc.body;
  537. } catch {
  538. return null;
  539. }
  540. }
  541. function clamp(n, min, max) {
  542. return Math.min(Math.max(n, min), max);
  543. }
  544. function getVisibleCenterInFrame(frameEl, elRect) {
  545. const w = frameEl?.clientWidth || 0;
  546. const h = frameEl?.clientHeight || 0;
  547. if (!w || !h) return null;
  548. const visibleLeft = Math.max(0, elRect.left);
  549. const visibleRight = Math.min(w, elRect.right);
  550. const visibleTop = Math.max(0, elRect.top);
  551. const visibleBottom = Math.min(h, elRect.bottom);
  552. if (visibleRight - visibleLeft <= 1 || visibleBottom - visibleTop <= 1) {
  553. return null;
  554. }
  555. return {
  556. x: (visibleLeft + visibleRight) / 2,
  557. y: (visibleTop + visibleBottom) / 2
  558. };
  559. }
  560. function updateConnectionLine() {
  561. if (!connectionSvg || !connectionPath) return;
  562. const middleFrame = document.getElementById('middle-frame');
  563. const contentFrame = document.getElementById('content-frame');
  564. if (!middleFrame || !contentFrame) return;
  565. const midRect = middleFrame.getBoundingClientRect();
  566. const rightRect = contentFrame.getBoundingClientRect();
  567. const active = getActiveElementInFrame(middleFrame);
  568. const anchor = getAnchorElementInContentFrame(contentFrame);
  569. if (!active || !anchor) {
  570. connectionPath.setAttribute('d', '');
  571. connectionSvg.style.opacity = '0';
  572. return;
  573. }
  574. const activeRect = active.getBoundingClientRect();
  575. const anchorRect = anchor.getBoundingClientRect();
  576. // Use the *visible* part of the element within its iframe viewport
  577. const activeCenter = getVisibleCenterInFrame(middleFrame, activeRect);
  578. const anchorCenter = getVisibleCenterInFrame(contentFrame, anchorRect);
  579. if (!activeCenter || !anchorCenter) {
  580. // If either side isn't visible in its iframe, hide the line (prevents weird drifting)
  581. connectionPath.setAttribute('d', '');
  582. connectionSvg.style.opacity = '0';
  583. return;
  584. }
  585. // Convert iframe-viewport coordinates to parent viewport coordinates
  586. const startX = midRect.left + clamp(activeRect.right, 0, middleFrame.clientWidth);
  587. const startY = midRect.top + activeCenter.y;
  588. // Stop just before the content block (avoid entering the dark code area)
  589. const endX = rightRect.left + clamp(anchorRect.left - 2, 6, contentFrame.clientWidth - 12);
  590. const endY = rightRect.top + anchorCenter.y;
  591. // Draw an L-shaped polyline.
  592. // Keep the vertical segment aligned with the column divider (middle ↔ right).
  593. const dividerX = rightRect.left + 0.5; // half-pixel for crisper stroke alignment
  594. const x1 = Math.max(startX + 12, dividerX);
  595. const d = [
  596. `M ${startX} ${startY}`,
  597. `L ${x1} ${startY}`,
  598. `L ${x1} ${endY}`,
  599. `L ${endX} ${endY}`
  600. ].join(' ');
  601. connectionPath.setAttribute('d', d);
  602. connectionSvg.style.opacity = '0.85';
  603. }
  604. function attachFrameScrollListeners(frameEl) {
  605. if (!frameEl) return;
  606. const onScroll = () => {
  607. markFrameScrolling(frameEl);
  608. scheduleConnectionLineUpdate();
  609. };
  610. try {
  611. // Window scroll inside iframe
  612. frameEl.contentWindow?.addEventListener('scroll', onScroll, { passive: true });
  613. // Some pages scroll on document/body; capture to be safe
  614. frameEl.contentDocument?.addEventListener('scroll', onScroll, true);
  615. frameEl.contentDocument?.documentElement?.addEventListener?.('scroll', onScroll, { passive: true });
  616. frameEl.contentDocument?.body?.addEventListener?.('scroll', onScroll, { passive: true });
  617. } catch {}
  618. }
  619. const _scrollHideTimers = new WeakMap();
  620. function markFrameScrolling(frameEl) {
  621. try {
  622. const doc = frameEl?.contentDocument;
  623. if (!doc) return;
  624. doc.documentElement?.classList.add('scrolling');
  625. doc.body?.classList.add('scrolling');
  626. const prev = _scrollHideTimers.get(frameEl);
  627. if (prev) clearTimeout(prev);
  628. _scrollHideTimers.set(frameEl, setTimeout(() => {
  629. try {
  630. doc.documentElement?.classList.remove('scrolling');
  631. doc.body?.classList.remove('scrolling');
  632. } catch {}
  633. }, 500));
  634. } catch {}
  635. }
  636. // Always-on lightweight loop to keep the line aligned even
  637. // if iframe scroll events were missed due to timing.
  638. let _connLoopStarted = false;
  639. function startConnectionLineLoop() {
  640. if (_connLoopStarted) return;
  641. _connLoopStarted = true;
  642. const loop = () => {
  643. // Only bother when we have a path (avoids work when hidden)
  644. if (connectionPath?.getAttribute('d')) {
  645. scheduleConnectionLineUpdate();
  646. }
  647. requestAnimationFrame(loop);
  648. };
  649. requestAnimationFrame(loop);
  650. }
  651. // Make initial active state robust against iframe load ordering
  652. window.addEventListener('load', () => {
  653. // Restore route (if present) before doing any extra syncing
  654. try {
  655. const routeUrl = getRouteContentUrl();
  656. if (routeUrl) {
  657. _docApplyingRoute = true;
  658. ensureCategoryForContent(routeUrl);
  659. loadContent(routeUrl, { updateRoute: false });
  660. } else {
  661. // No route: persist current default content into URL (so first refresh is stable)
  662. const current = baseDocPath(document.getElementById('content-frame')?.getAttribute('src') || '');
  663. if (current) setRouteContentUrl(current, { replace: true });
  664. }
  665. } catch {}
  666. _docApplyingRoute = false;
  667. const contentFrame = document.getElementById('content-frame');
  668. const src = contentFrame?.getAttribute('src');
  669. if (src) setMiddleActive(src);
  670. const middleFrame = document.getElementById('middle-frame');
  671. if (middleFrame) {
  672. middleFrame.addEventListener('load', () => {
  673. const current = document.getElementById('content-frame')?.getAttribute('src');
  674. if (current) setMiddleActive(current);
  675. attachFrameScrollListeners(middleFrame);
  676. scheduleConnectionLineUpdate();
  677. });
  678. }
  679. if (contentFrame) {
  680. contentFrame.addEventListener('load', () => {
  681. const current = contentFrame.getAttribute('src');
  682. if (current) setMiddleActive(current);
  683. attachFrameScrollListeners(contentFrame);
  684. scheduleConnectionLineUpdate();
  685. });
  686. }
  687. // If the iframes were already loaded before we attached 'load' listeners,
  688. // still attach scroll listeners immediately.
  689. attachFrameScrollListeners(middleFrame);
  690. attachFrameScrollListeners(contentFrame);
  691. window.addEventListener('resize', scheduleConnectionLineUpdate, { passive: true });
  692. scheduleConnectionLineUpdate();
  693. startConnectionLineLoop();
  694. });
  695. // Back/forward + manual hash edits: restore selection
  696. window.addEventListener('hashchange', () => {
  697. if (_docApplyingRoute) return;
  698. const routeUrl = getRouteContentUrl();
  699. if (!routeUrl) return;
  700. _docApplyingRoute = true;
  701. try {
  702. ensureCategoryForContent(routeUrl);
  703. loadContent(routeUrl, { updateRoute: false });
  704. } finally {
  705. _docApplyingRoute = false;
  706. }
  707. });
  708. </script>
  709. </body>
  710. </html>