@open-take/compositor 0.5.2 → 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
@@ -0,0 +1,1398 @@
1
+ // swarm.js — a team of agent cursors building a finished screen in front of
2
+ // the viewer: each flies in, drags a selection box with corner handles round
3
+ // a card and the card appears, types a line of copy in with a text cursor,
4
+ // draws a rule, wipes in a picture, copies a repeated label from where it
5
+ // already stands, until the real screen stands untouched. A style some launch
6
+ // films use for "many agents working at once"; not a default for every film.
7
+ //
8
+ // The idea is swarm-animation (github.com/thefullctx/swarm-animation, MIT): a
9
+ // script that plays over a live web page on the browser's own clock and
10
+ // random numbers. Written again here as plain functions of film time, with no
11
+ // code taken from it; the ways of hiding a thing without moving the layout
12
+ // are its: a text node holds what is typed and an invisible twin beside it
13
+ // the rest, a box's paint is taken off and put back, a picture is wiped in.
14
+ // Under `film render` the original runs in clock mode — the same frames on
15
+ // any number of workers, but front to back only and with no motion blur, and
16
+ // with no start time, labels, holds or events to set sound and camera on.
17
+ //
18
+ // Plain functions of film time t (s): the plan is made once from the seed and
19
+ // the layout, and `draw(t)` writes the screen as it is at t — the same t
20
+ // gives the same frame in any order, so a render split across workers agrees.
21
+ // No timers, no Math.random.
22
+ //
23
+ // import { swarm, swarmBoxes } from "./lib/swarm.js";
24
+ // await document.fonts.ready; // the layout is read once, after the fonts
25
+ // const sw = swarm(document.querySelector("#table"), {
26
+ // agents: 8, seed: 1, start: 2.0, duration: 6, // or speed (1: about 22 characters a second)
27
+ // labels: ["競品 A", "競品 B", …], colors: ["#7cc4ff", …],
28
+ // assign: (item) => item.el.closest("tr")?.rowIndex - 1, // or "nearest"; or data-swarm-agent="3"
29
+ // holds: [{ agent: 5, from: 4.2, to: 6.0, color: "#fbbf24", label: "競品 F · 需要你" }],
30
+ // });
31
+ // window.__render = (t) => { camera(t); sw.draw(t); }; // after the camera: constantSize reads it
32
+ // sw.events.forEach((e) => e.kind === "done" && tl.event(e.t, "tick"));
33
+ //
34
+ // swarm(root, o) the elements inside root built by o.agents cursors; the overlay is put
35
+ // inside root, so a root that is scaled, moved or tilted in CSS
36
+ // perspective carries the cursors with it
37
+ // swarmBoxes(el, boxes, o) the same over a picture (<img>, <video>, <canvas>): each box
38
+ // { x, y, w, h, kind?, label?, agent?, order? } is revealed through a
39
+ // mask of its own; boxes in the picture's own px, or in o.size [w, h]
40
+ // (a shoot's boxes are in the still's CSS px: size: [1440, 900]); a
41
+ // box inside another is covered in the colour sampled round it until
42
+ // its own agent builds it, so a card shows empty, not with its rows
43
+ // plan(items, o) the schedule alone, no page: what tests and a sound script read
44
+ //
45
+ // each gives back { el, draw(t), end, events, items, agentsAt(t) }:
46
+ // draw(t) the screen at t: before o.start everything is hidden (the root's own
47
+ // background stays), after the last cursor leaves the page is as it was
48
+ // end when the last item lands
49
+ // events [{ t, agent, kind, el, item }] by time: kind "box", "type", "line", "wipe",
50
+ // "copy" when an item's work starts, "done" when it lands, "hold" and
51
+ // "resume" — for hits in the score and camera moves
52
+ // items [{ el, kind, agent, arrive, start, end, rect }] in plan order
53
+ // agentsAt(t) [{ x, y, visible, label, color, state }] in root px (its border box's top
54
+ // left); state "enter", "travel", "wait", "type", "box", "line", "wipe",
55
+ // "copy", "hold", "leave", "park", "gone"
56
+ //
57
+ // Options (swarm and swarmBoxes):
58
+ // agents 8, seed 1, start 0 how many, which numbers, when the first one enters
59
+ // duration | speed duration: start → end, the speed fitted to it (holds included);
60
+ // else speed (1)
61
+ // labels, colors per agent: its tag (none: a bare cursor) and colour (default eight
62
+ // hues apart, light enough for a dark surface)
63
+ // assign "nearest" (default: the free agent takes the nearest of the
64
+ // next few things in reading order) or (item, i) => agent index
65
+ // (null: nearest); data-swarm-agent on an element or an ancestor
66
+ // wins over both. An agent with its own items still helps with
67
+ // shared ones that come before them in reading order (a header)
68
+ // holds [{ agent, from, to, color?, label? }]: that agent stops where it
69
+ // is — mid-travel or mid-word — and waits, its cursor, tag and
70
+ // selection in the hold's colour with the hold's label, a ring
71
+ // pulsing round the tip; it carries on at `to` from where it was
72
+ // from [{ x, y }, …] in root px: where agents enter (cycled); default
73
+ // from outside the root's nearest edge to each agent's first item
74
+ // exit "leave" (default: out past the nearest edge) or "park": stay where
75
+ // the last item was left, until `out` (s) if given
76
+ // lift px the cursors float above the surface (translateZ): on a root
77
+ // tilted in perspective they move against it as the camera moves;
78
+ // sets transform-style: preserve-3d on the root, which must be the
79
+ // tilted element (or keep preserve-3d down to it)
80
+ // constantSize true: cursors, tags, handles and badges keep their size on screen
81
+ // when a camera scales the root (read each draw from the root's
82
+ // box on screen); false: they scale with the surface
83
+ // copies true: a short label repeated 3+ times (a status, a tag) is carried
84
+ // over from the nearest place it has already landed, when there is
85
+ // one by the time its agent comes to it; else it is typed
86
+ // guides true: a faint guide line drops from some boxes as they start
87
+ // font the tags' font
88
+ //
89
+ // In the root: data-swarm-skip (left alone, children too), data-swarm="media" (wiped in as one
90
+ // picture) or "box" (built as a card), data-swarm-agent="3", data-swarm-order="2" (an explicit
91
+ // order: items sort by it, then by reading order; the same number for a whole stage). What is
92
+ // found: text (typed), elements with a background, a shadow or two or more borders (boxes), a
93
+ // thin element or one with a single border (rules: drawn), img / svg / canvas / video / iframe /
94
+ // input (media: dragged, then wiped down). Nothing is hidden with display: text is split
95
+ // between the text node and an invisible twin (in a flex or grid parent, both in one inline
96
+ // wrapper), a box loses its paint with !important, media takes opacity and clip-path — the
97
+ // layout does not move. Transitions are held off on the items while they are being built.
98
+ //
99
+ // The layout is read once, on the first call, with the transforms of the root and everything
100
+ // above it set aside — so a root already under a camera or a tilt is read flat, in its own px.
101
+ // What changes layout after that (a font arriving late, text the film changes) is not followed:
102
+ // build after `await document.fonts.ready` and leave the built elements' layout alone. A root
103
+ // with overflow: hidden clips the cursors that enter from outside it.
104
+ //
105
+ // Nothing here blurs: the cursors are elements moved by transform, which `film render`
106
+ // measures like any other, so a fast flight is smeared by the master's shutter and a landing is
107
+ // sharp. A draft has no shutter — `film still --at` shows a frame as the master will.
108
+ //
109
+ // On lib/space.js: a slab is a live element, so swarm(slabEl) builds inside it and the stage
110
+ // redraws its texture as it changes — every frame while cursors move, which costs a slab's
111
+ // re-rasterising at its `scale` per frame; `lift` and `constantSize` do nothing there (the
112
+ // overlay is part of the picture on the slab). Not tried under a render.
113
+
114
+ import { clamp, ease, lerp, rng } from "./anim.js";
115
+
116
+ /** @typedef {[number, number]} Pt */
117
+ /** @typedef {{ x: number, y: number, w: number, h: number }} Rect */
118
+ /** @typedef {"text" | "box" | "rule" | "media" | "copy"} Kind */
119
+ /**
120
+ * One thing an agent builds, as the plan reads it (coordinates in the overlay's px).
121
+ * @typedef {object} PlanItem
122
+ * @property {Kind} kind
123
+ * @property {Rect} rect
124
+ * @property {Pt[]} [path] text: the caret before the first character and after each; rule: its two ends
125
+ * @property {Rect} [src] copy: where the original stands
126
+ * @property {number} [agent] the agent it is given to; none: the nearest free one
127
+ * @property {number} [order] sorts before reading order (default 0)
128
+ * @property {number} [after] an item that must land before this one starts
129
+ * @property {number} [copyOf] the item this one copies (lands first)
130
+ * @property {number} [group] text: one of a repeated label; copied from a landed one when there is one
131
+ * @property {number} [work] seconds of work at speed 1 (default from its kind and size)
132
+ */
133
+ /** @typedef {{ agent: number, from: number, to: number, color?: string, label?: string }} Hold */
134
+ /**
135
+ * @typedef {object} PlanOptions
136
+ * @property {number} [agents]
137
+ * @property {number} [seed]
138
+ * @property {number} [start]
139
+ * @property {number} [duration]
140
+ * @property {number} [speed]
141
+ * @property {Hold[]} [holds]
142
+ * @property {{ x: number, y: number }[]} [from] entry points, in the plan's px
143
+ * @property {"leave" | "park"} [exit]
144
+ * @property {number} [out] parked agents leave the picture at this time
145
+ * @property {Rect} [bounds] what "outside" means for entering and leaving (default: round the items)
146
+ * @property {number} [stagger] s between agents entering (0.07)
147
+ */
148
+ /** @typedef {"travel" | "wait" | "work" | "leave" | "park"} SegKind */
149
+ /** @typedef {{ kind: SegKind, t0: number, t1: number, dur: number, from: Pt, to: Pt, item: number, bow: number }} Seg */
150
+ /** @typedef {{ agent: number, arrive: number, start: number, end: number, work: number, set: number }} Slot */
151
+ /** @typedef {{ t: number, agent: number, kind: string, item: number }} PlanEvent */
152
+ /** @typedef {{ x: number, y: number, state: string, seg: SegKind, item: number, p: number, alpha: number, held: Hold | null }} AgentAt */
153
+
154
+ /** a[i], known to be there @template T @param {T[]} a @param {number} i @returns {T} */
155
+ const nth = (a, i) => /** @type {T} */ (a[i]);
156
+ const FADE = 0.22; // s a finished item's selection takes to fade
157
+ const VERB = /** @type {Record<Kind, string>} */ ({ text: "type", box: "box", rule: "line", media: "wipe", copy: "copy" });
158
+
159
+ /** seconds of work for an item at speed 1 @param {PlanItem} it */
160
+ export function workOf(it) {
161
+ if (it.work != null) return it.work;
162
+ const { w, h } = it.rect;
163
+ const size = clamp(Math.sqrt(Math.max(0, w * h)) / 400);
164
+ if (it.kind === "text") return clamp(0.25 + ((it.path?.length ?? 9) - 1) * 0.045, 0.35, 2);
165
+ if (it.kind === "rule") return 0.3 + 0.3 * clamp(Math.max(w, h) / 800);
166
+ if (it.kind === "media") return 0.7 + 0.5 * size;
167
+ if (it.kind === "copy") return 0.7;
168
+ return 0.45 + 0.35 * size;
169
+ }
170
+
171
+ /** seconds a cursor takes to cross `d` px at speed 1: short hops quick, long flights not much longer @param {number} d */
172
+ const travelOf = (d) => 0.25 + 0.55 * Math.sqrt(d / 1000);
173
+
174
+ const centre = (/** @type {Rect} */ r) => /** @type {Pt} */ ([r.x + r.w / 2, r.y + r.h / 2]);
175
+
176
+ /**
177
+ * Where the cursor is while an item is p (0..1) of the way built: a box's
178
+ * dragging corner, the caret of a text, a rule's tip, a copy in flight.
179
+ * @param {PlanItem} it @param {number} p @returns {Pt}
180
+ */
181
+ export function workPoint(it, p) {
182
+ const r = it.rect;
183
+ const u = clamp(p);
184
+ if (it.kind === "text") {
185
+ /** @type {Pt[]} */
186
+ const path = it.path?.length ? it.path : [[r.x, r.y + r.h / 2], [r.x + r.w, r.y + r.h / 2]];
187
+ const f = u * (path.length - 1);
188
+ const i = Math.floor(f);
189
+ const a = nth(path, i);
190
+ const b = path[Math.min(path.length - 1, i + 1)] ?? a;
191
+ return [lerp(a[0], b[0], f - i), lerp(a[1], b[1], f - i)];
192
+ }
193
+ if (it.kind === "rule") {
194
+ /** @type {Pt[]} */
195
+ const path = it.path ?? [[r.x, r.y], [r.x + r.w, r.y]];
196
+ const a = nth(path, 0);
197
+ const b = path[path.length - 1] ?? a;
198
+ const q = ease.inOut3(u);
199
+ return [lerp(a[0], b[0], q), lerp(a[1], b[1], q)];
200
+ }
201
+ if (it.kind === "copy") {
202
+ const from = centre(it.src ?? r);
203
+ const to = centre(r);
204
+ const q = ease.inOut3(clamp(u / 0.5));
205
+ return [lerp(from[0], to[0], q), lerp(from[1], to[1], q)];
206
+ }
207
+ const q = ease.out3(clamp(u / (it.kind === "media" ? 0.33 : 0.55)));
208
+ return [r.x + r.w * q, r.y + r.h * q];
209
+ }
210
+
211
+ /** the end of `dur` s of an agent's work begun at t, its holds skipped @param {Hold[]} hs @param {number} t @param {number} dur */
212
+ function advance(hs, t, dur) {
213
+ let at = t;
214
+ let left = dur;
215
+ for (const h of hs) {
216
+ if (h.to <= at) continue;
217
+ if (h.from >= at + left && !(left === 0 && h.from <= at)) break;
218
+ if (h.from > at) left -= h.from - at;
219
+ at = Math.max(at, h.to);
220
+ }
221
+ return at + left;
222
+ }
223
+
224
+ /** an agent's working time between t0 and t: the time its holds took left out @param {Hold[]} hs @param {number} t0 @param {number} t */
225
+ function workBetween(hs, t0, t) {
226
+ if (t <= t0) return 0;
227
+ let w = t - t0;
228
+ for (const h of hs) w -= Math.max(0, Math.min(t, h.to) - Math.max(t0, h.from));
229
+ return w;
230
+ }
231
+
232
+ /** the union of rects @param {Rect[]} rs @returns {Rect} */
233
+ function union(rs) {
234
+ if (!rs.length) return { x: 0, y: 0, w: 0, h: 0 };
235
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
236
+ for (const r of rs) {
237
+ x0 = Math.min(x0, r.x); y0 = Math.min(y0, r.y);
238
+ x1 = Math.max(x1, r.x + r.w); y1 = Math.max(y1, r.y + r.h);
239
+ }
240
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
241
+ }
242
+
243
+ /** the point just outside `b`'s edge nearest to p, `m` px out, slid along it by `slide` @param {Rect} b @param {Pt} p @param {number} m @param {number} slide @returns {Pt} */
244
+ function outside(b, p, m, slide) {
245
+ const d = [p[0] - b.x, b.x + b.w - p[0], p[1] - b.y, b.y + b.h - p[1]];
246
+ const k = d.indexOf(Math.min(...d));
247
+ if (k === 0) return [b.x - m, p[1] + slide];
248
+ if (k === 1) return [b.x + b.w + m, p[1] + slide];
249
+ if (k === 2) return [p[0] + slide, b.y - m];
250
+ return [p[0] + slide, b.y + b.h + m];
251
+ }
252
+
253
+ /**
254
+ * The schedule, with no page: which agent builds which item, when it arrives,
255
+ * starts and lands, where every cursor is at any t. Pure: the same items and
256
+ * options give the same plan.
257
+ * @param {PlanItem[]} items @param {PlanOptions} [o]
258
+ */
259
+ export function plan(items, o = {}) {
260
+ const n = Math.max(1, Math.round(o.agents ?? 8));
261
+ const start = o.start ?? 0;
262
+ /** @type {Hold[][]} */
263
+ const holdsOf = Array.from({ length: n }, () => []);
264
+ for (const h of o.holds ?? []) if (h.to > h.from) nth(holdsOf, ((h.agent % n) + n) % n).push(h);
265
+ for (const hs of holdsOf) hs.sort((a, b) => a.from - b.from);
266
+ let speed = o.speed ?? 1;
267
+ if (o.duration && o.duration > 0 && items.length) {
268
+ let lo = 0.01, hi = 100;
269
+ for (let k = 0; k < 48; k++) {
270
+ const mid = Math.sqrt(lo * hi);
271
+ if (simulate(items, o, n, start, mid, holdsOf).end - start > o.duration) lo = mid;
272
+ else hi = mid;
273
+ }
274
+ speed = hi;
275
+ }
276
+ const s = simulate(items, o, n, start, speed, holdsOf);
277
+ /** @type {PlanEvent[]} */
278
+ const events = [];
279
+ s.slots.forEach((sl, i) => {
280
+ const it = nth(s.items, i);
281
+ events.push({ t: sl.start, agent: sl.agent, kind: VERB[it.kind], item: i });
282
+ events.push({ t: sl.end, agent: sl.agent, kind: "done", item: i });
283
+ });
284
+ holdsOf.forEach((hs, a) => {
285
+ for (const h of hs) {
286
+ events.push({ t: h.from, agent: a, kind: "hold", item: -1 });
287
+ events.push({ t: h.to, agent: a, kind: "resume", item: -1 });
288
+ }
289
+ });
290
+ events.sort((a, b) => a.t - b.t || a.agent - b.agent || (a.kind === "done" ? -1 : 0) - (b.kind === "done" ? -1 : 0));
291
+
292
+ /** where agent a is at t, null when it is not in the picture @param {number} a @param {number} t @returns {AgentAt | null} */
293
+ const agentAt = (a, t) => {
294
+ const segs = nth(s.segs, a);
295
+ const hs = nth(holdsOf, a);
296
+ const first = segs[0];
297
+ const last = segs[segs.length - 1];
298
+ if (!first || !last || t < first.t0 || t >= last.t1) return null;
299
+ let k = 0;
300
+ while (k < segs.length - 1 && t >= nth(segs, k).t1) k++;
301
+ const sg = nth(segs, k);
302
+ const held = hs.find((h) => t >= h.from && t < h.to) ?? null;
303
+ let x = sg.to[0], y = sg.to[1], p = 0;
304
+ let state = sg.kind === "park" ? "park" : sg.kind === "wait" ? "wait" : sg.kind;
305
+ if (sg.kind === "travel" || sg.kind === "leave") {
306
+ const u = sg.dur > 0 ? clamp(workBetween(hs, sg.t0, t) / sg.dur) : 1;
307
+ const e = ease.inOut3(u);
308
+ const dx = sg.to[0] - sg.from[0], dy = sg.to[1] - sg.from[1];
309
+ const bend = sg.bow * Math.sin(Math.PI * e);
310
+ x = lerp(sg.from[0], sg.to[0], e) - dy * bend;
311
+ y = lerp(sg.from[1], sg.to[1], e) + dx * bend;
312
+ if (sg.kind === "travel" && k === 0) state = "enter";
313
+ } else if (sg.kind === "work") {
314
+ p = sg.dur > 0 ? clamp(workBetween(hs, sg.t0, t) / sg.dur) : 1;
315
+ [x, y] = workPoint(nth(s.items, sg.item), p);
316
+ state = VERB[nth(s.items, sg.item).kind];
317
+ }
318
+ if (held) state = "hold";
319
+ let alpha = clamp((t - first.t0) / 0.12);
320
+ if (last.kind === "leave") alpha *= clamp((last.t1 - t) / 0.15);
321
+ return { x, y, state, seg: sg.kind, item: sg.item, p, alpha, held };
322
+ };
323
+
324
+ /** an item at t: 0 not begun, 1 being built (p), 2 landed @param {number} i @param {number} t */
325
+ const itemAt = (i, t) => {
326
+ const sl = s.slots[i];
327
+ if (!sl) return { phase: 2, p: 1 };
328
+ if (t < sl.start) return { phase: 0, p: 0 };
329
+ if (t >= sl.end) return { phase: 2, p: 1 };
330
+ return { phase: 1, p: sl.work > 0 ? clamp(workBetween(nth(holdsOf, sl.agent), sl.start, t) / sl.work) : 1 };
331
+ };
332
+
333
+ return {
334
+ n, start, speed, end: s.end, gone: s.gone, slots: s.slots, segs: s.segs, holds: holdsOf, events, bounds: s.bounds, items: s.items,
335
+ agentAt, itemAt,
336
+ };
337
+ }
338
+
339
+ /**
340
+ * One run of the schedule at a speed.
341
+ * @param {PlanItem[]} items @param {PlanOptions} o @param {number} n @param {number} start @param {number} speed @param {Hold[][]} holdsOf
342
+ */
343
+ function simulate(items, o, n, start, speed, holdsOf) {
344
+ const r = rng((o.seed ?? 1) * 7919 + 17);
345
+ const bounds = o.bounds ?? union(items.map((it) => it.rect));
346
+ /** @type {PlanItem[]} */
347
+ const res = items.map((it) => ({ ...it }));
348
+ /** @type {(Slot | undefined)[]} */
349
+ const slots = items.map(() => undefined);
350
+ const rank = (/** @type {number} */ i) => nth(items, i).order ?? 0;
351
+ const before = (/** @type {number} */ i, /** @type {number} */ j) => rank(i) - rank(j) || i - j;
352
+ /** @type {number[][]} */
353
+ const queues = Array.from({ length: n }, () => []);
354
+ /** @type {number[]} */
355
+ let pool = [];
356
+ items.forEach((it, i) => {
357
+ if (it.agent != null && Number.isFinite(it.agent) && it.agent >= 0) nth(queues, Math.floor(it.agent) % n).push(i);
358
+ else pool.push(i);
359
+ });
360
+ for (const q of queues) q.sort(before);
361
+ pool.sort(before);
362
+ const deps = (/** @type {number} */ i) => {
363
+ const it = nth(items, i);
364
+ return [it.after, it.copyOf].filter((d) => d != null && d >= 0 && d < items.length && d !== i);
365
+ };
366
+ /** @type {Set<number>} */
367
+ const broken = new Set();
368
+ const ready = (/** @type {number} */ i) => broken.has(i) || deps(i).every((d) => slots[/** @type {number} */ (d)]);
369
+ const depEnd = (/** @type {number} */ i) =>
370
+ broken.has(i) ? -Infinity : Math.max(-Infinity, ...deps(i).map((d) => slots[/** @type {number} */ (d)]?.end ?? -Infinity));
371
+ const stagger = o.stagger ?? 0.07;
372
+ const agents = Array.from({ length: n }, (_, a) => {
373
+ const t = start + a * stagger + r() * 0.06;
374
+ const firstItem = nth(queues, a)[0] ?? pool[Math.min(pool.length - 1, a)];
375
+ const given = o.from?.length ? nth(o.from, a % o.from.length) : null;
376
+ /** @type {Pt} */
377
+ let pos;
378
+ if (given) pos = [given.x, given.y];
379
+ else if (firstItem != null) pos = outside(bounds, workPoint(nth(items, firstItem), 0), 70 + r() * 40, (r() - 0.5) * 80);
380
+ else pos = [bounds.x - 80, bounds.y + bounds.h * r()];
381
+ /** @type {Seg[]} */
382
+ const segs = [];
383
+ return { a, free: t, pos, segs, done: false, k: 0 };
384
+ });
385
+ const K = 6;
386
+ /** the nearest of the candidates, with a little chance in it @param {{ pos: Pt, free: number }} ag @param {number[]} cands */
387
+ const nearest = (ag, cands) => {
388
+ let best = nth(cands, 0), bestScore = Infinity;
389
+ for (const i of cands) {
390
+ const p = workPoint(nth(items, i), 0);
391
+ const d = Math.hypot(p[0] - ag.pos[0], p[1] - ag.pos[1]);
392
+ const late = Math.max(0, depEnd(i) - (ag.free + travelOf(d) / speed));
393
+ const score = d * (0.7 + 0.6 * r()) + late * 800;
394
+ if (score < bestScore) { bestScore = score; best = i; }
395
+ }
396
+ return best;
397
+ };
398
+ /** -2: nothing left for it, -1: nothing it can start yet @param {typeof agents[number]} ag */
399
+ const choose = (ag) => {
400
+ const head = nth(queues, ag.a)[0];
401
+ /** @type {number[]} */
402
+ const cands = [];
403
+ for (const i of pool) {
404
+ if (ready(i)) cands.push(i);
405
+ if (cands.length >= K) break;
406
+ }
407
+ if (head != null) {
408
+ const first = cands.filter((i) => before(i, head) < 0);
409
+ if (first.length) return nearest(ag, first);
410
+ if (ready(head)) return head;
411
+ return cands.length ? nearest(ag, cands) : -1;
412
+ }
413
+ if (cands.length) return nearest(ag, cands);
414
+ return pool.length ? -1 : -2;
415
+ };
416
+ /** @param {typeof agents[number]} ag @param {number} i */
417
+ const place = (ag, i) => {
418
+ const it = nth(res, i);
419
+ if (it.group != null && it.kind === "text") {
420
+ // a repeated label is copied from the nearest place it has already landed
421
+ let src = -1, best = Infinity;
422
+ slots.forEach((sl, j) => {
423
+ const other = nth(res, j);
424
+ if (!sl || other.group !== it.group || sl.end > ag.free) return;
425
+ const c = centre(other.rect);
426
+ const d = Math.hypot(c[0] - ag.pos[0], c[1] - ag.pos[1]);
427
+ if (d < best) { best = d; src = j; }
428
+ });
429
+ if (src >= 0) Object.assign(it, { kind: "copy", copyOf: src, src: nth(res, src).rect, group: undefined });
430
+ }
431
+ const hs = nth(holdsOf, ag.a);
432
+ const to = workPoint(it, 0);
433
+ const dur = travelOf(Math.hypot(to[0] - ag.pos[0], to[1] - ag.pos[1])) / speed;
434
+ const t1 = advance(hs, ag.free, dur);
435
+ const bow = (r() < 0.5 ? -1 : 1) * (0.05 + 0.1 * r());
436
+ ag.segs.push({ kind: "travel", t0: ag.free, t1, dur, from: ag.pos, to, item: i, bow });
437
+ const s0 = advance(hs, Math.max(t1, depEnd(i)), 0);
438
+ if (s0 > t1) ag.segs.push({ kind: "wait", t0: t1, t1: s0, dur: s0 - t1, from: to, to, item: i, bow: 0 });
439
+ const work = workOf(it) / speed;
440
+ const s1 = advance(hs, s0, work);
441
+ const end = workPoint(it, 1);
442
+ ag.segs.push({ kind: "work", t0: s0, t1: s1, dur: work, from: to, to: end, item: i, bow: 0 });
443
+ slots[i] = { agent: ag.a, arrive: t1, start: s0, end: s1, work, set: ag.k++ % 2 };
444
+ ag.free = s1;
445
+ ag.pos = end;
446
+ const q = nth(queues, ag.a);
447
+ if (q[0] === i) q.shift();
448
+ else pool = pool.filter((j) => j !== i);
449
+ };
450
+ let left = items.length;
451
+ while (left > 0) {
452
+ const order = agents.filter((ag) => !ag.done).sort((x, y) => x.free - y.free || x.a - y.a);
453
+ let took = false;
454
+ for (const ag of order) {
455
+ const pick = choose(ag);
456
+ if (pick === -2) { ag.done = true; continue; }
457
+ if (pick < 0) continue;
458
+ place(ag, pick);
459
+ left--;
460
+ took = true;
461
+ break;
462
+ }
463
+ if (took) continue;
464
+ // every agent is waiting on something no one has taken: let the first such item go without it
465
+ const stuck = items.findIndex((_, i) => !slots[i] && !ready(i));
466
+ if (stuck < 0) break;
467
+ broken.add(stuck);
468
+ }
469
+ let end = start;
470
+ for (const sl of slots) if (sl) end = Math.max(end, sl.end);
471
+ let gone = start;
472
+ for (const ag of agents) {
473
+ if (!ag.segs.length) continue;
474
+ const hs = nth(holdsOf, ag.a);
475
+ if (o.exit === "park") {
476
+ ag.segs.push({ kind: "park", t0: ag.free, t1: o.out ?? Infinity, dur: 0, from: ag.pos, to: ag.pos, item: -1, bow: 0 });
477
+ gone = Math.max(gone, o.out ?? Infinity);
478
+ continue;
479
+ }
480
+ const linger = advance(hs, ag.free, 0.12 / speed);
481
+ ag.segs.push({ kind: "wait", t0: ag.free, t1: linger, dur: linger - ag.free, from: ag.pos, to: ag.pos, item: -1, bow: 0 });
482
+ const to = outside(bounds, ag.pos, 90, (r() - 0.5) * 120);
483
+ const dur = travelOf(Math.hypot(to[0] - ag.pos[0], to[1] - ag.pos[1])) / speed;
484
+ const t1 = advance(hs, linger, dur);
485
+ ag.segs.push({ kind: "leave", t0: linger, t1, dur, from: ag.pos, to, item: -1, bow: (r() < 0.5 ? -1 : 1) * 0.08 });
486
+ gone = Math.max(gone, t1);
487
+ }
488
+ return { slots: slots.map((sl) => /** @type {Slot} */ (sl)), segs: agents.map((ag) => ag.segs), end, gone, bounds, items: res };
489
+ }
490
+
491
+ // --- on a page -------------------------------------------------------------------
492
+
493
+ const MEDIA = new Set(["IMG", "SVG", "CANVAS", "VIDEO", "PICTURE", "IFRAME", "INPUT", "TEXTAREA", "SELECT", "OBJECT", "EMBED"]);
494
+ const SKIP = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "HEAD", "META", "LINK", "BR", "WBR"]);
495
+
496
+ /** the colours, when none are given: hues spread round the wheel, light enough for a dark surface @param {number} n */
497
+ const hues = (n) => Array.from({ length: n }, (_, i) => `hsl(${Math.round((210 + (i * 360) / n) % 360)} 85% 70%)`);
498
+
499
+ /** dark ink on a light colour, white on a dark one @param {string} c */
500
+ export function inkOn(c) {
501
+ const s = c.trim().toLowerCase();
502
+ let l = 0.7;
503
+ const hex = s.match(/^#([0-9a-f]{3,8})$/);
504
+ const rgb = s.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/);
505
+ const hsl = s.match(/^hsla?\(\s*[\d.]+(?:deg)?[,\s]+[\d.]+%[,\s]+([\d.]+)%/);
506
+ /** @type {number[] | null} */
507
+ let v = null;
508
+ if (hex) {
509
+ const h = nth(hex, 1);
510
+ const full = h.length < 6 ? h.slice(0, 3).split("").map((x) => x + x).join("") : h.slice(0, 6);
511
+ v = [0, 2, 4].map((k) => Number.parseInt(full.slice(k, k + 2), 16));
512
+ } else if (rgb) v = [1, 2, 3].map((k) => Number(rgb[k]));
513
+ if (v) l = (0.2126 * nth(v, 0) + 0.7152 * nth(v, 1) + 0.0722 * nth(v, 2)) / 255;
514
+ else if (hsl) l = Number(hsl[1]) / 100;
515
+ return l > 0.55 ? "#111318" : "#ffffff";
516
+ }
517
+
518
+ let styled = false;
519
+ function styles() {
520
+ if (styled || typeof document === "undefined") return;
521
+ styled = true;
522
+ const k = "var(--swarm-k, 1)";
523
+ const css = document.createElement("style");
524
+ css.id = "swarm-css";
525
+ css.textContent = `
526
+ .swarm-nopaint { background: transparent !important; background-image: none !important; border-color: transparent !important; box-shadow: none !important; outline-color: transparent !important; }
527
+ .swarm-hide { opacity: 0 !important; }
528
+ .swarm-still, .swarm-still * { transition: none !important; }
529
+ swarm-ghost { opacity: 0; }
530
+ swarm-ghost, swarm-wrap { display: inline; }
531
+ .swarm-layer { position: absolute; width: 0; height: 0; overflow: visible; pointer-events: none; z-index: 2147483000; }
532
+ .swarm-layer * { box-sizing: border-box; }
533
+ .swarm-abs { position: absolute; left: 0; top: 0; transform-origin: 0 0; }
534
+ .swarm-sel { border: calc(1.5px * ${k}) solid var(--c); }
535
+ .swarm-hd { position: absolute; width: calc(7px * ${k}); height: calc(7px * ${k}); background: #fff; border: calc(1.5px * ${k}) solid var(--c); border-radius: 1px; }
536
+ .swarm-hd0 { left: calc(-4px * ${k}); top: calc(-4px * ${k}); } .swarm-hd1 { right: calc(-4px * ${k}); top: calc(-4px * ${k}); }
537
+ .swarm-hd2 { left: calc(-4px * ${k}); bottom: calc(-4px * ${k}); } .swarm-hd3 { right: calc(-4px * ${k}); bottom: calc(-4px * ${k}); }
538
+ .swarm-badge { position: absolute; left: 50%; top: calc(100% + 5px * ${k}); transform: translateX(-50%); padding: calc(3px * ${k}) calc(5px * ${k}); border-radius: calc(2px * ${k}); background: var(--c); color: var(--ink); font: 500 calc(10px * ${k})/1 ui-monospace, Menlo, Consolas, monospace; white-space: nowrap; }
539
+ .swarm-fill { background: color-mix(in srgb, var(--c) 24%, transparent); }
540
+ .swarm-line { height: calc(2px * ${k}); margin-top: calc(-1px * ${k}); background: var(--c); box-shadow: 0 0 calc(6px * ${k}) var(--c); }
541
+ .swarm-guide { width: calc(1px * ${k}); background: var(--c); }
542
+ .swarm-clone { white-space: pre; }
543
+ .swarm-agent { position: absolute; left: 0; top: 0; width: 0; height: 0; transform-origin: 0 0; will-change: transform; filter: drop-shadow(0 1px 2px rgba(0, 0, 0, .5)); }
544
+ .swarm-agent svg { position: absolute; display: none; overflow: visible; }
545
+ .swarm-agent[data-mode=arrow] .swarm-i-arrow, .swarm-agent[data-mode=text] .swarm-i-text, .swarm-agent[data-mode=cross] .swarm-i-cross, .swarm-agent[data-mode=pen] .swarm-i-pen { display: block; }
546
+ .swarm-tag { position: absolute; left: 13px; top: 19px; padding: 3px 7px 4px; border-radius: 6px; background: var(--c); color: var(--ink); white-space: nowrap; }
547
+ .swarm-ring { position: absolute; left: -14px; top: -14px; width: 28px; height: 28px; border-radius: 50%; border: 2px solid var(--c); display: none; }
548
+ `;
549
+ document.head.append(css);
550
+ }
551
+
552
+ const SVG = (/** @type {string} */ cls, /** @type {string} */ body) =>
553
+ `<svg class="${cls}" width="1" height="1" viewBox="0 0 1 1">${body}</svg>`;
554
+ const ICONS =
555
+ SVG("swarm-i-arrow", `<path d="M0 0 L0 17 L4.6 12.8 L7.6 19.4 L10.4 18.2 L7.5 11.7 L13.4 11.7 Z" fill="var(--c)" stroke="rgba(0,0,0,.6)" stroke-width="1.1" stroke-linejoin="round"/>`) +
556
+ SVG("swarm-i-text", `<path d="M-3.5 -9 H3.5 M0 -9 V9 M-3.5 9 H3.5" style="transform: scale(var(--ib, 1))" fill="none" stroke="var(--c)" stroke-width="1.8" stroke-linecap="round"/>`) +
557
+ SVG("swarm-i-cross", `<path d="M-9 0 H-3 M3 0 H9 M0 -9 V-3 M0 3 V9" fill="none" stroke="var(--c)" stroke-width="1.8" stroke-linecap="round"/>`) +
558
+ SVG("swarm-i-pen", `<path d="M0 0 L2.6 -8.4 L12.6 -18.4 L16.4 -14.6 L6.4 -4.6 Z" fill="var(--c)" stroke="rgba(0,0,0,.6)" stroke-width="1" stroke-linejoin="round"/>`);
559
+
560
+ /**
561
+ * The page's layout read with the transforms of `root` and everything above it
562
+ * set aside, so a root under a camera or a tilt is read in its own px.
563
+ * @template T @param {Element} root @param {() => T} fn @returns {T}
564
+ */
565
+ function flat(root, fn) {
566
+ /** @type {[HTMLElement, string, string, string][]} */
567
+ const saved = [];
568
+ for (let e = /** @type {Element | null} */ (root); e; e = e.parentElement) {
569
+ if (!(e instanceof HTMLElement)) continue;
570
+ const cs = getComputedStyle(e);
571
+ for (const p of ["transform", "translate", "scale", "rotate"]) {
572
+ if (cs.getPropertyValue(p) === "none" || cs.getPropertyValue(p) === "") continue;
573
+ saved.push([e, p, e.style.getPropertyValue(p), e.style.getPropertyPriority(p)]);
574
+ e.style.setProperty(p, "none", "important");
575
+ }
576
+ }
577
+ try {
578
+ return fn();
579
+ } finally {
580
+ for (const [e, p, v, pr] of saved.reverse()) {
581
+ if (v) e.style.setProperty(p, v, pr);
582
+ else e.style.removeProperty(p);
583
+ }
584
+ }
585
+ }
586
+
587
+ /** a colour that paints something @param {string} c */
588
+ const shows = (c) => !!c && c !== "transparent" && !/(?:,|\/)\s*0(?:\.0*)?\s*\)$/.test(c) && !/^rgba\(.*,\s*0\)$/.test(c);
589
+
590
+ /** the element's own paint: none, a box, or a rule along one edge @param {CSSStyleDeclaration} cs @param {DOMRect} r */
591
+ function paintOf(cs, r) {
592
+ const bg = shows(cs.backgroundColor) || cs.backgroundImage !== "none";
593
+ const sides = ["Top", "Right", "Bottom", "Left"].filter(
594
+ (s) => Number.parseFloat(cs.getPropertyValue(`border-${s.toLowerCase()}-width`)) > 0 &&
595
+ cs.getPropertyValue(`border-${s.toLowerCase()}-style`) !== "none" &&
596
+ shows(cs.getPropertyValue(`border-${s.toLowerCase()}-color`)),
597
+ );
598
+ const shadow = cs.boxShadow !== "none";
599
+ if (!bg && !sides.length && !shadow) return null;
600
+ if (r.height <= 4 || r.width <= 4) return { kind: /** @type {const} */ ("rule"), edge: r.height <= 4 ? "h" : "v" };
601
+ if (!bg && !shadow && sides.length === 1) return { kind: /** @type {const} */ ("rule"), edge: nth(sides, 0) };
602
+ return { kind: /** @type {const} */ ("box"), edge: "" };
603
+ }
604
+
605
+ /** @param {Element} el */
606
+ const isMedia = (el) => MEDIA.has(el.tagName.toUpperCase()) || el.getAttribute("data-swarm") === "media";
607
+
608
+ /** all of its content is inline text (no picture, no block) @param {Element} el @returns {boolean} */
609
+ function inlineOnly(el) {
610
+ for (const c of Array.from(el.children)) {
611
+ if (isMedia(c)) return false;
612
+ if (SKIP.has(c.tagName.toUpperCase())) continue;
613
+ const d = getComputedStyle(c).display;
614
+ if (d !== "inline" && d !== "contents") return false;
615
+ if (!inlineOnly(c)) return false;
616
+ }
617
+ return true;
618
+ }
619
+
620
+ /** @param {Node} el @param {boolean} deep @returns {Text[]} */
621
+ function textNodes(el, deep) {
622
+ /** @type {Text[]} */
623
+ const out = [];
624
+ for (const c of Array.from(el.childNodes)) {
625
+ if (c.nodeType === 3 && /** @type {Text} */ (c).data.trim()) out.push(/** @type {Text} */ (c));
626
+ else if (deep && c.nodeType === 1 && !SKIP.has(/** @type {Element} */ (c).tagName.toUpperCase())) out.push(...textNodes(c, true));
627
+ }
628
+ return out;
629
+ }
630
+
631
+ /**
632
+ * @typedef {object} Part one text node of a text item, split while it is typed
633
+ * @property {Text} node
634
+ * @property {string} text its data as the page had it
635
+ * @property {number[]} cuts cuts[m]: the length of text showing m characters
636
+ * @property {HTMLElement | null} ghost
637
+ * @property {HTMLElement | null} wrap
638
+ * @property {boolean} wraps its parent lays out flex or grid items
639
+ */
640
+ /**
641
+ * @typedef {object} DomItem
642
+ * @property {Element} el
643
+ * @property {Kind} kind
644
+ * @property {Part[]} parts
645
+ * @property {number} chars
646
+ * @property {string} clip media: its own inline clip-path
647
+ * @property {string} key what was last written
648
+ * @property {string} text
649
+ * @property {Record<string, string>} font copy: the original's type, for the copy in flight
650
+ */
651
+
652
+ /** the characters a reader sees in s, as cut points (a run of spaces is one) @param {string} s @param {boolean} pre */
653
+ function cutsOf(s, pre) {
654
+ const cuts = [0];
655
+ /** @type {number[]} */
656
+ const at = [];
657
+ for (let i = 0; i < s.length; i++) {
658
+ const ws = /\s/.test(s.charAt(i));
659
+ if (!pre && ws && i > 0 && /\s/.test(s.charAt(i - 1))) continue;
660
+ at.push(i);
661
+ cuts.push(i + 1);
662
+ }
663
+ cuts[cuts.length - 1] = s.length;
664
+ return { cuts, at };
665
+ }
666
+
667
+ /** the client rect of a range, or null @param {Range} rg */
668
+ const lastRect = (rg) => {
669
+ const rs = rg.getClientRects();
670
+ const r = rs[rs.length - 1];
671
+ return r && (r.width > 0 || r.height > 0) ? r : null;
672
+ };
673
+
674
+ /**
675
+ * Builds the overlay and the plan for a set of items on a page; `write(t)`
676
+ * puts the page's own side (what is hidden or shown) for each draw.
677
+ * @param {HTMLElement} root @param {object} o
678
+ * @param {(layer: HTMLElement, origin: Pt) => { items: PlanItem[], els: (Element | null)[], fonts: (Record<string, string> | null)[], write: (P: ReturnType<typeof plan>, t: number) => void }} scan
679
+ */
680
+ function mount(root, o, scan) {
681
+ const opt = /** @type {any} */ (o);
682
+ styles();
683
+ const layer = document.createElement("div");
684
+ layer.className = "swarm-layer";
685
+ layer.setAttribute("aria-hidden", "true");
686
+ root.append(layer);
687
+ const rcs = getComputedStyle(root);
688
+ if (rcs.position !== "static" || rcs.transform !== "none") { layer.style.left = "0"; layer.style.top = "0"; }
689
+ if (opt.lift) {
690
+ layer.style.transform = `translateZ(${opt.lift}px)`;
691
+ root.style.transformStyle = "preserve-3d";
692
+ }
693
+ const read = flat(root, () => {
694
+ const lr = layer.getBoundingClientRect();
695
+ const rr = root.getBoundingClientRect();
696
+ /** @type {Pt} */
697
+ const origin = [lr.left, lr.top];
698
+ const found = scan(layer, origin);
699
+ /** @type {Pt} */
700
+ const offset = [lr.left - rr.left, lr.top - rr.top];
701
+ return { ...found, offset, rootRect: { x: rr.left - lr.left, y: rr.top - lr.top, w: rr.width, h: rr.height } };
702
+ });
703
+ const { items, els, fonts, write, offset, rootRect } = read;
704
+ const n = Math.max(1, Math.round(opt.agents ?? 8));
705
+ const P = plan(items, {
706
+ agents: n, seed: opt.seed, start: opt.start, duration: opt.duration, speed: opt.speed, holds: opt.holds,
707
+ exit: opt.exit, out: opt.out, stagger: opt.stagger, bounds: rootRect,
708
+ from: opt.from?.map((/** @type {{ x: number, y: number }} */ p) => ({ x: p.x - offset[0], y: p.y - offset[1] })),
709
+ });
710
+ /** @type {string[]} */
711
+ const colors = opt.colors?.length ? opt.colors : hues(n);
712
+ const colorOf = (/** @type {number} */ a) => nth(colors, a % colors.length);
713
+ /** @type {(string | undefined)[]} */
714
+ const labels = opt.labels ?? [];
715
+ const font = opt.font ?? `600 12px/1.2 ui-sans-serif, system-ui, -apple-system, "PingFang TC", "Noto Sans TC", "Segoe UI", sans-serif`;
716
+ const guides = opt.guides !== false;
717
+ const constant = opt.constantSize !== false;
718
+ const seed = opt.seed ?? 1;
719
+ const guided = (/** @type {number} */ i) => {
720
+ const s = Math.sin((i + 1) * 12.9898 + seed * 78.233) * 43758.5453;
721
+ return s - Math.floor(s) < 0.3;
722
+ };
723
+
724
+ const mk = (/** @type {string} */ cls, /** @type {HTMLElement} */ parent, /** @type {string} */ tag = "div") => {
725
+ const e = document.createElement(tag);
726
+ e.className = cls;
727
+ parent.append(e);
728
+ return e;
729
+ };
730
+ const sets = Array.from({ length: n }, (_, a) =>
731
+ [0, 1].map(() => {
732
+ const guide = mk("swarm-abs swarm-guide", layer);
733
+ const fill = mk("swarm-abs swarm-fill", layer);
734
+ const line = mk("swarm-abs swarm-line", layer);
735
+ const clone = mk("swarm-abs swarm-clone", layer);
736
+ const sel = mk("swarm-abs swarm-sel", layer);
737
+ for (let h = 0; h < 4; h++) mk(`swarm-hd swarm-hd${h}`, sel);
738
+ const badge = mk("swarm-badge", sel);
739
+ for (const e of [guide, fill, line, clone, sel]) e.style.display = "none";
740
+ return { guide, fill, line, clone, sel, badge, a, cloneOf: -1 };
741
+ }),
742
+ );
743
+ const cursors = Array.from({ length: n }, (_, a) => {
744
+ const el = mk("swarm-agent", layer);
745
+ el.innerHTML = ICONS;
746
+ const ring = mk("swarm-ring", el);
747
+ const tag = mk("swarm-tag", el, "span");
748
+ tag.style.font = font;
749
+ el.style.display = "none";
750
+ el.dataset.mode = "arrow";
751
+ return { el, ring, tag, a };
752
+ });
753
+ layer.style.display = "none";
754
+
755
+ /** @param {HTMLElement} e @param {boolean} on */
756
+ const show = (e, on) => { const v = on ? "" : "none"; if (e.style.display !== v) e.style.display = v; };
757
+ /** @param {HTMLElement} e @param {string} c */
758
+ const paint = (e, c) => { if (e.style.getPropertyValue("--c") !== c) { e.style.setProperty("--c", c); e.style.setProperty("--ink", inkOn(c)); } };
759
+ /** @param {HTMLElement} e @param {Rect} r */
760
+ const place = (e, r) => {
761
+ e.style.transform = `translate(${r.x.toFixed(2)}px, ${r.y.toFixed(2)}px)`;
762
+ e.style.width = `${Math.max(0, r.w).toFixed(2)}px`;
763
+ e.style.height = `${Math.max(0, r.h).toFixed(2)}px`;
764
+ };
765
+
766
+ /** one agent's selection, fill, line, guide and copy for item i at progress p @param {typeof sets[number][number]} s @param {number} i @param {number} p @param {number} since @param {number} alpha @param {string} c @param {number} k */
767
+ const chrome = (s, i, p, since, alpha, c, k) => {
768
+ const it = nth(P.items, i);
769
+ const r = it.rect;
770
+ for (const e of [s.sel, s.fill, s.line, s.guide, s.clone]) paint(e, c);
771
+ let sel = /** @type {Rect | null} */ (null), fill = /** @type {Rect | null} */ (null), fillAlpha = 1, wipe = 0;
772
+ if (it.kind === "box" || it.kind === "media") {
773
+ const q = ease.out3(clamp(p / (it.kind === "media" ? 0.33 : 0.55)));
774
+ sel = fill = { x: r.x, y: r.y, w: r.w * q, h: r.h * q };
775
+ if (it.kind === "box") fillAlpha = p < 0.55 ? 1 : 1 - (p - 0.55) / 0.45;
776
+ else wipe = p > 0.33 ? ease.inOut3((p - 0.33) / 0.67) : 0;
777
+ } else if (it.kind === "text") {
778
+ sel = { x: r.x - 2, y: r.y - 2, w: r.w + 4, h: r.h + 4 };
779
+ } else if (it.kind === "copy") {
780
+ const src = it.src ?? r;
781
+ const q = ease.inOut3(clamp(p / 0.5));
782
+ const x = lerp(src.x, r.x, q), y = lerp(src.y, r.y, q);
783
+ sel = { x: x - 2, y: y - 2, w: lerp(src.w, r.w, q) + 4, h: lerp(src.h, r.h, q) + 4 };
784
+ const flying = p < 0.5;
785
+ show(s.clone, flying && alpha > 0);
786
+ if (flying) {
787
+ if (s.cloneOf !== i) {
788
+ s.cloneOf = i;
789
+ const el = els[it.copyOf ?? -1] ?? els[i];
790
+ s.clone.textContent = el?.textContent?.trim() ?? "";
791
+ Object.assign(s.clone.style, fonts[i] ?? {});
792
+ }
793
+ s.clone.style.transform = `translate(${x.toFixed(2)}px, ${y.toFixed(2)}px)`;
794
+ s.clone.style.opacity = String(alpha);
795
+ }
796
+ }
797
+ if (it.kind !== "copy") show(s.clone, false);
798
+ show(s.sel, !!sel && alpha > 0);
799
+ if (sel) {
800
+ place(s.sel, sel);
801
+ s.sel.style.opacity = String(alpha);
802
+ const sized = it.kind === "box" || it.kind === "media";
803
+ show(s.badge, sized);
804
+ const txt = sized ? `${Math.round(sel.w)} × ${Math.round(sel.h)}` : "";
805
+ if (s.badge.textContent !== txt) s.badge.textContent = txt;
806
+ }
807
+ show(s.fill, !!fill && alpha * fillAlpha > 0);
808
+ if (fill) {
809
+ place(s.fill, fill);
810
+ s.fill.style.opacity = String(alpha * clamp(fillAlpha));
811
+ s.fill.style.clipPath = wipe > 0 ? `inset(${(wipe * 100).toFixed(2)}% 0 0 0)` : "";
812
+ }
813
+ const isRule = it.kind === "rule";
814
+ show(s.line, isRule && alpha > 0);
815
+ if (isRule) {
816
+ const a = nth(/** @type {Pt[]} */ (it.path ?? [[r.x, r.y]]), 0);
817
+ const tip = workPoint(it, p);
818
+ const len = Math.hypot(tip[0] - a[0], tip[1] - a[1]);
819
+ s.line.style.transform = `translate(${a[0].toFixed(2)}px, ${a[1].toFixed(2)}px) rotate(${Math.atan2(tip[1] - a[1], tip[0] - a[0])}rad)`;
820
+ s.line.style.width = `${len.toFixed(2)}px`;
821
+ s.line.style.opacity = String(alpha);
822
+ }
823
+ const g = guides && (it.kind === "box" || it.kind === "media") && guided(i) && since < 0.45;
824
+ show(s.guide, g && alpha > 0);
825
+ if (g) {
826
+ const b = P.bounds;
827
+ s.guide.style.transform = `translate(${(r.x - 0.5 * k).toFixed(2)}px, ${b.y.toFixed(2)}px)`;
828
+ s.guide.style.height = `${b.h.toFixed(2)}px`;
829
+ s.guide.style.opacity = String(0.55 * alpha * (1 - since / 0.45));
830
+ }
831
+ };
832
+
833
+ /** the root's scale on screen, read from its box @returns {number} */
834
+ const screenScale = () => {
835
+ const w = root.offsetWidth;
836
+ if (!w) return 1;
837
+ const s = root.getBoundingClientRect().width / w;
838
+ return s > 0.01 ? s : 1;
839
+ };
840
+
841
+ /** @param {number} t */
842
+ const draw = (t) => {
843
+ const live = t >= P.start && t < P.gone;
844
+ const k = live && constant ? 1 / screenScale() : 1;
845
+ write(P, t);
846
+ show(layer, live);
847
+ if (!live) return;
848
+ layer.style.setProperty("--swarm-k", k.toFixed(4));
849
+ for (let a = 0; a < n; a++) {
850
+ const cur = nth(cursors, a);
851
+ const at = P.agentAt(a, t);
852
+ show(cur.el, !!at);
853
+ const segs = nth(P.segs, a);
854
+ /** @type {Seg[]} */
855
+ const shown = [];
856
+ for (const sg of segs) {
857
+ if (sg.kind !== "work") continue;
858
+ if (t >= sg.t0 && t < sg.t1) shown.push(sg);
859
+ else if (t >= sg.t1 && t < sg.t1 + FADE) shown.push(sg);
860
+ }
861
+ const used = new Set();
862
+ const held = at?.held ?? null;
863
+ const c = held ? (held.color ?? "#fbbf24") : colorOf(a);
864
+ for (const sg of shown) {
865
+ const sl = nth(P.slots, sg.item);
866
+ const s = nth(nth(sets, a), sl.set);
867
+ used.add(s);
868
+ const st = P.itemAt(sg.item, t);
869
+ const alpha = st.phase === 2 ? clamp(1 - (t - sl.end) / FADE) : 1;
870
+ chrome(s, sg.item, st.p, t - sl.start, alpha, c, k);
871
+ }
872
+ for (const s of nth(sets, a)) if (!used.has(s)) for (const e of [s.sel, s.fill, s.line, s.guide, s.clone]) show(e, false);
873
+ if (!at) continue;
874
+ cur.el.style.transform = `translate(${at.x.toFixed(2)}px, ${at.y.toFixed(2)}px) scale(${k.toFixed(4)})`;
875
+ cur.el.style.opacity = String(at.alpha);
876
+ const kind = at.seg === "work" && at.item >= 0 ? nth(P.items, at.item).kind : null;
877
+ const mode = kind === "text" ? "text" : kind === "rule" ? "pen" : kind === "box" || kind === "media" ? "cross" : "arrow";
878
+ if (cur.el.dataset.mode !== mode) cur.el.dataset.mode = mode;
879
+ if (mode === "text") cur.el.style.setProperty("--ib", clamp(lineH(nth(P.items, at.item)) / 18, 0.6, 3).toFixed(3));
880
+ paint(cur.el, c);
881
+ const label = held ? (held.label ?? labels[a]) : labels[a];
882
+ show(cur.tag, !!label);
883
+ if (label && cur.tag.textContent !== label) cur.tag.textContent = label;
884
+ show(cur.ring, !!held);
885
+ if (held) {
886
+ const ph = (((t - held.from) % 1.1) + 1.1) % 1.1 / 1.1;
887
+ cur.ring.style.transform = `scale(${(0.5 + 1.1 * ph).toFixed(3)})`;
888
+ cur.ring.style.opacity = String((1 - ph).toFixed(3));
889
+ }
890
+ }
891
+ };
892
+
893
+ /** in root px @param {number} t */
894
+ const agentsAt = (t) =>
895
+ Array.from({ length: n }, (_, a) => {
896
+ const at = P.agentAt(a, t);
897
+ const held = at?.held ?? null;
898
+ return {
899
+ x: (at?.x ?? 0) + offset[0], y: (at?.y ?? 0) + offset[1], visible: !!at,
900
+ label: held ? (held.label ?? labels[a] ?? "") : (labels[a] ?? ""),
901
+ color: held ? (held.color ?? "#fbbf24") : colorOf(a),
902
+ state: at ? at.state : t < P.start ? "waiting" : "gone",
903
+ };
904
+ });
905
+
906
+ return {
907
+ el: layer,
908
+ draw,
909
+ agentsAt,
910
+ end: P.end,
911
+ events: P.events.map((e) => ({ ...e, el: e.item >= 0 ? (els[e.item] ?? null) : null })),
912
+ items: P.slots.map((sl, i) => {
913
+ const r = nth(P.items, i).rect;
914
+ return { el: els[i] ?? null, kind: nth(P.items, i).kind, agent: sl.agent, arrive: sl.arrive, start: sl.start, end: sl.end, rect: { x: r.x + offset[0], y: r.y + offset[1], w: r.w, h: r.h } };
915
+ }),
916
+ plan: P,
917
+ };
918
+ }
919
+
920
+ /** a text item's line height, from its caret path's first character @param {PlanItem} it */
921
+ function lineH(it) {
922
+ return /** @type {any} */ (it).lineH ?? 18;
923
+ }
924
+
925
+ /**
926
+ * @typedef {object} SwarmOptions
927
+ * @property {number} [agents]
928
+ * @property {number} [seed]
929
+ * @property {number} [start]
930
+ * @property {number} [duration]
931
+ * @property {number} [speed]
932
+ * @property {string[]} [labels]
933
+ * @property {string[]} [colors]
934
+ * @property {"nearest" | ((item: { el: Element | null, kind: Kind, rect: Rect, text: string }, i: number) => number | null | undefined)} [assign]
935
+ * @property {Hold[]} [holds]
936
+ * @property {{ x: number, y: number }[]} [from]
937
+ * @property {"leave" | "park"} [exit]
938
+ * @property {number} [out]
939
+ * @property {number} [lift]
940
+ * @property {boolean} [constantSize]
941
+ * @property {boolean} [copies]
942
+ * @property {boolean} [guides]
943
+ * @property {string} [font]
944
+ * @property {number} [stagger]
945
+ */
946
+ /**
947
+ * @typedef {object} Swarm
948
+ * @property {HTMLElement | null} el
949
+ * @property {(t: number) => void} draw
950
+ * @property {number} end
951
+ * @property {{ t: number, agent: number, kind: string, item: number, el: Element | null }[]} events
952
+ * @property {{ el: Element | null, kind: Kind, agent: number, arrive: number, start: number, end: number, rect: Rect }[]} items
953
+ * @property {(t: number) => { x: number, y: number, visible: boolean, label: string, color: string, state: string }[]} agentsAt
954
+ */
955
+
956
+ /** built on first use: `end`, `events` and the rest read the page's layout @param {() => any} make @returns {Swarm} */
957
+ function lazy(make) {
958
+ /** @type {any} */
959
+ let b = null;
960
+ const get = () => (b ??= make());
961
+ return {
962
+ get el() { return get().el; },
963
+ draw: (t) => get().draw(t),
964
+ get end() { return get().end; },
965
+ get events() { return get().events; },
966
+ get items() { return get().items; },
967
+ agentsAt: (t) => get().agentsAt(t),
968
+ };
969
+ }
970
+
971
+ /**
972
+ * A team of agent cursors builds what is inside `root`. Built on first use
973
+ * (draw, end, events): read them after `await document.fonts.ready`.
974
+ * @param {HTMLElement} root @param {SwarmOptions} [o] @returns {Swarm}
975
+ */
976
+ export function swarm(root, o = {}) {
977
+ return lazy(() =>
978
+ mount(root, o, (layer, origin) => {
979
+ const rel = (/** @type {DOMRect} */ r) => ({ x: r.left - origin[0], y: r.top - origin[1], w: r.width, h: r.height });
980
+ /** @type {PlanItem[]} */
981
+ const items = [];
982
+ /** @type {DomItem[]} */
983
+ const dom = [];
984
+ /** @type {Map<Element, number>} */
985
+ const boxOf = new Map();
986
+ /** @param {Element} el */
987
+ const fixedAgent = (el) => {
988
+ const host = el.closest("[data-swarm-agent]");
989
+ return host && root.contains(host) ? Number(host.getAttribute("data-swarm-agent")) : undefined;
990
+ };
991
+ /** @param {Element} el */
992
+ const orderOf = (el) => {
993
+ const host = el.closest("[data-swarm-order]");
994
+ return host && root.contains(host) ? Number(host.getAttribute("data-swarm-order")) : undefined;
995
+ };
996
+ /** @param {DomItem} d @param {PlanItem} p */
997
+ const add = (d, p) => {
998
+ const a = fixedAgent(d.el);
999
+ if (a != null && Number.isFinite(a)) p.agent = a;
1000
+ const ord = orderOf(d.el);
1001
+ if (ord != null && Number.isFinite(ord)) p.order = ord;
1002
+ items.push(p);
1003
+ dom.push(d);
1004
+ return items.length - 1;
1005
+ };
1006
+ /** @param {Element} el */
1007
+ const visit = (el) => {
1008
+ if (el === layer || el.hasAttribute("data-swarm-skip") || SKIP.has(el.tagName.toUpperCase())) return;
1009
+ const cs = getComputedStyle(el);
1010
+ if (cs.display === "none" || cs.visibility === "hidden" || cs.visibility === "collapse") return;
1011
+ if (el !== root && Number.parseFloat(cs.opacity) === 0) return;
1012
+ const br = el.getBoundingClientRect();
1013
+ const base = { el, parts: [], chars: 0, clip: "", key: "", text: "", font: {} };
1014
+ if (el !== root && isMedia(el)) {
1015
+ if (br.width > 1 && br.height > 1) {
1016
+ const clip = el instanceof HTMLElement || el instanceof SVGElement ? el.style.clipPath : "";
1017
+ add({ ...base, kind: "media", clip }, { kind: "media", rect: rel(br) });
1018
+ }
1019
+ return;
1020
+ }
1021
+ if (el !== root) {
1022
+ const forced = el.getAttribute("data-swarm") === "box";
1023
+ const pt = forced ? { kind: /** @type {const} */ ("box"), edge: "" } : paintOf(cs, br);
1024
+ if (pt && br.width > 0 && br.height > 0) {
1025
+ const r = rel(br);
1026
+ /** @type {Pt[] | undefined} */
1027
+ let path;
1028
+ if (pt.kind === "rule") {
1029
+ const e = pt.edge;
1030
+ if (e === "Top" || e === "h") path = [[r.x, e === "h" ? r.y + r.h / 2 : r.y + 0.5], [r.x + r.w, e === "h" ? r.y + r.h / 2 : r.y + 0.5]];
1031
+ else if (e === "Bottom") path = [[r.x, r.y + r.h - 0.5], [r.x + r.w, r.y + r.h - 0.5]];
1032
+ else if (e === "Left" || e === "v") path = [[e === "v" ? r.x + r.w / 2 : r.x + 0.5, r.y], [e === "v" ? r.x + r.w / 2 : r.x + 0.5, r.y + r.h]];
1033
+ else path = [[r.x + r.w - 0.5, r.y], [r.x + r.w - 0.5, r.y + r.h]];
1034
+ }
1035
+ boxOf.set(el, add({ ...base, kind: pt.kind }, { kind: pt.kind, rect: r, path }));
1036
+ }
1037
+ }
1038
+ const leaf = inlineOnly(el);
1039
+ const nodes = textNodes(el, leaf);
1040
+ if (nodes.length) {
1041
+ const pre = cs.whiteSpace.startsWith("pre") || cs.whiteSpace === "break-spaces";
1042
+ /** @type {Part[]} */
1043
+ const parts = [];
1044
+ /** @type {Pt[]} */
1045
+ const path = [];
1046
+ /** @type {Rect[]} */
1047
+ const rects = [];
1048
+ /** @type {number[]} */
1049
+ const heights = [];
1050
+ const rg = document.createRange();
1051
+ for (const node of nodes) {
1052
+ const { cuts, at } = cutsOf(node.data, pre);
1053
+ const parent = node.parentElement;
1054
+ const wraps = !!parent && /flex|grid/.test(getComputedStyle(parent).display);
1055
+ parts.push({ node, text: node.data, cuts, ghost: null, wrap: null, wraps });
1056
+ rg.selectNodeContents(node);
1057
+ for (const r of Array.from(rg.getClientRects())) if (r.width > 0 && r.height > 0) rects.push(rel(r));
1058
+ for (const i of at) {
1059
+ rg.setStart(node, i);
1060
+ rg.setEnd(node, i + 1);
1061
+ const r = lastRect(rg);
1062
+ if (!r) {
1063
+ if (path.length) path.push(/** @type {Pt} */ (path[path.length - 1]));
1064
+ continue;
1065
+ }
1066
+ const q = rel(r);
1067
+ if (!path.length) path.push([q.x, q.y + q.h / 2]);
1068
+ path.push([q.x + q.w, q.y + q.h / 2]);
1069
+ heights.push(q.h);
1070
+ }
1071
+ }
1072
+ rg.detach();
1073
+ if (rects.length && path.length > 1) {
1074
+ const text = nodes.map((x) => x.data).join("").replace(/\s+/g, " ").trim();
1075
+ const chars = parts.reduce((s, p) => s + p.cuts.length - 1, 0);
1076
+ while (path.length < chars + 1) path.push(/** @type {Pt} */ (path[path.length - 1]));
1077
+ const pi = /** @type {PlanItem & { lineH?: number }} */ ({ kind: "text", rect: union(rects), path: path.slice(0, chars + 1), lineH: heights.sort((a, b) => a - b)[heights.length >> 1] ?? 18 });
1078
+ const box = boxOf.get(el);
1079
+ if (box != null) pi.after = box;
1080
+ const fcs = cs;
1081
+ add({ ...base, kind: "text", parts, chars, text, font: { font: fcs.font, letterSpacing: fcs.letterSpacing, color: fcs.color, textTransform: fcs.textTransform } }, pi);
1082
+ }
1083
+ }
1084
+ if (!leaf) for (const c of Array.from(el.children)) visit(c);
1085
+ };
1086
+ visit(root);
1087
+
1088
+ // a short label repeated three times or more is copied from its first place
1089
+ if (o.copies !== false) {
1090
+ /** @type {Map<string, number[]>} */
1091
+ const groups = new Map();
1092
+ dom.forEach((d, i) => {
1093
+ if (d.kind !== "text" || d.text.length > 28 || d.el.children.length) return;
1094
+ const key = `${d.el.tagName}|${d.el.getAttribute("class") ?? ""}|${d.text}`;
1095
+ groups.set(key, [...(groups.get(key) ?? []), i]);
1096
+ });
1097
+ let id = 0;
1098
+ for (const g of groups.values()) {
1099
+ if (g.length < 3) continue;
1100
+ for (const i of g) nth(items, i).group = id;
1101
+ id++;
1102
+ }
1103
+ }
1104
+ if (typeof o.assign === "function") {
1105
+ const fn = o.assign;
1106
+ items.forEach((it, i) => {
1107
+ if (it.agent != null) return;
1108
+ const d = nth(dom, i);
1109
+ const a = fn({ el: d.el, kind: it.kind, rect: it.rect, text: d.text }, i);
1110
+ if (a != null && Number.isFinite(a) && a >= 0) it.agent = a;
1111
+ });
1112
+ }
1113
+
1114
+ /** the page's side at t @param {ReturnType<typeof plan>} P @param {number} t */
1115
+ const write = (P, t) => {
1116
+ const before = t < P.start;
1117
+ dom.forEach((d, i) => {
1118
+ const sl = P.slots[i];
1119
+ const st = before ? { phase: 0, p: 0 } : P.itemAt(i, t);
1120
+ const still = !sl || t < sl.end + 0.5;
1121
+ const copy = P.items[i]?.kind === "copy";
1122
+ let key = "";
1123
+ if (d.kind === "text") {
1124
+ const k = st.phase === 2 ? -1 : copy ? (st.p >= 0.5 ? d.chars : 0) : Math.floor(st.p * d.chars + 1e-9);
1125
+ key = `t${k}`;
1126
+ if (key !== d.key) typeText(d, k);
1127
+ } else if (d.kind === "box" || d.kind === "rule") {
1128
+ const on = st.phase === 2 || (d.kind === "box" && st.phase === 1 && st.p >= 0.55);
1129
+ key = on ? "on" : "off";
1130
+ if (key !== d.key) d.el.classList.toggle("swarm-nopaint", !on);
1131
+ } else {
1132
+ const q = st.phase === 2 ? 1 : st.phase === 1 && st.p >= 0.33 ? ease.inOut3((st.p - 0.33) / 0.67) : 0;
1133
+ key = st.phase === 2 ? "done" : `m${q.toFixed(4)}`;
1134
+ if (key !== d.key) {
1135
+ const e = /** @type {HTMLElement} */ (d.el);
1136
+ e.classList.toggle("swarm-hide", q === 0 && st.phase !== 2);
1137
+ e.style.clipPath = st.phase === 2 ? d.clip : q > 0 ? `inset(0 0 ${((1 - q) * 100).toFixed(3)}% 0)` : d.clip;
1138
+ }
1139
+ }
1140
+ key += still ? "s" : "";
1141
+ if (key !== d.key) {
1142
+ d.el.classList.toggle("swarm-still", still);
1143
+ d.key = key;
1144
+ }
1145
+ });
1146
+ };
1147
+ return { items, els: dom.map((d) => d.el), fonts: dom.map((d) => (d.kind === "text" ? d.font : null)), write };
1148
+ }),
1149
+ );
1150
+ }
1151
+
1152
+ /** a text item showing k characters (-1: as the page had it, the split undone) @param {DomItem} d @param {number} k */
1153
+ function typeText(d, k) {
1154
+ let left = k;
1155
+ for (const p of d.parts) {
1156
+ if (k < 0) {
1157
+ if (!p.ghost) continue;
1158
+ p.node.data = p.text;
1159
+ p.ghost.remove();
1160
+ p.ghost = null;
1161
+ if (p.wrap) {
1162
+ p.wrap.parentNode?.insertBefore(p.node, p.wrap);
1163
+ p.wrap.remove();
1164
+ p.wrap = null;
1165
+ }
1166
+ continue;
1167
+ }
1168
+ if (!p.ghost) {
1169
+ const parent = p.node.parentNode;
1170
+ if (!parent) continue;
1171
+ if (p.wraps) {
1172
+ p.wrap = document.createElement("swarm-wrap");
1173
+ parent.insertBefore(p.wrap, p.node);
1174
+ p.wrap.append(p.node);
1175
+ }
1176
+ p.ghost = document.createElement("swarm-ghost");
1177
+ p.ghost.append(document.createTextNode(""));
1178
+ p.node.parentNode?.insertBefore(p.ghost, p.node.nextSibling);
1179
+ }
1180
+ const m = Math.min(p.cuts.length - 1, Math.max(0, left));
1181
+ left -= m;
1182
+ const cut = nth(p.cuts, m);
1183
+ p.node.data = p.text.slice(0, cut);
1184
+ const g = /** @type {Text} */ (p.ghost.firstChild);
1185
+ g.data = p.text.slice(cut);
1186
+ }
1187
+ }
1188
+
1189
+ /**
1190
+ * The colour round a rect of a picture (the median of a ring just outside
1191
+ * it), for the patch that hides what is printed there; `fallback` when the
1192
+ * picture cannot be read (another origin).
1193
+ * @param {HTMLElement} el @param {Rect} px where the picture is laid out @param {string} fallback
1194
+ * @returns {(r: Rect) => string} r in the picture's laid-out px
1195
+ */
1196
+ function sampler(el, px, fallback) {
1197
+ const m = /** @type {any} */ (el);
1198
+ const w = Math.round(m.naturalWidth || m.videoWidth || m.width || px.w);
1199
+ const h = Math.round(m.naturalHeight || m.videoHeight || m.height || px.h);
1200
+ /** @type {Uint8ClampedArray | null} */
1201
+ let data = null;
1202
+ try {
1203
+ const cv = document.createElement("canvas");
1204
+ cv.width = w;
1205
+ cv.height = h;
1206
+ const g = cv.getContext("2d", { willReadFrequently: true });
1207
+ if (g) {
1208
+ g.drawImage(/** @type {CanvasImageSource} */ (m), 0, 0, w, h);
1209
+ data = g.getImageData(0, 0, w, h).data;
1210
+ }
1211
+ } catch {
1212
+ data = null;
1213
+ }
1214
+ const k = w / (px.w || 1);
1215
+ return (r) => {
1216
+ if (!data) return fallback;
1217
+ const d = 3;
1218
+ const x0 = r.x * k - d, y0 = r.y * k - d, x1 = (r.x + r.w) * k + d, y1 = (r.y + r.h) * k + d;
1219
+ /** @type {[number, number, number, number][]} */
1220
+ const px4 = [];
1221
+ for (let s = 0; s <= 24; s++) {
1222
+ const u = s / 24;
1223
+ for (const [x, y] of [[lerp(x0, x1, u), y0], [lerp(x0, x1, u), y1], [x0, lerp(y0, y1, u)], [x1, lerp(y0, y1, u)]]) {
1224
+ const xi = Math.round(clamp(/** @type {number} */ (x), 0, w - 1)), yi = Math.round(clamp(/** @type {number} */ (y), 0, h - 1));
1225
+ const j = 4 * (yi * w + xi);
1226
+ const c = /** @type {[number, number, number]} */ ([data[j] ?? 0, data[j + 1] ?? 0, data[j + 2] ?? 0]);
1227
+ px4.push([0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2], ...c]);
1228
+ }
1229
+ }
1230
+ px4.sort((a, b) => a[0] - b[0]);
1231
+ const mid = nth(px4, px4.length >> 1);
1232
+ return `rgb(${mid[1]}, ${mid[2]}, ${mid[3]})`;
1233
+ };
1234
+ }
1235
+
1236
+ /**
1237
+ * The same cursors over a picture of a screen (an <img>, <video> or
1238
+ * <canvas> of a recorded or saved screen): each box is revealed through a
1239
+ * mask of its own as its agent builds it — dragged and shown ("box", the
1240
+ * default), typed left to right ("text"), drawn ("line") or wiped down
1241
+ * ("media") — and when the last has landed the rest of the picture comes in
1242
+ * over `settle` s (0.4). `under` (0) is how much of the picture shows where
1243
+ * nothing is built yet. Boxes in the picture's own px, or in `size` [w, h].
1244
+ * A box inside another is printed in the other's pixels: while the outer one
1245
+ * shows and the inner one is not built, the inner one is covered by a patch
1246
+ * in the colour round it (sampled from the picture; `patch` when it cannot be
1247
+ * read), so a card shows empty until its rows are typed in.
1248
+ * The overlay goes in `o.root` (default the picture's parent).
1249
+ * @param {HTMLElement} el
1250
+ * @param {({ x: number, y: number, w?: number, h?: number, width?: number, height?: number, kind?: "box" | "text" | "line" | "media", label?: string, agent?: number, order?: number } | [number, number, number, number])[]} boxes
1251
+ * @param {SwarmOptions & { root?: HTMLElement, size?: [number, number], under?: number, settle?: number, patch?: string }} [o]
1252
+ * @returns {Swarm}
1253
+ */
1254
+ export function swarmBoxes(el, boxes, o = {}) {
1255
+ const root = o.root ?? /** @type {HTMLElement} */ (el.parentElement);
1256
+ return lazy(() =>
1257
+ mount(root, o, (_layer, origin) => {
1258
+ const pr = el.getBoundingClientRect();
1259
+ const px = { x: pr.left - origin[0], y: pr.top - origin[1], w: pr.width, h: pr.height };
1260
+ const media = /** @type {any} */ (el);
1261
+ const [sw, sh] = o.size ?? [media.naturalWidth || media.videoWidth || media.width || pr.width, media.naturalHeight || media.videoHeight || media.height || pr.height];
1262
+ const sx = px.w / (sw || 1), sy = px.h / (sh || 1);
1263
+ /** @type {PlanItem[]} */
1264
+ const items = [];
1265
+ /** @type {Rect[]} */
1266
+ const local = [];
1267
+ const kinds = /** @type {("box" | "text" | "line" | "media")[]} */ ([]);
1268
+ for (const b of boxes) {
1269
+ const [x, y, w, h] = Array.isArray(b) ? b : [b.x, b.y, b.w ?? b.width ?? 0, b.h ?? b.height ?? 0];
1270
+ const kind = Array.isArray(b) ? "box" : (b.kind ?? "box");
1271
+ const r = { x: px.x + x * sx, y: px.y + y * sy, w: w * sx, h: h * sy };
1272
+ local.push({ x: x * sx, y: y * sy, w: w * sx, h: h * sy });
1273
+ kinds.push(kind);
1274
+ /** @type {PlanItem} */
1275
+ const it = { kind: kind === "line" ? "rule" : kind, rect: r };
1276
+ if (kind === "text") {
1277
+ const chars = Math.max(4, Math.round(r.w / Math.max(4, r.h * 0.55)));
1278
+ it.path = Array.from({ length: chars + 1 }, (_, k) => /** @type {Pt} */ ([r.x + (r.w * k) / chars, r.y + r.h / 2]));
1279
+ } else if (kind === "line") it.path = [[r.x, r.y + r.h / 2], [r.x + r.w, r.y + r.h / 2]];
1280
+ if (!Array.isArray(b)) {
1281
+ if (b.agent != null) it.agent = b.agent;
1282
+ if (b.order != null) it.order = b.order;
1283
+ }
1284
+ items.push(it);
1285
+ }
1286
+ if (typeof o.assign === "function") {
1287
+ const fn = o.assign;
1288
+ items.forEach((it, i) => {
1289
+ if (it.agent != null) return;
1290
+ const a = fn({ el, kind: it.kind, rect: it.rect, text: "" }, i);
1291
+ if (a != null && Number.isFinite(a) && a >= 0) it.agent = a;
1292
+ });
1293
+ }
1294
+ const under = clamp(o.under ?? 0);
1295
+ const settle = o.settle ?? 0.4;
1296
+ const own = { mask: el.style.getPropertyValue("mask"), webkit: el.style.getPropertyValue("-webkit-mask") };
1297
+
1298
+ // A box printed inside another (rows in a card) is part of the card's
1299
+ // pixels: while the card is shown and the row is not built yet, a patch
1300
+ // in the colour round the row covers it, so the card shows empty.
1301
+ const area = (/** @type {Rect} */ r) => r.w * r.h;
1302
+ const inside = (/** @type {Rect} */ a, /** @type {Rect} */ b) =>
1303
+ a.x >= b.x - 1 && a.y >= b.y - 1 && a.x + a.w <= b.x + b.w + 1 && a.y + a.h <= b.y + b.h + 1 && area(a) < area(b);
1304
+ const parent = local.map((r, i) => {
1305
+ let best = -1;
1306
+ local.forEach((q, j) => {
1307
+ const k = nth(kinds, j);
1308
+ if (j !== i && (k === "box" || k === "media") && inside(r, q) && (best < 0 || area(q) < area(nth(local, best)))) best = j;
1309
+ });
1310
+ return best;
1311
+ });
1312
+ const colourOf = sampler(el, px, o.patch ?? "#000");
1313
+ const patches = local.map((r, i) => {
1314
+ if (nth(parent, i) < 0) return null;
1315
+ const d = document.createElement("div");
1316
+ d.className = "swarm-abs";
1317
+ d.style.background = colourOf(r);
1318
+ d.style.display = "none";
1319
+ _layer.append(d);
1320
+ return d;
1321
+ });
1322
+ /** the part of item i the picture shows, in the picture's px, or null @param {number} i @param {{ phase: number, p: number }} st @returns {Rect | null} */
1323
+ const shownPart = (i, st) => {
1324
+ if (st.phase === 0) return null;
1325
+ const kind = nth(kinds, i);
1326
+ let { x, y, w, h } = nth(local, i);
1327
+ if (st.phase === 1) {
1328
+ const p = st.p;
1329
+ if (kind === "box") { if (p < 0.55) return null; }
1330
+ else if (kind === "media") { if (p < 0.33) return null; h *= ease.inOut3((p - 0.33) / 0.67); }
1331
+ else if (kind === "text") {
1332
+ const chars = (nth(items, i).path?.length ?? 2) - 1;
1333
+ w *= Math.floor(p * chars + 1e-9) / chars;
1334
+ } else w *= ease.inOut3(p);
1335
+ }
1336
+ return w > 0 && h > 0 ? { x, y, w, h } : null;
1337
+ };
1338
+ /** what of item i is not built yet, given what is shown @param {number} i @param {Rect | null} part @returns {Rect | null} */
1339
+ const remainder = (i, part) => {
1340
+ const r = nth(local, i);
1341
+ if (!part) return r;
1342
+ const kind = nth(kinds, i);
1343
+ if (kind === "text" || kind === "line") return part.w < r.w ? { x: part.x + part.w, y: r.y, w: r.x + r.w - part.x - part.w, h: r.h } : null;
1344
+ if (kind === "media") return part.h < r.h ? { x: r.x, y: part.y + part.h, w: r.w, h: r.y + r.h - part.y - part.h } : null;
1345
+ return null;
1346
+ };
1347
+ /** @param {Rect} a @param {Rect} b @returns {Rect | null} */
1348
+ const meet = (a, b) => {
1349
+ const x = Math.max(a.x, b.x), y = Math.max(a.y, b.y);
1350
+ const w = Math.min(a.x + a.w, b.x + b.w) - x, h = Math.min(a.y + a.h, b.y + b.h) - y;
1351
+ return w > 0 && h > 0 ? { x, y, w, h } : null;
1352
+ };
1353
+ let last = "";
1354
+ /** @param {ReturnType<typeof plan>} P @param {number} t */
1355
+ const write = (P, t) => {
1356
+ const rest = t < P.start ? under : under + (1 - under) * clamp((t - P.end) / Math.max(1e-6, settle));
1357
+ const parts = local.map((_, i) => shownPart(i, t < P.start ? { phase: 0, p: 0 } : P.itemAt(i, t)));
1358
+ patches.forEach((d, i) => {
1359
+ if (!d) return;
1360
+ const pp = parts[nth(parent, i)] ?? null;
1361
+ const rem = pp && rest < 1 ? remainder(i, parts[i] ?? null) : null;
1362
+ const r = rem && pp ? meet(rem, pp) : null;
1363
+ const v = r ? "" : "none";
1364
+ if (d.style.display !== v) d.style.display = v;
1365
+ if (r) {
1366
+ d.style.transform = `translate(${(px.x + r.x).toFixed(2)}px, ${(px.y + r.y).toFixed(2)}px)`;
1367
+ d.style.width = `${r.w.toFixed(2)}px`;
1368
+ d.style.height = `${r.h.toFixed(2)}px`;
1369
+ }
1370
+ });
1371
+ if (t >= P.start && rest >= 1) {
1372
+ if (last !== "") {
1373
+ last = "";
1374
+ el.style.removeProperty("mask");
1375
+ el.style.removeProperty("-webkit-mask");
1376
+ if (own.mask) el.style.setProperty("mask", own.mask);
1377
+ if (own.webkit) el.style.setProperty("-webkit-mask", own.webkit);
1378
+ }
1379
+ return;
1380
+ }
1381
+ /** @type {string[]} */
1382
+ const layers = [];
1383
+ if (rest > 0) layers.push(`linear-gradient(rgba(0,0,0,${rest.toFixed(3)}), rgba(0,0,0,${rest.toFixed(3)})) 0 0 / 100% 100% no-repeat`);
1384
+ for (const r of parts) {
1385
+ if (!r) continue;
1386
+ layers.push(`linear-gradient(#000, #000) ${r.x.toFixed(2)}px ${r.y.toFixed(2)}px / ${r.w.toFixed(2)}px ${r.h.toFixed(2)}px no-repeat`);
1387
+ }
1388
+ const v = layers.length ? layers.join(", ") : "linear-gradient(transparent, transparent)";
1389
+ if (v !== last) {
1390
+ last = v;
1391
+ el.style.setProperty("mask", v);
1392
+ el.style.setProperty("-webkit-mask", v);
1393
+ }
1394
+ };
1395
+ return { items, els: items.map(() => el), fonts: items.map(() => null), write };
1396
+ }),
1397
+ );
1398
+ }