@mountaya/elements 0.0.0-stage → 0.1.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 (831) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENCE.fr.txt +280 -0
  3. package/LICENSE.txt +262 -0
  4. package/README.md +1509 -2
  5. package/THIRD-PARTY-NOTICES.txt +103 -0
  6. package/dist/accentColor-GNKBD2CW.js +4 -0
  7. package/dist/accentColor-GNKBD2CW.js.map +1 -0
  8. package/dist/accentColor-VX2JSMGE.cjs +17 -0
  9. package/dist/accentColor-VX2JSMGE.cjs.map +1 -0
  10. package/dist/agent/index.cjs +1964 -0
  11. package/dist/agent/index.cjs.map +1 -0
  12. package/dist/agent/index.d.cts +2016 -0
  13. package/dist/agent/index.d.ts +2016 -0
  14. package/dist/agent/index.js +1937 -0
  15. package/dist/agent/index.js.map +1 -0
  16. package/dist/amenities-B3-qAjxu.d.cts +160 -0
  17. package/dist/amenities-B3-qAjxu.d.ts +160 -0
  18. package/dist/bundle-Je5zsRFg.d.cts +222 -0
  19. package/dist/bundle-xYrrbJTH.d.ts +222 -0
  20. package/dist/camera/index.cjs +3477 -0
  21. package/dist/camera/index.cjs.map +1 -0
  22. package/dist/camera/index.d.cts +1751 -0
  23. package/dist/camera/index.d.ts +1751 -0
  24. package/dist/camera/index.js +3328 -0
  25. package/dist/camera/index.js.map +1 -0
  26. package/dist/camera-BrFLU1DH.d.cts +549 -0
  27. package/dist/camera-C48Ykaxv.d.ts +549 -0
  28. package/dist/chunk-23PFRRB6.js +3 -0
  29. package/dist/chunk-23PFRRB6.js.map +1 -0
  30. package/dist/chunk-2GI5SAH2.js +71 -0
  31. package/dist/chunk-2GI5SAH2.js.map +1 -0
  32. package/dist/chunk-2MQK6A74.js +39 -0
  33. package/dist/chunk-2MQK6A74.js.map +1 -0
  34. package/dist/chunk-2RE7R4LD.js +73 -0
  35. package/dist/chunk-2RE7R4LD.js.map +1 -0
  36. package/dist/chunk-3JZQKN4O.js +6 -0
  37. package/dist/chunk-3JZQKN4O.js.map +1 -0
  38. package/dist/chunk-3NDXVUUI.js +50 -0
  39. package/dist/chunk-3NDXVUUI.js.map +1 -0
  40. package/dist/chunk-3R4GFTUM.cjs +59 -0
  41. package/dist/chunk-3R4GFTUM.cjs.map +1 -0
  42. package/dist/chunk-3RVUQ6JN.cjs +22 -0
  43. package/dist/chunk-3RVUQ6JN.cjs.map +1 -0
  44. package/dist/chunk-4F6BJMJC.cjs +49 -0
  45. package/dist/chunk-4F6BJMJC.cjs.map +1 -0
  46. package/dist/chunk-4NWQD4BX.js +132 -0
  47. package/dist/chunk-4NWQD4BX.js.map +1 -0
  48. package/dist/chunk-5K2MH3R6.js +10 -0
  49. package/dist/chunk-5K2MH3R6.js.map +1 -0
  50. package/dist/chunk-6ACRNQQQ.cjs +8 -0
  51. package/dist/chunk-6ACRNQQQ.cjs.map +1 -0
  52. package/dist/chunk-6D26E3IA.js +66 -0
  53. package/dist/chunk-6D26E3IA.js.map +1 -0
  54. package/dist/chunk-6ESAW35P.cjs +80 -0
  55. package/dist/chunk-6ESAW35P.cjs.map +1 -0
  56. package/dist/chunk-6LIW2A5M.cjs +1176 -0
  57. package/dist/chunk-6LIW2A5M.cjs.map +1 -0
  58. package/dist/chunk-6OTTWVCA.js +57 -0
  59. package/dist/chunk-6OTTWVCA.js.map +1 -0
  60. package/dist/chunk-6VROJ4UG.js +862 -0
  61. package/dist/chunk-6VROJ4UG.js.map +1 -0
  62. package/dist/chunk-6Y7FTGO4.js +23 -0
  63. package/dist/chunk-6Y7FTGO4.js.map +1 -0
  64. package/dist/chunk-75I4CG64.js +104 -0
  65. package/dist/chunk-75I4CG64.js.map +1 -0
  66. package/dist/chunk-7CUBXHAH.cjs +14 -0
  67. package/dist/chunk-7CUBXHAH.cjs.map +1 -0
  68. package/dist/chunk-7GTCURVY.js +52 -0
  69. package/dist/chunk-7GTCURVY.js.map +1 -0
  70. package/dist/chunk-7IWOL6AM.cjs +100 -0
  71. package/dist/chunk-7IWOL6AM.cjs.map +1 -0
  72. package/dist/chunk-7QN7M667.cjs +151 -0
  73. package/dist/chunk-7QN7M667.cjs.map +1 -0
  74. package/dist/chunk-A6KQDKLM.cjs +1197 -0
  75. package/dist/chunk-A6KQDKLM.cjs.map +1 -0
  76. package/dist/chunk-A77EA67G.js +354 -0
  77. package/dist/chunk-A77EA67G.js.map +1 -0
  78. package/dist/chunk-AFKOABJ4.cjs +7194 -0
  79. package/dist/chunk-AFKOABJ4.cjs.map +1 -0
  80. package/dist/chunk-AG6JV5Z2.cjs +183 -0
  81. package/dist/chunk-AG6JV5Z2.cjs.map +1 -0
  82. package/dist/chunk-APBK7NMS.js +30 -0
  83. package/dist/chunk-APBK7NMS.js.map +1 -0
  84. package/dist/chunk-AWO5YA7A.cjs +33 -0
  85. package/dist/chunk-AWO5YA7A.cjs.map +1 -0
  86. package/dist/chunk-AZATU6QW.js +108 -0
  87. package/dist/chunk-AZATU6QW.js.map +1 -0
  88. package/dist/chunk-BD2U3WST.cjs +623 -0
  89. package/dist/chunk-BD2U3WST.cjs.map +1 -0
  90. package/dist/chunk-BHBEOU6L.cjs +65 -0
  91. package/dist/chunk-BHBEOU6L.cjs.map +1 -0
  92. package/dist/chunk-CNOSNYNE.js +8 -0
  93. package/dist/chunk-CNOSNYNE.js.map +1 -0
  94. package/dist/chunk-CW3EFR4O.js +12 -0
  95. package/dist/chunk-CW3EFR4O.js.map +1 -0
  96. package/dist/chunk-DASVRNBK.js +7187 -0
  97. package/dist/chunk-DASVRNBK.js.map +1 -0
  98. package/dist/chunk-DJ6LCKYP.js +42 -0
  99. package/dist/chunk-DJ6LCKYP.js.map +1 -0
  100. package/dist/chunk-E5FHQAIO.cjs +45 -0
  101. package/dist/chunk-E5FHQAIO.cjs.map +1 -0
  102. package/dist/chunk-EOML5OTY.cjs +360 -0
  103. package/dist/chunk-EOML5OTY.cjs.map +1 -0
  104. package/dist/chunk-EP5CASHL.js +613 -0
  105. package/dist/chunk-EP5CASHL.js.map +1 -0
  106. package/dist/chunk-EP5OEEVZ.cjs +14 -0
  107. package/dist/chunk-EP5OEEVZ.cjs.map +1 -0
  108. package/dist/chunk-EUXI3FGQ.js +150 -0
  109. package/dist/chunk-EUXI3FGQ.js.map +1 -0
  110. package/dist/chunk-EWFSHCOS.js +40 -0
  111. package/dist/chunk-EWFSHCOS.js.map +1 -0
  112. package/dist/chunk-EX2C5K2T.cjs +25 -0
  113. package/dist/chunk-EX2C5K2T.cjs.map +1 -0
  114. package/dist/chunk-FEXWDQIZ.cjs +8 -0
  115. package/dist/chunk-FEXWDQIZ.cjs.map +1 -0
  116. package/dist/chunk-FEYBFY7H.cjs +358 -0
  117. package/dist/chunk-FEYBFY7H.cjs.map +1 -0
  118. package/dist/chunk-FRGAV6N6.cjs +34 -0
  119. package/dist/chunk-FRGAV6N6.cjs.map +1 -0
  120. package/dist/chunk-G5DHP5VF.js +6 -0
  121. package/dist/chunk-G5DHP5VF.js.map +1 -0
  122. package/dist/chunk-G5W2UHV2.js +99 -0
  123. package/dist/chunk-G5W2UHV2.js.map +1 -0
  124. package/dist/chunk-G7OP7O2C.cjs +39 -0
  125. package/dist/chunk-G7OP7O2C.cjs.map +1 -0
  126. package/dist/chunk-GE6CFCAM.cjs +25 -0
  127. package/dist/chunk-GE6CFCAM.cjs.map +1 -0
  128. package/dist/chunk-GIFALLHI.cjs +111 -0
  129. package/dist/chunk-GIFALLHI.cjs.map +1 -0
  130. package/dist/chunk-GLFET5GM.js +129 -0
  131. package/dist/chunk-GLFET5GM.js.map +1 -0
  132. package/dist/chunk-GQ6UFPFM.js +22 -0
  133. package/dist/chunk-GQ6UFPFM.js.map +1 -0
  134. package/dist/chunk-GQJWVMXS.js +129 -0
  135. package/dist/chunk-GQJWVMXS.js.map +1 -0
  136. package/dist/chunk-GVVJPUKC.js +80 -0
  137. package/dist/chunk-GVVJPUKC.js.map +1 -0
  138. package/dist/chunk-GZ2HOCQ2.cjs +134 -0
  139. package/dist/chunk-GZ2HOCQ2.cjs.map +1 -0
  140. package/dist/chunk-HCBOHXWP.js +37 -0
  141. package/dist/chunk-HCBOHXWP.js.map +1 -0
  142. package/dist/chunk-IBQJDVHF.cjs +281 -0
  143. package/dist/chunk-IBQJDVHF.cjs.map +1 -0
  144. package/dist/chunk-ISLB6Y5Q.cjs +106 -0
  145. package/dist/chunk-ISLB6Y5Q.cjs.map +1 -0
  146. package/dist/chunk-J55CRR4F.js +105 -0
  147. package/dist/chunk-J55CRR4F.js.map +1 -0
  148. package/dist/chunk-JBG6Z6MQ.cjs +28 -0
  149. package/dist/chunk-JBG6Z6MQ.cjs.map +1 -0
  150. package/dist/chunk-K3RQOZRU.js +61 -0
  151. package/dist/chunk-K3RQOZRU.js.map +1 -0
  152. package/dist/chunk-KDJYS4GB.cjs +703 -0
  153. package/dist/chunk-KDJYS4GB.cjs.map +1 -0
  154. package/dist/chunk-KMCAHUZM.cjs +4 -0
  155. package/dist/chunk-KMCAHUZM.cjs.map +1 -0
  156. package/dist/chunk-KUCBNPC6.js +87 -0
  157. package/dist/chunk-KUCBNPC6.js.map +1 -0
  158. package/dist/chunk-KV6UE5A4.js +50 -0
  159. package/dist/chunk-KV6UE5A4.js.map +1 -0
  160. package/dist/chunk-L6TZ2HQR.cjs +18 -0
  161. package/dist/chunk-L6TZ2HQR.cjs.map +1 -0
  162. package/dist/chunk-L7QHHGG2.cjs +141 -0
  163. package/dist/chunk-L7QHHGG2.cjs.map +1 -0
  164. package/dist/chunk-LHK3Y2AL.js +271 -0
  165. package/dist/chunk-LHK3Y2AL.js.map +1 -0
  166. package/dist/chunk-LO5RYRBH.cjs +6317 -0
  167. package/dist/chunk-LO5RYRBH.cjs.map +1 -0
  168. package/dist/chunk-LS5SJMUO.cjs +194 -0
  169. package/dist/chunk-LS5SJMUO.cjs.map +1 -0
  170. package/dist/chunk-LUGTMZFN.cjs +42 -0
  171. package/dist/chunk-LUGTMZFN.cjs.map +1 -0
  172. package/dist/chunk-LVUQU6D5.js +32 -0
  173. package/dist/chunk-LVUQU6D5.js.map +1 -0
  174. package/dist/chunk-M2QRC2GZ.js +166 -0
  175. package/dist/chunk-M2QRC2GZ.js.map +1 -0
  176. package/dist/chunk-M6QJYQIM.cjs +53 -0
  177. package/dist/chunk-M6QJYQIM.cjs.map +1 -0
  178. package/dist/chunk-MGCPH5EO.js +12 -0
  179. package/dist/chunk-MGCPH5EO.js.map +1 -0
  180. package/dist/chunk-MLVUWEZR.cjs +474 -0
  181. package/dist/chunk-MLVUWEZR.cjs.map +1 -0
  182. package/dist/chunk-MTAMJMZL.cjs +707 -0
  183. package/dist/chunk-MTAMJMZL.cjs.map +1 -0
  184. package/dist/chunk-MXL5AT3N.js +48 -0
  185. package/dist/chunk-MXL5AT3N.js.map +1 -0
  186. package/dist/chunk-MYEQSESM.cjs +75 -0
  187. package/dist/chunk-MYEQSESM.cjs.map +1 -0
  188. package/dist/chunk-N3VPF6ZD.js +427 -0
  189. package/dist/chunk-N3VPF6ZD.js.map +1 -0
  190. package/dist/chunk-N6VUAIGI.js +7 -0
  191. package/dist/chunk-N6VUAIGI.js.map +1 -0
  192. package/dist/chunk-N6XRLUN6.js +6286 -0
  193. package/dist/chunk-N6XRLUN6.js.map +1 -0
  194. package/dist/chunk-NOGDOZIT.cjs +114 -0
  195. package/dist/chunk-NOGDOZIT.cjs.map +1 -0
  196. package/dist/chunk-NUWXEISH.cjs +10 -0
  197. package/dist/chunk-NUWXEISH.cjs.map +1 -0
  198. package/dist/chunk-NZCZHXYN.cjs +161 -0
  199. package/dist/chunk-NZCZHXYN.cjs.map +1 -0
  200. package/dist/chunk-ODROSWQX.cjs +53 -0
  201. package/dist/chunk-ODROSWQX.cjs.map +1 -0
  202. package/dist/chunk-OE36AYKG.cjs +82 -0
  203. package/dist/chunk-OE36AYKG.cjs.map +1 -0
  204. package/dist/chunk-OLON7MO6.cjs +437 -0
  205. package/dist/chunk-OLON7MO6.cjs.map +1 -0
  206. package/dist/chunk-PBUOR2IT.js +277 -0
  207. package/dist/chunk-PBUOR2IT.js.map +1 -0
  208. package/dist/chunk-PC2ELXFF.cjs +225 -0
  209. package/dist/chunk-PC2ELXFF.cjs.map +1 -0
  210. package/dist/chunk-PCSGXLOC.js +71 -0
  211. package/dist/chunk-PCSGXLOC.js.map +1 -0
  212. package/dist/chunk-PFNMP6FQ.js +56 -0
  213. package/dist/chunk-PFNMP6FQ.js.map +1 -0
  214. package/dist/chunk-PIWSZTIP.js +690 -0
  215. package/dist/chunk-PIWSZTIP.js.map +1 -0
  216. package/dist/chunk-PKWHJ2GI.js +136 -0
  217. package/dist/chunk-PKWHJ2GI.js.map +1 -0
  218. package/dist/chunk-PLMVBX2A.cjs +76 -0
  219. package/dist/chunk-PLMVBX2A.cjs.map +1 -0
  220. package/dist/chunk-PM3XCD2G.cjs +113 -0
  221. package/dist/chunk-PM3XCD2G.cjs.map +1 -0
  222. package/dist/chunk-QAL4GZO7.cjs +143 -0
  223. package/dist/chunk-QAL4GZO7.cjs.map +1 -0
  224. package/dist/chunk-QDB2SEA2.js +74 -0
  225. package/dist/chunk-QDB2SEA2.js.map +1 -0
  226. package/dist/chunk-QOV7UNUN.js +25 -0
  227. package/dist/chunk-QOV7UNUN.js.map +1 -0
  228. package/dist/chunk-QQUWYLSF.cjs +50 -0
  229. package/dist/chunk-QQUWYLSF.cjs.map +1 -0
  230. package/dist/chunk-QUMBH3U4.cjs +9 -0
  231. package/dist/chunk-QUMBH3U4.cjs.map +1 -0
  232. package/dist/chunk-R4KA7OFQ.js +12 -0
  233. package/dist/chunk-R4KA7OFQ.js.map +1 -0
  234. package/dist/chunk-RBSGAZQQ.js +17 -0
  235. package/dist/chunk-RBSGAZQQ.js.map +1 -0
  236. package/dist/chunk-RM5YJWZI.js +46 -0
  237. package/dist/chunk-RM5YJWZI.js.map +1 -0
  238. package/dist/chunk-ROKNKXA4.cjs +8 -0
  239. package/dist/chunk-ROKNKXA4.cjs.map +1 -0
  240. package/dist/chunk-RQG6D546.cjs +75 -0
  241. package/dist/chunk-RQG6D546.cjs.map +1 -0
  242. package/dist/chunk-SG4YDD5L.cjs +74 -0
  243. package/dist/chunk-SG4YDD5L.cjs.map +1 -0
  244. package/dist/chunk-SNRCA7EO.js +56 -0
  245. package/dist/chunk-SNRCA7EO.js.map +1 -0
  246. package/dist/chunk-SO75R4WW.cjs +22 -0
  247. package/dist/chunk-SO75R4WW.cjs.map +1 -0
  248. package/dist/chunk-SP34NHFI.js +45 -0
  249. package/dist/chunk-SP34NHFI.js.map +1 -0
  250. package/dist/chunk-SSKSSBWJ.cjs +179 -0
  251. package/dist/chunk-SSKSSBWJ.cjs.map +1 -0
  252. package/dist/chunk-TB5663C2.js +1108 -0
  253. package/dist/chunk-TB5663C2.js.map +1 -0
  254. package/dist/chunk-TGH4NRES.js +220 -0
  255. package/dist/chunk-TGH4NRES.js.map +1 -0
  256. package/dist/chunk-TJ6ZPNID.js +189 -0
  257. package/dist/chunk-TJ6ZPNID.js.map +1 -0
  258. package/dist/chunk-U45T35N2.cjs +90 -0
  259. package/dist/chunk-U45T35N2.cjs.map +1 -0
  260. package/dist/chunk-UKVOPEZ2.js +442 -0
  261. package/dist/chunk-UKVOPEZ2.js.map +1 -0
  262. package/dist/chunk-UTB4NROA.cjs +887 -0
  263. package/dist/chunk-UTB4NROA.cjs.map +1 -0
  264. package/dist/chunk-UTW33B5V.js +6 -0
  265. package/dist/chunk-UTW33B5V.js.map +1 -0
  266. package/dist/chunk-UYUBSD2V.cjs +33 -0
  267. package/dist/chunk-UYUBSD2V.cjs.map +1 -0
  268. package/dist/chunk-V3JEP5AG.cjs +59 -0
  269. package/dist/chunk-V3JEP5AG.cjs.map +1 -0
  270. package/dist/chunk-VFAGJXHR.js +18 -0
  271. package/dist/chunk-VFAGJXHR.js.map +1 -0
  272. package/dist/chunk-VMEE57E5.cjs +58 -0
  273. package/dist/chunk-VMEE57E5.cjs.map +1 -0
  274. package/dist/chunk-VQVBEX3Y.cjs +113 -0
  275. package/dist/chunk-VQVBEX3Y.cjs.map +1 -0
  276. package/dist/chunk-VZDXX7TT.cjs +64 -0
  277. package/dist/chunk-VZDXX7TT.cjs.map +1 -0
  278. package/dist/chunk-WE5ZTI4D.js +346 -0
  279. package/dist/chunk-WE5ZTI4D.js.map +1 -0
  280. package/dist/chunk-WEFUVABP.js +19 -0
  281. package/dist/chunk-WEFUVABP.js.map +1 -0
  282. package/dist/chunk-WMU4LRKC.js +28 -0
  283. package/dist/chunk-WMU4LRKC.js.map +1 -0
  284. package/dist/chunk-WQ24RRHL.cjs +354 -0
  285. package/dist/chunk-WQ24RRHL.cjs.map +1 -0
  286. package/dist/chunk-WW4CGS7G.cjs +26 -0
  287. package/dist/chunk-WW4CGS7G.cjs.map +1 -0
  288. package/dist/chunk-WXE5WCTM.js +1144 -0
  289. package/dist/chunk-WXE5WCTM.js.map +1 -0
  290. package/dist/chunk-X23BGIYA.cjs +37 -0
  291. package/dist/chunk-X23BGIYA.cjs.map +1 -0
  292. package/dist/chunk-XEW4FTR2.js +98 -0
  293. package/dist/chunk-XEW4FTR2.js.map +1 -0
  294. package/dist/chunk-XIOI4IYW.js +167 -0
  295. package/dist/chunk-XIOI4IYW.js.map +1 -0
  296. package/dist/chunk-XLVPJ37V.cjs +44 -0
  297. package/dist/chunk-XLVPJ37V.cjs.map +1 -0
  298. package/dist/chunk-XOHAXXZA.cjs +51 -0
  299. package/dist/chunk-XOHAXXZA.cjs.map +1 -0
  300. package/dist/chunk-Y4NRIHK6.cjs +313 -0
  301. package/dist/chunk-Y4NRIHK6.cjs.map +1 -0
  302. package/dist/chunk-Y4YMMKL3.js +23 -0
  303. package/dist/chunk-Y4YMMKL3.js.map +1 -0
  304. package/dist/chunk-YJNYBVE3.cjs +14 -0
  305. package/dist/chunk-YJNYBVE3.cjs.map +1 -0
  306. package/dist/chunk-Z762QNQP.cjs +60 -0
  307. package/dist/chunk-Z762QNQP.cjs.map +1 -0
  308. package/dist/chunk-ZG5KMBOF.js +669 -0
  309. package/dist/chunk-ZG5KMBOF.js.map +1 -0
  310. package/dist/chunk-ZKONQEFA.js +344 -0
  311. package/dist/chunk-ZKONQEFA.js.map +1 -0
  312. package/dist/chunk-ZR5X7QMH.js +39 -0
  313. package/dist/chunk-ZR5X7QMH.js.map +1 -0
  314. package/dist/chunk-ZW4BJQ26.js +84 -0
  315. package/dist/chunk-ZW4BJQ26.js.map +1 -0
  316. package/dist/climbs-BhlWuu0x.d.ts +70 -0
  317. package/dist/climbs-DgBFwySV.d.cts +70 -0
  318. package/dist/collab/index.cjs +1283 -0
  319. package/dist/collab/index.cjs.map +1 -0
  320. package/dist/collab/index.d.cts +850 -0
  321. package/dist/collab/index.d.ts +850 -0
  322. package/dist/collab/index.js +1274 -0
  323. package/dist/collab/index.js.map +1 -0
  324. package/dist/data/index.cjs +132 -0
  325. package/dist/data/index.cjs.map +1 -0
  326. package/dist/data/index.d.cts +468 -0
  327. package/dist/data/index.d.ts +468 -0
  328. package/dist/data/index.js +15 -0
  329. package/dist/data/index.js.map +1 -0
  330. package/dist/editor/index.cjs +4506 -0
  331. package/dist/editor/index.cjs.map +1 -0
  332. package/dist/editor/index.d.cts +59 -0
  333. package/dist/editor/index.d.ts +59 -0
  334. package/dist/editor/index.js +4486 -0
  335. package/dist/editor/index.js.map +1 -0
  336. package/dist/elevationTiles-pmsb9wnU.d.cts +77 -0
  337. package/dist/elevationTiles-pmsb9wnU.d.ts +77 -0
  338. package/dist/errors/index.cjs +28 -0
  339. package/dist/errors/index.cjs.map +1 -0
  340. package/dist/errors/index.d.cts +125 -0
  341. package/dist/errors/index.d.ts +125 -0
  342. package/dist/errors/index.js +3 -0
  343. package/dist/errors/index.js.map +1 -0
  344. package/dist/geo/index.cjs +232 -0
  345. package/dist/geo/index.cjs.map +1 -0
  346. package/dist/geo/index.d.cts +821 -0
  347. package/dist/geo/index.d.ts +821 -0
  348. package/dist/geo/index.js +15 -0
  349. package/dist/geo/index.js.map +1 -0
  350. package/dist/geodesy-543qXKtI.d.cts +78 -0
  351. package/dist/geodesy-543qXKtI.d.ts +78 -0
  352. package/dist/geolocation-DDkQdWMN.d.cts +106 -0
  353. package/dist/geolocation-DDkQdWMN.d.ts +106 -0
  354. package/dist/i18n/fr/index.cjs +338 -0
  355. package/dist/i18n/fr/index.cjs.map +1 -0
  356. package/dist/i18n/fr/index.d.cts +25 -0
  357. package/dist/i18n/fr/index.d.ts +25 -0
  358. package/dist/i18n/fr/index.js +336 -0
  359. package/dist/i18n/fr/index.js.map +1 -0
  360. package/dist/i18n/index.cjs +464 -0
  361. package/dist/i18n/index.cjs.map +1 -0
  362. package/dist/i18n/index.d.cts +227 -0
  363. package/dist/i18n/index.d.ts +227 -0
  364. package/dist/i18n/index.js +430 -0
  365. package/dist/i18n/index.js.map +1 -0
  366. package/dist/icons/index.cjs +116 -0
  367. package/dist/icons/index.cjs.map +1 -0
  368. package/dist/icons/index.d.cts +457 -0
  369. package/dist/icons/index.d.ts +457 -0
  370. package/dist/icons/index.js +11 -0
  371. package/dist/icons/index.js.map +1 -0
  372. package/dist/index.cjs +1869 -0
  373. package/dist/index.cjs.map +1 -0
  374. package/dist/index.d.cts +251 -0
  375. package/dist/index.d.ts +251 -0
  376. package/dist/index.js +67 -0
  377. package/dist/index.js.map +1 -0
  378. package/dist/itinerary-Dp2ZnqgD.d.cts +178 -0
  379. package/dist/itinerary-Dp2ZnqgD.d.ts +178 -0
  380. package/dist/language-CEWQ5uYw.d.cts +69 -0
  381. package/dist/language-CEWQ5uYw.d.ts +69 -0
  382. package/dist/layers/index.cjs +318 -0
  383. package/dist/layers/index.cjs.map +1 -0
  384. package/dist/layers/index.d.cts +1555 -0
  385. package/dist/layers/index.d.ts +1555 -0
  386. package/dist/layers/index.js +17 -0
  387. package/dist/layers/index.js.map +1 -0
  388. package/dist/map-client/index.cjs +4 -0
  389. package/dist/map-client/index.cjs.map +1 -0
  390. package/dist/map-client/index.d.cts +1856 -0
  391. package/dist/map-client/index.d.ts +1856 -0
  392. package/dist/map-client/index.js +3 -0
  393. package/dist/map-client/index.js.map +1 -0
  394. package/dist/maplibre-worker.mjs +12 -0
  395. package/dist/markerSprite-DGBQF6PO.cjs +49 -0
  396. package/dist/markerSprite-DGBQF6PO.cjs.map +1 -0
  397. package/dist/markerSprite-DZLTR6F6.js +8 -0
  398. package/dist/markerSprite-DZLTR6F6.js.map +1 -0
  399. package/dist/mountayaMap-C9mxRFib.d.cts +3277 -0
  400. package/dist/mountayaMap-DgnlQ2fE.d.ts +3277 -0
  401. package/dist/navigation/index.cjs +699 -0
  402. package/dist/navigation/index.cjs.map +1 -0
  403. package/dist/navigation/index.d.cts +632 -0
  404. package/dist/navigation/index.d.ts +632 -0
  405. package/dist/navigation/index.js +689 -0
  406. package/dist/navigation/index.js.map +1 -0
  407. package/dist/order-BLhsGsH8.d.ts +132 -0
  408. package/dist/order-BZkUwMou.d.cts +132 -0
  409. package/dist/paint-BgUcj8l7.d.cts +118 -0
  410. package/dist/paint-Dx_qGNE_.d.ts +118 -0
  411. package/dist/profile/index.cjs +675 -0
  412. package/dist/profile/index.cjs.map +1 -0
  413. package/dist/profile/index.d.cts +2086 -0
  414. package/dist/profile/index.d.ts +2086 -0
  415. package/dist/profile/index.js +18 -0
  416. package/dist/profile/index.js.map +1 -0
  417. package/dist/provider-DM71XnLX.d.cts +121 -0
  418. package/dist/provider-DM71XnLX.d.ts +121 -0
  419. package/dist/roadAccess-D_rOE4xW.d.cts +86 -0
  420. package/dist/roadAccess-D_rOE4xW.d.ts +86 -0
  421. package/dist/routeProfile-BKfSfxx6.d.ts +210 -0
  422. package/dist/routeProfile-BsSUABXv.d.cts +210 -0
  423. package/dist/seams/index.cjs +39 -0
  424. package/dist/seams/index.cjs.map +1 -0
  425. package/dist/seams/index.d.cts +254 -0
  426. package/dist/seams/index.d.ts +254 -0
  427. package/dist/seams/index.js +6 -0
  428. package/dist/seams/index.js.map +1 -0
  429. package/dist/search/index.cjs +147 -0
  430. package/dist/search/index.cjs.map +1 -0
  431. package/dist/search/index.d.cts +888 -0
  432. package/dist/search/index.d.ts +888 -0
  433. package/dist/search/index.js +14 -0
  434. package/dist/search/index.js.map +1 -0
  435. package/dist/searchHighlight-DFE7LVIL.cjs +33 -0
  436. package/dist/searchHighlight-DFE7LVIL.cjs.map +1 -0
  437. package/dist/searchHighlight-MHAQZVWG.js +12 -0
  438. package/dist/searchHighlight-MHAQZVWG.js.map +1 -0
  439. package/dist/searchLimits-j99-NTXR.d.cts +24 -0
  440. package/dist/searchLimits-j99-NTXR.d.ts +24 -0
  441. package/dist/sections-CVlc2Inr.d.cts +953 -0
  442. package/dist/sections-CmtaduLc.d.ts +953 -0
  443. package/dist/segmentRoute-C5UL_5bp.d.ts +172 -0
  444. package/dist/segmentRoute-CIo6dR8Y.d.cts +172 -0
  445. package/dist/strings-30RSdIat.d.cts +552 -0
  446. package/dist/strings-DPTIbzT5.d.ts +552 -0
  447. package/dist/stripeImage-CQUXM2YI.js +14 -0
  448. package/dist/stripeImage-CQUXM2YI.js.map +1 -0
  449. package/dist/stripeImage-R43OPA6U.cjs +39 -0
  450. package/dist/stripeImage-R43OPA6U.cjs.map +1 -0
  451. package/dist/style/index.cjs +116 -0
  452. package/dist/style/index.cjs.map +1 -0
  453. package/dist/style/index.d.cts +538 -0
  454. package/dist/style/index.d.ts +538 -0
  455. package/dist/style/index.js +11 -0
  456. package/dist/style/index.js.map +1 -0
  457. package/dist/styles.css +11 -0
  458. package/dist/testing/index.cjs +629 -0
  459. package/dist/testing/index.cjs.map +1 -0
  460. package/dist/testing/index.d.cts +265 -0
  461. package/dist/testing/index.d.ts +265 -0
  462. package/dist/testing/index.js +623 -0
  463. package/dist/testing/index.js.map +1 -0
  464. package/dist/timezone/index.cjs +759 -0
  465. package/dist/timezone/index.cjs.map +1 -0
  466. package/dist/timezone/index.d.cts +53 -0
  467. package/dist/timezone/index.d.ts +53 -0
  468. package/dist/timezone/index.js +757 -0
  469. package/dist/timezone/index.js.map +1 -0
  470. package/dist/types-B034JMjl.d.ts +973 -0
  471. package/dist/types-B2NDLxQA.d.cts +21 -0
  472. package/dist/types-B2NDLxQA.d.ts +21 -0
  473. package/dist/types-BEv8V_8V.d.cts +55 -0
  474. package/dist/types-BEv8V_8V.d.ts +55 -0
  475. package/dist/types-C8aX5KMU.d.cts +973 -0
  476. package/dist/types-CTQwbSdA.d.cts +321 -0
  477. package/dist/types-nO2joeRk.d.ts +321 -0
  478. package/dist/units/index.cjs +99 -0
  479. package/dist/units/index.cjs.map +1 -0
  480. package/dist/units/index.d.cts +75 -0
  481. package/dist/units/index.d.ts +75 -0
  482. package/dist/units/index.js +6 -0
  483. package/dist/units/index.js.map +1 -0
  484. package/dist/units-D9mBrusY.d.cts +900 -0
  485. package/dist/units-D9mBrusY.d.ts +900 -0
  486. package/dist/video/index.cjs +2198 -0
  487. package/dist/video/index.cjs.map +1 -0
  488. package/dist/video/index.d.cts +873 -0
  489. package/dist/video/index.d.ts +873 -0
  490. package/dist/video/index.js +2173 -0
  491. package/dist/video/index.js.map +1 -0
  492. package/dist/videoOverlay-Dh_D5_Zs.d.cts +44 -0
  493. package/dist/videoOverlay-Dh_D5_Zs.d.ts +44 -0
  494. package/dist/view/index.cjs +43 -0
  495. package/dist/view/index.cjs.map +1 -0
  496. package/dist/view/index.d.cts +836 -0
  497. package/dist/view/index.d.ts +836 -0
  498. package/dist/view/index.js +34 -0
  499. package/dist/view/index.js.map +1 -0
  500. package/dist/zones-B05QA8fy.d.cts +75 -0
  501. package/dist/zones-B05QA8fy.d.ts +75 -0
  502. package/package.json +433 -4
  503. package/src/agent/engines/session.ts +2255 -0
  504. package/src/agent/index.ts +109 -0
  505. package/src/agent/rules/agentError.ts +128 -0
  506. package/src/agent/rules/boundedInputJson.ts +53 -0
  507. package/src/agent/rules/conversation.ts +629 -0
  508. package/src/agent/rules/conversationFaults.ts +349 -0
  509. package/src/agent/rules/conversationHost.ts +390 -0
  510. package/src/agent/rules/dispatcher.ts +102 -0
  511. package/src/agent/rules/errorCodes.ts +78 -0
  512. package/src/agent/rules/errorStatus.ts +65 -0
  513. package/src/agent/rules/scriptedTransport.ts +390 -0
  514. package/src/agent/rules/stickToBottom.ts +38 -0
  515. package/src/agent/rules/toolResultPayload.ts +197 -0
  516. package/src/auth/rules/clientHeader.ts +22 -0
  517. package/src/auth/rules/sentCredential.ts +76 -0
  518. package/src/auth/rules/transformRequest.ts +803 -0
  519. package/src/camera/engines/videoFlight.ts +1758 -0
  520. package/src/camera/index.ts +157 -0
  521. package/src/camera/rules/clearance.ts +1099 -0
  522. package/src/camera/rules/fit.ts +132 -0
  523. package/src/camera/rules/modes.ts +1023 -0
  524. package/src/camera/rules/plan.ts +478 -0
  525. package/src/camera/rules/planner.ts +129 -0
  526. package/src/camera/rules/poseRanges.ts +38 -0
  527. package/src/camera/rules/presets.ts +185 -0
  528. package/src/camera/rules/profileSamples.ts +243 -0
  529. package/src/camera/rules/route.ts +596 -0
  530. package/src/camera/rules/routeContent.ts +104 -0
  531. package/src/camera/rules/spline.ts +765 -0
  532. package/src/camera/rules/sweptViewports.ts +39 -0
  533. package/src/camera/rules/track.ts +1412 -0
  534. package/src/camera/rules/vocabulary.ts +130 -0
  535. package/src/camera/rules/zoom.ts +216 -0
  536. package/src/collab/engines/session.ts +1902 -0
  537. package/src/collab/engines/trailingThrottle.ts +151 -0
  538. package/src/collab/index.ts +56 -0
  539. package/src/collab/rules/dispatch.ts +143 -0
  540. package/src/collab/rules/peerNames.ts +51 -0
  541. package/src/collab/rules/scriptedTransport.ts +244 -0
  542. package/src/compose/engines/baseMapSwitch.ts +1136 -0
  543. package/src/compose/engines/events.ts +962 -0
  544. package/src/compose/engines/mountayaMap.ts +5674 -0
  545. package/src/compose/engines/sentCredentials.ts +146 -0
  546. package/src/compose/engines/slotRequests.ts +413 -0
  547. package/src/compose/rules/accessRefusal.ts +109 -0
  548. package/src/compose/rules/accessStanding.ts +75 -0
  549. package/src/compose/rules/analysisKinds.ts +331 -0
  550. package/src/compose/rules/analysisLayers.ts +176 -0
  551. package/src/compose/rules/cameraMoves.ts +38 -0
  552. package/src/compose/rules/carriedLayers.ts +87 -0
  553. package/src/compose/rules/developmentWarnings.ts +166 -0
  554. package/src/compose/rules/fitCamera.ts +54 -0
  555. package/src/compose/rules/geoJsonSlot.ts +61 -0
  556. package/src/compose/rules/geometrySlots.ts +155 -0
  557. package/src/compose/rules/glyphNode.ts +62 -0
  558. package/src/compose/rules/layerKeys.ts +92 -0
  559. package/src/compose/rules/layerOrder.ts +85 -0
  560. package/src/compose/rules/layersManifest.ts +26 -0
  561. package/src/compose/rules/mapOptions.ts +300 -0
  562. package/src/compose/rules/maplibreWorkerVersion.gen.ts +8 -0
  563. package/src/compose/rules/markerPin.ts +122 -0
  564. package/src/compose/rules/markerRegistry.ts +85 -0
  565. package/src/compose/rules/markerSprite.ts +382 -0
  566. package/src/compose/rules/maxBounds.ts +120 -0
  567. package/src/compose/rules/overlayLookup.ts +49 -0
  568. package/src/compose/rules/paintDiff.ts +38 -0
  569. package/src/compose/rules/panLock.ts +77 -0
  570. package/src/compose/rules/patch.ts +124 -0
  571. package/src/compose/rules/queriedFeature.ts +55 -0
  572. package/src/compose/rules/queryLayers.ts +46 -0
  573. package/src/compose/rules/searchHighlight.ts +313 -0
  574. package/src/compose/rules/slotNames.ts +19 -0
  575. package/src/compose/rules/stripeImage.ts +253 -0
  576. package/src/compose/rules/swapMarker.ts +66 -0
  577. package/src/compose/rules/terrainVariant.ts +88 -0
  578. package/src/compose/rules/types.ts +566 -0
  579. package/src/compose/rules/urlHash.ts +19 -0
  580. package/src/compose/rules/viewOptions.ts +451 -0
  581. package/src/compose/rules/workerUrl.ts +96 -0
  582. package/src/data/engines/itineraryResource.ts +643 -0
  583. package/src/data/index.ts +78 -0
  584. package/src/data/rules/adapt.ts +473 -0
  585. package/src/data/rules/editModes.ts +51 -0
  586. package/src/data/rules/itinerary.ts +168 -0
  587. package/src/data/rules/nullable.ts +63 -0
  588. package/src/data/rules/roadAccess.ts +169 -0
  589. package/src/data/rules/segmentGroups.ts +309 -0
  590. package/src/data/rules/selectors.ts +95 -0
  591. package/src/data/rules/zones.ts +79 -0
  592. package/src/draw/engines/boundaryEngine.ts +1003 -0
  593. package/src/draw/engines/framedAdapter.ts +198 -0
  594. package/src/draw/engines/pointerCursor.ts +205 -0
  595. package/src/draw/engines/segmentEngine.ts +1405 -0
  596. package/src/draw/engines/snapIndex.ts +254 -0
  597. package/src/draw/engines/waypointEngine.ts +574 -0
  598. package/src/draw/engines/zoneEngine.ts +1137 -0
  599. package/src/draw/rules/drawFrame.ts +123 -0
  600. package/src/draw/rules/insertVertex.ts +226 -0
  601. package/src/draw/rules/screenSpace.ts +62 -0
  602. package/src/draw/rules/seeds.ts +185 -0
  603. package/src/draw/rules/snap.ts +115 -0
  604. package/src/draw/rules/snapCameraKey.ts +50 -0
  605. package/src/draw/rules/terraDrawShared.ts +214 -0
  606. package/src/draw/rules/zoneOutline.ts +213 -0
  607. package/src/editing/engines/cursor.ts +505 -0
  608. package/src/editing/engines/draftMarker.ts +149 -0
  609. package/src/editing/rules/accent.ts +11 -0
  610. package/src/editing/rules/engine.ts +286 -0
  611. package/src/editing/rules/placement.ts +22 -0
  612. package/src/editing/rules/positions.ts +89 -0
  613. package/src/editing/rules/sources.ts +9 -0
  614. package/src/editing/rules/types.ts +457 -0
  615. package/src/editing/rules/vocabulary.ts +10 -0
  616. package/src/editing/rules/waypointCursor.ts +228 -0
  617. package/src/editor/engines/directionArrows.ts +459 -0
  618. package/src/editor/engines/directions.ts +1383 -0
  619. package/src/editor/engines/editorClient.ts +134 -0
  620. package/src/editor/engines/eventScope.ts +59 -0
  621. package/src/editor/engines/frameLoop.ts +159 -0
  622. package/src/editor/engines/itineraryPreview.ts +272 -0
  623. package/src/editor/engines/mapLockGuard.ts +66 -0
  624. package/src/editor/engines/overlayRenderer.ts +2696 -0
  625. package/src/editor/engines/peerDraft.ts +760 -0
  626. package/src/editor/engines/poiPick.ts +305 -0
  627. package/src/editor/engines/pointPick.ts +84 -0
  628. package/src/editor/engines/roadAccessLine.ts +140 -0
  629. package/src/editor/engines/searchHighlight.ts +183 -0
  630. package/src/editor/engines/viewClient.ts +4083 -0
  631. package/src/editor/engines/zoneBadges.ts +503 -0
  632. package/src/editor/index.ts +97 -0
  633. package/src/editor/rules/accentColor.ts +116 -0
  634. package/src/editor/rules/camera.ts +121 -0
  635. package/src/editor/rules/contract.ts +125 -0
  636. package/src/editor/rules/icons.ts +825 -0
  637. package/src/editor/rules/markerElements.ts +244 -0
  638. package/src/editor/rules/style.ts +51 -0
  639. package/src/editor/rules/terrain.ts +98 -0
  640. package/src/editor/rules/tileWarm.ts +191 -0
  641. package/src/editor/rules/tilesReload.ts +158 -0
  642. package/src/editor/rules/zoneBadgePlacement.ts +1832 -0
  643. package/src/editor/rules/zoneTimeStyling.ts +119 -0
  644. package/src/errors/index.ts +25 -0
  645. package/src/errors/rules/errors.ts +157 -0
  646. package/src/errors/rules/print.ts +129 -0
  647. package/src/geo/index.ts +94 -0
  648. package/src/geo/rules/boundaries.ts +105 -0
  649. package/src/geo/rules/camera.ts +496 -0
  650. package/src/geo/rules/corridor.ts +242 -0
  651. package/src/geo/rules/elevationTiles.ts +269 -0
  652. package/src/geo/rules/formatLngLat.ts +63 -0
  653. package/src/geo/rules/geodesy.ts +125 -0
  654. package/src/geo/rules/geometry.ts +362 -0
  655. package/src/geo/rules/lineWalk.ts +77 -0
  656. package/src/geo/rules/longitude.ts +99 -0
  657. package/src/geo/rules/searchLimits.ts +22 -0
  658. package/src/geo/rules/segmentGeometry.ts +80 -0
  659. package/src/geo/rules/terrain.ts +107 -0
  660. package/src/geo/rules/tuples.ts +124 -0
  661. package/src/geo/rules/types.ts +54 -0
  662. package/src/geo/rules/webMercator.ts +57 -0
  663. package/src/i18n/fr/index.ts +17 -0
  664. package/src/i18n/fr/rules/fr.ts +85 -0
  665. package/src/i18n/fr/rules/words.gen.ts +277 -0
  666. package/src/i18n/index.ts +81 -0
  667. package/src/i18n/rules/bundle.ts +378 -0
  668. package/src/i18n/rules/config.ts +71 -0
  669. package/src/i18n/rules/endonyms.gen.ts +19 -0
  670. package/src/i18n/rules/language.ts +92 -0
  671. package/src/i18n/rules/localizedName.ts +33 -0
  672. package/src/i18n/rules/merge.ts +106 -0
  673. package/src/i18n/rules/scope.ts +127 -0
  674. package/src/i18n/rules/strings.ts +632 -0
  675. package/src/i18n/rules/videoOverlay.ts +121 -0
  676. package/src/i18n/rules/wordForms.ts +95 -0
  677. package/src/i18n/rules/words.gen.ts +277 -0
  678. package/src/icons/index.ts +54 -0
  679. package/src/icons/rules/activities.ts +40 -0
  680. package/src/icons/rules/amenities.ts +250 -0
  681. package/src/icons/rules/artwork.gen.ts +83 -0
  682. package/src/icons/rules/artwork.ts +47 -0
  683. package/src/icons/rules/fallback.ts +21 -0
  684. package/src/icons/rules/lucideMarkers.gen.ts +112 -0
  685. package/src/icons/rules/lucideUi.gen.ts +197 -0
  686. package/src/icons/rules/paint.ts +107 -0
  687. package/src/icons/rules/parse.ts +475 -0
  688. package/src/icons/rules/provider.ts +373 -0
  689. package/src/icons/rules/sprites.ts +54 -0
  690. package/src/icons/rules/ui.ts +348 -0
  691. package/src/icons/rules/waypoints.ts +215 -0
  692. package/src/index.ts +1012 -0
  693. package/src/layers/engines/layersSelection.ts +515 -0
  694. package/src/layers/engines/readoutEngine.ts +131 -0
  695. package/src/layers/index.ts +151 -0
  696. package/src/layers/rules/analysis.ts +135 -0
  697. package/src/layers/rules/enrichment.ts +30 -0
  698. package/src/layers/rules/geoJson.ts +270 -0
  699. package/src/layers/rules/hover.ts +67 -0
  700. package/src/layers/rules/itineraries.ts +182 -0
  701. package/src/layers/rules/layersPanel.ts +237 -0
  702. package/src/layers/rules/order.ts +194 -0
  703. package/src/layers/rules/overlayInstant.ts +49 -0
  704. package/src/layers/rules/overlays.ts +52 -0
  705. package/src/layers/rules/poiPanel.ts +119 -0
  706. package/src/layers/rules/pois.ts +114 -0
  707. package/src/layers/rules/readout.ts +340 -0
  708. package/src/layers/rules/streetView.ts +16 -0
  709. package/src/layers/rules/tileTimestamp.ts +146 -0
  710. package/src/layers/rules/timeSlider.ts +192 -0
  711. package/src/layers/rules/timeWindow.ts +123 -0
  712. package/src/layers/rules/zones.ts +43 -0
  713. package/src/layers/rules/zoom.ts +77 -0
  714. package/src/map-client/index.ts +71 -0
  715. package/src/map-client/rules/mapClient.ts +1943 -0
  716. package/src/navigation/engines/navigation.ts +493 -0
  717. package/src/navigation/index.ts +51 -0
  718. package/src/navigation/rules/followedRoute.ts +78 -0
  719. package/src/navigation/rules/instructions.ts +89 -0
  720. package/src/navigation/rules/itineraryRoute.ts +232 -0
  721. package/src/navigation/rules/offRoute.ts +41 -0
  722. package/src/navigation/rules/progress.ts +230 -0
  723. package/src/navigation/rules/prompts.ts +217 -0
  724. package/src/navigation/rules/routeRequest.ts +98 -0
  725. package/src/navigation/rules/status.ts +142 -0
  726. package/src/navigation/rules/steps.ts +234 -0
  727. package/src/navigation/rules/types.ts +83 -0
  728. package/src/profile/index.ts +307 -0
  729. package/src/profile/rules/amenityBadge.ts +35 -0
  730. package/src/profile/rules/amenityFilter.ts +74 -0
  731. package/src/profile/rules/amenityStacks.ts +66 -0
  732. package/src/profile/rules/axis.ts +89 -0
  733. package/src/profile/rules/axisCulling.ts +83 -0
  734. package/src/profile/rules/axisLookup.ts +180 -0
  735. package/src/profile/rules/climbs.ts +292 -0
  736. package/src/profile/rules/cursorMarker.ts +122 -0
  737. package/src/profile/rules/cursorReadout.ts +104 -0
  738. package/src/profile/rules/curvePlacement.ts +216 -0
  739. package/src/profile/rules/dock.ts +293 -0
  740. package/src/profile/rules/elevation.ts +1263 -0
  741. package/src/profile/rules/instant.ts +89 -0
  742. package/src/profile/rules/intl.ts +237 -0
  743. package/src/profile/rules/legEmphasis.ts +53 -0
  744. package/src/profile/rules/profileColors.ts +66 -0
  745. package/src/profile/rules/profileLayout.ts +59 -0
  746. package/src/profile/rules/profileSlices.ts +55 -0
  747. package/src/profile/rules/routeProfile.ts +475 -0
  748. package/src/profile/rules/rowMatch.ts +50 -0
  749. package/src/profile/rules/scale.ts +650 -0
  750. package/src/profile/rules/scaleFrame.ts +171 -0
  751. package/src/profile/rules/sectionChips.ts +83 -0
  752. package/src/profile/rules/sections.ts +923 -0
  753. package/src/profile/rules/slopeRamp.ts +160 -0
  754. package/src/profile/rules/statStrip.ts +103 -0
  755. package/src/profile/rules/steepness.ts +51 -0
  756. package/src/profile/rules/tableCells.ts +269 -0
  757. package/src/profile/rules/tableCursor.ts +87 -0
  758. package/src/profile/rules/unitPatterns.ts +335 -0
  759. package/src/profile/rules/units.ts +1025 -0
  760. package/src/profile/rules/waypointCard.ts +593 -0
  761. package/src/profile/rules/webAddress.ts +130 -0
  762. package/src/profile/rules/windowSpans.ts +65 -0
  763. package/src/rules/asciiFold.ts +17 -0
  764. package/src/rules/inDevelopment.ts +54 -0
  765. package/src/rules/listeners.ts +62 -0
  766. package/src/rules/timers.ts +9 -0
  767. package/src/rules/types.ts +22 -0
  768. package/src/rules/uuid.ts +87 -0
  769. package/src/seams/engines/geolocateControl.ts +286 -0
  770. package/src/seams/index.ts +50 -0
  771. package/src/seams/rules/clock.ts +169 -0
  772. package/src/seams/rules/geolocation.ts +165 -0
  773. package/src/seams/rules/segmentRoute.ts +187 -0
  774. package/src/search/engines/search.ts +1093 -0
  775. package/src/search/index.ts +114 -0
  776. package/src/search/rules/describe.ts +383 -0
  777. package/src/search/rules/filters.ts +195 -0
  778. package/src/search/rules/highlight.ts +270 -0
  779. package/src/search/rules/pick.ts +90 -0
  780. package/src/search/rules/rows.ts +258 -0
  781. package/src/search/rules/searchFocus.ts +27 -0
  782. package/src/search/rules/searchViewport.ts +44 -0
  783. package/src/search/rules/shown.ts +77 -0
  784. package/src/search/rules/types.ts +340 -0
  785. package/src/stream/rules/reconnectSchedule.ts +83 -0
  786. package/src/style/engines/organizationRead.ts +80 -0
  787. package/src/style/index.ts +63 -0
  788. package/src/style/rules/apply.ts +268 -0
  789. package/src/style/rules/attribution.ts +119 -0
  790. package/src/style/rules/itineraryLine.ts +142 -0
  791. package/src/style/rules/language.ts +668 -0
  792. package/src/style/rules/layout.gen.ts +27 -0
  793. package/src/style/rules/organization.ts +96 -0
  794. package/src/style/rules/paint.ts +143 -0
  795. package/src/style/rules/panelLayout.ts +51 -0
  796. package/src/style/rules/roadAccessColors.ts +29 -0
  797. package/src/style/rules/roadAccessLine.ts +267 -0
  798. package/src/style/rules/segmentColors.ts +207 -0
  799. package/src/testing/catalogs.ts +103 -0
  800. package/src/testing/index.ts +30 -0
  801. package/src/testing/mapClient.ts +241 -0
  802. package/src/testing/mountayaMap.ts +741 -0
  803. package/src/timezone/index.ts +14 -0
  804. package/src/timezone/rules/viewport.ts +875 -0
  805. package/src/units/index.ts +55 -0
  806. package/src/units/rules/conversions.ts +620 -0
  807. package/src/units/rules/preferenceChoices.ts +124 -0
  808. package/src/units/rules/preferences.ts +77 -0
  809. package/src/units/rules/rounding.ts +69 -0
  810. package/src/video/engines/videoRun.ts +654 -0
  811. package/src/video/engines/viewClient.ts +6 -0
  812. package/src/video/index.ts +83 -0
  813. package/src/video/profileOverlay/rules/contract.ts +212 -0
  814. package/src/video/profileOverlay/rules/curve.ts +216 -0
  815. package/src/video/profileOverlay/rules/draw.ts +410 -0
  816. package/src/video/profileOverlay/rules/fonts.ts +54 -0
  817. package/src/video/profileOverlay/rules/graphDesign.ts +690 -0
  818. package/src/video/profileOverlay/rules/minimalDesign.ts +144 -0
  819. package/src/video/profileOverlay/rules/registry.ts +23 -0
  820. package/src/video/profileOverlay/rules/staticLayer.ts +582 -0
  821. package/src/video/profileOverlay/rules/stripDesign.ts +327 -0
  822. package/src/video/profileOverlay/rules/types.ts +78 -0
  823. package/src/video/rules/videoConstants.ts +250 -0
  824. package/src/video/rules/videoEncoder.ts +277 -0
  825. package/src/video/rules/videoFrames.ts +99 -0
  826. package/src/video/rules/videoPreview.ts +185 -0
  827. package/src/video/rules/videoRecorder.ts +746 -0
  828. package/src/video/rules/videoWatermark.ts +155 -0
  829. package/src/video/rules/watermarkMark.ts +40 -0
  830. package/src/view/engines/viewClient.ts +6 -0
  831. package/src/view/index.ts +20 -0
@@ -0,0 +1,4506 @@
1
+ 'use strict';
2
+
3
+ var chunkAFKOABJ4_cjs = require('../chunk-AFKOABJ4.cjs');
4
+ require('../chunk-LS5SJMUO.cjs');
5
+ var chunkSSKSSBWJ_cjs = require('../chunk-SSKSSBWJ.cjs');
6
+ require('../chunk-VZDXX7TT.cjs');
7
+ require('../chunk-NOGDOZIT.cjs');
8
+ var chunkROKNKXA4_cjs = require('../chunk-ROKNKXA4.cjs');
9
+ var chunkIBQJDVHF_cjs = require('../chunk-IBQJDVHF.cjs');
10
+ require('../chunk-UTB4NROA.cjs');
11
+ require('../chunk-JBG6Z6MQ.cjs');
12
+ require('../chunk-FEXWDQIZ.cjs');
13
+ require('../chunk-VQVBEX3Y.cjs');
14
+ require('../chunk-QAL4GZO7.cjs');
15
+ require('../chunk-WQ24RRHL.cjs');
16
+ var chunk7CUBXHAH_cjs = require('../chunk-7CUBXHAH.cjs');
17
+ var chunkEP5OEEVZ_cjs = require('../chunk-EP5OEEVZ.cjs');
18
+ require('../chunk-LUGTMZFN.cjs');
19
+ var chunkV3JEP5AG_cjs = require('../chunk-V3JEP5AG.cjs');
20
+ require('../chunk-PM3XCD2G.cjs');
21
+ require('../chunk-QUMBH3U4.cjs');
22
+ require('../chunk-GIFALLHI.cjs');
23
+ var chunk4F6BJMJC_cjs = require('../chunk-4F6BJMJC.cjs');
24
+ require('../chunk-XOHAXXZA.cjs');
25
+ require('../chunk-G7OP7O2C.cjs');
26
+ var chunkGE6CFCAM_cjs = require('../chunk-GE6CFCAM.cjs');
27
+ require('../chunk-MYEQSESM.cjs');
28
+ var chunkWW4CGS7G_cjs = require('../chunk-WW4CGS7G.cjs');
29
+ var chunkEX2C5K2T_cjs = require('../chunk-EX2C5K2T.cjs');
30
+ var chunk7QN7M667_cjs = require('../chunk-7QN7M667.cjs');
31
+ require('../chunk-AWO5YA7A.cjs');
32
+ require('../chunk-3RVUQ6JN.cjs');
33
+ var chunkNZCZHXYN_cjs = require('../chunk-NZCZHXYN.cjs');
34
+ require('../chunk-VMEE57E5.cjs');
35
+ var chunkL6TZ2HQR_cjs = require('../chunk-L6TZ2HQR.cjs');
36
+ var chunkAG6JV5Z2_cjs = require('../chunk-AG6JV5Z2.cjs');
37
+ var chunkISLB6Y5Q_cjs = require('../chunk-ISLB6Y5Q.cjs');
38
+ var terraDraw = require('terra-draw');
39
+ var terraDrawMaplibreGlAdapter = require('terra-draw-maplibre-gl-adapter');
40
+ var MapLibreGlDirections = require('@maplibre/maplibre-gl-directions');
41
+
42
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
43
+
44
+ var MapLibreGlDirections__default = /*#__PURE__*/_interopDefault(MapLibreGlDirections);
45
+
46
+ // src/editing/rules/positions.ts
47
+ var isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
48
+ var readEditPosition = (position, owner, member, absence = "leave it out") => {
49
+ if (position === void 0 || position === null) {
50
+ return position;
51
+ }
52
+ const written = position;
53
+ const ordinates = Array.isArray(written) ? written : [];
54
+ const [longitude, latitude] = ordinates;
55
+ const isPlaced = isFiniteNumber(longitude) && isFiniteNumber(latitude) && Math.abs(latitude) <= chunkL6TZ2HQR_cjs.LATITUDE_LIMIT;
56
+ if (!isPlaced) {
57
+ throw new chunkISLB6Y5Q_cjs.MountayaElementsError(
58
+ `${owner}: ${member} is ${chunkISLB6Y5Q_cjs.printValue(written)}; pass [longitude, latitude] as two finite numbers, the latitude from -90 to 90, or ${absence}.`
59
+ );
60
+ }
61
+ return position;
62
+ };
63
+ var hexColor = /^#(?:[0-9a-f]{6}|[0-9a-f]{3})$/i;
64
+ var readEditColor = (color, owner) => {
65
+ const written = color;
66
+ if (typeof written !== "string" || !hexColor.test(written)) {
67
+ throw new chunkISLB6Y5Q_cjs.MountayaElementsError(
68
+ `${owner}: color is ${chunkISLB6Y5Q_cjs.printValue(written)}; pass a colour as #rrggbb or #rgb, hexadecimal digits.`
69
+ );
70
+ }
71
+ const digits = written.slice(1);
72
+ return digits.length === 3 ? `#${digits.replace(/./g, (digit) => digit + digit)}` : `#${digits}`;
73
+ };
74
+
75
+ // src/draw/rules/screenSpace.ts
76
+ var projectPointToSegmentPx = (p, a, b) => {
77
+ const dx = b.x - a.x;
78
+ const dy = b.y - a.y;
79
+ const lengthSq = dx * dx + dy * dy;
80
+ if (lengthSq === 0) {
81
+ return { x: a.x, y: a.y };
82
+ }
83
+ const t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSq;
84
+ const clamped = Math.max(0, Math.min(1, t));
85
+ return { x: a.x + clamped * dx, y: a.y + clamped * dy };
86
+ };
87
+ var sqDist = (a, b) => {
88
+ const dx = a.x - b.x;
89
+ const dy = a.y - b.y;
90
+ return dx * dx + dy * dy;
91
+ };
92
+
93
+ // src/draw/rules/insertVertex.ts
94
+ var COORDINATE_PRECISION = 9;
95
+ var clampCoordinatePrecision = (position) => {
96
+ const factor = 10 ** COORDINATE_PRECISION;
97
+ return [
98
+ Math.round((position[0] ?? 0) * factor) / factor,
99
+ Math.round((position[1] ?? 0) * factor) / factor
100
+ ];
101
+ };
102
+ var pointerPosition = (lngLat) => clampCoordinatePrecision([chunkL6TZ2HQR_cjs.wrapLongitudePastRange(lngLat.lng), lngLat.lat]);
103
+ var nearestEdgeInsertion = ({
104
+ line,
105
+ lngLat,
106
+ map,
107
+ thresholdPx
108
+ }) => {
109
+ if (line.length < 2) {
110
+ return null;
111
+ }
112
+ const cursorPx = map.project({ lat: lngLat[1] ?? 0, lng: lngLat[0] ?? 0 });
113
+ let bestDistSq = Number.POSITIVE_INFINITY;
114
+ let bestPx = null;
115
+ let bestIndex = -1;
116
+ for (let i = 1; i < line.length; i++) {
117
+ const prev = line[i - 1];
118
+ const next = line[i];
119
+ if (!prev || !next) {
120
+ continue;
121
+ }
122
+ const a = map.project({ lat: prev[1] ?? 0, lng: prev[0] ?? 0 });
123
+ const b = map.project({ lat: next[1] ?? 0, lng: next[0] ?? 0 });
124
+ const projected = projectPointToSegmentPx(cursorPx, a, b);
125
+ const distSq = sqDist(cursorPx, projected);
126
+ if (distSq < bestDistSq) {
127
+ bestDistSq = distSq;
128
+ bestPx = projected;
129
+ bestIndex = i;
130
+ }
131
+ }
132
+ if (bestPx === null || bestDistSq > thresholdPx * thresholdPx) {
133
+ return null;
134
+ }
135
+ const snapped = map.unproject([bestPx.x, bestPx.y]);
136
+ return { index: bestIndex, lngLat: clampCoordinatePrecision([snapped.lng, snapped.lat]) };
137
+ };
138
+ var nearestVertex = ({ line, lngLat, map }) => {
139
+ if (line.length === 0) {
140
+ return { distancePx: Number.POSITIVE_INFINITY, index: -1 };
141
+ }
142
+ const cursorPx = map.project({ lat: lngLat[1] ?? 0, lng: lngLat[0] ?? 0 });
143
+ let bestDistSq = Number.POSITIVE_INFINITY;
144
+ let bestIndex = -1;
145
+ for (const [index, vertex] of line.entries()) {
146
+ if (!vertex) {
147
+ continue;
148
+ }
149
+ const vertexPx = map.project({ lat: vertex[1] ?? 0, lng: vertex[0] ?? 0 });
150
+ const distSq = sqDist(cursorPx, vertexPx);
151
+ if (distSq < bestDistSq) {
152
+ bestDistSq = distSq;
153
+ bestIndex = index;
154
+ }
155
+ }
156
+ return { distancePx: Math.sqrt(bestDistSq), index: bestIndex };
157
+ };
158
+
159
+ // src/draw/rules/terraDrawShared.ts
160
+ var SELECT_MODE = "select";
161
+ var TERRA_DRAW_MID_POINT_PROPERTY = "midPoint";
162
+ var isProgrammaticChange = (context) => (
163
+ // The kind is read first for a caller the compiler does not check: `in` throws on null and on
164
+ // every primitive.
165
+ typeof context === "object" && context !== null && "origin" in context && context.origin === "api"
166
+ );
167
+ var drawIdStrategy = {
168
+ getId: () => chunk4F6BJMJC_cjs.localId(),
169
+ isValidId: (id) => typeof id === "string" || typeof id === "number"
170
+ };
171
+ var DRAW_REFUSAL_PREFIX = "Feature validation failed: ";
172
+ var DRAW_REFUSAL_REMEDY = "Pass positions of two finite numbers, a longitude from -180 to 180 and a latitude from -90 to 90, and for an area one closed ring with no hole.";
173
+ var refusalOf = ({ engine, remedy = DRAW_REFUSAL_REMEDY, shape }, reason, cause) => new chunkISLB6Y5Q_cjs.MountayaElementsError(
174
+ `${engine}: TerraDraw refuses the ${shape} (${reason ?? "no reason given"}). ${remedy}`,
175
+ cause === void 0 ? void 0 : { cause }
176
+ );
177
+ var addDrawFeature = (draw, feature, subject) => {
178
+ const [verdict] = draw.addFeatures([feature]);
179
+ if (verdict !== void 0 && !verdict.valid) {
180
+ throw refusalOf(subject, verdict.reason);
181
+ }
182
+ };
183
+ var updateDrawGeometry = (draw, id, geometry, subject) => {
184
+ try {
185
+ draw.updateFeatureGeometry(id, geometry);
186
+ } catch (error) {
187
+ if (error instanceof Error && error.message.startsWith(DRAW_REFUSAL_PREFIX)) {
188
+ throw refusalOf(subject, error.message.slice(DRAW_REFUSAL_PREFIX.length), error);
189
+ }
190
+ throw error;
191
+ }
192
+ };
193
+ var applyHeldWrite = (write) => {
194
+ try {
195
+ write();
196
+ } catch (error) {
197
+ chunkWW4CGS7G_cjs.surfaceFault(error);
198
+ }
199
+ };
200
+ var copyPositions = (positions) => positions.map((position) => [...position]);
201
+
202
+ // src/draw/rules/drawFrame.ts
203
+ var frameLongitudeFor = (longitudes) => {
204
+ let west = Number.POSITIVE_INFINITY;
205
+ let east = Number.NEGATIVE_INFINITY;
206
+ for (const longitude of longitudes) {
207
+ if (!Number.isFinite(longitude)) {
208
+ return 0;
209
+ }
210
+ west = Math.min(west, longitude);
211
+ east = Math.max(east, longitude);
212
+ }
213
+ if (west > east) {
214
+ return 0;
215
+ }
216
+ return chunkL6TZ2HQR_cjs.LONGITUDE_LIMIT * Math.round((west + east) / 2 / chunkL6TZ2HQR_cjs.LONGITUDE_LIMIT) + 0;
217
+ };
218
+ var polygonFrameLongitude = (geometry) => frameLongitudeFor(geometry.coordinates.flatMap((ring) => ring.map(([lng = 0]) => lng)));
219
+ var intoFrame = (position, frameLongitude) => clampCoordinatePrecision([(position[0] ?? 0) - frameLongitude, position[1] ?? 0]);
220
+ var outOfFrame = (position, frameLongitude) => clampCoordinatePrecision([(position[0] ?? 0) + frameLongitude, position[1] ?? 0]);
221
+ var shownCopyOffset = (frameLongitude, centerLongitude) => chunkAG6JV5Z2_cjs.DEGREES_PER_TURN * Math.round((centerLongitude - frameLongitude) / chunkAG6JV5Z2_cjs.DEGREES_PER_TURN) + 0;
222
+
223
+ // src/draw/engines/framedAdapter.ts
224
+ var shiftedBy = (feature, degrees) => {
225
+ const { geometry } = feature;
226
+ switch (geometry.type) {
227
+ case "Point": {
228
+ const [lng = 0, lat = 0] = geometry.coordinates;
229
+ return { ...feature, geometry: { coordinates: [lng + degrees, lat], type: "Point" } };
230
+ }
231
+ case "LineString":
232
+ return {
233
+ ...feature,
234
+ geometry: {
235
+ coordinates: geometry.coordinates.map(([lng = 0, lat = 0]) => [lng + degrees, lat]),
236
+ type: "LineString"
237
+ }
238
+ };
239
+ case "Polygon":
240
+ return {
241
+ ...feature,
242
+ geometry: {
243
+ coordinates: geometry.coordinates.map(
244
+ (ring) => ring.map(([lng = 0, lat = 0]) => [lng + degrees, lat])
245
+ ),
246
+ type: "Polygon"
247
+ }
248
+ };
249
+ }
250
+ };
251
+ var inertSource = { setData: () => {
252
+ } };
253
+ var styleGuarded = (map) => {
254
+ const getSource = (id) => map.getSource(id) ?? inertSource;
255
+ const removeLayer = (id) => map.getLayer(id) === void 0 ? map : map.removeLayer(id);
256
+ const removeSource = (id) => map.getSource(id) === void 0 ? map : map.removeSource(id);
257
+ const bound = /* @__PURE__ */ new Map();
258
+ return new Proxy(map, {
259
+ get: (target, key) => {
260
+ if (key === "getSource") {
261
+ return getSource;
262
+ }
263
+ if (key === "removeLayer") {
264
+ return removeLayer;
265
+ }
266
+ if (key === "removeSource") {
267
+ return removeSource;
268
+ }
269
+ const value = Reflect.get(target, key, target);
270
+ if (typeof value !== "function") {
271
+ return value;
272
+ }
273
+ let method = bound.get(key);
274
+ if (method === void 0) {
275
+ method = value.bind(target);
276
+ bound.set(key, method);
277
+ }
278
+ return method;
279
+ }
280
+ });
281
+ };
282
+ var FramedMapLibreAdapter = class extends terraDrawMaplibreGlAdapter.TerraDrawMapLibreGLAdapter {
283
+ /**
284
+ * @param config The map the edit draws on and the prefix its sources and layers are named
285
+ * under, as TerraDraw's MapLibre adapter takes them.
286
+ * @param frame The frame of the edit. The adapter reads it on every call and never writes it.
287
+ */
288
+ constructor(config, frame) {
289
+ super({ ...config, map: styleGuarded(config.map) });
290
+ this.frame = frame;
291
+ this.framedMap = config.map;
292
+ }
293
+ frame;
294
+ framedMap;
295
+ /**
296
+ * project answers the pixel a position the library holds is drawn at, on the copy of the world
297
+ * the map shows.
298
+ */
299
+ project(lng, lat) {
300
+ return super.project(lng + this.worldOffset(), lat);
301
+ }
302
+ /**
303
+ * unproject answers the position the library holds for a pixel of the map's container. It is
304
+ * what a pointer event's position is read through.
305
+ */
306
+ unproject(x, y) {
307
+ const { lat, lng } = super.unproject(x, y);
308
+ return { lat, lng: lng - this.worldOffset() };
309
+ }
310
+ /**
311
+ * render draws what the library holds at its world longitude: every feature moved east by the
312
+ * frame, as copies, since the library keeps reading the ones it handed over.
313
+ */
314
+ render(changes, styling) {
315
+ const degrees = this.frame.longitude;
316
+ if (degrees === 0) {
317
+ super.render(changes, styling);
318
+ return;
319
+ }
320
+ super.render(
321
+ {
322
+ created: changes.created.map((feature) => shiftedBy(feature, degrees)),
323
+ deletedIds: changes.deletedIds,
324
+ unchanged: changes.unchanged.map((feature) => shiftedBy(feature, degrees)),
325
+ updated: changes.updated.map((feature) => shiftedBy(feature, degrees))
326
+ },
327
+ styling
328
+ );
329
+ }
330
+ /**
331
+ * worldOffset is what separates a longitude the library holds from the one the map shows it
332
+ * at: the frame, and the copy of the world on screen.
333
+ */
334
+ worldOffset() {
335
+ const frameLongitude = this.frame.longitude;
336
+ if (frameLongitude === 0) {
337
+ return 0;
338
+ }
339
+ return frameLongitude + shownCopyOffset(frameLongitude, this.framedMap.getCenter().lng);
340
+ }
341
+ };
342
+
343
+ // src/draw/engines/boundaryEngine.ts
344
+ var BOUNDARY_DRAW_MODE_NAME = "rectangle";
345
+ var BOUNDARY_TERRADRAW_PREFIX = "td-boundary";
346
+ var BOUNDARY_FILL_LAYER_ID = `${BOUNDARY_TERRADRAW_PREFIX}-polygon`;
347
+ var BOUNDARY_VERTEX_LAYER_ID = `${BOUNDARY_TERRADRAW_PREFIX}-point`;
348
+ var BOUNDARY_RING_CORNERS = 4;
349
+ var boundaryRefusal = { engine: "TerraDrawBoundaryEngine", shape: "box" };
350
+ var buildBoundaryDrawMode = () => new terraDraw.TerraDrawRectangleMode();
351
+ var buildBoundarySelectFlags = () => ({
352
+ [BOUNDARY_DRAW_MODE_NAME]: {
353
+ feature: {
354
+ coordinates: { deletable: false, draggable: true, midpoints: false },
355
+ draggable: true
356
+ }
357
+ }
358
+ });
359
+ var defaultBoundaryDrawFactory = ({ map, prefixId }) => new terraDraw.TerraDraw({
360
+ adapter: new FramedMapLibreAdapter({ map, prefixId }, { longitude: 0 }),
361
+ idStrategy: drawIdStrategy,
362
+ modes: [
363
+ buildBoundaryDrawMode(),
364
+ new terraDraw.TerraDrawSelectMode({ flags: buildBoundarySelectFlags() })
365
+ ]
366
+ });
367
+ var ringCorners = (geometry) => {
368
+ const ring = geometry.coordinates[0];
369
+ if (!ring || ring.length !== BOUNDARY_RING_CORNERS + 1) {
370
+ return null;
371
+ }
372
+ return ring.slice(0, BOUNDARY_RING_CORNERS);
373
+ };
374
+ var isAxisAlignedRectangle = (corners) => {
375
+ const lngs = new Set(corners.map((corner) => corner[0]));
376
+ const lats = new Set(corners.map((corner) => corner[1]));
377
+ if (lngs.size > 2 || lats.size > 2) {
378
+ return false;
379
+ }
380
+ const held = new Set(corners.map((corner) => `${corner[0]}|${corner[1]}`));
381
+ return [...lngs].every((lng) => [...lats].every((lat) => held.has(`${lng}|${lat}`)));
382
+ };
383
+ var cornersFromCornerDrag = (previous, corners) => {
384
+ if (!previous || previous.length !== corners.length) {
385
+ return null;
386
+ }
387
+ const moved = corners.reduce((indices, corner, index) => {
388
+ const before = previous[index];
389
+ if (!before || before[0] !== corner[0] || before[1] !== corner[1]) {
390
+ indices.push(index);
391
+ }
392
+ return indices;
393
+ }, []);
394
+ const movedIndex = moved.length === 1 ? moved[0] : void 0;
395
+ if (movedIndex === void 0) {
396
+ return null;
397
+ }
398
+ const besideIndex = (movedIndex + 1) % BOUNDARY_RING_CORNERS;
399
+ const anchorIndex = (movedIndex + 2) % BOUNDARY_RING_CORNERS;
400
+ const acrossIndex = (movedIndex + 3) % BOUNDARY_RING_CORNERS;
401
+ const [draggedLng, draggedLat] = corners[movedIndex] ?? [];
402
+ const [anchorLng, anchorLat] = corners[anchorIndex] ?? [];
403
+ if (draggedLng === void 0 || draggedLat === void 0 || anchorLng === void 0 || anchorLat === void 0) {
404
+ return null;
405
+ }
406
+ const [west, south, east, north] = chunk7QN7M667_cjs.normalizeBoundingBox([
407
+ draggedLng,
408
+ draggedLat,
409
+ anchorLng,
410
+ anchorLat
411
+ ]);
412
+ const draggedIsWest = draggedLng <= anchorLng;
413
+ const draggedIsSouth = draggedLat <= anchorLat;
414
+ const dragged = [draggedIsWest ? west : east, draggedIsSouth ? south : north];
415
+ const anchor = [draggedIsWest ? east : west, draggedIsSouth ? north : south];
416
+ const besideSharesLng = previous[besideIndex]?.[0] === previous[movedIndex]?.[0];
417
+ const onDraggedMeridian = [dragged[0] ?? 0, anchor[1] ?? 0];
418
+ const onDraggedParallel = [anchor[0] ?? 0, dragged[1] ?? 0];
419
+ const rebuilt = [...corners];
420
+ rebuilt[movedIndex] = dragged;
421
+ rebuilt[anchorIndex] = anchor;
422
+ rebuilt[besideIndex] = besideSharesLng ? onDraggedMeridian : onDraggedParallel;
423
+ rebuilt[acrossIndex] = besideSharesLng ? onDraggedParallel : onDraggedMeridian;
424
+ return rebuilt;
425
+ };
426
+ var closedRing = (corners) => ({
427
+ coordinates: [[...corners, ...corners.slice(0, 1)]],
428
+ type: "Polygon"
429
+ });
430
+ var drawableBox = (bbox) => {
431
+ const [west, south, east, north] = chunk7QN7M667_cjs.normalizeBoundingBox(bbox);
432
+ const [drawnWest, drawnEast] = west === chunkL6TZ2HQR_cjs.LONGITUDE_LIMIT && east > chunkL6TZ2HQR_cjs.LONGITUDE_LIMIT ? [-chunkL6TZ2HQR_cjs.LONGITUDE_LIMIT, east - west - chunkL6TZ2HQR_cjs.LONGITUDE_LIMIT] : [west, Math.min(east, chunkL6TZ2HQR_cjs.LONGITUDE_LIMIT)];
433
+ const southWest = clampCoordinatePrecision([drawnWest, south]);
434
+ const northEast = clampCoordinatePrecision([drawnEast, north]);
435
+ return [southWest[0], southWest[1], northEast[0], northEast[1]];
436
+ };
437
+ var sameBoundingBox = (a, b) => {
438
+ if (a === null || b === null) {
439
+ return a === b;
440
+ }
441
+ return a.every((value, index) => value === b[index]);
442
+ };
443
+ var TerraDrawBoundaryEngine = class {
444
+ constructor(map, options, emitDraft, createDraw = defaultBoundaryDrawFactory, events, cursor) {
445
+ this.map = map;
446
+ this.emitDraft = emitDraft;
447
+ this.featureId = options.featureId;
448
+ this.activeFeatureId = options.featureId;
449
+ this.color = readEditColor(options.color, "TerraDrawBoundaryEngine");
450
+ this.events = events ?? null;
451
+ this.cursor = cursor ?? null;
452
+ this.changeHandler = (ids, _type, context) => {
453
+ this.handleChange(ids, isProgrammaticChange(context));
454
+ };
455
+ this.finishHandler = (id) => {
456
+ this.handleFinish(id);
457
+ };
458
+ this.draw = createDraw({ map: this.map, prefixId: BOUNDARY_TERRADRAW_PREFIX });
459
+ this.draw.start();
460
+ this.attachDrawListeners();
461
+ if (options.seedBbox) {
462
+ const seed = drawableBox(options.seedBbox);
463
+ this.lastEmitted = seed;
464
+ try {
465
+ this.seedFeature(seed);
466
+ } catch (error) {
467
+ this.dispose();
468
+ throw error;
469
+ }
470
+ } else {
471
+ this.armDrawMode();
472
+ }
473
+ this.applyBoundaryDraftStyle(this.color);
474
+ this.detachHoverCursor = this.attachHoverCursor();
475
+ this.detachCursorReassert = this.attachCursorReassert();
476
+ }
477
+ map;
478
+ emitDraft;
479
+ draw;
480
+ featureId;
481
+ // The id the drawn box actually lives under in the TerraDraw store. It starts at
482
+ // featureId — the id a seeded edit adds the saved box under — but a create-draw
483
+ // produces a feature under the id strategy's TerraDraw-assigned id, so the finish
484
+ // handler re-points this to that drawn id. Every store read/write keys off this
485
+ // field. The type widens to string | number because the id strategy can mint
486
+ // either kind (terra-draw's FeatureId is not re-exported from the package entry).
487
+ activeFeatureId;
488
+ // Whether a box currently exists. It gates the draw-vs-select mode, the cursor
489
+ // lock, and the create-draw's one-shot finish handling; clearDraft flips it back so
490
+ // the surface can be drawn on again.
491
+ hasBox = false;
492
+ // The box's corners as of the last observed change, so a corner drag can be told
493
+ // from a wholesale move and the drag's anchor identified. Null until a box exists.
494
+ lastCorners = null;
495
+ // The last extent handed to the sink, so the programmatic echo of the engine's own
496
+ // re-rectangling write is dropped instead of reaching the consumer twice per frame.
497
+ lastEmitted = null;
498
+ // The current draft color, held so a base-map switch replay can re-apply it.
499
+ color;
500
+ // The map event engine the cursor listeners detach through; held so dispose/replay
501
+ // tears them down by reference. Null on the factory-only unit-test path.
502
+ events;
503
+ // The cursor controller this engine locks the create cursor on and layers the
504
+ // corner/grab overrides above. Null on the factory-only unit-test path.
505
+ cursor;
506
+ detachHoverCursor = null;
507
+ // Whether a drag has reported a live frame its release has not settled yet.
508
+ gestureOpen = false;
509
+ // Whether the engine is writing a repaired rectangle back, whose echo it does not read.
510
+ repairing = false;
511
+ detachCursorReassert = null;
512
+ // The stable change/finish listener references, held so the pre-swap detach can `off`
513
+ // exactly what the constructor registered. A TerraDraw listener lives on the instance
514
+ // rather than on the adapter, so `stop()` does NOT drop it — an inline closure per
515
+ // replay would stack one more binding on every base-map switch.
516
+ changeHandler;
517
+ finishHandler;
518
+ // The box read off the store by {@link detachBeforeStyleReload}, held for the replay to
519
+ // re-seed from. It exists because stopping TerraDraw EMPTIES the store: `stop()`
520
+ // unregisters the adapter, whose base `unregister()` ends in its own `clear()`, which
521
+ // calls back through `onClear` into `_store.clear()`. So by the time the replay runs
522
+ // there is nothing left to read, and a replay that re-registered the adapter correctly
523
+ // still came back to five empty layers. Null while no swap is in flight.
524
+ detachedBbox = null;
525
+ // Whether TerraDraw is stopped for a style reload: raised by the detach, lowered by the replay.
526
+ // While it is raised the store is empty and refuses every write, so the engine reads and
527
+ // writes what it holds itself.
528
+ detached = false;
529
+ // The latest write made while TerraDraw is stopped for a style reload, applied when the replay
530
+ // ends: a box as it is drawn, or null for a clear. Undefined when none was made.
531
+ heldDraft;
532
+ // Whether the edit is over. A disposed engine has no replay to come, so a box or a clear
533
+ // applied to it inside the detach window is held by nothing.
534
+ disposed = false;
535
+ setDraftStyle(style) {
536
+ if (this.disposed) {
537
+ return;
538
+ }
539
+ this.color = readEditColor(style.color, "TerraDrawBoundaryEngine");
540
+ if (this.detached) {
541
+ return;
542
+ }
543
+ this.applyBoundaryDraftStyle(this.color);
544
+ }
545
+ readDraft() {
546
+ if (this.disposed) {
547
+ return null;
548
+ }
549
+ if (this.detached) {
550
+ const held = this.heldDraft === void 0 ? this.detachedBbox : this.heldDraft;
551
+ return held === null ? null : [...held];
552
+ }
553
+ return this.currentBbox();
554
+ }
555
+ applyDraft(bbox) {
556
+ if (this.disposed) {
557
+ return;
558
+ }
559
+ const normalized = drawableBox(bbox);
560
+ if (this.detached) {
561
+ this.heldDraft = normalized;
562
+ return;
563
+ }
564
+ if (this.hasBox) {
565
+ updateDrawGeometry(
566
+ this.draw,
567
+ this.activeFeatureId,
568
+ chunkNZCZHXYN_cjs.boundingBoxToPolygon(normalized),
569
+ boundaryRefusal
570
+ );
571
+ return;
572
+ }
573
+ this.seedFeature(normalized);
574
+ this.emitBbox(normalized, true, "settled");
575
+ }
576
+ clearDraft() {
577
+ if (this.disposed) {
578
+ return;
579
+ }
580
+ if (this.detached) {
581
+ this.heldDraft = null;
582
+ return;
583
+ }
584
+ this.draw.clear();
585
+ this.hasBox = false;
586
+ this.lastCorners = null;
587
+ this.activeFeatureId = this.featureId;
588
+ this.armDrawMode();
589
+ this.gestureOpen = false;
590
+ this.emitBbox(null, false, "settled");
591
+ }
592
+ dispose() {
593
+ this.detachCursorReassert?.();
594
+ this.detachCursorReassert = null;
595
+ this.detachHoverCursor?.();
596
+ this.detachHoverCursor = null;
597
+ this.cursor?.popOverride();
598
+ this.cursor?.unlock();
599
+ this.detachDrawListeners();
600
+ if (this.draw.enabled) {
601
+ this.draw.clear();
602
+ }
603
+ this.draw.stop();
604
+ this.disposed = true;
605
+ this.heldDraft = void 0;
606
+ this.detachedBbox = null;
607
+ }
608
+ /**
609
+ * detachBeforeStyleReload stops TerraDraw before the swap, so the replay's `start()`
610
+ * actually re-registers the adapter. See {@link EditEngine.detachBeforeStyleReload}
611
+ * for why the pair is needed and why the order is load-bearing: the adapter's
612
+ * `unregister()` removes five layers and three sources unguarded, which succeeds
613
+ * silently on the outgoing style and is noisy-then-fatal on the incoming one.
614
+ *
615
+ * The box is read off the store FIRST, because `stop()` empties it — the adapter's base
616
+ * `unregister()` ends in its own `clear()`, which calls back through `onClear` into
617
+ * `_store.clear()`. And the listeners come off before that, so the deletion the clear
618
+ * emits is not turned into a draft saying the user erased their box mid-swap.
619
+ */
620
+ detachBeforeStyleReload() {
621
+ if (this.disposed) {
622
+ return;
623
+ }
624
+ if (this.detached) {
625
+ return;
626
+ }
627
+ this.detached = true;
628
+ this.detachedBbox = this.currentBbox();
629
+ this.detachDrawListeners();
630
+ this.draw.stop();
631
+ }
632
+ /**
633
+ * replayAfterStyleReload re-renders the active edit after a base-map switch wiped
634
+ * the style. It re-attaches what setStyle tore down: the library's layers + change
635
+ * listeners, the box, its color, and the hover cursor over its corners and interior (the
636
+ * TerraDraw point/polygon layers are rebuilt). A no-op-safe rebuild — the previous
637
+ * detaches already ran when the style reload tore the layers down.
638
+ *
639
+ * It is the second half of a pair: {@link detachBeforeStyleReload} must have stopped
640
+ * the instance before the swap, or the `start()` below returns early and re-registers
641
+ * nothing.
642
+ */
643
+ replayAfterStyleReload() {
644
+ if (this.disposed) {
645
+ return;
646
+ }
647
+ const bbox = this.detachedBbox ?? this.currentBbox();
648
+ this.detachedBbox = null;
649
+ this.detached = false;
650
+ this.draw.start();
651
+ this.attachDrawListeners();
652
+ if (bbox) {
653
+ this.draw.clear();
654
+ this.seedFeature(bbox);
655
+ } else {
656
+ this.armDrawMode();
657
+ }
658
+ this.applyBoundaryDraftStyle(this.color);
659
+ this.detachHoverCursor?.();
660
+ this.detachHoverCursor = this.attachHoverCursor();
661
+ this.detachCursorReassert?.();
662
+ this.detachCursorReassert = this.attachCursorReassert();
663
+ const held = this.heldDraft;
664
+ this.heldDraft = void 0;
665
+ if (held === null) {
666
+ applyHeldWrite(() => this.clearDraft());
667
+ } else if (held !== void 0) {
668
+ applyHeldWrite(() => this.applyDraft(held));
669
+ }
670
+ }
671
+ /**
672
+ * attachDrawListeners wires the change + finish listeners onto the (re-)started
673
+ * TerraDraw instance. Shared by the constructor and the style-reload replay so both
674
+ * paths subscribe identically.
675
+ */
676
+ attachDrawListeners() {
677
+ this.draw.on("change", this.changeHandler);
678
+ this.draw.on("finish", this.finishHandler);
679
+ }
680
+ /**
681
+ * detachDrawListeners drops the change + finish listeners by reference. The detach
682
+ * half of {@link attachDrawListeners}, needed because a TerraDraw listener lives on
683
+ * the instance and not on the adapter: `stop()` unregisters the adapter and leaves
684
+ * every listener attached.
685
+ */
686
+ detachDrawListeners() {
687
+ this.draw.off("change", this.changeHandler);
688
+ this.draw.off("finish", this.finishHandler);
689
+ }
690
+ /**
691
+ * handleChange is the single fan-out the change listener calls on every geometry
692
+ * change. It reads the box back, repairs it when a corner drag sheared it out of
693
+ * alignment, and emits the resulting extent.
694
+ *
695
+ * The repair is what makes corner-resizing possible at all: TerraDraw drags each
696
+ * coordinate independently, so the store briefly holds a general quad. Rewriting it
697
+ * as the box spanning the dragged corner and the one opposite it happens within the
698
+ * same change, so the user sees a rectangle tracking the pointer rather than a
699
+ * shearing quad.
700
+ */
701
+ handleChange(ids, programmatic) {
702
+ if (this.repairing) {
703
+ return;
704
+ }
705
+ if (!ids.includes(this.activeFeatureId)) {
706
+ return;
707
+ }
708
+ const geometry = this.geometryOf(this.activeFeatureId);
709
+ if (!geometry) {
710
+ return;
711
+ }
712
+ const corners = ringCorners(geometry);
713
+ if (!corners) {
714
+ return;
715
+ }
716
+ if (!isAxisAlignedRectangle(corners)) {
717
+ const dragged = cornersFromCornerDrag(this.lastCorners, corners);
718
+ const repairedPolygon = dragged ? closedRing(dragged) : chunkNZCZHXYN_cjs.boundingBoxToPolygon(this.extentOf(geometry));
719
+ const repaired = this.extentOf(repairedPolygon);
720
+ this.lastCorners = ringCorners(repairedPolygon);
721
+ this.emitChange(repaired, programmatic);
722
+ this.repairing = true;
723
+ try {
724
+ this.draw.updateFeatureGeometry(this.activeFeatureId, repairedPolygon);
725
+ } finally {
726
+ this.repairing = false;
727
+ }
728
+ return;
729
+ }
730
+ this.lastCorners = corners;
731
+ this.emitChange(this.extentOf(geometry), programmatic);
732
+ }
733
+ /**
734
+ * emitChange reports a changed box with the phase its origin gives it. A change TerraDraw
735
+ * makes under the pointer (a corner drag, a whole-box drag) is one frame of a gesture the
736
+ * select mode's `finish` closes, so it is `live` and {@link handleFinish} settles it. A
737
+ * store-API write is whole when it lands, so it is `settled`, and it closes a drag still open:
738
+ * it replaces the box the drag moved.
739
+ */
740
+ emitChange(bbox, programmatic) {
741
+ const phase = programmatic ? "settled" : "live";
742
+ this.gestureOpen = phase === "live";
743
+ this.emitBbox(bbox, programmatic, phase);
744
+ }
745
+ /**
746
+ * handleFinish runs when TerraDraw completes a drawn rectangle. It is the
747
+ * create-draw's completion seam: the drawn feature carries the id strategy's
748
+ * TerraDraw-assigned id, not featureId, so until this fires the feature is invisible
749
+ * to the featureId-keyed reads and no draft emits. The handler adopts the drawn id,
750
+ * switches into the select mode and selects the feature (so only ONE box is ever
751
+ * drawn and it becomes resizable), hands the cursor over from "draw here" to the
752
+ * manipulation affordances, and emits the finished extent so the consumer's confirm
753
+ * enables.
754
+ *
755
+ * Guarded to run once per box: a resize after the switch flows through `change`, and
756
+ * a seeded edit never fires finish at all. A redraw re-opens the guard through
757
+ * clearDraft.
758
+ */
759
+ handleFinish(id) {
760
+ if (this.hasBox) {
761
+ if (id === this.activeFeatureId) {
762
+ this.settleGesture();
763
+ }
764
+ return;
765
+ }
766
+ const geometry = this.geometryOf(id);
767
+ const corners = geometry ? ringCorners(geometry) : null;
768
+ if (!geometry || !corners) {
769
+ return;
770
+ }
771
+ this.activeFeatureId = id;
772
+ this.adoptBox(corners);
773
+ this.draw.selectFeature(id);
774
+ this.emitBbox(this.extentOf(geometry), false, "settled");
775
+ }
776
+ /**
777
+ * settleGesture reports the box once more, `settled` and interactive, when a drag that
778
+ * reported `live` frames is released, and does nothing when none is open: the select mode
779
+ * finishes every pointer release, a release that moved nothing included.
780
+ */
781
+ settleGesture() {
782
+ if (!this.gestureOpen) {
783
+ return;
784
+ }
785
+ this.gestureOpen = false;
786
+ const bbox = this.currentBbox();
787
+ if (bbox !== null) {
788
+ this.emitBbox(bbox, false, "settled", true);
789
+ }
790
+ }
791
+ /**
792
+ * seedFeature adds the box feature under featureId, selects it, and shows its corner
793
+ * handles. The feature carries the draw mode name in `properties.mode` so TerraDraw
794
+ * renders it under the rectangle mode's styling.
795
+ */
796
+ seedFeature(bbox) {
797
+ const feature = {
798
+ geometry: chunkNZCZHXYN_cjs.boundingBoxToPolygon(bbox),
799
+ id: this.featureId,
800
+ properties: { mode: BOUNDARY_DRAW_MODE_NAME },
801
+ type: "Feature"
802
+ };
803
+ addDrawFeature(this.draw, feature, boundaryRefusal);
804
+ this.activeFeatureId = this.featureId;
805
+ const corners = ringCorners(chunkNZCZHXYN_cjs.boundingBoxToPolygon(bbox));
806
+ this.adoptBox(corners ?? []);
807
+ this.draw.selectFeature(this.featureId);
808
+ }
809
+ /**
810
+ * adoptBox moves the surface into its "a box exists" state: it records the corners,
811
+ * switches into the select mode so no second box can be started, and releases the
812
+ * create cursor — from here the affordances are the corner-drag and whole-box-grab
813
+ * overrides, and a locked "draw here" cursor would misdescribe them.
814
+ */
815
+ adoptBox(corners) {
816
+ this.hasBox = true;
817
+ this.lastCorners = corners;
818
+ this.draw.setMode(SELECT_MODE);
819
+ this.cursor?.unlock();
820
+ }
821
+ /**
822
+ * armDrawMode moves the surface into its empty state: the rectangle draw mode so the
823
+ * next gesture draws a box, and the "+" create cursor pinned so the empty canvas
824
+ * reads as drawable. Without the explicit setMode, start() leaves TerraDraw in its
825
+ * no-op default mode and the canvas cannot draw at all.
826
+ */
827
+ armDrawMode() {
828
+ this.draw.setMode(BOUNDARY_DRAW_MODE_NAME);
829
+ this.cursor?.lock(chunkIBQJDVHF_cjs.ZONE_CREATE_CURSOR);
830
+ }
831
+ /**
832
+ * emitBbox hands an extent to the sink, dropping an emission that carries no news.
833
+ * The dedupe is load-bearing rather than cosmetic: the engine repairs a sheared box
834
+ * by writing the corrected rectangle back, and that write fires its own api-origin
835
+ * change carrying the extent just emitted. Without the guard every corner-drag frame
836
+ * would reach the consumer twice.
837
+ */
838
+ emitBbox(bbox, programmatic, phase, closesGesture = false) {
839
+ if (!closesGesture && sameBoundingBox(bbox, this.lastEmitted)) {
840
+ return;
841
+ }
842
+ this.lastEmitted = bbox;
843
+ chunkWW4CGS7G_cjs.notifyListeners([this.emitDraft], { bbox, phase, programmatic });
844
+ }
845
+ /**
846
+ * currentBbox reads the box's current extent from the TerraDraw store, or null when
847
+ * no box exists (before the first draw, after a clear).
848
+ */
849
+ currentBbox() {
850
+ const geometry = this.geometryOf(this.activeFeatureId);
851
+ return geometry ? this.extentOf(geometry) : null;
852
+ }
853
+ /**
854
+ * extentOf reduces a polygon to its normalized [west, south, east, north] extent, planar over
855
+ * its outer ring as the engine drew it: a box wider than half the world keeps its sides, where
856
+ * `boundsOf` would read it across the antimeridian. For a rectangle that is a lossless read;
857
+ * for the transient quad a mid-drag store holds it is the fallback the repair path degrades to.
858
+ *
859
+ * The ring is folded position by position rather than spread into `Math.min` and `Math.max`,
860
+ * which throw a RangeError once a ring is longer than a call's argument list.
861
+ */
862
+ extentOf(geometry) {
863
+ let west = Number.POSITIVE_INFINITY;
864
+ let south = Number.POSITIVE_INFINITY;
865
+ let east = Number.NEGATIVE_INFINITY;
866
+ let north = Number.NEGATIVE_INFINITY;
867
+ for (const [lng, lat] of geometry.coordinates[0] ?? []) {
868
+ if (lng === void 0 || lat === void 0 || !Number.isFinite(lng) || !Number.isFinite(lat)) {
869
+ continue;
870
+ }
871
+ west = Math.min(west, lng);
872
+ south = Math.min(south, lat);
873
+ east = Math.max(east, lng);
874
+ north = Math.max(north, lat);
875
+ }
876
+ return chunk7QN7M667_cjs.normalizeBoundingBox(west <= east ? [west, south, east, north] : [0, 0, 0, 0]);
877
+ }
878
+ /**
879
+ * geometryOf reads one feature's shape from the TerraDraw store by id and narrows it
880
+ * to a Polygon — or null when the feature is gone or its kind does not match (a
881
+ * transient state mid-draw, or the Point geometry the store union also admits).
882
+ */
883
+ geometryOf(id) {
884
+ const feature = this.draw.getSnapshotFeature(id);
885
+ if (!feature) {
886
+ return null;
887
+ }
888
+ const geometry = feature.geometry;
889
+ return geometry.type === "Polygon" ? geometry : null;
890
+ }
891
+ /**
892
+ * applyBoundaryDraftStyle pushes the draft color onto the rectangle draw mode and the
893
+ * select mode so the box's fill, outline, and corner handles all render in it.
894
+ * updateModeOptions accepts a partial options object and runs while the modes are
895
+ * started, recoloring live. The color was held to `#rrggbb` as it was handed over
896
+ * ({@link readEditColor}).
897
+ */
898
+ applyBoundaryDraftStyle(hex) {
899
+ this.draw.updateModeOptions(BOUNDARY_DRAW_MODE_NAME, {
900
+ styles: { fillColor: hex, fillOpacity: 0.2, outlineColor: hex, outlineWidth: 2 }
901
+ });
902
+ this.draw.updateModeOptions(SELECT_MODE, {
903
+ styles: {
904
+ selectedLineStringColor: hex,
905
+ selectedPointColor: hex,
906
+ selectedPolygonColor: hex,
907
+ selectedPolygonOutlineColor: hex,
908
+ selectionPointColor: hex
909
+ }
910
+ });
911
+ }
912
+ /**
913
+ * attachCursorReassert subscribes the shared map-level mousemove re-assert that
914
+ * re-pins the held create cursor (or an override above it) after a cursor clobber on
915
+ * a plain move. A no-op (null detach) when the event engine or cursor controller is
916
+ * absent — the factory-only unit-test path.
917
+ */
918
+ attachCursorReassert() {
919
+ if (!this.events || !this.cursor) {
920
+ return null;
921
+ }
922
+ return chunkIBQJDVHF_cjs.attachCursorReassert(this.events, this.cursor);
923
+ }
924
+ /**
925
+ * attachHoverCursor layers the edit's hover cursor over whatever cursor is held, through the
926
+ * shared {@link attachEditHoverCursor}: the `move` cursor over a corner handle, which a drag
927
+ * resizes the box by, and grab (grabbing while pressed) over the box's interior, which a drag
928
+ * repositions. A corner wins over the interior it sits on: resize beats reposition. The box
929
+ * carries no insert midpoint (a rectangle has exactly four corners), so the midpoint property
930
+ * never appears on its handles. A no-op (empty detach) on the factory-only unit-test path.
931
+ */
932
+ attachHoverCursor() {
933
+ const events = this.events;
934
+ const cursor = this.cursor;
935
+ if (!events || !cursor) {
936
+ return () => {
937
+ };
938
+ }
939
+ return chunkIBQJDVHF_cjs.attachEditHoverCursor({
940
+ cursor,
941
+ events,
942
+ layers: [
943
+ { kind: "handle", layerId: BOUNDARY_VERTEX_LAYER_ID, midpointProperty: "midPoint" },
944
+ { kind: "interior", layerId: BOUNDARY_FILL_LAYER_ID }
945
+ ],
946
+ map: this.map
947
+ });
948
+ }
949
+ };
950
+
951
+ // src/draw/rules/seeds.ts
952
+ var sameOrdinate = (a, b) => a === b || Number.isNaN(a) && Number.isNaN(b);
953
+ var samePoint = (a, b) => sameOrdinate(a[0], b[0]) && sameOrdinate(a[1], b[1]);
954
+ var pointText = (position) => `[${position.slice(0, 2).join(", ")}]`;
955
+ var refusePinMismatch = (seed, startPin, endPin, owner) => {
956
+ if (seed.length < chunkEX2C5K2T_cjs.SEGMENT_MIN_VIAS) {
957
+ if (startPin && endPin && !samePoint(startPin, endPin)) {
958
+ throw new chunkISLB6Y5Q_cjs.MountayaElementsError(
959
+ `${owner}: pinnedStart is ${pointText(startPin)} and pinnedEnd is ${pointText(endPin)}, with fewer than two seedVias. An edit pinned at both ends opens on the line between them: pass seedVias that start at pinnedStart and end at pinnedEnd.`
960
+ );
961
+ }
962
+ return;
963
+ }
964
+ const head = seed[0];
965
+ if (startPin && head && !samePoint(head, startPin)) {
966
+ throw new chunkISLB6Y5Q_cjs.MountayaElementsError(
967
+ `${owner}: seedVias starts at ${pointText(head)} and pinnedStart is ${pointText(startPin)}. A pinned start is the line's first via: pass one position for both, or leave pinnedStart out to leave the start free.`
968
+ );
969
+ }
970
+ const tail = seed.at(-1);
971
+ if (endPin && tail && !samePoint(tail, endPin)) {
972
+ throw new chunkISLB6Y5Q_cjs.MountayaElementsError(
973
+ `${owner}: seedVias ends at ${pointText(tail)} and pinnedEnd is ${pointText(endPin)}. A pinned end is the line's last via: pass one position for both, or leave pinnedEnd out to leave the end free.`
974
+ );
975
+ }
976
+ };
977
+ var refuseSegmentPositions = (options, owner) => {
978
+ const startPin = readEditPosition(options.pinnedStart, owner, "pinnedStart");
979
+ const endPin = readEditPosition(options.pinnedEnd, owner, "pinnedEnd");
980
+ const written = options.seedVias;
981
+ if (written !== void 0 && written !== null && !Array.isArray(written)) {
982
+ throw new chunkISLB6Y5Q_cjs.MountayaElementsError(
983
+ `${owner}: seedVias is ${chunkISLB6Y5Q_cjs.printValue(written)}; pass a list of [longitude, latitude] positions, or leave it out to draw a new segment.`
984
+ );
985
+ }
986
+ for (const [index, via] of (options.seedVias ?? []).entries()) {
987
+ readEditPosition(via, owner, `seedVias[${index}]`, "leave the via out");
988
+ }
989
+ return { endPin, startPin };
990
+ };
991
+ var refuseSegmentSeed = (options, owner) => {
992
+ const { endPin, startPin } = refuseSegmentPositions(options, owner);
993
+ refusePinMismatch(
994
+ (options.seedVias ?? []).map(clampCoordinatePrecision),
995
+ startPin ? clampCoordinatePrecision(startPin) : void 0,
996
+ endPin ? clampCoordinatePrecision(endPin) : void 0,
997
+ owner
998
+ );
999
+ };
1000
+ var refuseZoneSeed = (options, owner) => {
1001
+ const written = options.seedGeometry;
1002
+ if (written === void 0 || written === null) {
1003
+ return;
1004
+ }
1005
+ const kind = typeof written === "object" && written !== null && "type" in written ? written.type : null;
1006
+ if (kind !== "Polygon") {
1007
+ throw new chunkISLB6Y5Q_cjs.MountayaElementsError(
1008
+ `${owner}: seedGeometry is ${typeof kind === "string" ? `a ${kind}` : chunkISLB6Y5Q_cjs.printValue(written)}; pass a Polygon of one closed ring, or leave it out to draw a new zone.`
1009
+ );
1010
+ }
1011
+ const rings = typeof written === "object" && "coordinates" in written ? written.coordinates : void 0;
1012
+ if (!Array.isArray(rings) || rings.length === 0) {
1013
+ throw new chunkISLB6Y5Q_cjs.MountayaElementsError(
1014
+ `${owner}: seedGeometry is a Polygon whose coordinates are ${chunkISLB6Y5Q_cjs.printValue(rings)}; pass one closed ring, or leave seedGeometry out to draw a new zone.`
1015
+ );
1016
+ }
1017
+ if (rings.length > 1) {
1018
+ throw new chunkISLB6Y5Q_cjs.MountayaElementsError(
1019
+ `${owner}: seedGeometry holds ${rings.length} rings; a zone is one closed ring with no hole. Pass the outer ring alone.`
1020
+ );
1021
+ }
1022
+ };
1023
+
1024
+ // src/draw/rules/snap.ts
1025
+ var SNAP_THRESHOLD_PX = 40;
1026
+
1027
+ // src/draw/engines/segmentEngine.ts
1028
+ var EDIT_MODE = "linestring";
1029
+ var SEGMENT_TERRADRAW_PREFIX = "td-edit";
1030
+ var SEGMENT_VERTEX_LAYER_ID = `${SEGMENT_TERRADRAW_PREFIX}-point`;
1031
+ var ANALYZE_DEBOUNCE_MS = 300;
1032
+ var segmentRefusal = {
1033
+ engine: "TerraDrawLinestringSegmentEngine",
1034
+ shape: "line"
1035
+ };
1036
+ var liesOn = (end, pin) => end !== void 0 && pin !== void 0 && samePoint(end, pin);
1037
+ var normalizeDraftLine = (line) => {
1038
+ const collapsed = [];
1039
+ for (const coordinate of line) {
1040
+ const previous = collapsed[collapsed.length - 1];
1041
+ if (!previous || previous[0] !== coordinate[0] || previous[1] !== coordinate[1]) {
1042
+ collapsed.push(coordinate);
1043
+ }
1044
+ }
1045
+ return collapsed;
1046
+ };
1047
+ var pinFirstCoordinate = (firstCoordinate) => (feature) => {
1048
+ const pinned = firstCoordinate();
1049
+ if (!pinned) {
1050
+ return { valid: true };
1051
+ }
1052
+ const geometry = feature.geometry;
1053
+ if (geometry.type !== "LineString") {
1054
+ return { valid: true };
1055
+ }
1056
+ const head = geometry.coordinates[0];
1057
+ if (!head) {
1058
+ return { reason: "vertex 0 is pinned", valid: false };
1059
+ }
1060
+ if (!samePoint(head, pinned)) {
1061
+ return { reason: "vertex 0 is pinned", valid: false };
1062
+ }
1063
+ return { valid: true };
1064
+ };
1065
+ var pinLastCoordinate = (lastCoordinate) => (feature) => {
1066
+ const pinned = lastCoordinate();
1067
+ if (!pinned) {
1068
+ return { valid: true };
1069
+ }
1070
+ const geometry = feature.geometry;
1071
+ if (geometry.type !== "LineString") {
1072
+ return { valid: true };
1073
+ }
1074
+ const tail = geometry.coordinates.at(-1);
1075
+ if (!tail) {
1076
+ return { reason: "the last vertex is pinned", valid: false };
1077
+ }
1078
+ if (!samePoint(tail, pinned)) {
1079
+ return { reason: "the last vertex is pinned", valid: false };
1080
+ }
1081
+ return { valid: true };
1082
+ };
1083
+ var bothBoundariesPinned = (first, last) => (feature) => {
1084
+ const head = first(feature);
1085
+ if (!head.valid) {
1086
+ return head;
1087
+ }
1088
+ return last(feature);
1089
+ };
1090
+ var defaultSegmentDrawFactory = ({ map, prefixId, validation }) => new terraDraw.TerraDraw({
1091
+ adapter: new FramedMapLibreAdapter({ map, prefixId }, { longitude: 0 }),
1092
+ idStrategy: drawIdStrategy,
1093
+ modes: [
1094
+ // The linestring mode is the editable feature's home mode and the carrier of
1095
+ // the start-vertex pin validation, but it is never entered — the engine
1096
+ // builds and reshapes the line through select-mode writes — so it needs no
1097
+ // `editable` draw affordance.
1098
+ new terraDraw.TerraDrawLineStringMode({ validation }),
1099
+ new terraDraw.TerraDrawSelectMode({
1100
+ // An empty-map click must NOT deselect the line: the click grammar keeps
1101
+ // the feature selected for the whole edit so a click always appends/splices
1102
+ // rather than dropping the selection (and its handles) out from under the
1103
+ // next gesture. Midpoint insertion is unaffected by this flag.
1104
+ allowManualDeselection: false,
1105
+ flags: {
1106
+ [EDIT_MODE]: {
1107
+ feature: {
1108
+ // Only individual coordinates and inserted midpoints move; the
1109
+ // whole feature does not drag (that would translate the line
1110
+ // wholesale). Deleting a coordinate is NOT TerraDraw's to do: a
1111
+ // gesture on a handle is ambiguous (remove it, or route through it
1112
+ // again to close a loop), so the engine intercepts it and asks
1113
+ // instead — see attachClickInsert / attachVertexPrompt.
1114
+ coordinates: { deletable: false, draggable: true, midpoints: true },
1115
+ draggable: false,
1116
+ validation
1117
+ }
1118
+ }
1119
+ },
1120
+ // Null out the select mode's own key handling: Escape must cancel the edit
1121
+ // at the app level (not silently deselect the feature) and Delete/Backspace
1122
+ // must not wipe the whole line — a single-vertex delete goes through the
1123
+ // engine's own ask-the-user prompt.
1124
+ keyEvents: null
1125
+ })
1126
+ ]
1127
+ });
1128
+ var TerraDrawLinestringSegmentEngine = class {
1129
+ constructor(map, events, cursor, options, emitDraft, emitViaPrompt, createDraw = defaultSegmentDrawFactory) {
1130
+ this.map = map;
1131
+ this.emitDraft = emitDraft;
1132
+ this.emitViaPrompt = emitViaPrompt;
1133
+ this.events = events;
1134
+ this.cursor = cursor;
1135
+ this.featureId = options.featureId;
1136
+ this.color = readEditColor(options.color, segmentRefusal.engine);
1137
+ this.analyzeFn = options.analyzeFn ?? null;
1138
+ this.activitySlug = options.activitySlug ?? "";
1139
+ const seed = (options.seedVias ?? []).map(clampCoordinatePrecision);
1140
+ const rawStartPin = options.pinnedStart;
1141
+ const rawEndPin = options.pinnedEnd;
1142
+ const startPin = rawStartPin ? clampCoordinatePrecision(rawStartPin) : void 0;
1143
+ const endPin = rawEndPin ? clampCoordinatePrecision(rawEndPin) : void 0;
1144
+ refuseSegmentSeed(options, segmentRefusal.engine);
1145
+ this.pinnedFirst = startPin;
1146
+ this.pinnedLast = endPin;
1147
+ this.firstPinAtOpen = startPin;
1148
+ this.lastPinAtOpen = endPin;
1149
+ if (seed.length >= chunkEX2C5K2T_cjs.SEGMENT_MIN_VIAS) {
1150
+ this.chainSeedPin = void 0;
1151
+ } else {
1152
+ this.chainSeedPin = startPin ?? endPin;
1153
+ }
1154
+ this.changeHandler = (ids, _type, context) => {
1155
+ if (context?.target === "properties") {
1156
+ return;
1157
+ }
1158
+ this.handleChange(ids, isProgrammaticChange(context));
1159
+ };
1160
+ this.finishHandler = (id) => {
1161
+ this.handleFinish(id);
1162
+ };
1163
+ const validation = bothBoundariesPinned(
1164
+ pinFirstCoordinate(() => this.pinnedFirst),
1165
+ pinLastCoordinate(() => this.pinnedLast)
1166
+ );
1167
+ this.draw = createDraw({ map: this.map, prefixId: SEGMENT_TERRADRAW_PREFIX, validation });
1168
+ this.detachClickInsert = this.attachClickInsert();
1169
+ this.detachVertexPrompt = this.attachVertexPrompt();
1170
+ this.draw.start();
1171
+ this.draw.on("change", this.changeHandler);
1172
+ this.draw.on("finish", this.finishHandler);
1173
+ this.draw.setMode(SELECT_MODE);
1174
+ try {
1175
+ if (seed.length >= chunkEX2C5K2T_cjs.SEGMENT_MIN_VIAS) {
1176
+ this.seedFeature(seed);
1177
+ } else if (this.chainSeedPin) {
1178
+ this.seedFeature([this.chainSeedPin, this.chainSeedPin]);
1179
+ }
1180
+ } catch (error) {
1181
+ this.dispose();
1182
+ throw error;
1183
+ }
1184
+ this.applySegmentDraftStyle(this.color);
1185
+ this.detachVertexCursor = this.attachVertexCursor();
1186
+ this.detachCursorReassert = chunkIBQJDVHF_cjs.attachCursorReassert(this.events, this.cursor);
1187
+ if (seed.length >= chunkEX2C5K2T_cjs.SEGMENT_MIN_VIAS) {
1188
+ this.scheduleAnalyze();
1189
+ }
1190
+ }
1191
+ map;
1192
+ emitDraft;
1193
+ emitViaPrompt;
1194
+ draw;
1195
+ // The id the editable line lives under in the TerraDraw store for the whole
1196
+ // edit. Every store read/write (currentLine, applyDraft, the click grammar,
1197
+ // select) keys off it. The line is created directly under this id on the first
1198
+ // click (or seeded under it), so there is no second TerraDraw-assigned id to
1199
+ // reconcile the way a native draw session would produce.
1200
+ featureId;
1201
+ // The start-vertex lock the guard reads, set only when a pin is passed: a non-first
1202
+ // reshape seeds the saved line with vertex 0 = the saved head, and a chained segment
1203
+ // opens with vertex 0 = the previous segment's end, both pinning it from the first
1204
+ // paint; a first segment (from-scratch or an existing reshape) passes no pin and
1205
+ // leaves it undefined so vertex 0 stays freely draggable. applyDraft re-pins it to
1206
+ // the restored head only while it is already locked, so the guard tracks the applied
1207
+ // draft rather than a stale head.
1208
+ pinnedFirst;
1209
+ // The end-vertex lock, the mirror of pinnedFirst: set only for an insert, whose
1210
+ // last vertex is the NEXT segment's start. It also redirects the click grammar,
1211
+ // which splices in front of the pin rather than appending past it, so the drawn
1212
+ // line always finishes on its neighbour. Undefined for every other edit, leaving
1213
+ // the tail freely draggable. applyDraft re-pins it the same way as the head.
1214
+ pinnedLast;
1215
+ // The two boundaries the edit opened pinned on, as they are drawn, kept for the whole edit. The
1216
+ // click that starts a line where an applied draft left none releases both locks, and an applied
1217
+ // draft that puts the line back on one of these points locks that end again.
1218
+ firstPinAtOpen;
1219
+ lastPinAtOpen;
1220
+ // The single boundary pin a one-sided insert or an append opens on, held so
1221
+ // applyDraft can restore the degenerate `[pin, pin]` line when an undo steps the
1222
+ // edit back to empty. Undefined for a from-scratch first segment (no neighbour),
1223
+ // for a reshape (whose undo history never steps below the seeded line), and for a
1224
+ // two-sided insert (which opens on a real two-point line, not a degenerate).
1225
+ chainSeedPin;
1226
+ // True only while the engine itself is writing the line through the store API in
1227
+ // response to a user click (create, tail-append, mid-edge splice, degenerate tail
1228
+ // replace). TerraDraw tags every store-API write `{origin:"api"}`, which
1229
+ // handleChange would otherwise read as programmatic and skip from undo history;
1230
+ // this flag overrides that so a clicked point records as an interactive edit —
1231
+ // directions parity, where every added via is its own undo step, and where a
1232
+ // splice becomes individually undoable. It never wraps a genuinely programmatic
1233
+ // write (applyDraft, a seed), so those stay out of history.
1234
+ interactiveWrite = false;
1235
+ // True once an interactive (non-programmatic) change has landed since the last
1236
+ // map mousedown — the signal that TerraDraw already consumed the current gesture
1237
+ // (a vertex drag, a midpoint insert). The click grammar reads it to skip its own
1238
+ // append/splice on that same gesture, so a midpoint-handle click inserts once
1239
+ // (TerraDraw on pointerup) rather than twice (a second splice on the following
1240
+ // map click). Reset on every mousedown.
1241
+ gestureConsumed = false;
1242
+ // True while a TerraDraw gesture has emitted `live` frames that no `settled` draft has
1243
+ // closed yet. TerraDraw's `finish` closes the gesture, and it fires on every pointer release
1244
+ // in the select mode, a drag the pin guard refused at every step included, so the finish
1245
+ // settles only a gesture that actually emitted a frame.
1246
+ gestureOpen = false;
1247
+ // The stable change and finish listener references the engine registers on the TerraDraw
1248
+ // instance, held so a style-reload replay can `off` the previous binding before `on`-ing
1249
+ // again rather than stacking a duplicate listener per replay.
1250
+ changeHandler;
1251
+ finishHandler;
1252
+ // The line read off the store by {@link detachBeforeStyleReload}, held for the replay to
1253
+ // re-seed from. It exists because stopping TerraDraw EMPTIES the store: `stop()`
1254
+ // unregisters the adapter, whose base `unregister()` ends in its own `clear()`, which
1255
+ // calls back through `onClear` into `_store.clear()`. So by the time the replay runs there
1256
+ // is nothing left to read, and a replay that re-registered the adapter correctly still
1257
+ // came back to empty layers. Null while no swap is in flight.
1258
+ detachedLine = null;
1259
+ // Whether TerraDraw is stopped for a style reload: raised by the detach, lowered by the replay.
1260
+ // While it is raised the store is empty and refuses every write, so the engine reads and
1261
+ // writes what it holds itself.
1262
+ detached = false;
1263
+ // The latest draft applied while TerraDraw is stopped for a style reload, written when the
1264
+ // replay ends. Undefined when none was applied.
1265
+ heldDraft;
1266
+ // Whether the edit is over. A disposed engine has no replay to come, so a draft applied to it
1267
+ // inside the detach window is held by nothing.
1268
+ disposed = false;
1269
+ // The current segment color the draft renders in, held so a base-map
1270
+ // switch replay can re-apply it onto the fresh style.
1271
+ color;
1272
+ // The map event engine the hover cursor's listeners detach through; held so
1273
+ // dispose/replay tears them down by reference rather than leaking onto the
1274
+ // next edit's engine instance.
1275
+ events;
1276
+ // The cursor controller the hover cursor pushes onto; the base
1277
+ // edit cross is locked one layer above this engine (the editing hook), and
1278
+ // the override layers above that so leaving the vertex reverts to the
1279
+ // cross rather than the OS default.
1280
+ cursor;
1281
+ // Detaches the vertex-layer mouseenter/mouseleave listeners that drive the
1282
+ // `move` cursor override; set on attach, cleared on dispose / replay so a
1283
+ // teardown leaves no listener pointing at the stopped TerraDraw instance.
1284
+ detachVertexCursor = null;
1285
+ // Detaches the map-level click + mousedown listeners that drive the click
1286
+ // grammar; set on attach, cleared on dispose / replay so a teardown leaves no
1287
+ // listener pointing at the stopped TerraDraw instance.
1288
+ detachClickInsert = null;
1289
+ // Detaches the map-level contextmenu listener that raises the ask-the-user
1290
+ // prompt for a right-clicked handle (TerraDraw's own coordinate delete is off);
1291
+ // set on attach, cleared on dispose / replay.
1292
+ detachVertexPrompt = null;
1293
+ // Whether the app currently holds a via prompt open. While true the click
1294
+ // grammar is detached, so the click that dismisses the prompt cannot also
1295
+ // append or splice a vertex.
1296
+ viaPromptPending = false;
1297
+ // Detaches the shared map-level mousemove cursor re-assert; set on attach,
1298
+ // cleared on dispose / replay. TerraDraw's select mode writes the canvas cursor
1299
+ // only over a handle today, never on empty map, so the locked edit cross is
1300
+ // untouched while the pointer roams free and this re-assert is a no-op write
1301
+ // there (its value-changed guard skips it). It is the structural-consistency net
1302
+ // every lock-holding engine shares: should a TerraDraw version start clobbering
1303
+ // the cursor on a plain move, the re-pin already covers it.
1304
+ detachCursorReassert = null;
1305
+ // The injected freehand elevation/analysis resolver (the linestring twin of
1306
+ // the directions routeFn). Null when none is injected — a render-free test or
1307
+ // a session with no data seam — so the engine still constructs and emits a
1308
+ // route-less draft, the historical behavior.
1309
+ analyzeFn;
1310
+ // The activity the analyzeFn resolves the profile for (the itinerary's, shared
1311
+ // by every segment); empty when no analyzeFn is wired.
1312
+ activitySlug;
1313
+ // The most recent SegmentRoute the analyzeFn resolved for the current line,
1314
+ // cached so an immediate `change` emit can carry the last-known profile while a
1315
+ // fresh analyze is in flight — the panel keeps the previous profile rather than
1316
+ // flashing empty. Null below the two-point floor or when no profile resolves.
1317
+ lastRoute = null;
1318
+ // The pending debounce timer that coalesces a burst of geometry changes into
1319
+ // one analyzeFn call; cleared when it fires, when a newer change supersedes it,
1320
+ // and on dispose so a post-teardown analyze never runs.
1321
+ analyzeTimer = null;
1322
+ // A monotonic token stamped on each analyze kickoff and re-read when it
1323
+ // resolves: a newer change bumps the token, so an older in-flight analyze whose
1324
+ // token no longer matches is dropped rather than emitting a stale profile. It
1325
+ // is the race guard against an out-of-order resolution overwriting a newer one.
1326
+ analyzeToken = 0;
1327
+ // Aborts the analyze in flight: a newer change and a dispose each abort it, so the host's
1328
+ // call is told its answer is no longer read.
1329
+ analyzeController = null;
1330
+ // Whether this edit has already said in the console that its analyzeFn failed.
1331
+ analyzeFaultReported = false;
1332
+ setDraftStyle(style) {
1333
+ if (this.disposed) {
1334
+ return;
1335
+ }
1336
+ this.color = readEditColor(style.color, segmentRefusal.engine);
1337
+ if (this.detached) {
1338
+ return;
1339
+ }
1340
+ this.applySegmentDraftStyle(this.color);
1341
+ }
1342
+ setViaPromptPending(pending) {
1343
+ if (this.disposed) {
1344
+ return;
1345
+ }
1346
+ if (this.viaPromptPending === pending) {
1347
+ return;
1348
+ }
1349
+ this.viaPromptPending = pending;
1350
+ if (pending) {
1351
+ this.detachClickInsert?.();
1352
+ this.detachClickInsert = null;
1353
+ return;
1354
+ }
1355
+ this.detachClickInsert ??= this.attachClickInsert();
1356
+ }
1357
+ readDraft() {
1358
+ if (this.disposed) {
1359
+ return null;
1360
+ }
1361
+ if (this.detached) {
1362
+ const line = this.heldDraft === void 0 ? this.detachedLine : this.lineForDraft(this.heldDraft);
1363
+ return line === null ? null : copyPositions(line);
1364
+ }
1365
+ return this.currentLine();
1366
+ }
1367
+ applyDraft(draft) {
1368
+ if (this.disposed) {
1369
+ return;
1370
+ }
1371
+ const coordinates = draft.map(clampCoordinatePrecision);
1372
+ if (this.detached) {
1373
+ this.heldDraft = coordinates;
1374
+ return;
1375
+ }
1376
+ const lastRoute = this.lastRoute;
1377
+ this.lastRoute = null;
1378
+ const pinnedFirst = this.pinnedFirst;
1379
+ const pinnedLast = this.pinnedLast;
1380
+ try {
1381
+ this.writeDraft(coordinates);
1382
+ } catch (error) {
1383
+ this.pinnedFirst = pinnedFirst;
1384
+ this.pinnedLast = pinnedLast;
1385
+ this.lastRoute = lastRoute;
1386
+ throw error;
1387
+ }
1388
+ }
1389
+ /**
1390
+ * lineForDraft answers the line an applied draft is held as: the draft itself from two points
1391
+ * up, the degenerate `[point, point]` for a single point, and for none the degenerate line on
1392
+ * the boundary pin the edit opened on, or null where it opened on none.
1393
+ */
1394
+ lineForDraft(coordinates) {
1395
+ if (coordinates.length >= chunkEX2C5K2T_cjs.SEGMENT_MIN_VIAS) {
1396
+ return coordinates;
1397
+ }
1398
+ const head = coordinates[0] ?? this.chainSeedPin;
1399
+ return head === void 0 ? null : [head, head];
1400
+ }
1401
+ /**
1402
+ * writeDraft replaces the line with an applied draft, re-pinning the boundaries the edit holds
1403
+ * pinned to the ends of the line the draft is held as before the write, so the write is judged
1404
+ * against them. A boundary the click grammar released is pinned again where that line is back
1405
+ * on the point the edit opened pinned on.
1406
+ */
1407
+ writeDraft(coordinates) {
1408
+ const line = this.lineForDraft(coordinates);
1409
+ if (coordinates.length === 0 && this.draw.getSnapshotFeature(this.featureId)) {
1410
+ this.draw.removeFeatures([this.featureId]);
1411
+ }
1412
+ if (line === null) {
1413
+ return;
1414
+ }
1415
+ const head = line[0];
1416
+ if (this.pinnedFirst !== void 0 || liesOn(head, this.firstPinAtOpen)) {
1417
+ this.pinnedFirst = head;
1418
+ }
1419
+ const tail = line.at(-1);
1420
+ if (this.pinnedLast !== void 0 || liesOn(tail, this.lastPinAtOpen)) {
1421
+ this.pinnedLast = tail;
1422
+ }
1423
+ this.writeOrSeedLine(line);
1424
+ }
1425
+ dispose() {
1426
+ this.detachCursorReassert?.();
1427
+ this.detachCursorReassert = null;
1428
+ this.detachVertexCursor?.();
1429
+ this.detachVertexCursor = null;
1430
+ this.cursor.popOverride();
1431
+ this.detachClickInsert?.();
1432
+ this.detachClickInsert = null;
1433
+ this.detachVertexPrompt?.();
1434
+ this.detachVertexPrompt = null;
1435
+ this.cancelAnalyze();
1436
+ this.analyzeToken += 1;
1437
+ this.lastRoute = null;
1438
+ this.draw.off("change", this.changeHandler);
1439
+ this.draw.off("finish", this.finishHandler);
1440
+ if (this.draw.enabled) {
1441
+ this.draw.clear();
1442
+ }
1443
+ this.draw.stop();
1444
+ this.disposed = true;
1445
+ this.heldDraft = void 0;
1446
+ this.detachedLine = null;
1447
+ }
1448
+ /**
1449
+ * detachBeforeStyleReload stops TerraDraw before the swap, so the replay's `start()`
1450
+ * actually re-registers the adapter. See {@link EditEngine.detachBeforeStyleReload}
1451
+ * for why the pair is needed and why the order is load-bearing: the adapter's
1452
+ * `unregister()` removes five layers and three sources unguarded, which succeeds
1453
+ * silently on the outgoing style and is noisy-then-fatal on the incoming one.
1454
+ *
1455
+ * The map-level click grammar is left alone: a map-level listener survives `setStyle`
1456
+ * untouched, and the replay's own detach-then-re-attach is what re-establishes its
1457
+ * dispatch order against the restarted instance.
1458
+ *
1459
+ * The line is read off the store FIRST, because `stop()` empties it — the adapter's base
1460
+ * `unregister()` ends in its own `clear()`, which calls back through `onClear` into
1461
+ * `_store.clear()`. And the change and finish listeners come off before that, so the
1462
+ * deletion the clear emits is not turned into a draft saying the user erased their line
1463
+ * mid-swap.
1464
+ */
1465
+ detachBeforeStyleReload() {
1466
+ if (this.disposed) {
1467
+ return;
1468
+ }
1469
+ if (this.detached) {
1470
+ return;
1471
+ }
1472
+ this.detached = true;
1473
+ this.detachedLine = this.currentLine();
1474
+ this.draw.off("change", this.changeHandler);
1475
+ this.draw.off("finish", this.finishHandler);
1476
+ this.draw.stop();
1477
+ }
1478
+ /**
1479
+ * replayAfterStyleReload re-renders the active edit's scene after a base-map
1480
+ * switch wiped the style. It re-attaches what setStyle tore down: the library's
1481
+ * layers + change listener, the editable feature, its color, and the hover cursor over its
1482
+ * handles (its TerraDraw point layer is rebuilt).
1483
+ *
1484
+ * Unlike the waypoint engines — which leave their map-level pointer
1485
+ * subscriptions alone because a map-level listener survives setStyle untouched
1486
+ * — this engine detaches THEN re-attaches its map-level click grammar. The
1487
+ * detach makes the re-attach net-zero (no double-bind), and re-attaching is
1488
+ * deliberate: the listeners must re-register AFTER TerraDraw re-starts is wired,
1489
+ * so MapLibre dispatches the click handler ahead of any registration TerraDraw
1490
+ * lands during start() — the same ordering the constructor establishes.
1491
+ *
1492
+ * It is the second half of a pair: {@link detachBeforeStyleReload} must have stopped
1493
+ * the instance before the swap, or the `start()` below returns early and re-registers
1494
+ * nothing.
1495
+ */
1496
+ replayAfterStyleReload() {
1497
+ if (this.disposed) {
1498
+ return;
1499
+ }
1500
+ const line = this.detachedLine ?? this.currentLine();
1501
+ this.detachedLine = null;
1502
+ this.detached = false;
1503
+ this.detachClickInsert?.();
1504
+ this.detachClickInsert = this.viaPromptPending ? null : this.attachClickInsert();
1505
+ this.detachVertexPrompt?.();
1506
+ this.detachVertexPrompt = this.attachVertexPrompt();
1507
+ this.draw.off("change", this.changeHandler);
1508
+ this.draw.off("finish", this.finishHandler);
1509
+ this.draw.start();
1510
+ this.draw.on("change", this.changeHandler);
1511
+ this.draw.on("finish", this.finishHandler);
1512
+ this.draw.setMode(SELECT_MODE);
1513
+ if (line) {
1514
+ this.draw.clear();
1515
+ this.seedFeature(line);
1516
+ }
1517
+ this.applySegmentDraftStyle(this.color);
1518
+ this.detachVertexCursor?.();
1519
+ this.detachVertexCursor = this.attachVertexCursor();
1520
+ this.detachCursorReassert?.();
1521
+ this.detachCursorReassert = chunkIBQJDVHF_cjs.attachCursorReassert(this.events, this.cursor);
1522
+ const held = this.heldDraft;
1523
+ this.heldDraft = void 0;
1524
+ if (held !== void 0) {
1525
+ applyHeldWrite(() => this.applyDraft(held));
1526
+ }
1527
+ }
1528
+ /**
1529
+ * handleChange is the single fan-out the per-edit change listener calls on every
1530
+ * geometry change to the editable line — an interactive drag/insert, an engine
1531
+ * click write, or a programmatic applyDraft/seed. A change under any other id is
1532
+ * skipped. It emits IMMEDIATELY with the engine's CACHED route so the panel stays
1533
+ * responsive — the line moved, but the last-known elevation profile holds rather
1534
+ * than flashing empty — and, off the same change, schedules a debounced analyzeFn
1535
+ * for the current line. When that analyze resolves it caches the fresh profile
1536
+ * and emits again. Below the two-point floor (a degenerate start, an undo that
1537
+ * stepped below it) the cached route is cleared and the draft carries an explicit
1538
+ * null, the same below-floor behavior the directions engine has. The line is
1539
+ * normalized first so the degenerate `[p, p]` reads as one via and the Save-closed
1540
+ * floor holds.
1541
+ *
1542
+ * The phase follows the change's origin. A change TerraDraw makes under the pointer (a
1543
+ * vertex drag, a midpoint insert) is one frame of a gesture its `finish` closes, so it is
1544
+ * `live` and {@link handleFinish} settles it. A store-API write, the engine's own click
1545
+ * write or a programmatic one, is whole when it lands, so it is `settled`.
1546
+ */
1547
+ handleChange(ids, apiOrigin) {
1548
+ if (!ids.includes(this.featureId)) {
1549
+ return;
1550
+ }
1551
+ const programmatic = apiOrigin && !this.interactiveWrite;
1552
+ const phase = apiOrigin ? "settled" : "live";
1553
+ if (!programmatic) {
1554
+ this.gestureConsumed = true;
1555
+ }
1556
+ this.gestureOpen = phase === "live";
1557
+ const line = normalizeDraftLine(this.currentLine() ?? []);
1558
+ if (line.length < chunkEX2C5K2T_cjs.SEGMENT_MIN_VIAS) {
1559
+ this.lastRoute = null;
1560
+ this.cancelAnalyze();
1561
+ this.analyzeToken += 1;
1562
+ chunkWW4CGS7G_cjs.notifyListeners([this.emitDraft], { phase, programmatic, route: null, vias: line });
1563
+ return;
1564
+ }
1565
+ chunkWW4CGS7G_cjs.notifyListeners([this.emitDraft], { phase, programmatic, route: this.lastRoute, vias: line });
1566
+ this.scheduleAnalyze();
1567
+ }
1568
+ /**
1569
+ * handleFinish settles the gesture TerraDraw just finished on the editable line: a
1570
+ * coordinate drag, or a midpoint insert, both of which reach the draft as `live` frames. It
1571
+ * emits the line as it stands once more, `settled` and interactive, so a history subscriber
1572
+ * records the whole gesture as one step. A finish that closes no live frame emits nothing,
1573
+ * because the select mode also finishes a drag the pin guard refused at every step, and that
1574
+ * gesture changed nothing. The geometry did not move since the last frame, so the draft
1575
+ * carries the route that frame carried.
1576
+ */
1577
+ handleFinish(id) {
1578
+ if (id !== this.featureId || !this.gestureOpen) {
1579
+ return;
1580
+ }
1581
+ this.gestureOpen = false;
1582
+ const line = normalizeDraftLine(this.currentLine() ?? []);
1583
+ const route = line.length < chunkEX2C5K2T_cjs.SEGMENT_MIN_VIAS ? null : this.lastRoute;
1584
+ chunkWW4CGS7G_cjs.notifyListeners([this.emitDraft], { phase: "settled", programmatic: false, route, vias: line });
1585
+ }
1586
+ /**
1587
+ * scheduleAnalyze debounces an analyzeFn call for the current line, coalescing a burst of
1588
+ * rapid changes into a single round trip. Each call cancels the pending timer, aborts the
1589
+ * analyze in flight and bumps the analyze token, so a newer change supersedes an older one:
1590
+ * the host's call is handed a signal that aborts as it is superseded or the edit ends, and an
1591
+ * answer that lands anyway is dropped by the token. The line is read when the timer fires, so a
1592
+ * drag that changes it every frame copies it once. On a matching resolution it caches the route
1593
+ * and emits a programmatic draft (the geometry did not change with the analyze, so a history
1594
+ * subscriber must not record it) carrying the fresh profile. A null analyzeFn (a render-free
1595
+ * test, no data seam) is a no-op. A resolved null (below floor, an absorbed query error) clears
1596
+ * the cache and emits the cleared route. An analyzeFn that throws or rejects is read as no new
1597
+ * profile: the edit stays open, and {@link warnOnAnalyzeFault} says so once.
1598
+ */
1599
+ scheduleAnalyze() {
1600
+ if (!this.analyzeFn) {
1601
+ return;
1602
+ }
1603
+ this.cancelAnalyze();
1604
+ this.analyzeToken += 1;
1605
+ const token = this.analyzeToken;
1606
+ this.analyzeTimer = setTimeout(() => {
1607
+ this.analyzeTimer = null;
1608
+ const analyze = this.analyzeFn;
1609
+ if (!analyze) {
1610
+ return;
1611
+ }
1612
+ const controller = new AbortController();
1613
+ this.analyzeController = controller;
1614
+ const line = normalizeDraftLine(this.currentLine() ?? []);
1615
+ const answer = (async () => analyze(this.activitySlug, line, { signal: controller.signal }))();
1616
+ void answer.then(
1617
+ (route) => {
1618
+ if (token !== this.analyzeToken) {
1619
+ return;
1620
+ }
1621
+ this.lastRoute = route;
1622
+ chunkWW4CGS7G_cjs.notifyListeners([this.emitDraft], {
1623
+ phase: "settled",
1624
+ programmatic: true,
1625
+ route,
1626
+ vias: this.currentLine() ?? line
1627
+ });
1628
+ },
1629
+ (fault) => {
1630
+ if (token === this.analyzeToken) {
1631
+ this.warnOnAnalyzeFault(fault);
1632
+ }
1633
+ }
1634
+ );
1635
+ }, ANALYZE_DEBOUNCE_MS);
1636
+ }
1637
+ /**
1638
+ * warnOnAnalyzeFault says in the console, once per edit and in development only, that the
1639
+ * injected analyzeFn threw or rejected.
1640
+ *
1641
+ * The engine reads a fault as no new profile, so nothing the host holds rejects and the live
1642
+ * elevation simply does not refresh. Once per edit, because a drag asks for an analyze at every
1643
+ * line it settles on and an analyzer that is down fails each one for the same reason. A
1644
+ * production build says nothing: the fault is the host's to report through its own analyzer.
1645
+ */
1646
+ warnOnAnalyzeFault(fault) {
1647
+ if (this.analyzeFaultReported || !chunkEP5OEEVZ_cjs.inDevelopment()) {
1648
+ return;
1649
+ }
1650
+ this.analyzeFaultReported = true;
1651
+ console.warn(
1652
+ "[@mountaya/elements] TerraDrawLinestringSegmentEngine: analyzeFn threw, so the edit shows no fresh profile for this line. An analyzer that finds none resolves to null; one that throws or rejects is read the same way and the edit stays open. The error it threw follows.",
1653
+ fault
1654
+ );
1655
+ }
1656
+ /**
1657
+ * cancelAnalyze clears the pending debounce timer and aborts the analyze in flight, so no
1658
+ * scheduled analyze fires and the host's call is told it is no longer read; idempotent.
1659
+ */
1660
+ cancelAnalyze() {
1661
+ if (this.analyzeTimer !== null) {
1662
+ clearTimeout(this.analyzeTimer);
1663
+ this.analyzeTimer = null;
1664
+ }
1665
+ this.analyzeController?.abort();
1666
+ this.analyzeController = null;
1667
+ }
1668
+ /** seedFeature adds the editable linestring feature under featureId, selects it, and shows its handles + midpoints. */
1669
+ seedFeature(coordinates) {
1670
+ const feature = {
1671
+ geometry: { coordinates, type: "LineString" },
1672
+ id: this.featureId,
1673
+ properties: { mode: EDIT_MODE },
1674
+ type: "Feature"
1675
+ };
1676
+ addDrawFeature(this.draw, feature, segmentRefusal);
1677
+ this.draw.setMode(SELECT_MODE);
1678
+ this.draw.selectFeature(this.featureId);
1679
+ }
1680
+ /**
1681
+ * writeOrSeedLine writes the given coordinates onto the editable feature, or
1682
+ * re-creates it through the seed path when it is absent. updateFeatureGeometry
1683
+ * THROWS when the feature is gone (an applyDraft that lands after an undo-to-empty
1684
+ * removed it), so a present feature takes the geometry update — which keeps the
1685
+ * selection + handles live via TerraDraw's afterFeatureUpdated refresh — while an
1686
+ * absent one is re-seeded and re-selected.
1687
+ */
1688
+ writeOrSeedLine(coordinates) {
1689
+ if (this.draw.getSnapshotFeature(this.featureId)) {
1690
+ updateDrawGeometry(
1691
+ this.draw,
1692
+ this.featureId,
1693
+ { coordinates, type: "LineString" },
1694
+ segmentRefusal
1695
+ );
1696
+ } else {
1697
+ this.seedFeature(coordinates);
1698
+ }
1699
+ }
1700
+ /**
1701
+ * applySegmentDraftStyle pushes the segment color onto the edit + select
1702
+ * mode styles so the draft line, its vertices, the selection handles, and
1703
+ * the midpoint-insert handles all render in the segment color.
1704
+ * updateModeOptions accepts a partial options object, so only the styling
1705
+ * keys are sent; it runs while the modes are started, recoloring live.
1706
+ * The color was held to `#rrggbb` as it was handed over ({@link readEditColor}).
1707
+ */
1708
+ applySegmentDraftStyle(hex) {
1709
+ this.draw.updateModeOptions(EDIT_MODE, {
1710
+ styles: {
1711
+ coordinatePointColor: hex,
1712
+ lineStringColor: hex,
1713
+ lineStringWidth: 4
1714
+ }
1715
+ });
1716
+ this.draw.updateModeOptions(SELECT_MODE, {
1717
+ styles: {
1718
+ midPointColor: hex,
1719
+ selectedLineStringColor: hex,
1720
+ selectedPointColor: hex,
1721
+ selectionPointColor: hex
1722
+ }
1723
+ });
1724
+ }
1725
+ /** currentLine reads the editable line's current coordinates from the TerraDraw store, or null when it is gone. */
1726
+ currentLine() {
1727
+ return this.lineOf(this.featureId);
1728
+ }
1729
+ /**
1730
+ * lineOf reads one feature's coordinates from the TerraDraw store by id, narrowed
1731
+ * to a LineString, or null when the feature is gone or is not a line (a transient
1732
+ * store state). currentLine reads the editable line through it, so the narrowing
1733
+ * that keeps the draft honest lives in one place.
1734
+ */
1735
+ lineOf(id) {
1736
+ const feature = this.draw.getSnapshotFeature(id);
1737
+ if (feature?.geometry.type !== "LineString") {
1738
+ return null;
1739
+ }
1740
+ return feature.geometry.coordinates;
1741
+ }
1742
+ /**
1743
+ * attachVertexCursor layers the drag/insert affordance over the locked edit cross whenever the
1744
+ * pointer sits on a handle of the editable line, through the shared
1745
+ * {@link attachEditHoverCursor}: the `move` cursor over a draggable vertex (a drag there
1746
+ * reshapes) and "pointer" over an insert-midpoint (a click there splits the line). The
1747
+ * TerraDraw point layer hosts both, distinguished by the midpoint property. The base cross
1748
+ * stays pinned underneath and shows again off the handles. The select-mode handler only writes
1749
+ * the canvas cursor over a handle, never on empty map, so the locked cross is untouched while
1750
+ * the pointer roams free.
1751
+ */
1752
+ attachVertexCursor() {
1753
+ return chunkIBQJDVHF_cjs.attachEditHoverCursor({
1754
+ cursor: this.cursor,
1755
+ events: this.events,
1756
+ layers: [
1757
+ {
1758
+ kind: "handle",
1759
+ layerId: SEGMENT_VERTEX_LAYER_ID,
1760
+ midpointProperty: TERRA_DRAW_MID_POINT_PROPERTY
1761
+ }
1762
+ ],
1763
+ map: this.map
1764
+ });
1765
+ }
1766
+ /**
1767
+ * attachClickInsert subscribes to canvas-level clicks so the engine can grow or
1768
+ * reshape the editable line with the directions click grammar, plus a mousedown
1769
+ * that resets the consumed-gesture guard at the start of every pointer sequence.
1770
+ * On a click the handler runs a three-way branch behind two guards:
1771
+ *
1772
+ * - Consumed-gesture guard: skip when TerraDraw already handled the gesture on
1773
+ * the preceding pointerup (a drag, a midpoint insert), so the engine does not
1774
+ * double the coordinate.
1775
+ * - Vertex-proximity guard: skip within the snap radius of an existing vertex —
1776
+ * that click belongs to TerraDraw (grab-to-drag, right-click delete).
1777
+ * - No feature yet → create the degenerate `[click, click]` and select it. A boundary
1778
+ * still pinned there (an applied draft emptied an edit that opened on a saved line) is
1779
+ * released, so the click starts a line as the first click of a fresh edit does. An applied
1780
+ * draft that puts the line back on a point the edit opened pinned on locks that end again.
1781
+ * - Degenerate line → replace its duplicate tail with the click.
1782
+ * - Real line → splice into the nearest edge within the snap radius, else append
1783
+ * the click to the tail (the reshape-extends behavior).
1784
+ *
1785
+ * Every write runs under {@link runInteractiveWrite} so it records as an undo
1786
+ * step, and clamps its coordinate to 9 dp so the store-API write never trips
1787
+ * TerraDraw's excessive-precision throw. A consumed click stops propagation so a
1788
+ * sibling MapLibre click listener does not also act on it. A write the library refuses, the
1789
+ * first click's seed or any after it, leaves the listener as this package's error with the
1790
+ * library's reason, and writes nothing.
1791
+ */
1792
+ attachClickInsert() {
1793
+ const onDown = () => {
1794
+ this.gestureConsumed = false;
1795
+ };
1796
+ const onClick = (event) => {
1797
+ if (this.gestureConsumed || this.detached) {
1798
+ return;
1799
+ }
1800
+ const clickLngLat = pointerPosition(event.lngLat);
1801
+ const line = this.currentLine() ?? [];
1802
+ const vertex = nearestVertex({ line, lngLat: clickLngLat, map: this.map });
1803
+ if (vertex.distancePx < SNAP_THRESHOLD_PX) {
1804
+ this.promptForVertex(line, vertex.index);
1805
+ this.consumeClick(event);
1806
+ return;
1807
+ }
1808
+ if (line.length === 0) {
1809
+ this.pinnedFirst = void 0;
1810
+ this.pinnedLast = void 0;
1811
+ this.runInteractiveWrite(() => this.seedFeature([clickLngLat, clickLngLat]));
1812
+ this.consumeClick(event);
1813
+ return;
1814
+ }
1815
+ if (normalizeDraftLine(line).length < chunkEX2C5K2T_cjs.SEGMENT_MIN_VIAS) {
1816
+ const pin = line[0] ?? clickLngLat;
1817
+ const coordinates = this.pinnedLast !== void 0 ? [clickLngLat, pin] : [pin, clickLngLat];
1818
+ this.runInteractiveWrite(
1819
+ () => updateDrawGeometry(
1820
+ this.draw,
1821
+ this.featureId,
1822
+ { coordinates, type: "LineString" },
1823
+ segmentRefusal
1824
+ )
1825
+ );
1826
+ this.consumeClick(event);
1827
+ return;
1828
+ }
1829
+ const insertion = nearestEdgeInsertion({
1830
+ line,
1831
+ lngLat: clickLngLat,
1832
+ map: this.map,
1833
+ thresholdPx: SNAP_THRESHOLD_PX
1834
+ });
1835
+ const next = [...line];
1836
+ if (insertion) {
1837
+ next.splice(insertion.index, 0, insertion.lngLat);
1838
+ } else if (this.pinnedLast !== void 0) {
1839
+ next.splice(next.length - 1, 0, clickLngLat);
1840
+ } else {
1841
+ next.push(clickLngLat);
1842
+ }
1843
+ this.runInteractiveWrite(
1844
+ () => updateDrawGeometry(
1845
+ this.draw,
1846
+ this.featureId,
1847
+ { coordinates: next, type: "LineString" },
1848
+ segmentRefusal
1849
+ )
1850
+ );
1851
+ this.consumeClick(event);
1852
+ };
1853
+ const detachClick = this.events.on("click", onClick);
1854
+ const detachDown = this.events.on("mousedown", onDown);
1855
+ return () => {
1856
+ detachClick();
1857
+ detachDown();
1858
+ };
1859
+ }
1860
+ /**
1861
+ * attachVertexPrompt raises the ask-the-user prompt for a RIGHT-clicked handle.
1862
+ * Right-click was TerraDraw's own coordinate delete; the select mode's
1863
+ * `deletable` flag is off, so the gesture arrives here instead and the engine
1864
+ * asks what it meant rather than deleting. Scoped map-level (the vertex hit test
1865
+ * is the same screen-space radius the click grammar uses, so the two agree by
1866
+ * construction) and detached by reference on dispose / replay.
1867
+ */
1868
+ attachVertexPrompt() {
1869
+ return this.events.on("contextmenu", (event) => {
1870
+ const lngLat = pointerPosition(event.lngLat);
1871
+ const line = this.currentLine() ?? [];
1872
+ const vertex = nearestVertex({ line, lngLat, map: this.map });
1873
+ if (vertex.distancePx >= SNAP_THRESHOLD_PX) {
1874
+ return;
1875
+ }
1876
+ this.promptForVertex(line, vertex.index);
1877
+ this.consumeClick(event);
1878
+ });
1879
+ }
1880
+ /**
1881
+ * promptForVertex emits the ask-the-user prompt for the handle at `index`,
1882
+ * carrying the coordinate so the app can anchor the prompt on it. A no-op for an
1883
+ * index the line does not carry, so a stale hit test can never raise a prompt
1884
+ * against a vertex that is gone.
1885
+ */
1886
+ promptForVertex(line, index) {
1887
+ const vertex = line[index];
1888
+ if (!vertex) {
1889
+ return;
1890
+ }
1891
+ chunkWW4CGS7G_cjs.notifyListeners([this.emitViaPrompt], { index, lngLat: [vertex[0] ?? 0, vertex[1] ?? 0] });
1892
+ }
1893
+ /**
1894
+ * runInteractiveWrite flags a store-API write as an interactive click write for
1895
+ * the duration of `write`, so handleChange emits its api-origin change as an
1896
+ * interactive draft (an undo step) rather than a skipped programmatic echo. The
1897
+ * flag is always cleared, even if the write throws (a validation rejection), so a
1898
+ * later programmatic write is never mis-flagged.
1899
+ */
1900
+ runInteractiveWrite(write) {
1901
+ this.interactiveWrite = true;
1902
+ try {
1903
+ write();
1904
+ } finally {
1905
+ this.interactiveWrite = false;
1906
+ }
1907
+ }
1908
+ /**
1909
+ * consumeClick blocks sibling MapLibre click listeners from also acting on a
1910
+ * click the engine turned into a vertex edit (a feature-select handler, say).
1911
+ * TerraDraw already handled its own handle gestures on the preceding pointerup,
1912
+ * so this does NOT gate TerraDraw — it only stops other MapLibre listeners on the
1913
+ * same synthetic click.
1914
+ */
1915
+ consumeClick(event) {
1916
+ event.preventDefault();
1917
+ const originalEvent = event.originalEvent;
1918
+ if (originalEvent && typeof originalEvent.stopPropagation === "function") {
1919
+ originalEvent.stopPropagation();
1920
+ }
1921
+ }
1922
+ };
1923
+
1924
+ // src/editing/engines/draftMarker.ts
1925
+ var DRAFT_SOURCE = "td-waypoint-draft-source";
1926
+ var DRAFT_LAYER = "td-waypoint-draft-layer";
1927
+ var DraftWaypointMarker = class {
1928
+ constructor(map, placement) {
1929
+ this.map = map;
1930
+ this.placement = placement;
1931
+ }
1932
+ map;
1933
+ placement;
1934
+ lastSnapshot = null;
1935
+ apply(snapshot) {
1936
+ this.lastSnapshot = snapshot;
1937
+ const data = {
1938
+ geometry: { coordinates: snapshot.lngLat, type: "Point" },
1939
+ properties: {},
1940
+ type: "Feature"
1941
+ };
1942
+ const existing = this.map.getSource(DRAFT_SOURCE);
1943
+ if (chunkAFKOABJ4_cjs.isGeoJsonSource(existing)) {
1944
+ existing.setData(data);
1945
+ this.ensureLayerIcon(snapshot);
1946
+ return;
1947
+ }
1948
+ this.map.addSource(DRAFT_SOURCE, { data, type: "geojson" });
1949
+ this.placement.addLayerOrdered(
1950
+ {
1951
+ id: DRAFT_LAYER,
1952
+ layout: {
1953
+ "icon-allow-overlap": true,
1954
+ "icon-ignore-placement": true,
1955
+ "icon-image": chunk7CUBXHAH_cjs.waypointIconImageId(snapshot.icon, snapshot.color),
1956
+ "icon-size": 0.7
1957
+ },
1958
+ source: DRAFT_SOURCE,
1959
+ type: "symbol"
1960
+ },
1961
+ 100 /* CHROME */
1962
+ );
1963
+ }
1964
+ setStyle(style) {
1965
+ if (!this.lastSnapshot) {
1966
+ return;
1967
+ }
1968
+ this.lastSnapshot = { ...this.lastSnapshot, ...style };
1969
+ this.ensureLayerIcon(this.lastSnapshot);
1970
+ }
1971
+ clear() {
1972
+ this.placement.forgetLayerRank(DRAFT_LAYER);
1973
+ if (this.map.getSource(DRAFT_SOURCE)) {
1974
+ this.map.removeSource(DRAFT_SOURCE);
1975
+ }
1976
+ this.lastSnapshot = null;
1977
+ }
1978
+ /**
1979
+ * replay re-adds the marker after a base-map switch has wiped the style.
1980
+ * The last known draft is re-applied; if no draft ever landed the call is
1981
+ * a no-op (a first placement post-reload still drops a fresh marker via
1982
+ * `apply`).
1983
+ */
1984
+ replay() {
1985
+ if (!this.lastSnapshot) {
1986
+ return;
1987
+ }
1988
+ const snapshot = this.lastSnapshot;
1989
+ this.lastSnapshot = null;
1990
+ this.apply(snapshot);
1991
+ }
1992
+ read() {
1993
+ return this.lastSnapshot;
1994
+ }
1995
+ /**
1996
+ * ensureLayerIcon writes the current snapshot's icon-image onto the symbol
1997
+ * layer, guarded by `getLayer` because the layer may not exist (a first
1998
+ * `setStyle` before any `apply`) or may be mid-rebuild on a terrain
1999
+ * switch.
2000
+ */
2001
+ ensureLayerIcon(snapshot) {
2002
+ if (!this.map.getLayer(DRAFT_LAYER)) {
2003
+ return;
2004
+ }
2005
+ this.map.setLayoutProperty(
2006
+ DRAFT_LAYER,
2007
+ "icon-image",
2008
+ chunk7CUBXHAH_cjs.waypointIconImageId(snapshot.icon, snapshot.color)
2009
+ );
2010
+ }
2011
+ };
2012
+
2013
+ // src/draw/rules/snapCameraKey.ts
2014
+ var PROJECTION_PROBE_OFFSET_DEG = 1e-3;
2015
+ var snapCameraKey = (map) => {
2016
+ const center = map.getCenter();
2017
+ const canvas = map.getCanvas();
2018
+ const at = map.project(center);
2019
+ const beside = map.project({
2020
+ lat: center.lat + PROJECTION_PROBE_OFFSET_DEG,
2021
+ lng: center.lng + PROJECTION_PROBE_OFFSET_DEG
2022
+ });
2023
+ return `${map.getZoom()}|${center.lng}|${center.lat}|${map.getBearing()}|${map.getPitch()}|${canvas.width}|${canvas.height}|${at.x}|${at.y}|${beside.x}|${beside.y}`;
2024
+ };
2025
+
2026
+ // src/draw/engines/pointerCursor.ts
2027
+ var svgElementOf = (owner, node) => {
2028
+ const element = owner.createElementNS(chunkSSKSSBWJ_cjs.SVG_NAMESPACE, node.tag);
2029
+ for (const [name, value] of Object.entries(node.attributes)) {
2030
+ element.setAttribute(name, value);
2031
+ }
2032
+ for (const child of node.children ?? []) {
2033
+ element.append(svgElementOf(owner, child));
2034
+ }
2035
+ return element;
2036
+ };
2037
+ var PointerWaypointCursor = class {
2038
+ /**
2039
+ * @throws {MountayaElementsError} When `options.size` is not a finite number above 6, twice
2040
+ * the ring's inset. Nothing is mounted before the size is read, so a refused cursor leaves no
2041
+ * node behind.
2042
+ */
2043
+ constructor(map, initial, options) {
2044
+ this.map = map;
2045
+ this.options = options;
2046
+ this.currentStyle = initial;
2047
+ this.node = document.createElement("div");
2048
+ this.paint();
2049
+ Object.assign(this.node.style, {
2050
+ height: `${options.size}px`,
2051
+ left: "0",
2052
+ pointerEvents: "none",
2053
+ position: "absolute",
2054
+ top: "0",
2055
+ // Offscreen until the first setPosition lands — the canvas container
2056
+ // can mount the element before the engine has seen its first
2057
+ // mousemove, and a (0, 0) start would flash the cursor in the corner.
2058
+ transform: "translate3d(-9999px, -9999px, 0)",
2059
+ visibility: "visible",
2060
+ width: `${options.size}px`,
2061
+ // Compositor-friendly transform updates per frame: the browser keeps
2062
+ // the element on its own layer and never repaints the canvas to move
2063
+ // the cursor.
2064
+ willChange: "transform",
2065
+ // Above the canvas + the TerraDraw draw layers but below modals / the
2066
+ // sidenav, so the cursor reads as part of the map.
2067
+ zIndex: "5"
2068
+ });
2069
+ }
2070
+ map;
2071
+ options;
2072
+ node;
2073
+ currentStyle;
2074
+ mounted = false;
2075
+ /**
2076
+ * attach mounts the cursor element into MapLibre's canvas container. A
2077
+ * repeated call is a no-op so a style-reload replay can re-call without
2078
+ * stacking siblings.
2079
+ */
2080
+ attach() {
2081
+ if (this.mounted) {
2082
+ return;
2083
+ }
2084
+ this.map.getCanvasContainer().appendChild(this.node);
2085
+ this.mounted = true;
2086
+ }
2087
+ /**
2088
+ * setStyle re-paints the cursor with the given icon glyph and color, so a
2089
+ * side-panel attribute flip updates the visible cursor live without a
2090
+ * re-attach round-trip. The element node stays the same; only the drawing
2091
+ * under it is replaced.
2092
+ */
2093
+ setStyle(style) {
2094
+ this.currentStyle = style;
2095
+ this.paint();
2096
+ }
2097
+ /**
2098
+ * setPosition writes a `transform: translate3d(...)` so the cursor is
2099
+ * centred on the given canvas pixel. Centering subtracts half the canvas
2100
+ * size from the pixel — the cursor sprite's hotspot is its own centre,
2101
+ * matching the OS cursor's `Xhot Yhot` and the tile sprite's icon centre.
2102
+ */
2103
+ setPosition(point) {
2104
+ const half = this.options.size / 2;
2105
+ this.node.style.transform = `translate3d(${point.x - half}px, ${point.y - half}px, 0)`;
2106
+ }
2107
+ /**
2108
+ * setVisible toggles the element's `visibility` so a pointer-out hides the
2109
+ * cursor cleanly + a pointer-in shows it again, all without unmounting
2110
+ * (the next setPosition would otherwise need to wait until the element
2111
+ * re-attaches). `visibility: hidden` keeps the layout slot live so the
2112
+ * compositor layer survives the round trip.
2113
+ */
2114
+ setVisible(visible) {
2115
+ this.node.style.visibility = visible ? "visible" : "hidden";
2116
+ }
2117
+ /**
2118
+ * dispose removes the cursor element from the canvas container. A
2119
+ * repeated call is a no-op so a teardown that fires after a style-reload
2120
+ * unmount leaves the DOM untouched.
2121
+ */
2122
+ dispose() {
2123
+ if (!this.mounted) {
2124
+ return;
2125
+ }
2126
+ this.node.remove();
2127
+ this.mounted = false;
2128
+ }
2129
+ /**
2130
+ * paint replaces the element's drawing with the current style's, built node by node from the
2131
+ * tree {@link describeWaypointSvg} answers. The data-URL cursor writes the same tree as text,
2132
+ * so both visible cursors paint the identical glyph in the identical canvas.
2133
+ *
2134
+ * The draft colour and the provider's markup never reach `innerHTML`: the colour is set as an
2135
+ * attribute value and the glyph arrives as parsed shapes, so neither becomes an element of the
2136
+ * host page.
2137
+ */
2138
+ paint() {
2139
+ const drawing = chunkSSKSSBWJ_cjs.describeWaypointSvg(
2140
+ { ...this.currentStyle, ...this.options },
2141
+ "PointerWaypointCursor"
2142
+ );
2143
+ this.node.replaceChildren(svgElementOf(this.node.ownerDocument, drawing));
2144
+ }
2145
+ };
2146
+
2147
+ // src/draw/engines/snapIndex.ts
2148
+ var ScreenSpaceSnapIndex = class {
2149
+ // The camera key the cached projection was built under. A query whose key
2150
+ // differs has a different projection, so the cache is rebuilt. Null until
2151
+ // the first build.
2152
+ cachedCameraKey = null;
2153
+ // The per-line coordinate-array references the cache was built from, held so
2154
+ // swapping ONE line's geometry (an immutable store edit) rebuilds while the
2155
+ // studio re-wrapping the same inner refs in a fresh outer array does not. The
2156
+ // outer array's own identity is deliberately NOT tracked: the studio sync
2157
+ // effect mints a fresh outer array on unrelated dependency changes, and the
2158
+ // per-line ref + length compare fully captures whether the geometry changed,
2159
+ // so keying on the wrapper would force a pointless reprojection on every such
2160
+ // re-wrap.
2161
+ cachedLineRefs = [];
2162
+ // The built per-line screen-space projection, parallel to cachedLineRefs.
2163
+ cachedLines = [];
2164
+ /**
2165
+ * snap returns the cursor's (possibly snapped) lng/lat plus a `snapped`
2166
+ * discriminator, matching {@link snapToActiveSegments} byte-for-byte across
2167
+ * its corner cases (empty segments, single-vertex lines, nullish-coordinate
2168
+ * holes, and the `>` threshold boundary) while projecting only the cursor
2169
+ * in steady state.
2170
+ *
2171
+ * The flow mirrors the un-cached helper: an empty candidate list short-
2172
+ * circuits with the input verbatim and zero project/unproject calls; a
2173
+ * non-empty list projects the cursor once, walks every cached edge tracking
2174
+ * the best squared distance, rejects when the best exceeds threshold-squared
2175
+ * (the `>` comparison admits a point exactly at the bound), and on a hit
2176
+ * unprojects the single best pixel back to a coordinate.
2177
+ */
2178
+ snap(input) {
2179
+ const { cameraKey, lngLat, map, segments, thresholdPx } = input;
2180
+ if (segments.length === 0) {
2181
+ return { lngLat, snapped: false };
2182
+ }
2183
+ this.ensureBuilt(cameraKey, map, segments);
2184
+ const cursorPx = map.project({ lat: lngLat[1] ?? 0, lng: lngLat[0] ?? 0 });
2185
+ let bestDistSq = Number.POSITIVE_INFINITY;
2186
+ let bestPx = null;
2187
+ for (const line of this.cachedLines) {
2188
+ if (!line.hasBbox) {
2189
+ continue;
2190
+ }
2191
+ if (cursorPx.x < line.bbox.minX - thresholdPx || cursorPx.x > line.bbox.maxX + thresholdPx || cursorPx.y < line.bbox.minY - thresholdPx || cursorPx.y > line.bbox.maxY + thresholdPx) {
2192
+ continue;
2193
+ }
2194
+ const { pixels, valid } = line;
2195
+ const count = valid.length;
2196
+ for (let i = 1; i < count; i++) {
2197
+ if (valid[i - 1] === 0 || valid[i] === 0) {
2198
+ continue;
2199
+ }
2200
+ const a = { x: pixels[(i - 1) * 2] ?? 0, y: pixels[(i - 1) * 2 + 1] ?? 0 };
2201
+ const b = { x: pixels[i * 2] ?? 0, y: pixels[i * 2 + 1] ?? 0 };
2202
+ const projected = projectPointToSegmentPx(cursorPx, a, b);
2203
+ const distSq = sqDist(cursorPx, projected);
2204
+ if (distSq < bestDistSq) {
2205
+ bestDistSq = distSq;
2206
+ bestPx = projected;
2207
+ }
2208
+ }
2209
+ }
2210
+ if (bestPx === null || bestDistSq > thresholdPx * thresholdPx) {
2211
+ return { lngLat, snapped: false };
2212
+ }
2213
+ const snapped = map.unproject([bestPx.x, bestPx.y]);
2214
+ return { lngLat: [snapped.lng, snapped.lat], snapped: true };
2215
+ }
2216
+ /**
2217
+ * ensureBuilt rebuilds the cached projection when it is stale and is a no-op
2218
+ * when it is current. The cache is stale when (a) the camera key differs from
2219
+ * the build key (the projection changed) or (b) any per-line
2220
+ * coordinate-array reference differs, including the line count (a line was
2221
+ * added, removed, or swapped). The per-line compare is O(lines) and cheap; it
2222
+ * is what lets the studio re-wrap the same immutable line refs in a fresh
2223
+ * outer array every render without forcing a pointless reprojection, while a
2224
+ * real geometry swap (a new inner array) still rebuilds.
2225
+ */
2226
+ ensureBuilt(cameraKey, map, segments) {
2227
+ if (this.cachedCameraKey === cameraKey && this.lineRefsMatch(segments)) {
2228
+ return;
2229
+ }
2230
+ this.build(cameraKey, map, segments);
2231
+ }
2232
+ /**
2233
+ * lineRefsMatch reports whether every line's coordinate-array reference is
2234
+ * identical to the one the cache was built from. A length or reference
2235
+ * mismatch means a line was added, removed, or swapped, so the cache must
2236
+ * rebuild. The reference compare is the immutability assumption in action:
2237
+ * unchanged geometry keeps its array identity, a real edit produces a new
2238
+ * array.
2239
+ */
2240
+ lineRefsMatch(segments) {
2241
+ if (segments.length !== this.cachedLineRefs.length) {
2242
+ return false;
2243
+ }
2244
+ for (let i = 0; i < segments.length; i++) {
2245
+ if (segments[i] !== this.cachedLineRefs[i]) {
2246
+ return false;
2247
+ }
2248
+ }
2249
+ return true;
2250
+ }
2251
+ /**
2252
+ * build projects every coordinate of every segment once and records, per
2253
+ * line, the interleaved pixel array, the per-coordinate validity, and the
2254
+ * screen-space bbox of the valid pixels. A nullish coordinate is left
2255
+ * invalid (and unprojected) so the query reproduces the hole semantics; a
2256
+ * line with fewer than two valid pixels carries no bbox and is unsnappable.
2257
+ */
2258
+ build(cameraKey, map, segments) {
2259
+ const lines = [];
2260
+ for (const line of segments) {
2261
+ const length = line.length;
2262
+ const pixels = new Float64Array(length * 2);
2263
+ const valid = new Uint8Array(length);
2264
+ let minX = Number.POSITIVE_INFINITY;
2265
+ let minY = Number.POSITIVE_INFINITY;
2266
+ let maxX = Number.NEGATIVE_INFINITY;
2267
+ let maxY = Number.NEGATIVE_INFINITY;
2268
+ let validCount = 0;
2269
+ for (let i = 0; i < length; i++) {
2270
+ const coord = line[i];
2271
+ if (!coord) {
2272
+ continue;
2273
+ }
2274
+ const px = map.project({ lat: coord[1] ?? 0, lng: coord[0] ?? 0 });
2275
+ pixels[i * 2] = px.x;
2276
+ pixels[i * 2 + 1] = px.y;
2277
+ valid[i] = 1;
2278
+ validCount++;
2279
+ if (px.x < minX) {
2280
+ minX = px.x;
2281
+ }
2282
+ if (px.x > maxX) {
2283
+ maxX = px.x;
2284
+ }
2285
+ if (px.y < minY) {
2286
+ minY = px.y;
2287
+ }
2288
+ if (px.y > maxY) {
2289
+ maxY = px.y;
2290
+ }
2291
+ }
2292
+ const hasBbox = validCount >= 2;
2293
+ lines.push({ bbox: { maxX, maxY, minX, minY }, hasBbox, pixels, valid });
2294
+ }
2295
+ this.cachedCameraKey = cameraKey;
2296
+ this.cachedLineRefs = segments.slice();
2297
+ this.cachedLines = lines;
2298
+ }
2299
+ };
2300
+
2301
+ // src/draw/engines/waypointEngine.ts
2302
+ var POINT_MODE = "point";
2303
+ var WAYPOINT_TERRADRAW_PREFIX = "td-waypoint";
2304
+ var buildWaypointPointMode = () => new terraDraw.TerraDrawPointMode({ styles: { pointOpacity: 0, pointOutlineOpacity: 0 } });
2305
+ var defaultWaypointDrawFactory = ({ map, prefixId }) => new terraDraw.TerraDraw({
2306
+ adapter: new FramedMapLibreAdapter({ map, prefixId }, { longitude: 0 }),
2307
+ idStrategy: drawIdStrategy,
2308
+ modes: [buildWaypointPointMode()]
2309
+ });
2310
+ var TerraDrawPointWaypointEngine = class {
2311
+ /**
2312
+ * @throws {MountayaElementsError} When `options.initialLngLat` is neither `null` nor a
2313
+ * longitude and a latitude a map can place: two finite numbers, the latitude from -90 to 90.
2314
+ * It is refused before the drawing library is built, so a refused edit leaves nothing on the
2315
+ * map.
2316
+ */
2317
+ constructor(map, placement, options, emitChange, createDraw = defaultWaypointDrawFactory, getSnapSegments = () => [], events, cursor, pointerCursorOptions) {
2318
+ this.map = map;
2319
+ this.emitChange = emitChange;
2320
+ this.getSnapSegments = getSnapSegments;
2321
+ const initialLngLat = readEditPosition(
2322
+ options.initialLngLat,
2323
+ "TerraDrawPointWaypointEngine",
2324
+ "initialLngLat",
2325
+ "pass null for a waypoint not placed yet"
2326
+ );
2327
+ this.currentIcon = options.initialIcon;
2328
+ this.currentColor = options.initialColor;
2329
+ this.events = events ?? null;
2330
+ this.cursor = cursor ?? null;
2331
+ this.pointerCursor = events && pointerCursorOptions ? new PointerWaypointCursor(
2332
+ this.map,
2333
+ { color: this.currentColor, icon: this.currentIcon },
2334
+ pointerCursorOptions
2335
+ ) : null;
2336
+ this.marker = new DraftWaypointMarker(this.map, placement);
2337
+ const validation = () => ({ valid: true });
2338
+ this.draw = createDraw({ map: this.map, prefixId: WAYPOINT_TERRADRAW_PREFIX, validation });
2339
+ this.changeHandler = (ids, type, context) => {
2340
+ this.handleChange(ids, type, isProgrammaticChange(context));
2341
+ };
2342
+ this.draw.start();
2343
+ this.draw.setMode(POINT_MODE);
2344
+ this.draw.on("change", this.changeHandler);
2345
+ this.detachCursorReassert = this.attachCursorReassert();
2346
+ if (initialLngLat) {
2347
+ this.marker.apply({
2348
+ color: this.currentColor,
2349
+ icon: this.currentIcon,
2350
+ lngLat: initialLngLat
2351
+ });
2352
+ }
2353
+ if (events && this.pointerCursor) {
2354
+ this.pointerCursor.attach();
2355
+ this.detachPointerMove = events.on("mousemove", (event) => {
2356
+ this.lastPointerEvent = {
2357
+ lngLat: [event.lngLat.lng, event.lngLat.lat],
2358
+ point: { x: event.point.x, y: event.point.y }
2359
+ };
2360
+ if (this.pointerFrame !== null) {
2361
+ return;
2362
+ }
2363
+ this.pointerFrame = requestAnimationFrame(() => {
2364
+ this.pointerFrame = null;
2365
+ this.placePointerCursor();
2366
+ });
2367
+ });
2368
+ this.detachPointerOut = events.on("mouseout", () => {
2369
+ this.pointerCursor?.setVisible(false);
2370
+ });
2371
+ this.detachPointerIn = events.on("mouseover", () => {
2372
+ this.pointerCursor?.setVisible(true);
2373
+ });
2374
+ }
2375
+ }
2376
+ map;
2377
+ emitChange;
2378
+ getSnapSegments;
2379
+ draw;
2380
+ marker;
2381
+ // The DOM pointer cursor that visibly tracks the pointer (snap-aware). The
2382
+ // OS cursor is hidden during a waypoint edit (`cursor: none` on the canvas
2383
+ // through the hook's lockCursor), so this element is the only visible
2384
+ // cursor the user sees — when snap engages, it jumps onto the segment and
2385
+ // glides along it. Null when no event engine is wired (the factory-only
2386
+ // path a unit test takes), so the renderer-less engine still constructs.
2387
+ pointerCursor;
2388
+ currentIcon;
2389
+ currentColor;
2390
+ // The map event engine the cursor re-assert + pointer listeners detach
2391
+ // through; null when none is wired (the factory-only unit-test path). Held so
2392
+ // the style-reload replay re-attaches the re-assert by reference rather than
2393
+ // leaking onto the rebuilt scene.
2394
+ events;
2395
+ // The cursor controller the engine re-asserts the locked cursor through;
2396
+ // null when no event engine is wired (the factory-only unit-test path), so
2397
+ // the renderer-less engine still constructs. The hook locks `"none"` for the
2398
+ // whole edit so the DOM PointerWaypointCursor is the only visible cursor —
2399
+ // but TerraDraw's point mode writes `canvas.style.cursor = "crosshair"` on
2400
+ // every move, which would clobber that lock; the controller re-pins it.
2401
+ cursor;
2402
+ // The TerraDraw feature id of the currently-rendered draft point, held so
2403
+ // the next click can delete it before the new one is accepted (the
2404
+ // single-feature invariant).
2405
+ draftFeatureId = null;
2406
+ // Detaches the map-level mousemove cursor re-assert (our listener through the
2407
+ // shared event engine), set when the engine attaches and cleared on dispose
2408
+ // / replay. It counters TerraDraw's point mode, which writes the canvas
2409
+ // cursor directly on every move (`setCursor("crosshair")` through the adapter)
2410
+ // — over empty map that would wipe the `"none"` lock the hook holds, so the
2411
+ // DOM pointer cursor would race a flickering OS crosshair. Re-pinning the lock
2412
+ // after TerraDraw's write keeps `"none"` intact. Unlike the directions engine
2413
+ // it does NOT touch drag-pan: a waypoint edit never locks the map (panning
2414
+ // stays enabled), and TerraDraw only toggles drag-pan during an actual drag
2415
+ // gesture, never on a plain move over empty map.
2416
+ detachCursorReassert = null;
2417
+ // Detaches the canvas mousemove + pointer-out + pointer-in listeners that
2418
+ // drive the visible cursor: every frame the pointer moves, the cursor
2419
+ // re-positions at the snapped foot when within threshold or at the raw
2420
+ // cursor when outside; an out hides it, an in shows it. Held so dispose
2421
+ // tears the listeners down by reference and a teardown leaves nothing
2422
+ // pointing at the disposed engine. Null when no event engine is wired.
2423
+ detachPointerMove = null;
2424
+ detachPointerOut = null;
2425
+ detachPointerIn = null;
2426
+ // The rAF id of the pending visual-snap frame, so a burst of mousemove
2427
+ // events coalesces into a single cursor reposition per frame. Cleared in
2428
+ // the frame handler and on dispose.
2429
+ pointerFrame = null;
2430
+ // The latest mousemove event the engine saw, read by the rAF frame so the
2431
+ // latest pixel wins when several events fire between frames. Carries both
2432
+ // the lng/lat (for snap) and the raw canvas pixel (used directly when snap
2433
+ // is inactive, sparing a re-project).
2434
+ lastPointerEvent = null;
2435
+ // Caches the screen-space projection of the active itinerary's segments so the
2436
+ // magnet does not re-project every coordinate of every segment on every frame.
2437
+ // One per engine (so its cache lives exactly as long as the edit) and shared by
2438
+ // both snap call sites (the rAF cursor frame and the click-commit handler), so
2439
+ // a move and the click that follows reuse the same warm cache when the camera
2440
+ // and geometry have not changed.
2441
+ snapIndex = new ScreenSpaceSnapIndex();
2442
+ // The stable change-listener reference, held so the pre-swap detach can `off` exactly
2443
+ // what the constructor registered. A TerraDraw listener lives on the instance rather
2444
+ // than on the adapter, so `stop()` does NOT drop it — an inline closure per replay
2445
+ // would stack one more binding on every base-map switch.
2446
+ changeHandler;
2447
+ setDraftStyle(style) {
2448
+ this.currentColor = style.color;
2449
+ this.currentIcon = style.icon;
2450
+ this.marker.setStyle(style);
2451
+ this.pointerCursor?.setStyle(style);
2452
+ }
2453
+ readDraft() {
2454
+ return this.marker.read();
2455
+ }
2456
+ clearDraft() {
2457
+ this.marker.clear();
2458
+ if (this.draftFeatureId !== null && this.draw.enabled) {
2459
+ this.draw.removeFeatures([this.draftFeatureId]);
2460
+ }
2461
+ this.draftFeatureId = null;
2462
+ }
2463
+ applyDraft(snapshot) {
2464
+ this.currentColor = snapshot.color;
2465
+ this.currentIcon = snapshot.icon;
2466
+ this.marker.apply(snapshot);
2467
+ this.pointerCursor?.setStyle({ color: snapshot.color, icon: snapshot.icon });
2468
+ }
2469
+ dispose() {
2470
+ this.detachCursorReassert?.();
2471
+ this.detachCursorReassert = null;
2472
+ this.detachPointerMove?.();
2473
+ this.detachPointerMove = null;
2474
+ this.detachPointerOut?.();
2475
+ this.detachPointerOut = null;
2476
+ this.detachPointerIn?.();
2477
+ this.detachPointerIn = null;
2478
+ if (this.pointerFrame !== null) {
2479
+ cancelAnimationFrame(this.pointerFrame);
2480
+ this.pointerFrame = null;
2481
+ }
2482
+ this.lastPointerEvent = null;
2483
+ this.pointerCursor?.dispose();
2484
+ this.marker.clear();
2485
+ this.draw.off("change", this.changeHandler);
2486
+ if (this.draw.enabled) {
2487
+ this.draw.clear();
2488
+ }
2489
+ this.draw.stop();
2490
+ }
2491
+ /**
2492
+ * detachBeforeStyleReload stops TerraDraw before the swap, so the replay's `start()`
2493
+ * actually re-registers the adapter. See {@link EditEngine.detachBeforeStyleReload}
2494
+ * for why the pair is needed and why the order is load-bearing: the adapter's
2495
+ * `unregister()` removes five layers and three sources unguarded, which succeeds
2496
+ * silently on the outgoing style and is noisy-then-fatal on the incoming one.
2497
+ *
2498
+ * This family's VISIBLE overlay is the shared draft marker, which the client re-adds
2499
+ * itself — so the surface looked like it survived a switch while the TerraDraw
2500
+ * instance under it did not, and nothing said so until the edit ended and the
2501
+ * teardown reached the removed sources. The detach is what closes that gap, and the
2502
+ * marker is untouched here: it owns its own replay.
2503
+ */
2504
+ detachBeforeStyleReload() {
2505
+ this.draw.off("change", this.changeHandler);
2506
+ this.draw.stop();
2507
+ this.draftFeatureId = null;
2508
+ }
2509
+ /**
2510
+ * replayAfterStyleReload re-renders the active edit's scene after a base-map
2511
+ * switch wiped the style. It re-attaches only what setStyle tore down: the
2512
+ * library's layers + change listener, the marker's source + symbol layer, and
2513
+ * the visible pointer cursor (its parent canvas container is rebuilt). It does
2514
+ * NOT re-attach the magnet's map-level pointer subscriptions (the
2515
+ * mousemove/mouseout/mouseover the constructor bound with no layerId): a
2516
+ * map-level listener survives setStyle untouched — only layer-scoped listeners
2517
+ * and library layers come off — so re-attaching here would double-bind them.
2518
+ * The cursor re-assert is the one exception: its listener was scoped to the
2519
+ * torn-down cursor scene, so it is detached and rebuilt clean.
2520
+ *
2521
+ * It is the second half of a pair: {@link detachBeforeStyleReload} must have stopped
2522
+ * the instance before the swap, or the `start()` below returns early and re-registers
2523
+ * nothing — which for this family is invisible until the edit ends.
2524
+ */
2525
+ replayAfterStyleReload() {
2526
+ this.draw.start();
2527
+ this.draw.setMode(POINT_MODE);
2528
+ this.draw.on("change", this.changeHandler);
2529
+ this.marker.replay();
2530
+ this.pointerCursor?.attach();
2531
+ this.detachCursorReassert?.();
2532
+ this.detachCursorReassert = this.attachCursorReassert();
2533
+ }
2534
+ /**
2535
+ * handleChange enforces the single-draft-point invariant and emits a
2536
+ * change for each interactive click. A programmatic addFeatures from
2537
+ * `applyWaypointDraft` (if any) is skipped — the marker is the rendering
2538
+ * target and TerraDraw's own point store is just an event source for the
2539
+ * waypoint engine.
2540
+ */
2541
+ handleChange(ids, type, programmatic) {
2542
+ if (programmatic) {
2543
+ return;
2544
+ }
2545
+ if (type !== "create") {
2546
+ return;
2547
+ }
2548
+ const id = ids[0];
2549
+ if (id === void 0) {
2550
+ return;
2551
+ }
2552
+ const feature = this.draw.getSnapshotFeature(id);
2553
+ if (feature?.geometry.type !== "Point") {
2554
+ return;
2555
+ }
2556
+ const [lng, lat] = feature.geometry.coordinates;
2557
+ const rawLngLat = pointerPosition({ lat: lat ?? 0, lng: lng ?? 0 });
2558
+ const snap = this.snapOnto(rawLngLat);
2559
+ const lngLat = [snap.lngLat[0] ?? 0, snap.lngLat[1] ?? 0];
2560
+ if (this.draftFeatureId !== null && this.draftFeatureId !== id) {
2561
+ this.draw.removeFeatures([this.draftFeatureId]);
2562
+ }
2563
+ this.draftFeatureId = id;
2564
+ this.marker.apply({ color: this.currentColor, icon: this.currentIcon, lngLat });
2565
+ chunkWW4CGS7G_cjs.notifyListeners([this.emitChange], { lngLat, poiSeed: null });
2566
+ }
2567
+ /**
2568
+ * placePointerCursor puts the visible cursor where the latest pointer move lands once the
2569
+ * magnet has had its say: on the foot of the snap, or under the pointer. It is the body of
2570
+ * the frame the move listener asks for, and it does nothing with no move to read.
2571
+ */
2572
+ placePointerCursor() {
2573
+ const latest = this.lastPointerEvent;
2574
+ if (!latest || !this.pointerCursor) {
2575
+ return;
2576
+ }
2577
+ const [pointerLng, pointerLat] = latest.lngLat;
2578
+ const snap = this.snapOnto(pointerPosition({ lat: pointerLat, lng: pointerLng }));
2579
+ if (snap.snapped) {
2580
+ const footLng = snap.lngLat[0] ?? 0;
2581
+ const target = this.map.project({
2582
+ lat: snap.lngLat[1] ?? 0,
2583
+ lng: footLng + chunkAG6JV5Z2_cjs.DEGREES_PER_TURN * Math.round((pointerLng - footLng) / chunkAG6JV5Z2_cjs.DEGREES_PER_TURN)
2584
+ });
2585
+ this.pointerCursor.setPosition({ x: target.x, y: target.y });
2586
+ return;
2587
+ }
2588
+ this.pointerCursor.setPosition(latest.point);
2589
+ }
2590
+ /**
2591
+ * snapOnto answers where a position lands once the magnet has had its say: on the nearest
2592
+ * active-itinerary segment within {@link SNAP_THRESHOLD_PX}, or where it was.
2593
+ *
2594
+ * With no segment there is nothing to project and the camera is not read at all, so a map
2595
+ * double with no projection still carries an edit that has no itinerary under it.
2596
+ */
2597
+ snapOnto(lngLat) {
2598
+ const segments = this.getSnapSegments();
2599
+ return this.snapIndex.snap({
2600
+ cameraKey: segments.length === 0 ? "" : snapCameraKey(this.map),
2601
+ lngLat,
2602
+ map: this.map,
2603
+ segments,
2604
+ thresholdPx: SNAP_THRESHOLD_PX
2605
+ });
2606
+ }
2607
+ /**
2608
+ * attachCursorReassert subscribes the shared map-level mousemove re-assert that
2609
+ * re-pins the held lock after TerraDraw's point mode has written the canvas
2610
+ * cursor. The point mode writes `setCursor("crosshair")` through the adapter on
2611
+ * every move — over empty map that would wipe the `"none"` lock the hook holds,
2612
+ * leaving the DOM PointerWaypointCursor racing a flickering OS crosshair.
2613
+ * {@link attachCursorReassert} re-pins `"none"` through the controller after
2614
+ * TerraDraw's write.
2615
+ *
2616
+ * The shared utility leaves drag-pan untouched, which is exactly right here:
2617
+ * unlike the directions engine a waypoint edit never locks the map (panning
2618
+ * stays enabled), and TerraDraw only toggles drag-pan inside a drag gesture,
2619
+ * never on a plain move over empty map. A no-op (no listener) when the event
2620
+ * manager or the cursor controller is absent — the factory-injection unit-test
2621
+ * path, which never holds a lock.
2622
+ */
2623
+ attachCursorReassert() {
2624
+ if (!this.events || !this.cursor) {
2625
+ return null;
2626
+ }
2627
+ return chunkIBQJDVHF_cjs.attachCursorReassert(this.events, this.cursor);
2628
+ }
2629
+ };
2630
+ var OUTLINE_POSITIONS_JUDGED_MAX = 1e3;
2631
+ var admitted = { valid: true };
2632
+ var ringOf = (feature) => feature.geometry.type === "Polygon" ? feature.geometry.coordinates[0] ?? null : null;
2633
+ var judged = ({ kind, positions }) => terraDraw.ValidateNotSelfIntersecting({
2634
+ geometry: kind === "ring" ? { coordinates: [positions], type: "Polygon" } : { coordinates: positions, type: "LineString" },
2635
+ properties: {},
2636
+ type: "Feature"
2637
+ });
2638
+ var drawnOnTheMap = ({ kind, positions }) => {
2639
+ const projected = [];
2640
+ for (const [longitude = Number.NaN, latitude = Number.NaN] of positions) {
2641
+ if (Math.abs(latitude) >= chunkL6TZ2HQR_cjs.LATITUDE_LIMIT) {
2642
+ return null;
2643
+ }
2644
+ const sine = Math.sin(latitude * chunkAG6JV5Z2_cjs.DEGREES_TO_RADIANS);
2645
+ projected.push([longitude, Math.log((1 + sine) / (1 - sine)) / 2 * chunkAG6JV5Z2_cjs.RADIANS_TO_DEGREES]);
2646
+ }
2647
+ return { kind, positions: projected };
2648
+ };
2649
+ var onTheMap = (shape) => {
2650
+ const drawn = drawnOnTheMap(shape);
2651
+ return drawn === null ? admitted : judged(drawn);
2652
+ };
2653
+ var crossingOf = (shape) => {
2654
+ const stored = judged(shape);
2655
+ return stored.valid ? onTheMap(shape) : stored;
2656
+ };
2657
+ var drawnOutlineVerdict = (feature, updateType) => {
2658
+ const ring = ringOf(feature);
2659
+ if (ring === null || ring.length > OUTLINE_POSITIONS_JUDGED_MAX) {
2660
+ return admitted;
2661
+ }
2662
+ if (updateType === "finish") {
2663
+ return crossingOf({ kind: "ring", positions: ring });
2664
+ }
2665
+ return crossingOf({ kind: "path", positions: ring.slice(0, -1) });
2666
+ };
2667
+ var reshapedOutlineVerdict = (feature, standing, updateType) => {
2668
+ const ring = ringOf(feature);
2669
+ if (ring === null || standing === null || ring.length > OUTLINE_POSITIONS_JUDGED_MAX) {
2670
+ return admitted;
2671
+ }
2672
+ const judge = updateType === "provisional" ? onTheMap : updateType === "commit" && ring.length < standing.length ? crossingOf : null;
2673
+ if (judge === null) {
2674
+ return admitted;
2675
+ }
2676
+ const verdict = judge({ kind: "ring", positions: ring });
2677
+ if (verdict.valid || !judge({ kind: "ring", positions: standing }).valid) {
2678
+ return admitted;
2679
+ }
2680
+ return verdict;
2681
+ };
2682
+
2683
+ // src/draw/engines/zoneEngine.ts
2684
+ var ZONE_TERRADRAW_PREFIX = "td-zone";
2685
+ var ZONE_VERTEX_LAYER_ID = `${ZONE_TERRADRAW_PREFIX}-point`;
2686
+ var ZONE_FILL_LAYER_ID = `${ZONE_TERRADRAW_PREFIX}-polygon`;
2687
+ var zoneRefusal = {
2688
+ engine: "TerraDrawZoneEngine",
2689
+ remedy: "Pass one closed ring with no hole, of positions of two finite numbers: longitudes within half a turn of each other, continuous across the antimeridian, and latitudes from -90 to 90.",
2690
+ shape: "zone"
2691
+ };
2692
+ var drawablePolygon = (geometry, frameLongitude) => ({
2693
+ coordinates: geometry.coordinates.map(
2694
+ (ring) => ring.map((position) => intoFrame(position, frameLongitude))
2695
+ ),
2696
+ type: "Polygon"
2697
+ });
2698
+ var worldPolygon = (geometry, frameLongitude) => frameLongitude === 0 ? geometry : {
2699
+ coordinates: geometry.coordinates.map(
2700
+ (ring) => ring.map((position) => outOfFrame(position, frameLongitude))
2701
+ ),
2702
+ type: "Polygon"
2703
+ };
2704
+ var zoneDrawModeNames = {
2705
+ circle: "circle",
2706
+ freehand: "freehand",
2707
+ polygon: "polygon",
2708
+ sector: "sector",
2709
+ sensor: "sensor"
2710
+ };
2711
+ var buildZoneDrawMode = (mode, validation) => {
2712
+ switch (mode) {
2713
+ case "circle":
2714
+ return new terraDraw.TerraDrawCircleMode();
2715
+ case "polygon":
2716
+ return new terraDraw.TerraDrawPolygonMode({ editable: true, validation });
2717
+ case "sector":
2718
+ return new terraDraw.TerraDrawSectorMode();
2719
+ case "sensor":
2720
+ return new terraDraw.TerraDrawSensorMode();
2721
+ case "freehand":
2722
+ return new terraDraw.TerraDrawFreehandMode({ validation });
2723
+ }
2724
+ };
2725
+ var buildZoneSelectFlags = (mode, validation) => ({
2726
+ [zoneDrawModeNames[mode]]: {
2727
+ feature: {
2728
+ coordinates: { deletable: true, draggable: true, midpoints: true },
2729
+ draggable: true,
2730
+ validation
2731
+ }
2732
+ }
2733
+ });
2734
+ var defaultZoneDrawFactory = ({ frame, map, mode, prefixId, validation }) => new terraDraw.TerraDraw({
2735
+ adapter: new FramedMapLibreAdapter({ map, prefixId }, frame),
2736
+ idStrategy: drawIdStrategy,
2737
+ modes: [
2738
+ buildZoneDrawMode(mode, validation.draw),
2739
+ new terraDraw.TerraDrawSelectMode({ flags: buildZoneSelectFlags(mode, validation.reshape) })
2740
+ ]
2741
+ });
2742
+ var TerraDrawZoneEngine = class {
2743
+ constructor(map, options, emitDraft, createDraw = defaultZoneDrawFactory, events, cursor) {
2744
+ this.map = map;
2745
+ this.emitDraft = emitDraft;
2746
+ this.featureId = options.featureId;
2747
+ this.activeFeatureId = options.featureId;
2748
+ this.mode = options.mode;
2749
+ this.drawModeName = zoneDrawModeNames[options.mode];
2750
+ this.color = readEditColor(options.color, zoneRefusal.engine);
2751
+ this.onOutlineRefusedChange = options.onOutlineRefusedChange ?? null;
2752
+ this.events = events ?? null;
2753
+ this.cursor = cursor ?? null;
2754
+ this.changeHandler = (ids, type, context) => {
2755
+ if (context?.target === "properties") {
2756
+ return;
2757
+ }
2758
+ this.handleChange(ids, type, isProgrammaticChange(context));
2759
+ };
2760
+ this.finishHandler = (id) => {
2761
+ this.handleFinish(id);
2762
+ };
2763
+ refuseZoneSeed(options, zoneRefusal.engine);
2764
+ this.draw = createDraw({
2765
+ frame: this.frame,
2766
+ map: this.map,
2767
+ mode: options.mode,
2768
+ prefixId: ZONE_TERRADRAW_PREFIX,
2769
+ validation: {
2770
+ draw: (feature, { updateType }) => this.writing ? { valid: true } : this.heard(drawnOutlineVerdict(feature, updateType)),
2771
+ reshape: (feature, { updateType }) => {
2772
+ const verdict = reshapedOutlineVerdict(feature, this.standingRing(), updateType);
2773
+ return updateType === "provisional" && !verdict.valid ? verdict : this.heard(verdict);
2774
+ }
2775
+ }
2776
+ });
2777
+ this.draw.start();
2778
+ this.attachDrawListeners();
2779
+ if (options.seedGeometry) {
2780
+ try {
2781
+ this.seedFeature(options.seedGeometry);
2782
+ } catch (error) {
2783
+ this.dispose();
2784
+ throw error;
2785
+ }
2786
+ } else {
2787
+ this.frameOnMapCenter();
2788
+ this.draw.setMode(this.drawModeName);
2789
+ }
2790
+ this.detachFrameFollow = this.events?.on("moveend", () => this.followMap()) ?? null;
2791
+ this.applyZoneDraftStyle(this.color);
2792
+ this.detachHoverCursor = this.attachHoverCursor();
2793
+ this.detachCursorReassert = this.attachCursorReassert();
2794
+ }
2795
+ map;
2796
+ emitDraft;
2797
+ draw;
2798
+ featureId;
2799
+ // The id the editable feature actually lives under in the TerraDraw store. It
2800
+ // starts at featureId — the id a seeded edit adds the saved shape under — but a
2801
+ // create-draw produces a feature under the id strategy's TerraDraw-assigned id
2802
+ // (the store owns no id until the draw lands), so the finish handler re-points
2803
+ // this to that drawn id. Every store read/write (currentGeometry, applyDraft,
2804
+ // select) keys off this field rather than featureId so a create-draw's feature
2805
+ // is readable and reshapeable once it completes. The type widens to
2806
+ // string | number because the id strategy can mint either kind (terra-draw's
2807
+ // FeatureId is string | number and is not re-exported from the package entry to
2808
+ // name directly).
2809
+ activeFeatureId;
2810
+ // Guards the create-draw adoption to once per drawn shape. A create-draw's finish
2811
+ // fires the adopt-id + select-mode switch exactly once; after it, and on a seeded
2812
+ // edit from the start, a finish arrives for the active feature and settles a
2813
+ // reshape instead, so this stays false on the edit path.
2814
+ drawCompleted = false;
2815
+ // True while a reshape has emitted `live` frames that no `settled` draft has closed
2816
+ // yet. The select mode's `finish` closes the gesture on every pointer release, so a
2817
+ // finish settles only a gesture that actually emitted a frame.
2818
+ gestureOpen = false;
2819
+ mode;
2820
+ // The TerraDraw mode name the active draw mode registered under, derived from
2821
+ // the zone mode once so setMode/updateModeOptions/draft properties read one
2822
+ // value.
2823
+ drawModeName;
2824
+ // The current level color the draft renders in, held so a base-map switch
2825
+ // replay can re-apply it onto the fresh style.
2826
+ color;
2827
+ // The map event engine the hover cursor's listeners detach through; held so
2828
+ // dispose/replay tears them down by reference rather than leaking onto the next
2829
+ // edit's engine instance. Null on the factory-only unit-test path.
2830
+ events;
2831
+ // The cursor controller the hover cursor pushes onto; the base "+"
2832
+ // create cursor is locked one layer above this engine (the editing hook), and
2833
+ // the override layers above that so leaving a vertex reverts to the create
2834
+ // cursor rather than the OS default. Null on the factory-only unit-test path.
2835
+ cursor;
2836
+ // Detaches the hover cursor over the shape's handles and its fill; set on attach, cleared on
2837
+ // dispose / replay so a teardown leaves no listener pointing at the stopped TerraDraw instance
2838
+ // and a style reload rewires a clean one on the rebuilt layers.
2839
+ detachHoverCursor = null;
2840
+ // Detaches the shared map-level mousemove cursor re-assert; set on attach, cleared
2841
+ // on dispose / replay. TerraDraw's draw + select modes write the canvas cursor
2842
+ // only over a handle, never on empty map, so the locked "+" create cursor is
2843
+ // untouched while the pointer roams free and this re-assert is a no-op write there
2844
+ // (its value-changed guard skips it). It is the structural-consistency net every
2845
+ // lock-holding engine shares against a future cursor clobber on a plain move. Null
2846
+ // on the factory-only unit-test path (no event engine + controller wired).
2847
+ detachCursorReassert = null;
2848
+ // The stable change/finish listener references, held so the pre-swap detach can `off`
2849
+ // exactly what the constructor registered. A TerraDraw listener lives on the instance
2850
+ // rather than on the adapter, so `stop()` does NOT drop it — an inline closure per
2851
+ // replay would stack one more binding on every base-map switch.
2852
+ changeHandler;
2853
+ finishHandler;
2854
+ // The geometry read off the store by {@link detachBeforeStyleReload}, held for the replay
2855
+ // to re-seed from. It exists because stopping TerraDraw EMPTIES the store: `stop()`
2856
+ // unregisters the adapter, whose base `unregister()` ends in its own `clear()`, which
2857
+ // calls back through `onClear` into `_store.clear()`. So by the time the replay runs
2858
+ // there is nothing left to read, and a replay that re-registered the adapter correctly
2859
+ // still came back to five empty layers. Null while no swap is in flight.
2860
+ detachedGeometry = null;
2861
+ // Whether TerraDraw is stopped for a style reload: raised by the detach, lowered by the replay.
2862
+ // While it is raised the store is empty and refuses every write, so the engine reads and
2863
+ // writes what it holds itself.
2864
+ detached = false;
2865
+ // The latest geometry applied while TerraDraw is stopped for a style reload, as it is drawn,
2866
+ // written when the replay ends. Undefined when none was applied.
2867
+ heldDraft;
2868
+ // Whether the edit is over. A disposed engine has no replay to come, so a geometry applied to
2869
+ // it inside the detach window is held by nothing.
2870
+ disposed = false;
2871
+ // The frame the edit is held in, which the adapter the factory builds reads on every projection
2872
+ // and render. Every read of the store adds its longitude and every write takes it off.
2873
+ frame = { longitude: 0 };
2874
+ // Detaches the map-level listener that moves the frame with the map while nothing is drawn.
2875
+ // Null on the factory-only unit-test path, and once the edit is over.
2876
+ detachFrameFollow = null;
2877
+ // Whether the engine is writing a shape into the store itself: a seed, or a draft its host
2878
+ // applied. TerraDraw asks the draw mode's validation about a store write as it asks about a
2879
+ // frame under the pointer, and a shape the host hands over is drawn as written.
2880
+ writing = false;
2881
+ // Whether the latest gesture judged was refused for an outline that would cross itself, as
2882
+ // the host was last told through `onOutlineRefusedChange`.
2883
+ refused = false;
2884
+ onOutlineRefusedChange;
2885
+ setDraftStyle(style) {
2886
+ if (this.disposed) {
2887
+ return;
2888
+ }
2889
+ this.color = readEditColor(style.color, zoneRefusal.engine);
2890
+ if (this.detached) {
2891
+ return;
2892
+ }
2893
+ this.applyZoneDraftStyle(this.color);
2894
+ }
2895
+ readDraft() {
2896
+ if (this.disposed) {
2897
+ return null;
2898
+ }
2899
+ if (this.detached) {
2900
+ const held = this.heldDraft ?? this.detachedGeometry;
2901
+ return held === null ? null : { coordinates: held.coordinates.map(copyPositions), type: "Polygon" };
2902
+ }
2903
+ return this.currentGeometry();
2904
+ }
2905
+ applyDraft(geometry) {
2906
+ if (this.disposed) {
2907
+ return;
2908
+ }
2909
+ if (!this.geometryMatchesMode(geometry)) {
2910
+ return;
2911
+ }
2912
+ if (this.detached) {
2913
+ this.heldDraft = drawablePolygon(geometry, 0);
2914
+ return;
2915
+ }
2916
+ if (this.draw.getSnapshotFeature(this.activeFeatureId) === void 0) {
2917
+ this.seedFeature(geometry);
2918
+ return;
2919
+ }
2920
+ const standingFrame = this.frame.longitude;
2921
+ this.frame.longitude = polygonFrameLongitude(geometry);
2922
+ try {
2923
+ this.write(
2924
+ () => updateDrawGeometry(
2925
+ this.draw,
2926
+ this.activeFeatureId,
2927
+ drawablePolygon(geometry, this.frame.longitude),
2928
+ zoneRefusal
2929
+ )
2930
+ );
2931
+ } catch (error) {
2932
+ this.frame.longitude = standingFrame;
2933
+ throw error;
2934
+ }
2935
+ }
2936
+ dispose() {
2937
+ this.tellRefused(false);
2938
+ this.detachCursorReassert?.();
2939
+ this.detachCursorReassert = null;
2940
+ this.detachFrameFollow?.();
2941
+ this.detachFrameFollow = null;
2942
+ this.detachHoverCursor?.();
2943
+ this.detachHoverCursor = null;
2944
+ this.cursor?.popOverride();
2945
+ this.disposed = true;
2946
+ this.heldDraft = void 0;
2947
+ this.detachedGeometry = null;
2948
+ this.detachDrawListeners();
2949
+ try {
2950
+ if (this.draw.enabled) {
2951
+ this.draw.clear();
2952
+ }
2953
+ } finally {
2954
+ this.draw.stop();
2955
+ }
2956
+ }
2957
+ /**
2958
+ * detachBeforeStyleReload stops TerraDraw before the swap, so the replay's `start()`
2959
+ * actually re-registers the adapter. See {@link EditEngine.detachBeforeStyleReload}
2960
+ * for why the pair is needed and why the order is load-bearing: the adapter's
2961
+ * `unregister()` removes five layers and three sources unguarded, which succeeds
2962
+ * silently on the outgoing style and is noisy-then-fatal on the incoming one.
2963
+ *
2964
+ * The geometry is read off the store FIRST, because `stop()` empties it — the adapter's
2965
+ * base `unregister()` ends in its own `clear()`, which calls back through `onClear` into
2966
+ * `_store.clear()`. And the listeners come off before that, so the deletion the clear
2967
+ * emits is not turned into a draft saying the user erased their zone mid-swap.
2968
+ */
2969
+ detachBeforeStyleReload() {
2970
+ if (this.disposed) {
2971
+ return;
2972
+ }
2973
+ if (this.detached) {
2974
+ return;
2975
+ }
2976
+ this.detached = true;
2977
+ this.detachedGeometry = this.currentGeometry();
2978
+ this.detachDrawListeners();
2979
+ this.draw.stop();
2980
+ }
2981
+ /**
2982
+ * attachDrawListeners wires the change + finish listeners onto the (re-)started
2983
+ * TerraDraw instance. Shared by the constructor and the style-reload replay so both
2984
+ * paths subscribe identically, and by reference so {@link detachDrawListeners} can
2985
+ * take exactly them back off.
2986
+ */
2987
+ attachDrawListeners() {
2988
+ this.draw.on("change", this.changeHandler);
2989
+ this.draw.on("finish", this.finishHandler);
2990
+ }
2991
+ /**
2992
+ * detachDrawListeners drops the change + finish listeners by reference. The detach
2993
+ * half of {@link attachDrawListeners}, needed because a TerraDraw listener lives on
2994
+ * the instance and not on the adapter: `stop()` unregisters the adapter and leaves
2995
+ * every listener attached.
2996
+ */
2997
+ detachDrawListeners() {
2998
+ this.draw.off("change", this.changeHandler);
2999
+ this.draw.off("finish", this.finishHandler);
3000
+ }
3001
+ /**
3002
+ * replayAfterStyleReload re-renders the active edit's scene after a base-map
3003
+ * switch wiped the style. It re-attaches what setStyle tore down: the library's
3004
+ * layers + change listener, the editable feature, its color, and the hover cursor over
3005
+ * its handles and fill (its TerraDraw point/fill layers are rebuilt). Unlike the segment
3006
+ * engine it binds no click grammar of its own, so the hover cursor and the re-assert are
3007
+ * the only map-level listeners it rewires, each detached before it is attached again.
3008
+ *
3009
+ * It is the second half of a pair: {@link detachBeforeStyleReload} must have stopped
3010
+ * the instance before the swap, or the `start()` below returns early and re-registers
3011
+ * nothing.
3012
+ */
3013
+ replayAfterStyleReload() {
3014
+ if (this.disposed) {
3015
+ return;
3016
+ }
3017
+ const geometry = this.detachedGeometry ?? this.currentGeometry();
3018
+ this.detachedGeometry = null;
3019
+ this.detached = false;
3020
+ this.draw.start();
3021
+ this.attachDrawListeners();
3022
+ if (geometry) {
3023
+ this.draw.clear();
3024
+ this.seedFeature(geometry);
3025
+ } else {
3026
+ this.frameOnMapCenter();
3027
+ this.draw.setMode(this.drawModeName);
3028
+ }
3029
+ this.applyZoneDraftStyle(this.color);
3030
+ this.detachHoverCursor?.();
3031
+ this.detachHoverCursor = this.attachHoverCursor();
3032
+ this.detachCursorReassert?.();
3033
+ this.detachCursorReassert = this.attachCursorReassert();
3034
+ const held = this.heldDraft;
3035
+ this.heldDraft = void 0;
3036
+ if (held !== void 0) {
3037
+ applyHeldWrite(() => this.applyDraft(held));
3038
+ }
3039
+ }
3040
+ /**
3041
+ * handleChange is the single fan-out the per-edit change listener calls on every
3042
+ * geometry change (interactive draw/drag or programmatic write). It reads the
3043
+ * current shape and emits it through the sink with the programmatic flag; a
3044
+ * change that leaves no qualifying geometry (a cleared store, a half-drawn shape
3045
+ * below the geometry's floor) is dropped rather than emitting a null draft —
3046
+ * ZoneDraft has no null geometry, so the absence of a shape is "no draft yet".
3047
+ *
3048
+ * The phase follows the change's origin. A change TerraDraw makes under the pointer (a
3049
+ * vertex drag, a whole-shape drag, a midpoint insert) is one frame of a gesture its
3050
+ * `finish` closes, so it is `live` and {@link handleFinish} settles it. A store-API write
3051
+ * is whole when it lands, so it is `settled`.
3052
+ */
3053
+ handleChange(ids, _type, programmatic) {
3054
+ if (!ids.includes(this.activeFeatureId)) {
3055
+ return;
3056
+ }
3057
+ const geometry = this.currentGeometry();
3058
+ if (!geometry) {
3059
+ return;
3060
+ }
3061
+ const phase = programmatic ? "settled" : "live";
3062
+ this.gestureOpen = phase === "live";
3063
+ this.emit({ geometry, mode: this.mode, phase, programmatic });
3064
+ }
3065
+ /**
3066
+ * handleFinish runs when TerraDraw finishes a gesture, and does one of two things.
3067
+ *
3068
+ * A finish on the active feature closes a reshape (a coordinate drag, a whole-shape drag, a
3069
+ * midpoint insert, a coordinate delete), which reached the draft as `live` frames. It emits
3070
+ * the shape as it stands once more, `settled` and interactive, so a history subscriber records
3071
+ * the whole gesture as one step. A finish that closes no live frame emits nothing: the select
3072
+ * mode finishes every pointer release, a release that moved nothing included.
3073
+ *
3074
+ * Any other finish completes a create-draw: a circle, sector or sensor sized on release, a
3075
+ * polygon closed, a freehand area traced to its end. The drawn feature carries the id
3076
+ * strategy's TerraDraw-assigned id, not featureId, so until this fires the feature is
3077
+ * invisible to the featureId-keyed reads and no draft emits. The handler adopts the drawn id
3078
+ * as the active id, switches out of the draw mode into the select mode and selects the
3079
+ * feature (so only ONE shape is ever drawn and it becomes reshapeable), and emits the finished
3080
+ * geometry as a settled, interactive draft so the consumer's draft and Save light up. The draw
3081
+ * is the whole gesture, since its frames were never emitted.
3082
+ *
3083
+ * The adoption runs once per drawn shape. A finish whose feature does not read back as the
3084
+ * active mode's geometry kind (a transient or mismatched store state) is left for the next
3085
+ * qualifying signal rather than adopted.
3086
+ */
3087
+ handleFinish(id) {
3088
+ if (id === this.activeFeatureId) {
3089
+ this.settleGesture();
3090
+ return;
3091
+ }
3092
+ if (this.drawCompleted) {
3093
+ return;
3094
+ }
3095
+ const geometry = this.geometryOf(id);
3096
+ if (!geometry) {
3097
+ return;
3098
+ }
3099
+ this.drawCompleted = true;
3100
+ this.activeFeatureId = id;
3101
+ this.draw.setMode(SELECT_MODE);
3102
+ this.draw.selectFeature(id);
3103
+ this.gestureOpen = false;
3104
+ this.emit({ geometry, mode: this.mode, phase: "settled", programmatic: false });
3105
+ }
3106
+ /**
3107
+ * settleGesture emits the active shape once more, `settled` and interactive, when a reshape
3108
+ * that emitted `live` frames finishes, and does nothing when none is open.
3109
+ */
3110
+ settleGesture() {
3111
+ if (!this.gestureOpen) {
3112
+ return;
3113
+ }
3114
+ const geometry = this.currentGeometry();
3115
+ if (!geometry) {
3116
+ return;
3117
+ }
3118
+ this.gestureOpen = false;
3119
+ this.emit({ geometry, mode: this.mode, phase: "settled", programmatic: false });
3120
+ }
3121
+ /**
3122
+ * seedFeature adds the editable zone feature, selects it, and shows its handles
3123
+ * (for the vertex-editable modes). The feature carries the active draw mode name
3124
+ * in `properties.mode` so TerraDraw renders it under the right mode's styling. A
3125
+ * seed that is not a Polygon (the shape every zone mode draws) is ignored.
3126
+ */
3127
+ seedFeature(geometry) {
3128
+ if (!this.geometryMatchesMode(geometry)) {
3129
+ return;
3130
+ }
3131
+ const standingFrame = this.frame.longitude;
3132
+ this.frame.longitude = polygonFrameLongitude(geometry);
3133
+ const feature = {
3134
+ geometry: drawablePolygon(geometry, this.frame.longitude),
3135
+ id: this.featureId,
3136
+ properties: { mode: this.drawModeName },
3137
+ type: "Feature"
3138
+ };
3139
+ try {
3140
+ this.write(() => addDrawFeature(this.draw, feature, zoneRefusal));
3141
+ } catch (error) {
3142
+ this.frame.longitude = standingFrame;
3143
+ throw error;
3144
+ }
3145
+ this.activeFeatureId = this.featureId;
3146
+ this.draw.setMode(SELECT_MODE);
3147
+ this.draw.selectFeature(this.featureId);
3148
+ }
3149
+ /**
3150
+ * applyZoneDraftStyle pushes the level color onto the active draw mode's styles
3151
+ * and the select mode's styles so the drawn area, its outline, vertices, and the
3152
+ * midpoint-insert handles all render in the level color. updateModeOptions
3153
+ * accepts a partial options object, so only the styling keys are sent; it runs
3154
+ * while the modes are started, recoloring live. The color was held to `#rrggbb` as
3155
+ * it was handed over ({@link readEditColor}). Every mode draws a Polygon area, so they
3156
+ * all share the
3157
+ * fillColor/outlineColor keys; the select mode colors the selected shape + its
3158
+ * handles.
3159
+ */
3160
+ applyZoneDraftStyle(hex) {
3161
+ this.applyPolygonDrawStyle(hex);
3162
+ this.draw.updateModeOptions(SELECT_MODE, {
3163
+ styles: {
3164
+ midPointColor: hex,
3165
+ selectedLineStringColor: hex,
3166
+ selectedPointColor: hex,
3167
+ selectedPolygonColor: hex,
3168
+ selectedPolygonOutlineColor: hex,
3169
+ selectionPointColor: hex
3170
+ }
3171
+ });
3172
+ }
3173
+ /**
3174
+ * applyPolygonDrawStyle pushes the level color onto whichever zone draw mode is
3175
+ * active (circle/polygon/sector/sensor/freehand). All five draw a Polygon and
3176
+ * share the fillColor/outlineColor/outlineWidth keys, but each is a distinct mode
3177
+ * class for the typed updateModeOptions generic, so the call is dispatched per
3178
+ * mode rather than cast through a shared supertype — keeping the styling keys
3179
+ * type-checked against the concrete mode the way the segment engine does.
3180
+ */
3181
+ applyPolygonDrawStyle(hex) {
3182
+ const styles = { fillColor: hex, fillOpacity: 0.2, outlineColor: hex, outlineWidth: 2 };
3183
+ switch (this.mode) {
3184
+ case "circle":
3185
+ this.draw.updateModeOptions(this.drawModeName, { styles });
3186
+ return;
3187
+ case "polygon":
3188
+ this.draw.updateModeOptions(this.drawModeName, { styles });
3189
+ return;
3190
+ case "sector":
3191
+ this.draw.updateModeOptions(this.drawModeName, { styles });
3192
+ return;
3193
+ case "sensor":
3194
+ this.draw.updateModeOptions(this.drawModeName, { styles });
3195
+ return;
3196
+ case "freehand":
3197
+ this.draw.updateModeOptions(this.drawModeName, { styles });
3198
+ return;
3199
+ }
3200
+ }
3201
+ /**
3202
+ * currentGeometry reads the editable feature's current shape from the TerraDraw
3203
+ * store, narrowed to the Polygon every zone mode produces — or null when the
3204
+ * feature is gone or its kind does not match (a transient state mid-draw). The
3205
+ * narrowing keeps the ZoneDraft geometry honest: a zone draft is always a Polygon.
3206
+ */
3207
+ currentGeometry() {
3208
+ return this.geometryOf(this.activeFeatureId);
3209
+ }
3210
+ /**
3211
+ * geometryOf reads one feature's shape from the TerraDraw store by id and narrows
3212
+ * it to the Polygon every zone mode produces — or null when the feature is gone or
3213
+ * its kind does not match (a transient state mid-draw, or the Point geometry the
3214
+ * store union also admits). currentGeometry reads the active feature through it;
3215
+ * the finish handler reads the just-drawn feature through it before adopting that
3216
+ * id, so the narrowing that keeps the ZoneDraft geometry honest lives in one place.
3217
+ */
3218
+ geometryOf(id) {
3219
+ const feature = this.draw.getSnapshotFeature(id);
3220
+ if (!feature) {
3221
+ return null;
3222
+ }
3223
+ const geometry = feature.geometry;
3224
+ return geometry.type === "Polygon" ? worldPolygon(geometry, this.frame.longitude) : null;
3225
+ }
3226
+ /**
3227
+ * heard tells the host whether a verdict on a gesture refused it ({@link tellRefused}) and
3228
+ * answers the verdict as it came.
3229
+ */
3230
+ heard(verdict) {
3231
+ this.tellRefused(!verdict.valid);
3232
+ return verdict;
3233
+ }
3234
+ /**
3235
+ * tellRefused tells the host through `onOutlineRefusedChange` whether the latest gesture was
3236
+ * refused, when that changed since it was last told. A listener that throws stops no gesture:
3237
+ * its fault is handed to the runtime on a microtask.
3238
+ */
3239
+ tellRefused(refused) {
3240
+ if (refused === this.refused) {
3241
+ return;
3242
+ }
3243
+ this.refused = refused;
3244
+ try {
3245
+ this.onOutlineRefusedChange?.(refused);
3246
+ } catch (fault) {
3247
+ chunkWW4CGS7G_cjs.surfaceFault(fault);
3248
+ }
3249
+ }
3250
+ /**
3251
+ * write runs one write of the engine's own into the store, a seed or an applied draft, with
3252
+ * the draw mode's validation stood down for as long as it runs: the shape is the host's, an
3253
+ * undo, a redo or a proposal, and a saved outline that crosses itself has to open to be
3254
+ * repaired. A write made from inside another, by a sink the first one told, leaves the outer
3255
+ * one as it found it.
3256
+ */
3257
+ write(store) {
3258
+ const outer = this.writing;
3259
+ this.writing = true;
3260
+ try {
3261
+ store();
3262
+ } finally {
3263
+ this.writing = outer;
3264
+ }
3265
+ }
3266
+ /**
3267
+ * standingRing reads the outer ring the store holds for the edit, as the library holds it, or
3268
+ * null while it holds none: what a reshape is judged against.
3269
+ */
3270
+ standingRing() {
3271
+ const geometry = this.draw.getSnapshotFeature(this.activeFeatureId)?.geometry;
3272
+ return geometry?.type === "Polygon" ? geometry.coordinates[0] ?? null : null;
3273
+ }
3274
+ /**
3275
+ * emit hands a draft to the host's sink. A sink that throws stops neither the write that
3276
+ * reported the draft nor the library's own listeners after this one: its fault is handed to
3277
+ * the runtime on a microtask.
3278
+ */
3279
+ emit(draft) {
3280
+ try {
3281
+ this.emitDraft(draft);
3282
+ } catch (fault) {
3283
+ chunkWW4CGS7G_cjs.surfaceFault(fault);
3284
+ }
3285
+ }
3286
+ /**
3287
+ * frameOnMapCenter lays the frame where the map looks, for an edit that holds no shape yet:
3288
+ * what is drawn next is drawn on screen, so it lands inside the range the library holds.
3289
+ */
3290
+ frameOnMapCenter() {
3291
+ this.frame.longitude = frameLongitudeFor([this.map.getCenter().lng]);
3292
+ }
3293
+ /**
3294
+ * followMap moves the frame to where the map stopped, while the library holds nothing: no
3295
+ * shape, and no draw under way. A frame that moved under a feature would draw it half a turn
3296
+ * from where it is, so a store that holds one keeps its frame.
3297
+ */
3298
+ followMap() {
3299
+ if (this.disposed || this.detached) {
3300
+ return;
3301
+ }
3302
+ if (this.draw.getSnapshot().length === 0) {
3303
+ this.frameOnMapCenter();
3304
+ }
3305
+ }
3306
+ /**
3307
+ * geometryMatchesMode reports whether a geometry is the Polygon every zone mode
3308
+ * draws. The single guard seedFeature and applyDraft read so a non-Polygon shape
3309
+ * is never written into the store.
3310
+ */
3311
+ geometryMatchesMode(geometry) {
3312
+ return geometry.type === "Polygon";
3313
+ }
3314
+ /**
3315
+ * attachCursorReassert subscribes the shared map-level mousemove re-assert that
3316
+ * re-pins the held "+" create cursor (or an override above it) after a future
3317
+ * cursor clobber on a plain move. TerraDraw's draw + select modes write the
3318
+ * canvas cursor only over a handle today, never on empty map, so this is a no-op
3319
+ * write there — it is the uniform regression net every lock-holding engine holds,
3320
+ * so a TerraDraw version that starts clobbering the cursor on a plain move is
3321
+ * already covered. Attached LAST (after draw.start() wires TerraDraw's handler)
3322
+ * so MapLibre dispatches the re-pin after TerraDraw, and the shared utility leaves
3323
+ * drag-pan untouched (a zone edit never locks the map). A no-op (null detach)
3324
+ * when the event engine or cursor controller is absent — the factory-only path.
3325
+ */
3326
+ attachCursorReassert() {
3327
+ if (!this.events || !this.cursor) {
3328
+ return null;
3329
+ }
3330
+ return chunkIBQJDVHF_cjs.attachCursorReassert(this.events, this.cursor);
3331
+ }
3332
+ /**
3333
+ * attachHoverCursor layers the edit's hover cursor over the locked "+" create cursor, through
3334
+ * the shared {@link attachEditHoverCursor}: the `move` cursor over a draggable vertex,
3335
+ * "pointer" over an insert midpoint, and grab (grabbing while pressed) over the polygon fill,
3336
+ * whose drag translates the whole zone. A handle wins over the fill it sits on, so an imprecise
3337
+ * vertex grab reshapes rather than translates. Circle, sector and sensor render no handles, so
3338
+ * only the fill answers for them. A no-op (empty detach) when the event engine or cursor
3339
+ * controller is absent, the factory-only unit-test path.
3340
+ */
3341
+ attachHoverCursor() {
3342
+ const events = this.events;
3343
+ const cursor = this.cursor;
3344
+ if (!events || !cursor) {
3345
+ return () => {
3346
+ };
3347
+ }
3348
+ return chunkIBQJDVHF_cjs.attachEditHoverCursor({
3349
+ cursor,
3350
+ events,
3351
+ layers: [
3352
+ {
3353
+ kind: "handle",
3354
+ layerId: ZONE_VERTEX_LAYER_ID,
3355
+ midpointProperty: TERRA_DRAW_MID_POINT_PROPERTY
3356
+ },
3357
+ { kind: "interior", layerId: ZONE_FILL_LAYER_ID }
3358
+ ],
3359
+ map: this.map
3360
+ });
3361
+ }
3362
+ };
3363
+ var PINNED_BOUNDARY_TOLERANCE = 1e-7;
3364
+ var isPinnedWaypointIntact = (waypoints, pinned, index) => {
3365
+ const at = waypoints[index];
3366
+ if (!at) {
3367
+ return false;
3368
+ }
3369
+ const pinnedLng = pinned[0] ?? 0;
3370
+ const pinnedLat = pinned[1] ?? 0;
3371
+ return Math.abs(at[0] - pinnedLng) <= PINNED_BOUNDARY_TOLERANCE && Math.abs(at[1] - pinnedLat) <= PINNED_BOUNDARY_TOLERANCE;
3372
+ };
3373
+ var seedOnPins = (seed, pinnedStart, pinnedEnd) => {
3374
+ const vias = [...seed];
3375
+ if (vias.length < chunkEX2C5K2T_cjs.DIRECTIONS_VIA_MIN) {
3376
+ return vias;
3377
+ }
3378
+ const pairs = vias.map((via) => [via[0] ?? 0, via[1] ?? 0]);
3379
+ if (pinnedStart && !isPinnedWaypointIntact(pairs, pinnedStart, 0)) {
3380
+ vias[0] = pinnedStart;
3381
+ }
3382
+ if (pinnedEnd && !isPinnedWaypointIntact(pairs, pinnedEnd, vias.length - 1)) {
3383
+ vias[vias.length - 1] = pinnedEnd;
3384
+ }
3385
+ return vias;
3386
+ };
3387
+ var darkenColor = (hex, fraction) => {
3388
+ const value = Number.parseInt(hex.replace("#", ""), 16);
3389
+ const r = Math.max(0, (value >> 16) - Math.round(255 * fraction));
3390
+ const g = Math.max(0, (value >> 8 & 255) - Math.round(255 * fraction));
3391
+ const b = Math.max(0, (value & 255) - Math.round(255 * fraction));
3392
+ return `#${(r << 16 | g << 8 | b).toString(16).padStart(6, "0")}`;
3393
+ };
3394
+ var removalGuarded = (map) => {
3395
+ const removeLayer = (id) => map.getLayer(id) === void 0 ? map : map.removeLayer(id);
3396
+ const removeSource = (id) => map.getSource(id) === void 0 ? map : map.removeSource(id);
3397
+ const bound = /* @__PURE__ */ new Map();
3398
+ return new Proxy(map, {
3399
+ get: (target, key) => {
3400
+ if (key === "removeLayer") {
3401
+ return removeLayer;
3402
+ }
3403
+ if (key === "removeSource") {
3404
+ return removeSource;
3405
+ }
3406
+ const value = Reflect.get(target, key, target);
3407
+ if (typeof value !== "function") {
3408
+ return value;
3409
+ }
3410
+ let method = bound.get(key);
3411
+ if (method === void 0) {
3412
+ method = value.bind(target);
3413
+ bound.set(key, method);
3414
+ }
3415
+ return method;
3416
+ }
3417
+ });
3418
+ };
3419
+ var directionsLayers = (color) => {
3420
+ const casing = darkenColor(color, 0.2);
3421
+ return MapLibreGlDirections.layersFactory().map((layer) => {
3422
+ const next = { ...layer };
3423
+ if (layer.id.includes("routeline-casing") || layer.id.includes("alt-routeline-casing")) {
3424
+ next.paint = { ...layer.paint, "line-color": casing };
3425
+ } else if (layer.id.includes("routeline") || layer.id.includes("alt-routeline")) {
3426
+ next.paint = { ...layer.paint, "line-color": color };
3427
+ } else if (layer.id.includes("waypoint-casing") || layer.id.includes("snappoint-casing") || layer.id.includes("hoverpoint-casing")) {
3428
+ next.paint = { ...layer.paint, "circle-color": casing };
3429
+ } else if (layer.id.includes("waypoint") || layer.id.includes("snappoint") || layer.id.includes("hoverpoint")) {
3430
+ next.paint = { ...layer.paint, "circle-color": color };
3431
+ } else if (layer.id.includes("snapline")) {
3432
+ next.paint = { ...layer.paint, "line-color": color };
3433
+ }
3434
+ return next;
3435
+ });
3436
+ };
3437
+ var lineColorLayers = [
3438
+ "maplibre-gl-directions-routeline",
3439
+ "maplibre-gl-directions-alt-routeline",
3440
+ "maplibre-gl-directions-snapline"
3441
+ ];
3442
+ var lineCasingLayers = [
3443
+ "maplibre-gl-directions-routeline-casing",
3444
+ "maplibre-gl-directions-alt-routeline-casing"
3445
+ ];
3446
+ var circleColorLayers = [
3447
+ "maplibre-gl-directions-waypoint",
3448
+ "maplibre-gl-directions-snappoint",
3449
+ "maplibre-gl-directions-hoverpoint"
3450
+ ];
3451
+ var circleCasingLayers = [
3452
+ "maplibre-gl-directions-waypoint-casing",
3453
+ "maplibre-gl-directions-snappoint-casing",
3454
+ "maplibre-gl-directions-hoverpoint-casing"
3455
+ ];
3456
+ var snapWaypointsToRoute = (vias, route) => {
3457
+ if (route.length === 0) {
3458
+ return vias.map((via) => [via[0] ?? 0, via[1] ?? 0]);
3459
+ }
3460
+ const first = route[0] ?? [0, 0];
3461
+ const last = route[route.length - 1] ?? first;
3462
+ return vias.map((via, index) => {
3463
+ if (index === 0) {
3464
+ return first;
3465
+ }
3466
+ if (index === vias.length - 1) {
3467
+ return last;
3468
+ }
3469
+ const lng = via[0] ?? 0;
3470
+ const lat = via[1] ?? 0;
3471
+ let nearest = first;
3472
+ let nearestDistance = Number.POSITIVE_INFINITY;
3473
+ for (const coord of route) {
3474
+ const dx = (coord[0] ?? 0) - lng;
3475
+ const dy = (coord[1] ?? 0) - lat;
3476
+ const distance = dx * dx + dy * dy;
3477
+ if (distance < nearestDistance) {
3478
+ nearestDistance = distance;
3479
+ nearest = coord;
3480
+ }
3481
+ }
3482
+ return nearest;
3483
+ });
3484
+ };
3485
+ var parseWaypoints = (url) => {
3486
+ const coords = url.split("/").pop()?.split("?")[0] ?? "";
3487
+ if (coords.length === 0) {
3488
+ return [];
3489
+ }
3490
+ return coords.split(";").map((pair) => {
3491
+ const [lng, lat] = pair.split(",").map(Number);
3492
+ return [lng ?? 0, lat ?? 0];
3493
+ });
3494
+ };
3495
+ var routeFnFrom = (options) => {
3496
+ const { routeFn } = options;
3497
+ if (typeof routeFn !== "function") {
3498
+ throw new chunkISLB6Y5Q_cjs.MountayaElementsError(
3499
+ `DirectionsSegmentEngine: routeFn is ${String(routeFn)}. A directions edit draws the line its router answers: pass the function that routes the vias as routeFn, or begin the edit in linestring mode.`
3500
+ );
3501
+ }
3502
+ return routeFn;
3503
+ };
3504
+ var activitySlugFrom = (options) => {
3505
+ const { activitySlug } = options;
3506
+ if (typeof activitySlug !== "string" || activitySlug === "") {
3507
+ const shown = typeof activitySlug === "string" ? '""' : String(activitySlug);
3508
+ throw new chunkISLB6Y5Q_cjs.MountayaElementsError(
3509
+ `DirectionsSegmentEngine: activitySlug is ${shown}. A directions edit routes for one activity: pass the slug of the itinerary's activity as activitySlug, or begin the edit in linestring mode.`
3510
+ );
3511
+ }
3512
+ return activitySlug;
3513
+ };
3514
+ var refuseUnroutableEdit = (options) => {
3515
+ routeFnFrom(options);
3516
+ activitySlugFrom(options);
3517
+ refuseSegmentPositions(options, "DirectionsSegmentEngine");
3518
+ };
3519
+ var DirectionsSegmentEngine = class {
3520
+ /**
3521
+ * Builds the directions plugin over the map and opens the edit on its seed. A seed whose head
3522
+ * or tail is further from its pin than the backend's tolerance opens with the pin in its place.
3523
+ *
3524
+ * @param map The map the edit is drawn on.
3525
+ * @param events The event engine the cursor listeners are registered through.
3526
+ * @param cursor The cursor engine the edit's cursors are locked on.
3527
+ * @param options The edit: its colour, its seed and pins, its router and its activity.
3528
+ * @param emitDraft The sink every change of the vias, and every route, is pushed at.
3529
+ * @param emitViaPrompt The sink a click on an existing via is handed to.
3530
+ *
3531
+ * @throws {MountayaElementsError} When `options.routeFn` is not a function, when
3532
+ * `options.activitySlug` is missing or empty, when `options.pinnedStart`, `options.pinnedEnd`
3533
+ * or a seed via is not a longitude and a latitude a map can place (two finite numbers, the
3534
+ * latitude from -90 to 90), and when `options.color` is neither `#rrggbb` nor `#rgb`. Each is
3535
+ * refused before the directions plugin is built, so a refused edit leaves no layer, source or
3536
+ * listener on the map.
3537
+ */
3538
+ constructor(map, events, cursor, options, emitDraft, emitViaPrompt) {
3539
+ this.map = map;
3540
+ this.events = events;
3541
+ this.cursor = cursor;
3542
+ this.emitDraft = emitDraft;
3543
+ this.emitViaPrompt = emitViaPrompt;
3544
+ this.routeFn = routeFnFrom(options);
3545
+ this.activitySlug = activitySlugFrom(options);
3546
+ const { endPin: pinnedEnd, startPin: pinnedStart } = refuseSegmentPositions(
3547
+ options,
3548
+ "DirectionsSegmentEngine"
3549
+ );
3550
+ this.color = readEditColor(options.color, "DirectionsSegmentEngine");
3551
+ this.vias = seedOnPins(options.seedVias ?? [], pinnedStart, pinnedEnd);
3552
+ this.acceptedVias = [...this.vias];
3553
+ this.pinnedStart = pinnedStart;
3554
+ this.pinnedEnd = pinnedEnd;
3555
+ this.onViaCapRefused = options.onViaCapRefused;
3556
+ const directions = this.attach();
3557
+ if (this.vias.length > 0) {
3558
+ void directions.setWaypoints(this.toLngLatPairs(this.vias));
3559
+ }
3560
+ }
3561
+ map;
3562
+ events;
3563
+ cursor;
3564
+ emitDraft;
3565
+ emitViaPrompt;
3566
+ directions = null;
3567
+ color;
3568
+ routeFn;
3569
+ activitySlug;
3570
+ // The vias the SDK currently holds, mirrored here so a base-map-switch replay
3571
+ // can re-seed the rebuilt instance from the last known state.
3572
+ vias;
3573
+ // The pinned first-vertex coordinate. When set, the head of the SDK's
3574
+ // waypoints is locked to this position: any interactive change (move-vertex-0
3575
+ // or remove-vertex-0) that drifts it past `PINNED_BOUNDARY_TOLERANCE` triggers
3576
+ // a programmatic revert. The constraint expresses the backend's segment
3577
+ // continuity (segment N's start = segment N-1's end) inside the editor so a
3578
+ // drag never breaks the chain.
3579
+ pinnedStart;
3580
+ // The pinned last-vertex coordinate, the mirror of pinnedStart: segment N's end
3581
+ // locked to segment N+1's start. Set only for an insert, which is the one edit
3582
+ // with a successor to meet. It also changes where a click lands: an added
3583
+ // waypoint is moved in FRONT of the pin so the drawn line always finishes on its
3584
+ // neighbour rather than running past it.
3585
+ pinnedEnd;
3586
+ // Reports an interactive add declined by the via cap, so the app can say so. The
3587
+ // decline is otherwise invisible: the SDK's waypoint is reverted and no draft is
3588
+ // emitted, leaving the click indistinguishable from a miss.
3589
+ onViaCapRefused;
3590
+ // Guard against re-entering the setwaypoints listener during a pinned-start
3591
+ // revert: the programmatic setWaypoints call fires its own setwaypoints
3592
+ // event, which would otherwise re-run the same check on the just-restored
3593
+ // state. The flag is raised before the revert call and cleared after the
3594
+ // event drains.
3595
+ reverting = false;
3596
+ // Detaches the routed-line "+"-insert cursor affordance (our listeners through
3597
+ // the shared event engine), set when the engine attaches and cleared on dispose.
3598
+ detachRouteCursor = null;
3599
+ // Detaches the map-level mousemove re-assert (our listener through the shared
3600
+ // event engine), set when the engine attaches and cleared on dispose. It
3601
+ // counters the SDK's own global move handler, which writes the canvas cursor
3602
+ // directly and re-enables drag-pan when the pointer is off every sensitive
3603
+ // layer: i.e. over empty map, the from-scratch "add the next point" state.
3604
+ detachCursorReassert = null;
3605
+ // The most recent SegmentRoute the injected routeFn returned for the current
3606
+ // vias, kept on the engine so the next SegmentDraft emit can carry it to the
3607
+ // live elevation panel. The SDK consumes a 2D-projected sibling; this field
3608
+ // holds the full 3D geometry + elevation + analysis the live preview reads.
3609
+ lastRoute = null;
3610
+ // The last via set whose route the routeFn ACCEPTED, kept as the restore point
3611
+ // for a refused route. It trails `vias`: the SDK's waypoint events update
3612
+ // `vias` the moment a click lands, while the accept/refuse verdict only
3613
+ // arrives when the router resolves, so the two differ exactly across an
3614
+ // in-flight placement, which is the window a refusal has to undo.
3615
+ acceptedVias;
3616
+ // Monotonic guard for out-of-order routeFn resolutions. Each computeRoute call
3617
+ // captures the token it bumps before awaiting the router; on resolution it
3618
+ // updates lastRoute and emits the fresh-route draft ONLY when its token is
3619
+ // still current, so a superseded via-set's late resolution cannot clobber a
3620
+ // newer route or push a stale live profile. Mirrors the freehand engine's
3621
+ // analyzeToken, the same race guard both engines need over an async resolver.
3622
+ // dispose() bumps it too, so a resolution landing after the edit ended emits nothing.
3623
+ routeToken = 0;
3624
+ // The routing calls still in flight, by the request the SDK built (its URL encodes the
3625
+ // waypoints). A request identical to one in flight shares that call rather than asking the
3626
+ // router twice, and still resolves under its own token, with its own emit. Only a call in
3627
+ // flight is shared, and only within this engine: a settled answer read back later would skip
3628
+ // the route a restore needs emitted again, and an answer another engine asked for is that
3629
+ // engine's to emit.
3630
+ //
3631
+ // Each call holds the controller whose signal its router was handed. A call the engine drops
3632
+ // (a request for other waypoints replaced the one it answered, or the edit ended) is aborted
3633
+ // and taken out of the map in the same step, so a later request for its waypoints shares
3634
+ // nothing with a call whose router was told to stop.
3635
+ routesInFlight = /* @__PURE__ */ new Map();
3636
+ // Whether the app currently holds a via prompt open. While true the SDK's own
3637
+ // interactivity is off, so no click adds, moves, or removes a waypoint until
3638
+ // the prompt resolves.
3639
+ viaPromptPending = false;
3640
+ // Whether this edit has said in the console that its router threw.
3641
+ routeFaultReported = false;
3642
+ // Whether the edit is over. The plugin is gone both after a dispose and between the detach
3643
+ // before a style reload and the replay after it, and only the second has a replay to come:
3644
+ // there the engine reads and writes the vias it holds, and here it holds none.
3645
+ disposed = false;
3646
+ setDraftStyle(style) {
3647
+ this.color = readEditColor(style.color, "DirectionsSegmentEngine");
3648
+ const map = this.map;
3649
+ const casing = darkenColor(this.color, 0.2);
3650
+ for (const id of lineColorLayers) {
3651
+ if (map.getLayer(id)) {
3652
+ map.setPaintProperty(id, "line-color", this.color);
3653
+ }
3654
+ }
3655
+ for (const id of lineCasingLayers) {
3656
+ if (map.getLayer(id)) {
3657
+ map.setPaintProperty(id, "line-color", casing);
3658
+ }
3659
+ }
3660
+ for (const id of circleColorLayers) {
3661
+ if (map.getLayer(id)) {
3662
+ map.setPaintProperty(id, "circle-color", this.color);
3663
+ }
3664
+ }
3665
+ for (const id of circleCasingLayers) {
3666
+ if (map.getLayer(id)) {
3667
+ map.setPaintProperty(id, "circle-color", casing);
3668
+ }
3669
+ }
3670
+ }
3671
+ readDraft() {
3672
+ if (this.disposed) {
3673
+ return null;
3674
+ }
3675
+ return this.directions ? [...this.directions.waypoints] : this.vias.map((via) => [...via]);
3676
+ }
3677
+ setViaPromptPending(pending) {
3678
+ this.viaPromptPending = pending;
3679
+ if (this.directions) {
3680
+ this.directions.interactive = !pending;
3681
+ }
3682
+ }
3683
+ applyDraft(coordinates) {
3684
+ if (this.disposed) {
3685
+ return;
3686
+ }
3687
+ if (!this.directions) {
3688
+ this.lastRoute = null;
3689
+ this.vias = [...coordinates];
3690
+ return;
3691
+ }
3692
+ this.lastRoute = null;
3693
+ this.vias = [...coordinates];
3694
+ void this.directions.setWaypoints(this.toLngLatPairs(coordinates));
3695
+ }
3696
+ dispose() {
3697
+ this.detachRouteCursor?.();
3698
+ this.detachRouteCursor = null;
3699
+ this.detachCursorReassert?.();
3700
+ this.detachCursorReassert = null;
3701
+ this.lastRoute = null;
3702
+ this.routeToken += 1;
3703
+ this.dropRoutesInFlight();
3704
+ this.disposed = true;
3705
+ this.destroyDirections();
3706
+ }
3707
+ /**
3708
+ * destroyDirections destroys the SDK instance, if one stands, and pushes nothing at the draft
3709
+ * sink while it does.
3710
+ *
3711
+ * The SDK's `destroy()` calls `clear()`, which is `setWaypoints([])`, which fires
3712
+ * `setwaypoints`. The engine's own listener reads that event as a programmatic change: it
3713
+ * replaces `this.vias` with the SDK's empty list and emits a draft with no via and no route.
3714
+ * `reverting` is the flag that listener already stands down for, so the destroy runs under it
3715
+ * at every teardown: the end of an edit, and the detach before a style reload.
3716
+ */
3717
+ destroyDirections() {
3718
+ this.reverting = true;
3719
+ try {
3720
+ this.directions?.destroy();
3721
+ } finally {
3722
+ this.reverting = false;
3723
+ }
3724
+ this.directions = null;
3725
+ }
3726
+ /**
3727
+ * detachBeforeStyleReload destroys the MapLibreGlDirections instance BEFORE the swap,
3728
+ * so {@link replayAfterStyleReload} can build a fresh one on the style that arrives.
3729
+ * See {@link EditEngine.detachBeforeStyleReload} for the shared half of the reason;
3730
+ * two things are specific to this engine.
3731
+ *
3732
+ * **The order is not a preference.** `destroy()` ends with a `removeLayer` per
3733
+ * configured layer and one `removeSource`, unguarded in the SDK. Run before the swap,
3734
+ * every one of them is still on the style and is removed with the edit. Run after, the
3735
+ * swap has already taken them off, and the map the SDK is handed through
3736
+ * {@link removalGuarded} removes nothing that is gone: unguarded, MapLibre would fire an
3737
+ * `ErrorEvent` per missing layer and throw on the missing source.
3738
+ *
3739
+ * **And the teardown wipes the vias it is about to be replayed from.** `destroy()`
3740
+ * calls `clear()`, which is `setWaypoints([])`, which fires `setwaypoints`, which the
3741
+ * engine's own listener turns into `emitFromSdk(true)`, and that replaces `this.vias`
3742
+ * with the SDK's now-empty list and pushes an empty draft at the sink. `reverting` is
3743
+ * the guard this engine already owns for exactly that re-entry, so the destroy sits
3744
+ * inside it. Without this the replay below would re-seed nothing even once the
3745
+ * instance rebuilt correctly.
3746
+ */
3747
+ detachBeforeStyleReload() {
3748
+ if (this.disposed) {
3749
+ return;
3750
+ }
3751
+ this.detachRouteCursor?.();
3752
+ this.detachRouteCursor = null;
3753
+ this.detachCursorReassert?.();
3754
+ this.detachCursorReassert = null;
3755
+ this.lastRoute = null;
3756
+ this.destroyDirections();
3757
+ }
3758
+ /**
3759
+ * replayAfterStyleReload re-renders the active edit's scene after a base-map
3760
+ * switch wiped the style. setStyle removed the SDK's layers + sources, so a whole
3761
+ * MapLibreGlDirections instance is built on the fresh style and re-seeded with the
3762
+ * vias the engine held; attach() re-wires the fetch override + the SDK's interaction
3763
+ * listeners + the cursor affordances.
3764
+ *
3765
+ * The instance it replaces was destroyed by {@link detachBeforeStyleReload}, before
3766
+ * the swap rather than here: without that this rebuilds onto layers the swap has
3767
+ * already taken away, and `this.vias` has been emptied by the teardown's own
3768
+ * `setwaypoints`. Both cursor listeners were detached there and are re-created by
3769
+ * attach(), so the pair is net-zero (no double-bind). Unlike the waypoint engines,
3770
+ * which leave their map-level subscriptions alone because a map-level listener
3771
+ * survives setStyle untouched, the map-level cursor re-assert is rebuilt
3772
+ * deliberately: it was bound to the destroyed SDK instance, so it is re-registered
3773
+ * AFTER the rebuilt SDK attaches its own move handler, preserving the dispatch order
3774
+ * attach() relies on.
3775
+ */
3776
+ replayAfterStyleReload() {
3777
+ if (this.disposed) {
3778
+ return;
3779
+ }
3780
+ if (this.directions) {
3781
+ this.detachBeforeStyleReload();
3782
+ }
3783
+ const directions = this.attach();
3784
+ if (this.vias.length > 0) {
3785
+ void directions.setWaypoints(this.toLngLatPairs(this.vias));
3786
+ }
3787
+ }
3788
+ /**
3789
+ * attach builds the MapLibreGlDirections instance with the segment-colored
3790
+ * layers, overrides its request to route through the injected routeFn (sharing
3791
+ * a call still in flight), wires the typed waypoint events to the draft sink,
3792
+ * reconciles the SDK's internal cursor handling so our cross/"+" win on the
3793
+ * routed line, and enables interactivity so a click adds a waypoint. It is the single
3794
+ * construct-and-wire point, reused by the constructor and the style-reload
3795
+ * replay. Returns the built instance so a caller can re-seed it without
3796
+ * re-reading the field (the control-flow narrowing cannot see this method
3797
+ * reassigns it).
3798
+ */
3799
+ attach() {
3800
+ const configuration = {
3801
+ api: "https://routing.invalid/route/v1",
3802
+ dragThreshold: 0,
3803
+ layers: directionsLayers(this.color),
3804
+ profile: "route",
3805
+ requestOptions: { geometries: "geojson", overview: "full" }
3806
+ };
3807
+ const directions = new MapLibreGlDirections__default.default(removalGuarded(this.map), configuration);
3808
+ this.directions = directions;
3809
+ directions.fetch = (request) => this.routeViaInjection(request);
3810
+ directions.on("addwaypoint", () => {
3811
+ if (this.enforceViaCap()) {
3812
+ return;
3813
+ }
3814
+ if (this.enforcePinnedEnd(true)) {
3815
+ return;
3816
+ }
3817
+ this.emitFromSdk(false);
3818
+ });
3819
+ directions.on("beforeremovewaypoint", (event) => {
3820
+ event.preventDefault();
3821
+ const via = this.vias[event.data.index];
3822
+ if (!via) {
3823
+ return;
3824
+ }
3825
+ chunkWW4CGS7G_cjs.notifyListeners([this.emitViaPrompt], {
3826
+ index: event.data.index,
3827
+ lngLat: [via[0] ?? 0, via[1] ?? 0]
3828
+ });
3829
+ });
3830
+ directions.on("removewaypoint", () => {
3831
+ if (this.enforcePinnedStart() || this.enforcePinnedEnd()) {
3832
+ return;
3833
+ }
3834
+ this.emitFromSdk(false);
3835
+ });
3836
+ directions.on("movewaypoint", () => {
3837
+ if (this.enforcePinnedStart() || this.enforcePinnedEnd()) {
3838
+ return;
3839
+ }
3840
+ this.emitFromSdk(false);
3841
+ });
3842
+ directions.on("setwaypoints", () => {
3843
+ if (this.reverting) {
3844
+ return;
3845
+ }
3846
+ this.emitFromSdk(true);
3847
+ });
3848
+ directions.interactive = !this.viaPromptPending;
3849
+ this.detachRouteCursor = this.attachRouteCursor();
3850
+ this.detachCursorReassert = this.attachCursorReassert();
3851
+ return directions;
3852
+ }
3853
+ /**
3854
+ * routeViaInjection is the fetch override body: it parses the waypoints from the
3855
+ * SDK-built URL, resolves them through the injected routeFn (sharing a call an
3856
+ * identical request has in flight, see {@link routeOnce}), and shapes the result
3857
+ * into the SDK's Directions response. Fewer than two waypoints or a null routeFn
3858
+ * result yields a NoRoute response so the SDK clears the routed line rather than
3859
+ * drawing a stale one.
3860
+ */
3861
+ routeViaInjection(request) {
3862
+ return this.computeRoute(parseWaypoints(request.url), request.url);
3863
+ }
3864
+ /**
3865
+ * routeOnce calls the injected routeFn for one request, or joins the call an identical
3866
+ * request already has in flight, keyed by the request's URL. The call is forgotten as it
3867
+ * settles, so the next request for the same waypoints routes again.
3868
+ *
3869
+ * The router is handed the signal of the call's own controller, which
3870
+ * {@link dropRoutesInFlight} aborts. It is the engine's and not the plugin's: the plugin
3871
+ * aborts its request at every write of its waypoints, a re-seed with the same ones included,
3872
+ * and that request shares this call.
3873
+ */
3874
+ routeOnce(key, waypoints) {
3875
+ const inFlight = this.routesInFlight.get(key);
3876
+ if (inFlight !== void 0) {
3877
+ return inFlight;
3878
+ }
3879
+ const controller = new AbortController();
3880
+ const call = this.routeFn(this.activitySlug, waypoints, { signal: controller.signal });
3881
+ const request = { call, controller };
3882
+ this.routesInFlight.set(key, request);
3883
+ const forget = () => {
3884
+ if (this.routesInFlight.get(key) === request) {
3885
+ this.routesInFlight.delete(key);
3886
+ }
3887
+ };
3888
+ call.then(forget, forget);
3889
+ return request;
3890
+ }
3891
+ /**
3892
+ * dropRoutesInFlight aborts every routing call in flight but the one for `kept`, and forgets
3893
+ * each: the request it answered was replaced by one for other waypoints, or the edit ended,
3894
+ * and nobody reads its answer. With no `kept`, every call is dropped.
3895
+ *
3896
+ * A call is forgotten before it is aborted, so a request made from inside a router's own
3897
+ * `abort` listener joins no call that is being told to stop.
3898
+ *
3899
+ * @param kept The key of the request being asked for, whose call in flight is shared.
3900
+ */
3901
+ dropRoutesInFlight(kept) {
3902
+ for (const [key, request] of [...this.routesInFlight]) {
3903
+ if (key !== kept) {
3904
+ this.routesInFlight.delete(key);
3905
+ request.controller.abort();
3906
+ }
3907
+ }
3908
+ }
3909
+ /**
3910
+ * computeRoute calls the injected routeFn for the waypoints and maps the result
3911
+ * onto the SDK's Directions shape (a single route with the GeoJSON line +
3912
+ * distance/duration, the snapped waypoints echoed). A below-floor waypoint count
3913
+ * or a null result (the router found nothing) returns a NoRoute response; a
3914
+ * thrown routeFn (a transport error, an unknown activity slug, a partial GraphQL
3915
+ * response) is absorbed into NoRoute so the edit stays usable rather than
3916
+ * surfacing inside the renderer, and {@link warnOnRouteFault} says it in the console,
3917
+ * once per edit and in development only, so a line that never paints has a reason.
3918
+ *
3919
+ * The returned geometry strips the elevation axis so the SDK's interactive math
3920
+ * (`Ve` compares snappoint locations to route coords with strict 2D equality in
3921
+ * geojson mode) sees coordinates of the same dimension as the snappoints the
3922
+ * SDK builds: a 3D-vs-2D mismatch otherwise drops every intermediate leg to a
3923
+ * one-coord empty slice in buildRoutelines and the routed line never paints.
3924
+ * The snappoints echo a route-anchored coordinate so the SDK's coord-match loop
3925
+ * finds them: the first via lands at the route's first coord, the last via at
3926
+ * its last coord, and any intermediate via at its nearest route vertex. That
3927
+ * is the only contract buildRoutelines needs to cut a route into legs.
3928
+ *
3929
+ * `key` names the request, for {@link routeOnce} to share a call still in flight. Every call
3930
+ * in flight for other waypoints is dropped as this one begins ({@link dropRoutesInFlight}),
3931
+ * and a dropped request rejects here with the abort's reason, whatever its router answers:
3932
+ * a route, no route, or a rejection. The plugin reads that as a request of its own that it
3933
+ * aborted, and draws nothing for it.
3934
+ */
3935
+ async computeRoute(waypoints, key) {
3936
+ const noRoute = { code: "NoRoute", routes: [], waypoints: [] };
3937
+ this.routeToken += 1;
3938
+ const token = this.routeToken;
3939
+ this.dropRoutesInFlight(key);
3940
+ if (waypoints.length < chunkEX2C5K2T_cjs.DIRECTIONS_VIA_MIN || waypoints.length > chunkEX2C5K2T_cjs.DIRECTIONS_VIA_MAX) {
3941
+ this.lastRoute = null;
3942
+ return noRoute;
3943
+ }
3944
+ let request = null;
3945
+ let route;
3946
+ try {
3947
+ request = this.routeOnce(key, waypoints);
3948
+ route = await request.call;
3949
+ } catch (fault) {
3950
+ request?.controller.signal.throwIfAborted();
3951
+ this.warnOnRouteFault(fault);
3952
+ if (token === this.routeToken) {
3953
+ this.lastRoute = null;
3954
+ }
3955
+ return noRoute;
3956
+ }
3957
+ request.controller.signal.throwIfAborted();
3958
+ if (route === chunkROKNKXA4_cjs.SEGMENT_ROUTE_REFUSED) {
3959
+ if (token === this.routeToken) {
3960
+ this.revertToAcceptedVias();
3961
+ }
3962
+ return noRoute;
3963
+ }
3964
+ if (!route) {
3965
+ if (token === this.routeToken) {
3966
+ this.lastRoute = null;
3967
+ }
3968
+ return noRoute;
3969
+ }
3970
+ if (token === this.routeToken) {
3971
+ this.lastRoute = route;
3972
+ this.acceptedVias = [...waypoints];
3973
+ chunkWW4CGS7G_cjs.notifyListeners([this.emitDraft], {
3974
+ phase: "settled",
3975
+ programmatic: true,
3976
+ route,
3977
+ vias: waypoints
3978
+ });
3979
+ }
3980
+ const coordinates2d = route.geometry.coordinates.map((coordinate) => [
3981
+ coordinate[0] ?? 0,
3982
+ coordinate[1] ?? 0
3983
+ ]);
3984
+ const snapped = snapWaypointsToRoute(waypoints, coordinates2d);
3985
+ const legs = Array.from({ length: Math.max(waypoints.length - 1, 0) }, () => ({
3986
+ annotation: { congestion: [], distance: [], duration: [] },
3987
+ distance: 0,
3988
+ duration: 0,
3989
+ steps: [],
3990
+ summary: ""
3991
+ }));
3992
+ return {
3993
+ code: "Ok",
3994
+ routes: [
3995
+ {
3996
+ distance: route.distance,
3997
+ duration: route.duration,
3998
+ geometry: { coordinates: coordinates2d },
3999
+ legs
4000
+ }
4001
+ ],
4002
+ waypoints: snapped.map((location) => ({ location }))
4003
+ };
4004
+ }
4005
+ /**
4006
+ * warnOnRouteFault says in the console, once per edit and in development only, that the
4007
+ * injected router threw.
4008
+ *
4009
+ * The engine reads a throw as no route found, so nothing the host holds rejects and the line
4010
+ * simply does not paint. The console is where the developer who wired the router is looking,
4011
+ * and the error rides beside the sentence with its stack. Once per edit, because a drag asks
4012
+ * for a route at every position it settles on and a router that is down fails each one for
4013
+ * the same reason. A production build says nothing: the fault is the host's to report through
4014
+ * its own router.
4015
+ */
4016
+ warnOnRouteFault(fault) {
4017
+ if (this.routeFaultReported || !chunkEP5OEEVZ_cjs.inDevelopment()) {
4018
+ return;
4019
+ }
4020
+ this.routeFaultReported = true;
4021
+ console.warn(
4022
+ "[@mountaya/elements] DirectionsSegmentEngine: routeFn threw, so the edit draws no route for these vias. A router that finds no route resolves to null; one that throws is read the same way and the edit stays open. The error it threw follows.",
4023
+ fault
4024
+ );
4025
+ }
4026
+ /**
4027
+ * enforcePinnedStart inspects the SDK's current first waypoint against the
4028
+ * pinned-start coordinate. If the head drifted past the backend's horizontal
4029
+ * tolerance (or was removed outright), it restores `pinnedStart` at index 0
4030
+ * via a programmatic setWaypoints, flagged through `reverting` so the
4031
+ * resulting setwaypoints event short-circuits in the listener and the
4032
+ * revert never enters history. Returns true when a revert ran so the caller
4033
+ * (the interactive move/remove listener) skips its own normal emit; the
4034
+ * revert's own setwaypoints event would have emitted a programmatic draft,
4035
+ * but the `reverting` guard suppresses it: the restored state is the same
4036
+ * state the next interactive gesture will read, so a duplicate emit is just
4037
+ * noise. Without a pinnedStart configured, the guard always returns false.
4038
+ */
4039
+ enforcePinnedStart() {
4040
+ if (!this.pinnedStart || !this.directions) {
4041
+ return false;
4042
+ }
4043
+ const current = this.directions.waypoints;
4044
+ if (isPinnedWaypointIntact(current, this.pinnedStart, 0)) {
4045
+ return false;
4046
+ }
4047
+ const pinned = [this.pinnedStart[0] ?? 0, this.pinnedStart[1] ?? 0];
4048
+ const tail = current.slice(1);
4049
+ const corrected = [pinned, ...tail];
4050
+ this.reverting = true;
4051
+ try {
4052
+ void this.directions.setWaypoints(corrected);
4053
+ } finally {
4054
+ this.reverting = false;
4055
+ }
4056
+ this.vias = corrected.map((point) => [point[0], point[1]]);
4057
+ return true;
4058
+ }
4059
+ /**
4060
+ * enforcePinnedEnd is the tail mirror of {@link enforcePinnedStart}, with one
4061
+ * extra job. It keeps the pinned coordinate LAST, which covers two situations:
4062
+ *
4063
+ * - a drag or a programmatic remove moved the tail off the neighbour's start, so
4064
+ * the pin is restored in place exactly as the head guard restores index 0;
4065
+ * - an interactive add appended a via PAST the pin, so the pin is moved back
4066
+ * behind it. The click is kept, not reverted: the user asked for a point and
4067
+ * gets one, it just lands before the neighbour instead of after it.
4068
+ *
4069
+ * The second case is a real geometry change, so `emitInteractive` makes the
4070
+ * reorder emit its own interactive draft (the `reverting` flag suppresses the
4071
+ * setwaypoints event's emit, and the added via must still reach history and the
4072
+ * router). The restore cases pass false and stay silent, like the head guard.
4073
+ *
4074
+ * Returns true when it corrected the waypoints, so the caller skips its own emit.
4075
+ * Without a pinnedEnd configured it always returns false.
4076
+ */
4077
+ enforcePinnedEnd(emitInteractive = false) {
4078
+ if (!this.pinnedEnd || !this.directions) {
4079
+ return false;
4080
+ }
4081
+ const current = this.directions.waypoints;
4082
+ if (isPinnedWaypointIntact(current, this.pinnedEnd, current.length - 1)) {
4083
+ return false;
4084
+ }
4085
+ const pinned = [this.pinnedEnd[0] ?? 0, this.pinnedEnd[1] ?? 0];
4086
+ const pinIndex = current.findIndex(
4087
+ (_waypoint, index) => isPinnedWaypointIntact(current, pinned, index)
4088
+ );
4089
+ const rest = pinIndex === -1 ? current.slice(0, -1) : current.filter((_wp, index) => index !== pinIndex);
4090
+ const corrected = [...rest, pinned];
4091
+ this.reverting = true;
4092
+ try {
4093
+ void this.directions.setWaypoints(corrected);
4094
+ } finally {
4095
+ this.reverting = false;
4096
+ }
4097
+ this.vias = corrected.map((point) => [point[0], point[1]]);
4098
+ if (emitInteractive) {
4099
+ this.emitFromSdk(false);
4100
+ }
4101
+ return true;
4102
+ }
4103
+ /**
4104
+ * enforceViaCap refuses an interactive add that would push the via count past
4105
+ * `DIRECTIONS_VIA_MAX`. The router floors an over-cap set to a NoRoute response
4106
+ * (the SDK then clears the whole routed line), so rather than route it, the
4107
+ * engine reverts the SDK to the pre-insert vias it still holds in `this.vias`
4108
+ * and keeps the current `lastRoute` so the painted line survives the declined
4109
+ * insert. The revert is a programmatic setWaypoints flagged through `reverting`,
4110
+ * so the resulting setwaypoints event short-circuits in the listener and the
4111
+ * decline never enters history. Returns true when a revert ran so the
4112
+ * `addwaypoint` listener skips its own emit; false (the common case) leaves the
4113
+ * add to flow through normally. Mirrors `enforcePinnedStart`'s revert exactly.
4114
+ */
4115
+ enforceViaCap() {
4116
+ if (!this.directions || this.directions.waypoints.length <= chunkEX2C5K2T_cjs.DIRECTIONS_VIA_MAX) {
4117
+ return false;
4118
+ }
4119
+ this.reverting = true;
4120
+ try {
4121
+ void this.directions.setWaypoints(this.toLngLatPairs(this.vias));
4122
+ } finally {
4123
+ this.reverting = false;
4124
+ }
4125
+ if (this.onViaCapRefused !== void 0) {
4126
+ chunkWW4CGS7G_cjs.notifyListeners([this.onViaCapRefused]);
4127
+ }
4128
+ return true;
4129
+ }
4130
+ /**
4131
+ * revertToAcceptedVias undoes an in-flight placement by re-seeding the SDK with
4132
+ * the last via set whose route was accepted. `vias` is reset alongside so the
4133
+ * engine's mirror does not keep describing the refused set, and the `reverting`
4134
+ * guard keeps the resulting `setwaypoints` event from re-entering the pinned
4135
+ * checks on the just-restored state, the same shape as enforceViaCap's revert.
4136
+ *
4137
+ * The re-seed fires its own routing round-trip, for vias the router has already
4138
+ * answered and the user accepted: a router that asks the user before it answers
4139
+ * asks nothing of a set it answered before (the studio's remembers them), and the
4140
+ * route the user kept repaints.
4141
+ */
4142
+ revertToAcceptedVias() {
4143
+ if (!this.directions) {
4144
+ return;
4145
+ }
4146
+ this.vias = [...this.acceptedVias];
4147
+ this.reverting = true;
4148
+ try {
4149
+ void this.directions.setWaypoints(this.toLngLatPairs(this.acceptedVias));
4150
+ } finally {
4151
+ this.reverting = false;
4152
+ }
4153
+ }
4154
+ /**
4155
+ * emitFromSdk reads the SDK's current waypoints, mirrors them onto the engine's
4156
+ * via cache, and forwards them as a draft with the given programmatic flag. The
4157
+ * flag comes from the event that triggered it (false for an interactive
4158
+ * add/move/remove, true for a programmatic setwaypoints re-seed) so a restore's
4159
+ * setwaypoints event does not re-enter history while a user gesture does.
4160
+ *
4161
+ * Every draft it forwards is `settled`. The SDK reports a waypoint once per gesture: an add
4162
+ * on the click, a move when the drag lets go (it reports no frame while `refreshOnMove` is
4163
+ * off, as this engine leaves it), a re-seed in one call. So there is never a frame to report.
4164
+ */
4165
+ emitFromSdk(programmatic) {
4166
+ if (!this.directions) {
4167
+ return;
4168
+ }
4169
+ const vias = [...this.directions.waypoints];
4170
+ this.vias = vias;
4171
+ const draft = { phase: "settled", programmatic, route: this.lastRoute, vias };
4172
+ chunkWW4CGS7G_cjs.notifyListeners([this.emitDraft], draft);
4173
+ }
4174
+ /**
4175
+ * attachRouteCursor shows "pointer" as an override while the pointer sits on the SDK's
4176
+ * sensitive routeline layer, through the shared {@link attachEditHoverCursor}, and the base
4177
+ * "+" append cross off it. So the cursor reads "pointer" on the routed line between two
4178
+ * existing points, where a click inserts a point, and "+" elsewhere, where a click adds the
4179
+ * next one. The override (not a fresh lock) keeps the base cross intact, the same
4180
+ * reconciliation the rest of the cursor system uses.
4181
+ *
4182
+ * The SDK's own `onMove` writes `canvas.style.cursor` directly on every move (clearing it over
4183
+ * empty map, overwriting it on the routeline); the map-level {@link attachCursorReassert}
4184
+ * re-pins the effective held cursor after it, the routeline override included.
4185
+ */
4186
+ attachRouteCursor() {
4187
+ return chunkIBQJDVHF_cjs.attachEditHoverCursor({
4188
+ cursor: this.cursor,
4189
+ events: this.events,
4190
+ layers: [{ cursor: "pointer", kind: "fixed", layerId: "maplibre-gl-directions-routeline" }],
4191
+ map: this.map
4192
+ });
4193
+ }
4194
+ /**
4195
+ * attachCursorReassert subscribes the shared map-level mousemove re-assert that
4196
+ * re-pins the EFFECTIVE held cursor (the routeline "pointer" override when one
4197
+ * is held, else the locked "+" cross) after the SDK's own global move handler
4198
+ * has run. The SDK's `onMove` writes `canvas.style.cursor` directly: over empty
4199
+ * map (the "add the next point" append state) it clears it to "", on the
4200
+ * routeline it overwrites it; one map-level listener counters both because
4201
+ * `reassert` re-pins whichever tier is held.
4202
+ *
4203
+ * It deliberately does NOT touch drag-pan: the SDK owns pan itself: it enables
4204
+ * panning over empty map (so a drag pans the map while editing, and a click
4205
+ * still adds the next point) and disables it only while dragging a waypoint or
4206
+ * the routed line (so that drag reshapes). Registering it LAST (after
4207
+ * `interactive = true` has attached the SDK's move handler) means MapLibre
4208
+ * dispatches us after the SDK, so our cursor re-pin wins; it detaches by
4209
+ * reference through the shared manager.
4210
+ */
4211
+ attachCursorReassert() {
4212
+ return chunkIBQJDVHF_cjs.attachCursorReassert(this.events, this.cursor);
4213
+ }
4214
+ /** toLngLatPairs widens Position[] to the [number, number][] the SDK's setWaypoints expects, defaulting a missing axis to 0. */
4215
+ toLngLatPairs(coordinates) {
4216
+ return coordinates.map((coordinate) => [coordinate[0] ?? 0, coordinate[1] ?? 0]);
4217
+ }
4218
+ };
4219
+
4220
+ // src/editor/engines/poiPick.ts
4221
+ var isCapturable = (poi) => chunkV3JEP5AG_cjs.omtCategoryToPoiEnum(poi.category) !== null;
4222
+ var PoiPickWaypointEngine = class {
4223
+ /**
4224
+ * @throws {MountayaElementsError} When `options.initialLngLat` is neither `null` nor a
4225
+ * longitude and a latitude a map can place: two finite numbers, the latitude from -90 to 90.
4226
+ * It is refused before the marker is built and before a seam is subscribed to.
4227
+ */
4228
+ constructor(map, placement, options, emitChange, query, events, cursor) {
4229
+ this.emitChange = emitChange;
4230
+ const initialLngLat = readEditPosition(
4231
+ options.initialLngLat,
4232
+ "PoiPickWaypointEngine",
4233
+ "initialLngLat",
4234
+ "pass null for a waypoint not placed yet"
4235
+ );
4236
+ this.currentIcon = options.initialIcon;
4237
+ this.currentColor = options.initialColor;
4238
+ this.onPoiHoverChange = options.onPoiHoverChange;
4239
+ this.marker = new DraftWaypointMarker(map, placement);
4240
+ if (initialLngLat) {
4241
+ this.marker.apply({
4242
+ color: this.currentColor,
4243
+ icon: this.currentIcon,
4244
+ lngLat: initialLngLat
4245
+ });
4246
+ }
4247
+ this.detachClick = query.onMapClick((lngLat) => {
4248
+ this.handleClick(lngLat, query);
4249
+ });
4250
+ this.detachPointerMove = this.onPoiHoverChange === void 0 ? () => {
4251
+ } : query.onPointerMove((move) => {
4252
+ this.lastPointerMove = { lngLat: move.lngLat };
4253
+ if (this.pointerFrame === null) {
4254
+ this.pointerFrame = requestAnimationFrame(() => {
4255
+ this.pointerFrame = null;
4256
+ const latest = this.lastPointerMove;
4257
+ if (!latest) {
4258
+ return;
4259
+ }
4260
+ this.reportHover(query.queryPoisAt(latest.lngLat).some(isCapturable));
4261
+ });
4262
+ }
4263
+ });
4264
+ if (events && cursor) {
4265
+ this.detachCursorReassert = chunkIBQJDVHF_cjs.attachCursorReassert(events, cursor);
4266
+ }
4267
+ }
4268
+ emitChange;
4269
+ marker;
4270
+ detachClick;
4271
+ detachPointerMove;
4272
+ // Detaches the shared map-level mousemove cursor re-assert; null when no event engine and
4273
+ // cursor engine are wired (a suite that drives the click seam alone). The POI-pick edit holds the
4274
+ // native `"pointer"` lock (it selects an existing POI rather than dropping a point), and every
4275
+ // lock-holding engine re-asserts the held cursor on a map-level move, attached LAST and detached
4276
+ // FIRST. The engine paints no library scene of its own, so nothing clobbers the lock here: the
4277
+ // re-assert writes nothing (its value-changed guard skips the redundant write).
4278
+ detachCursorReassert = null;
4279
+ currentIcon;
4280
+ currentColor;
4281
+ pointerFrame = null;
4282
+ // The latest pointer-move's geographic coordinate, read by the rAF frame to
4283
+ // resolve the hover signal. Only the coordinate is kept: the native `"pointer"`
4284
+ // cursor tracks the pixel itself, so the pixel position the move also carries
4285
+ // is unused.
4286
+ lastPointerMove = null;
4287
+ // The seam the hover signal is reported through, and the answer it was last told. The
4288
+ // answer starts at false, the state a host assumes before it is told anything.
4289
+ onPoiHoverChange;
4290
+ isOverPoi = false;
4291
+ setDraftStyle(style) {
4292
+ this.currentColor = style.color;
4293
+ this.currentIcon = style.icon;
4294
+ this.marker.setStyle(style);
4295
+ }
4296
+ readDraft() {
4297
+ return this.marker.read();
4298
+ }
4299
+ clearDraft() {
4300
+ this.marker.clear();
4301
+ }
4302
+ applyDraft(snapshot) {
4303
+ this.currentColor = snapshot.color;
4304
+ this.currentIcon = snapshot.icon;
4305
+ this.marker.apply(snapshot);
4306
+ }
4307
+ dispose() {
4308
+ this.detachCursorReassert?.();
4309
+ this.detachCursorReassert = null;
4310
+ this.detachClick();
4311
+ this.detachPointerMove();
4312
+ if (this.pointerFrame !== null) {
4313
+ cancelAnimationFrame(this.pointerFrame);
4314
+ this.pointerFrame = null;
4315
+ }
4316
+ this.lastPointerMove = null;
4317
+ this.marker.clear();
4318
+ this.reportHover(false);
4319
+ }
4320
+ /**
4321
+ * detachBeforeStyleReload is a no-op here, and it is the one engine for which that is
4322
+ * the right answer. Its siblings implement this because each delegates its rendering
4323
+ * to a library that will not re-attach without a stop first (see
4324
+ * {@link EditEngine.detachBeforeStyleReload}). This engine delegates to nothing: its
4325
+ * only scene is the shared draft marker, which lives in the façade's marker registry
4326
+ * and re-adds itself, and its map-level click and pointer-move listeners survive
4327
+ * `setStyle` untouched. There is no library to stop and nothing to take off the
4328
+ * outgoing style, so stopping anything here would only be a teardown with no
4329
+ * matching rebuild.
4330
+ */
4331
+ detachBeforeStyleReload() {
4332
+ }
4333
+ /**
4334
+ * replayAfterStyleReload re-renders the active edit's scene after a base-map
4335
+ * switch wiped the style. It re-attaches only what setStyle tore down: the
4336
+ * marker's source + symbol layer (the engine owns no rendered layer of its
4337
+ * own). The cursor is the native `"pointer"` lock the hook re-asserts, not a
4338
+ * DOM element parented to the canvas container, so nothing cursor-side needs
4339
+ * rebuilding here. It does NOT re-attach the engine's map-level subscriptions
4340
+ * (the map-click, pointer-move, and cursor re-assert the constructor bound with
4341
+ * no layerId): a map-level listener survives setStyle untouched (only
4342
+ * layer-scoped listeners and library layers come off) so re-attaching here
4343
+ * would double-bind them. Unlike the directions/point engines, whose re-assert
4344
+ * was bound to a torn-down library scene and so is rebuilt, this engine paints
4345
+ * no such scene, so its re-assert needs nothing rewired.
4346
+ */
4347
+ replayAfterStyleReload() {
4348
+ this.marker.replay();
4349
+ }
4350
+ /**
4351
+ * handleClick reads the POIs under the clicked coordinate and emits a draft change for the
4352
+ * one the click captures: the first, topmost first, whose category is in the supported
4353
+ * vocabulary. That is the POI the hover seam answers for, so a click captures exactly when
4354
+ * the seam says it would.
4355
+ *
4356
+ * A click over no such POI is dropped, so the seam never carries an unrecognized category
4357
+ * onward. The tile's category string is translated to a `PoiCategory` member before it rides
4358
+ * through the seed, and the POI's display name rides with it (null when the tile carries
4359
+ * none), so the tool layer can seed the draft name from the POI just clicked.
4360
+ */
4361
+ handleClick(lngLat, query) {
4362
+ const first = query.queryPoisAt(lngLat).find(isCapturable);
4363
+ if (!first) {
4364
+ return;
4365
+ }
4366
+ const category = chunkV3JEP5AG_cjs.omtCategoryToPoiEnum(first.category);
4367
+ if (!category) {
4368
+ return;
4369
+ }
4370
+ const seed = {
4371
+ category,
4372
+ // OpenMapTiles surfaces the feature's display label on its `name`
4373
+ // property; the seam carries it through so the tool layer can re-seed
4374
+ // the draft name on every fresh POI capture (last POI wins).
4375
+ name: first.name,
4376
+ // The tile feature the place came from, so a saved waypoint records its provenance. A
4377
+ // tile that numbers no feature leaves it null, and the category and name stand alone.
4378
+ sourceFeatureId: first.id
4379
+ };
4380
+ this.marker.apply({
4381
+ color: this.currentColor,
4382
+ icon: this.currentIcon,
4383
+ lngLat
4384
+ });
4385
+ chunkWW4CGS7G_cjs.notifyListeners([this.emitChange], { lngLat, poiSeed: seed });
4386
+ }
4387
+ /**
4388
+ * reportHover tells the hover seam whether the pointer is over a POI a click would capture,
4389
+ * when that answer differs from the one it was last told.
4390
+ *
4391
+ * The answer is recorded before the seam is called, so a handler that throws leaves the
4392
+ * engine's own state right. Its error is the host's defect: thrown through the engine it
4393
+ * would abort a frame or a teardown half way, so it is handed to the runtime on a microtask.
4394
+ */
4395
+ reportHover(isOverPoi) {
4396
+ if (isOverPoi === this.isOverPoi) {
4397
+ return;
4398
+ }
4399
+ this.isOverPoi = isOverPoi;
4400
+ try {
4401
+ this.onPoiHoverChange?.(isOverPoi);
4402
+ } catch (fault) {
4403
+ chunkWW4CGS7G_cjs.surfaceFault(fault);
4404
+ }
4405
+ }
4406
+ };
4407
+
4408
+ // src/editor/engines/editorClient.ts
4409
+ var editEngines = {
4410
+ boundary: (seams, options, emitDraft) => new TerraDrawBoundaryEngine(
4411
+ seams.map,
4412
+ options,
4413
+ emitDraft,
4414
+ void 0,
4415
+ seams.events,
4416
+ seams.cursor
4417
+ ),
4418
+ refuseBoundary: (options) => {
4419
+ readEditColor(options.color, "TerraDrawBoundaryEngine");
4420
+ },
4421
+ refuseSegment: (options) => {
4422
+ if (options.mode === "directions") {
4423
+ refuseUnroutableEdit(options);
4424
+ readEditColor(options.color, "DirectionsSegmentEngine");
4425
+ } else {
4426
+ refuseSegmentSeed(options, "TerraDrawLinestringSegmentEngine");
4427
+ readEditColor(options.color, "TerraDrawLinestringSegmentEngine");
4428
+ }
4429
+ },
4430
+ refuseWaypoint: (options) => {
4431
+ readEditPosition(
4432
+ options.initialLngLat,
4433
+ options.mode === "point" ? "TerraDrawPointWaypointEngine" : "PoiPickWaypointEngine",
4434
+ "initialLngLat",
4435
+ "pass null for a waypoint not placed yet"
4436
+ );
4437
+ },
4438
+ refuseZone: (options) => {
4439
+ refuseZoneSeed(options, "TerraDrawZoneEngine");
4440
+ readEditColor(options.color, "TerraDrawZoneEngine");
4441
+ },
4442
+ segment: (seams, options, emitDraft, emitViaPrompt) => options.mode === "directions" ? new DirectionsSegmentEngine(
4443
+ seams.map,
4444
+ seams.events,
4445
+ seams.cursor,
4446
+ options,
4447
+ emitDraft,
4448
+ emitViaPrompt
4449
+ ) : new TerraDrawLinestringSegmentEngine(
4450
+ seams.map,
4451
+ seams.events,
4452
+ seams.cursor,
4453
+ options,
4454
+ emitDraft,
4455
+ emitViaPrompt
4456
+ ),
4457
+ waypoint: (seams, options, emitDraftChange) => options.mode === "point" ? (
4458
+ // The draw factory is left at the engine's default, so the snap provider, the event
4459
+ // engine, the cursor engine and the cursor's glyphs land in their named positions.
4460
+ new TerraDrawPointWaypointEngine(
4461
+ seams.map,
4462
+ seams.placement,
4463
+ options,
4464
+ emitDraftChange,
4465
+ void 0,
4466
+ seams.snapSegments,
4467
+ seams.events,
4468
+ seams.cursor,
4469
+ seams.cursorOptions
4470
+ )
4471
+ ) : new PoiPickWaypointEngine(
4472
+ seams.map,
4473
+ seams.placement,
4474
+ options,
4475
+ emitDraftChange,
4476
+ seams.pick,
4477
+ seams.events,
4478
+ seams.cursor
4479
+ ),
4480
+ zone: (seams, options, emitDraft) => new TerraDrawZoneEngine(seams.map, options, emitDraft, void 0, seams.events, seams.cursor)
4481
+ };
4482
+ var MapLibreClient = class _MapLibreClient extends chunkAFKOABJ4_cjs.MapLibreViewClient {
4483
+ static {
4484
+ chunkAFKOABJ4_cjs.bindEditEngines(_MapLibreClient.prototype, editEngines);
4485
+ }
4486
+ };
4487
+
4488
+ Object.defineProperty(exports, "blankStyle", {
4489
+ enumerable: true,
4490
+ get: function () { return chunkAFKOABJ4_cjs.blankStyle; }
4491
+ });
4492
+ Object.defineProperty(exports, "SEGMENT_ROUTE_REFUSED", {
4493
+ enumerable: true,
4494
+ get: function () { return chunkROKNKXA4_cjs.SEGMENT_ROUTE_REFUSED; }
4495
+ });
4496
+ Object.defineProperty(exports, "ZONE_LEVELS", {
4497
+ enumerable: true,
4498
+ get: function () { return chunkGE6CFCAM_cjs.ZONE_LEVELS; }
4499
+ });
4500
+ Object.defineProperty(exports, "ZONE_MODES", {
4501
+ enumerable: true,
4502
+ get: function () { return chunkGE6CFCAM_cjs.ZONE_MODES; }
4503
+ });
4504
+ exports.MapLibreClient = MapLibreClient;
4505
+ //# sourceMappingURL=index.cjs.map
4506
+ //# sourceMappingURL=index.cjs.map