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