index.html 32 KB

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