scrollcraft.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. /* ============================================================================
  2. scrollcraft: a scroll-driven interaction runtime
  3. ----------------------------------------------------------------------------
  4. Vanilla JS. Zero dependencies. Zero DOM generation.
  5. The engine does NOT build your page. You author real, semantic HTML and mark
  6. it up with data-sc-* attributes; the engine reads them and drives them from a
  7. single scroll value on a single rAF loop. That is deliberate: a runtime that
  8. generates its own DOM from a config object makes every site it touches look
  9. identical, which is the failure mode this replaces.
  10. ---------------------------------------------------------------------------
  11. ACTS: the unit of scroll time
  12. ---------------------------------------------------------------------------
  13. <section data-sc-act="pin" data-sc-span="2.5"> ... </section>
  14. data-sc-act scrub | pin | pan | flow (default: flow)
  15. data-sc-clip-map="travel" opts a pinned act OUT of full-life clip mapping.
  16. By DEFAULT a scrub clip is mapped across the stage's entire
  17. on-screen life, not across its pinned travel, because a pinned
  18. stage is visible for a viewport BEFORE the pin begins (sliding
  19. up into view) and a viewport AFTER it ends (sliding off the
  20. top). Mapped to pinned travel, the clip sits on its first
  21. frame through the whole entry and its last frame through the
  22. whole exit: the reader watches a still photograph while the
  23. page moves. Pair it with data-sc-dwell, which moves quickly at
  24. the edges and settles in the middle, so the fast motion lands
  25. on the two slides and the settle lands inside the pin where
  26. the copy is. data-sc-runout is accepted and ignored; it named
  27. the old opt-in for the exit half of this.
  28. data-sc-span viewport-heights of scroll this act owns. Pinned devices only
  29. (scrub/pin/pan). Default 1.5. The engine sets the outer
  30. height and sticks the first .sc-stage / [data-sc-stage] child.
  31. Every act exposes a normalized progress p (0..1):
  32. pinned p = (y - top) / (height - vh)
  33. flow p = (y + vh - top) / (height + vh)
  34. and publishes it as --sc-p on the act element, so CSS can read it too.
  35. ---------------------------------------------------------------------------
  36. DEVICES: what p drives
  37. ---------------------------------------------------------------------------
  38. data-sc-scrub on <video>. p scrubs currentTime. Blob-loaded, so
  39. it seeks without needing HTTP range support.
  40. data-sc-sequence="a/{i}.webp:120:1"
  41. on <canvas>. p scrubs an image sequence
  42. (path template : frameCount : startIndex).
  43. data-sc-pan="0.6" on a wide rail inside data-sc-act="pan". p drives
  44. horizontal travel. Value = extra travel multiplier.
  45. data-sc-parallax="-0.2" translateY by rate * act-progress * viewport.
  46. Negative = moves up faster than scroll (recedes).
  47. data-sc-cue="0.1 0.5" opacity/rise keyed to p. One value = enter+hold.
  48. Two = enter..leave. Add a third for the hold point.
  49. data-sc-kinetic="lines" lines | words | chars. Splits the element and
  50. staggers its reveal across the cue window.
  51. data-sc-reveal="up" up | down | left | right | iris. clip-path wipe.
  52. data-sc-count="0 4200" number bloom across the cue window.
  53. data-sc-in flow-section reveal, fires once on entry via
  54. IntersectionObserver (cheaper, and content that
  55. re-hides on scroll-up is a defect, not an effect).
  56. data-sc-stagger="60" on the parent staggers kids.
  57. data-sc-drift="#07090c" page background interpolates toward this colour
  58. while the act is on screen.
  59. ---------------------------------------------------------------------------
  60. WORLDFLIGHT: the page mode for one continuous flight
  61. ---------------------------------------------------------------------------
  62. <div data-sc-mode="worldflight" data-sc-seam="0.12">
  63. <div data-sc-world>
  64. <div data-sc-segment data-sc-w="1.4" data-sc-linger="0.3"
  65. data-sc-waypoint="Approach">
  66. <img class="sc-world__poster" src="p1.webp" alt="">
  67. <video data-sc-src="leg1.mp4" data-sc-src-mobile="leg1-m.mp4"></video>
  68. </div>
  69. ... more segments, in flight order ...
  70. </div>
  71. <div data-sc-world-copy>
  72. <div class="sc-world__scrim sc-scrim sc-scrim--band"></div>
  73. <div data-sc-copy data-sc-window="hero"> ... </div>
  74. <div data-sc-copy data-sc-window="0.34 0.56"> ... </div>
  75. <div data-sc-copy data-sc-window="finale"> ... </div>
  76. </div>
  77. <div data-sc-spacer aria-hidden="true"></div>
  78. </div>
  79. Acts cut the page into pinned blocks, which is the right shape for a page of
  80. chapters and the wrong shape for one continuous camera move: the reader hits
  81. the end of an act, the stage unsticks, a static page slides past, and the next
  82. act starts the whole thing again. Worldflight removes the seams by removing
  83. the blocks. There is ONE fixed stage for the entire page. The only element in
  84. document flow is a spacer, whose height the engine sets to the sum of the
  85. segment weights plus one viewport so the last flight can finish. Scroll drives
  86. the film timeline and the overlay opacity. Nothing else moves.
  87. data-sc-w viewport-heights this segment owns. Default 1.3.
  88. data-sc-linger dwell remap for this leg only (see lingerEase). Max 0.6.
  89. data-sc-seam crossfade band, in viewport-heights of scroll. Default 0.12.
  90. data-sc-waypoint label published on --sc-seg / the sc:waypoint event, so a
  91. page can draw its own route rail. The engine draws none.
  92. data-sc-window on a copy block: "hero" | "finale" | "from to [in [out]]"
  93. as fractions of the WHOLE track.
  94. Every clip stays mounted for the life of the page. Segments crossfade by
  95. opacity over the seam band; nothing ever swaps a src, because a src swap is a
  96. black frame and a black frame is the cut this mode exists to avoid.
  97. ---------------------------------------------------------------------------
  98. POINTER: interactivity that isn't scroll
  99. ---------------------------------------------------------------------------
  100. data-sc-tilt="8" 3D tilt toward the pointer, spring-damped, degrees.
  101. data-sc-magnet="0.35" element drifts toward the pointer inside its bounds.
  102. data-sc-spotlight publishes --sc-mx/--sc-my (0..1) for a light that
  103. follows the pointer across the surface.
  104. All three are gated to (hover: hover) and (pointer: fine) and disabled under
  105. prefers-reduced-motion. Touch never fires them.
  106. ---------------------------------------------------------------------------
  107. REDUCED MOTION
  108. ---------------------------------------------------------------------------
  109. Fewer and gentler, not zero. Cues still fade (comprehension survives), but
  110. translation collapses, video clips are never fetched (the poster holds), and
  111. pointer devices are inert. A worldflight still tells its whole story: the
  112. posters cross-dissolve through the same seams and the same copy windows.
  113. ---------------------------------------------------------------------------
  114. THE PLAYHEAD
  115. ---------------------------------------------------------------------------
  116. Every scrub clip on the page, act or worldflight, is driven by one smoothed
  117. playhead. Scroll only ever writes a TARGET; a standalone rAF loop walks the
  118. current time toward it at a fixed fraction per frame (data-sc-lerp, default
  119. 0.18; 1.0 under reduced motion, which is no smoothing at all). Writes are
  120. gated by a deadband and skipped while the decoder is still seeking. Without
  121. the smoothing a trackpad flick reads as a stutter, because wheel events do
  122. not arrive at a constant rate and a 1:1 write reproduces every gap in them.
  123. ========================================================================== */
  124. (function (global) {
  125. 'use strict';
  126. var reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
  127. var fineMQ = matchMedia('(hover: hover) and (pointer: fine)');
  128. var smallMQ = matchMedia('(max-width: 860px)');
  129. var coarse = matchMedia('(hover: none) and (pointer: coarse)').matches;
  130. var isMobile = function () { return coarse || smallMQ.matches; };
  131. var clamp = function (x, a, b) { return x < a ? a : x > b ? b : x; };
  132. var clamp01 = function (x) { return clamp(x, 0, 1); };
  133. var smooth = function (x) { x = clamp01(x); return x * x * (3 - 2 * x); };
  134. var lerp = function (a, b, t) { return a + (b - a) * t; };
  135. // Monotone dwell remap. Settles the camera mid-act (where the copy peaks) and
  136. // moves quicker at the edges. f(0)=0 and f(1)=1 always, so seam frames between
  137. // consecutive clips are untouched and the chain stays invisible.
  138. function dwell(x, L) {
  139. if (!L) return x;
  140. L = clamp01(L);
  141. var c = x - 0.5;
  142. return (1 - L) * x + L * (4 * c * c * c + 0.5);
  143. }
  144. // Same curve, capped harder, and used per worldflight segment. Above ~0.6 the
  145. // derivative at the midpoint gets low enough that the camera visibly stops
  146. // dead mid-leg, which reads as a stall rather than a hold. The endpoints are
  147. // fixed by construction: f(0)=0, f(1)=1, so the first and last frames of every
  148. // leg are still exactly the frames the seam law matched, and the chain between
  149. // legs stays invisible no matter how much dwell a leg asks for.
  150. function lingerEase(x, L) {
  151. if (!L) return x;
  152. L = clamp(L, 0, 0.6);
  153. var c = x - 0.5;
  154. return (1 - L) * x + L * (4 * c * c * c + 0.5);
  155. }
  156. // The lerp is a mechanism, not a taste knob. It is exposed so a page whose
  157. // clips are unusually short (where 0.18 lags behind the pointer) can tighten
  158. // it, and it is never read as 0: a 0 lerp is a playhead that never moves.
  159. function lerpRate(el) {
  160. var v = parseFloat(el && el.getAttribute && el.getAttribute('data-sc-lerp'));
  161. return isNaN(v) || v <= 0 ? 0 : clamp(v, 0.02, 1);
  162. }
  163. // ---- colour -------------------------------------------------------------
  164. function parseColor(str) {
  165. str = (str || '').trim();
  166. var m = str.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
  167. if (m) {
  168. var h = m[1];
  169. if (h.length === 3) h = h[0] + h[0] + h[1] + h[1] + h[2] + h[2];
  170. return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
  171. }
  172. m = str.match(/rgba?\(([^)]+)\)/i);
  173. if (m) {
  174. var p = m[1].split(/[,\s/]+/).filter(Boolean).map(parseFloat);
  175. return [p[0], p[1], p[2]];
  176. }
  177. return null;
  178. }
  179. function mixColor(a, b, t) {
  180. return 'rgb(' + Math.round(lerp(a[0], b[0], t)) + ',' +
  181. Math.round(lerp(a[1], b[1], t)) + ',' +
  182. Math.round(lerp(a[2], b[2], t)) + ')';
  183. }
  184. // ---- text splitting -----------------------------------------------------
  185. // Wraps each unit in a masked span so the reveal can slide from behind a clean
  186. // edge instead of just fading. Lines are measured after layout, so this must
  187. // run once fonts are ready or the line boxes are wrong.
  188. function splitText(el, mode) {
  189. if (el.__scSplit) return el.__scSplit;
  190. var text = el.textContent;
  191. var units = [];
  192. if (mode === 'chars' || mode === 'words') {
  193. var parts = mode === 'chars' ? Array.from(text) : text.split(/(\s+)/);
  194. el.textContent = '';
  195. parts.forEach(function (t) {
  196. if (/^\s+$/.test(t)) { el.appendChild(document.createTextNode(t)); return; }
  197. var mask = document.createElement('span');
  198. mask.className = 'sc-split';
  199. var inner = document.createElement('span');
  200. inner.className = 'sc-split__i';
  201. inner.textContent = t;
  202. mask.appendChild(inner);
  203. el.appendChild(mask);
  204. units.push(inner);
  205. });
  206. } else {
  207. // lines: wrap every word, measure offsetTop, regroup words into line spans
  208. var words = text.split(/\s+/).filter(Boolean);
  209. el.textContent = '';
  210. var probes = words.map(function (w, i) {
  211. var s = document.createElement('span');
  212. s.textContent = w;
  213. el.appendChild(s);
  214. if (i < words.length - 1) el.appendChild(document.createTextNode(' '));
  215. return s;
  216. });
  217. var lines = [], cur = null, lastTop = null;
  218. probes.forEach(function (s) {
  219. var top = s.offsetTop;
  220. if (lastTop === null || Math.abs(top - lastTop) > 1) { cur = []; lines.push(cur); lastTop = top; }
  221. cur.push(s.textContent);
  222. });
  223. el.textContent = '';
  224. lines.forEach(function (words, li) {
  225. var mask = document.createElement('span');
  226. mask.className = 'sc-split sc-split--line';
  227. var inner = document.createElement('span');
  228. inner.className = 'sc-split__i';
  229. inner.textContent = words.join(' ');
  230. mask.appendChild(inner);
  231. el.appendChild(mask);
  232. // Whitespace between the line spans. Without it the line boxes abut in
  233. // the text layer, so selecting and copying the heading yields
  234. // "even whenbreakfast" and a screen reader hears the same.
  235. if (li < lines.length - 1) el.appendChild(document.createTextNode(' '));
  236. units.push(inner);
  237. });
  238. }
  239. el.classList.add('sc-is-split');
  240. el.__scSplit = units;
  241. return units;
  242. }
  243. // ---- number formatting --------------------------------------------------
  244. function formatNum(v, template) {
  245. var decimals = 0;
  246. var dot = template.indexOf('.');
  247. if (dot > -1) decimals = template.length - dot - 1;
  248. var s = v.toFixed(decimals);
  249. if (/,/.test(template) || Math.abs(v) >= 10000) {
  250. var bits = s.split('.');
  251. bits[0] = bits[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  252. s = bits.join('.');
  253. }
  254. return s;
  255. }
  256. // =========================================================================
  257. function mount(root, opts) {
  258. root = typeof root === 'string' ? document.querySelector(root) : (root || document);
  259. opts = opts || {};
  260. var acts = [];
  261. var worlds = [];
  262. var drifts = [];
  263. var playheads = [];
  264. var scrollEls = [];
  265. var vh = innerHeight, vw = innerWidth;
  266. var y = 0, needsLayout = true;
  267. var progressBar = root.querySelector('[data-sc-progress]');
  268. var docEl = document.documentElement;
  269. // One rate for the page, overridable per clip. Read from the mount root, the
  270. // document element, or the option bag, in that order.
  271. var LERP = lerpRate(root.nodeType === 1 ? root : null) ||
  272. lerpRate(docEl) ||
  273. (opts.lerp > 0 ? clamp(opts.lerp, 0.02, 1) : 0) ||
  274. 0.18;
  275. // Every scrub clip on the page lives here, whatever drives it. tick() walks
  276. // this one list, so an act clip and a worldflight leg get the same playhead.
  277. function makeClip(v, host) {
  278. var rec = {
  279. el: v, host: host || v,
  280. ready: false, loading: false, painted: false,
  281. cur: 0, target: 0, live: false, stuckAt: 0,
  282. lerp: lerpRate(v) || LERP
  283. };
  284. v.muted = true; v.playsInline = true; v.preload = 'none';
  285. v.setAttribute('muted', ''); v.setAttribute('playsinline', '');
  286. playheads.push(rec);
  287. return rec;
  288. }
  289. // ---- collect acts -----------------------------------------------------
  290. Array.prototype.forEach.call(root.querySelectorAll('[data-sc-act]'), function (el) {
  291. var device = el.getAttribute('data-sc-act') || 'flow';
  292. var pinned = device === 'scrub' || device === 'pin' || device === 'pan';
  293. var act = {
  294. el: el,
  295. device: device,
  296. pinned: pinned,
  297. span: parseFloat(el.getAttribute('data-sc-span')) || (pinned ? 1.5 : 0),
  298. dwell: parseFloat(el.getAttribute('data-sc-dwell')) || 0,
  299. clipTravel: pinned && el.getAttribute('data-sc-clip-map') === 'travel',
  300. p: 0, raw: 0, top: 0, height: 0, live: false,
  301. cues: [], parallax: [], reveals: [], counts: [],
  302. video: null, seq: null, rail: null
  303. };
  304. if (pinned) {
  305. act.stage = el.querySelector('[data-sc-stage]') || el.querySelector('.sc-stage');
  306. if (act.stage) act.stage.classList.add('sc-stage');
  307. el.classList.add('sc-act--pinned');
  308. }
  309. // scrub video
  310. var v = el.querySelector('video[data-sc-scrub]');
  311. if (v) act.video = makeClip(v, el);
  312. // image sequence
  313. var cv = el.querySelector('canvas[data-sc-sequence]');
  314. if (cv) {
  315. var spec = cv.getAttribute('data-sc-sequence').split(':');
  316. act.seq = {
  317. el: cv, ctx: cv.getContext('2d', { alpha: false }),
  318. tpl: spec[0], count: parseInt(spec[1], 10) || 1, start: parseInt(spec[2], 10) || 0,
  319. frames: [], loaded: 0, drawn: -1
  320. };
  321. }
  322. // horizontal rail
  323. act.rail = el.querySelector('[data-sc-pan]');
  324. if (act.rail) act.railExtra = parseFloat(act.rail.getAttribute('data-sc-pan')) || 0;
  325. // cues
  326. Array.prototype.forEach.call(el.querySelectorAll('[data-sc-cue]'), function (c) {
  327. var nums = (c.getAttribute('data-sc-cue') || '').trim().split(/\s+/).map(parseFloat);
  328. // from [to [rampIn [rampOut]]]
  329. // rampIn/rampOut are fractions OF THE WINDOW, defaulting to 0.3 each.
  330. // That leaves a ~40% plateau at full opacity in the middle. Without a
  331. // plateau a cue is a triangle: it touches opacity 1 for a single
  332. // instant, so the reader has to stop on exactly the right pixel to see
  333. // the line at full strength, and every heading reads as slightly faded.
  334. var cue = {
  335. el: c,
  336. from: isNaN(nums[0]) ? 0 : nums[0],
  337. to: nums.length > 1 && !isNaN(nums[1]) ? nums[1] : null,
  338. rIn: nums.length > 2 && !isNaN(nums[2]) ? clamp01(nums[2]) : 0.3,
  339. rOut: nums.length > 3 && !isNaN(nums[3]) ? clamp01(nums[3]) : null,
  340. rise: parseFloat(c.getAttribute('data-sc-rise')),
  341. kinetic: c.getAttribute('data-sc-kinetic'),
  342. units: null, state: -1
  343. };
  344. if (cue.rOut === null) cue.rOut = (nums.length > 2 && !isNaN(nums[2])) ? 0.3 : 0.3;
  345. if (isNaN(cue.rise)) cue.rise = 1;
  346. act.cues.push(cue);
  347. });
  348. // parallax
  349. Array.prototype.forEach.call(el.querySelectorAll('[data-sc-parallax]'), function (c) {
  350. act.parallax.push({ el: c, rate: parseFloat(c.getAttribute('data-sc-parallax')) || 0 });
  351. });
  352. // reveals
  353. Array.prototype.forEach.call(el.querySelectorAll('[data-sc-reveal]'), function (c) {
  354. var nums = (c.getAttribute('data-sc-reveal-at') || '0 0.5').trim().split(/\s+/).map(parseFloat);
  355. act.reveals.push({ el: c, dir: c.getAttribute('data-sc-reveal') || 'up', from: nums[0] || 0, to: nums[1] || 0.5 });
  356. });
  357. // counters
  358. Array.prototype.forEach.call(el.querySelectorAll('[data-sc-count]'), function (c) {
  359. var nums = (c.getAttribute('data-sc-count') || '').trim().split(/\s+/);
  360. var at = (c.getAttribute('data-sc-count-at') || '0.1 0.55').trim().split(/\s+/).map(parseFloat);
  361. // Strip separators before parsing so the author can write the target
  362. // exactly as it should render. Without this, "0 3,500" parses the target
  363. // as 3 (the comma stops parseFloat) and "0 3500" renders "3500", because
  364. // formatNum only adds separators above 10,000. So any real figure between
  365. // 1,000 and 9,999 could not be shown the way it is written everywhere
  366. // else on the page. The template still drives the formatting.
  367. var num = function (s) { return parseFloat(String(s).replace(/,/g, '')) || 0; };
  368. act.counts.push({
  369. el: c, a: num(nums[0]), b: num(nums[1]),
  370. tpl: nums[1] || '0', from: at[0], to: at[1], last: null
  371. });
  372. });
  373. acts.push(act);
  374. var d = el.getAttribute('data-sc-drift');
  375. if (d) { var rgb = parseColor(d); if (rgb) drifts.push({ act: act, rgb: rgb }); }
  376. });
  377. // ---- collect worldflights --------------------------------------------
  378. Array.prototype.forEach.call(root.querySelectorAll('[data-sc-mode="worldflight"]'), function (el) {
  379. var W = {
  380. el: el,
  381. stage: el.querySelector('[data-sc-world]') || el.querySelector('.sc-world'),
  382. copyLayer: el.querySelector('[data-sc-world-copy]') || el.querySelector('.sc-world__copy'),
  383. spacer: el.querySelector('[data-sc-spacer]') || el.querySelector('.sc-world__spacer'),
  384. seam: 0, segs: [], copies: [], total: 0, top: 0, index: -1, checked: false
  385. };
  386. var seam = parseFloat(el.getAttribute('data-sc-seam'));
  387. // A seam wider than the shortest leg would have three clips dissolving at
  388. // once and no leg ever fully present. Cap it well under that.
  389. W.seam = isNaN(seam) || seam <= 0 ? 0.12 : clamp(seam, 0.02, 0.4);
  390. if (W.stage) W.stage.classList.add('sc-world');
  391. if (W.copyLayer) W.copyLayer.classList.add('sc-world__copy');
  392. if (W.spacer) W.spacer.classList.add('sc-world__spacer');
  393. Array.prototype.forEach.call(el.querySelectorAll('[data-sc-segment]'), function (s) {
  394. var seg = {
  395. el: s,
  396. w: parseFloat(s.getAttribute('data-sc-w')) || 1.3,
  397. linger: clamp(parseFloat(s.getAttribute('data-sc-linger')) || 0, 0, 0.6),
  398. label: s.getAttribute('data-sc-waypoint') || '',
  399. poster: s.querySelector('[data-sc-poster]') || s.querySelector('.sc-world__poster') || s.querySelector('img'),
  400. c0: 0, c1: 0, local: 0, op: -1, z: -1, clip: null
  401. };
  402. s.classList.add('sc-world__seg');
  403. if (seg.poster) seg.poster.classList.add('sc-world__poster');
  404. var v = s.querySelector('video');
  405. if (v) {
  406. // Mark it as a scrub clip whether or not the author did. Everything
  407. // downstream, the stylesheet and the verification harness included,
  408. // finds scrub media by this attribute.
  409. v.setAttribute('data-sc-scrub', '');
  410. seg.clip = makeClip(v, s);
  411. }
  412. W.segs.push(seg);
  413. });
  414. var run = 0;
  415. W.segs.forEach(function (s) { s.c0 = run; run += Math.max(s.w, 0.1); s.c1 = run; });
  416. W.total = Math.max(run, 0.001);
  417. Array.prototype.forEach.call(el.querySelectorAll('[data-sc-copy]'), function (cEl) {
  418. var spec = (cEl.getAttribute('data-sc-window') || '').trim();
  419. var q = { el: cEl, from: 0, to: 1, rIn: 0.3, rOut: 0.3, state: -1 };
  420. var first = W.segs[0], last = W.segs[W.segs.length - 1];
  421. if (spec === 'hero') {
  422. // Present the instant the reader lands. A hero that fades IN has to
  423. // fade in from nothing over an empty first screen, which is the one
  424. // moment on the page where there is nothing else to look at.
  425. q.from = 0;
  426. q.to = first ? (0.62 * first.w) / W.total : 0.3;
  427. q.rIn = 0; q.rOut = 0.65;
  428. } else if (spec === 'finale') {
  429. q.from = last ? (last.c0 + 0.4 * last.w) / W.total : 0.7;
  430. q.to = 1; q.rIn = 0.55; q.rOut = 0;
  431. } else {
  432. var n = spec.split(/\s+/).map(parseFloat);
  433. q.from = isNaN(n[0]) ? 0 : clamp01(n[0]);
  434. q.to = (n.length > 1 && !isNaN(n[1])) ? clamp01(n[1]) : clamp01(q.from + 0.18);
  435. if (n.length > 2 && !isNaN(n[2])) q.rIn = clamp01(n[2]);
  436. if (n.length > 3 && !isNaN(n[3])) q.rOut = clamp01(n[3]);
  437. }
  438. if (q.to <= q.from) q.to = clamp01(q.from + 0.05);
  439. W.copies.push(q);
  440. });
  441. worlds.push(W);
  442. });
  443. // ---- flow reveals (fire once) ----------------------------------------
  444. var io = null;
  445. if ('IntersectionObserver' in window) {
  446. io = new IntersectionObserver(function (entries) {
  447. entries.forEach(function (e) {
  448. if (!e.isIntersecting) return;
  449. var el = e.target;
  450. el.classList.add('sc-in');
  451. var stagger = parseFloat(el.getAttribute('data-sc-stagger'));
  452. if (!isNaN(stagger)) {
  453. Array.prototype.forEach.call(el.children, function (kid, i) {
  454. kid.style.transitionDelay = (i * stagger) + 'ms';
  455. kid.classList.add('sc-in');
  456. });
  457. }
  458. io.unobserve(el);
  459. });
  460. }, { rootMargin: '0px 0px -12% 0px', threshold: 0.01 });
  461. Array.prototype.forEach.call(root.querySelectorAll('[data-sc-in]'), function (el) { io.observe(el); });
  462. } else {
  463. Array.prototype.forEach.call(root.querySelectorAll('[data-sc-in]'), function (el) { el.classList.add('sc-in'); });
  464. }
  465. // ---- layout -----------------------------------------------------------
  466. function layout() {
  467. vh = innerHeight; vw = innerWidth;
  468. acts.forEach(function (a) {
  469. if (a.pinned) a.el.style.height = (a.span * 100) + 'vh';
  470. });
  471. // The spacer is the whole document flow of a worldflight. Its height is
  472. // the sum of the leg weights plus one viewport: without that extra screen
  473. // the track runs out at the moment the last leg reaches p=1, so the last
  474. // leg's final second is a place the reader can never actually stop.
  475. // Set in pixels, not vh, because .sc-world is sized in svh on phones and a
  476. // vh/svh mismatch would put the track and the stage on different rulers.
  477. worlds.forEach(function (W) {
  478. if (W.spacer) W.spacer.style.height = Math.round((W.total + 1) * vh) + 'px';
  479. });
  480. acts.forEach(function (a) {
  481. var r = a.el.getBoundingClientRect();
  482. a.top = r.top + scrollY;
  483. a.height = r.height;
  484. });
  485. if (acts.length) {
  486. acts.forEach(function (a) {
  487. if (a.seq && a.seq.el) {
  488. var box = a.seq.el.getBoundingClientRect();
  489. var dpr = Math.min(devicePixelRatio || 1, 2);
  490. a.seq.el.width = Math.round(box.width * dpr);
  491. a.seq.el.height = Math.round(box.height * dpr);
  492. a.seq.drawn = -1;
  493. }
  494. });
  495. }
  496. // A pinned act whose stage is not actually sticky fails silently: the
  497. // stage just scrolls by, the copy cues correctly against a frame nobody
  498. // can see, and every automated check passes. Any author rule that sets
  499. // `position` on the stage causes it. Say so.
  500. acts.forEach(function (a) {
  501. if (!a.pinned || !a.stage || a.stageChecked) return;
  502. a.stageChecked = true;
  503. var pos = getComputedStyle(a.stage).position;
  504. if (pos !== 'sticky' && pos !== '-webkit-sticky') {
  505. console.warn('[scrollcraft] act "' + (a.el.id || a.device) + '" will not pin: its stage computes ' +
  506. 'position:' + pos + ', not sticky. Something is overriding .sc-stage.', a.stage);
  507. }
  508. });
  509. worlds.forEach(function (W) {
  510. W.top = W.el.getBoundingClientRect().top + scrollY;
  511. if (W.checked) return;
  512. W.checked = true;
  513. if (!W.stage) {
  514. console.warn('[scrollcraft] worldflight has no [data-sc-world] stage; nothing will fly.', W.el);
  515. return;
  516. }
  517. if (!W.spacer) {
  518. console.warn('[scrollcraft] worldflight has no [data-sc-spacer]; the page has no scroll track.', W.el);
  519. }
  520. // The same silent failure as an unpinned act, one level worse: a stage
  521. // that is not fixed scrolls away and takes the whole page with it, while
  522. // every progress number still reads correctly.
  523. var wp = getComputedStyle(W.stage).position;
  524. if (wp !== 'fixed') {
  525. console.warn('[scrollcraft] worldflight stage computes position:' + wp + ', not fixed. ' +
  526. 'Something is overriding .sc-world, and the flight will scroll off screen.', W.stage);
  527. }
  528. });
  529. needsLayout = false;
  530. read();
  531. }
  532. // ---- video ------------------------------------------------------------
  533. function loadVideo(a) { loadClip(a.video); }
  534. function loadClip(V) {
  535. // Under reduced motion the clip is never fetched. The poster holds the
  536. // frame and the copy still cues, so the page reads without the decode.
  537. if (reduce || !V || V.loading) return;
  538. var src = V.el.getAttribute('data-sc-src') ||
  539. (isMobile() && V.el.getAttribute('data-sc-src-mobile')) ||
  540. V.el.currentSrc || V.el.src;
  541. if (isMobile() && V.el.getAttribute('data-sc-src-mobile')) src = V.el.getAttribute('data-sc-src-mobile');
  542. if (!src) return;
  543. V.loading = true;
  544. fetch(src).then(function (r) { if (!r.ok) throw new Error(r.status); return r.blob(); })
  545. .then(function (blob) {
  546. // Listeners and preload BEFORE src. Assigning src starts the load, so
  547. // attaching afterwards and then calling load() restarts it and aborts
  548. // the first request (visible as ERR_ABORTED on the blob URL).
  549. V.el.addEventListener('loadedmetadata', function () {
  550. V.ready = true;
  551. // Force one seek even when the target is already 0. The reveal is
  552. // gated on a 'seeked' event, and the raf loop only seeks when the
  553. // time actually needs to change, so a clip sitting at the very top
  554. // of its act would never seek, never fire 'seeked', and never
  555. // replace its poster until the reader scrolled it off zero.
  556. try { V.el.currentTime = Math.max(V.target * (V.el.duration || 1), 0.001); } catch (e) {}
  557. read();
  558. // Prime the decoder the moment the clip can be primed, without
  559. // waiting for a gesture. A muted inline play() is allowed with no
  560. // user activation on every platform except a restricted one (Low
  561. // Power Mode, data saver), and there the rejection is harmless: the
  562. // gesture listeners below retry on the next real touch.
  563. primeClip(V);
  564. });
  565. // Reveal only once a real frame has painted. iOS keeps a seeked-but-
  566. // never-played muted video blank, so hiding the poster on metadata
  567. // alone flashes an empty stage.
  568. var reveal = function () {
  569. if (V.painted) return;
  570. V.painted = true;
  571. V.host.classList.add('sc-has-clip');
  572. V.el.classList.add('sc-has-clip');
  573. };
  574. V.el.addEventListener('seeked', reveal, { once: true });
  575. // Never let visibility depend only on an event that may not arrive.
  576. // On iOS a clip that has not been played can accept a seek and never
  577. // fire 'seeked', which leaves the element at opacity 0 for the life of
  578. // the page: the poster stays up, the act looks frozen, and every later
  579. // act is fine because by then the reader has touched the screen and
  580. // the decoder is live. Reveal on a timer as well. A stage that is
  581. // briefly blank is a smaller fault than one that never shows its clip.
  582. setTimeout(reveal, 2500);
  583. V.el.preload = 'auto';
  584. V.el.muted = true; // as a property, not only an attribute
  585. V.el.playsInline = true;
  586. V.el.src = URL.createObjectURL(blob);
  587. })
  588. .catch(function () { V.loading = false; });
  589. }
  590. // ---- image sequence ---------------------------------------------------
  591. function loadSeq(a) {
  592. var S = a.seq;
  593. if (!S || S.frames.length) return;
  594. for (var i = 0; i < S.count; i++) {
  595. (function (i) {
  596. var img = new Image();
  597. img.decoding = 'async';
  598. img.src = S.tpl.replace('{i}', String(S.start + i))
  599. .replace('{ii}', String(S.start + i).padStart(2, '0'))
  600. .replace('{iii}', String(S.start + i).padStart(3, '0'))
  601. .replace('{iiii}', String(S.start + i).padStart(4, '0'));
  602. img.onload = function () { S.loaded++; if (S.loaded === 1) S.drawn = -1; };
  603. S.frames[i] = img;
  604. })(i);
  605. }
  606. }
  607. function drawSeq(a) {
  608. var S = a.seq;
  609. if (!S || !S.frames.length) return;
  610. var idx = clamp(Math.round(a.p * (S.count - 1)), 0, S.count - 1);
  611. if (idx === S.drawn) return;
  612. var img = S.frames[idx];
  613. if (!img || !img.complete || !img.naturalWidth) return;
  614. var cw = S.el.width, ch = S.el.height;
  615. // cover fit
  616. var scale = Math.max(cw / img.naturalWidth, ch / img.naturalHeight);
  617. var w = img.naturalWidth * scale, h = img.naturalHeight * scale;
  618. S.ctx.drawImage(img, (cw - w) / 2, (ch - h) / 2, w, h);
  619. S.drawn = idx;
  620. }
  621. // ---- worldflight ------------------------------------------------------
  622. // t is the position along the flight, measured in viewport-heights of
  623. // scroll, so every number here is in the same unit the author wrote the
  624. // weights in. There is no per-segment geometry to read: the stage never
  625. // moves, so nothing needs measuring on scroll.
  626. function readWorld(W) {
  627. if (!W.segs.length) return;
  628. var S = W.seam;
  629. var t = clamp((y - W.top) / Math.max(vh, 1), 0, W.total);
  630. var pr = t / W.total;
  631. var i, s;
  632. // The current leg is the last one whose crossfade has begun.
  633. var k = 0;
  634. for (i = 0; i < W.segs.length; i++) if (t >= W.segs[i].c0 - S / 2) k = i;
  635. for (i = 0; i < W.segs.length; i++) {
  636. s = W.segs[i];
  637. var local = clamp01((t - s.c0) / Math.max(s.w, 0.001));
  638. s.local = local;
  639. // Fetch a leg only while it is within reach. Loading the whole flight up
  640. // front is tens of megabytes before the first frame paints; loading it
  641. // on arrival means arriving at a poster.
  642. if (s.clip && t > s.c0 - 1.6 && t < s.c1 + 1.6) loadClip(s.clip);
  643. // Opacity. The incoming leg fades UP over the outgoing one, which holds
  644. // at full strength underneath until it is completely covered. Fading
  645. // both halves of a crossfade is what puts the page ground through the
  646. // middle of the seam and reads as a flash.
  647. var op;
  648. if (i > k) op = 0;
  649. else if (i === k) op = i === 0 ? 1 : smooth((t - (s.c0 - S / 2)) / S);
  650. else op = t < s.c1 + S / 2 ? 1 : 0;
  651. var z = i === k ? 120 : Math.round(100 + op * 10);
  652. if (op !== s.op) {
  653. s.el.style.opacity = op.toFixed(3);
  654. // A leg at zero must stop compositing entirely. Six full-bleed video
  655. // layers all painting at opacity 0 costs the same as painting them.
  656. s.el.style.visibility = op > 0.002 ? 'visible' : 'hidden';
  657. s.op = op;
  658. }
  659. if (z !== s.z) { s.el.style.zIndex = String(z); s.z = z; }
  660. if (s.clip) {
  661. s.clip.live = op > 0.002;
  662. s.clip.target = lingerEase(local, s.linger);
  663. }
  664. // Until a real frame has painted, the poster carries the move. A still
  665. // that sits perfectly still while the page scrolls announces itself as a
  666. // placeholder; a slow push in reads as the camera already flying.
  667. if (s.poster && !reduce && !(s.clip && s.clip.painted) && op > 0.002) {
  668. s.poster.style.transform = 'scale(' + (1.03 + local * 0.14).toFixed(4) + ')';
  669. }
  670. }
  671. for (var c = 0; c < W.copies.length; c++) {
  672. var q = W.copies[c];
  673. var win = Math.max(q.to - q.from, 0.001);
  674. var inEnd = q.from + win * q.rIn;
  675. var outStart = q.to - win * q.rOut;
  676. var vis;
  677. // A hero declares rIn 0, so inEnd sits exactly on `from` and the ramp
  678. // branch is skipped: the block is simply present from the first pixel.
  679. if (pr < q.from) vis = 0;
  680. else if (pr < inEnd) vis = smooth((pr - q.from) / Math.max(inEnd - q.from, 0.001));
  681. else if (pr <= outStart) vis = 1;
  682. else vis = smooth(1 - (pr - outStart) / Math.max(q.to - outStart, 0.001));
  683. vis = clamp01(vis);
  684. // The ONLY transform on the copy side, and it is capped at 4vh across
  685. // the whole window. Anything larger stops reading as a parallax layer
  686. // over a moving world and starts reading as a second page scrolling at a
  687. // different speed, which is the exact cheapness this mode replaces.
  688. var wp = clamp01((pr - q.from) / win);
  689. q.el.style.opacity = vis.toFixed(3);
  690. q.el.style.transform = reduce ? 'none'
  691. : 'translate3d(0,' + ((0.5 - wp) * 4).toFixed(2) + 'vh,0)';
  692. var on = vis > 0.5;
  693. if (on !== (q.state === 1)) { q.state = on ? 1 : 0; q.el.style.pointerEvents = on ? 'auto' : 'none'; }
  694. }
  695. // Publish the route, draw none of it. A gauge, a map, a leg counter and a
  696. // set of chapter dots are all the same two numbers, and a runtime that
  697. // ships one of them ships it to every page that uses this mode.
  698. var cur = W.segs[k];
  699. W.el.style.setProperty('--sc-seg', String(k));
  700. W.el.style.setProperty('--sc-segp', cur.local.toFixed(4));
  701. docEl.style.setProperty('--sc-seg', String(k));
  702. docEl.style.setProperty('--sc-segp', cur.local.toFixed(4));
  703. if (k !== W.index) {
  704. W.index = k;
  705. try {
  706. W.el.dispatchEvent(new CustomEvent('sc:waypoint', {
  707. bubbles: true,
  708. detail: { index: k, count: W.segs.length, label: cur.label, el: cur.el, progress: pr }
  709. }));
  710. } catch (e) {}
  711. }
  712. }
  713. // ---- per-frame scroll read -------------------------------------------
  714. function read() {
  715. y = scrollY || pageYOffset;
  716. var driftA = null, driftB = null, driftT = 0;
  717. var maxY = Math.max((document.documentElement.scrollHeight || 0) - vh, 1);
  718. for (var i = 0; i < acts.length; i++) {
  719. var a = acts[i];
  720. var raw;
  721. if (a.pinned) {
  722. var travel = Math.max(a.height - vh, 1);
  723. raw = clamp01((y - a.top) / travel);
  724. } else {
  725. raw = clamp01((y + vh - a.top) / (a.height + vh));
  726. }
  727. a.raw = raw;
  728. a.p = a.dwell ? dwell(raw, a.dwell) : raw;
  729. // Clip time is NOT cue time. Cues belong to the pin, so they keep using
  730. // `p`. The clip belongs to the stage, and the stage is on screen for one
  731. // viewport before the pin starts and one after it ends. Driving the clip
  732. // from `p` therefore parks it on frame one for the whole entry slide and
  733. // on its last frame for the whole exit slide, which is a still
  734. // photograph moving up the screen under the reader's hand.
  735. //
  736. // So map the clip across the stage's entire visible life instead. Both
  737. // ends are clamped to scroll that actually exists: an act at the top of
  738. // the document has no entry slide and must still start on frame one, and
  739. // an act near the bottom must still reach its last frame while the page
  740. // can still scroll.
  741. a.vp = a.p;
  742. if (a.pinned && !a.clipTravel) {
  743. var startY = a.top - Math.min(vh, a.top);
  744. var endY = Math.min(a.top + a.height, maxY);
  745. var vraw = clamp01((y - startY) / Math.max(endY - startY, 1));
  746. a.vp = a.dwell ? dwell(vraw, a.dwell) : vraw;
  747. }
  748. a.live = (y > a.top - vh * 1.25) && (y < a.top + a.height + vh * 1.25);
  749. a.el.style.setProperty('--sc-p', a.p.toFixed(4));
  750. // Fetch earlier than we drive. A 1080p clip is megabytes, and a reader
  751. // who scrolls briskly will otherwise arrive at a stage that is still
  752. // downloading and see a poster where the camera move should be.
  753. var warm = (y > a.top - vh * 3) && (y < a.top + a.height + vh * 1.5);
  754. if (warm) {
  755. if (a.video) loadVideo(a);
  756. if (a.seq) loadSeq(a);
  757. }
  758. if (a.live && a.seq) drawSeq(a);
  759. if (a.video) { a.video.live = a.live; if (a.video.ready) a.video.target = a.vp; }
  760. // horizontal rail
  761. if (a.rail) {
  762. var over = a.rail.scrollWidth - vw;
  763. if (over > 0) {
  764. var extra = over * (a.railExtra || 0);
  765. a.rail.style.transform = 'translate3d(' + (-(over + extra) * a.p).toFixed(2) + 'px,0,0)';
  766. }
  767. }
  768. if (!a.live) {
  769. // An act that scrolls out of range must release its cues rather than
  770. // freezing them at whatever they last were. A "hold" cue left at
  771. // opacity 1 keeps its element hit-testable and paintable long after
  772. // its act is gone, which shows up as a stray headline over a later
  773. // section. Zero once, then leave it alone.
  774. if (a.parked !== true) {
  775. for (var z = 0; z < a.cues.length; z++) {
  776. var pq = a.cues[z];
  777. pq.el.style.opacity = '0';
  778. pq.el.style.pointerEvents = 'none';
  779. pq.state = 0;
  780. if (pq.units) for (var zu = 0; zu < pq.units.length; zu++) pq.units[zu].style.opacity = '0';
  781. }
  782. a.parked = true;
  783. }
  784. continue;
  785. }
  786. a.parked = false;
  787. // cues
  788. for (var c = 0; c < a.cues.length; c++) {
  789. var q = a.cues[c];
  790. var vis;
  791. if (q.to === null) {
  792. vis = smooth((a.p - q.from) / 0.18);
  793. } else {
  794. var win = Math.max(q.to - q.from, 0.001);
  795. var inEnd = q.from + win * q.rIn; // full opacity from here
  796. var outStart = q.to - win * q.rOut; // starts leaving here
  797. if (a.p < inEnd) vis = smooth((a.p - q.from) / Math.max(inEnd - q.from, 0.001));
  798. else if (a.p <= outStart) vis = 1; // the plateau
  799. else vis = smooth(1 - (a.p - outStart) / Math.max(q.to - outStart, 0.001));
  800. }
  801. vis = clamp01(vis);
  802. if (q.kinetic) {
  803. if (!q.units) q.units = splitText(q.el, q.kinetic);
  804. var n = q.units.length;
  805. // Stagger across the reveal window. 0.62 spread leaves the tail of
  806. // the window for the last unit to finish, so the line lands together
  807. // rather than trickling.
  808. for (var u = 0; u < n; u++) {
  809. var uStart = (u / Math.max(n, 1)) * 0.62;
  810. var uv = clamp01((vis - uStart) / (1 - 0.62 + 0.001));
  811. uv = smooth(uv);
  812. q.units[u].style.opacity = uv.toFixed(3);
  813. q.units[u].style.transform = reduce ? 'none'
  814. : 'translate3d(0,' + ((1 - uv) * 100).toFixed(2) + '%,0)';
  815. }
  816. q.el.style.opacity = '1';
  817. } else {
  818. q.el.style.opacity = vis.toFixed(3);
  819. q.el.style.transform = reduce ? 'none'
  820. : 'translate3d(0,' + ((1 - vis) * 2.4 * q.rise).toFixed(2) + 'vh,0)';
  821. }
  822. var on = vis > 0.5;
  823. if (on !== (q.state === 1)) { q.state = on ? 1 : 0; q.el.style.pointerEvents = on ? 'auto' : 'none'; }
  824. }
  825. // parallax
  826. if (!reduce) {
  827. for (var pz = 0; pz < a.parallax.length; pz++) {
  828. var pp = a.parallax[pz];
  829. pp.el.style.transform = 'translate3d(0,' + (pp.rate * (a.p - 0.5) * 100).toFixed(2) + 'px,0)';
  830. }
  831. }
  832. // reveals
  833. for (var rv = 0; rv < a.reveals.length; rv++) {
  834. var R = a.reveals[rv];
  835. var t = smooth((a.p - R.from) / Math.max(R.to - R.from, 0.001));
  836. var pct = ((1 - t) * 100).toFixed(2);
  837. R.el.style.clipPath =
  838. R.dir === 'down' ? 'inset(' + pct + '% 0 0 0)' :
  839. R.dir === 'left' ? 'inset(0 ' + pct + '% 0 0)' :
  840. R.dir === 'right' ? 'inset(0 0 0 ' + pct + '%)' :
  841. R.dir === 'iris' ? 'circle(' + (t * 78).toFixed(2) + '% at 50% 50%)' :
  842. 'inset(0 0 ' + pct + '% 0)';
  843. }
  844. // counters
  845. for (var ct = 0; ct < a.counts.length; ct++) {
  846. var K = a.counts[ct];
  847. var kt = smooth((a.p - K.from) / Math.max(K.to - K.from, 0.001));
  848. var val = lerp(K.a, K.b, kt);
  849. var out = formatNum(val, K.tpl);
  850. if (out !== K.last) { K.el.textContent = out; K.last = out; }
  851. }
  852. }
  853. for (var w = 0; w < worlds.length; w++) readWorld(worlds[w]);
  854. // background drift
  855. for (var d = 0; d < drifts.length; d++) {
  856. var D = drifts[d];
  857. if (D.act.raw > 0 && D.act.raw < 1) {
  858. driftA = D; driftT = smooth(D.act.raw / 0.35);
  859. driftB = drifts[d - 1] || D;
  860. break;
  861. }
  862. if (D.act.raw >= 1) { driftA = D; driftB = D; driftT = 1; }
  863. }
  864. if (driftA) {
  865. docEl.style.setProperty('--sc-canvas', mixColor(driftB.rgb, driftA.rgb, driftT));
  866. }
  867. if (progressBar) {
  868. var max = Math.max(document.body.scrollHeight - vh, 1);
  869. progressBar.style.transform = 'scaleX(' + clamp01(y / max).toFixed(4) + ')';
  870. }
  871. }
  872. // ---- video seek loop --------------------------------------------------
  873. // Split from read() on purpose: seeking is asynchronous and rate-limited by
  874. // the decoder, while read() must stay cheap enough to run on every scroll
  875. // event. The lerp here is also what turns a jittery wheel into a glide.
  876. function tick() {
  877. // Deadband. A phone decoder cannot service a seek every frame, so asking
  878. // for one costs more than it shows; 20ms of clip is under a frame of
  879. // footage anyway.
  880. var eps = isMobile() ? 0.02 : 0.008;
  881. for (var i = 0; i < playheads.length; i++) {
  882. var V = playheads[i];
  883. if (!V.ready) continue;
  884. // Never queue a seek while the decoder is still resolving the last one.
  885. // On a phone a fast flick otherwise piles seeks up and freezes the clip.
  886. // But a seek that never completes would freeze the clip for the life of
  887. // the page through this very guard, so a seek stuck past 700ms is
  888. // re-issued rather than waited on forever.
  889. if (V.el.seeking) {
  890. var nw = performance.now();
  891. if (!V.stuckAt) V.stuckAt = nw;
  892. else if (nw - V.stuckAt > 700) {
  893. V.stuckAt = nw;
  894. try { V.el.currentTime = V.el.currentTime + 0.001; } catch (e) {}
  895. }
  896. continue;
  897. }
  898. V.stuckAt = 0;
  899. // An offscreen clip that has already arrived stops costing anything.
  900. if (!V.live && Math.abs(V.cur - V.target) < 0.002) continue;
  901. V.cur += (V.target - V.cur) * (reduce ? 1 : V.lerp);
  902. var dur = V.el.duration || 1;
  903. var t = clamp(V.cur, 0, 0.999) * dur;
  904. if (Math.abs(V.el.currentTime - t) > eps) { try { V.el.currentTime = t; } catch (e) {} }
  905. }
  906. requestAnimationFrame(tick);
  907. }
  908. // iOS will not paint a muted video that has never been handed a user
  909. // gesture, so a clip can be loaded, seeked and still show nothing.
  910. //
  911. // This used to fire once, on the first touch, across every playhead. That
  912. // loses a race it cannot win. The first act's clip is still being fetched
  913. // when the reader's first touch arrives (they touch the screen in order to
  914. // scroll, and the clip is megabytes) so play() is called on a video with
  915. // no source, does nothing, and the one shot is spent. Every later act loads
  916. // long after that touch, with user activation already granted, and works
  917. // without ever needing this. That is the exact shape of the bug: the hero
  918. // frozen, everything below it fine.
  919. //
  920. // So: keep listening, prime each clip once it actually has a source, and
  921. // stop only when they are all done. And force a seek afterwards, because a
  922. // primed decoder still shows the stale frame until something asks it for a
  923. // different time, and the deadband in tick() will not ask if the playhead is
  924. // already where it should be.
  925. var primedCount = 0;
  926. function primeClip(V) {
  927. // priming guards the retry: play() is a promise, and calling it again
  928. // while the last one is unsettled produces "interrupted by pause" and can
  929. // leave the element playing.
  930. if (V.primed || V.priming || !V.el.src) return;
  931. V.priming = true;
  932. var done = function () {
  933. V.priming = false;
  934. if (!V.primed) { V.primed = true; primedCount++; }
  935. try { V.el.pause(); } catch (e) {}
  936. // repaint: nudge past the deadband so the next tick writes for real
  937. try {
  938. var dur = V.el.duration || 1;
  939. V.cur = clamp(V.cur, 0, 0.999);
  940. V.el.currentTime = clamp(V.cur * dur + 0.05, 0, dur * 0.999);
  941. } catch (e) {}
  942. };
  943. var fail = function () { V.priming = false; };
  944. // A play() promise is allowed to stay pending forever (iOS does this to a
  945. // video it has decided not to start). If that happened here, `priming`
  946. // would jam and no gesture could ever retry, so the flag is released on a
  947. // timer as well. A late resolution after the release still lands in
  948. // done(), which is idempotent.
  949. setTimeout(function () { if (V.priming) fail(); }, 2000);
  950. var pr;
  951. try { pr = V.el.play(); } catch (e) { fail(); return; }
  952. if (pr && pr.then) pr.then(done, fail);
  953. else done();
  954. }
  955. function prime() {
  956. for (var i = 0; i < playheads.length; i++) primeClip(playheads[i]);
  957. if (playheads.length && primedCount >= playheads.length) {
  958. removeEventListener('touchstart', prime);
  959. removeEventListener('touchend', prime);
  960. removeEventListener('pointerdown', prime);
  961. removeEventListener('click', prime);
  962. removeEventListener('scroll', prime);
  963. }
  964. }
  965. // touchend and click are here because the HTML spec's list of activation-
  966. // triggering events includes touchend but NOT touchstart. A restricted
  967. // device (Low Power Mode) that rejects the touchstart prime for lacking
  968. // activation gets a second, valid chance the moment the finger lifts.
  969. addEventListener('touchstart', prime, { passive: true });
  970. addEventListener('touchend', prime, { passive: true });
  971. addEventListener('pointerdown', prime, { passive: true });
  972. addEventListener('click', prime, { passive: true });
  973. addEventListener('scroll', prime, { passive: true });
  974. // ---- pointer devices --------------------------------------------------
  975. var tilts = [], magnets = [], spots = [];
  976. function initPointer() {
  977. if (reduce || !fineMQ.matches) return;
  978. Array.prototype.forEach.call(root.querySelectorAll('[data-sc-tilt]'), function (el) {
  979. tilts.push({ el: el, max: parseFloat(el.getAttribute('data-sc-tilt')) || 6, x: 0, ty: 0, tx: 0, y: 0 });
  980. });
  981. Array.prototype.forEach.call(root.querySelectorAll('[data-sc-magnet]'), function (el) {
  982. magnets.push({ el: el, k: parseFloat(el.getAttribute('data-sc-magnet')) || 0.3, x: 0, y: 0, tx: 0, ty: 0 });
  983. });
  984. Array.prototype.forEach.call(root.querySelectorAll('[data-sc-spotlight]'), function (el) {
  985. spots.push(el);
  986. });
  987. if (!tilts.length && !magnets.length && !spots.length) return;
  988. addEventListener('pointermove', function (e) {
  989. if (e.pointerType !== 'mouse') return;
  990. for (var i = 0; i < tilts.length; i++) {
  991. var T = tilts[i], r = T.el.getBoundingClientRect();
  992. if (r.bottom < -200 || r.top > vh + 200) { T.tx = 0; T.ty = 0; continue; }
  993. var nx = (e.clientX - (r.left + r.width / 2)) / (r.width / 2);
  994. var ny = (e.clientY - (r.top + r.height / 2)) / (r.height / 2);
  995. var inside = Math.abs(nx) < 1.6 && Math.abs(ny) < 1.6;
  996. T.tx = inside ? clamp(ny, -1, 1) * -T.max : 0;
  997. T.ty = inside ? clamp(nx, -1, 1) * T.max : 0;
  998. }
  999. for (var m = 0; m < magnets.length; m++) {
  1000. var M = magnets[m], mr = M.el.getBoundingClientRect();
  1001. var dx = e.clientX - (mr.left + mr.width / 2);
  1002. var dy = e.clientY - (mr.top + mr.height / 2);
  1003. var near = Math.abs(dx) < mr.width && Math.abs(dy) < mr.height * 2.5;
  1004. M.tx = near ? dx * M.k : 0;
  1005. M.ty = near ? dy * M.k : 0;
  1006. }
  1007. for (var s = 0; s < spots.length; s++) {
  1008. var sr = spots[s].getBoundingClientRect();
  1009. spots[s].style.setProperty('--sc-mx', clamp01((e.clientX - sr.left) / sr.width).toFixed(3));
  1010. spots[s].style.setProperty('--sc-my', clamp01((e.clientY - sr.top) / sr.height).toFixed(3));
  1011. }
  1012. }, { passive: true });
  1013. (function pointerTick() {
  1014. // Interpolate toward the target rather than tracking the pointer
  1015. // directly. Direct tracking reads as artificial because it carries no
  1016. // momentum; the lerp gives it weight.
  1017. for (var i = 0; i < tilts.length; i++) {
  1018. var T = tilts[i];
  1019. T.x += (T.tx - T.x) * 0.09; T.y += (T.ty - T.y) * 0.09;
  1020. if (Math.abs(T.x) > 0.001 || Math.abs(T.y) > 0.001) {
  1021. T.el.style.transform = 'perspective(1100px) rotateX(' + T.x.toFixed(3) + 'deg) rotateY(' + T.y.toFixed(3) + 'deg)';
  1022. }
  1023. }
  1024. for (var m = 0; m < magnets.length; m++) {
  1025. var M = magnets[m];
  1026. M.x += (M.tx - M.x) * 0.12; M.y += (M.ty - M.y) * 0.12;
  1027. M.el.style.transform = 'translate3d(' + M.x.toFixed(2) + 'px,' + M.y.toFixed(2) + 'px,0)';
  1028. }
  1029. requestAnimationFrame(pointerTick);
  1030. })();
  1031. }
  1032. // ---- wiring -----------------------------------------------------------
  1033. var ticking = false;
  1034. addEventListener('scroll', function () {
  1035. if (!ticking) { ticking = true; requestAnimationFrame(function () { read(); ticking = false; }); }
  1036. }, { passive: true });
  1037. // Keyboard focus on a pinned or panning act. The browser's own
  1038. // scroll-into-view parks the focused element barely on screen, which is
  1039. // exactly the scroll position at which its cue has not opened yet, so focus
  1040. // lands on a control nobody can see and every automated opacity check still
  1041. // passes. Centring the act instead is a position where the cue is lit by
  1042. // definition. behavior:'instant' on purpose: scrollcraft.css sets
  1043. // scroll-behavior:smooth, so the default animates the jump and focus sits
  1044. // off screen for the whole of a multi-screen glide.
  1045. addEventListener('focusin', function (e) {
  1046. var el = e.target;
  1047. if (!el || !el.closest) return;
  1048. var act = el.closest('[data-sc-act]');
  1049. if (!act || !root.contains(act)) return;
  1050. var cue = el.closest('[data-sc-cue]');
  1051. if (!cue) return;
  1052. if (parseFloat(getComputedStyle(cue).opacity || '1') > 0.85) return;
  1053. el.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
  1054. });
  1055. var lastW = innerWidth;
  1056. addEventListener('resize', function () {
  1057. // Ignore URL-bar-only height changes on phones. Relaying out on those
  1058. // makes the page jump under the reader's thumb for no reason.
  1059. if (innerWidth === lastW && isMobile()) { vh = innerHeight; return; }
  1060. lastW = innerWidth;
  1061. layout();
  1062. }, { passive: true });
  1063. if (document.fonts && document.fonts.ready) {
  1064. // Line splitting measures line boxes, so it has to wait for the real face.
  1065. document.fonts.ready.then(function () {
  1066. acts.forEach(function (a) { a.cues.forEach(function (q) { if (q.kinetic && q.units) { q.el.__scSplit = null; q.units = null; } }); });
  1067. layout();
  1068. });
  1069. }
  1070. layout();
  1071. initPointer();
  1072. requestAnimationFrame(tick);
  1073. document.documentElement.classList.add('sc-ready');
  1074. var api = { layout: layout, read: read, acts: acts, worlds: worlds, clips: playheads, lerp: LERP };
  1075. global.ScrollCraft.instances.push(api);
  1076. return api;
  1077. }
  1078. // The instance list is not an API for the page. It is how the verification
  1079. // harness reads the real playhead records: a screenshot taken mid-lerp is a
  1080. // frame the page never actually holds, so the harness has to be able to ask
  1081. // whether the playhead has arrived rather than guess with a timeout.
  1082. global.ScrollCraft = { mount: mount, reduce: reduce, instances: [] };
  1083. })(window);