@open-take/compositor 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (439) hide show
  1. package/dist/cdp-CzT5BKNY.js +3 -0
  2. package/dist/cdp-QXbQfXna.js +373 -0
  3. package/dist/cdp-QXbQfXna.js.map +1 -0
  4. package/dist/index.d.ts +4327 -195
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +26282 -160
  7. package/dist/index.js.map +1 -1
  8. package/dist/server-841PMF2H.js +163 -0
  9. package/dist/server-841PMF2H.js.map +1 -0
  10. package/dist/server-C2aVv4-t.js +3 -0
  11. package/kit/audio.mjs +2366 -0
  12. package/kit/camera.js +587 -0
  13. package/kit/cursor.js +264 -0
  14. package/kit/cut.js +427 -0
  15. package/kit/draw.js +346 -0
  16. package/kit/look.js +589 -0
  17. package/kit/map.js +170 -0
  18. package/kit/media.js +3568 -0
  19. package/kit/motion.js +1115 -0
  20. package/kit/seams.js +1006 -0
  21. package/kit/stage.js +923 -0
  22. package/kit/time.js +812 -0
  23. package/kit/world.js +1072 -0
  24. package/package.json +7 -3
  25. package/src/ffmpeg.ts +63 -0
  26. package/src/film/beats.ts +1285 -0
  27. package/src/film/carry.ts +221 -0
  28. package/src/film/changes.ts +330 -0
  29. package/src/film/check.ts +996 -0
  30. package/src/film/clock.ts +2530 -0
  31. package/src/film/components-probe.ts +809 -0
  32. package/src/film/components.ts +1566 -0
  33. package/src/film/frames.ts +389 -0
  34. package/src/film/gallery.ts +3276 -0
  35. package/src/film/kit.ts +515 -0
  36. package/src/film/layout.ts +701 -0
  37. package/src/film/listen.ts +1979 -0
  38. package/src/film/look.ts +3829 -0
  39. package/src/film/materials.ts +976 -0
  40. package/src/film/moving.ts +248 -0
  41. package/src/film/part-files.ts +729 -0
  42. package/src/film/picture.ts +74 -0
  43. package/src/film/probe-text.ts +843 -0
  44. package/src/film/probe.ts +3456 -0
  45. package/src/film/provenance.ts +596 -0
  46. package/src/film/render.ts +2447 -0
  47. package/src/film/report.ts +1631 -0
  48. package/src/film/sheet.ts +156 -0
  49. package/src/film/study-declared.ts +123 -0
  50. package/src/film/study-picture.ts +791 -0
  51. package/src/film/study-sound.ts +416 -0
  52. package/src/film/study.ts +864 -0
  53. package/src/film/tuning.ts +155 -0
  54. package/src/film/viewer.ts +174 -0
  55. package/src/html/cdp.ts +575 -0
  56. package/src/html/server.ts +208 -0
  57. package/src/index.ts +202 -0
  58. package/src/launch-render.ts +3 -2
  59. package/src/math.ts +3 -3
  60. package/src/mjpeg-matroska.ts +228 -0
  61. package/src/render.ts +6 -4
  62. package/src/state-diff.ts +215 -0
  63. package/src/state-index.ts +99 -0
  64. package/src/types.ts +59 -1
  65. package/starter/PLAN.md +84 -0
  66. package/starter/START.md +460 -0
  67. package/starter/lib/anim.js +760 -0
  68. package/starter/lib/devices.js +1402 -0
  69. package/starter/lib/handoff.js +421 -0
  70. package/starter/lib/hud.js +1879 -0
  71. package/starter/lib/measure.mjs +154 -0
  72. package/starter/lib/moves.js +1095 -0
  73. package/starter/lib/palette.mjs +803 -0
  74. package/starter/lib/physics-seeds.mjs +198 -0
  75. package/starter/lib/physics.js +738 -0
  76. package/starter/lib/sampler.mjs +242 -0
  77. package/starter/lib/solid.js +727 -0
  78. package/starter/lib/space.js +1227 -0
  79. package/starter/lib/swarm.js +1398 -0
  80. package/starter/reference/motion.md +276 -0
  81. package/starter/reference/structure.md +466 -0
  82. package/starter/reference/travel/motion.md +433 -0
  83. package/starter/reference/travel/sound.md +241 -0
  84. package/starter/reference/travel/structure.md +518 -0
  85. package/starter/samples/NOTICE.txt +55 -0
  86. package/starter/samples/celli/celli_24_1.opus +0 -0
  87. package/starter/samples/celli/celli_24_3.opus +0 -0
  88. package/starter/samples/celli/celli_28_1.opus +0 -0
  89. package/starter/samples/celli/celli_28_3.opus +0 -0
  90. package/starter/samples/celli/celli_31_1.opus +0 -0
  91. package/starter/samples/celli/celli_31_3.opus +0 -0
  92. package/starter/samples/celli/celli_35_1.opus +0 -0
  93. package/starter/samples/celli/celli_35_3.opus +0 -0
  94. package/starter/samples/celli/celli_38_1.opus +0 -0
  95. package/starter/samples/celli/celli_38_3.opus +0 -0
  96. package/starter/samples/celli/celli_41_1.opus +0 -0
  97. package/starter/samples/celli/celli_41_3.opus +0 -0
  98. package/starter/samples/celli/celli_45_1.opus +0 -0
  99. package/starter/samples/celli/celli_45_3.opus +0 -0
  100. package/starter/samples/celli/celli_48_1.opus +0 -0
  101. package/starter/samples/celli/celli_48_3.opus +0 -0
  102. package/starter/samples/celli/celli_52_1.opus +0 -0
  103. package/starter/samples/celli/celli_52_3.opus +0 -0
  104. package/starter/samples/celli/celli_55_1.opus +0 -0
  105. package/starter/samples/celli/celli_55_3.opus +0 -0
  106. package/starter/samples/celli/celli_59_1.opus +0 -0
  107. package/starter/samples/celli/celli_59_3.opus +0 -0
  108. package/starter/samples/celli/celli_62_1.opus +0 -0
  109. package/starter/samples/celli/celli_62_3.opus +0 -0
  110. package/starter/samples/celli/celli_65_1.opus +0 -0
  111. package/starter/samples/celli/celli_65_3.opus +0 -0
  112. package/starter/samples/crash/crash_f_1.flac +0 -0
  113. package/starter/samples/crash/crash_fff_1.flac +0 -0
  114. package/starter/samples/ebass/ebass_0_x.flac +0 -0
  115. package/starter/samples/ebass/ebass_10_x.flac +0 -0
  116. package/starter/samples/ebass/ebass_11_x.flac +0 -0
  117. package/starter/samples/ebass/ebass_1_x.flac +0 -0
  118. package/starter/samples/ebass/ebass_2_x.flac +0 -0
  119. package/starter/samples/ebass/ebass_3_x.flac +0 -0
  120. package/starter/samples/ebass/ebass_4_x.flac +0 -0
  121. package/starter/samples/ebass/ebass_5_x.flac +0 -0
  122. package/starter/samples/ebass/ebass_6_x.flac +0 -0
  123. package/starter/samples/ebass/ebass_7_x.flac +0 -0
  124. package/starter/samples/ebass/ebass_8_x.flac +0 -0
  125. package/starter/samples/ebass/ebass_9_x.flac +0 -0
  126. package/starter/samples/ek_clap/ek_clap_1_1.flac +0 -0
  127. package/starter/samples/ek_hat/ek_hat_1_1.flac +0 -0
  128. package/starter/samples/ek_hat/ek_hat_1_2.flac +0 -0
  129. package/starter/samples/ek_kick/ek_kick_1_1.flac +0 -0
  130. package/starter/samples/ek_kick/ek_kick_1_2.flac +0 -0
  131. package/starter/samples/glock/glock_67_x.flac +0 -0
  132. package/starter/samples/glock/glock_72_x.flac +0 -0
  133. package/starter/samples/glock/glock_79_x.flac +0 -0
  134. package/starter/samples/glock/glock_84_x.flac +0 -0
  135. package/starter/samples/glock/glock_91_x.flac +0 -0
  136. package/starter/samples/glock/glock_96_x.flac +0 -0
  137. package/starter/samples/harp/harp_101_f.opus +0 -0
  138. package/starter/samples/harp/harp_28_f.opus +0 -0
  139. package/starter/samples/harp/harp_31_mp.opus +0 -0
  140. package/starter/samples/harp/harp_35_mf.opus +0 -0
  141. package/starter/samples/harp/harp_38_mf.opus +0 -0
  142. package/starter/samples/harp/harp_41_mf.opus +0 -0
  143. package/starter/samples/harp/harp_45_mf.opus +0 -0
  144. package/starter/samples/harp/harp_48_mf.opus +0 -0
  145. package/starter/samples/harp/harp_52_mf.opus +0 -0
  146. package/starter/samples/harp/harp_55_mf.opus +0 -0
  147. package/starter/samples/harp/harp_59_mf.opus +0 -0
  148. package/starter/samples/harp/harp_62_mf.opus +0 -0
  149. package/starter/samples/harp/harp_65_mf.opus +0 -0
  150. package/starter/samples/harp/harp_69_mf.opus +0 -0
  151. package/starter/samples/harp/harp_72_mf.opus +0 -0
  152. package/starter/samples/harp/harp_76_mf.opus +0 -0
  153. package/starter/samples/harp/harp_79_mf.opus +0 -0
  154. package/starter/samples/harp/harp_83_mf.opus +0 -0
  155. package/starter/samples/harp/harp_86_mf.opus +0 -0
  156. package/starter/samples/harp/harp_89_mf.opus +0 -0
  157. package/starter/samples/harp/harp_93_mf.opus +0 -0
  158. package/starter/samples/harp/harp_95_mf.opus +0 -0
  159. package/starter/samples/harp/harp_98_f.opus +0 -0
  160. package/starter/samples/manifest.json +2951 -0
  161. package/starter/samples/marimba/marimba_29_x.flac +0 -0
  162. package/starter/samples/marimba/marimba_36_x.flac +0 -0
  163. package/starter/samples/marimba/marimba_43_x.flac +0 -0
  164. package/starter/samples/marimba/marimba_47_x.flac +0 -0
  165. package/starter/samples/marimba/marimba_53_x.flac +0 -0
  166. package/starter/samples/marimba/marimba_60_x.flac +0 -0
  167. package/starter/samples/marimba/marimba_67_x.flac +0 -0
  168. package/starter/samples/marimba/marimba_71_x.flac +0 -0
  169. package/starter/samples/marimba/marimba_77_x.flac +0 -0
  170. package/starter/samples/marimba/marimba_84_x.flac +0 -0
  171. package/starter/samples/piano/piano_102_12.opus +0 -0
  172. package/starter/samples/piano/piano_102_16.opus +0 -0
  173. package/starter/samples/piano/piano_102_4.opus +0 -0
  174. package/starter/samples/piano/piano_102_8.opus +0 -0
  175. package/starter/samples/piano/piano_105_12.opus +0 -0
  176. package/starter/samples/piano/piano_105_16.opus +0 -0
  177. package/starter/samples/piano/piano_105_4.opus +0 -0
  178. package/starter/samples/piano/piano_105_8.opus +0 -0
  179. package/starter/samples/piano/piano_108_12.opus +0 -0
  180. package/starter/samples/piano/piano_108_16.opus +0 -0
  181. package/starter/samples/piano/piano_108_4.opus +0 -0
  182. package/starter/samples/piano/piano_108_8.opus +0 -0
  183. package/starter/samples/piano/piano_21_12.opus +0 -0
  184. package/starter/samples/piano/piano_21_16.opus +0 -0
  185. package/starter/samples/piano/piano_21_4.opus +0 -0
  186. package/starter/samples/piano/piano_21_8.opus +0 -0
  187. package/starter/samples/piano/piano_24_12.opus +0 -0
  188. package/starter/samples/piano/piano_24_16.opus +0 -0
  189. package/starter/samples/piano/piano_24_4.opus +0 -0
  190. package/starter/samples/piano/piano_24_8.opus +0 -0
  191. package/starter/samples/piano/piano_27_12.opus +0 -0
  192. package/starter/samples/piano/piano_27_16.opus +0 -0
  193. package/starter/samples/piano/piano_27_4.opus +0 -0
  194. package/starter/samples/piano/piano_27_8.opus +0 -0
  195. package/starter/samples/piano/piano_30_12.opus +0 -0
  196. package/starter/samples/piano/piano_30_16.opus +0 -0
  197. package/starter/samples/piano/piano_30_4.opus +0 -0
  198. package/starter/samples/piano/piano_30_8.opus +0 -0
  199. package/starter/samples/piano/piano_33_12.opus +0 -0
  200. package/starter/samples/piano/piano_33_16.opus +0 -0
  201. package/starter/samples/piano/piano_33_4.opus +0 -0
  202. package/starter/samples/piano/piano_33_8.opus +0 -0
  203. package/starter/samples/piano/piano_36_12.opus +0 -0
  204. package/starter/samples/piano/piano_36_16.opus +0 -0
  205. package/starter/samples/piano/piano_36_4.opus +0 -0
  206. package/starter/samples/piano/piano_36_8.opus +0 -0
  207. package/starter/samples/piano/piano_39_12.opus +0 -0
  208. package/starter/samples/piano/piano_39_16.opus +0 -0
  209. package/starter/samples/piano/piano_39_4.opus +0 -0
  210. package/starter/samples/piano/piano_39_8.opus +0 -0
  211. package/starter/samples/piano/piano_42_12.opus +0 -0
  212. package/starter/samples/piano/piano_42_16.opus +0 -0
  213. package/starter/samples/piano/piano_42_4.opus +0 -0
  214. package/starter/samples/piano/piano_42_8.opus +0 -0
  215. package/starter/samples/piano/piano_45_12.opus +0 -0
  216. package/starter/samples/piano/piano_45_16.opus +0 -0
  217. package/starter/samples/piano/piano_45_4.opus +0 -0
  218. package/starter/samples/piano/piano_45_8.opus +0 -0
  219. package/starter/samples/piano/piano_48_12.opus +0 -0
  220. package/starter/samples/piano/piano_48_16.opus +0 -0
  221. package/starter/samples/piano/piano_48_4.opus +0 -0
  222. package/starter/samples/piano/piano_48_8.opus +0 -0
  223. package/starter/samples/piano/piano_51_12.opus +0 -0
  224. package/starter/samples/piano/piano_51_16.opus +0 -0
  225. package/starter/samples/piano/piano_51_4.opus +0 -0
  226. package/starter/samples/piano/piano_51_8.opus +0 -0
  227. package/starter/samples/piano/piano_54_12.opus +0 -0
  228. package/starter/samples/piano/piano_54_16.opus +0 -0
  229. package/starter/samples/piano/piano_54_4.opus +0 -0
  230. package/starter/samples/piano/piano_54_8.opus +0 -0
  231. package/starter/samples/piano/piano_57_12.opus +0 -0
  232. package/starter/samples/piano/piano_57_16.opus +0 -0
  233. package/starter/samples/piano/piano_57_4.opus +0 -0
  234. package/starter/samples/piano/piano_57_8.opus +0 -0
  235. package/starter/samples/piano/piano_60_12.opus +0 -0
  236. package/starter/samples/piano/piano_60_16.opus +0 -0
  237. package/starter/samples/piano/piano_60_4.opus +0 -0
  238. package/starter/samples/piano/piano_60_8.opus +0 -0
  239. package/starter/samples/piano/piano_63_12.opus +0 -0
  240. package/starter/samples/piano/piano_63_16.opus +0 -0
  241. package/starter/samples/piano/piano_63_4.opus +0 -0
  242. package/starter/samples/piano/piano_63_8.opus +0 -0
  243. package/starter/samples/piano/piano_66_12.opus +0 -0
  244. package/starter/samples/piano/piano_66_16.opus +0 -0
  245. package/starter/samples/piano/piano_66_4.opus +0 -0
  246. package/starter/samples/piano/piano_66_8.opus +0 -0
  247. package/starter/samples/piano/piano_69_12.opus +0 -0
  248. package/starter/samples/piano/piano_69_16.opus +0 -0
  249. package/starter/samples/piano/piano_69_4.opus +0 -0
  250. package/starter/samples/piano/piano_69_8.opus +0 -0
  251. package/starter/samples/piano/piano_72_12.opus +0 -0
  252. package/starter/samples/piano/piano_72_16.opus +0 -0
  253. package/starter/samples/piano/piano_72_4.opus +0 -0
  254. package/starter/samples/piano/piano_72_8.opus +0 -0
  255. package/starter/samples/piano/piano_75_12.opus +0 -0
  256. package/starter/samples/piano/piano_75_16.opus +0 -0
  257. package/starter/samples/piano/piano_75_4.opus +0 -0
  258. package/starter/samples/piano/piano_75_8.opus +0 -0
  259. package/starter/samples/piano/piano_78_12.opus +0 -0
  260. package/starter/samples/piano/piano_78_16.opus +0 -0
  261. package/starter/samples/piano/piano_78_4.opus +0 -0
  262. package/starter/samples/piano/piano_78_8.opus +0 -0
  263. package/starter/samples/piano/piano_81_12.opus +0 -0
  264. package/starter/samples/piano/piano_81_16.opus +0 -0
  265. package/starter/samples/piano/piano_81_4.opus +0 -0
  266. package/starter/samples/piano/piano_81_8.opus +0 -0
  267. package/starter/samples/piano/piano_84_12.opus +0 -0
  268. package/starter/samples/piano/piano_84_16.opus +0 -0
  269. package/starter/samples/piano/piano_84_4.opus +0 -0
  270. package/starter/samples/piano/piano_84_8.opus +0 -0
  271. package/starter/samples/piano/piano_87_12.opus +0 -0
  272. package/starter/samples/piano/piano_87_16.opus +0 -0
  273. package/starter/samples/piano/piano_87_4.opus +0 -0
  274. package/starter/samples/piano/piano_87_8.opus +0 -0
  275. package/starter/samples/piano/piano_90_12.opus +0 -0
  276. package/starter/samples/piano/piano_90_16.opus +0 -0
  277. package/starter/samples/piano/piano_90_4.opus +0 -0
  278. package/starter/samples/piano/piano_90_8.opus +0 -0
  279. package/starter/samples/piano/piano_93_12.opus +0 -0
  280. package/starter/samples/piano/piano_93_16.opus +0 -0
  281. package/starter/samples/piano/piano_93_4.opus +0 -0
  282. package/starter/samples/piano/piano_93_8.opus +0 -0
  283. package/starter/samples/piano/piano_96_12.opus +0 -0
  284. package/starter/samples/piano/piano_96_16.opus +0 -0
  285. package/starter/samples/piano/piano_96_4.opus +0 -0
  286. package/starter/samples/piano/piano_96_8.opus +0 -0
  287. package/starter/samples/piano/piano_99_12.opus +0 -0
  288. package/starter/samples/piano/piano_99_16.opus +0 -0
  289. package/starter/samples/piano/piano_99_4.opus +0 -0
  290. package/starter/samples/piano/piano_99_8.opus +0 -0
  291. package/starter/samples/piano/piano_rel_102_x.opus +0 -0
  292. package/starter/samples/piano/piano_rel_105_x.opus +0 -0
  293. package/starter/samples/piano/piano_rel_108_x.opus +0 -0
  294. package/starter/samples/piano/piano_rel_21_x.opus +0 -0
  295. package/starter/samples/piano/piano_rel_24_x.opus +0 -0
  296. package/starter/samples/piano/piano_rel_27_x.opus +0 -0
  297. package/starter/samples/piano/piano_rel_30_x.opus +0 -0
  298. package/starter/samples/piano/piano_rel_33_x.opus +0 -0
  299. package/starter/samples/piano/piano_rel_36_x.opus +0 -0
  300. package/starter/samples/piano/piano_rel_39_x.opus +0 -0
  301. package/starter/samples/piano/piano_rel_42_x.opus +0 -0
  302. package/starter/samples/piano/piano_rel_45_x.opus +0 -0
  303. package/starter/samples/piano/piano_rel_48_x.opus +0 -0
  304. package/starter/samples/piano/piano_rel_51_x.opus +0 -0
  305. package/starter/samples/piano/piano_rel_54_x.opus +0 -0
  306. package/starter/samples/piano/piano_rel_57_x.opus +0 -0
  307. package/starter/samples/piano/piano_rel_60_x.opus +0 -0
  308. package/starter/samples/piano/piano_rel_63_x.opus +0 -0
  309. package/starter/samples/piano/piano_rel_66_x.opus +0 -0
  310. package/starter/samples/piano/piano_rel_69_x.opus +0 -0
  311. package/starter/samples/piano/piano_rel_72_x.opus +0 -0
  312. package/starter/samples/piano/piano_rel_75_x.opus +0 -0
  313. package/starter/samples/piano/piano_rel_78_x.opus +0 -0
  314. package/starter/samples/piano/piano_rel_81_x.opus +0 -0
  315. package/starter/samples/piano/piano_rel_84_x.opus +0 -0
  316. package/starter/samples/piano/piano_rel_87_x.opus +0 -0
  317. package/starter/samples/piano/piano_rel_90_x.opus +0 -0
  318. package/starter/samples/piano/piano_rel_93_x.opus +0 -0
  319. package/starter/samples/piano/piano_rel_96_x.opus +0 -0
  320. package/starter/samples/piano/piano_rel_99_x.opus +0 -0
  321. package/starter/samples/pizz/pizz_24_2.flac +0 -0
  322. package/starter/samples/pizz/pizz_28_2.flac +0 -0
  323. package/starter/samples/pizz/pizz_31_2.flac +0 -0
  324. package/starter/samples/pizz/pizz_35_2.flac +0 -0
  325. package/starter/samples/pizz/pizz_38_2.flac +0 -0
  326. package/starter/samples/pizz/pizz_41_2.flac +0 -0
  327. package/starter/samples/pizz/pizz_45_2.flac +0 -0
  328. package/starter/samples/pizz/pizz_48_2.flac +0 -0
  329. package/starter/samples/pizz/pizz_52_2.flac +0 -0
  330. package/starter/samples/pizz/pizz_57_2.flac +0 -0
  331. package/starter/samples/pizz/pizz_60_2.flac +0 -0
  332. package/starter/samples/pizz/pizz_64_2.flac +0 -0
  333. package/starter/samples/pizz/pizz_67_2.flac +0 -0
  334. package/starter/samples/pizz/pizz_71_2.flac +0 -0
  335. package/starter/samples/pizz/pizz_74_2.flac +0 -0
  336. package/starter/samples/pk_hat/pk_hat_2_1.flac +0 -0
  337. package/starter/samples/pk_hat/pk_hat_2_2.flac +0 -0
  338. package/starter/samples/pk_hat/pk_hat_6_1.flac +0 -0
  339. package/starter/samples/pk_hat/pk_hat_6_2.flac +0 -0
  340. package/starter/samples/pk_kick/pk_kick_3_1.flac +0 -0
  341. package/starter/samples/pk_kick/pk_kick_3_2.flac +0 -0
  342. package/starter/samples/pk_kick/pk_kick_7_1.flac +0 -0
  343. package/starter/samples/pk_kick/pk_kick_7_2.flac +0 -0
  344. package/starter/samples/pk_ohat/pk_ohat_3_1.flac +0 -0
  345. package/starter/samples/pk_ohat/pk_ohat_3_2.flac +0 -0
  346. package/starter/samples/pk_ohat/pk_ohat_6_1.flac +0 -0
  347. package/starter/samples/pk_ohat/pk_ohat_6_2.flac +0 -0
  348. package/starter/samples/pk_rim/pk_rim_2_1.flac +0 -0
  349. package/starter/samples/pk_rim/pk_rim_2_2.flac +0 -0
  350. package/starter/samples/pk_rim/pk_rim_5_1.flac +0 -0
  351. package/starter/samples/pk_rim/pk_rim_5_2.flac +0 -0
  352. package/starter/samples/pk_snare/pk_snare_3_1.flac +0 -0
  353. package/starter/samples/pk_snare/pk_snare_3_2.flac +0 -0
  354. package/starter/samples/pk_snare/pk_snare_7_1.flac +0 -0
  355. package/starter/samples/pk_snare/pk_snare_7_2.flac +0 -0
  356. package/starter/samples/shaker/shaker_1_1.flac +0 -0
  357. package/starter/samples/shaker/shaker_2_1.flac +0 -0
  358. package/starter/samples/snap/snap_r_1.flac +0 -0
  359. package/starter/samples/snap/snap_r_2.flac +0 -0
  360. package/starter/samples/snap/snap_r_3.flac +0 -0
  361. package/starter/samples/snap/snap_r_4.flac +0 -0
  362. package/starter/samples/snap/snap_r_5.flac +0 -0
  363. package/starter/samples/snap/snap_r_6.flac +0 -0
  364. package/starter/samples/tom/tom_3_1.flac +0 -0
  365. package/starter/samples/tom/tom_3_2.flac +0 -0
  366. package/starter/samples/tom/tom_4_1.flac +0 -0
  367. package/starter/samples/tom/tom_4_2.flac +0 -0
  368. package/starter/samples/vibes/vibes_41_1.opus +0 -0
  369. package/starter/samples/vibes/vibes_41_2.opus +0 -0
  370. package/starter/samples/vibes/vibes_45_1.opus +0 -0
  371. package/starter/samples/vibes/vibes_45_2.opus +0 -0
  372. package/starter/samples/vibes/vibes_48_1.opus +0 -0
  373. package/starter/samples/vibes/vibes_48_2.opus +0 -0
  374. package/starter/samples/vibes/vibes_52_1.opus +0 -0
  375. package/starter/samples/vibes/vibes_52_2.opus +0 -0
  376. package/starter/samples/vibes/vibes_55_1.opus +0 -0
  377. package/starter/samples/vibes/vibes_55_2.opus +0 -0
  378. package/starter/samples/vibes/vibes_59_1.opus +0 -0
  379. package/starter/samples/vibes/vibes_59_2.opus +0 -0
  380. package/starter/samples/vibes/vibes_62_1.opus +0 -0
  381. package/starter/samples/vibes/vibes_62_2.opus +0 -0
  382. package/starter/samples/vibes/vibes_65_1.opus +0 -0
  383. package/starter/samples/vibes/vibes_65_2.opus +0 -0
  384. package/starter/samples/vibes/vibes_69_1.opus +0 -0
  385. package/starter/samples/vibes/vibes_69_2.opus +0 -0
  386. package/starter/samples/vibes/vibes_72_1.opus +0 -0
  387. package/starter/samples/vibes/vibes_72_2.opus +0 -0
  388. package/starter/samples/vibes/vibes_76_1.opus +0 -0
  389. package/starter/samples/vibes/vibes_76_2.opus +0 -0
  390. package/starter/samples/violas/violas_36_1.opus +0 -0
  391. package/starter/samples/violas/violas_36_2.opus +0 -0
  392. package/starter/samples/violas/violas_38_1.opus +0 -0
  393. package/starter/samples/violas/violas_38_2.opus +0 -0
  394. package/starter/samples/violas/violas_40_1.opus +0 -0
  395. package/starter/samples/violas/violas_40_2.opus +0 -0
  396. package/starter/samples/violas/violas_43_1.opus +0 -0
  397. package/starter/samples/violas/violas_43_2.opus +0 -0
  398. package/starter/samples/violas/violas_47_1.opus +0 -0
  399. package/starter/samples/violas/violas_47_2.opus +0 -0
  400. package/starter/samples/violas/violas_50_1.opus +0 -0
  401. package/starter/samples/violas/violas_50_2.opus +0 -0
  402. package/starter/samples/violas/violas_53_1.opus +0 -0
  403. package/starter/samples/violas/violas_53_2.opus +0 -0
  404. package/starter/samples/violas/violas_57_1.opus +0 -0
  405. package/starter/samples/violas/violas_57_2.opus +0 -0
  406. package/starter/samples/violas/violas_60_1.opus +0 -0
  407. package/starter/samples/violas/violas_60_2.opus +0 -0
  408. package/starter/samples/violas/violas_64_1.opus +0 -0
  409. package/starter/samples/violas/violas_64_2.opus +0 -0
  410. package/starter/samples/violas/violas_67_1.opus +0 -0
  411. package/starter/samples/violas/violas_67_2.opus +0 -0
  412. package/starter/samples/violas/violas_71_1.opus +0 -0
  413. package/starter/samples/violas/violas_71_2.opus +0 -0
  414. package/starter/samples/violas/violas_74_1.opus +0 -0
  415. package/starter/samples/violas/violas_74_2.opus +0 -0
  416. package/starter/samples/violins/violins_43_1.opus +0 -0
  417. package/starter/samples/violins/violins_43_2.opus +0 -0
  418. package/starter/samples/violins/violins_45_1.opus +0 -0
  419. package/starter/samples/violins/violins_45_2.opus +0 -0
  420. package/starter/samples/violins/violins_47_1.opus +0 -0
  421. package/starter/samples/violins/violins_47_2.opus +0 -0
  422. package/starter/samples/violins/violins_50_1.opus +0 -0
  423. package/starter/samples/violins/violins_50_2.opus +0 -0
  424. package/starter/samples/violins/violins_54_1.opus +0 -0
  425. package/starter/samples/violins/violins_54_2.opus +0 -0
  426. package/starter/samples/violins/violins_57_1.opus +0 -0
  427. package/starter/samples/violins/violins_57_2.opus +0 -0
  428. package/starter/samples/violins/violins_60_1.opus +0 -0
  429. package/starter/samples/violins/violins_60_2.opus +0 -0
  430. package/starter/samples/violins/violins_64_1.opus +0 -0
  431. package/starter/samples/violins/violins_64_2.opus +0 -0
  432. package/starter/samples/violins/violins_67_1.opus +0 -0
  433. package/starter/samples/violins/violins_67_2.opus +0 -0
  434. package/starter/samples/violins/violins_71_1.opus +0 -0
  435. package/starter/samples/violins/violins_71_2.opus +0 -0
  436. package/starter/samples/violins/violins_74_1.opus +0 -0
  437. package/starter/samples/violins/violins_74_2.opus +0 -0
  438. package/starter/samples/woodblock/woodblock_f_1.flac +0 -0
  439. package/starter/samples/woodblock/woodblock_f_2.flac +0 -0
package/kit/media.js ADDED
@@ -0,0 +1,3568 @@
1
+ // @ts-check
2
+ // The real interface in a film — open-take's film kit. The kinds of material:
3
+ //
4
+ // screen(iframe) a saved screen (`make --states`: takes/x.take/states/s3/
5
+ // state.html; a shoot's still kept with { state: true }:
6
+ // shots/states/home/state.html — the same files) shown in
7
+ // an <iframe> the size of its viewport. screen(iframe, url)
8
+ // points the iframe at it.
9
+ // box() says where a part of it is — measured on the page as
10
+ // it is now, so restyling it moves the box too — in the
11
+ // screen's own CSS px: the coordinates the camera and cursor
12
+ // take when the screen is their layer.
13
+ // stills(log) the 2× stills `open-take shoot` writes, with its log
14
+ // (shots.json): which still shows at t, decoded before the
15
+ // frame is drawn, a bounded number held at once (a long drag
16
+ // can be 900 stills), and every box and cursor position the
17
+ // shoot recorded — in the still's own px — so nothing is
18
+ // copied by hand. state(i) is the URL of the saved screen
19
+ // a still kept, for screen(), and so for lift / isolate;
20
+ // changes(i) is what the action before it changed there.
21
+ // readTake(url) a take `open-take make` recorded (capture.json): its
22
+ // actions, its recording, its saved states. clip() maps
23
+ // film time onto the recording (a start and a speed, or
24
+ // keys that slow down round a click); clipEvents() turns
25
+ // the actions into film events through it — the input, and
26
+ // apart from it when its RESULT showed, which can be a
27
+ // second later; seam() says when and where a saved state
28
+ // stands in for the video without a jump.
29
+ // lift(screen, part) one real part of a saved screen as a layer of its
30
+ // own, starting exactly where it sat — to carry it
31
+ // anywhere at any size, the page around it kept or
32
+ // cleared; isolate() fades all but chosen parts instead.
33
+ // A part is a selector, an index id ("e12"), a ref of
34
+ // `open-take states` ("result:e12"), { text: "Total due",
35
+ // up: 2 } (the element showing that text, two parents
36
+ // out), an element or a box — or a list of them, lifted
37
+ // as one layer. group() moves several lifts as one body,
38
+ // arrange() lays them out in a row, carry() hands one
39
+ // over to another (the same part in the next screen).
40
+ // readValues(url) the values the product's parts showed, by field, from
41
+ // components.json — to fill a part the film draws itself
42
+ // with what the product really showed (and, given the
43
+ // timeline, to declare where each came from).
44
+ // product(url) the product's parts (components.json) as references:
45
+ // P.part("t1") is one part followed through every screen
46
+ // it is on — cam.frame(part), cur.click(part, t), lift(s,
47
+ // part), part.at(t) where it shows in the picture now.
48
+ // partFiles(url) the same parts as files (parts/index.json): each one's
49
+ // own HTML with its styles inlined and its fonts, that
50
+ // renders alone at its natural size — an iframe's src, or
51
+ // node() into the page in a shadow root of its own.
52
+ //
53
+ // A box is always in one place's own CSS px. Where a screen sits inside a
54
+ // bigger layer, box(…, { in: layer }) adds its offset — and refuses when
55
+ // something between them is transformed, rather than answer wrong.
56
+ //
57
+ // const s = screen(document.querySelector("#app"));
58
+ // window.__film = { duration: 30, ready: s.ready }; // the film waits for it
59
+ // cam.frame(s.box("#search"), { arrive: 3 });
60
+ //
61
+ // const st = await stills("shots/shots.json", document.querySelector("#still"));
62
+ // await st.show(st.at(t, { from: 4, start: 12, rate: 30 }));
63
+ //
64
+ // const home = screen(document.querySelector("#home"), st.state("home")); // a shoot's still, as live DOM
65
+ // const total = lift(home, "#total", { around: "clear" }); // that part, sharp at any size
66
+ //
67
+ // const c = clip({ at: 7, from: 12.0, to: 15.5 }); // film 7 s shows 12.0 s
68
+ // const card = lift(s, "e126", { around: "clear" }); // the number the app worked out
69
+ // let shown = 0; // when the new number showed
70
+ // const ready = Promise.all([card.ready, readTake("../takes/form.take/").then((take) => {
71
+ // const ev = clipEvents(take, c, { tl }); // also declared for the score
72
+ // shown = ev.find((e) => e.kind === "result" && e.action === "a2").t;
73
+ // })]);
74
+
75
+ /** @typedef {{ x: number, y: number, width: number, height: number }} Box */
76
+ /** @typedef {{ text: string, up?: number }} TextKey the element showing this text, `up` parents out */
77
+
78
+ /**
79
+ * Where the document inside the frame `el` begins, in `layer`'s CSS px: the
80
+ * offsets up to it, the borders they are taken inside of, less what scrolls in
81
+ * between, plus the frame's own border and padding. Anything transformed on
82
+ * the way (the frame included) would make that wrong, so it is refused.
83
+ * @param {string} what
84
+ * @param {Element} el
85
+ * @param {Element} layer
86
+ */
87
+ function offsetWithin(what, el, layer) {
88
+ if (!layer.contains(el))
89
+ throw new Error(`${what}: it is not inside the layer it was measured in`);
90
+ for (let n = /** @type {Element | null} */ (el); n && n !== layer; n = n.parentElement)
91
+ if (getComputedStyle(n).transform !== "none")
92
+ throw new Error(
93
+ `${what}: it, or something between it and the layer, is transformed — the kit cannot measure through that; place it untransformed in the layer (a seam's transform goes on the layer that holds the screen's iframe), or map it yourself`,
94
+ );
95
+ if (!(el instanceof HTMLElement)) throw new Error(`${what}: only HTML elements can be measured`);
96
+ // its document starts inside its border and padding
97
+ const own = getComputedStyle(el);
98
+ let x = el.clientLeft + Number.parseFloat(own.paddingLeft);
99
+ let y = el.clientTop + Number.parseFloat(own.paddingTop);
100
+ // what scrolls in between moves it
101
+ for (let n = el.parentElement; n && n !== layer; n = n.parentElement) {
102
+ x -= n.scrollLeft;
103
+ y -= n.scrollTop;
104
+ }
105
+ /** @type {Element | null} */
106
+ let n = el;
107
+ while (n && n !== layer) {
108
+ if (!(n instanceof HTMLElement)) throw new Error(`${what}: only HTML elements can be measured`);
109
+ x += n.offsetLeft;
110
+ y += n.offsetTop;
111
+ n = n.offsetParent;
112
+ if (n && n !== layer && !layer.contains(n))
113
+ throw new Error(
114
+ `${what}: the layer is not positioned — give it position: relative (or absolute) so what is inside it can be measured in it`,
115
+ );
116
+ // an offset is taken from inside its parent's border
117
+ if (n && n !== layer) {
118
+ x += n.clientLeft;
119
+ y += n.clientTop;
120
+ }
121
+ }
122
+ if (n !== layer)
123
+ throw new Error(
124
+ `${what}: the layer is not positioned — give it position: relative (or absolute) so what is inside it can be measured in it`,
125
+ );
126
+ return { x, y };
127
+ }
128
+
129
+ /**
130
+ * A saved screen shown in an iframe of its viewport's size: one already in
131
+ * the iframe's src, or `src` — a state.html URL (a take's, a shoot's
132
+ * states/<id>/state.html, stills().state(i)).
133
+ *
134
+ * `hidden`: a screen only to lift parts from, not to show — laid out (so it
135
+ * can be measured) but `visibility: hidden` on the iframe itself; the parts
136
+ * lifted from it sit beside it and show. (`display: none` would leave it
137
+ * nothing to measure.)
138
+ *
139
+ * const src = screen(iframe, st.state("result"), { hidden: true });
140
+ * const total = lift(src, "e170", { around: "clear" }); // shows; the screen does not
141
+ * @param {HTMLIFrameElement} frame
142
+ * @param {string | URL | { hidden?: boolean }} [src]
143
+ * @param {{ hidden?: boolean }} [o]
144
+ */
145
+ export function screen(frame, src, o = {}) {
146
+ if (src != null && typeof src === "object" && !(src instanceof URL)) {
147
+ o = src;
148
+ src = undefined;
149
+ }
150
+ if (o.hidden) frame.style.visibility = "hidden";
151
+ if (src != null) {
152
+ const url = new URL(String(src), location.href).href;
153
+ if (frame.src !== url) frame.src = url;
154
+ }
155
+ /** @type {{ viewport?: { w: number, h: number }, elements?: { id: string, box: number[] }[] } | null} */
156
+ let index = null;
157
+ // an iframe that has not loaded yet holds a blank page that also reads as
158
+ // complete: wait for the screen itself
159
+ const loaded = () => {
160
+ const doc = frame.contentDocument;
161
+ return !!doc && doc.readyState === "complete" && doc.URL !== "about:blank";
162
+ };
163
+ const ready = (async () => {
164
+ if (!loaded()) await new Promise((ok) => frame.addEventListener("load", ok, { once: true }));
165
+ try {
166
+ const res = await fetch(new URL("index.json", frame.src));
167
+ if (res.ok) index = await res.json();
168
+ } catch {
169
+ /* a screen without its index: boxes by selector still work */
170
+ }
171
+ })();
172
+
173
+ /** @param {string | Element | TextKey | Part} key */
174
+ const measure = (key) => {
175
+ const doc = frame.contentDocument;
176
+ // a part of product(): its element on this screen
177
+ if (isPart(key)) key = refOn(key, frame.src, "screen");
178
+ const id = typeof key === "string" ? idOf("screen", key, frame.src) : null;
179
+ if (id) {
180
+ const e = index?.elements?.find((el) => el.id === id);
181
+ if (!e) throw new Error(`screen: no element ${id} in ${frame.src}'s index.json`);
182
+ const [x = 0, y = 0, width = 0, height = 0] = e.box;
183
+ return { x, y, width, height };
184
+ }
185
+ if (!doc)
186
+ throw new Error(`screen: ${frame.src} is not same-origin — its parts cannot be measured`);
187
+ const el = findIn(doc, key, "screen");
188
+ const r = el.getBoundingClientRect();
189
+ return { x: r.left, y: r.top, width: r.width, height: r.height };
190
+ };
191
+
192
+ return {
193
+ frame,
194
+ /** resolves once the screen has loaded and its index (if any) is read */
195
+ ready,
196
+ /** the screen's size (its viewport's), CSS px */
197
+ get size() {
198
+ return {
199
+ width: index?.viewport?.w ?? frame.clientWidth,
200
+ height: index?.viewport?.h ?? frame.clientHeight,
201
+ };
202
+ },
203
+ /**
204
+ * Where a part of the screen is: a CSS selector (measured live), an
205
+ * element of it, { text, up } (measured live), or an index id ("e12" or
206
+ * a ref "result:e12", as captured), or a part of product(). In the
207
+ * screen's own px, or in `layer`'s px when given.
208
+ * @param {string | Element | TextKey | Part} key
209
+ * @param {{ in?: Element }} [o]
210
+ * @returns {Box}
211
+ */
212
+ box(key, o = {}) {
213
+ const b = measure(key);
214
+ if (!o.in) return b;
215
+ const off = offsetWithin("screen", frame, o.in);
216
+ return { x: b.x + off.x, y: b.y + off.y, width: b.width, height: b.height };
217
+ },
218
+ };
219
+ }
220
+
221
+ /**
222
+ * Decoded stills, bounded twice: at most `keep` held, and at most `ahead`
223
+ * fetched ahead while still loading. One pushed out while it loads is
224
+ * cancelled, so a render that seeks about cannot pile up decodes. stills()
225
+ * is what a film uses; this is the part that can be tested without a browser.
226
+ * @template T
227
+ * @param {{ keep: number, ahead: number, count: number, open: (i: number) => { ready: Promise<T>, cancel: () => void } }} o
228
+ */
229
+ export function stillCache({ keep, ahead, count, open }) {
230
+ /** @type {Map<number, { ready: Promise<T>, cancel: () => void, done: boolean }>} */
231
+ const held = new Map();
232
+ /** @param {number} i */
233
+ const get = (i) => {
234
+ const had = held.get(i);
235
+ if (had) {
236
+ held.delete(i); // the most recently wanted go last, the oldest first
237
+ held.set(i, had);
238
+ return had.ready;
239
+ }
240
+ const o = open(i);
241
+ /** @type {{ ready: Promise<T>, cancel: () => void, done: boolean }} */
242
+ const entry = { ready: o.ready, cancel: o.cancel, done: false };
243
+ entry.ready = o.ready.then((v) => {
244
+ entry.done = true;
245
+ return v;
246
+ });
247
+ entry.ready.catch(() => {}); // a cancelled fetch ahead is nobody's error
248
+ held.set(i, entry);
249
+ while (held.size > Math.max(1, keep)) {
250
+ const first = held.keys().next().value;
251
+ if (first === undefined) break;
252
+ const old = held.get(first);
253
+ held.delete(first);
254
+ if (old && !old.done) old.cancel();
255
+ }
256
+ return entry.ready;
257
+ };
258
+ const loading = () => {
259
+ let n = 0;
260
+ for (const e of held.values()) if (!e.done) n++;
261
+ return n;
262
+ };
263
+ return {
264
+ /** still i, and a few after it fetched while fewer than `ahead` are
265
+ * loading — never more than the cache holds besides still i, so what is
266
+ * fetched ahead cannot push out the still that was asked for */
267
+ /** @param {number} i */
268
+ take(i) {
269
+ const p = get(i);
270
+ for (let k = 1; k <= Math.min(ahead, keep - 1) && i + k < count; k++) {
271
+ if (held.has(i + k)) continue;
272
+ if (loading() > ahead) break; // the one wanted counts as loading too
273
+ get(i + k);
274
+ }
275
+ return p;
276
+ },
277
+ loading,
278
+ get size() {
279
+ return held.size;
280
+ },
281
+ };
282
+ }
283
+
284
+ /**
285
+ * @typedef {object} Still
286
+ * @property {string} file
287
+ * @property {string} [name]
288
+ * @property {number} t
289
+ * @property {{ x: number, y: number }} [cursor]
290
+ * @property {{ x: number, y: number }} [scroll]
291
+ * @property {Record<string, Box>} [boxes]
292
+ * @property {string} [state] its saved screen's id: states/<state>/state.html
293
+ */
294
+
295
+ /**
296
+ * The stills of a shoot, played into one <img>.
297
+ * @param {string} logUrl the shoot's shots.json
298
+ * @param {HTMLImageElement} img where the current still is shown (size it to the viewport)
299
+ * @param {{ keep?: number, ahead?: number }} [o] how many decoded stills are held, how many are fetched ahead
300
+ */
301
+ export async function stills(logUrl, img, { keep = 12, ahead = 3 } = {}) {
302
+ const res = await fetch(logUrl);
303
+ if (!res.ok) throw new Error(`stills: ${logUrl} could not be read (${res.status})`);
304
+ /** @type {{ viewport: { w: number, h: number }, scale?: number, stills: Still[], states?: { dir: string }, outputs?: any[] }} */
305
+ const log = await res.json();
306
+ const base = new URL(logUrl, location.href);
307
+ let shown = -1;
308
+ // what each action changed, when the shoot measured it (it does by default)
309
+ /** @type {unknown} */
310
+ let comp = null;
311
+ try {
312
+ const r = await fetch(new URL("components.json", base));
313
+ if (r.ok) comp = await r.json();
314
+ } catch {
315
+ /* a shoot without components.json: changes() says so */
316
+ }
317
+
318
+ /** @param {number} i */
319
+ const still = (i) => {
320
+ const s = log.stills[i];
321
+ if (!s) throw new Error(`stills: there is no still ${i} (the shoot has ${log.stills.length})`);
322
+ return s;
323
+ };
324
+ const cache = stillCache({
325
+ keep,
326
+ ahead,
327
+ count: log.stills.length,
328
+ open: (i) => {
329
+ const im = new Image();
330
+ const src = new URL(still(i).file, base).href;
331
+ im.src = src;
332
+ return {
333
+ ready: im.decode().then(
334
+ () => im,
335
+ () => {
336
+ throw new Error(`stills: ${src} could not be decoded`);
337
+ },
338
+ ),
339
+ cancel: () => {
340
+ im.src = ""; // stops the fetch and the decode
341
+ },
342
+ };
343
+ },
344
+ });
345
+
346
+ return {
347
+ log,
348
+ count: log.stills.length,
349
+ /**
350
+ * The still to show at t when stills from `from` play at `rate` a second
351
+ * from `start` (s). Whole frames of film time pick whole stills: a tiny
352
+ * float error never repeats one.
353
+ * @param {number} t
354
+ * @param {{ from?: number, start?: number, rate: number, to?: number }} o
355
+ */
356
+ at(t, o) {
357
+ const from = o.from ?? 0;
358
+ const to = o.to ?? log.stills.length - 1;
359
+ const i = from + Math.floor((t - (o.start ?? 0)) * o.rate + 1e-6);
360
+ return Math.max(from, Math.min(to, i));
361
+ },
362
+ /** show still i (decoded first), fetching a few ahead */
363
+ /** @param {number} i */
364
+ async show(i) {
365
+ const im = await cache.take(i);
366
+ if (shown !== i) {
367
+ img.src = im.src;
368
+ await img.decode();
369
+ shown = i;
370
+ }
371
+ },
372
+ /** a box the shoot recorded at still i, by the selector it was tracked
373
+ * with — in the still's own CSS px (the shoot logs page px; the still
374
+ * shows the page from its scroll) */
375
+ /** @param {number} i @param {string} selector */
376
+ box(i, selector) {
377
+ const s = still(i);
378
+ const b = s.boxes?.[selector];
379
+ if (!b) throw new Error(`stills: still ${i} recorded no box for ${selector}`);
380
+ return {
381
+ x: b.x - (s.scroll?.x ?? 0),
382
+ y: b.y - (s.scroll?.y ?? 0),
383
+ width: b.width,
384
+ height: b.height,
385
+ };
386
+ },
387
+ /**
388
+ * The saved screen a still kept (shot with { state: true } or --states):
389
+ * its state.html URL, for screen(iframe, url) — and so lift / isolate.
390
+ * By the still's index, its name, or the screen's id.
391
+ * @param {number | string} key
392
+ */
393
+ state(key) {
394
+ const s =
395
+ typeof key === "number"
396
+ ? still(key)
397
+ : (log.stills.find((x) => x.state === key) ?? log.stills.find((x) => x.name === key));
398
+ if (!s) throw new Error(`stills: no still ${JSON.stringify(key)} in ${logUrl}`);
399
+ if (!s.state)
400
+ throw new Error(
401
+ `stills: ${s.file} kept no saved screen — shoot it with s.still(name, { state: true }) (or --states)`,
402
+ );
403
+ const dir = log.states?.dir ?? "states";
404
+ return new URL(`${dir}/${s.state}/state.html`, base).href;
405
+ },
406
+ /**
407
+ * What the action before a saved screen changed there (changesIn): the
408
+ * parts that appeared or changed, innermost first, each with what it
409
+ * showed before and now, the text it gained, and its box in the still's
410
+ * own CSS px; `still` is the still that shows that screen. By a still's
411
+ * index or name (the screen it shows: its own, else the last one kept
412
+ * before it) or a screen's id.
413
+ *
414
+ * const c = st.changes("matched"); // { screen, since, action, still, parts }
415
+ * cam.frame(c.parts[0].box, { arrive: 6 });
416
+ * @param {number | string} key
417
+ */
418
+ changes(key) {
419
+ if (!comp)
420
+ throw new Error(
421
+ `stills: no components.json beside ${logUrl} — the shoot writes one unless --no-components; \`open-take components <dir>\` measures one afterwards`,
422
+ );
423
+ const ids = new Set(/** @type {any} */ (comp).states.map((/** @type {any} */ x) => x.id));
424
+ /** @param {number} i */
425
+ const shownBy = (i) => {
426
+ for (let k = i; k >= 0; k--) {
427
+ const s = log.stills[k]?.state;
428
+ if (s && ids.has(s)) return s;
429
+ }
430
+ return null;
431
+ };
432
+ /** @type {string | null} */
433
+ let id = null;
434
+ if (typeof key === "number") {
435
+ still(key); // throws for a still the shoot does not have
436
+ id = shownBy(key);
437
+ } else if (ids.has(key)) id = key;
438
+ else {
439
+ const i = log.stills.findIndex((x) => x.name === key);
440
+ if (i >= 0) id = shownBy(i);
441
+ }
442
+ if (!id) throw new Error(`stills: no saved screen for ${JSON.stringify(key)} in ${logUrl}`);
443
+ const c = changesIn(comp, id);
444
+ const i = log.stills.findIndex((x) => x.state === id);
445
+ return { ...c, still: i >= 0 ? i : null };
446
+ },
447
+ /** where the shoot's cursor was at still i, in the still's own CSS px */
448
+ /** @param {number} i */
449
+ cursor(i) {
450
+ const s = still(i);
451
+ if (!s.cursor) throw new Error(`stills: still ${i} recorded no cursor`);
452
+ return { x: s.cursor.x - (s.scroll?.x ?? 0), y: s.cursor.y - (s.scroll?.y ?? 0) };
453
+ },
454
+ /** the names of what the shoot kept of the product's output (s.save), in order */
455
+ outputs: (log.outputs ?? []).map((/** @type {any} */ o) => o.name),
456
+ /**
457
+ * Something the product made, as the shoot kept it with s.save: its URL
458
+ * (an <img>'s src, a fetch, an <object>), its kind (svg, png, image,
459
+ * text, picture, download), its size in CSS px, its text, and `still`,
460
+ * the still just before it — the product's moment it belongs to.
461
+ *
462
+ * const o = st.output("shape"); // { url, kind, w, h, text, still, … }
463
+ * img.src = o.url;
464
+ * @param {string} name
465
+ */
466
+ output(name) {
467
+ const o = (log.outputs ?? []).find((/** @type {any} */ x) => x.name === name);
468
+ if (!o)
469
+ throw new Error(
470
+ `stills: the shoot saved nothing called ${JSON.stringify(name)} — it has ${(log.outputs ?? []).map((/** @type {any} */ x) => JSON.stringify(x.name)).join(", ") || "none (s.save(name, target) keeps one)"}`,
471
+ );
472
+ return { ...o, url: new URL(o.file, base).href, still: o.still ?? null };
473
+ },
474
+ };
475
+ }
476
+
477
+ // --- what an action changed: components.json, by screen ------------------------
478
+
479
+ /**
480
+ * One part an action changed, as components.json measured it on the screen
481
+ * the action led to.
482
+ * @typedef {object} Change
483
+ * @property {string} ref the part on this screen ("<screen>:<element id>")
484
+ * @property {string} kind number, stat, heading, button, input, card, …
485
+ * @property {string} label
486
+ * @property {"appeared" | "changed" | "restyled" | "moved"} what
487
+ * @property {string} now what it shows now, in full
488
+ * @property {string | null} was what it showed on the screen before (null when it appeared)
489
+ * @property {string} added the text it gained (was → now, the common start and end left out)
490
+ * @property {string} removed the text it lost
491
+ * @property {string | null} restyled "disabled: true → –", "fill #fff → #e7f0ff", …
492
+ * @property {Box} box where it is on the screen, in the screen's CSS px
493
+ * @property {boolean} inner no other changed part sits inside it (the change itself, not a panel round it)
494
+ */
495
+
496
+ /**
497
+ * What `now` gained over `was` and what it lost, the common start and end
498
+ * left out, in whole words of `now`. Compared without whitespace, because a
499
+ * screen's fact strings run words together ("3 matches46 steps"); a `was`
500
+ * cut short with "…" has no common end.
501
+ * @param {string} was
502
+ * @param {string} now
503
+ */
504
+ export function wordDiff(was, now) {
505
+ const cut = was.endsWith("…");
506
+ const w = cut ? was.slice(0, -1) : was;
507
+ /** the non-space characters of s, each with its index in s and its word's number */
508
+ const chars = (/** @type {string} */ str) => {
509
+ /** @type {{ c: string, i: number, word: number }[]} */
510
+ const out = [];
511
+ let word = 0;
512
+ let inWord = false;
513
+ for (let i = 0; i < str.length; i++) {
514
+ const c = str[i] ?? "";
515
+ if (/\s/.test(c)) {
516
+ if (inWord) word++;
517
+ inWord = false;
518
+ } else {
519
+ out.push({ c, i, word });
520
+ inWord = true;
521
+ }
522
+ }
523
+ return out;
524
+ };
525
+ const A = chars(w);
526
+ const B = chars(now);
527
+ let p = 0;
528
+ while (p < A.length && p < B.length && A[p]?.c === B[p]?.c) p++;
529
+ let q = 0;
530
+ if (!cut)
531
+ while (
532
+ q < A.length - p &&
533
+ q < B.length - p &&
534
+ A[A.length - 1 - q]?.c === B[B.length - 1 - q]?.c
535
+ )
536
+ q++;
537
+ // whole words of now: a word only partly in the common start or end is not common
538
+ while (p > 0 && p < B.length && B[p - 1]?.word === B[p]?.word) p--;
539
+ while (q > 0 && q < B.length - p && B[B.length - q]?.word === B[B.length - 1 - q]?.word) q--;
540
+ const span = (/** @type {typeof A} */ X, /** @type {string} */ str) => {
541
+ const from = X[p]?.i ?? str.length;
542
+ const to = q > 0 ? (X[X.length - q]?.i ?? str.length) : str.length;
543
+ return from < to ? str.slice(from, to).trim() : "";
544
+ };
545
+ return { added: span(B, now), removed: span(A, w) };
546
+ }
547
+
548
+ /**
549
+ * What the action before a screen changed there: every part components.json
550
+ * found changed, appeared, moved or restyled, the innermost first (a number
551
+ * before the card it is in), with what it showed before and now in full and
552
+ * the text it gained or lost. Facts only: nothing here picks one to show.
553
+ * @param {unknown} file components.json, parsed
554
+ * @param {string} id the screen's id
555
+ * @returns {{ screen: string, since: string | null, action: { kind: string, label?: string, acted?: string } | null, parts: Change[] }}
556
+ */
557
+ export function changesIn(file, id) {
558
+ const f = /** @type {any} */ (file ?? {});
559
+ if (!f || typeof f !== "object" || !Array.isArray(f.components) || !Array.isArray(f.states))
560
+ throw new Error("changes: this is not a components.json (no components or screens)");
561
+ const states = /** @type {any[]} */ (f.states);
562
+ const at = states.findIndex((x) => x.id === id);
563
+ if (at < 0)
564
+ throw new Error(
565
+ `changes: no screen ${id} — components.json has ${states.map((x) => x.id).join(", ") || "none"}`,
566
+ );
567
+ const st = states[at];
568
+ /** @type {Map<string, any>} */
569
+ const entries = new Map();
570
+ for (const e of f.components) if (e && typeof e.ref === "string") entries.set(e.ref, e);
571
+ const textOf = (/** @type {any} */ e) => e?.values?.text?.text ?? e?.label ?? "";
572
+ const sides = (/** @type {string} */ v) => {
573
+ const m = / → /.exec(v ?? "");
574
+ return m ? [v.slice(0, m.index), v.slice(m.index + 3)] : [v ?? "", ""];
575
+ };
576
+ const refs = /** @type {string[]} */ (Array.isArray(st.action?.changes) ? st.action.changes : []);
577
+ // parts on this screen that say so themselves, in case the action's list is short
578
+ for (const e of entries.values()) {
579
+ const fa = e.facts ?? {};
580
+ if (
581
+ e.ref.startsWith(`${id}:`) &&
582
+ (fa.changed || fa.appeared || fa.moved || fa.restyled) &&
583
+ !refs.includes(e.ref)
584
+ )
585
+ refs.push(e.ref);
586
+ }
587
+ /** @type {Change[]} */
588
+ const parts = [];
589
+ for (const ref of refs) {
590
+ const e = entries.get(ref);
591
+ if (!e?.box) continue;
592
+ const fa = e.facts ?? {};
593
+ const what = fa.appeared
594
+ ? "appeared"
595
+ : fa.changed
596
+ ? "changed"
597
+ : fa.moved
598
+ ? "moved"
599
+ : fa.restyled
600
+ ? "restyled"
601
+ : "changed";
602
+ const now = textOf(e);
603
+ const prev = e.before ? entries.get(e.before) : null;
604
+ const was =
605
+ what === "appeared" ? null : prev ? textOf(prev) : fa.changed ? sides(fa.changed)[0] : null;
606
+ const { added, removed } = was == null ? { added: now, removed: "" } : wordDiff(was, now);
607
+ parts.push({
608
+ ref,
609
+ kind: e.kind ?? "",
610
+ label: e.label ?? "",
611
+ what,
612
+ now,
613
+ was,
614
+ added,
615
+ removed,
616
+ restyled: typeof fa.restyled === "string" ? fa.restyled : null,
617
+ box: boxFrom(e.box),
618
+ inner: true,
619
+ });
620
+ }
621
+ const within = (/** @type {Box} */ a, /** @type {Box} */ b) =>
622
+ a !== b &&
623
+ a.x >= b.x - 0.5 &&
624
+ a.y >= b.y - 0.5 &&
625
+ a.x + a.width <= b.x + b.width + 0.5 &&
626
+ a.y + a.height <= b.y + b.height + 0.5 &&
627
+ a.width * a.height < b.width * b.height;
628
+ for (const p of parts) p.inner = !parts.some((q) => q !== p && within(q.box, p.box));
629
+ const rank = { appeared: 0, changed: 0, moved: 1, restyled: 2 };
630
+ parts.sort(
631
+ (p, q) =>
632
+ Number(q.inner) - Number(p.inner) ||
633
+ rank[p.what] - rank[q.what] ||
634
+ p.box.y - q.box.y ||
635
+ p.box.x - q.box.x,
636
+ );
637
+ const a = st.action;
638
+ return {
639
+ screen: id,
640
+ since: at > 0 ? states[at - 1].id : null,
641
+ action: a?.kind
642
+ ? {
643
+ kind: a.kind,
644
+ ...(a.label ? { label: a.label } : {}),
645
+ ...(a.acted ? { acted: a.acted } : {}),
646
+ }
647
+ : null,
648
+ parts,
649
+ };
650
+ }
651
+
652
+ // --- a take: its recording, its actions, its saved states ----------------------
653
+
654
+ /**
655
+ * One action as the capture logged it (capture.json `events`): times in ms on
656
+ * the capture's clock, places in the viewport's CSS px.
657
+ * @typedef {object} TakeAction
658
+ * @property {string} [kind] "click" when absent
659
+ * @property {number} tMs when the input happened
660
+ * @property {number} x
661
+ * @property {number} y
662
+ * @property {{ x: number, y: number, w: number, h: number }} [box]
663
+ * @property {number} [durationMs]
664
+ * @property {string} [text]
665
+ * @property {string} [keys]
666
+ * @property {string} [sel]
667
+ * @property {string} [state]
668
+ * @property {{ atMs: number, doneMs: number, box: { x: number, y: number, w: number, h: number } }} [result]
669
+ * @property {number} [settledMs]
670
+ */
671
+ /**
672
+ * @typedef {object} TakeLog
673
+ * @property {{ w: number, h: number }} viewport
674
+ * @property {TakeAction[]} events
675
+ * @property {number} [tEndMs]
676
+ * @property {{ dir: string, items: { id: string, tMs: number, step?: number, moving?: true,
677
+ * fidelity?: { psnr: number, diffFrac: number, ok: boolean },
678
+ * seam?: { dx: number, dy: number, meanDiff: number, diffFrac: number } }[] }} [states]
679
+ */
680
+ /**
681
+ * @typedef {object} Take
682
+ * @property {TakeLog} log
683
+ * @property {string} video the recording's URL (capture.mp4)
684
+ * @property {(id: string) => string} state a saved state's state.html URL
685
+ * @property {(key: string | number) => ReturnType<typeof changesIn> & { tMs: number | null }} changes what an action changed (changesIn)
686
+ */
687
+
688
+ /**
689
+ * A take made by `open-take make` (`--states` for saved states): its
690
+ * capture.json read, and where its recording and states are.
691
+ * @param {string} url the take's folder (…/x.take/) or its capture.json
692
+ * @returns {Promise<Take>}
693
+ */
694
+ export async function readTake(url) {
695
+ const base = new URL(
696
+ /\.json$/.test(url) ? url : `${url.replace(/\/?$/, "/")}capture.json`,
697
+ location.href,
698
+ );
699
+ const res = await fetch(base);
700
+ if (!res.ok) throw new Error(`readTake: ${base.href} could not be read (${res.status})`);
701
+ const log = await res.json();
702
+ /** @type {unknown} */
703
+ let comp = null;
704
+ try {
705
+ const r = await fetch(new URL("components.json", base));
706
+ if (r.ok) comp = await r.json();
707
+ } catch {
708
+ /* recorded without --states: changes() says so */
709
+ }
710
+ return fromLog(log, base.href, comp);
711
+ }
712
+
713
+ /**
714
+ * A take from a capture log already in hand — `base` is where capture.json
715
+ * sits, for the recording's and the states' URLs.
716
+ * @param {TakeLog} log
717
+ * @param {string} base
718
+ * @param {unknown} [comp] its components.json, parsed, for changes()
719
+ * @returns {Take}
720
+ */
721
+ export function fromLog(log, base, comp = null) {
722
+ if (!log || !Array.isArray(log.events) || !log.viewport)
723
+ throw new Error("take: not a capture log (no events or viewport)");
724
+ return {
725
+ log,
726
+ video: new URL("capture.mp4", base).href,
727
+ /**
728
+ * What an action changed on the saved state it led to (changesIn): by
729
+ * the state's id or the plan step's index. `tMs` is when that state was
730
+ * saved, on the capture's clock.
731
+ * @param {string | number} key
732
+ */
733
+ changes: (key) => {
734
+ if (!comp)
735
+ throw new Error(
736
+ "take: no components.json — record with --states (it is written with them; --no-components skips it)",
737
+ );
738
+ const item =
739
+ typeof key === "number"
740
+ ? log.states?.items.find((s) => s.step === key)
741
+ : log.states?.items.find((s) => s.id === key);
742
+ const id = item?.id ?? (typeof key === "string" ? key : null);
743
+ if (!id) throw new Error(`take: no saved state after step ${key}`);
744
+ return { ...changesIn(comp, id), tMs: item?.tMs ?? null };
745
+ },
746
+ state: (id) => {
747
+ if (!log.states?.items.some((s) => s.id === id))
748
+ throw new Error(
749
+ `take: no saved state ${id} (record with --states; \`open-take states\` lists them)`,
750
+ );
751
+ return new URL(`${log.states.dir}/${id}/state.html`, base).href;
752
+ },
753
+ };
754
+ }
755
+
756
+ /**
757
+ * How film time maps onto a recording: the part of it a film shows, from
758
+ * where and how fast. Either a start and a speed — the recording's `from`
759
+ * (s) shows at film time `at`, then plays at `speed` (recording seconds a
760
+ * film second; 1 is as it happened) until its `to` — or `keys`, pairs of
761
+ * [film s, recording s] joined by straight lines, for a clip that slows down
762
+ * around a click and hurries through the waiting. `fileStart`: when the
763
+ * video file was cut from the recording, the recording time its first frame
764
+ * shows (so videoTime(t) is a time in that file).
765
+ * @param {{ at?: number, from?: number, to?: number, speed?: number,
766
+ * keys?: [number, number][], fileStart?: number }} o
767
+ */
768
+ export function clip(o) {
769
+ const fileStart = o.fileStart ?? 0;
770
+ /** film times and the recording times they show, joined by straight lines */
771
+ /** @type {number[]} */
772
+ const F = [];
773
+ /** @type {number[]} */
774
+ const C = [];
775
+ // a clip given no end runs on at its speed
776
+ let open = false;
777
+ if (o.keys) {
778
+ if (o.keys.length < 2) throw new Error("clip: keys needs two [film, recording] pairs at least");
779
+ for (const [f, c] of o.keys) {
780
+ const n = F.length;
781
+ if (!Number.isFinite(f) || !Number.isFinite(c))
782
+ throw new Error(`clip: key ${n} is not two times`);
783
+ if (
784
+ n &&
785
+ (!(f > /** @type {number} */ (F[n - 1])) || !(c >= /** @type {number} */ (C[n - 1])))
786
+ )
787
+ throw new Error(
788
+ `clip: keys must move forward — film time rising, recording time not falling (pair ${n})`,
789
+ );
790
+ F.push(f);
791
+ C.push(c);
792
+ }
793
+ } else {
794
+ const at = o.at ?? 0;
795
+ const from = o.from ?? 0;
796
+ const speed = o.speed ?? 1;
797
+ if (!(speed > 0))
798
+ throw new Error(`clip: speed is recording seconds a film second, above 0 (got ${speed})`);
799
+ if (![at, from].every(Number.isFinite)) throw new Error("clip: at and from are times (s)");
800
+ const to = o.to ?? Number.POSITIVE_INFINITY;
801
+ if (!(to > from)) throw new Error(`clip: to (${to}) must come after from (${from})`);
802
+ open = !Number.isFinite(to);
803
+ F.push(at, at + (open ? 1 : (to - from) / speed));
804
+ C.push(from, open ? from + speed : to);
805
+ }
806
+ const n = F.length;
807
+ /** @param {number[]} a @param {number} i */
808
+ const get = (a, i) => /** @type {number} */ (a[i]);
809
+ /** film s → recording s (held at the ends, or run on when open) @param {number} t */
810
+ const toCapture = (t) => {
811
+ if (t <= get(F, 0)) return get(C, 0);
812
+ for (let i = 1; i < n; i++)
813
+ if (t <= get(F, i) || (open && i === n - 1))
814
+ return (
815
+ get(C, i - 1) +
816
+ ((get(C, i) - get(C, i - 1)) * (t - get(F, i - 1))) / (get(F, i) - get(F, i - 1))
817
+ );
818
+ return get(C, n - 1);
819
+ };
820
+ /** recording s → the first film s showing it, or null when the clip never
821
+ * does @param {number} c */
822
+ const toFilm = (c) => {
823
+ if (c < get(C, 0) - 1e-9) return null;
824
+ for (let i = 1; i < n; i++) {
825
+ const c0 = get(C, i - 1);
826
+ const c1 = get(C, i);
827
+ if (c <= c1 + 1e-9 || (open && i === n - 1))
828
+ return c1 === c0
829
+ ? get(F, i - 1)
830
+ : get(F, i - 1) + ((get(F, i) - get(F, i - 1)) * (c - c0)) / (c1 - c0);
831
+ }
832
+ return null;
833
+ };
834
+ return {
835
+ /** film time the clip starts (s) */
836
+ start: get(F, 0),
837
+ /** film time it ends (s); Infinity when it was given no end */
838
+ end: open ? Number.POSITIVE_INFINITY : get(F, n - 1),
839
+ /** the span of the recording it shows (s) */
840
+ from: get(C, 0),
841
+ to: open ? Number.POSITIVE_INFINITY : get(C, n - 1),
842
+ toCapture,
843
+ toFilm,
844
+ /** where to seek the video element at film time t (s, in the file) @param {number} t */
845
+ videoTime: (t) => toCapture(t) - fileStart,
846
+ };
847
+ }
848
+
849
+ /** @typedef {ReturnType<typeof clip>} Clip */
850
+
851
+ /**
852
+ * @typedef {object} ClipEvent
853
+ * @property {number} t film time (s)
854
+ * @property {string} kind the action's kind ("click", "type", "press", …), or
855
+ * "key" (one character of a typed text), "result" (its result showed),
856
+ * "resultDone" (its result stopped changing), "settled" (the page went quiet)
857
+ * @property {"measured" | "estimated"} basis logged or read off the
858
+ * recording / spread evenly or guessed from page structure
859
+ * @property {string} action which action, a1… in capture order (`open-take states` names them so)
860
+ * @property {number} capture recording time (s)
861
+ * @property {number} [x] where (CSS px of the viewport, or what `map` gives)
862
+ * @property {number} [y]
863
+ * @property {Box} [box] the control, or for a result the region that changed
864
+ * @property {string} [label]
865
+ * @property {number | "not detected" | "outside the clip"} [resultAt] on an input: film time
866
+ * its result showed — "outside the clip" when it was measured but the clip ends first
867
+ * @property {number | "not detected" | "outside the clip"} [resultDone]
868
+ * @property {number} [settled]
869
+ */
870
+
871
+ /**
872
+ * A take's actions as film events, through a clip's time map: each input at
873
+ * the film time the clip shows it, and — apart from it — when its result
874
+ * showed (measured off the recording by `make`; older takes: `open-take
875
+ * states <take> --measure`). Actions outside the clip are left out.
876
+ * `tl`: also declare each one on a timeline (kit/time.js), for the score.
877
+ * `map`: viewport px → stage px, e.g. through the camera. `keys`: a typed
878
+ * text as one "key" event a character, spread evenly over its duration
879
+ * (estimated — the capture logs when typing ran, not each key).
880
+ * @param {Take | TakeLog} take
881
+ * @param {Clip} c
882
+ * @param {{ tl?: { event: (at: number, kind: string, o?: { x?: number, y?: number, label?: string }) => number },
883
+ * kinds?: string[], keys?: boolean, map?: (x: number, y: number, t: number) => number[] }} [o]
884
+ * @returns {ClipEvent[]}
885
+ */
886
+ export function clipEvents(take, c, o = {}) {
887
+ const log = "log" in take ? take.log : take;
888
+ /** @type {ClipEvent[]} */
889
+ const out = [];
890
+ /** @param {{ x: number, y: number, w: number, h: number } | undefined} b */
891
+ const asBox = (b) => (b ? { x: b.x, y: b.y, width: b.w, height: b.h } : undefined);
892
+ /** @param {number} x @param {number} y @param {number} t */
893
+ const at = (x, y, t) => {
894
+ if (!o.map) return { x, y };
895
+ const [mx, my] = o.map(x, y, t);
896
+ return { x: mx, y: my };
897
+ };
898
+ log.events.forEach((e, i) => {
899
+ const action = `a${i + 1}`;
900
+ const kind = e.kind ?? "click";
901
+ const t = c.toFilm(e.tMs / 1000);
902
+ if (t == null || t > c.end) return;
903
+ const film = (/** @type {number} */ ms) => {
904
+ const f = c.toFilm(ms / 1000);
905
+ return f == null || f > c.end ? null : f;
906
+ };
907
+ // measured, but past what the clip shows: said so, not "not detected"
908
+ const shown = (/** @type {number | null} */ f) =>
909
+ f ?? (e.result ? /** @type {const} */ ("outside the clip") : "not detected");
910
+ const resultAt = e.result ? film(e.result.atMs) : null;
911
+ const resultDone = e.result ? film(e.result.doneMs) : null;
912
+ const settled = e.settledMs != null ? film(e.settledMs) : null;
913
+ /** @type {ClipEvent} */
914
+ const input = {
915
+ t,
916
+ kind,
917
+ basis: "measured",
918
+ action,
919
+ capture: e.tMs / 1000,
920
+ ...at(e.x, e.y, t),
921
+ ...(e.box ? { box: asBox(e.box) } : {}),
922
+ ...(e.sel || e.text || e.keys ? { label: e.keys ?? e.text ?? e.sel } : {}),
923
+ resultAt: shown(resultAt),
924
+ resultDone: shown(resultDone),
925
+ ...(settled != null ? { settled } : {}),
926
+ };
927
+ out.push(input);
928
+ const typing = e.durationMs ?? 0;
929
+ if (o.keys && kind === "type" && e.text && typing > 0) {
930
+ const chars = [...e.text];
931
+ chars.forEach((ch, k) => {
932
+ const kt = film(e.tMs + (typing * (k + 0.5)) / chars.length);
933
+ if (kt != null)
934
+ out.push({
935
+ t: kt,
936
+ kind: "key",
937
+ basis: "estimated",
938
+ action,
939
+ capture: c.toCapture(kt),
940
+ ...at(e.x, e.y, kt),
941
+ label: ch,
942
+ });
943
+ });
944
+ }
945
+ if (e.result && resultAt != null) {
946
+ const b = e.result.box;
947
+ out.push({
948
+ t: resultAt,
949
+ kind: "result",
950
+ basis: "measured",
951
+ action,
952
+ capture: e.result.atMs / 1000,
953
+ ...at(b.x + b.w / 2, b.y + b.h / 2, resultAt),
954
+ box: asBox(b),
955
+ });
956
+ if (resultDone != null && resultDone > resultAt)
957
+ out.push({
958
+ t: resultDone,
959
+ kind: "resultDone",
960
+ basis: "measured",
961
+ action,
962
+ capture: e.result.doneMs / 1000,
963
+ ...at(b.x + b.w / 2, b.y + b.h / 2, resultDone),
964
+ box: asBox(b),
965
+ });
966
+ }
967
+ if (settled != null)
968
+ out.push({
969
+ t: settled,
970
+ kind: "settled",
971
+ basis: "estimated",
972
+ action,
973
+ capture: /** @type {number} */ (e.settledMs) / 1000,
974
+ });
975
+ });
976
+ const kept = (o.kinds ? out.filter((e) => o.kinds?.includes(e.kind)) : out).sort(
977
+ (a, b) => a.t - b.t,
978
+ );
979
+ if (o.tl)
980
+ for (const e of kept)
981
+ o.tl.event(e.t, e.kind, {
982
+ ...(e.x != null ? { x: e.x, y: e.y } : {}),
983
+ label: e.label != null ? `${e.action} ${e.label}` : e.action,
984
+ });
985
+ return kept;
986
+ }
987
+
988
+ /**
989
+ * Cutting from the recording to a saved state of the same moment, without a
990
+ * jump. Says when the two show the same thing — the stretch of film time
991
+ * from the state's action being done (its result stopped changing, measured;
992
+ * else the page went quiet, estimated; else the input) to the next input —
993
+ * and where to put the state so it lands on the video: a transform for the
994
+ * state's layer — a positioned box of the viewport's size holding its
995
+ * iframe, at the stage's 0, 0 with transform-origin 0 0 — when the video is
996
+ * shown at `video` (stage px; default the viewport's size at 0, 0). On the
997
+ * layer rather than the iframe itself, lift(), isolate() and box() still
998
+ * measure the screen, in the layer's px, and what they make moves with it —
999
+ * so a lifted part's rect and place() are in the state's px too: a stage box
1000
+ * b is ((b.x − offset.x) / scale, (b.y − offset.y) / scale, b.width / scale,
1001
+ * b.height / scale) there (full frame is not the stage's size unless the
1002
+ * scale is 1).
1003
+ * `residual` is what `make` measured between the recording's frame and the
1004
+ * state's screenshot: the shift left (CSS px) and the difference at it.
1005
+ * @param {Take | TakeLog} take
1006
+ * @param {Clip} c
1007
+ * @param {string} id the state ("s3")
1008
+ * @param {{ video?: { x?: number, y?: number, width: number, height: number } }} [o]
1009
+ */
1010
+ export function seam(take, c, id, o = {}) {
1011
+ const log = "log" in take ? take.log : take;
1012
+ const item = log.states?.items.find((s) => s.id === id);
1013
+ if (!item) throw new Error(`seam: no saved state ${id} in the take`);
1014
+ if (item.moving)
1015
+ throw new Error(`seam: nothing was saved at ${id} — the page was still moving there`);
1016
+ const vw = log.viewport.w;
1017
+ const vh = log.viewport.h;
1018
+ const v = o.video ?? { x: 0, y: 0, width: vw, height: vh };
1019
+ const sx = v.width / vw;
1020
+ const sy = v.height / vh;
1021
+ if (Math.abs(sx - sy) > 1e-3 * Math.max(sx, sy))
1022
+ throw new Error(
1023
+ `seam: the video is shown at ${v.width}×${v.height}, not the viewport's ${vw}:${vh} shape — a state cannot be stretched onto it`,
1024
+ );
1025
+ const s = item.seam;
1026
+ const dx = s ? s.dx : 0;
1027
+ const dy = s ? s.dy : 0;
1028
+ const x = (v.x ?? 0) + dx * sx;
1029
+ const y = (v.y ?? 0) + dy * sx;
1030
+ // the stretch of the recording the state stands for
1031
+ const before = log.events.filter((e) => e.tMs <= item.tMs);
1032
+ const last = before[before.length - 1];
1033
+ const next = log.events.find((e) => e.tMs > item.tMs);
1034
+ /** @type {[number, "measured" | "estimated"]} */
1035
+ let from = [0, "measured"];
1036
+ if (last)
1037
+ from = last.result
1038
+ ? [last.result.doneMs, "measured"]
1039
+ : last.settledMs != null
1040
+ ? [last.settledMs, "estimated"]
1041
+ : [last.tMs + (last.durationMs ?? 0), "estimated"];
1042
+ const until = next ? next.tMs : (log.tEndMs ?? item.tMs);
1043
+ // a clip that starts inside that stretch shows it from its own start
1044
+ const lo = Math.min(from[0], item.tMs) / 1000;
1045
+ const hi = Math.max(until, item.tMs) / 1000;
1046
+ if (lo < c.from && hi >= c.from) from = [c.from * 1000, "measured"];
1047
+ const filmLo = hi >= c.from ? c.toFilm(Math.max(lo, c.from)) : null;
1048
+ const filmHi = c.toFilm(hi) ?? c.end;
1049
+ const filmAt = c.toFilm(item.tMs / 1000);
1050
+ return {
1051
+ state: id,
1052
+ /** film time the clip shows the moment the state was saved, or null */
1053
+ at: filmAt != null && filmAt <= c.end ? filmAt : null,
1054
+ /** film times the video and the state show the same page — clipped to
1055
+ * the clip; null when the clip does not show that stretch */
1056
+ window:
1057
+ filmLo != null && filmLo <= c.end
1058
+ ? {
1059
+ from: filmLo,
1060
+ to: Math.min(filmHi, c.end),
1061
+ basis: { from: from[1], to: /** @type {const} */ ("measured") },
1062
+ }
1063
+ : null,
1064
+ /** scale of state px to stage px, and where the state's 0, 0 goes on the stage */
1065
+ scale: sx,
1066
+ offset: { x, y },
1067
+ /** for the state's layer, the box holding its iframe (transform-origin
1068
+ * 0 0, at the stage's 0, 0) */
1069
+ transform: `translate(${x.toFixed(2)}px, ${y.toFixed(2)}px) scale(${sx.toFixed(6)})`,
1070
+ residual: s
1071
+ ? {
1072
+ dx: s.dx,
1073
+ dy: s.dy,
1074
+ meanDiff: s.meanDiff,
1075
+ diffFrac: s.diffFrac,
1076
+ basis: /** @type {const} */ ("measured"),
1077
+ }
1078
+ : { basis: /** @type {const} */ ("not detected") },
1079
+ fidelity: item.fidelity ?? null,
1080
+ };
1081
+ }
1082
+
1083
+ // --- one real part of a saved screen, as a layer of its own ----------------------
1084
+
1085
+ /** @typedef {{ x: number, y: number, width?: number, height?: number, w?: number, h?: number }} BoxLike */
1086
+
1087
+ /** @param {BoxLike} b @returns {Box} */
1088
+ const boxOf = (b) => ({ x: b.x, y: b.y, width: b.width ?? b.w ?? 0, height: b.height ?? b.h ?? 0 });
1089
+
1090
+ /** the smallest box holding all of `bs` @param {Box[]} bs @returns {Box} */
1091
+ function unionOf(bs) {
1092
+ let x0 = Number.POSITIVE_INFINITY;
1093
+ let y0 = Number.POSITIVE_INFINITY;
1094
+ let x1 = Number.NEGATIVE_INFINITY;
1095
+ let y1 = Number.NEGATIVE_INFINITY;
1096
+ for (const b of bs) {
1097
+ x0 = Math.min(x0, b.x);
1098
+ y0 = Math.min(y0, b.y);
1099
+ x1 = Math.max(x1, b.x + b.width);
1100
+ y1 = Math.max(y1, b.y + b.height);
1101
+ }
1102
+ if (!(x1 >= x0 && y1 >= y0)) return { x: 0, y: 0, width: 0, height: 0 };
1103
+ return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
1104
+ }
1105
+
1106
+ /** an element, of this document or of a screen's (whose Element is another realm's) */
1107
+ /** @param {unknown} k @returns {k is Element} */
1108
+ const isElement = (k) =>
1109
+ !!k && typeof k === "object" && /** @type {{ nodeType?: unknown }} */ (k).nodeType === 1;
1110
+
1111
+ /** @param {unknown} k @returns {k is TextKey} */
1112
+ const isTextKey = (k) =>
1113
+ !!k &&
1114
+ typeof k === "object" &&
1115
+ !Array.isArray(k) &&
1116
+ typeof (/** @type {{ text?: unknown }} */ (k).text) === "string";
1117
+
1118
+ /** a part of product() — anything that says which element it is on a saved
1119
+ * screen, and where it is at t @param {unknown} k @returns {k is Part} */
1120
+ const isPart = (k) =>
1121
+ !!k &&
1122
+ typeof k === "object" &&
1123
+ typeof (/** @type {{ in?: unknown }} */ (k).in) === "function" &&
1124
+ typeof (/** @type {{ boxAt?: unknown }} */ (k).boxAt) === "function";
1125
+
1126
+ /** a bare box: not an element, a text, a part, a list @param {unknown} k @returns {k is BoxLike} */
1127
+ const isBoxKey = (k) =>
1128
+ !!k && typeof k === "object" && !isElement(k) && !Array.isArray(k) && !isTextKey(k) && !isPart(k);
1129
+
1130
+ /** what a page that cannot be measured is told */
1131
+ /** @param {string} what */
1132
+ const noLayout = (what) =>
1133
+ `${what}: the screen's iframe has no layout (display:none on it or an ancestor) — hide a scene with visibility, or use scenes() (kit/time.js)`;
1134
+
1135
+ /** the saved screen a state.html URL is, by its folder's name ("result"), or null @param {string} url */
1136
+ function stateOf(url) {
1137
+ const m = /\/([^/?#]+)\/state\.html(?:[?#].*)?$/.exec(url);
1138
+ if (!m?.[1]) return null;
1139
+ try {
1140
+ return decodeURIComponent(m[1]);
1141
+ } catch {
1142
+ return m[1];
1143
+ }
1144
+ }
1145
+
1146
+ /**
1147
+ * The index id a key names — "e12", or a ref "result:e12" as `open-take
1148
+ * states` and components.json write it (refused on another state's screen) —
1149
+ * or null when it names none.
1150
+ * @param {string} what @param {string} key @param {string} url the screen's
1151
+ */
1152
+ function idOf(what, key, url) {
1153
+ if (/^e\d+$/.test(key)) return key;
1154
+ const m = /^(.+):(e\d+)$/.exec(key);
1155
+ if (!m?.[1] || !m[2]) return null;
1156
+ const here = stateOf(url);
1157
+ if (here != null && here !== m[1])
1158
+ throw new Error(
1159
+ `${what}: ${key} is a part of the saved screen "${m[1]}", and this screen is "${here}"`,
1160
+ );
1161
+ return m[2];
1162
+ }
1163
+
1164
+ /** collapsed whitespace @param {string} s */
1165
+ const norm = (s) => s.replace(/\s+/g, " ").trim();
1166
+
1167
+ /**
1168
+ * The element that shows `text`: the innermost one whose own text is it (or,
1169
+ * split over several, whose whole text is it), else the first holding it —
1170
+ * then `up` parents out. Only what is laid out counts.
1171
+ * @param {Document} doc @param {TextKey} k @param {string} what
1172
+ */
1173
+ function byText(doc, k, what) {
1174
+ const want = norm(k.text);
1175
+ if (!want) throw new Error(`${what}: { text } is empty`);
1176
+ const root = doc.body ?? doc.documentElement;
1177
+ const skip = /^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/;
1178
+ /** @type {Element | null} */
1179
+ let found = null;
1180
+ /** @type {Element | null} */
1181
+ let partial = null;
1182
+ const walk = doc.createTreeWalker(root, 4 /* NodeFilter.SHOW_TEXT */);
1183
+ for (let n = walk.nextNode(); n; n = walk.nextNode()) {
1184
+ const p = n.parentElement;
1185
+ if (!p || skip.test(p.tagName)) continue;
1186
+ const s = norm(n.nodeValue ?? "");
1187
+ if (!s || !p.getClientRects().length) continue;
1188
+ if (s === want) {
1189
+ found = p;
1190
+ break;
1191
+ }
1192
+ if (!partial && s.includes(want)) partial = p;
1193
+ }
1194
+ if (!found) {
1195
+ const whole = Array.from(root.querySelectorAll("*")).filter(
1196
+ (e) =>
1197
+ !skip.test(e.tagName) && e.getClientRects().length && norm(e.textContent ?? "") === want,
1198
+ );
1199
+ found = whole.find((e) => !whole.some((c) => c !== e && e.contains(c))) ?? null;
1200
+ }
1201
+ let el = found ?? partial;
1202
+ if (!el) throw new Error(`${what}: no element shows the text "${want}" in ${doc.URL}`);
1203
+ for (let i = 0; i < (k.up ?? 0); i++) {
1204
+ if (!el.parentElement)
1205
+ throw new Error(`${what}: "${want}" has fewer than ${k.up} parents in ${doc.URL}`);
1206
+ el = el.parentElement;
1207
+ }
1208
+ return el;
1209
+ }
1210
+
1211
+ /**
1212
+ * Where an element's text is drawn — the union of its text's boxes (each
1213
+ * text run's own extent, not the element's), cut to the element when it
1214
+ * clips what overflows it — or null when it shows no text.
1215
+ * @param {Element} el
1216
+ * @returns {Box | null}
1217
+ */
1218
+ function inkOf(el) {
1219
+ const doc = el.ownerDocument;
1220
+ const view = doc.defaultView;
1221
+ const range = doc.createRange();
1222
+ /** @type {Box[]} */
1223
+ const runs = [];
1224
+ const walk = doc.createTreeWalker(el, 4 /* NodeFilter.SHOW_TEXT */);
1225
+ for (let n = walk.nextNode(); n; n = walk.nextNode()) {
1226
+ const s = n.nodeValue ?? "";
1227
+ const a = s.search(/\S/);
1228
+ if (a < 0) continue;
1229
+ const p = n.parentElement;
1230
+ if (p && view?.getComputedStyle(p).visibility === "hidden") continue;
1231
+ range.setStart(n, a);
1232
+ range.setEnd(n, s.length - (/\s*$/.exec(s)?.[0].length ?? 0));
1233
+ for (const r of Array.from(range.getClientRects()))
1234
+ if (r.width > 0 && r.height > 0)
1235
+ runs.push({ x: r.left, y: r.top, width: r.width, height: r.height });
1236
+ }
1237
+ if (!runs.length) return null;
1238
+ let u = unionOf(runs);
1239
+ const cs = view?.getComputedStyle(el);
1240
+ if (cs && (cs.overflowX !== "visible" || cs.overflowY !== "visible")) {
1241
+ const r = el.getBoundingClientRect();
1242
+ const x0 = Math.max(u.x, r.left);
1243
+ const y0 = Math.max(u.y, r.top);
1244
+ const x1 = Math.min(u.x + u.width, r.right);
1245
+ const y1 = Math.min(u.y + u.height, r.bottom);
1246
+ if (x1 > x0 && y1 > y0) u = { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
1247
+ }
1248
+ return u;
1249
+ }
1250
+
1251
+ /** the non-blank text nodes under an element, in order @param {Element} el */
1252
+ function textNodes(el) {
1253
+ /** @type {Text[]} */
1254
+ const out = [];
1255
+ const walk = el.ownerDocument.createTreeWalker(el, 4 /* NodeFilter.SHOW_TEXT */);
1256
+ for (let n = walk.nextNode(); n; n = walk.nextNode())
1257
+ if ((n.nodeValue ?? "").trim()) out.push(/** @type {Text} */ (n));
1258
+ return out;
1259
+ }
1260
+
1261
+ /**
1262
+ * Where the children of `into` start, against where the document inside
1263
+ * `frame` starts, for a layer that does not hold the screen (an overlay
1264
+ * outside every scene): both measured by layout from the page, with every
1265
+ * transform between them undone — so under a camera, where the part shows at
1266
+ * t is `part.from(cam, t)`.
1267
+ * @param {string} what @param {HTMLIFrameElement} frame @param {HTMLElement} into
1268
+ */
1269
+ function offsetTo(what, frame, into) {
1270
+ if (into.contains(frame)) return offsetWithin(what, frame, into);
1271
+ if (getComputedStyle(into).position === "static")
1272
+ throw new Error(
1273
+ `${what}: the layer it goes into is not positioned — give it position: relative (or absolute)`,
1274
+ );
1275
+ /** the layout position of el's border box on the page, CSS px @param {HTMLElement} el */
1276
+ const page = (el) => {
1277
+ let x = 0;
1278
+ let y = 0;
1279
+ for (let n = el.parentElement; n; n = n.parentElement) {
1280
+ x -= n.scrollLeft;
1281
+ y -= n.scrollTop;
1282
+ }
1283
+ /** @type {Element | null} */
1284
+ let n = el;
1285
+ while (n instanceof HTMLElement) {
1286
+ x += n.offsetLeft;
1287
+ y += n.offsetTop;
1288
+ n = n.offsetParent;
1289
+ if (n instanceof HTMLElement) {
1290
+ x += n.clientLeft;
1291
+ y += n.clientTop;
1292
+ }
1293
+ }
1294
+ return { x, y };
1295
+ };
1296
+ const a = page(frame);
1297
+ const own = getComputedStyle(frame);
1298
+ const b = page(into);
1299
+ return {
1300
+ x:
1301
+ a.x +
1302
+ frame.clientLeft +
1303
+ Number.parseFloat(own.paddingLeft) -
1304
+ (b.x + into.clientLeft - into.scrollLeft),
1305
+ y:
1306
+ a.y +
1307
+ frame.clientTop +
1308
+ Number.parseFloat(own.paddingTop) -
1309
+ (b.y + into.clientTop - into.scrollTop),
1310
+ };
1311
+ }
1312
+
1313
+ /** @param {any} source @returns {{ frame: HTMLIFrameElement, ready: Promise<unknown> }} */
1314
+ function screenOf(source) {
1315
+ if (source instanceof HTMLIFrameElement) return { frame: source, ready: whenLoaded(source) };
1316
+ if (source && source.frame instanceof HTMLIFrameElement)
1317
+ return { frame: source.frame, ready: Promise.all([source.ready, whenLoaded(source.frame)]) };
1318
+ throw new Error("lift: give it a saved screen — screen(iframe) — or its iframe");
1319
+ }
1320
+
1321
+ /** the frame's own document has loaded, and a saved state has finished
1322
+ * putting back what its markup could not carry (its ready flag; a page that
1323
+ * is not a saved state has no restore script, and nothing to wait for)
1324
+ * @param {HTMLIFrameElement} frame */
1325
+ async function whenLoaded(frame) {
1326
+ const loaded = () => {
1327
+ const doc = frame.contentDocument;
1328
+ return !!doc && doc.readyState === "complete" && doc.URL !== "about:blank";
1329
+ };
1330
+ if (!loaded()) await new Promise((ok) => frame.addEventListener("load", ok, { once: true }));
1331
+ const doc = frame.contentDocument;
1332
+ if (!doc) throw new Error(`lift: ${frame.src} is not same-origin — its parts cannot be lifted`);
1333
+ // a saved state marks itself ready once its restore script is done (it
1334
+ // gives up after 6 s); anything else has nothing to wait for
1335
+ // (watched, not polled: under the film's clock a timer here is film time)
1336
+ if (!doc.querySelector("script[data-ot-restore]")) return;
1337
+ const root = doc.documentElement;
1338
+ if (root.dataset.otReady === "1") return;
1339
+ await new Promise((ok) => {
1340
+ const watch = new MutationObserver(() => {
1341
+ if (root.dataset.otReady !== "1") return;
1342
+ watch.disconnect();
1343
+ ok(undefined);
1344
+ });
1345
+ watch.observe(root, { attributes: true, attributeFilter: ["data-ot-ready"] });
1346
+ });
1347
+ }
1348
+
1349
+ /**
1350
+ * A part of product() on the saved screen at `url`: its ref there — the same
1351
+ * element followed through the screens — or an error naming the screens it
1352
+ * is on. A page that is not a saved screen takes the part's own ref.
1353
+ * @param {Part} part @param {string} url @param {string} what
1354
+ */
1355
+ function refOn(part, url, what) {
1356
+ const here = stateOf(url);
1357
+ if (here == null) return part.ref;
1358
+ const ref = part.in(here);
1359
+ if (ref) return ref;
1360
+ const on = part.states.map((s) => s.state);
1361
+ throw new Error(
1362
+ `${what}: ${part.name} is not on the saved screen "${here}"${on.length ? ` — it is on ${on.join(", ")}` : ""}`,
1363
+ );
1364
+ }
1365
+
1366
+ /** an element of a saved screen's document: by selector, by its index id
1367
+ * ("e12", or the ref "result:e12" as `open-take states` names it), by the
1368
+ * text it shows ({ text, up }), a part of product() (its element on this
1369
+ * screen), or the element itself
1370
+ * @param {Document} doc @param {string | Element | TextKey | Part} key @param {string} [what] */
1371
+ function findIn(doc, key, what = "lift") {
1372
+ if (isElement(key)) return key;
1373
+ if (isPart(key)) key = refOn(key, doc.URL, what);
1374
+ if (isTextKey(key)) return byText(doc, key, what);
1375
+ if (typeof key !== "string") throw new Error(`${what}: ${String(key)} is not a part`);
1376
+ const id = idOf(what, key, doc.URL);
1377
+ const el = id ? doc.querySelector(`[data-ot-id="${id}"]`) : doc.querySelector(key);
1378
+ if (!el) throw new Error(`${what}: nothing matches ${key} in ${doc.URL}`);
1379
+ return el;
1380
+ }
1381
+
1382
+ /** child indices from <html> down to el @param {Element} el */
1383
+ function pathOf(el) {
1384
+ /** @type {number[]} */
1385
+ const path = [];
1386
+ for (let n = el; n.parentElement; n = n.parentElement)
1387
+ path.unshift(Array.prototype.indexOf.call(n.parentElement.children, n));
1388
+ return path;
1389
+ }
1390
+
1391
+ /** @param {Document} doc @param {number[]} path */
1392
+ function atPath(doc, path) {
1393
+ /** @type {Element | undefined} */
1394
+ let n = doc.documentElement;
1395
+ for (const i of path) n = n?.children[i];
1396
+ return n ?? null;
1397
+ }
1398
+
1399
+ /** put a layer over a screen: fades (isolate) right over it, lifted parts
1400
+ * over the fades — each above the ones of its kind made before it
1401
+ * @param {HTMLIFrameElement} frame @param {HTMLElement} el @param {"fade" | "lift"} kind */
1402
+ function stackOver(frame, el, kind) {
1403
+ el.dataset.otOver = kind;
1404
+ let at = /** @type {Element} */ (frame);
1405
+ for (
1406
+ let n = at.nextElementSibling;
1407
+ n instanceof HTMLElement && n.dataset.otOver;
1408
+ n = n.nextElementSibling
1409
+ )
1410
+ if (kind === "lift" || n.dataset.otOver === "fade") at = n;
1411
+ at.after(el);
1412
+ }
1413
+
1414
+ /** the first corner radius of an element, in px @param {Element} el */
1415
+ const radiusOf = (el) => Number.parseFloat(getComputedStyle(el).borderTopLeftRadius) || 0;
1416
+
1417
+ /**
1418
+ * A transform that puts a box `from` onto a rect `to` — both in one layer's
1419
+ * px, for an element sitting at `from` with transform-origin 0 0 (its own
1420
+ * top-left corner): `x`, `y` move that corner, `kx`, `ky` scale about it. `fit`:
1421
+ * "contain" (default) scales evenly to fit inside the rect, centred;
1422
+ * "cover" scales evenly to fill it; "fill" stretches to it.
1423
+ * @param {BoxLike} from
1424
+ * @param {BoxLike} to
1425
+ * @param {"contain" | "cover" | "fill"} [fit]
1426
+ */
1427
+ export function fitTransform(from, to, fit = "contain") {
1428
+ const a = boxOf(from);
1429
+ const b = boxOf(to);
1430
+ if (!(a.width > 0 && a.height > 0)) throw new Error("fitTransform: the box to move has no size");
1431
+ let kx = b.width / a.width;
1432
+ let ky = b.height / a.height;
1433
+ if (fit !== "fill") kx = ky = fit === "cover" ? Math.max(kx, ky) : Math.min(kx, ky);
1434
+ const x = b.x + (b.width - a.width * kx) / 2 - a.x;
1435
+ const y = b.y + (b.height - a.height * ky) / 2 - a.y;
1436
+ const f = (/** @type {number} */ v) => v.toFixed(3);
1437
+ return {
1438
+ x,
1439
+ y,
1440
+ kx,
1441
+ ky,
1442
+ css: `translate(${f(x)}px, ${f(y)}px) scale(${kx.toFixed(5)}, ${ky.toFixed(5)})`,
1443
+ };
1444
+ }
1445
+
1446
+ /**
1447
+ * Lift one real part out of a saved screen as a layer of its own — the
1448
+ * clicked card, the number the app worked out — so it can be carried from
1449
+ * where it sat to anywhere, at any size. It is the same saved page again,
1450
+ * shown through a window the part's size: live DOM, so it stays sharp
1451
+ * however big it gets (the renderer rasterizes each frame at its final
1452
+ * scale; a very slow push on small text can step a pixel — see `film
1453
+ * picture` in the guide).
1454
+ *
1455
+ * The layer starts exactly over the part, inside `into` (default: the
1456
+ * screen's own parent, which must be positioned — there it sits above the
1457
+ * screen, its isolate() fades and the parts lifted before it), so lifting
1458
+ * it changes nothing on screen until it moves. `box` is where the part sits in `into`'s
1459
+ * px — what motion.js's handoffs (morphRect, hop…) start from; `place(rect)`
1460
+ * moves it there. The layer takes its visibility from where it sits: in a
1461
+ * hidden scene it is hidden too.
1462
+ *
1463
+ * const s = screen(document.querySelector("#form"));
1464
+ * const card = lift(s, "e126", { around: "clear" }); // or a selector, a ref, { text }, a box
1465
+ * window.__film = { duration: 12, ready: card.ready };
1466
+ * // in __render(t):
1467
+ * card.place(morphRect(t, 4, 4.6, card.box, { x: 160, y: 140, w: 1600, h: 800 }));
1468
+ *
1469
+ * A list of parts is one layer over all of them — `member(i)` says where each
1470
+ * one sits:
1471
+ *
1472
+ * const prices = lift(s, ["e149", "e155", "e156"], { around: "clear" });
1473
+ *
1474
+ * `into` can also be a layer that does not hold the screen (an overlay
1475
+ * outside every scene, so the part survives a scene change): it must be
1476
+ * positioned, and the part's box there is measured by layout, transforms
1477
+ * undone — under a camera, `part.from(cam, t)` says where it shows.
1478
+ *
1479
+ * `around`: "keep" (default) — what was on screen within its box, page
1480
+ * included; "clear" — only the part itself, the rest of the page hidden and
1481
+ * see-through (a selector or id, not a bare box). `box`: "layout" (default)
1482
+ * — the element's box; "ink" — where its text is drawn (a line whose text
1483
+ * is 183 px of its 544 is lifted 183 px wide; an element with no text keeps
1484
+ * its box, and `by` says which was used). `background`: CSS behind it. `pad`:
1485
+ * px of the page kept around its box (a shadow, a focus ring). `radius`: the
1486
+ * window's corner radius (default the part's own). `css`: styles added to
1487
+ * the lifted copy only — restyle it without touching the screen. `parts`:
1488
+ * what `parts()` returns (default its own laid-out children, or a list's
1489
+ * members).
1490
+ *
1491
+ * Inside it, live: `doc` is the copy's document, `find(key)` an element of
1492
+ * it, `parts()` its parts in order (for motion.js's assemble), `text(s)` sets
1493
+ * the text it shows (the text holding its digits, else its first text).
1494
+ * `view(box | null)` changes which part of the screen the window shows (null:
1495
+ * the whole screen) — with `place` to a full frame it un-crops the part into
1496
+ * its page:
1497
+ *
1498
+ * part.view(t < a ? undefined : morphRect(t, a, b, part.source, { x: 0, y: 0, w: 1920, h: 1080 }));
1499
+ * part.place(morphRect(t, a, b, part.rect, { x: 0, y: 0, w: 1920, h: 1080 })); // view first
1500
+ *
1501
+ * @param {any} source a saved screen (screen(iframe)) or its iframe
1502
+ * @param {LiftKey | LiftKey[]} key a selector, an index id ("e12") or ref ("result:e12"), { text, up }, a part of product(), an element of the screen, a box in the screen's px — or a list of them
1503
+ * @param {{ into?: HTMLElement, around?: "keep" | "clear", box?: "layout" | "ink", background?: string, pad?: number,
1504
+ * radius?: number, css?: string, fit?: "contain" | "cover" | "fill", parts?: (string | Element | TextKey)[] }} [o]
1505
+ * @typedef {string | Element | TextKey | Part | BoxLike} LiftKey
1506
+ */
1507
+ export function lift(source, key, o = {}) {
1508
+ const { frame, ready: sourceReady } = screenOf(source);
1509
+ const around = o.around ?? "keep";
1510
+ const pad = o.pad ?? 0;
1511
+ const by = o.box ?? "layout";
1512
+ if (by !== "layout" && by !== "ink")
1513
+ throw new Error(`lift: box is "layout" or "ink" (got ${String(by)})`);
1514
+ const keys = Array.isArray(key) ? key : [key];
1515
+ if (!keys.length) throw new Error("lift: give it a part, or a list of parts, to lift");
1516
+ if (around === "clear" && keys.some(isBoxKey))
1517
+ throw new Error(
1518
+ 'lift: around: "clear" needs a part to keep (a selector, an id or { text }), not a bare box',
1519
+ );
1520
+ const into = o.into ?? frame.parentElement;
1521
+ if (!(into instanceof HTMLElement))
1522
+ throw new Error("lift: the screen has no parent to lift into");
1523
+ /** @param {LiftKey} k */
1524
+ const name = (k) =>
1525
+ typeof k === "string"
1526
+ ? k
1527
+ : isTextKey(k)
1528
+ ? `"${k.text}"`
1529
+ : isElement(k)
1530
+ ? k.tagName.toLowerCase()
1531
+ : isPart(k)
1532
+ ? (k.in(stateOf(frame.src) ?? "") ?? k.ref)
1533
+ : "box";
1534
+ const label = keys.map(name).join(" ");
1535
+ const el = document.createElement("div");
1536
+ el.dataset.otLift = label;
1537
+ Object.assign(el.style, {
1538
+ position: "absolute",
1539
+ left: "0px",
1540
+ top: "0px",
1541
+ overflow: "hidden",
1542
+ transformOrigin: "0 0",
1543
+ pointerEvents: "none",
1544
+ visibility: "hidden", // until it is in place
1545
+ ...(o.background ? { background: o.background } : {}),
1546
+ });
1547
+ const copy = document.createElement("iframe");
1548
+ copy.setAttribute("aria-hidden", "true");
1549
+ copy.tabIndex = -1;
1550
+ Object.assign(copy.style, { position: "absolute", border: "0", background: "transparent" });
1551
+ el.appendChild(copy);
1552
+ if (into === frame.parentElement) stackOver(frame, el, "lift");
1553
+ else into.appendChild(el);
1554
+
1555
+ /** where the part sits at rest: the screen's px, and `into`'s */
1556
+ /** @type {Box | null} */
1557
+ let rest = null;
1558
+ /** @type {Box | null} */
1559
+ let box = null;
1560
+ /** what the window shows now, in the screen's px (view() changes it) */
1561
+ /** @type {Box | null} */
1562
+ let win = null;
1563
+ /** where the screen's 0, 0 is in `into` */
1564
+ let off = { x: 0, y: 0 };
1565
+ /** how far the part moved in the copy (fonts, a restyle) */
1566
+ let shift = { x: 0, y: 0 };
1567
+ /** each member's box, the screen's px */
1568
+ /** @type {Box[]} */
1569
+ let members = [];
1570
+ /** @type {("ink" | "box")[]} */
1571
+ let measuredBy = [];
1572
+ /** @type {(Element | null)[]} */
1573
+ let mine = [];
1574
+ /** the last place(): the transform and the corner it was taken about */
1575
+ /** @type {{ f: ReturnType<typeof fitTransform>, at: Box } | null} */
1576
+ let placed = null;
1577
+ let radius = 0;
1578
+ /** @param {Element | null} t @param {LiftKey} k @returns {{ box: Box, by: "ink" | "box" }} */
1579
+ const measure = (t, k) => {
1580
+ if (!t) return { box: boxOf(/** @type {BoxLike} */ (k)), by: "box" };
1581
+ if (by === "ink") {
1582
+ const i = inkOf(t);
1583
+ if (i) return { box: i, by: "ink" };
1584
+ }
1585
+ const r = t.getBoundingClientRect();
1586
+ return { box: { x: r.left, y: r.top, width: r.width, height: r.height }, by: "box" };
1587
+ };
1588
+ /** the window, in `into`'s px */
1589
+ const winBox = () => {
1590
+ const w = /** @type {Box} */ (win);
1591
+ return { x: off.x + w.x, y: off.y + w.y, width: w.width, height: w.height };
1592
+ };
1593
+ const layout = () => {
1594
+ const w = /** @type {Box} */ (win);
1595
+ const b = winBox();
1596
+ Object.assign(el.style, {
1597
+ left: `${b.x}px`,
1598
+ top: `${b.y}px`,
1599
+ width: `${b.width}px`,
1600
+ height: `${b.height}px`,
1601
+ });
1602
+ Object.assign(copy.style, { left: `${-w.x - shift.x}px`, top: `${-w.y - shift.y}px` });
1603
+ };
1604
+ const ready = (async () => {
1605
+ await sourceReady;
1606
+ if (!frame.getClientRects().length) throw new Error(noLayout("lift"));
1607
+ if (!into.getClientRects().length)
1608
+ throw new Error(
1609
+ "lift: the layer it lifts into has no layout (display:none on it or an ancestor) — hide a scene with visibility, or use scenes() (kit/time.js)",
1610
+ );
1611
+ const doc = /** @type {Document} */ (frame.contentDocument);
1612
+ const targets = keys.map((k) =>
1613
+ isBoxKey(k) ? null : findIn(doc, /** @type {string | Element | TextKey | Part} */ (k)),
1614
+ );
1615
+ const ms = targets.map((t, i) => measure(t, /** @type {LiftKey} */ (keys[i])));
1616
+ members = ms.map((m) => m.box);
1617
+ measuredBy = ms.map((m) => m.by);
1618
+ const b = unionOf(members);
1619
+ if (!(b.width > 0 && b.height > 0)) throw new Error(`lift: ${label} has no size on the screen`);
1620
+ rest = { x: b.x - pad, y: b.y - pad, width: b.width + 2 * pad, height: b.height + 2 * pad };
1621
+ win = { ...rest };
1622
+ off = offsetTo("lift", frame, into);
1623
+ box = { x: rest.x + off.x, y: rest.y + off.y, width: rest.width, height: rest.height };
1624
+ const only = targets.length === 1 ? targets[0] : null;
1625
+ radius = o.radius ?? (only && !pad && measuredBy[0] === "box" ? radiusOf(only) : 0);
1626
+ Object.assign(copy.style, {
1627
+ width: `${frame.clientWidth}px`,
1628
+ height: `${frame.clientHeight}px`,
1629
+ left: `${-rest.x}px`,
1630
+ top: `${-rest.y}px`,
1631
+ });
1632
+ copy.src = frame.src;
1633
+ await whenLoaded(copy);
1634
+ const cdoc = /** @type {Document} */ (copy.contentDocument);
1635
+ const cwin = /** @type {Window} */ (copy.contentWindow);
1636
+ // the same scroll as the screen it came from
1637
+ cwin.scrollTo(frame.contentWindow?.scrollX ?? 0, frame.contentWindow?.scrollY ?? 0);
1638
+ mine = targets.map((t) => (t ? atPath(cdoc, pathOf(t)) : null));
1639
+ if (targets.some((t, i) => t && !mine[i]))
1640
+ throw new Error(`lift: ${label} is not in the copy of the screen`);
1641
+ let css = o.css ?? "";
1642
+ if (around === "clear") {
1643
+ for (const m of mine) m?.setAttribute("data-ot-lifted", "");
1644
+ css += `html,body{background:transparent!important}
1645
+ body *{visibility:hidden!important}
1646
+ [data-ot-lifted],[data-ot-lifted] *{visibility:visible!important}`;
1647
+ // a document of another colour scheme than the page it sits in gets an
1648
+ // opaque backdrop: match it so the hidden page is see-through
1649
+ copy.style.colorScheme = getComputedStyle(cdoc.documentElement).colorScheme || "normal";
1650
+ }
1651
+ if (css) {
1652
+ const st = cdoc.createElement("style");
1653
+ st.textContent = css;
1654
+ cdoc.head.appendChild(st);
1655
+ }
1656
+ // the parts may have moved in the copy (fonts, a restyle): measure again
1657
+ const was = unionOf(members.filter((_, i) => targets[i]));
1658
+ const now = unionOf(
1659
+ mine.flatMap((m, i) => (m ? [measure(m, /** @type {LiftKey} */ (keys[i])).box] : [])),
1660
+ );
1661
+ if (was.width > 0 && now.width > 0) {
1662
+ const dx = now.x - was.x;
1663
+ const dy = now.y - was.y;
1664
+ if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) shift = { x: dx, y: dy };
1665
+ }
1666
+ layout();
1667
+ Object.assign(el.style, {
1668
+ borderRadius: radius ? `${radius}px` : "",
1669
+ visibility: "", // its scene's: a hidden scene hides it
1670
+ });
1671
+ })();
1672
+ ready.catch(() => {});
1673
+
1674
+ const need = () => {
1675
+ if (!box) throw new Error("lift: not ready yet — wait for its .ready (put it in __film.ready)");
1676
+ return box;
1677
+ };
1678
+ const cdocOf = () => {
1679
+ need();
1680
+ const d = copy.contentDocument;
1681
+ if (!d) throw new Error("lift: the copy is not same-origin");
1682
+ return d;
1683
+ };
1684
+ return {
1685
+ /** the layer: a window onto a copy of the saved screen */
1686
+ el,
1687
+ /** the copy's iframe inside it */
1688
+ frame: copy,
1689
+ /** resolves once the copy is loaded and the layer sits over the part */
1690
+ ready,
1691
+ /** where the part sits, in `into`'s px (the layer's px at rest) */
1692
+ get box() {
1693
+ return { ...need() };
1694
+ },
1695
+ /** the same, as a motion.js rect (with the corner radius) */
1696
+ get rect() {
1697
+ const b = need();
1698
+ return { x: b.x, y: b.y, w: b.width, h: b.height, r: radius };
1699
+ },
1700
+ /** where the part sits in the screen's own px */
1701
+ get source() {
1702
+ need();
1703
+ return { .../** @type {Box} */ (rest) };
1704
+ },
1705
+ /** what the window shows now, in the screen's px (the part's own box until view() changes it) */
1706
+ get window() {
1707
+ need();
1708
+ return { .../** @type {Box} */ (win) };
1709
+ },
1710
+ /** how its box was measured: "ink" (where its text is drawn), "box" (the
1711
+ * element's box, or a box given), "mixed" (a list, some each way) */
1712
+ get by() {
1713
+ need();
1714
+ return measuredBy.every((m) => m === "ink")
1715
+ ? "ink"
1716
+ : measuredBy.every((m) => m === "box")
1717
+ ? "box"
1718
+ : "mixed";
1719
+ },
1720
+ /** how many parts it holds (a list's length; 1 otherwise) */
1721
+ count: keys.length,
1722
+ /** where part i of a list sits at rest, in `into`'s px @param {number} i */
1723
+ member(i) {
1724
+ need();
1725
+ const m = members[i];
1726
+ if (!m) throw new Error(`lift: there is no part ${i} (it holds ${members.length})`);
1727
+ return { x: m.x + off.x, y: m.y + off.y, width: m.width, height: m.height };
1728
+ },
1729
+ /** where a box of `into`'s px at rest (its box, a member) shows now,
1730
+ * after the last place() @param {BoxLike} b @returns {Box} */
1731
+ map(b) {
1732
+ const a = boxOf(b);
1733
+ if (!placed) return a;
1734
+ const { f, at } = placed;
1735
+ return {
1736
+ x: at.x + f.x + (a.x - at.x) * f.kx,
1737
+ y: at.y + f.y + (a.y - at.y) * f.ky,
1738
+ width: a.width * f.kx,
1739
+ height: a.height * f.ky,
1740
+ };
1741
+ },
1742
+ /** where the part shows at t through a camera on the layer it sits in
1743
+ * (`into`): throughCamera(box, cam, t)
1744
+ * @param {{ toView: (x: number, y: number, t: number) => number[] }} cam @param {number} t */
1745
+ from(cam, t) {
1746
+ return throughCamera(need(), cam, t);
1747
+ },
1748
+ /**
1749
+ * Which part of the screen the window shows, in the screen's px: a box,
1750
+ * null for the whole screen, undefined for the part's own box again. The
1751
+ * part's box, rect and source stay where it sat; place() puts the window
1752
+ * as it is now — so call view() first in a frame.
1753
+ * @param {BoxLike | null} [v]
1754
+ */
1755
+ view(v) {
1756
+ need();
1757
+ const w =
1758
+ v === undefined
1759
+ ? { .../** @type {Box} */ (rest) }
1760
+ : v === null
1761
+ ? { x: 0, y: 0, width: frame.clientWidth, height: frame.clientHeight }
1762
+ : boxOf(v);
1763
+ if (!(w.width > 0 && w.height > 0)) throw new Error("lift: view() needs a box with a size");
1764
+ win = w;
1765
+ layout();
1766
+ return { ...w };
1767
+ },
1768
+ /** the transform that puts the part onto `rect` (in `into`'s px) @param {BoxLike} rect @param {"contain" | "cover" | "fill"} [fit] */
1769
+ at: (rect, fit = o.fit) => fitTransform(winBox(), rect, fit).css,
1770
+ /**
1771
+ * Put the part onto `rect` (`into`'s px; a motion.js rect's radius is
1772
+ * kept on screen, scaled back so the corners read as given) and,
1773
+ * optionally, its opacity.
1774
+ * @param {BoxLike & { r?: number }} rect
1775
+ * @param {{ opacity?: number, fit?: "contain" | "cover" | "fill" }} [p]
1776
+ */
1777
+ place(rect, p = {}) {
1778
+ need();
1779
+ const at = winBox();
1780
+ const f = fitTransform(at, rect, p.fit ?? o.fit);
1781
+ placed = { f, at };
1782
+ el.style.transform = f.css;
1783
+ if (rect.r != null) el.style.borderRadius = `${rect.r / Math.min(f.kx, f.ky)}px`;
1784
+ if (p.opacity != null) el.style.opacity = String(p.opacity);
1785
+ return f;
1786
+ },
1787
+ /** the copy's document: the part as live DOM */
1788
+ get doc() {
1789
+ return cdocOf();
1790
+ },
1791
+ /** an element of the copy: a selector, an id or ref, { text, up } @param {string | Element | TextKey} k */
1792
+ find(k) {
1793
+ return findIn(cdocOf(), k);
1794
+ },
1795
+ /**
1796
+ * Its parts, in order, as elements of the copy — `o.parts` when given,
1797
+ * else a list's members, else its own children that are laid out.
1798
+ * @returns {Element[]}
1799
+ */
1800
+ parts() {
1801
+ const d = cdocOf();
1802
+ if (o.parts) return o.parts.map((k) => findIn(d, k));
1803
+ const held = /** @type {Element[]} */ (mine.filter(Boolean));
1804
+ if (held.length > 1) return held;
1805
+ const one = held[0];
1806
+ if (!one) return [];
1807
+ return Array.from(one.children).filter((c) => {
1808
+ const r = c.getBoundingClientRect();
1809
+ return r.width > 0 && r.height > 0;
1810
+ });
1811
+ },
1812
+ /**
1813
+ * Set the text it shows — of the part, or of `k` inside it: the first
1814
+ * text holding a digit (a number), else its first text; the text around
1815
+ * it stays, and what `s` starts or ends with that the product already
1816
+ * shows beside it in elements of their own ("$" in a span before the
1817
+ * digits) is not shown twice. A longer text can widen its own box.
1818
+ * Returns the element.
1819
+ * @param {string} s @param {string | Element | TextKey} [k]
1820
+ */
1821
+ text(s, k) {
1822
+ const d = cdocOf();
1823
+ const host = k != null ? findIn(d, k) : mine.find(Boolean);
1824
+ if (!host)
1825
+ throw new Error("lift: a bare box has no text to set — give text() an element of it");
1826
+ const nodes = textNodes(host);
1827
+ const n = nodes.find((x) => /\d/.test(x.nodeValue ?? "")) ?? nodes[0];
1828
+ if (!n) {
1829
+ if (host.textContent !== s) host.textContent = s;
1830
+ return host;
1831
+ }
1832
+ const v = n.nodeValue ?? "";
1833
+ // what the product wrote round the number in elements of their own
1834
+ // ("$" in a span before it, " ms" after) is not written twice
1835
+ const i = nodes.indexOf(n);
1836
+ const before = nodes
1837
+ .slice(0, i)
1838
+ .map((x) => x.nodeValue ?? "")
1839
+ .join("");
1840
+ const after = nodes
1841
+ .slice(i + 1)
1842
+ .map((x) => x.nodeValue ?? "")
1843
+ .join("");
1844
+ let lead = 0;
1845
+ for (let k = Math.min(s.length, before.trimEnd().length); k > 0; k--)
1846
+ if (before.trimEnd().endsWith(s.slice(0, k))) {
1847
+ lead = k;
1848
+ break;
1849
+ }
1850
+ let trail = 0;
1851
+ for (let k = Math.min(s.length - lead, after.trimStart().length); k > 0; k--)
1852
+ if (after.trimStart().startsWith(s.slice(s.length - k))) {
1853
+ trail = k;
1854
+ break;
1855
+ }
1856
+ const core = s.slice(lead, s.length - trail).trim();
1857
+ const next = `${/^\s*/.exec(v)?.[0] ?? ""}${core}${/\s*$/.exec(v)?.[0] ?? ""}`;
1858
+ if (v !== next) n.nodeValue = next;
1859
+ return /** @type {Element} */ (n.parentElement);
1860
+ },
1861
+ /** add styles to the lifted copy @param {string} css */
1862
+ restyle(css) {
1863
+ const cdoc = copy.contentDocument;
1864
+ if (!cdoc) throw new Error("lift: not ready yet");
1865
+ const st = cdoc.createElement("style");
1866
+ st.textContent = css;
1867
+ cdoc.head.appendChild(st);
1868
+ },
1869
+ remove: () => el.remove(),
1870
+ };
1871
+ }
1872
+
1873
+ /** @typedef {ReturnType<typeof lift>} Lifted */
1874
+
1875
+ /**
1876
+ * Several lifted parts moved as one body: their layout kept, scaled about
1877
+ * the box round them all — the three prices of a card carried together, at
1878
+ * one size. `place(rect)` puts that box onto `rect` (fit "contain" by
1879
+ * default) and each part where it falls inside it. A group can hold groups.
1880
+ *
1881
+ * const row = group([kill, vs, keep]);
1882
+ * row.place(morphRect(t, 4, 4.6, row.rect, { x: 160, y: 200, w: 1600, h: 380 }));
1883
+ *
1884
+ * Each part is placed by its window as it is now (a part whose view()
1885
+ * changed is placed by that window).
1886
+ * @param {{ box: Box, place: (rect: BoxLike, p?: { opacity?: number, fit?: "contain" | "cover" | "fill" }) => unknown }[]} parts
1887
+ */
1888
+ export function group(parts) {
1889
+ if (!parts.length) throw new Error("group: give it the parts to move together");
1890
+ const union = () => unionOf(parts.map((p) => p.box));
1891
+ return {
1892
+ parts,
1893
+ /** the box round all of them at rest */
1894
+ get box() {
1895
+ return union();
1896
+ },
1897
+ /** the same, as a motion.js rect */
1898
+ get rect() {
1899
+ const b = union();
1900
+ return { x: b.x, y: b.y, w: b.width, h: b.height, r: 0 };
1901
+ },
1902
+ /**
1903
+ * Put the group onto `rect`, each part where it falls.
1904
+ * @param {BoxLike} rect
1905
+ * @param {{ opacity?: number, fit?: "contain" | "cover" | "fill" }} [p]
1906
+ */
1907
+ place(rect, p = {}) {
1908
+ const U = union();
1909
+ const f = fitTransform(U, rect, p.fit ?? "contain");
1910
+ for (const part of parts) {
1911
+ const b = part.box;
1912
+ part.place(
1913
+ {
1914
+ x: U.x + f.x + (b.x - U.x) * f.kx,
1915
+ y: U.y + f.y + (b.y - U.y) * f.ky,
1916
+ width: b.width * f.kx,
1917
+ height: b.height * f.ky,
1918
+ },
1919
+ { fit: "fill", ...(p.opacity != null ? { opacity: p.opacity } : {}) },
1920
+ );
1921
+ }
1922
+ return f;
1923
+ },
1924
+ };
1925
+ }
1926
+
1927
+ /**
1928
+ * Where to put each of several parts to lay them out side by side in `rect`
1929
+ * — a row (default) or a column, `gap` px apart (in `rect`'s px), all at one
1930
+ * scale: the largest at which the line fits (or `scale`), centred, each
1931
+ * centred across the line (`align` "start" / "end" to line them up instead).
1932
+ * Returns one motion.js rect a part, to place them on (or to morphRect to).
1933
+ *
1934
+ * const slots = arrange([kill, vs, keep], { x: 160, y: 300, w: 1600, h: 400 }, { gap: 80 });
1935
+ * kill.place(morphRect(t, 4, 4.6, kill.rect, slots[0]));
1936
+ * @param {({ box: Box, rect?: { r?: number } } | BoxLike)[]} parts lifted parts, groups or boxes
1937
+ * @param {BoxLike} rect
1938
+ * @param {{ axis?: "row" | "column", gap?: number, align?: "center" | "start" | "end", scale?: number }} [o]
1939
+ * @returns {{ x: number, y: number, w: number, h: number, r: number, k: number }[]}
1940
+ */
1941
+ export function arrange(parts, rect, o = {}) {
1942
+ const { axis = "row", gap = 0, align = "center" } = o;
1943
+ const R = boxOf(rect);
1944
+ const boxes = parts.map((p) =>
1945
+ "box" in p && p.box ? boxOf(p.box) : boxOf(/** @type {BoxLike} */ (p)),
1946
+ );
1947
+ if (!boxes.length) return [];
1948
+ if (boxes.some((b) => !(b.width > 0 && b.height > 0)))
1949
+ throw new Error("arrange: every part needs a size");
1950
+ const row = axis === "row";
1951
+ const along = (/** @type {Box} */ b) => (row ? b.width : b.height);
1952
+ const across = (/** @type {Box} */ b) => (row ? b.height : b.width);
1953
+ const sum = boxes.reduce((s, b) => s + along(b), 0);
1954
+ const thick = Math.max(...boxes.map(across));
1955
+ const room = (row ? R.width : R.height) - gap * (boxes.length - 1);
1956
+ const k = o.scale ?? Math.min(room / sum, (row ? R.height : R.width) / thick);
1957
+ if (!(k > 0))
1958
+ throw new Error(`arrange: the parts and their gaps do not fit in the rect (scale ${k})`);
1959
+ const length = sum * k + gap * (boxes.length - 1);
1960
+ let at = row ? R.x + (R.width - length) / 2 : R.y + (R.height - length) / 2;
1961
+ const line0 = row ? R.y + (R.height - thick * k) / 2 : R.x + (R.width - thick * k) / 2;
1962
+ return boxes.map((b, i) => {
1963
+ const a = along(b) * k;
1964
+ const c = across(b) * k;
1965
+ const off = align === "start" ? 0 : align === "end" ? thick * k - c : (thick * k - c) / 2;
1966
+ const p = parts[i];
1967
+ const r0 = p && "rect" in p && p.rect && typeof p.rect.r === "number" ? p.rect.r : 0;
1968
+ const out = row
1969
+ ? { x: at, y: line0 + off, w: a, h: c, r: r0 * k, k }
1970
+ : { x: line0 + off, y: at, w: c, h: a, r: r0 * k, k };
1971
+ at += a + gap;
1972
+ return out;
1973
+ });
1974
+ }
1975
+
1976
+ /** the default handoff ease of motion.js (morphRect): a critically damped
1977
+ * spring that lands exactly at p = 1 — the same curve, kept here so this
1978
+ * file stands on its own */
1979
+ /** @param {number} p */
1980
+ const landing = (p) => {
1981
+ if (p <= 0) return 0;
1982
+ if (p >= 1) return 1;
1983
+ const T = Math.log(1000);
1984
+ const x = (/** @type {number} */ u) => 1 - Math.exp(-u) * (1 + u);
1985
+ return x(p * T) / x(T);
1986
+ };
1987
+
1988
+ /**
1989
+ * One part handed over to another between `a` and `b` (s) — the same
1990
+ * component in two saved screens (the wizard's step 2 becoming step 3, one
1991
+ * brand's row becoming the next's), carried without a cut: both are placed
1992
+ * on one box growing from A's rect to B's (motion.js's morphRect: sizes in
1993
+ * log space, the default landing ease), and from `swapAt` of the way (0.7)
1994
+ * B comes in over A, then A goes — at no instant is less than one of them
1995
+ * fully there, so the hand-over does not dip. Both must sit in one layer's
1996
+ * px (lift them `into` the same layer). Before `a`, A sits at its rect and B
1997
+ * is not seen; after `b`, B sits at its rect and A is not seen.
1998
+ *
1999
+ * carry(step2, step3, t, 6.0, 6.5); // in __render(t)
2000
+ * carry(a, b, t, 6, 6.5, { to: { x: 400, y: 200, w: 1120, h: 680 } });
2001
+ * @param {{ rect: BoxLike & { r?: number }, place: (rect: BoxLike & { r?: number }, p?: { opacity?: number, fit?: "contain" | "cover" | "fill" }) => unknown }} A
2002
+ * @param {{ rect: BoxLike & { r?: number }, place: (rect: BoxLike & { r?: number }, p?: { opacity?: number, fit?: "contain" | "cover" | "fill" }) => unknown }} B
2003
+ * @param {number} t
2004
+ * @param {number} a
2005
+ * @param {number} b
2006
+ * @param {{ swapAt?: number, from?: BoxLike & { r?: number }, to?: BoxLike & { r?: number },
2007
+ * ease?: (p: number) => number, fit?: "contain" | "cover" | "fill" }} [o]
2008
+ */
2009
+ export function carry(A, B, t, a, b, o = {}) {
2010
+ const { swapAt = 0.7, ease = landing, fit } = o;
2011
+ if (!(b > a)) throw new Error(`carry: it ends (${b}) before it starts (${a})`);
2012
+ const from = boxOf(o.from ?? A.rect);
2013
+ const to = boxOf(o.to ?? B.rect);
2014
+ const rf = (o.from ?? A.rect).r ?? 0;
2015
+ const rt = (o.to ?? B.rect).r ?? 0;
2016
+ const p = ease(Math.max(0, Math.min(1, (t - a) / (b - a))));
2017
+ const size = (/** @type {number} */ u, /** @type {number} */ v) =>
2018
+ u > 0 && v > 0 ? u * (v / u) ** p : u + (v - u) * p;
2019
+ const w = size(from.width, to.width);
2020
+ const h = size(from.height, to.height);
2021
+ const cx = from.x + from.width / 2 + (to.x + to.width / 2 - (from.x + from.width / 2)) * p;
2022
+ const cy = from.y + from.height / 2 + (to.y + to.height / 2 - (from.y + from.height / 2)) * p;
2023
+ const rect = { x: cx - w / 2, y: cy - h / 2, w, h, r: rf + (rt - rf) * p };
2024
+ const s = a + (b - a) * Math.max(0, Math.min(1, swapAt));
2025
+ const u = b > s ? Math.max(0, Math.min(1, (t - s) / (b - s))) : t >= b ? 1 : 0;
2026
+ const smooth = (/** @type {number} */ x) => x * x * x * (x * (x * 6 - 15) + 10);
2027
+ const inB = smooth(Math.min(1, 2 * u));
2028
+ const outA = 1 - smooth(Math.max(0, 2 * u - 1));
2029
+ const fo = fit ? { fit } : {};
2030
+ A.place(rect, { opacity: outA, ...fo });
2031
+ B.place(rect, { opacity: inB, ...fo });
2032
+ return { rect, a: outA, b: inB, p };
2033
+ }
2034
+
2035
+ /**
2036
+ * Keep one part of the product in place while its saved screens are swapped
2037
+ * in turn: in each screen but the `to`th, the part is moved (CSS translate)
2038
+ * to where it sits in that one. A wizard's card that the product moves down
2039
+ * as it adds a row stays where the eye was; the rest of each screen stays as
2040
+ * the product laid it out. Points taken on a screen (a click's cursor) move
2041
+ * with it: `point(i, p)`. `axis` "y" or "x" keeps only that one; `release()`
2042
+ * puts every screen back.
2043
+ *
2044
+ * await Promise.all(screens.map((s) => s.ready));
2045
+ * const card = hold(screens, { text: "從你的生活圈開始", up: 2 });
2046
+ * kh.click(card.point(1, shotOf("click-2").cursor), t2);
2047
+ *
2048
+ * film render reports the one-frame jumps the page did not declare, and how
2049
+ * far; this is one way to keep a part from jumping, when that is wanted.
2050
+ * @param {any[]} screens saved screens (or their iframes), in the order shown
2051
+ * @param {string | Element | TextKey | Part | (string | Element | TextKey | Part)[]} key the part, in every screen (a part of product() is found on each), or one key per screen
2052
+ * @param {{ to?: number, axis?: "x" | "y" | "both" }} [o]
2053
+ */
2054
+ export function hold(screens, key, o = {}) {
2055
+ const { to = 0, axis = "both" } = o;
2056
+ const frames = screens.map((s) => /** @type {HTMLIFrameElement} */ (s.frame ?? s));
2057
+ const parts = frames.map((f, i) => {
2058
+ const doc = f.contentDocument;
2059
+ if (!doc) throw new Error(`hold: screen ${i} is not same-origin, or not loaded`);
2060
+ const k = Array.isArray(key) ? key[i] : key;
2061
+ if (k == null) throw new Error(`hold: no key for screen ${i}`);
2062
+ return /** @type {HTMLElement} */ (findIn(doc, k, "hold"));
2063
+ });
2064
+ const home = parts[to];
2065
+ if (!home) throw new Error(`hold: no screen ${to} among ${frames.length}`);
2066
+ const at = home.getBoundingClientRect();
2067
+ const was = parts.map((el) => el.style.translate);
2068
+ const offsets = parts.map((el, i) => {
2069
+ if (i === to) return { dx: 0, dy: 0 };
2070
+ const r = el.getBoundingClientRect();
2071
+ const dx = axis === "y" ? 0 : at.left - r.left;
2072
+ const dy = axis === "x" ? 0 : at.top - r.top;
2073
+ if (Math.abs(dx) > 1e-3 || Math.abs(dy) > 1e-3) el.style.translate = `${dx}px ${dy}px`;
2074
+ return { dx, dy };
2075
+ });
2076
+ return {
2077
+ /** how far each screen's part was moved, its own px */
2078
+ offsets,
2079
+ /** a point on screen i (its own px), moved as its part was
2080
+ * @param {number} i @param {{ x: number, y: number }} p */
2081
+ point(i, p) {
2082
+ const d = offsets[i] ?? { dx: 0, dy: 0 };
2083
+ return { ...p, x: p.x + d.dx, y: p.y + d.dy };
2084
+ },
2085
+ release() {
2086
+ parts.forEach((el, i) => {
2087
+ el.style.translate = was[i] ?? "";
2088
+ });
2089
+ },
2090
+ };
2091
+ }
2092
+
2093
+ /**
2094
+ * Show a saved screen with everything but the chosen parts faded away: an
2095
+ * overlay over the screen (in the screen's parent, so a camera on that layer
2096
+ * carries it) with holes cut where the parts are. `set(p)` takes it from
2097
+ * nothing (0) to all the way (1). By default the rest fades into the page's
2098
+ * own background colour; `color` and `opacity` change that (a dim is
2099
+ * { color: "#000", opacity: 0.6 }), `blur` softens what is behind (px).
2100
+ *
2101
+ * const focus = isolate(s, ["e126", "e133"]);
2102
+ * window.__film = { …, ready: focus.ready };
2103
+ * focus.set(smooth((t - 5) / 0.4)); // in __render(t)
2104
+ *
2105
+ * @param {any} source a saved screen or its iframe
2106
+ * @param {(string | Element | TextKey | Part | BoxLike)[]} keys selectors, index ids or refs, { text, up }, parts of product(), elements or boxes (screen px)
2107
+ * @param {{ color?: string, opacity?: number, blur?: number, pad?: number, radius?: number }} [o]
2108
+ */
2109
+ export function isolate(source, keys, o = {}) {
2110
+ const { frame, ready: sourceReady } = screenOf(source);
2111
+ const parent = frame.parentElement;
2112
+ if (!parent) throw new Error("isolate: the screen has no parent to draw in");
2113
+ const el = document.createElement("div");
2114
+ Object.assign(el.style, {
2115
+ position: "absolute",
2116
+ left: "0px",
2117
+ top: "0px",
2118
+ pointerEvents: "none",
2119
+ opacity: "0",
2120
+ });
2121
+ stackOver(frame, el, "fade");
2122
+ const pad = o.pad ?? 0;
2123
+ /** @type {Box[]} */
2124
+ let holes = [];
2125
+ const opacity = o.opacity ?? 1;
2126
+ const ready = (async () => {
2127
+ await sourceReady;
2128
+ if (!frame.getClientRects().length) throw new Error(noLayout("isolate"));
2129
+ const doc = /** @type {Document} */ (frame.contentDocument);
2130
+ const f = (/** @type {number} */ v) => v.toFixed(2);
2131
+ let path = "";
2132
+ holes = keys.map((k) => {
2133
+ const target = isBoxKey(k) ? null : findIn(doc, k, "isolate");
2134
+ const r = target ? target.getBoundingClientRect() : null;
2135
+ const b = r
2136
+ ? { x: r.left, y: r.top, width: r.width, height: r.height }
2137
+ : boxOf(/** @type {BoxLike} */ (k));
2138
+ const x = b.x - pad;
2139
+ const y = b.y - pad;
2140
+ const w = b.width + 2 * pad;
2141
+ const h = b.height + 2 * pad;
2142
+ const rad = Math.min(o.radius ?? (target ? radiusOf(target) : 0), w / 2, h / 2);
2143
+ path += rad
2144
+ ? `M${f(x + rad)} ${f(y)}H${f(x + w - rad)}A${f(rad)} ${f(rad)} 0 0 1 ${f(x + w)} ${f(y + rad)}V${f(y + h - rad)}A${f(rad)} ${f(rad)} 0 0 1 ${f(x + w - rad)} ${f(y + h)}H${f(x + rad)}A${f(rad)} ${f(rad)} 0 0 1 ${f(x)} ${f(y + h - rad)}V${f(y + rad)}A${f(rad)} ${f(rad)} 0 0 1 ${f(x + rad)} ${f(y)}Z`
2145
+ : `M${f(x)} ${f(y)}H${f(x + w)}V${f(y + h)}H${f(x)}Z`;
2146
+ return { x, y, width: w, height: h };
2147
+ });
2148
+ const off = offsetWithin("isolate", frame, parent);
2149
+ const w = frame.clientWidth;
2150
+ const h = frame.clientHeight;
2151
+ // the page's own background: the body's, else the root's, else white
2152
+ const bg = (/** @type {Element} */ n) => {
2153
+ const c = getComputedStyle(n).backgroundColor;
2154
+ return c && c !== "transparent" && !/rgba\(.*,\s*0\)$/.test(c) ? c : null;
2155
+ };
2156
+ Object.assign(el.style, {
2157
+ left: `${off.x}px`,
2158
+ top: `${off.y}px`,
2159
+ width: `${w}px`,
2160
+ height: `${h}px`,
2161
+ background: o.color ?? bg(doc.body) ?? bg(doc.documentElement) ?? "#fff",
2162
+ clipPath: `path(evenodd, "M0 0H${w}V${h}H0Z${path}")`,
2163
+ });
2164
+ })();
2165
+ ready.catch(() => {});
2166
+ return {
2167
+ el,
2168
+ ready,
2169
+ /** the parts left showing, in the screen's px */
2170
+ get holes() {
2171
+ return holes.map((b) => ({ ...b }));
2172
+ },
2173
+ /** how far the rest has faded, 0..1 @param {number} p */
2174
+ set(p) {
2175
+ const k = Math.max(0, Math.min(1, p));
2176
+ el.style.opacity = String(k * opacity);
2177
+ const blur = o.blur ? `blur(${(k * o.blur).toFixed(2)}px)` : "";
2178
+ el.style.backdropFilter = blur;
2179
+ },
2180
+ };
2181
+ }
2182
+
2183
+ /**
2184
+ * A box of a layer under a camera, as it shows in the picture at t: its four
2185
+ * corners through cam.toView, bounded. For carrying a part from where the
2186
+ * camera shows it into a layer the camera does not move.
2187
+ * @param {BoxLike} b
2188
+ * @param {{ toView: (x: number, y: number, t: number) => number[] }} cam
2189
+ * @param {number} t
2190
+ * @returns {Box}
2191
+ */
2192
+ export function throughCamera(b, cam, t) {
2193
+ const a = boxOf(b);
2194
+ const pts = [
2195
+ cam.toView(a.x, a.y, t),
2196
+ cam.toView(a.x + a.width, a.y, t),
2197
+ cam.toView(a.x, a.y + a.height, t),
2198
+ cam.toView(a.x + a.width, a.y + a.height, t),
2199
+ ];
2200
+ const xs = pts.map((p) => /** @type {number} */ (p[0]));
2201
+ const ys = pts.map((p) => /** @type {number} */ (p[1]));
2202
+ const x = Math.min(...xs);
2203
+ const y = Math.min(...ys);
2204
+ return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y };
2205
+ }
2206
+
2207
+ // --- the product's real values ------------------------------------------------------
2208
+
2209
+ /**
2210
+ * One value a part showed, as components.json (version 2) keeps it: the text
2211
+ * as the product wrote it, in full; the number in it and its unit when it has
2212
+ * one; and where it was read.
2213
+ * @typedef {object} PartValue
2214
+ * @property {string} text
2215
+ * @property {number} [value]
2216
+ * @property {string} [unit]
2217
+ * @property {{ state: string, eid: string, selector?: string, shot?: string }} source
2218
+ */
2219
+
2220
+ /**
2221
+ * The real values of the parts in components.json, by field, so a part the
2222
+ * film draws on its own (a card rebuilt in the page, at film size) can show
2223
+ * what the product showed — nothing here makes a value up: a field the part
2224
+ * did not show is an error that names the fields it did.
2225
+ *
2226
+ * const v = await readValues("../shots/components.json", { tl });
2227
+ * v.fields("result:e149") // ["number", "label", …] — what it showed
2228
+ * price.textContent = v.text("result:e149", "number"); // "$3,376"
2229
+ * const n = v.valueOf("result:e149", "number").value; // 3376, for a count
2230
+ * v.relations("form:e12") // [{ kind: "changes", to: "result:e149" }]
2231
+ *
2232
+ * With `tl` (kit/time.js), every value read is declared as the source of its
2233
+ * text (tl.source), once, so `film probe` can say where it came from. A part
2234
+ * is its ref ("<state>:<element id>") or anything with a `ref`. A count's
2235
+ * in-between numbers are the film's, not the product's: declare nothing for
2236
+ * them.
2237
+ * @param {unknown} file components.json, parsed
2238
+ * @param {{ tl?: { source: (label: string, o: object) => unknown }, file?: string }} [o]
2239
+ * `file`: where it was read from, as the page fetched it (kept on each source)
2240
+ */
2241
+ export function partValues(file, o = {}) {
2242
+ const f = /** @type {{ version?: number, components?: unknown }} */ (file ?? {});
2243
+ if (!f || typeof f !== "object" || !Array.isArray(f.components))
2244
+ throw new Error("readValues: this is not a components.json (no components list)");
2245
+ const version = typeof f.version === "number" ? f.version : 0;
2246
+ /** @type {Map<string, Record<string, any>>} */
2247
+ const parts = new Map();
2248
+ for (const c of /** @type {Record<string, any>[]} */ (f.components))
2249
+ if (c && typeof c.ref === "string") parts.set(c.ref, c);
2250
+ /** @type {Set<string>} */
2251
+ const declared = new Set();
2252
+ /** @param {string | { ref?: string }} p */
2253
+ const refOf = (p) => {
2254
+ const ref = typeof p === "string" ? p : p && typeof p === "object" ? p.ref : undefined;
2255
+ if (typeof ref !== "string" || !ref)
2256
+ throw new Error('readValues: a part is its ref ("<state>:<element id>") or has one');
2257
+ return ref;
2258
+ };
2259
+ /** @param {string | { ref?: string }} p */
2260
+ const part = (p) => {
2261
+ const ref = refOf(p);
2262
+ const e = parts.get(ref);
2263
+ if (!e)
2264
+ throw new Error(
2265
+ `readValues: no part ${ref} in components.json (${parts.size} part(s); \`open-take components <dir>\` lists them)`,
2266
+ );
2267
+ return e;
2268
+ };
2269
+ /** @param {string | { ref?: string }} p @returns {Record<string, PartValue>} */
2270
+ const valuesOf = (p) => {
2271
+ const e = part(p);
2272
+ const v = e.values && typeof e.values === "object" ? e.values : {};
2273
+ /** @type {Record<string, PartValue>} */
2274
+ const out = {};
2275
+ for (const [k, x] of Object.entries(v))
2276
+ if (x && typeof x === "object" && typeof x.text === "string")
2277
+ out[k] = { ...x, source: { ...(x.source ?? {}) } };
2278
+ return out;
2279
+ };
2280
+ /** @param {string | { ref?: string }} p @param {string} field @returns {PartValue} */
2281
+ const valueBy = (p, field) => {
2282
+ const ref = refOf(p);
2283
+ const all = valuesOf(ref);
2284
+ const x = all[field];
2285
+ if (!x) {
2286
+ const have = Object.keys(all);
2287
+ throw new Error(
2288
+ version < 2
2289
+ ? `readValues: components.json is version ${version || "unknown"} and keeps no values — measure the screens again (\`open-take components <dir>\`) for version 2`
2290
+ : `readValues: ${ref} showed no "${field}"${have.length ? ` — it showed: ${have.join(", ")}` : " — it keeps no values"}`,
2291
+ );
2292
+ }
2293
+ if (o.tl && !declared.has(`${ref}\u0000${field}`)) {
2294
+ declared.add(`${ref}\u0000${field}`);
2295
+ o.tl.source(x.text, { ref, field, ...(o.file ? { file: o.file } : {}) });
2296
+ }
2297
+ return x;
2298
+ };
2299
+ return {
2300
+ version,
2301
+ /** every part's ref, in the file's order (an order for reading, nothing more) */
2302
+ refs: () => [...parts.keys()],
2303
+ /** the part's entry as the file has it @param {string | { ref?: string }} p */
2304
+ part: (p) => ({ ...part(p) }),
2305
+ /** the fields a part showed @param {string | { ref?: string }} p */
2306
+ fields: (p) => Object.keys(valuesOf(p)),
2307
+ /** every value a part showed, by field (none: {}) */
2308
+ values: valuesOf,
2309
+ /** one value, by field — an error when the part did not show it */
2310
+ valueOf: valueBy,
2311
+ /** the text of one value, as the product wrote it
2312
+ * @param {string | { ref?: string }} p @param {string} field */
2313
+ text: (p, field) => valueBy(p, field).text,
2314
+ /** the parts that showed a field, by ref, in the file's order @param {string} field */
2315
+ withField: (field) =>
2316
+ [...parts.values()]
2317
+ .filter((e) => e.values && typeof e.values === "object" && e.values[field]?.text != null)
2318
+ .map((e) => /** @type {string} */ (e.ref)),
2319
+ /** what a part did to others, as the log and the screens showed it
2320
+ * @param {string | { ref?: string }} p
2321
+ * @returns {{ kind: string, to: string }[]} */
2322
+ relations: (p) => {
2323
+ const r = part(p).relations;
2324
+ return Array.isArray(r) ? r.map((x) => ({ ...x })) : [];
2325
+ },
2326
+ /** where a part was read: its saved screen, the page's url, when
2327
+ * @param {string | { ref?: string }} p
2328
+ * @returns {{ state?: string, url?: string, capturedAt?: string } | null} */
2329
+ provenance: (p) => {
2330
+ const v = part(p).provenance;
2331
+ return v && typeof v === "object" ? { ...v } : null;
2332
+ },
2333
+ };
2334
+ }
2335
+
2336
+ /**
2337
+ * components.json fetched (relative to the page) and read by partValues.
2338
+ * @param {string} url
2339
+ * @param {{ tl?: { source: (label: string, o: object) => unknown } }} [o]
2340
+ */
2341
+ export async function readValues(url, o = {}) {
2342
+ const res = await fetch(url);
2343
+ if (!res.ok) throw new Error(`readValues: ${url} — ${res.status}`);
2344
+ return partValues(await res.json(), { ...o, file: url });
2345
+ }
2346
+
2347
+ // --- the product's parts, as references ----------------------------------------------
2348
+
2349
+ /**
2350
+ * One part of the product as one reference — the same element followed
2351
+ * through every saved screen it is on, and where it shows in the film at t
2352
+ * through the screens shown (P.play), where they are drawn (P.view) and the
2353
+ * camera. Boxes are the screen's CSS px (`box`), the layer's px the screens
2354
+ * sit in (`boxAt`, `pointAt` — what cam.frame and the cursor take) and the
2355
+ * picture's px (`at(t).picture`).
2356
+ * @typedef {object} Part
2357
+ * @property {string} key how the page's registry knows it (film render's report reads it by this)
2358
+ * @property {string} name what the film calls it (its key, unless named)
2359
+ * @property {string} ref its element on the screen it was named on, `<state>:<eN>`
2360
+ * @property {string} [track] the track of components.json it is
2361
+ * @property {string} [kind] its kind in components.json
2362
+ * @property {PartState[]} states every screen it is on, in the log's order
2363
+ * @property {(state: string) => string | null} in its ref on a screen, or null
2364
+ * @property {(state?: string) => Box} box where it is on a screen (default: its own), the screen's px
2365
+ * @property {(t: number) => Box} boxAt where it is at t, the layer's px
2366
+ * @property {(t: number) => { x: number, y: number }} pointAt where the capture acted on it, carried to where it is at t — else its centre; the layer's px
2367
+ * @property {(t: number) => PartAt} at where it shows at t, every step of the way
2368
+ * @property {(layer: { box: Box, source: Box, map: (b: BoxLike) => Box }) => Part} via the part as a lifted copy shows it (after the copy's place())
2369
+ * @property {(t: number, label?: string) => number} mark the film names it at t (a caption, a voice, a ring) — returns t
2370
+ * @property {(t: number) => { what: string, share: number }[]} coveredBy what in the page is drawn over it at t, by share of its picture
2371
+ * @property {(use: string, t: number, o?: { end?: number, label?: string, steps?: PlayEntry[] }) => void} used say the film uses it at t (the camera and the cursor do)
2372
+ * @property {PartUse[]} uses every use, in the order made
2373
+ */
2374
+ /** @typedef {{ state: string, ref: string, box: Box, value?: number }} PartState */
2375
+ /** @typedef {{ use: string, t: number, end?: number, label?: string, ref?: string, steps?: PlayEntry[] }} PartUse */
2376
+ /**
2377
+ * @typedef {object} PartAt
2378
+ * @property {number} t
2379
+ * @property {string} state the screen it was read on
2380
+ * @property {boolean} shown that screen is the one shown at t (false: it is not on that one, and the nearest screen it is on was read)
2381
+ * @property {string} [showing] the screen shown at t (with play)
2382
+ * @property {Box} screen the screen's px
2383
+ * @property {Box} stage the layer's px
2384
+ * @property {Box} picture the picture's px
2385
+ * @property {number} inFrame the share of it inside the picture's frame, 0..1
2386
+ * @property {"screen" | "still" | "recording"} drawn what shows it: the saved screen, a still, the recording
2387
+ * @property {number} [sourcePx] picture px per px of the still or the recording that shows it
2388
+ */
2389
+ /** @typedef {[number, string | { still: number }]} PlayEntry from film time t, a screen or a still */
2390
+ /** @typedef {{ scale: number, offset?: { x: number, y: number } } | { x: number, y: number, width: number, height: number } | { x: number, y: number, scale: number }} PlaceLike */
2391
+
2392
+ /** smootherstep, 6p⁵ − 15p⁴ + 10p³ — the cursor's own drag pace (kit/cursor.js) */
2393
+ /** @param {number} p */
2394
+ export const smootherstep = (p) => {
2395
+ const x = Math.max(0, Math.min(1, p));
2396
+ return x * x * x * (x * (x * 6 - 15) + 10);
2397
+ };
2398
+ /** @param {number} p */
2399
+ const linearPace = (p) => Math.max(0, Math.min(1, p));
2400
+
2401
+ /** the share of `b` inside `f`, 0..1 @param {Box} b @param {Box} f */
2402
+ const shareInside = (b, f) => {
2403
+ const w = Math.min(b.x + b.width, f.x + f.width) - Math.max(b.x, f.x);
2404
+ const h = Math.min(b.y + b.height, f.y + f.height) - Math.max(b.y, f.y);
2405
+ const a = b.width * b.height;
2406
+ return a > 0 ? (Math.max(0, w) * Math.max(0, h)) / a : 0;
2407
+ };
2408
+
2409
+ /** a box from components.json's or index.json's [x, y, w, h] @param {number[]} b @returns {Box} */
2410
+ const boxFrom = (b) => ({ x: b[0] ?? 0, y: b[1] ?? 0, width: b[2] ?? 0, height: b[3] ?? 0 });
2411
+
2412
+ /** the fraction along a polyline at each of its points, by length (as the
2413
+ * cursor walks a drag) @param {{ x: number, y: number }[]} path */
2414
+ function lengthsAlong(path) {
2415
+ const at = [0];
2416
+ let total = 0;
2417
+ for (let i = 1; i < path.length; i++) {
2418
+ const a = /** @type {{ x: number, y: number }} */ (path[i - 1]);
2419
+ const b = /** @type {{ x: number, y: number }} */ (path[i]);
2420
+ total += Math.hypot(b.x - a.x, b.y - a.y);
2421
+ at.push(total);
2422
+ }
2423
+ return at.map((d) => (total > 0 ? d / total : 0));
2424
+ }
2425
+
2426
+ /** the progress at which a rising ease reaches `v`, by bisection
2427
+ * @param {(p: number) => number} ease @param {number} v */
2428
+ function easeInverse(ease, v) {
2429
+ if (v <= ease(0)) return 0;
2430
+ if (v >= ease(1)) return 1;
2431
+ let lo = 0;
2432
+ let hi = 1;
2433
+ for (let i = 0; i < 64; i++) {
2434
+ const mid = (lo + hi) / 2;
2435
+ if (ease(mid) < v) lo = mid;
2436
+ else hi = mid;
2437
+ }
2438
+ return (lo + hi) / 2;
2439
+ }
2440
+
2441
+ /**
2442
+ * The product's parts from what is already in hand — components.json, its
2443
+ * log (shots.json or capture.json) and each listed screen's index.json, by
2444
+ * state id — as product() reads them; `base` is where components.json was
2445
+ * read (for the URLs of the screens, stills and recording that show them).
2446
+ * @param {{ components?: any, log?: any, indexes?: Record<string, any>, base?: string, logUrl?: string,
2447
+ * tl?: { event: (at: number, kind: string, o?: { x?: number, y?: number, label?: string }) => number, curve: (name: string, fn: (t: number) => number) => void },
2448
+ * states?: string[] }} data
2449
+ */
2450
+ export function productFrom(data) {
2451
+ const comp = data.components ?? null;
2452
+ const log = data.log ?? null;
2453
+ const indexes = data.indexes ?? {};
2454
+ const tl = data.tl;
2455
+ if (comp && (typeof comp !== "object" || !Array.isArray(comp.components)))
2456
+ throw new Error("product: this is not a components.json (no components list)");
2457
+ const kind = comp?.source?.kind ?? (log?.stills ? "shoot" : log?.events ? "take" : "state");
2458
+ /** @type {{ id: string, url?: string, since?: string, action?: any, shot?: string }[]} */
2459
+ let screens = comp ? comp.states : Object.keys(indexes).map((id) => ({ id, url: "state.html" }));
2460
+ if (data.states) {
2461
+ const keep = new Set(data.states);
2462
+ for (const id of keep)
2463
+ if (!screens.some((s) => s.id === id))
2464
+ throw new Error(
2465
+ `product: no screen ${id} — it has ${screens.map((s) => s.id).join(", ") || "none"}`,
2466
+ );
2467
+ screens = screens.filter((s) => keep.has(s.id));
2468
+ }
2469
+ const order = screens.map((s) => s.id);
2470
+ const screenOf = new Map(screens.map((s) => [s.id, s]));
2471
+ const firstIndex = order.map((id) => indexes[id]).find(Boolean);
2472
+ /** @type {{ w: number, h: number }} */
2473
+ const viewport = comp?.source?.viewport ??
2474
+ firstIndex?.viewport ??
2475
+ log?.viewport ?? { w: 0, h: 0 };
2476
+
2477
+ // components.json's parts: by ref, the element before each, its repeats
2478
+ /** @type {Map<string, any>} */
2479
+ const entries = new Map();
2480
+ for (const e of comp?.components ?? []) if (e && typeof e.ref === "string") entries.set(e.ref, e);
2481
+ /** @type {Map<string, string[]>} */
2482
+ const after = new Map();
2483
+ for (const e of entries.values())
2484
+ if (e.before) after.set(e.before, [...(after.get(e.before) ?? []), e.ref]);
2485
+ /** @type {Map<string, any>} */
2486
+ const tracks = new Map((comp?.tracks ?? []).map((/** @type {any} */ t) => [t.id, t]));
2487
+
2488
+ // the stills of a shoot, by the screen each kept
2489
+ /** @type {any[]} */
2490
+ const stills = Array.isArray(log?.stills) ? log.stills : [];
2491
+ /** @type {Map<string, number>} */
2492
+ const stillOfState = new Map();
2493
+ stills.forEach((s, i) => {
2494
+ if (s.state && !stillOfState.has(s.state)) stillOfState.set(s.state, i);
2495
+ });
2496
+ /** the screen a still shows: its own, else the last one kept before it, else the next @param {number} i */
2497
+ const stateOfStill = (i) => {
2498
+ for (let k = Math.min(i, stills.length - 1); k >= 0; k--)
2499
+ if (stills[k]?.state && screenOf.has(stills[k].state)) return stills[k].state;
2500
+ for (let k = i + 1; k < stills.length; k++)
2501
+ if (stills[k]?.state && screenOf.has(stills[k].state)) return stills[k].state;
2502
+ return order[0] ?? "";
2503
+ };
2504
+ /** what one px of a still or the recording is, in the screen's px */
2505
+ const ratio = {
2506
+ still:
2507
+ typeof log?.scale === "number"
2508
+ ? log.scale
2509
+ : kind === "shoot"
2510
+ ? comp?.source?.srcRatio
2511
+ : undefined,
2512
+ recording:
2513
+ log?.video?.width && log?.viewport?.w
2514
+ ? log.video.width / log.viewport.w
2515
+ : kind === "take"
2516
+ ? comp?.source?.srcRatio
2517
+ : undefined,
2518
+ };
2519
+
2520
+ /** @param {string} ref */
2521
+ const stateOfRef = (ref) => /^(.+):(e\d+)$/.exec(ref)?.[1] ?? "";
2522
+ /** where an element is on its screen: components.json's box, else index.json's @param {string} ref @returns {Box | null} */
2523
+ const elementBox = (ref) => {
2524
+ const e = entries.get(ref);
2525
+ if (e?.box) return boxFrom(e.box);
2526
+ const m = /^(.+):(e\d+)$/.exec(ref);
2527
+ const el = m
2528
+ ? indexes[m[1] ?? ""]?.elements?.find((/** @type {any} */ x) => x.id === m[2])
2529
+ : null;
2530
+ return el?.box ? boxFrom(el.box) : null;
2531
+ };
2532
+ /** the element showing `text` on a screen (its text or name, whitespace
2533
+ * collapsed), `up` parents out — by index.json @param {string} state @param {TextKey} k */
2534
+ const byIndexText = (state, k) => {
2535
+ const els = indexes[state]?.elements;
2536
+ if (!Array.isArray(els)) return null;
2537
+ const want = norm(k.text);
2538
+ const hit =
2539
+ els.find((/** @type {any} */ e) => norm(e.text ?? "") === want) ??
2540
+ els.find((/** @type {any} */ e) => norm(e.name ?? "") === want);
2541
+ if (!hit) return null;
2542
+ if (!k.up) return `${state}:${hit.id}`;
2543
+ const path = /** @type {number[]} */ (hit.path ?? []);
2544
+ if (path.length < k.up) return null;
2545
+ const up = path.slice(0, path.length - k.up).join(".");
2546
+ const parent = els.find((/** @type {any} */ e) => (e.path ?? []).join(".") === up);
2547
+ return parent ? `${state}:${parent.id}` : null;
2548
+ };
2549
+
2550
+ // which screen shows at film time t (P.play)
2551
+ /** @type {((t: number) => { state: string, still: number | null, drawn: "screen" | "still" | "recording" }) | null} */
2552
+ let playing = null;
2553
+ /** @param {string | { still: number }} v @returns {{ state: string, still: number | null, drawn: "screen" | "still" | "recording" }} */
2554
+ const entryOf = (v) => {
2555
+ if (typeof v === "string") {
2556
+ if (!screenOf.has(v))
2557
+ throw new Error(`product: play names a screen ${v} it does not have (${order.join(", ")})`);
2558
+ return { state: v, still: stillOfState.get(v) ?? null, drawn: "screen" };
2559
+ }
2560
+ if (v && typeof v === "object" && Number.isInteger(v.still)) {
2561
+ if (!stills[v.still])
2562
+ throw new Error(`product: play names still ${v.still}; the shoot has ${stills.length}`);
2563
+ return { state: stateOfStill(v.still), still: v.still, drawn: "still" };
2564
+ }
2565
+ throw new Error("product: play takes a screen's id or { still: i } at each time");
2566
+ };
2567
+ /** @param {number} t */
2568
+ const shownAt = (t) => (playing ? playing(t) : null);
2569
+
2570
+ // where the screens are drawn, the camera, the frame (P.view)
2571
+ /** @type {{ place?: PlaceLike | ((t: number) => PlaceLike), cam?: { toView: (x: number, y: number, t: number) => number[], view?: { width: number, height: number } }, el?: Element[], frame?: { width: number, height: number } }} */
2572
+ let view = {};
2573
+ /** @param {number} t @returns {{ x: number, y: number, scale: number }} */
2574
+ const placeAt = (t) => {
2575
+ const p = typeof view.place === "function" ? view.place(t) : view.place;
2576
+ if (!p) return { x: 0, y: 0, scale: 1 };
2577
+ const q = /** @type {any} */ (p);
2578
+ if (typeof q.scale === "number" && q.offset)
2579
+ return { x: q.offset.x, y: q.offset.y, scale: q.scale };
2580
+ if (typeof q.scale === "number") return { x: q.x ?? 0, y: q.y ?? 0, scale: q.scale };
2581
+ if (typeof q.width === "number" && viewport.w)
2582
+ return { x: q.x ?? 0, y: q.y ?? 0, scale: q.width / viewport.w };
2583
+ throw new Error(
2584
+ "product: view's place is a seam() ({ scale, offset }), the box the screen is drawn in ({ x, y, width, height }) or { x, y, scale }",
2585
+ );
2586
+ };
2587
+ /** @param {Box} b @param {number} t @returns {Box} */
2588
+ const toStage = (b, t) => {
2589
+ const p = placeAt(t);
2590
+ return {
2591
+ x: p.x + b.x * p.scale,
2592
+ y: p.y + b.y * p.scale,
2593
+ width: b.width * p.scale,
2594
+ height: b.height * p.scale,
2595
+ };
2596
+ };
2597
+ /** @param {Box} b @param {number} t */
2598
+ const toPicture = (b, t) => (view.cam ? throughCamera(b, view.cam, t) : { ...b });
2599
+ const frameBox = () => {
2600
+ const f =
2601
+ view.frame ??
2602
+ view.cam?.view ??
2603
+ (typeof innerWidth === "number" && typeof window !== "undefined"
2604
+ ? { width: innerWidth, height: innerHeight }
2605
+ : { width: viewport.w, height: viewport.h });
2606
+ return { x: 0, y: 0, width: f.width, height: f.height };
2607
+ };
2608
+
2609
+ // the page's own registry, for `film render`'s report (like __otDrift):
2610
+ // every part made and every use of it
2611
+ const g = /** @type {{ __otParts?: { key: string, name: string, uses: PartUse[] }[] }} */ (
2612
+ /** @type {unknown} */ (globalThis)
2613
+ );
2614
+ g.__otParts ??= [];
2615
+ const registry = g.__otParts;
2616
+ /** @type {Part[]} */
2617
+ const made = [];
2618
+ /** @type {Map<string, Part>} */
2619
+ const byKey = new Map();
2620
+ // what a use says of where the part is waits a moment, so the screens
2621
+ // played and the camera given just after a use are the ones it is read
2622
+ // through
2623
+ /** @type {(() => void)[]} */
2624
+ let pending = [];
2625
+ /** @param {() => void} f */
2626
+ const later = (f) => {
2627
+ if (!pending.length)
2628
+ queueMicrotask(() => {
2629
+ const run = pending;
2630
+ pending = [];
2631
+ for (const x of run) x();
2632
+ });
2633
+ pending.push(f);
2634
+ };
2635
+
2636
+ /**
2637
+ * @param {{ key: string, name: string, ref: string, track?: any, text?: TextKey }} spec
2638
+ * @param {((b: Box, t: number) => Box) | null} [mapped] where a screen box shows in the layer, when not through view()'s place (via)
2639
+ * @returns {Part}
2640
+ */
2641
+ const makePart = (spec, mapped = null) => {
2642
+ const own = stateOfRef(spec.ref);
2643
+ /** @type {Map<string, string | null>} */
2644
+ const memo = new Map();
2645
+ /** its ref on a screen: track steps → the element before / after →
2646
+ * repeats → the text it was named by @param {string} state */
2647
+ const inState = (state) => {
2648
+ if (memo.has(state)) return memo.get(state) ?? null;
2649
+ const hit = find(state);
2650
+ memo.set(state, hit);
2651
+ return hit;
2652
+ };
2653
+ /** @param {string} state @returns {string | null} */
2654
+ const find = (state) => {
2655
+ if (!screenOf.has(state)) return null;
2656
+ if (own === state) return spec.ref;
2657
+ const step = spec.track?.steps?.find((/** @type {any} */ s) => s.state === state);
2658
+ if (step) return step.ref;
2659
+ const from = [spec.ref, ...(spec.track?.steps ?? []).map((/** @type {any} */ s) => s.ref)];
2660
+ /** every ref reached from `start` by the links `next` gives @param {string[]} start @param {(r: string) => string[]} next */
2661
+ const reach = (start, next) => {
2662
+ const seen = new Set(start);
2663
+ const todo = [...start];
2664
+ while (todo.length) {
2665
+ const r = /** @type {string} */ (todo.pop());
2666
+ for (const n of next(r))
2667
+ if (!seen.has(n)) {
2668
+ seen.add(n);
2669
+ todo.push(n);
2670
+ }
2671
+ }
2672
+ return seen;
2673
+ };
2674
+ const chain = reach(from, (r) => [
2675
+ ...(entries.get(r)?.before ? [entries.get(r).before] : []),
2676
+ ...(after.get(r) ?? []),
2677
+ ]);
2678
+ for (const r of chain) if (stateOfRef(r) === state) return r;
2679
+ // repeats: the same kind, text and place on an earlier screen
2680
+ const roots = new Set([...chain].map((r) => entries.get(r)?.repeats ?? r));
2681
+ for (const e of entries.values())
2682
+ if (e.state === state && roots.has(e.repeats ?? e.ref)) return e.ref;
2683
+ if (spec.text) return byIndexText(state, spec.text);
2684
+ return null;
2685
+ };
2686
+ const states = () =>
2687
+ order.flatMap((state) => {
2688
+ const ref = inState(state);
2689
+ const b = ref ? elementBox(ref) : null;
2690
+ if (!ref || !b) return [];
2691
+ const step = spec.track?.steps?.find((/** @type {any} */ s) => s.ref === ref);
2692
+ const v = step?.value ?? entries.get(ref)?.values?.number?.value;
2693
+ return [{ state, ref, box: b, ...(typeof v === "number" ? { value: v } : {}) }];
2694
+ });
2695
+ /** its own screen, or — when product(url, { states }) left that one out —
2696
+ * the first screen it is on */
2697
+ const home = () => (inState(own) ? own : (order.find((id) => inState(id)) ?? own));
2698
+ /** the screen it is read on at t, whether that is the one shown, and the
2699
+ * one shown (with play) @param {number} t */
2700
+ const readOn = (t) => {
2701
+ const s = shownAt(t);
2702
+ if (!s)
2703
+ return {
2704
+ state: home() || order[0] || "",
2705
+ shown: true,
2706
+ drawn: /** @type {const} */ ("screen"),
2707
+ still: null,
2708
+ };
2709
+ if (inState(s.state)) return { ...s, shown: true, showing: s.state };
2710
+ // not on the screen shown: the nearest screen it is on
2711
+ const i = order.indexOf(s.state);
2712
+ let best = "";
2713
+ let far = Number.POSITIVE_INFINITY;
2714
+ order.forEach((id, k) => {
2715
+ if (inState(id) && Math.abs(k - i) < far) {
2716
+ far = Math.abs(k - i);
2717
+ best = id;
2718
+ }
2719
+ });
2720
+ return { ...s, state: best || own, shown: false, showing: s.state };
2721
+ };
2722
+ /** @param {string} [state] */
2723
+ const box = (state = home()) => {
2724
+ const ref = inState(state);
2725
+ const b = ref ? elementBox(ref) : null;
2726
+ if (!b) {
2727
+ const on = states().map((s) => s.state);
2728
+ throw new Error(
2729
+ `product: ${part.name} is not on the screen ${state}${on.length ? ` — it is on ${on.join(", ")}` : ""}`,
2730
+ );
2731
+ }
2732
+ return b;
2733
+ };
2734
+ /** @param {Box} b @param {number} t */
2735
+ const stageOf = (b, t) => (mapped ? mapped(b, t) : toStage(b, t));
2736
+ /** @param {number} t @returns {PartAt} */
2737
+ const at = (t) => {
2738
+ const r = readOn(t);
2739
+ const screen = box(r.state);
2740
+ const stage = stageOf(screen, t);
2741
+ const picture = toPicture(stage, t);
2742
+ const k =
2743
+ r.drawn === "still" ? ratio.still : r.drawn === "recording" ? ratio.recording : undefined;
2744
+ return {
2745
+ t,
2746
+ state: r.state,
2747
+ shown: r.shown,
2748
+ ...("showing" in r && r.showing ? { showing: r.showing } : {}),
2749
+ screen,
2750
+ stage,
2751
+ picture,
2752
+ inFrame: shareInside(picture, frameBox()),
2753
+ drawn: r.drawn,
2754
+ ...(k && screen.width > 0 ? { sourcePx: picture.width / screen.width / k } : {}),
2755
+ };
2756
+ };
2757
+ /** where the capture acted on it: the action that led out of the screen
2758
+ * shown just before t (else its last one), the point the log kept (the
2759
+ * shoot's cursor less its scroll, the take's event), and the screen that
2760
+ * point is on @param {number} t */
2761
+ const acted = (t) => {
2762
+ const before = readOn(t - 1e-6).state;
2763
+ const from = order.indexOf(before);
2764
+ const found = screens.filter(({ id, since, action: a }) =>
2765
+ a
2766
+ ? (a.acted && a.acted === inState(id)) ||
2767
+ (a.actedBefore && since && a.actedBefore === inState(since))
2768
+ : false,
2769
+ );
2770
+ if (!found.length) return null;
2771
+ const s = found.find((x) => order.indexOf(x.id) > from) ?? found[found.length - 1];
2772
+ if (!s) return null;
2773
+ /** @type {{ x: number, y: number } | null} */
2774
+ let p = null;
2775
+ if (kind === "shoot") {
2776
+ const i = stillOfState.get(s.id);
2777
+ const still = i != null ? stills[i] : null;
2778
+ if (still?.cursor)
2779
+ p = {
2780
+ x: still.cursor.x - (still.scroll?.x ?? 0),
2781
+ y: still.cursor.y - (still.scroll?.y ?? 0),
2782
+ };
2783
+ } else if (kind === "take") {
2784
+ const e = log?.events?.find((/** @type {any} */ x) => x.state === s.id);
2785
+ if (e) p = e.kind === "dropFiles" && e.to ? { x: e.to.x, y: e.to.y } : { x: e.x, y: e.y };
2786
+ }
2787
+ if (!p) return null;
2788
+ // a shoot's first screen has its point on itself; every other point is
2789
+ // on what was acted on as the screen before showed it
2790
+ const on = s.since && inState(s.since) ? s.since : s.id;
2791
+ return { p, on };
2792
+ };
2793
+ /** @param {number} t */
2794
+ const pointAt = (t) => {
2795
+ const a = acted(t);
2796
+ if (!a) {
2797
+ const s = stageOf(box(readOn(t).state), t);
2798
+ return { x: s.x + s.width / 2, y: s.y + s.height / 2 };
2799
+ }
2800
+ // its offset inside the part, kept on the box shown just before t
2801
+ const there = box(readOn(t - 1e-6).state);
2802
+ const was = box(a.on);
2803
+ const q = { x: there.x + (a.p.x - was.x), y: there.y + (a.p.y - was.y), width: 0, height: 0 };
2804
+ const s = stageOf(q, t);
2805
+ return { x: s.x, y: s.y };
2806
+ };
2807
+ /** @type {PartUse[]} */
2808
+ const uses = [];
2809
+ /** @type {{ t: number, b: Box } | null} */
2810
+ let last = null;
2811
+ /** @param {number} t */
2812
+ const pictureAt = (t) => {
2813
+ if (last?.t !== t) last = { t, b: at(t).picture };
2814
+ return last.b;
2815
+ };
2816
+ let curves = false;
2817
+ // a lifted copy is one part however often via() asks for it (a page
2818
+ // asks on every frame)
2819
+ /** @type {WeakMap<object, Part>} */
2820
+ const vias = new WeakMap();
2821
+ let copies = 0;
2822
+ /** @type {Part} */
2823
+ const part = {
2824
+ key: spec.key,
2825
+ name: spec.name,
2826
+ ref: spec.ref,
2827
+ ...(spec.track ? { track: spec.track.id } : {}),
2828
+ ...(entries.get(spec.ref)?.kind ? { kind: entries.get(spec.ref).kind } : {}),
2829
+ get states() {
2830
+ return states();
2831
+ },
2832
+ in: inState,
2833
+ box,
2834
+ boxAt: (t) => at(t).stage,
2835
+ pointAt,
2836
+ at,
2837
+ via: (layer) => {
2838
+ if (!layer || typeof layer.map !== "function" || !layer.box || !layer.source)
2839
+ throw new Error(
2840
+ "product: via() takes a lifted copy (lift()) — its box, source and map()",
2841
+ );
2842
+ const had = vias.get(layer);
2843
+ if (had) return had;
2844
+ const copy = keep(
2845
+ makePart({ ...spec, name: part.name, key: `${spec.key} via ${++copies}` }, (b) => {
2846
+ const L = layer.box;
2847
+ const S = layer.source;
2848
+ return layer.map({
2849
+ x: b.x + L.x - S.x,
2850
+ y: b.y + L.y - S.y,
2851
+ width: b.width,
2852
+ height: b.height,
2853
+ });
2854
+ }),
2855
+ );
2856
+ vias.set(layer, copy);
2857
+ return copy;
2858
+ },
2859
+ mark: (t, label) => {
2860
+ part.used("mark", t, label != null ? { label } : {});
2861
+ return t;
2862
+ },
2863
+ coveredBy: (t) => covered(part, at(t).picture),
2864
+ used: (use, t, o = {}) => {
2865
+ if (!Number.isFinite(t)) return;
2866
+ /** @type {PartUse} */
2867
+ const u = { use, t, ...o };
2868
+ uses.push(u);
2869
+ later(() => {
2870
+ const ref = inState(readOn(t).state) ?? spec.ref;
2871
+ u.ref = ref;
2872
+ if (!tl) return;
2873
+ const b = pictureAt(t);
2874
+ tl.event(t, "part", {
2875
+ x: b.x + b.width / 2,
2876
+ y: b.y + b.height / 2,
2877
+ label: `${use} ${ref}`,
2878
+ });
2879
+ if (curves) return;
2880
+ curves = true;
2881
+ // under the name it has now (a later part() may have named it)
2882
+ tl.curve(`part:${part.name}.x`, (u) => {
2883
+ const p = pictureAt(u);
2884
+ return p.x + p.width / 2;
2885
+ });
2886
+ tl.curve(`part:${part.name}.y`, (u) => {
2887
+ const p = pictureAt(u);
2888
+ return p.y + p.height / 2;
2889
+ });
2890
+ tl.curve(`part:${part.name}.w`, (u) => pictureAt(u).width);
2891
+ tl.curve(`part:${part.name}.h`, (u) => pictureAt(u).height);
2892
+ });
2893
+ },
2894
+ uses,
2895
+ };
2896
+ return part;
2897
+ };
2898
+ /** a part the film named, kept in the page's registry @param {Part} part */
2899
+ const keep = (part) => {
2900
+ made.push(part);
2901
+ registry.push(part);
2902
+ return part;
2903
+ };
2904
+
2905
+ // --- what is drawn over a part (a page in a browser) ---
2906
+ const urls = (() => {
2907
+ /** @type {Set<string>} */
2908
+ const out = new Set();
2909
+ if (!data.base) return out;
2910
+ /** @param {string} rel @param {string} base */
2911
+ const add = (rel, base) => {
2912
+ try {
2913
+ out.add(new URL(rel, base).href.replace(/[?#].*$/, ""));
2914
+ } catch {
2915
+ /* not a URL: nothing to match */
2916
+ }
2917
+ };
2918
+ for (const s of screens) if (s.url) add(s.url, data.base);
2919
+ const lb = data.logUrl ?? data.base;
2920
+ for (const s of stills) if (s.file) add(s.file, lb);
2921
+ if (kind === "take") add("capture.mp4", lb);
2922
+ return out;
2923
+ })();
2924
+ /** the elements showing the screens: view()'s, else those whose src is one of them */
2925
+ const screenEls = () =>
2926
+ view.el ??
2927
+ Array.from(document.querySelectorAll("iframe, img, video")).filter((e) => {
2928
+ const src =
2929
+ /** @type {HTMLIFrameElement} */ (e).src || /** @type {HTMLVideoElement} */ (e).currentSrc;
2930
+ return src && urls.has(src.replace(/[?#].*$/, "")) && !e.closest("[data-ot-lift]");
2931
+ });
2932
+ /** @param {Part} part @param {Box} pic */
2933
+ const covered = (part, pic) => {
2934
+ if (typeof document === "undefined")
2935
+ throw new Error("product: coveredBy() reads the page — it runs in a browser");
2936
+ const mine = new Set([
2937
+ part.ref,
2938
+ ...part.states.map((s) => s.ref),
2939
+ ...(part.track ? [part.track] : []),
2940
+ ]);
2941
+ const shows = new Set(screenEls());
2942
+ const style = document.createElement("style");
2943
+ style.textContent = "*{pointer-events:auto!important}";
2944
+ document.head.appendChild(style);
2945
+ /** @type {Map<string, number>} */
2946
+ const counts = new Map();
2947
+ const N = 24;
2948
+ try {
2949
+ for (let j = 0; j < 4; j++)
2950
+ for (let i = 0; i < 6; i++) {
2951
+ const x = pic.x + ((i + 0.5) * pic.width) / 6;
2952
+ const y = pic.y + ((j + 0.5) * pic.height) / 4;
2953
+ if (x < 0 || y < 0 || x >= innerWidth || y >= innerHeight) continue;
2954
+ const top = document.elementsFromPoint(x, y).find(paints);
2955
+ // the screen's own element, or inside one view() gave (a wrapper)
2956
+ if (!top || [...shows].some((e) => e === top || e.contains(top))) continue;
2957
+ const lifted = top.closest("[data-ot-lift]");
2958
+ if (
2959
+ lifted instanceof HTMLElement &&
2960
+ (lifted.dataset.otLift ?? "").split(" ").some((k) => mine.has(k))
2961
+ )
2962
+ continue;
2963
+ const what = describe(top);
2964
+ counts.set(what, (counts.get(what) ?? 0) + 1);
2965
+ }
2966
+ } finally {
2967
+ style.remove();
2968
+ }
2969
+ return [...counts]
2970
+ .map(([what, n]) => ({ what, share: n / N }))
2971
+ .sort((a, b) => b.share - a.share);
2972
+ };
2973
+
2974
+ /** @param {string | TextKey | Part} key @param {{ name?: string }} [o] @returns {Part} */
2975
+ const partOf = (key, o = {}) => {
2976
+ if (isPart(key)) return key;
2977
+ /** @param {string} id @param {() => { name: string, ref: string, track?: any, text?: TextKey }} make */
2978
+ const once = (id, make) => {
2979
+ const had = byKey.get(id);
2980
+ if (had) {
2981
+ if (o.name) had.name = o.name;
2982
+ return had;
2983
+ }
2984
+ const spec = { ...make(), key: id };
2985
+ if (o.name) spec.name = o.name;
2986
+ const p = makePart(spec);
2987
+ if (!p.states.length)
2988
+ throw new Error(
2989
+ `product: ${spec.name} is on none of the screens read (${order.join(", ") || "none"}) — product(url, { states }) left out ${stateOfRef(spec.ref)}`,
2990
+ );
2991
+ byKey.set(id, keep(p));
2992
+ return p;
2993
+ };
2994
+ if (typeof key === "string") {
2995
+ // a track and the refs of its steps are one part
2996
+ const t = tracks.get(key);
2997
+ if (t?.steps?.length) return once(key, () => ({ name: key, ref: t.steps[0].ref, track: t }));
2998
+ if (/^(.+):(e\d+)$/.test(key) && elementBox(key)) {
2999
+ const track = tracks.get(entries.get(key)?.track);
3000
+ return once(track ? track.id : key, () => ({
3001
+ name: key,
3002
+ ref: key,
3003
+ ...(track ? { track } : {}),
3004
+ }));
3005
+ }
3006
+ } else if (isTextKey(key)) {
3007
+ for (const state of order) {
3008
+ const ref = byIndexText(state, key);
3009
+ if (!ref) continue;
3010
+ const track = tracks.get(entries.get(ref)?.track);
3011
+ return once(`{ text: ${JSON.stringify(key.text)}, up: ${key.up ?? 0} }`, () => ({
3012
+ name: `"${key.text}"`,
3013
+ ref,
3014
+ text: key,
3015
+ ...(track ? { track } : {}),
3016
+ }));
3017
+ }
3018
+ }
3019
+ const what =
3020
+ typeof key === "string" ? key : isTextKey(key) ? `{ text: "${key.text}" }` : String(key);
3021
+ throw new Error(
3022
+ `product: no part ${what} — it has ${entries.size} part(s) by ref (${[...entries.keys()].slice(0, 3).join(", ")}${entries.size > 3 ? ", …" : ""})${tracks.size ? `, tracks ${[...tracks.keys()].join(", ")}` : ""}, screens ${order.join(", ") || "none"}; \`open-take components <dir>\` lists them`,
3023
+ );
3024
+ };
3025
+
3026
+ return {
3027
+ kind,
3028
+ /** the screens, in the log's order */
3029
+ states: order,
3030
+ /** a part: a ref ("home:e41"), a track ("t1"), { text, up }, or a part
3031
+ * again; `name` is what the film calls it */
3032
+ part: partOf,
3033
+ /**
3034
+ * Which screen shows at film time t: a list of [t, screen id | { still:
3035
+ * i }] (each from its time on), a function of t giving one, or a clip()
3036
+ * of a take (the last state saved by the time the clip shows). Spread a
3037
+ * drag's `steps` into the list. Without it, a part is read on its own
3038
+ * screen.
3039
+ * @param {PlayEntry[] | ((t: number) => string | { still: number }) | { toCapture: (t: number) => number }} schedule
3040
+ */
3041
+ play(schedule) {
3042
+ if (Array.isArray(schedule)) {
3043
+ const list = schedule
3044
+ .map(([t, v], i) => ({ t, e: entryOf(v), i }))
3045
+ .sort((a, b) => a.t - b.t || a.i - b.i);
3046
+ if (!list.length) throw new Error("product: play needs at least one [t, screen]");
3047
+ playing = (t) => {
3048
+ let e = /** @type {(typeof list)[number]} */ (list[0]).e;
3049
+ for (const x of list) if (x.t <= t) e = x.e;
3050
+ return e;
3051
+ };
3052
+ } else if (typeof schedule === "function") {
3053
+ const f = schedule;
3054
+ playing = (t) => entryOf(f(t));
3055
+ } else if (schedule && typeof schedule.toCapture === "function") {
3056
+ const c = schedule;
3057
+ const items = (log?.states?.items ?? []).filter(
3058
+ (/** @type {any} */ s) => !s.moving && screenOf.has(s.id),
3059
+ );
3060
+ if (!items.length) throw new Error("product: play(clip) needs a take with saved states");
3061
+ playing = (t) => {
3062
+ const ms = c.toCapture(t) * 1000;
3063
+ let id = items[0].id;
3064
+ for (const s of items) if (s.tMs <= ms) id = s.id;
3065
+ return { state: id, still: null, drawn: "recording" };
3066
+ };
3067
+ } else
3068
+ throw new Error("product: play takes a list of [t, screen], a function of t, or a clip()");
3069
+ return this;
3070
+ },
3071
+ /** the screen shown at t (play), or null @param {number} t */
3072
+ state: (t) => shownAt(t)?.state ?? null,
3073
+ /** the still shown at t (play: { still } or a screen a still kept), or null @param {number} t */
3074
+ still: (t) => shownAt(t)?.still ?? null,
3075
+ /**
3076
+ * Where the screens are drawn and seen: `place` a seam() ({ scale,
3077
+ * offset }), the box the screen's viewport is drawn in, { x, y, scale },
3078
+ * or a function of t giving one (default: the screen's own px are the
3079
+ * layer's); `cam` anything with toView(x, y, t) (kit/camera.js); `frame`
3080
+ * the picture's size (default the camera's view); `el` the elements
3081
+ * showing the screens (default: those whose src is one of them) — only
3082
+ * coveredBy() reads it.
3083
+ * @param {{ place?: PlaceLike | ((t: number) => PlaceLike), cam?: { toView: (x: number, y: number, t: number) => number[], view?: { width: number, height: number } }, el?: Element[], frame?: { width: number, height: number } }} v
3084
+ */
3085
+ view(v) {
3086
+ view = { ...view, ...v };
3087
+ return this;
3088
+ },
3089
+ /**
3090
+ * A drag in step with the screens saved along it: the path the cursor
3091
+ * takes (the layer's px) — where the control was pressed, then the real
3092
+ * cursor at each saved step — and from when each step shows: when the
3093
+ * cursor, paced by `ease`, reaches its point. `key`: a track ("t1") or a
3094
+ * shoot's drag name (its stills `<name>-<i>`), with `end`; or a take's
3095
+ * action ("a3") with `{ clip }`, from the capture's own path, times and
3096
+ * pace. `ease`, `press` and `end` are the film's to change; `steps` is a
3097
+ * plain list. Hand it to cur.drag(d) and spread d.steps into play().
3098
+ * @param {string | Part} key
3099
+ * @param {number} at
3100
+ * @param {number | { ease?: (p: number) => number, press?: { x: number, y: number }, clip?: Clip, states?: string[] }} [end]
3101
+ * @param {{ ease?: (p: number) => number, press?: { x: number, y: number }, clip?: Clip, states?: string[] }} [o]
3102
+ */
3103
+ drag(key, at, end, o = {}) {
3104
+ if (end != null && typeof end === "object") {
3105
+ o = end;
3106
+ end = undefined;
3107
+ }
3108
+ if (!Number.isFinite(at)) throw new Error("product: drag needs the time it starts (s)");
3109
+ /** @param {{ x: number, y: number }} p */
3110
+ const layer = (p) => {
3111
+ const s = toStage({ x: p.x, y: p.y, width: 0, height: 0 }, at);
3112
+ return { x: s.x, y: s.y };
3113
+ };
3114
+ // a take's action: the capture's own stroke
3115
+ if (typeof key === "string" && /^a\d+$/.test(key) && kind === "take") {
3116
+ const i = Number(key.slice(1)) - 1;
3117
+ const e = log?.events?.[i];
3118
+ if (!e)
3119
+ throw new Error(`product: no action ${key} — the take has ${log?.events?.length ?? 0}`);
3120
+ if (e.kind !== "drag")
3121
+ throw new Error(`product: ${key} is a ${e.kind ?? "click"}, not a drag`);
3122
+ if (!o.clip)
3123
+ throw new Error(
3124
+ `product: drag ${key} needs { clip } — the clip that shows the recording`,
3125
+ );
3126
+ const a = o.clip.toFilm(e.tMs / 1000);
3127
+ const b = end ?? o.clip.toFilm((e.tMs + (e.durationMs ?? 0)) / 1000);
3128
+ if (a == null || b == null) throw new Error(`product: the clip does not show ${key}`);
3129
+ const pts = (e.path?.length >= 2 ? e.path : [{ x: e.x, y: e.y }, e.to]).map(layer);
3130
+ const ease = o.ease ?? (e.ease === "smooth" ? smootherstep : linearPace);
3131
+ // the screen before it: the one saved just before the one it led to,
3132
+ // else the last saved by its time (as `open-take states` reads it)
3133
+ const items = log?.states?.items ?? [];
3134
+ const k = e.state ? items.findIndex((/** @type {any} */ s) => s.id === e.state) : -1;
3135
+ let prior = k > 0 ? items[k - 1].id : undefined;
3136
+ if (k <= 0) for (const s of items) if (s.tMs <= e.tMs) prior = s.id;
3137
+ const ref = prior && e.target ? `${prior}:${e.target}` : null;
3138
+ const p = ref && elementBox(ref) ? partOf(ref) : null;
3139
+ const d = dragOf(
3140
+ {
3141
+ path: o.press ? [layer(o.press), ...pts] : pts,
3142
+ at: a,
3143
+ end: b,
3144
+ ease,
3145
+ steps: [],
3146
+ basis: "take recording",
3147
+ },
3148
+ p,
3149
+ key,
3150
+ );
3151
+ return d;
3152
+ }
3153
+ if (end == null)
3154
+ throw new Error(
3155
+ "product: a drag over saved stills needs its end (s): their clock includes the waits",
3156
+ );
3157
+ if (!(end > at)) throw new Error(`product: drag ends (${end}) before it starts (${at})`);
3158
+ // the steps: a drag's stills, or a track's screens
3159
+ /** @type {{ still: number, state: string | null }[]} */
3160
+ let steps = [];
3161
+ /** @type {Part | null} */
3162
+ let p = null;
3163
+ if (typeof key === "string" && stills.some((s) => s.name === `${key}-1`)) {
3164
+ const re = new RegExp(`^${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}-(\\d+)$`);
3165
+ stills.forEach((s, i) => {
3166
+ if (re.test(s.name ?? ""))
3167
+ steps.push({ still: i, state: s.state && screenOf.has(s.state) ? s.state : null });
3168
+ });
3169
+ const lastStep = steps[steps.length - 1];
3170
+ const fin = lastStep ? stills[lastStep.still + 1] : null;
3171
+ if (lastStep && fin?.name === key)
3172
+ steps.push({
3173
+ still: lastStep.still + 1,
3174
+ state: fin.state && screenOf.has(fin.state) ? fin.state : null,
3175
+ });
3176
+ } else {
3177
+ p = partOf(/** @type {string | Part} */ (key));
3178
+ const part = p;
3179
+ const on = part.states
3180
+ .filter((s) => stillOfState.has(s.state))
3181
+ .map((s) => ({
3182
+ still: /** @type {number} */ (stillOfState.get(s.state)),
3183
+ state: s.state,
3184
+ }));
3185
+ if (o.states) steps = on.filter((s) => o.states?.includes(s.state));
3186
+ else {
3187
+ // the drag's own run: screens one after another whose still one
3188
+ // drag took (its steps "<name>-<i>" and the still it ends on)
3189
+ /** @param {number} i */
3190
+ const dragName = (i) =>
3191
+ stills[i]?.action === "drag" ? String(stills[i].name ?? "").replace(/-\d+$/, "") : null;
3192
+ /** @type {(typeof on)[]} */
3193
+ const runs = [];
3194
+ for (const s of on) {
3195
+ const name = dragName(s.still);
3196
+ const run = runs[runs.length - 1];
3197
+ const last = run?.[run.length - 1];
3198
+ if (name == null) continue;
3199
+ if (
3200
+ run &&
3201
+ last &&
3202
+ order.indexOf(s.state) === order.indexOf(last.state) + 1 &&
3203
+ dragName(last.still) === name
3204
+ )
3205
+ run.push(s);
3206
+ else runs.push([s]);
3207
+ }
3208
+ // the run whose drag acted on this part, else the first
3209
+ const mine = runs.find((run) =>
3210
+ run.some(({ state, still }) => {
3211
+ const a = screenOf.get(state)?.action;
3212
+ return (
3213
+ (a?.acted && a.acted === part.in(state)) ||
3214
+ (a?.actedBefore && a.actedBefore === part.in(stateOfStill(still - 1)))
3215
+ );
3216
+ }),
3217
+ );
3218
+ steps = mine ?? runs[0] ?? [];
3219
+ if (!steps.length)
3220
+ throw new Error(
3221
+ `product: drag ${part.name} — none of the screens it is on (${on.map((s) => s.state).join(", ") || "none with a still"}) was saved along a drag; { states } names the steps`,
3222
+ );
3223
+ }
3224
+ }
3225
+ steps = steps.filter((s) => stills[s.still]?.cursor);
3226
+ if (!steps.length)
3227
+ throw new Error(
3228
+ `product: drag ${typeof key === "string" ? key : key.name} has no still with a cursor to follow`,
3229
+ );
3230
+ const pts = steps.map((s) => {
3231
+ const c = stills[s.still];
3232
+ return layer({ x: c.cursor.x - (c.scroll?.x ?? 0), y: c.cursor.y - (c.scroll?.y ?? 0) });
3233
+ });
3234
+ // where it was pressed: the control the first step acted on, as the
3235
+ // screen before it showed it
3236
+ let press = o.press ? layer(o.press) : null;
3237
+ const step0 = /** @type {(typeof steps)[number]} */ (steps[0]);
3238
+ const a0 = step0.state ? screenOf.get(step0.state)?.action : null;
3239
+ const ref0 = a0?.actedBefore ?? a0?.acted;
3240
+ if (ref0) {
3241
+ // a drag named by its stills: the part is the control pressed
3242
+ if (!p && elementBox(ref0))
3243
+ try {
3244
+ p = partOf(ref0);
3245
+ } catch {
3246
+ /* on none of the screens read: the drag goes without a part */
3247
+ }
3248
+ if (!press) {
3249
+ const prior = stateOfStill(Math.max(0, step0.still - 1));
3250
+ // followed to that screen without keeping it as a part the film named
3251
+ const track = tracks.get(entries.get(ref0)?.track);
3252
+ const control = makePart({ key: "", name: ref0, ref: ref0, ...(track ? { track } : {}) });
3253
+ const b = elementBox(control.in(prior) ?? ref0);
3254
+ if (b) press = layer({ x: b.x + b.width / 2, y: b.y + b.height / 2 });
3255
+ }
3256
+ }
3257
+ const first = /** @type {{ x: number, y: number }} */ (pts[0]);
3258
+ const path =
3259
+ press && Math.hypot(press.x - first.x, press.y - first.y) > 1e-9 ? [press, ...pts] : pts;
3260
+ if (path.length < 2)
3261
+ throw new Error(
3262
+ `product: drag ${typeof key === "string" ? key : key.name} has one point to follow (${steps[0]?.state ?? `still ${step0.still}`}) — { press } says where it starts`,
3263
+ );
3264
+ const ease = o.ease ?? smootherstep;
3265
+ const L = lengthsAlong(path);
3266
+ const skip = path.length - pts.length;
3267
+ const span = /** @type {number} */ (end) - at;
3268
+ /** @type {PlayEntry[]} */
3269
+ const list = steps.map((s, k) => [
3270
+ at + span * easeInverse(ease, /** @type {number} */ (L[k + skip])),
3271
+ s.state ?? { still: s.still },
3272
+ ]);
3273
+ return dragOf(
3274
+ { path, at, end, ease, steps: list, basis: "shoot stills" },
3275
+ p,
3276
+ typeof key === "string" ? key : key.name,
3277
+ );
3278
+ },
3279
+ /** every part made, with its uses */
3280
+ parts: () => [...made],
3281
+ };
3282
+
3283
+ /**
3284
+ * @param {{ path: { x: number, y: number }[], at: number, end: number, ease: (p: number) => number, steps: PlayEntry[], basis: string }} d
3285
+ * @param {Part | null} p @param {string} name
3286
+ */
3287
+ function dragOf(d, p, name) {
3288
+ /** @param {number} t */
3289
+ const stepAt = (t) => {
3290
+ let s = d.steps[0];
3291
+ for (const x of d.steps) if (x[0] <= t) s = x;
3292
+ return s ?? null;
3293
+ };
3294
+ const use = { end: d.end, steps: d.steps.map((s) => /** @type {PlayEntry} */ ([...s])) };
3295
+ if (p) p.used("drag", d.at, use);
3296
+ else {
3297
+ // no part of components.json was pressed: the drag alone, by its name
3298
+ // (once, however often the page asks for it)
3299
+ const key = `drag ${name}`;
3300
+ let had = registry.find((x) => x.key === key);
3301
+ if (!had) {
3302
+ had = { key, name, uses: [] };
3303
+ registry.push(had);
3304
+ }
3305
+ if (!had.uses.some((u) => u.t === d.at && u.end === d.end))
3306
+ had.uses.push({ use: "drag", t: d.at, ...use });
3307
+ }
3308
+ return {
3309
+ ...d,
3310
+ /** the part dragged, when the inventory knows it */
3311
+ part: p,
3312
+ /** the screen shown at t (its step's), or null for a take's @param {number} t */
3313
+ state(t) {
3314
+ const s = stepAt(t);
3315
+ if (!s) return null;
3316
+ return typeof s[1] === "string" ? s[1] : stateOfStill(s[1].still);
3317
+ },
3318
+ /** the still shown at t, or null @param {number} t */
3319
+ still(t) {
3320
+ const s = stepAt(t);
3321
+ if (!s) return null;
3322
+ return typeof s[1] === "string" ? (stillOfState.get(s[1]) ?? null) : s[1].still;
3323
+ },
3324
+ /** the dragged part's value at t (its track's), or null @param {number} t */
3325
+ value(t) {
3326
+ const st = this.state(t);
3327
+ if (!p || !st) return null;
3328
+ return p.states.find((s) => s.state === st)?.value ?? null;
3329
+ },
3330
+ };
3331
+ }
3332
+ }
3333
+
3334
+ /** whether an element paints something of its own at all: a picture, a
3335
+ * fill, a border, a shape, its own text — a bare wrapper does not
3336
+ * @param {Element} el */
3337
+ function paints(el) {
3338
+ const view = el.ownerDocument.defaultView;
3339
+ if (!view) return false;
3340
+ for (let n = /** @type {Element | null} */ (el); n; n = n.parentElement) {
3341
+ const c = view.getComputedStyle(n);
3342
+ if (c.display === "none" || Number(c.opacity) === 0) return false;
3343
+ }
3344
+ const cs = view.getComputedStyle(el);
3345
+ if (cs.visibility === "hidden" || cs.visibility === "collapse") return false;
3346
+ const tag = el.tagName.toUpperCase();
3347
+ if (/^(IMG|VIDEO|CANVAS|IFRAME|OBJECT|EMBED|PICTURE)$/.test(tag)) return true;
3348
+ if (el instanceof view.SVGElement) {
3349
+ if (tag === "SVG" || tag === "G" || tag === "DEFS") return false;
3350
+ return cs.fill !== "none" || cs.stroke !== "none";
3351
+ }
3352
+ const bg = cs.backgroundColor;
3353
+ if (bg && bg !== "transparent" && !/rgba\(.*,\s*0\)$/.test(bg)) return true;
3354
+ if (cs.backgroundImage && cs.backgroundImage !== "none") return true;
3355
+ if (
3356
+ ["Top", "Right", "Bottom", "Left"].some(
3357
+ (s) =>
3358
+ Number.parseFloat(cs.getPropertyValue(`border-${s.toLowerCase()}-width`)) > 0 &&
3359
+ cs.getPropertyValue(`border-${s.toLowerCase()}-style`) !== "none",
3360
+ )
3361
+ )
3362
+ return true;
3363
+ return Array.from(el.childNodes).some((n) => n.nodeType === 3 && (n.nodeValue ?? "").trim());
3364
+ }
3365
+
3366
+ /** an element in a few words: its tag, its id or first class, else the
3367
+ * nearest id around it @param {Element} el */
3368
+ function describe(el) {
3369
+ const tag = el.tagName.toLowerCase();
3370
+ if (el.id) return `${tag}#${el.id}`;
3371
+ const cls = el.getAttribute("class")?.trim().split(/\s+/)[0];
3372
+ const up = el.parentElement?.closest("[id]");
3373
+ return `${tag}${cls ? `.${cls}` : ""}${up ? ` in #${up.id}` : ""}`;
3374
+ }
3375
+
3376
+ /**
3377
+ * The product's parts as references: components.json (`open-take
3378
+ * components`), its log and every listed screen's index.json, read so every
3379
+ * later call answers at once (a camera move or a click resolves when it is
3380
+ * asked for). `url`: a shoot's folder (shots/), a take (x.take/), a film's
3381
+ * states/ or one saved screen's folder, or a components.json. `states`: only
3382
+ * these screens. `tl` (kit/time.js): each use is declared — an event "part"
3383
+ * where it shows, and curves `part:<name>.x/.y/.w/.h` (the picture's px) —
3384
+ * so `film probe` follows it like any declared subject.
3385
+ *
3386
+ * const P = await product("../shots/", { tl });
3387
+ * P.view({ cam });
3388
+ * const part = P.part("home:e41");
3389
+ * cam.frame(part, { arrive: 12 }); // where it is when the move lands
3390
+ * cur.click(part, 13); // on the point the shoot clicked
3391
+ * const d = P.drag("t1", 20.4, 21.4); // the cursor in step with the saved steps
3392
+ * cur.drag(d);
3393
+ * P.play([[0, "home"], ...d.steps, [23.3, "done"]]);
3394
+ *
3395
+ * Every part made, and what the film did with it, is in window.__otParts for
3396
+ * `film render`'s report.
3397
+ * @param {string} url
3398
+ * @param {{ tl?: { event: (at: number, kind: string, o?: { x?: number, y?: number, label?: string }) => number, curve: (name: string, fn: (t: number) => number) => void }, states?: string[] }} [o]
3399
+ */
3400
+ export async function product(url, o = {}) {
3401
+ let at = new URL(url, location.href);
3402
+ /** @param {URL} u */
3403
+ const read = async (u) => {
3404
+ const res = await fetch(u);
3405
+ return res.ok ? res.json() : null;
3406
+ };
3407
+ /** @type {any} */
3408
+ let components = null;
3409
+ if (/\.json$/i.test(at.pathname)) {
3410
+ components = await read(at);
3411
+ if (!components) throw new Error(`product: ${at.href} could not be read`);
3412
+ // a log given instead: the folder it is in
3413
+ if (!Array.isArray(components.components)) {
3414
+ components = null;
3415
+ at = new URL(".", at);
3416
+ }
3417
+ } else at = new URL(at.href.replace(/\/?(?=[?#]|$)/, "/"));
3418
+ const compUrl = /\.json$/i.test(at.pathname) ? at : new URL("components.json", at);
3419
+ components ??= await read(compUrl);
3420
+ /** @type {Record<string, any>} */
3421
+ const indexes = {};
3422
+ if (!components) {
3423
+ // one saved screen without its inventory: its index alone
3424
+ const index = await read(new URL("index.json", compUrl));
3425
+ if (!index)
3426
+ throw new Error(
3427
+ `product: no components.json at ${compUrl.href} — \`open-take components <dir>\` writes it`,
3428
+ );
3429
+ indexes[stateOf(new URL("state.html", compUrl).href) ?? "state"] = index;
3430
+ return productFrom({ indexes, base: compUrl.href, ...o });
3431
+ }
3432
+ const logUrl = components.source?.log ? new URL(components.source.log, compUrl) : null;
3433
+ const log = logUrl ? await read(logUrl) : null;
3434
+ const wanted = (components.states ?? []).filter(
3435
+ (/** @type {any} */ s) => !o.states || o.states.includes(s.id),
3436
+ );
3437
+ await Promise.all(
3438
+ wanted.map(async (/** @type {any} */ s) => {
3439
+ const index = await read(
3440
+ new URL(String(s.url).replace(/state\.html$/, "index.json"), compUrl),
3441
+ );
3442
+ if (index) indexes[s.id] = index;
3443
+ }),
3444
+ );
3445
+ return productFrom({
3446
+ components,
3447
+ log,
3448
+ indexes,
3449
+ base: compUrl.href,
3450
+ ...(logUrl ? { logUrl: logUrl.href } : {}),
3451
+ ...o,
3452
+ });
3453
+ }
3454
+
3455
+ /**
3456
+ * @typedef {object} PartFile
3457
+ * @property {string} file its file name in parts/ ("home-e12-card.html")
3458
+ * @property {string} url the file's URL, for an iframe's src
3459
+ * @property {string} ref the part in components.json ("home:e12")
3460
+ * @property {string} state
3461
+ * @property {string} el
3462
+ * @property {string} kind number, stat, heading, button, input, card, …
3463
+ * @property {string} label
3464
+ * @property {Record<string, string>} values what it holds, by field, as the page showed it
3465
+ * @property {number} w its natural width, CSS px
3466
+ * @property {number} h its natural height, CSS px
3467
+ * @property {[number, number]} [drawn] what it draws to the right and below, when more than w × h (a heading set past its width) — the size an iframe needs to show all of it
3468
+ * @property {[number, number, number, number]} box where it sat on its screen
3469
+ * @property {string} [picture] its crisp picture's URL
3470
+ * @property {string} backdrop what was behind it on the page (the file is see-through)
3471
+ * @property {string[]} fonts font families set in it that have their font in the file
3472
+ */
3473
+
3474
+ /**
3475
+ * The product's parts as files (parts/index.json — beside a film's states/
3476
+ * after `film init --url`, in a shoot's or a take's folder): each part's own
3477
+ * elements with every computed style inlined and its fonts declared, so it
3478
+ * renders alone, in the product's styles, at its natural size `w` × `h`.
3479
+ * One route among the others (screen, lift, product, the film's own HTML);
3480
+ * nothing here picks a part.
3481
+ *
3482
+ * const F = await partFiles("parts/");
3483
+ * const card = F.get("home:e12"); // by ref or file name
3484
+ * frame.src = card.url; frame.width = card.w; frame.height = card.h; // scale the iframe
3485
+ * const el = await F.node("home:e12"); // or into the page itself
3486
+ * stage.append(el); el.style.transform = "scale(3)";
3487
+ *
3488
+ * node() puts the part in a shadow root of its own (the film's CSS does not
3489
+ * reach it; its ::before / ::after rules stay with it), adds its @font-face
3490
+ * rules to the page once (fonts are declared on the document) and makes its
3491
+ * references absolute. The host is a block of the part's natural size.
3492
+ * @param {string} url the parts folder, or its index.json
3493
+ */
3494
+ export async function partFiles(url) {
3495
+ const at = new URL(url, location.href);
3496
+ const indexUrl = /\.json$/i.test(at.pathname)
3497
+ ? at
3498
+ : new URL("index.json", at.href.replace(/\/?(?=[?#]|$)/, "/"));
3499
+ const res = await fetch(indexUrl);
3500
+ if (!res.ok)
3501
+ throw new Error(
3502
+ `partFiles: no parts/index.json at ${indexUrl.href} — \`film init --url\`, \`shoot\` and \`make --states\` write it`,
3503
+ );
3504
+ const index = await res.json();
3505
+ /** @type {PartFile[]} */
3506
+ const list = (index.parts ?? []).map((/** @type {any} */ p) => ({
3507
+ ...p,
3508
+ url: new URL(p.file, indexUrl).href,
3509
+ ...(p.picture ? { picture: new URL(p.picture, indexUrl).href } : {}),
3510
+ }));
3511
+ /** @param {string} key */
3512
+ const get = (key) => {
3513
+ const p = list.find((x) => x.ref === key || x.file === key || x.file === `${key}.html`);
3514
+ if (!p) {
3515
+ const sk = (index.skipped ?? []).find((/** @type {any} */ s) => s.ref === key);
3516
+ throw new Error(
3517
+ sk
3518
+ ? `partFiles: ${key} is not a file — ${sk.why}`
3519
+ : `partFiles: no part ${key} — there are ${list.map((x) => x.ref).join(", ") || "none"}`,
3520
+ );
3521
+ }
3522
+ return p;
3523
+ };
3524
+ /** every url() and src / href / poster in it, absolute against `base`
3525
+ * @param {string} css @param {string} base */
3526
+ const absCss = (css, base) =>
3527
+ css.replace(/url\(\s*(["']?)([^"')]+)\1\s*\)/g, (m, q, u) =>
3528
+ /^([a-z][a-z0-9+.-]*:|#)/i.test(u) ? m : `url(${q}${new URL(u, base).href}${q})`,
3529
+ );
3530
+ /** @type {Set<string>} */
3531
+ const fontsAdded = new Set();
3532
+ /** @param {string} key */
3533
+ const node = async (key) => {
3534
+ const p = get(key);
3535
+ const r = await fetch(p.url);
3536
+ if (!r.ok) throw new Error(`partFiles: ${p.url} could not be read`);
3537
+ const doc = new DOMParser().parseFromString(await r.text(), "text/html");
3538
+ for (const el of Array.from(doc.body.querySelectorAll("*"))) {
3539
+ for (const a of ["src", "href", "poster", "xlink:href"]) {
3540
+ const v = el.getAttribute(a);
3541
+ if (v && !/^([a-z][a-z0-9+.-]*:|#)/i.test(v)) el.setAttribute(a, new URL(v, p.url).href);
3542
+ }
3543
+ const st = el.getAttribute("style");
3544
+ if (st?.includes("url(")) el.setAttribute("style", absCss(st, p.url));
3545
+ }
3546
+ const fonts = doc.querySelector("style[data-part-fonts]")?.textContent ?? "";
3547
+ if (fonts.trim()) {
3548
+ const css = absCss(fonts, p.url);
3549
+ if (!fontsAdded.has(css)) {
3550
+ fontsAdded.add(css);
3551
+ const s = document.createElement("style");
3552
+ s.setAttribute("data-part-fonts", p.file);
3553
+ s.textContent = css;
3554
+ document.head.appendChild(s);
3555
+ }
3556
+ }
3557
+ const host = document.createElement("div");
3558
+ host.dataset.part = p.ref;
3559
+ host.style.cssText = `display:block;position:relative;width:${p.w}px;height:${p.h}px;transform-origin:0 0`;
3560
+ const root = host.attachShadow({ mode: "open" });
3561
+ const own = document.createElement("style");
3562
+ own.textContent = `:host{display:block}${absCss(doc.querySelector("style[data-part-pseudo]")?.textContent ?? "", p.url)}`;
3563
+ root.appendChild(own);
3564
+ for (const c of Array.from(doc.body.children)) root.appendChild(document.importNode(c, true));
3565
+ return host;
3566
+ };
3567
+ return { list, get, node };
3568
+ }