index.html 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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. // Developer
  448. { group: 'Developer', title: '模块开发与测试指南', url: 'module.html' }
  449. ];
  450. function normalizeDocUrl(url) {
  451. const raw = String(url || '');
  452. const noHash = raw.split('#')[0];
  453. const noQuery = noHash.split('?')[0];
  454. return String(noQuery || '')
  455. .replace(/^[#/]+/, '')
  456. .replace(/^\.\//, '')
  457. .replace(/^\/+/, '');
  458. }
  459. function docFindIndex(currentUrl) {
  460. const u = normalizeDocUrl(currentUrl);
  461. if (!u) return -1;
  462. return DOC_PAGES.findIndex(p => u === p.url || u.endsWith(p.url));
  463. }
  464. function docGetPrevNext(currentUrl) {
  465. const idx = docFindIndex(currentUrl);
  466. if (idx < 0) return { idx: -1, prev: null, next: null, current: null };
  467. const prev = (idx > 0) ? DOC_PAGES[idx - 1] : null;
  468. const next = (idx < DOC_PAGES.length - 1) ? DOC_PAGES[idx + 1] : null;
  469. return { idx, prev, next, current: DOC_PAGES[idx] };
  470. }
  471. function docNavigatePrev(currentUrl) {
  472. const { prev } = docGetPrevNext(currentUrl);
  473. if (prev) loadContent(prev.url);
  474. }
  475. function docNavigateNext(currentUrl) {
  476. const { next } = docGetPrevNext(currentUrl);
  477. if (next) loadContent(next.url);
  478. }
  479. // Expose to iframes (same origin)
  480. window.docGetPrevNext = docGetPrevNext;
  481. window.docNavigatePrev = docNavigatePrev;
  482. window.docNavigateNext = docNavigateNext;
  483. // =============================
  484. // Middle ↔ Right connection line
  485. // =============================
  486. const connectionSvg = document.getElementById('column-connection-line');
  487. const connectionPath = document.getElementById('column-connection-path');
  488. let _connRaf = 0;
  489. function scheduleConnectionLineUpdate() {
  490. if (_connRaf) return;
  491. _connRaf = requestAnimationFrame(() => {
  492. _connRaf = 0;
  493. updateConnectionLine();
  494. });
  495. }
  496. function getActiveElementInFrame(frameEl) {
  497. try {
  498. const doc = frameEl?.contentDocument;
  499. if (!doc) return null;
  500. // Middle list pages use .card.active / .header-card.active; fall back to .active
  501. return (
  502. doc.querySelector('.card.active') ||
  503. doc.querySelector('.header-card.active') ||
  504. doc.querySelector('.nav-item.active') ||
  505. doc.querySelector('.active')
  506. );
  507. } catch {
  508. return null;
  509. }
  510. }
  511. function getAnchorElementInContentFrame(frameEl) {
  512. try {
  513. const doc = frameEl?.contentDocument;
  514. if (!doc) return null;
  515. // Prefer a *visible* code area anchor (in-viewport), then fall back
  516. const candidates = [
  517. '.box-container .box-header',
  518. '.code-view.active, .html-view.active, .css-view.active',
  519. '.box-container',
  520. 'h1',
  521. '.container',
  522. 'body'
  523. ];
  524. for (const sel of candidates) {
  525. const el = doc.querySelector(sel);
  526. if (!el) continue;
  527. // If it's visible in the iframe viewport, use it; else keep looking
  528. const r = el.getBoundingClientRect();
  529. const vh = frameEl?.clientHeight || 0;
  530. if (!vh) return el;
  531. const visibleTop = Math.max(0, r.top);
  532. const visibleBottom = Math.min(vh, r.bottom);
  533. if (visibleBottom - visibleTop > 8) return el;
  534. }
  535. return doc.body;
  536. } catch {
  537. return null;
  538. }
  539. }
  540. function clamp(n, min, max) {
  541. return Math.min(Math.max(n, min), max);
  542. }
  543. function getVisibleCenterInFrame(frameEl, elRect) {
  544. const w = frameEl?.clientWidth || 0;
  545. const h = frameEl?.clientHeight || 0;
  546. if (!w || !h) return null;
  547. const visibleLeft = Math.max(0, elRect.left);
  548. const visibleRight = Math.min(w, elRect.right);
  549. const visibleTop = Math.max(0, elRect.top);
  550. const visibleBottom = Math.min(h, elRect.bottom);
  551. if (visibleRight - visibleLeft <= 1 || visibleBottom - visibleTop <= 1) {
  552. return null;
  553. }
  554. return {
  555. x: (visibleLeft + visibleRight) / 2,
  556. y: (visibleTop + visibleBottom) / 2
  557. };
  558. }
  559. function updateConnectionLine() {
  560. if (!connectionSvg || !connectionPath) return;
  561. const middleFrame = document.getElementById('middle-frame');
  562. const contentFrame = document.getElementById('content-frame');
  563. if (!middleFrame || !contentFrame) return;
  564. const midRect = middleFrame.getBoundingClientRect();
  565. const rightRect = contentFrame.getBoundingClientRect();
  566. const active = getActiveElementInFrame(middleFrame);
  567. const anchor = getAnchorElementInContentFrame(contentFrame);
  568. if (!active || !anchor) {
  569. connectionPath.setAttribute('d', '');
  570. connectionSvg.style.opacity = '0';
  571. return;
  572. }
  573. const activeRect = active.getBoundingClientRect();
  574. const anchorRect = anchor.getBoundingClientRect();
  575. // Use the *visible* part of the element within its iframe viewport
  576. const activeCenter = getVisibleCenterInFrame(middleFrame, activeRect);
  577. const anchorCenter = getVisibleCenterInFrame(contentFrame, anchorRect);
  578. if (!activeCenter || !anchorCenter) {
  579. // If either side isn't visible in its iframe, hide the line (prevents weird drifting)
  580. connectionPath.setAttribute('d', '');
  581. connectionSvg.style.opacity = '0';
  582. return;
  583. }
  584. // Convert iframe-viewport coordinates to parent viewport coordinates
  585. const startX = midRect.left + clamp(activeRect.right, 0, middleFrame.clientWidth);
  586. const startY = midRect.top + activeCenter.y;
  587. // Point into the code area a bit (not exactly at left edge)
  588. const endX = rightRect.left + clamp(anchorRect.left + 18, 12, contentFrame.clientWidth - 12);
  589. const endY = rightRect.top + anchorCenter.y;
  590. // Draw an L-shaped polyline.
  591. // Keep the vertical segment aligned with the column divider (middle ↔ right).
  592. const dividerX = rightRect.left + 0.5; // half-pixel for crisper stroke alignment
  593. const x1 = Math.max(startX + 12, dividerX);
  594. const d = [
  595. `M ${startX} ${startY}`,
  596. `L ${x1} ${startY}`,
  597. `L ${x1} ${endY}`,
  598. `L ${endX} ${endY}`
  599. ].join(' ');
  600. connectionPath.setAttribute('d', d);
  601. connectionSvg.style.opacity = '0.85';
  602. }
  603. function attachFrameScrollListeners(frameEl) {
  604. if (!frameEl) return;
  605. const onScroll = () => {
  606. markFrameScrolling(frameEl);
  607. scheduleConnectionLineUpdate();
  608. };
  609. try {
  610. // Window scroll inside iframe
  611. frameEl.contentWindow?.addEventListener('scroll', onScroll, { passive: true });
  612. // Some pages scroll on document/body; capture to be safe
  613. frameEl.contentDocument?.addEventListener('scroll', onScroll, true);
  614. frameEl.contentDocument?.documentElement?.addEventListener?.('scroll', onScroll, { passive: true });
  615. frameEl.contentDocument?.body?.addEventListener?.('scroll', onScroll, { passive: true });
  616. } catch {}
  617. }
  618. const _scrollHideTimers = new WeakMap();
  619. function markFrameScrolling(frameEl) {
  620. try {
  621. const doc = frameEl?.contentDocument;
  622. if (!doc) return;
  623. doc.documentElement?.classList.add('scrolling');
  624. doc.body?.classList.add('scrolling');
  625. const prev = _scrollHideTimers.get(frameEl);
  626. if (prev) clearTimeout(prev);
  627. _scrollHideTimers.set(frameEl, setTimeout(() => {
  628. try {
  629. doc.documentElement?.classList.remove('scrolling');
  630. doc.body?.classList.remove('scrolling');
  631. } catch {}
  632. }, 500));
  633. } catch {}
  634. }
  635. // Always-on lightweight loop to keep the line aligned even
  636. // if iframe scroll events were missed due to timing.
  637. let _connLoopStarted = false;
  638. function startConnectionLineLoop() {
  639. if (_connLoopStarted) return;
  640. _connLoopStarted = true;
  641. const loop = () => {
  642. // Only bother when we have a path (avoids work when hidden)
  643. if (connectionPath?.getAttribute('d')) {
  644. scheduleConnectionLineUpdate();
  645. }
  646. requestAnimationFrame(loop);
  647. };
  648. requestAnimationFrame(loop);
  649. }
  650. // Make initial active state robust against iframe load ordering
  651. window.addEventListener('load', () => {
  652. // Restore route (if present) before doing any extra syncing
  653. try {
  654. const routeUrl = getRouteContentUrl();
  655. if (routeUrl) {
  656. _docApplyingRoute = true;
  657. ensureCategoryForContent(routeUrl);
  658. loadContent(routeUrl, { updateRoute: false });
  659. } else {
  660. // No route: persist current default content into URL (so first refresh is stable)
  661. const current = baseDocPath(document.getElementById('content-frame')?.getAttribute('src') || '');
  662. if (current) setRouteContentUrl(current, { replace: true });
  663. }
  664. } catch {}
  665. _docApplyingRoute = false;
  666. const contentFrame = document.getElementById('content-frame');
  667. const src = contentFrame?.getAttribute('src');
  668. if (src) setMiddleActive(src);
  669. const middleFrame = document.getElementById('middle-frame');
  670. if (middleFrame) {
  671. middleFrame.addEventListener('load', () => {
  672. const current = document.getElementById('content-frame')?.getAttribute('src');
  673. if (current) setMiddleActive(current);
  674. attachFrameScrollListeners(middleFrame);
  675. scheduleConnectionLineUpdate();
  676. });
  677. }
  678. if (contentFrame) {
  679. contentFrame.addEventListener('load', () => {
  680. const current = contentFrame.getAttribute('src');
  681. if (current) setMiddleActive(current);
  682. attachFrameScrollListeners(contentFrame);
  683. scheduleConnectionLineUpdate();
  684. });
  685. }
  686. // If the iframes were already loaded before we attached 'load' listeners,
  687. // still attach scroll listeners immediately.
  688. attachFrameScrollListeners(middleFrame);
  689. attachFrameScrollListeners(contentFrame);
  690. window.addEventListener('resize', scheduleConnectionLineUpdate, { passive: true });
  691. scheduleConnectionLineUpdate();
  692. startConnectionLineLoop();
  693. });
  694. // Back/forward + manual hash edits: restore selection
  695. window.addEventListener('hashchange', () => {
  696. if (_docApplyingRoute) return;
  697. const routeUrl = getRouteContentUrl();
  698. if (!routeUrl) return;
  699. _docApplyingRoute = true;
  700. try {
  701. ensureCategoryForContent(routeUrl);
  702. loadContent(routeUrl, { updateRoute: false });
  703. } finally {
  704. _docApplyingRoute = false;
  705. }
  706. });
  707. </script>
  708. </body>
  709. </html>