@mountaya/studio 0.0.0-stage → 0.2.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 (521) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/LICENCE.fr.txt +280 -0
  3. package/LICENSE.txt +262 -0
  4. package/README.md +917 -2
  5. package/dist/agent/index.cjs +2600 -0
  6. package/dist/agent/index.cjs.map +1 -0
  7. package/dist/agent/index.d.cts +1237 -0
  8. package/dist/agent/index.d.ts +1237 -0
  9. package/dist/agent/index.js +2581 -0
  10. package/dist/agent/index.js.map +1 -0
  11. package/dist/chunk-3Oi_Zrtm.js +9 -0
  12. package/dist/chunk-3Oi_Zrtm.js.map +1 -0
  13. package/dist/chunk-B18OPIu_.js +6 -0
  14. package/dist/chunk-B18OPIu_.js.map +1 -0
  15. package/dist/chunk-B5Uz3Qct.cjs +15 -0
  16. package/dist/chunk-B5Uz3Qct.cjs.map +1 -0
  17. package/dist/chunk-BBEJwkd3.d.cts +839 -0
  18. package/dist/chunk-BIEc_SkR.cjs +29 -0
  19. package/dist/chunk-BIEc_SkR.cjs.map +1 -0
  20. package/dist/chunk-BKMFOe-N.js +171 -0
  21. package/dist/chunk-BKMFOe-N.js.map +1 -0
  22. package/dist/chunk-BP4uy7E1.d.ts +11583 -0
  23. package/dist/chunk-BSHTsFiB.js +1403 -0
  24. package/dist/chunk-BSHTsFiB.js.map +1 -0
  25. package/dist/chunk-BTUUABGI.js +17 -0
  26. package/dist/chunk-BTUUABGI.js.map +1 -0
  27. package/dist/chunk-BaPiaz5X.cjs +115 -0
  28. package/dist/chunk-BaPiaz5X.cjs.map +1 -0
  29. package/dist/chunk-BeCVpkYr.cjs +542 -0
  30. package/dist/chunk-BeCVpkYr.cjs.map +1 -0
  31. package/dist/chunk-BgngsvK8.cjs +6202 -0
  32. package/dist/chunk-BgngsvK8.cjs.map +1 -0
  33. package/dist/chunk-BhInd7CJ.d.cts +253 -0
  34. package/dist/chunk-Bn6ZbxkS.cjs +27 -0
  35. package/dist/chunk-By9ZnkVI.js +60 -0
  36. package/dist/chunk-By9ZnkVI.js.map +1 -0
  37. package/dist/chunk-BzqPhxsz.cjs +367 -0
  38. package/dist/chunk-BzqPhxsz.cjs.map +1 -0
  39. package/dist/chunk-C2mMX81q.d.ts +443 -0
  40. package/dist/chunk-C2rr9Q0V.cjs +1402 -0
  41. package/dist/chunk-C2rr9Q0V.cjs.map +1 -0
  42. package/dist/chunk-CDJCbwIQ.d.cts +78 -0
  43. package/dist/chunk-CLGvBOVH.d.cts +1654 -0
  44. package/dist/chunk-COdw1dc6.d.ts +525 -0
  45. package/dist/chunk-CQCJnT2i.d.ts +511 -0
  46. package/dist/chunk-CSyHY67q.cjs +353 -0
  47. package/dist/chunk-CSyHY67q.cjs.map +1 -0
  48. package/dist/chunk-CiK1Iqrv.js +950 -0
  49. package/dist/chunk-CiK1Iqrv.js.map +1 -0
  50. package/dist/chunk-CmJBgSwZ.cjs +24 -0
  51. package/dist/chunk-CmJBgSwZ.cjs.map +1 -0
  52. package/dist/chunk-CnrsRK2u.cjs +83 -0
  53. package/dist/chunk-CnrsRK2u.cjs.map +1 -0
  54. package/dist/chunk-Co782_9r.js +326 -0
  55. package/dist/chunk-Co782_9r.js.map +1 -0
  56. package/dist/chunk-Csr3KDpZ.cjs +32 -0
  57. package/dist/chunk-Csr3KDpZ.cjs.map +1 -0
  58. package/dist/chunk-CwkmccXv.js +89 -0
  59. package/dist/chunk-CwkmccXv.js.map +1 -0
  60. package/dist/chunk-D0Q4iL9B.cjs +255 -0
  61. package/dist/chunk-D0Q4iL9B.cjs.map +1 -0
  62. package/dist/chunk-DFwiSzUS.cjs +72 -0
  63. package/dist/chunk-DFwiSzUS.cjs.map +1 -0
  64. package/dist/chunk-DIFayl2P.d.cts +443 -0
  65. package/dist/chunk-DIGF58ux.d.cts +525 -0
  66. package/dist/chunk-DKuuuld5.js +101 -0
  67. package/dist/chunk-DKuuuld5.js.map +1 -0
  68. package/dist/chunk-DMePkFEo.js +5054 -0
  69. package/dist/chunk-DMePkFEo.js.map +1 -0
  70. package/dist/chunk-DO5SIBgu.js +305 -0
  71. package/dist/chunk-DO5SIBgu.js.map +1 -0
  72. package/dist/chunk-DOQ_7eE5.d.ts +6662 -0
  73. package/dist/chunk-DThaaNeb.d.cts +15 -0
  74. package/dist/chunk-DThaaNeb.d.ts +15 -0
  75. package/dist/chunk-DUQzjUJy.d.ts +78 -0
  76. package/dist/chunk-DX37IPhV.cjs +1903 -0
  77. package/dist/chunk-DX37IPhV.cjs.map +1 -0
  78. package/dist/chunk-Damps5Tk.cjs +155 -0
  79. package/dist/chunk-Damps5Tk.cjs.map +1 -0
  80. package/dist/chunk-DbK5PhpJ.d.ts +1654 -0
  81. package/dist/chunk-De0vAASv.d.ts +253 -0
  82. package/dist/chunk-DhSZ7YZt.d.cts +6662 -0
  83. package/dist/chunk-DjEvqvPA.cjs +43 -0
  84. package/dist/chunk-DjEvqvPA.cjs.map +1 -0
  85. package/dist/chunk-DkwDzwvu.d.cts +121 -0
  86. package/dist/chunk-DkwDzwvu.d.ts +121 -0
  87. package/dist/chunk-Dmszv9If.js +71 -0
  88. package/dist/chunk-Dmszv9If.js.map +1 -0
  89. package/dist/chunk-Dp_ftNWY.d.cts +511 -0
  90. package/dist/chunk-DsHQySz0.js +31 -0
  91. package/dist/chunk-DsHQySz0.js.map +1 -0
  92. package/dist/chunk-DwoUyHHh.js +281 -0
  93. package/dist/chunk-DwoUyHHh.js.map +1 -0
  94. package/dist/chunk-IaIDQflj.d.cts +2315 -0
  95. package/dist/chunk-IaIDQflj.d.ts +2315 -0
  96. package/dist/chunk-cVXLsZfL.d.ts +839 -0
  97. package/dist/chunk-mIaCX9EJ.d.cts +11583 -0
  98. package/dist/chunk-nJQxbOwQ.cjs +8962 -0
  99. package/dist/chunk-nJQxbOwQ.cjs.map +1 -0
  100. package/dist/chunk-o9jaxhCO.js +8852 -0
  101. package/dist/chunk-o9jaxhCO.js.map +1 -0
  102. package/dist/chunk-p-Tt_Lwz.js +14 -0
  103. package/dist/chunk-p-Tt_Lwz.js.map +1 -0
  104. package/dist/engines/index.cjs +2091 -0
  105. package/dist/engines/index.cjs.map +1 -0
  106. package/dist/engines/index.d.cts +2176 -0
  107. package/dist/engines/index.d.ts +2176 -0
  108. package/dist/engines/index.js +2075 -0
  109. package/dist/engines/index.js.map +1 -0
  110. package/dist/handlers/index.cjs +53 -0
  111. package/dist/handlers/index.cjs.map +1 -0
  112. package/dist/handlers/index.d.cts +403 -0
  113. package/dist/handlers/index.d.ts +403 -0
  114. package/dist/handlers/index.js +33 -0
  115. package/dist/handlers/index.js.map +1 -0
  116. package/dist/index.cjs +3511 -0
  117. package/dist/index.cjs.map +1 -0
  118. package/dist/index.d.cts +8 -0
  119. package/dist/index.d.ts +8 -0
  120. package/dist/index.js +3033 -0
  121. package/dist/index.js.map +1 -0
  122. package/dist/plugins/index.cjs +510 -0
  123. package/dist/plugins/index.cjs.map +1 -0
  124. package/dist/plugins/index.d.cts +296 -0
  125. package/dist/plugins/index.d.ts +296 -0
  126. package/dist/plugins/index.js +489 -0
  127. package/dist/plugins/index.js.map +1 -0
  128. package/dist/seams/index.cjs +89 -0
  129. package/dist/seams/index.cjs.map +1 -0
  130. package/dist/seams/index.d.cts +452 -0
  131. package/dist/seams/index.d.ts +452 -0
  132. package/dist/seams/index.js +49 -0
  133. package/dist/seams/index.js.map +1 -0
  134. package/dist/strings/fr/index.cjs +2135 -0
  135. package/dist/strings/fr/index.cjs.map +1 -0
  136. package/dist/strings/fr/index.d.cts +17 -0
  137. package/dist/strings/fr/index.d.ts +17 -0
  138. package/dist/strings/fr/index.js +2130 -0
  139. package/dist/strings/fr/index.js.map +1 -0
  140. package/dist/strings/index.cjs +2384 -0
  141. package/dist/strings/index.cjs.map +1 -0
  142. package/dist/strings/index.d.cts +3 -0
  143. package/dist/strings/index.d.ts +3 -0
  144. package/dist/strings/index.js +2353 -0
  145. package/dist/strings/index.js.map +1 -0
  146. package/dist/testing/index.cjs +230 -0
  147. package/dist/testing/index.cjs.map +1 -0
  148. package/dist/testing/index.d.cts +246 -0
  149. package/dist/testing/index.d.ts +246 -0
  150. package/dist/testing/index.js +219 -0
  151. package/dist/testing/index.js.map +1 -0
  152. package/dist/time/index.cjs +28 -0
  153. package/dist/time/index.cjs.map +1 -0
  154. package/dist/time/index.d.cts +41 -0
  155. package/dist/time/index.d.ts +41 -0
  156. package/dist/time/index.js +23 -0
  157. package/dist/time/index.js.map +1 -0
  158. package/package.json +224 -4
  159. package/src/agent/engines/agentThreads.ts +1601 -0
  160. package/src/agent/engines/directorChat.ts +500 -0
  161. package/src/agent/index.ts +67 -0
  162. package/src/agent/rules/agentEditLock.ts +115 -0
  163. package/src/agent/rules/agentErrorCopy.ts +44 -0
  164. package/src/agent/rules/copilotOrganization.ts +36 -0
  165. package/src/agent/rules/playbook.gen.ts +444 -0
  166. package/src/agent/rules/router.ts +518 -0
  167. package/src/agent/rules/stateDelta.ts +29 -0
  168. package/src/agent/rules/studioRouter.ts +123 -0
  169. package/src/agent/rules/surfaces.gen.ts +633 -0
  170. package/src/agent/rules/threadsUrl.ts +48 -0
  171. package/src/agent/rules/transcriptObserver.ts +90 -0
  172. package/src/agent/stores/agentThreads.ts +451 -0
  173. package/src/bus/contracts/noData.ts +18 -0
  174. package/src/bus/contracts/shared.ts +172 -0
  175. package/src/bus/contracts/studioTools.ts +224 -0
  176. package/src/bus/rules/bus.ts +857 -0
  177. package/src/bus/rules/confirmation.ts +22 -0
  178. package/src/bus/rules/defineRegistry.ts +24 -0
  179. package/src/bus/rules/errors.ts +401 -0
  180. package/src/bus/rules/handlerErrors.ts +103 -0
  181. package/src/bus/rules/handlerRegistry.ts +627 -0
  182. package/src/bus/rules/inputSchema.ts +232 -0
  183. package/src/bus/rules/invalidInput.ts +441 -0
  184. package/src/bus/rules/lateBoundTools.ts +100 -0
  185. package/src/bus/rules/studioRegistry.ts +324 -0
  186. package/src/bus/rules/studioToolBus.ts +73 -0
  187. package/src/bus/rules/types.ts +804 -0
  188. package/src/chrome/contracts/alert.ts +42 -0
  189. package/src/chrome/contracts/itinerary.ts +26 -0
  190. package/src/chrome/contracts/map.ts +23 -0
  191. package/src/chrome/contracts/overlay.ts +46 -0
  192. package/src/chrome/contracts/panel.ts +29 -0
  193. package/src/chrome/contracts/question.ts +52 -0
  194. package/src/chrome/contracts/selection.ts +26 -0
  195. package/src/chrome/contracts/sidenav.ts +23 -0
  196. package/src/chrome/contracts/snapshot.ts +319 -0
  197. package/src/chrome/contracts/state.ts +22 -0
  198. package/src/chrome/contracts/tabs.ts +56 -0
  199. package/src/chrome/handlers/alert.ts +91 -0
  200. package/src/chrome/handlers/introspection.ts +180 -0
  201. package/src/chrome/handlers/panels.ts +42 -0
  202. package/src/chrome/handlers/question.ts +24 -0
  203. package/src/chrome/handlers/sidenav.ts +116 -0
  204. package/src/chrome/handlers/snapshot.ts +451 -0
  205. package/src/chrome/handlers/stateDelta.ts +125 -0
  206. package/src/chrome/handlers/tabs.ts +143 -0
  207. package/src/chrome/handlers/timestamp.ts +19 -0
  208. package/src/chrome/rules/agentSelectors.ts +210 -0
  209. package/src/chrome/rules/mapAlert.ts +13 -0
  210. package/src/chrome/rules/question.ts +25 -0
  211. package/src/chrome/rules/tabs.ts +13 -0
  212. package/src/chrome/stores/activeDraftSession.ts +134 -0
  213. package/src/chrome/stores/chrome.ts +527 -0
  214. package/src/chrome/stores/uiStore.ts +575 -0
  215. package/src/collab/contracts/collab.ts +261 -0
  216. package/src/collab/handlers/collab.ts +468 -0
  217. package/src/collab/rules/toolNames.ts +33 -0
  218. package/src/collab/stores/collab.ts +899 -0
  219. package/src/collections/contracts/collection.ts +182 -0
  220. package/src/collections/handlers/collectionAttach.ts +141 -0
  221. package/src/collections/handlers/collections.ts +499 -0
  222. package/src/collections/handlers/heldCollection.ts +42 -0
  223. package/src/collections/handlers/restCollections.ts +386 -0
  224. package/src/collections/rules/collections.ts +138 -0
  225. package/src/collections/rules/entityCollections.ts +53 -0
  226. package/src/collections/stores/collections.ts +133 -0
  227. package/src/data/contracts/data.ts +233 -0
  228. package/src/data/contracts/itinerary.ts +71 -0
  229. package/src/data/handlers/activityResolve.ts +76 -0
  230. package/src/data/handlers/data.ts +200 -0
  231. package/src/data/handlers/graphql.ts +26 -0
  232. package/src/data/handlers/mutationSink.ts +1577 -0
  233. package/src/data/handlers/profile.ts +83 -0
  234. package/src/data/handlers/writeThrough.ts +417 -0
  235. package/src/data/rules/cache.ts +181 -0
  236. package/src/data/rules/dataTypes.ts +40 -0
  237. package/src/data/rules/keys.ts +106 -0
  238. package/src/data/rules/persistence.ts +1058 -0
  239. package/src/data/rules/requestBody.ts +43 -0
  240. package/src/data/rules/restErrors.ts +354 -0
  241. package/src/data/rules/sessionSurface.ts +156 -0
  242. package/src/data/rules/toolResultData.ts +73 -0
  243. package/src/data/rules/uuid.ts +24 -0
  244. package/src/edit/contracts/edit.ts +37 -0
  245. package/src/edit/contracts/itinerary.ts +57 -0
  246. package/src/edit/handlers/draftCommit.ts +257 -0
  247. package/src/edit/handlers/editDiscard.ts +34 -0
  248. package/src/edit/handlers/editLock.ts +949 -0
  249. package/src/edit/handlers/editor.ts +203 -0
  250. package/src/edit/handlers/formUnsaved.ts +24 -0
  251. package/src/edit/rules/draftMetadata.ts +117 -0
  252. package/src/edit/rules/editKeyboard.ts +222 -0
  253. package/src/edit/rules/editShortcuts.ts +102 -0
  254. package/src/edit/rules/editTooltip.ts +174 -0
  255. package/src/edit/rules/editorTaken.ts +49 -0
  256. package/src/edit/rules/history.ts +26 -0
  257. package/src/edit/rules/unsavedWork.ts +60 -0
  258. package/src/edit/stores/editorReservation.ts +70 -0
  259. package/src/edit/stores/formsUnsaved.ts +54 -0
  260. package/src/embed/contracts/embed.ts +48 -0
  261. package/src/embed/engines/embedFraming.ts +1329 -0
  262. package/src/embed/engines/embedReady.ts +353 -0
  263. package/src/embed/engines/framingPageSession.ts +169 -0
  264. package/src/embed/handlers/embed.ts +130 -0
  265. package/src/embed/rules/allowedDomains.ts +71 -0
  266. package/src/embed/rules/bridgeMessages.ts +224 -0
  267. package/src/embed/rules/defaults.ts +173 -0
  268. package/src/embed/rules/displaySeed.ts +115 -0
  269. package/src/embed/rules/embedAllowlist.ts +146 -0
  270. package/src/embed/rules/embedConstraints.ts +215 -0
  271. package/src/embed/rules/embedElements.ts +277 -0
  272. package/src/embed/rules/embedSectionFields.ts +126 -0
  273. package/src/embed/rules/embedSecurity.ts +116 -0
  274. package/src/embed/rules/fieldDependencies.ts +89 -0
  275. package/src/embed/rules/fieldOptions.ts +138 -0
  276. package/src/embed/rules/layerOptions.ts +161 -0
  277. package/src/embed/rules/readyProtocol.ts +66 -0
  278. package/src/embed/rules/safetyRules.ts +215 -0
  279. package/src/embed/rules/snippet.ts +531 -0
  280. package/src/embed/rules/tableCode.ts +270 -0
  281. package/src/embed/stores/embed.ts +60 -0
  282. package/src/embed/stores/embedContent.ts +77 -0
  283. package/src/engines/index.ts +81 -0
  284. package/src/handlers/index.ts +66 -0
  285. package/src/index.ts +1065 -0
  286. package/src/itinerary/contracts/itinerary.ts +705 -0
  287. package/src/itinerary/engines/itineraryPace.ts +612 -0
  288. package/src/itinerary/engines/profileMarker.ts +238 -0
  289. package/src/itinerary/handlers/importStaging.ts +352 -0
  290. package/src/itinerary/handlers/itinerary.ts +572 -0
  291. package/src/itinerary/handlers/itineraryDuplicate.ts +177 -0
  292. package/src/itinerary/handlers/itineraryExport.ts +117 -0
  293. package/src/itinerary/handlers/itineraryImport.ts +783 -0
  294. package/src/itinerary/handlers/itineraryPublish.ts +118 -0
  295. package/src/itinerary/handlers/itinerarySelection.ts +354 -0
  296. package/src/itinerary/handlers/itinerarySuggest.ts +1186 -0
  297. package/src/itinerary/handlers/itineraryUnpublish.ts +101 -0
  298. package/src/itinerary/handlers/publicationScope.ts +118 -0
  299. package/src/itinerary/handlers/restItineraries.ts +752 -0
  300. package/src/itinerary/handlers/restItineraryExport.ts +70 -0
  301. package/src/itinerary/handlers/restItineraryImport.ts +311 -0
  302. package/src/itinerary/handlers/restItineraryPace.ts +87 -0
  303. package/src/itinerary/handlers/restItineraryRecord.ts +36 -0
  304. package/src/itinerary/handlers/suggestParams.ts +379 -0
  305. package/src/itinerary/handlers/suggestStaging.ts +363 -0
  306. package/src/itinerary/handlers/surfaceOpen.ts +389 -0
  307. package/src/itinerary/rules/activity.ts +139 -0
  308. package/src/itinerary/rules/analysis.ts +42 -0
  309. package/src/itinerary/rules/ceiling.ts +49 -0
  310. package/src/itinerary/rules/createFlow.ts +107 -0
  311. package/src/itinerary/rules/densify.ts +440 -0
  312. package/src/itinerary/rules/draftSurface.ts +219 -0
  313. package/src/itinerary/rules/editorView.ts +83 -0
  314. package/src/itinerary/rules/export.ts +159 -0
  315. package/src/itinerary/rules/friendlyName.ts +77 -0
  316. package/src/itinerary/rules/import.ts +1050 -0
  317. package/src/itinerary/rules/importFiles.ts +140 -0
  318. package/src/itinerary/rules/importTotals.ts +77 -0
  319. package/src/itinerary/rules/liveSegment.ts +712 -0
  320. package/src/itinerary/rules/lngLat.ts +17 -0
  321. package/src/itinerary/rules/mapSync.ts +100 -0
  322. package/src/itinerary/rules/previewRender.ts +416 -0
  323. package/src/itinerary/rules/profileReadout.ts +216 -0
  324. package/src/itinerary/rules/routing.ts +707 -0
  325. package/src/itinerary/rules/suggest.ts +522 -0
  326. package/src/itinerary/rules/suggestionPreview.ts +119 -0
  327. package/src/itinerary/rules/view.ts +61 -0
  328. package/src/itinerary/stores/importSession.ts +319 -0
  329. package/src/itinerary/stores/itinerary.ts +331 -0
  330. package/src/itinerary/stores/itineraryDuplicate.ts +76 -0
  331. package/src/itinerary/stores/sessionIdentity.ts +43 -0
  332. package/src/itinerary/stores/suggestSession.ts +418 -0
  333. package/src/layers/contracts/itinerary.ts +46 -0
  334. package/src/layers/contracts/overlay.ts +132 -0
  335. package/src/layers/handlers/enrichment.ts +36 -0
  336. package/src/layers/handlers/overlay.ts +406 -0
  337. package/src/layers/handlers/restLayers.ts +94 -0
  338. package/src/layers/handlers/tiles.ts +25 -0
  339. package/src/layers/rules/layers.ts +212 -0
  340. package/src/layers/rules/overlayInstant.ts +12 -0
  341. package/src/layers/rules/reachabilityIcon.ts +18 -0
  342. package/src/layers/rules/readout.ts +102 -0
  343. package/src/layers/stores/layers.ts +262 -0
  344. package/src/map/contracts/contextmenu.ts +33 -0
  345. package/src/map/contracts/geolocate.ts +37 -0
  346. package/src/map/contracts/map.ts +146 -0
  347. package/src/map/contracts/streetview.ts +53 -0
  348. package/src/map/contracts/terrain.ts +152 -0
  349. package/src/map/handlers/contextMenu.ts +135 -0
  350. package/src/map/handlers/geolocate.ts +52 -0
  351. package/src/map/handlers/map.ts +391 -0
  352. package/src/map/handlers/streetview.ts +94 -0
  353. package/src/map/handlers/terrain.ts +663 -0
  354. package/src/map/rules/baseTerrain.ts +75 -0
  355. package/src/map/rules/clickTargets.ts +464 -0
  356. package/src/map/rules/constraints.ts +32 -0
  357. package/src/map/rules/contextMenuReadout.ts +67 -0
  358. package/src/map/rules/coordinates.ts +71 -0
  359. package/src/map/rules/itineraryFit.ts +8 -0
  360. package/src/map/rules/mapEvents.ts +64 -0
  361. package/src/map/rules/mapProjection.ts +476 -0
  362. package/src/map/rules/terrainReading.ts +62 -0
  363. package/src/plugins/contracts/ids.ts +66 -0
  364. package/src/plugins/contracts/plugin.ts +202 -0
  365. package/src/plugins/contracts/slots.ts +137 -0
  366. package/src/plugins/engines/studioPlugin.ts +1365 -0
  367. package/src/plugins/index.ts +111 -0
  368. package/src/plugins/rules/contributions.ts +152 -0
  369. package/src/plugins/rules/errors.ts +60 -0
  370. package/src/plugins/rules/ids.ts +42 -0
  371. package/src/plugins/rules/validation.ts +249 -0
  372. package/src/rules/listeners.ts +57 -0
  373. package/src/rules/origin.ts +13 -0
  374. package/src/rules/storeWrite.ts +37 -0
  375. package/src/rules/types.ts +136 -0
  376. package/src/seams/index.ts +79 -0
  377. package/src/seams/rules/clock.ts +28 -0
  378. package/src/seams/rules/formatters.ts +211 -0
  379. package/src/seams/rules/ids.ts +102 -0
  380. package/src/seams/rules/links.ts +66 -0
  381. package/src/seams/rules/navigation.ts +222 -0
  382. package/src/seams/rules/notify.ts +49 -0
  383. package/src/seams/rules/persistenceDrawer.ts +220 -0
  384. package/src/seams/rules/saveFile.ts +101 -0
  385. package/src/seams/rules/seams.ts +156 -0
  386. package/src/seams/rules/storage.ts +116 -0
  387. package/src/search/contracts/overlay.ts +74 -0
  388. package/src/search/contracts/search.ts +197 -0
  389. package/src/search/handlers/pois.ts +57 -0
  390. package/src/search/handlers/search.ts +280 -0
  391. package/src/search/rules/params.ts +925 -0
  392. package/src/search/rules/poiGroups.ts +138 -0
  393. package/src/search/rules/searchFetch.ts +139 -0
  394. package/src/search/rules/timeWindow.ts +30 -0
  395. package/src/search/stores/search.ts +51 -0
  396. package/src/segments/contracts/itinerary.ts +433 -0
  397. package/src/segments/contracts/segment.ts +35 -0
  398. package/src/segments/engines/segmentDraft.ts +926 -0
  399. package/src/segments/handlers/chainGuards.ts +67 -0
  400. package/src/segments/handlers/directions.ts +44 -0
  401. package/src/segments/handlers/itineraryEcho.ts +45 -0
  402. package/src/segments/handlers/roadAccessDialog.ts +34 -0
  403. package/src/segments/handlers/segment.ts +111 -0
  404. package/src/segments/handlers/segmentEdit.ts +1341 -0
  405. package/src/segments/handlers/segmentGroups.ts +347 -0
  406. package/src/segments/handlers/segmentStructure.ts +1144 -0
  407. package/src/segments/rules/chain.ts +196 -0
  408. package/src/segments/rules/chainModel.ts +217 -0
  409. package/src/segments/rules/colors.ts +11 -0
  410. package/src/segments/rules/commit.ts +76 -0
  411. package/src/segments/rules/draft.ts +90 -0
  412. package/src/segments/rules/draftDisposition.ts +43 -0
  413. package/src/segments/rules/draftSegmentEdit.ts +129 -0
  414. package/src/segments/rules/engine.ts +222 -0
  415. package/src/segments/rules/groupSave.ts +234 -0
  416. package/src/segments/rules/hazardPrompt.ts +60 -0
  417. package/src/segments/rules/itineraryEcho.ts +40 -0
  418. package/src/segments/rules/liveSegmentProjection.ts +55 -0
  419. package/src/segments/rules/merge.ts +51 -0
  420. package/src/segments/rules/metrics.ts +456 -0
  421. package/src/segments/rules/naming.ts +168 -0
  422. package/src/segments/rules/segmentArming.ts +144 -0
  423. package/src/segments/rules/splitPick.ts +84 -0
  424. package/src/segments/rules/viaSimplify.ts +230 -0
  425. package/src/segments/stores/directions.ts +77 -0
  426. package/src/segments/stores/roadAccessDialog.ts +58 -0
  427. package/src/segments/stores/segmentEdit.ts +922 -0
  428. package/src/segments/stores/segmentGroupEdit.ts +84 -0
  429. package/src/segments/stores/segmentSplit.ts +77 -0
  430. package/src/share/contracts/share.ts +39 -0
  431. package/src/share/contracts/shareLink.ts +63 -0
  432. package/src/share/engines/shareLink.ts +1053 -0
  433. package/src/share/handlers/share.ts +47 -0
  434. package/src/share/handlers/shareLink.ts +231 -0
  435. package/src/share/handlers/shareScope.ts +54 -0
  436. package/src/share/rules/link.ts +89 -0
  437. package/src/share/rules/shareLink.ts +218 -0
  438. package/src/share/rules/targets.ts +92 -0
  439. package/src/share/rules/viewConfig.ts +95 -0
  440. package/src/share/stores/share.ts +58 -0
  441. package/src/strings/fr/index.ts +18 -0
  442. package/src/strings/fr/rules/fr.ts +2368 -0
  443. package/src/strings/index.ts +98 -0
  444. package/src/strings/rules/confirmCopy.ts +156 -0
  445. package/src/strings/rules/draftToolNames.ts +94 -0
  446. package/src/strings/rules/en.ts +2519 -0
  447. package/src/strings/rules/failureAlert.ts +115 -0
  448. package/src/strings/rules/formError.ts +400 -0
  449. package/src/strings/rules/maneuvers.ts +107 -0
  450. package/src/strings/rules/outputOptions.ts +126 -0
  451. package/src/strings/rules/publicationState.ts +100 -0
  452. package/src/strings/rules/routeHazardCopy.ts +62 -0
  453. package/src/strings/rules/searchLabels.ts +50 -0
  454. package/src/strings/rules/segmentChainVerbs.ts +62 -0
  455. package/src/strings/rules/studioCopy.ts +130 -0
  456. package/src/strings/rules/unitOptions.ts +119 -0
  457. package/src/testing/checkedBus.ts +226 -0
  458. package/src/testing/index.ts +30 -0
  459. package/src/testing/plugins.ts +106 -0
  460. package/src/testing/studio.ts +267 -0
  461. package/src/testing/urlSeam.ts +153 -0
  462. package/src/time/index.ts +12 -0
  463. package/src/time/rules/sun.ts +78 -0
  464. package/src/video/contracts/cameraSchemas.ts +266 -0
  465. package/src/video/contracts/profileSchemas.ts +37 -0
  466. package/src/video/contracts/video.ts +601 -0
  467. package/src/video/handlers/video.ts +1638 -0
  468. package/src/video/handlers/videoDirector.ts +114 -0
  469. package/src/video/rules/previewRefresh.ts +76 -0
  470. package/src/video/rules/profileSource.ts +51 -0
  471. package/src/video/rules/routeSpans.ts +79 -0
  472. package/src/video/rules/shotDefaults.ts +28 -0
  473. package/src/video/rules/stepOrder.ts +17 -0
  474. package/src/video/rules/videoSnapshot.ts +136 -0
  475. package/src/video/stores/directorThreads.ts +167 -0
  476. package/src/video/stores/videoExport.ts +290 -0
  477. package/src/viewer/contracts/preferences.ts +40 -0
  478. package/src/viewer/handlers/preferences.ts +91 -0
  479. package/src/viewer/rules/capabilities.ts +42 -0
  480. package/src/viewer/rules/config.ts +266 -0
  481. package/src/viewer/rules/context.ts +375 -0
  482. package/src/viewer/rules/ownership.ts +134 -0
  483. package/src/viewer/rules/platformViewer.ts +199 -0
  484. package/src/viewer/rules/scope.ts +197 -0
  485. package/src/viewer/rules/url.ts +145 -0
  486. package/src/viewer/rules/viewer.ts +307 -0
  487. package/src/viewer/rules/viewerSeam.ts +49 -0
  488. package/src/viewer/rules/viewerUnits.ts +34 -0
  489. package/src/waypoints/contracts/itinerary.ts +417 -0
  490. package/src/waypoints/handlers/poiWaypointStyle.ts +32 -0
  491. package/src/waypoints/handlers/waypointDetailsDialog.ts +38 -0
  492. package/src/waypoints/handlers/waypointEdit.ts +1073 -0
  493. package/src/waypoints/rules/amenities.ts +30 -0
  494. package/src/waypoints/rules/defaults.ts +31 -0
  495. package/src/waypoints/rules/details.ts +213 -0
  496. package/src/waypoints/rules/detailsDraft.ts +312 -0
  497. package/src/waypoints/rules/detailsPreview.ts +76 -0
  498. package/src/waypoints/rules/detailsSave.ts +356 -0
  499. package/src/waypoints/rules/draftDirty.ts +45 -0
  500. package/src/waypoints/rules/icons.ts +32 -0
  501. package/src/waypoints/rules/liveWaypoint.ts +63 -0
  502. package/src/waypoints/rules/naming.ts +185 -0
  503. package/src/waypoints/rules/sections.ts +77 -0
  504. package/src/waypoints/rules/waypointDraft.ts +62 -0
  505. package/src/waypoints/stores/waypointDetails.ts +62 -0
  506. package/src/waypoints/stores/waypointEdit.ts +566 -0
  507. package/src/zones/contracts/collection.ts +37 -0
  508. package/src/zones/contracts/zone.ts +528 -0
  509. package/src/zones/engines/zoneForm.ts +1773 -0
  510. package/src/zones/handlers/restZones.ts +287 -0
  511. package/src/zones/handlers/zonePublish.ts +206 -0
  512. package/src/zones/handlers/zoneUnpublish.ts +56 -0
  513. package/src/zones/handlers/zones.ts +2254 -0
  514. package/src/zones/rules/geometry.ts +946 -0
  515. package/src/zones/rules/zoneDefaults.ts +34 -0
  516. package/src/zones/rules/zoneDraft.ts +54 -0
  517. package/src/zones/rules/zoneForm.ts +563 -0
  518. package/src/zones/rules/zoneMetadata.ts +29 -0
  519. package/src/zones/rules/zoneSource.ts +87 -0
  520. package/src/zones/rules/zoneSourceRefusal.ts +104 -0
  521. package/src/zones/stores/zoneEdit.ts +998 -0
@@ -0,0 +1,1773 @@
1
+ import { MountayaElementsError } from "@mountaya/elements/errors";
2
+ import { localizedName, type MapLanguage } from "@mountaya/elements/i18n";
3
+
4
+ import type { StudioToolInputs, StudioToolOutputs } from "../../bus/contracts/studioTools.js";
5
+ import type { ToolFailure, ToolResultOf } from "../../bus/rules/types.js";
6
+ import type { UiStore, UiStoreApi } from "../../chrome/stores/uiStore.js";
7
+ import { notifyListeners } from "../../rules/listeners.js";
8
+ import type { CategoryActivities, Zone, ZoneSource } from "../../rules/types.js";
9
+ import { MAX_TIMER_MS } from "../../seams/rules/clock.js";
10
+ import type { StudioIds } from "../../seams/rules/ids.js";
11
+ import { activityForId } from "../../segments/rules/engine.js";
12
+ import type { StudioStrings } from "../../strings/rules/en.js";
13
+ import { canEditOwnedResource } from "../../viewer/rules/ownership.js";
14
+ import type { ZoneRangeType } from "../contracts/zone.js";
15
+ import {
16
+ DEFAULT_ZONE_CREATE_METHOD,
17
+ DEFAULT_ZONE_LEVEL,
18
+ DEFAULT_ZONE_MODE,
19
+ } from "../rules/zoneDefaults.js";
20
+ import {
21
+ activityIdForSlug,
22
+ firstRoutableActivityId,
23
+ isZoneGeometryDirty,
24
+ isZoneMetadataDirty,
25
+ isZoneSourceDirty,
26
+ isZoneWindowInvalid,
27
+ parametersOf,
28
+ type QueryParameters,
29
+ typedOver,
30
+ windowOpens,
31
+ ZONE_DEFAULT_DISTANCE_RANGE_METERS,
32
+ ZONE_DEFAULT_TIME_RANGE_SECONDS,
33
+ ZONE_PREVIEW_DEBOUNCE_MS,
34
+ type ZoneFormFields,
35
+ type ZoneSaveRequest,
36
+ zoneAutoName,
37
+ zoneDescriptionSchema,
38
+ zoneNameSchema,
39
+ zoneSaveRequest,
40
+ zoneSourceQuery,
41
+ } from "../rules/zoneForm.js";
42
+ import { zoneSourceRefused } from "../rules/zoneSourceRefusal.js";
43
+ import type {
44
+ ZoneCreateMethod,
45
+ ZoneEditLevel,
46
+ ZoneEditMode,
47
+ ZoneEditSession,
48
+ } from "../stores/zoneEdit.js";
49
+
50
+ /** The tools a zone form runs, by name. */
51
+ type ZoneFormTool =
52
+ | "studio.alert.show"
53
+ | "studio.zone.beginOriginPick"
54
+ | "studio.zone.create"
55
+ | "studio.zone.editBegin"
56
+ | "studio.zone.editCommit"
57
+ | "studio.zone.reachabilityPreview"
58
+ | "studio.zone.setCreateMethod"
59
+ | "studio.zone.setLevel"
60
+ | "studio.zone.update";
61
+
62
+ /**
63
+ * ZoneFormDispatch runs one of the tools a zone form runs, and resolves with the tool's result.
64
+ *
65
+ * The result holds that tool's own data, read from {@link StudioToolOutputs}: the form takes the
66
+ * collections a create could not file the zone into straight off the answer of
67
+ * `studio.zone.create`, with no parse of its own. So the dispatch a host hands over is one typed
68
+ * by the studio's outputs: a bus built with `StudioToolInputs` and `StudioToolOutputs`, or a
69
+ * binding's own dispatch that answers each verb's data.
70
+ *
71
+ * It never rejects, as a tool bus's dispatch never does: a refusal is a result whose `ok` is
72
+ * false. A host holding such a bus and a context writes it as
73
+ * `(name, input) => bus.dispatch(context, name, input)`.
74
+ */
75
+ export type ZoneFormDispatch = <TName extends ZoneFormTool>(
76
+ name: TName,
77
+ input: StudioToolInputs[TName],
78
+ ) => Promise<ToolResultOf<StudioToolOutputs, TName>>;
79
+
80
+ /**
81
+ * ZoneFormConfig is what a zone form reads from its host, all of it replaceable mid-life through
82
+ * {@link ZoneFormEngine.configure}.
83
+ */
84
+ export interface ZoneFormConfig {
85
+ /**
86
+ * The activity catalog. A reachability zone's activity is chosen from it, seeded from its first
87
+ * routable entry, and named from it. Empty while the host has not resolved one, in which case
88
+ * no activity is seeded.
89
+ *
90
+ * Compared by identity: a replaced catalog resolves a bound computed zone's stored activity
91
+ * again, and leaves an activity and a budget its reader moved.
92
+ */
93
+ readonly activities: readonly CategoryActivities[];
94
+ /**
95
+ * The organization a create is filed under when it inherits none from an open itinerary, or
96
+ * null to leave it personal until the reader picks one.
97
+ */
98
+ readonly defaultOrganizationId: string | null;
99
+ /** Runs the form's tools. Read when a tool is run, so the one configured last is the one used. */
100
+ readonly dispatch: ZoneFormDispatch;
101
+ /**
102
+ * The collections the open itinerary belongs to, by id, which a create begun inside that
103
+ * itinerary is filed into. Read only while such a create is open; empty otherwise, and while
104
+ * the host is still reading them.
105
+ */
106
+ readonly inheritedCollectionIds: readonly string[];
107
+ /** The reader's language, which a derived name's activity is named and lower-cased in. */
108
+ readonly language: MapLanguage;
109
+ /** The words a derived name and the collection warning are written in. */
110
+ readonly strings: Pick<StudioStrings, "zoneForm">;
111
+ /** The reader's user id, or null for a reader with none. A zone's creator may edit it. */
112
+ readonly userId: string | null;
113
+ /** The organizations the reader may write to. A member of a zone's organization may edit it. */
114
+ readonly writableOrganizationIds: ReadonlySet<string>;
115
+ }
116
+
117
+ /**
118
+ * ZoneFormEngineOptions is the {@link ZoneFormConfig} an engine starts with, plus the settings
119
+ * that are fixed for its life.
120
+ */
121
+ export interface ZoneFormEngineOptions extends ZoneFormConfig {
122
+ /**
123
+ * How long a reachability zone's parameters hold still before their preview is asked for, in
124
+ * milliseconds. Zero asks at once. A whole or fractional number from 0 to 2,147,483,647, the
125
+ * longest delay a timer honours.
126
+ *
127
+ * @default 600
128
+ */
129
+ readonly debounceMs?: number | undefined;
130
+ /** Where the id of a zone about to be drawn comes from. */
131
+ readonly ids: StudioIds;
132
+ /**
133
+ * The store the form's zone lives in: the bound zone, the draw session, and the create's method
134
+ * and origin. Fixed for the engine's life, because the fields are seeded from it: another store
135
+ * is another form, and takes another engine.
136
+ */
137
+ readonly ui: UiStoreApi;
138
+ }
139
+
140
+ /**
141
+ * ZoneFormSnapshot is what a {@link ZoneFormEngine} answers: the form's fields, and what the form
142
+ * has decided about them.
143
+ *
144
+ * It names the zone it answers for, so a reader holding one knows which zone the fields describe
145
+ * and never takes one zone's fields for another's.
146
+ *
147
+ * It does not say who may edit. `canEditOwnedResource` answers that from the zone and the reader,
148
+ * which a surface already holds, and a peer's lock or the co-pilot's turn are a surface's to read.
149
+ */
150
+ export interface ZoneFormSnapshot {
151
+ /** Whether a draw or a reshape is armed on the map. */
152
+ readonly armed: boolean;
153
+ /** Whether the description is one the tools accept. */
154
+ readonly descriptionValid: boolean;
155
+ /**
156
+ * Why the latest {@link ZoneFormEngine.beginDraw} was refused, or null. A draw is refused when
157
+ * another edit is armed, when a collaborator holds the zone, or when the reader may not edit.
158
+ * It answers for the create the snapshot describes: it is cleared by the next `beginDraw`, once
159
+ * a draw or a reshape is armed, whoever arms it, and on every change that clears `saveFailure`
160
+ * for another form (another zone bound, the zone unbinding, another create, a create's other
161
+ * method, a create inheriting from elsewhere). A refusal that lands after one of those is
162
+ * dropped. Word it for a reader with `mapToolError`.
163
+ */
164
+ readonly drawFailure: ToolFailure | null;
165
+ /** The form's fields. Stable by reference until one of them changes. */
166
+ readonly fields: ZoneFormFields;
167
+ /**
168
+ * Whether the create takes its organization, activity and collections from the itinerary it was
169
+ * begun inside. The three follow that itinerary while it does, and an `edit` of one does not
170
+ * hold, so a surface names them and offers no picker for them.
171
+ */
172
+ readonly inherits: boolean;
173
+ /**
174
+ * How the zone is authored: a create reads the method it was opened with, and a saved zone is
175
+ * a reachability zone when it carries a query.
176
+ */
177
+ readonly method: ZoneCreateMethod;
178
+ /** Whether the name is one the tools accept. */
179
+ readonly nameValid: boolean;
180
+ /**
181
+ * Why the latest {@link ZoneFormEngine.beginOriginPick} was refused, or null. A pick is refused
182
+ * while an edit is armed, and when the reader may not edit. It answers for the form the snapshot
183
+ * describes: it is cleared by the next `beginOriginPick`, once an origin is placed or moved,
184
+ * whoever places it, and on every change that clears `saveFailure` for another form. A refusal
185
+ * that lands after one of those, or after a later pick was asked, is dropped. Word it for a
186
+ * reader with `mapToolError`.
187
+ */
188
+ readonly pickFailure: ToolFailure | null;
189
+ /**
190
+ * Why the latest reachability preview failed, or null. It answers for the zone the snapshot
191
+ * names and the query the fields state: it stands until a later preview answers, and it is
192
+ * dropped when the form's subject changes (another zone is bound or the zone unbinds, a create
193
+ * switches method, a create starts or stops inheriting from an itinerary or inherits from
194
+ * another one, or the create surface is entered again) and when the fields state no query at
195
+ * all (a drawn zone, no origin, no activity). A failure that lands after a change of subject
196
+ * is dropped too, whatever query the form then states. A reachability create is not ready to
197
+ * save while it stands. Word it for a reader with its `detail`, or with `mapToolError`.
198
+ */
199
+ readonly previewFailure: ToolFailure | null;
200
+ /**
201
+ * Why the latest save was refused, or null. It answers for the zone the snapshot names: it is
202
+ * cleared by the next save, by an edit of the name, the description or the window, and when
203
+ * the form's subject changes: another zone is bound or the zone unbinds, a create switches
204
+ * method, whoever switches it, a create starts or stops inheriting from an itinerary or
205
+ * inherits from another one, or the create surface is entered again. A refusal that lands
206
+ * after a change of subject is dropped. Word it for a reader with `mapToolError`.
207
+ *
208
+ * A refusal of the query a reachability form states is no failed save: it is `sourceFailure`.
209
+ */
210
+ readonly saveFailure: ToolFailure | null;
211
+ /**
212
+ * Whether there is anything to persist at all: a reachability create, an armed draw or reshape,
213
+ * or a saved zone whose metadata or parameters moved. A surface shows no Save without it.
214
+ */
215
+ readonly saveOffered: boolean;
216
+ /**
217
+ * Whether {@link ZoneFormEngine.save} is worth calling now: no save is in flight, the name, the
218
+ * description and the window are valid, and something is unsaved. A reachability create is
219
+ * ready once its query resolves and its preview has not failed.
220
+ */
221
+ readonly saveReady: boolean;
222
+ /**
223
+ * Whether a save of the form the snapshot describes is in flight. A save sent for another zone,
224
+ * or for a create the form has left, is not this form's: it reads false here and holds back no
225
+ * save of this one.
226
+ */
227
+ readonly saving: boolean;
228
+ /**
229
+ * Why the latest save's reachability query was refused, or null: the API computed an area
230
+ * from the query and cannot store it as a zone, or refuses the query itself. A surface shows
231
+ * it where the query's fields are, since changing one of them is what answers it. Word it for
232
+ * a reader with `mapToolError`, which reads the API's own sentence.
233
+ *
234
+ * It answers for the query that was sent: it is read only while the fields state that query,
235
+ * so it leaves when the origin, the activity, the measure, the budget or the pace moves. The
236
+ * next save clears it, and so does every change of subject that clears `saveFailure`. A form
237
+ * that states no query, a drawn zone's, keeps such a refusal as its `saveFailure`.
238
+ */
239
+ readonly sourceFailure: ToolFailure | null;
240
+ /** Whether the availability window is one the tools accept: no start after its end. */
241
+ readonly windowValid: boolean;
242
+ /** The saved zone the fields answer for, or null while the form creates one. */
243
+ readonly zoneId: string | null;
244
+ }
245
+
246
+ /**
247
+ * queryKeyOf writes a reachability query as the text two readings of it are compared by, or
248
+ * null for no query. A refusal of a save's source is held under it, so it is read only while the
249
+ * fields state the query that was refused.
250
+ */
251
+ const queryKeyOf = (source: ZoneSource | null): string | null =>
252
+ source === null ? null : JSON.stringify(source);
253
+
254
+ /** One {@link ZoneFormEngine.subscribe} call, held by identity so each one leaves once. */
255
+ interface Subscription {
256
+ readonly listener: () => void;
257
+ }
258
+
259
+ /** Draft is the engine's own copy of every field, before the store's session is read over it. */
260
+ interface Draft {
261
+ activityId: string | null;
262
+ collectionIds: readonly string[];
263
+ /** The severity the form holds. An armed session's severity is shown over it. */
264
+ createLevel: ZoneEditLevel;
265
+ /** The shape the form holds. An armed session's shape, and a saved zone's, are shown over it. */
266
+ createMode: ZoneEditMode | null;
267
+ description: string;
268
+ endAt: Date | null;
269
+ name: string;
270
+ organizationId: string | null;
271
+ range: number;
272
+ rangeType: ZoneRangeType;
273
+ speedKmh: number | null;
274
+ startAt: Date | null;
275
+ windowOpen: boolean;
276
+ }
277
+
278
+ /** StoreFacts is what the form reads from the UI store, at one moment. */
279
+ interface StoreFacts {
280
+ /** The method a create was opened with, or null for one opened with none. */
281
+ readonly createMethod: ZoneCreateMethod | null;
282
+ /** Which create the store stands on: it moves with every entry into the create surface. */
283
+ readonly createSerial: number;
284
+ /** The itinerary a create inherits from, or null when it inherits nothing. */
285
+ readonly inherited: {
286
+ readonly activityId: string;
287
+ readonly itineraryId: string;
288
+ readonly organizationId: string | null;
289
+ } | null;
290
+ /** The point a reachability zone is measured from, or null. */
291
+ readonly origin: readonly [number, number] | null;
292
+ /** The open draw or reshape session, or null. */
293
+ readonly session: ZoneEditSession | null;
294
+ /** The saved zone the form is bound to, or null. */
295
+ readonly zone: Zone | null;
296
+ }
297
+
298
+ /**
299
+ * View is one reading of the form: the snapshot it publishes, the preview it is worth, and
300
+ * whether it holds something unsaved.
301
+ */
302
+ interface View {
303
+ /** The preview's input, or null when there is no query to preview. */
304
+ readonly preview: StudioToolInputs["studio.zone.reachabilityPreview"] | null;
305
+ /** What identifies `preview`: two readings with one key ask one question. */
306
+ readonly previewKey: string | null;
307
+ readonly snapshot: ZoneFormSnapshot;
308
+ /**
309
+ * Whether leaving would lose something the reader did, the store's `zoneFormUnsaved`: what Save
310
+ * would persist, except for a computed create the reader has not changed since it opened.
311
+ */
312
+ readonly changed: boolean;
313
+ }
314
+
315
+ /** The facts of a store nobody has read yet: a drawn create with nothing armed. */
316
+ const noFacts: StoreFacts = {
317
+ createMethod: null,
318
+ createSerial: 0,
319
+ inherited: null,
320
+ origin: null,
321
+ session: null,
322
+ zone: null,
323
+ };
324
+
325
+ /** factsOf reads what the form needs from one state of the UI store. */
326
+ const factsOf = (state: UiStore): StoreFacts => {
327
+ const zone = state.activeZone;
328
+ const itinerary = state.activeItinerary;
329
+
330
+ return {
331
+ createMethod: state.zoneCreateMethod,
332
+ createSerial: state.zoneCreateSerial,
333
+ // The flag and the itinerary are separate slots: a create inherits only while the itinerary
334
+ // it was begun inside is still open, and only a create inherits at all.
335
+ inherited:
336
+ zone === null && state.zoneCreateInheritsItinerary && itinerary !== null
337
+ ? {
338
+ activityId: itinerary.activity_id,
339
+ itineraryId: itinerary.id,
340
+ organizationId: itinerary.organization_id ?? null,
341
+ }
342
+ : null,
343
+ origin: state.zoneCreateOrigin,
344
+ session: state.zoneEditSession,
345
+ zone,
346
+ };
347
+ };
348
+
349
+ /** sameIds reports whether two id lists hold the same ids in the same order. */
350
+ const sameIds = (a: readonly string[], b: readonly string[]): boolean =>
351
+ a.length === b.length && a.every((id, index) => id === b[index]);
352
+
353
+ /** sameMembers reports whether two objects of one shape hold identical members. */
354
+ const sameMembers = <T extends object>(a: T, b: T): boolean => {
355
+ // Object.keys answers `string[]` for any object. The keys of `a` are the members T names: both
356
+ // arguments are records this module builds, with no member beside them.
357
+ const keys = Object.keys(a) as (keyof T)[];
358
+
359
+ return keys.length === Object.keys(b).length && keys.every((key) => Object.is(a[key], b[key]));
360
+ };
361
+
362
+ /**
363
+ * readsSame reports whether two states of the UI store hold the same slots a form reads, each by
364
+ * identity. The store tells its subscribers of every write, a hover and a selection included,
365
+ * and a write that moved none of these changes nothing a form shows.
366
+ */
367
+ const readsSame = (a: UiStore, b: UiStore): boolean =>
368
+ a.activeZone === b.activeZone &&
369
+ a.activeItinerary === b.activeItinerary &&
370
+ a.zoneCreateInheritsItinerary === b.zoneCreateInheritsItinerary &&
371
+ a.zoneCreateMethod === b.zoneCreateMethod &&
372
+ a.zoneCreateOrigin === b.zoneCreateOrigin &&
373
+ a.zoneCreateSerial === b.zoneCreateSerial &&
374
+ a.zoneEditSession === b.zoneEditSession;
375
+
376
+ /**
377
+ * debounceFrom reads the debounce an engine is constructed with, refusing a value no timer can
378
+ * keep.
379
+ *
380
+ * @throws {MountayaElementsError} When `debounceMs` is not a finite number from 0 to
381
+ * {@link MAX_TIMER_MS}. A `NaN` or a negative delay fires at once and an `Infinity` or an
382
+ * oversized one fires at once too, so each would be a debounce that debounces nothing while
383
+ * reading as a setting.
384
+ */
385
+ const debounceFrom = (debounceMs: number | undefined): number => {
386
+ if (debounceMs === undefined) {
387
+ return ZONE_PREVIEW_DEBOUNCE_MS;
388
+ }
389
+
390
+ if (!Number.isFinite(debounceMs) || debounceMs < 0 || debounceMs > MAX_TIMER_MS) {
391
+ throw new MountayaElementsError(
392
+ `ZoneFormEngine: debounceMs is ${String(debounceMs)}; pass a number of milliseconds ` +
393
+ `from 0 to ${MAX_TIMER_MS}, or omit it for ${ZONE_PREVIEW_DEBOUNCE_MS}.`,
394
+ );
395
+ }
396
+
397
+ return debounceMs;
398
+ };
399
+
400
+ /**
401
+ * ZoneFormEngine is the machine behind a zone form: it holds the form's fields, seeds them from
402
+ * the zone the UI store binds, keeps a create's name following its parameters until the reader
403
+ * types one, asks for a reachability zone's preview once its parameters hold still, and saves
404
+ * through the one tool the form's state calls for.
405
+ *
406
+ * What it does, in the order a form meets it:
407
+ *
408
+ * - **Seeding.** A saved zone seeds what it says: its name, description, severity and window,
409
+ * and, for a computed zone, the activity, measure, budget and pace of the query it is stored
410
+ * with. The same zone written again, by this form's save or a collaborator's, replaces only
411
+ * what the reader has not moved: a field typed and not saved stays as typed, the window as one
412
+ * answer and the query's parameters as one. A catalog that lands or is replaced under a
413
+ * computed zone resolves the stored activity again, whatever the reader did to the budget
414
+ * meanwhile, and leaves an activity the reader picked. A create is seeded per create: when the
415
+ * zone unbinds, and on every entry into the create surface, every field returns to a create's
416
+ * defaults, and when a create starts or stops inheriting, or the itinerary it inherits from is
417
+ * replaced by another, its organization, activity, collections, shape and reachability
418
+ * parameters do. A create begun inside an itinerary follows that itinerary's organization,
419
+ * activity and collections for as long as it is open, and one inside a personal itinerary
420
+ * stays personal. Any other create is filed under `defaultOrganizationId` and the first
421
+ * routable activity until its reader chooses, and a reader who chooses no organization has
422
+ * chosen: the create stays personal.
423
+ * - **The name.** While a create's name is nobody's, it follows {@link zoneAutoName}: a
424
+ * proposal's name, or a phrase written from the reachability parameters. The first
425
+ * `edit({ name })` makes it the reader's and it follows nothing after. A saved zone's name is
426
+ * never derived.
427
+ * - **The preview.** A reachability zone's query is previewed on the map through
428
+ * `studio.zone.reachabilityPreview`, `debounceMs` after its activity, origin, measure, budget,
429
+ * pace or severity last changed, so a typed budget costs one request. An answer for parameters
430
+ * that have since moved is ignored. A failure is the snapshot's `previewFailure` until the next
431
+ * answer, and never past the zone or the query it was about.
432
+ * - **Unsaved changes.** The snapshot says whether Save is offered and whether it is ready, from
433
+ * {@link isZoneMetadataDirty}, the stored query, the drawn shape and the bounds the tools hold a
434
+ * name, a description and a window to. Whether anything is unsaved at all is written on the
435
+ * store's `zoneFormUnsaved` while the engine runs, and taken back as it parks, so
436
+ * `studio.zone.publish` refuses to freeze a zone whose form holds what its reader has not
437
+ * saved.
438
+ * - **Saving.** {@link ZoneFormEngine.save} runs the request {@link zoneSaveRequest} routes, one
439
+ * at a time for each zone, and keeps a refusal as the snapshot's `saveFailure` for as long as
440
+ * the form answers for the zone the save was sent for. A refusal of the reachability query the
441
+ * fields state is kept apart, as the snapshot's `sourceFailure`, for as long as they state it.
442
+ * - **Listeners.** Every listener is told of every change. One that throws stops neither the
443
+ * engine nor the listeners after it: its fault is raised apart, as an uncaught error, and
444
+ * never through the command that caused the change.
445
+ *
446
+ * Every mutation goes through `dispatch`, so a person filling the form and an agent calling the
447
+ * same tools drive one surface. The slots that hold what its reader typed, which no tool takes,
448
+ * are the exception, and the engine writes them itself: the severity they pick for a create
449
+ * (`zoneCreatePickedLevel`), which a proposal's step records, the name of a draft a proposal
450
+ * named, which a name they type clears so that theirs is shown, and whether the form holds
451
+ * anything unsaved (`zoneFormUnsaved`).
452
+ *
453
+ * Time follows the engines' rule: the debounce keeps the rate a preview request is worth making
454
+ * at, which is no duration the product chose, so it runs on the runtime's timer (`setTimeout`)
455
+ * with its length as the `debounceMs` option, and the engine takes no `Clock`. A host that froze
456
+ * its clock would otherwise freeze every preview with it.
457
+ *
458
+ * The lifecycle is the listeners. Constructing one reads no store, arms no timer and runs no
459
+ * tool; the first subscriber starts watching the store and asks for the preview; the last
460
+ * unsubscribe parks: it stops watching, drops the pending preview and ignores the answer of one
461
+ * in flight. A parked engine keeps its fields and still answers for the store's current zone when
462
+ * read, by seeding on that read, so the render before a subscription shows the bound zone.
463
+ * React's StrictMode mounts, unmounts and mounts again, which parks and resumes within the
464
+ * debounce and asks once. {@link ZoneFormEngine.dispose} is the latch, for an owner that is not a
465
+ * component.
466
+ *
467
+ * A command (`edit`, `setMethod`, `beginOriginPick`, `beginDraw`, `save`) sent to an engine
468
+ * nobody subscribes to does nothing: a save run with nobody watching would show its refusal to
469
+ * no one, and an edit nobody sees is one nobody made.
470
+ *
471
+ * @example
472
+ * ```ts
473
+ * declare const activities: CategoryActivities[];
474
+ * declare const render: (snapshot: ZoneFormSnapshot) => void;
475
+ *
476
+ * const form = new ZoneFormEngine({
477
+ * activities,
478
+ * defaultOrganizationId: "org-1",
479
+ * dispatch: (name, input) => bus.dispatch(ctx, name, input),
480
+ * ids: systemStudioIds,
481
+ * inheritedCollectionIds: [],
482
+ * language: "en",
483
+ * strings: studioStrings.en,
484
+ * ui: ctx.ui,
485
+ * userId: "user-1",
486
+ * writableOrganizationIds: new Set(["org-1"]),
487
+ * });
488
+ * const release = form.subscribe(() => render(form.getSnapshot()));
489
+ *
490
+ * form.edit({ name: "North couloir" });
491
+ * await form.save();
492
+ * release();
493
+ * ```
494
+ */
495
+ export class ZoneFormEngine {
496
+ private config: ZoneFormConfig;
497
+ private readonly debounceMs: number;
498
+ private readonly ids: StudioIds;
499
+ private readonly ui: UiStoreApi;
500
+
501
+ private readonly draft: Draft = {
502
+ activityId: null,
503
+ collectionIds: [],
504
+ createLevel: DEFAULT_ZONE_LEVEL,
505
+ createMode: DEFAULT_ZONE_MODE,
506
+ description: "",
507
+ endAt: null,
508
+ name: "",
509
+ organizationId: null,
510
+ range: ZONE_DEFAULT_DISTANCE_RANGE_METERS,
511
+ rangeType: "distance",
512
+ speedKmh: null,
513
+ startAt: null,
514
+ windowOpen: false,
515
+ };
516
+ /** Whether the name is the reader's own, which stops it following anything. */
517
+ private nameTouched = false;
518
+ /** Whether the organization is the reader's own choice, null included, which no default fills. */
519
+ private organizationChosen = false;
520
+ /** The subjects a save is in flight for. A subject saves once at a time, and each on its own. */
521
+ private readonly saving = new Set<string>();
522
+ /** Whether a draw has been asked for and not answered yet. */
523
+ private drawing = false;
524
+ private drawFailure: ToolFailure | null = null;
525
+ private pickFailure: ToolFailure | null = null;
526
+ /** Counts the origin picks asked for: the refusal of an earlier one is dropped. */
527
+ private pickSerial = 0;
528
+ /** The origin the last seed read, which a pick that lands moves; undefined until the first. */
529
+ private origin: readonly [number, number] | null | undefined = undefined;
530
+ private saveFailure: ToolFailure | null = null;
531
+ /**
532
+ * The latest save's refusal of its reachability query, with the query it was sent with, as
533
+ * {@link queryKeyOf} writes it; null when the latest save met none.
534
+ */
535
+ private sourceRefusal: { readonly failure: ToolFailure; readonly query: string } | null = null;
536
+ private previewFailure: ToolFailure | null = null;
537
+ /** Whether the store's `zoneFormUnsaved` holds this engine's true, written by it. */
538
+ private unsavedWritten = false;
539
+ /**
540
+ * Whether the reader changed anything since the subject opened: typed a field, switched the
541
+ * method or picked an origin. A computed create opens saveable on what it was opened with, and
542
+ * leaving it untouched loses nothing the reader did, so it is unsaved only once this holds.
543
+ */
544
+ private touched = false;
545
+
546
+ /** The zone the metadata was seeded from; undefined until the first seed. */
547
+ private bound: Zone | null | undefined = undefined;
548
+ /**
549
+ * What the failures and a save in flight answer for: the bound zone, or a create, by its
550
+ * serial, the method it is authored by and the itinerary it inherits from. Null until the
551
+ * first seed.
552
+ */
553
+ private subject: string | null = null;
554
+ /**
555
+ * Counts the subjects a save or a draw can answer for: a refusal sent under an earlier one is
556
+ * dropped.
557
+ */
558
+ private subjectEpoch = 0;
559
+ /**
560
+ * The create the fields were last seeded for: its serial and the id of the itinerary it
561
+ * inherits from, and undefined while a zone is bound and before the first seed.
562
+ */
563
+ private create: string | undefined = undefined;
564
+ /** The serial of the create the fields were last seeded for, while the last seed was a create. */
565
+ private createSerial: number | undefined = undefined;
566
+ /** The zone and the catalog the reachability parameters were last seeded from. */
567
+ private sourceSeed: {
568
+ readonly activities: readonly CategoryActivities[];
569
+ readonly zone: Zone | null;
570
+ } | null = null;
571
+ /** The store state and the configuration the snapshot was last settled against. */
572
+ private settled: { readonly config: ZoneFormConfig; readonly state: UiStore } | null = null;
573
+ /**
574
+ * The name and the description last judged, with the verdicts, so a pass that moved neither
575
+ * parses nothing.
576
+ */
577
+ private judged: {
578
+ readonly description: string;
579
+ readonly descriptionValid: boolean;
580
+ readonly name: string;
581
+ readonly nameValid: boolean;
582
+ } | null = null;
583
+
584
+ private snapshot: ZoneFormSnapshot;
585
+ private readonly subscriptions = new Set<Subscription>();
586
+ /** Ends the watch on the store, while running. */
587
+ private unwatch: (() => void) | null = null;
588
+
589
+ /** The key of the preview asked for or waited on; undefined when none has been considered. */
590
+ private previewKey: string | null | undefined = undefined;
591
+ /** The preview the pending debounce asks for. */
592
+ private previewInput: StudioToolInputs["studio.zone.reachabilityPreview"] | null = null;
593
+ /**
594
+ * Counts the questions a preview can answer, and the subjects it can answer for: an answer
595
+ * from an earlier one is ignored.
596
+ */
597
+ private previewEpoch = 0;
598
+ private timer: ReturnType<typeof setTimeout> | null = null;
599
+
600
+ /** Whether a reconcile is running, so one started inside it runs after it. */
601
+ private reconciling = false;
602
+ /** Whether something changed during the running reconcile, which then runs again. */
603
+ private stale = false;
604
+
605
+ /**
606
+ * Whether nobody is watching. A parked engine watches no store, asks for no preview and answers
607
+ * no command.
608
+ */
609
+ private parked = true;
610
+ private disposed = false;
611
+
612
+ /**
613
+ * Constructing one holds the options and does nothing else: no store is read, no timer armed
614
+ * and no tool run. A React binding constructs during a render React is free to throw away, and
615
+ * a constructor with a side effect would leave the discarded copy acting.
616
+ *
617
+ * @throws {MountayaElementsError} When `debounceMs` is not a finite number from 0 to
618
+ * 2,147,483,647.
619
+ */
620
+ constructor(options: ZoneFormEngineOptions) {
621
+ const { debounceMs, ids, ui, ...config } = options;
622
+ this.debounceMs = debounceFrom(debounceMs);
623
+ this.ids = ids;
624
+ this.ui = ui;
625
+ this.config = config;
626
+ this.snapshot = this.view(noFacts).snapshot;
627
+ }
628
+
629
+ /**
630
+ * getSnapshot returns the current answer, by reference and stable between changes.
631
+ *
632
+ * A parked engine settles it on the read: it reads the store and seeds the fields for the zone
633
+ * bound now, without watching the store, arming a timer or running a tool. So a surface's first
634
+ * render, and a server's only one, show the bound zone.
635
+ */
636
+ getSnapshot(): ZoneFormSnapshot {
637
+ this.settle();
638
+
639
+ return this.snapshot;
640
+ }
641
+
642
+ /**
643
+ * subscribe registers a listener for every change of the snapshot, and returns its own
644
+ * unsubscribe, which is idempotent.
645
+ *
646
+ * The first listener starts the engine and the last one leaving parks it, which is the whole
647
+ * lifecycle a component can express correctly: React tears an effect down and sets it up again
648
+ * with the same object under StrictMode, so a latch here would leave a live surface bound to a
649
+ * dead engine. Each call is its own subscription, so two owners subscribing one shared function
650
+ * each hold the engine until they release it.
651
+ */
652
+ subscribe(listener: () => void): () => void {
653
+ if (this.disposed) {
654
+ return () => {};
655
+ }
656
+
657
+ const subscription: Subscription = { listener };
658
+ this.subscriptions.add(subscription);
659
+
660
+ if (this.parked) {
661
+ this.parked = false;
662
+ this.unwatch = this.ui.subscribe((state) => this.watch(state));
663
+ this.reconcile();
664
+ }
665
+
666
+ return () => {
667
+ if (!this.subscriptions.delete(subscription) || this.subscriptions.size > 0) {
668
+ return;
669
+ }
670
+
671
+ if (!this.parked) {
672
+ this.park();
673
+ }
674
+ };
675
+ }
676
+
677
+ /**
678
+ * configure replaces the configuration, and settles the form again only when a member changed.
679
+ *
680
+ * A binding calls it on every render, so it compares every member by identity and does nothing
681
+ * when all are the ones it holds. A changed one seeds what waited on it: a catalog that
682
+ * arrives seeds the activity, collections that arrive are followed, and a name still following
683
+ * its parameters is written again in the new language. A parked engine keeps the configuration
684
+ * for its next read.
685
+ */
686
+ configure(config: ZoneFormConfig): void {
687
+ if (this.disposed || sameMembers(this.config, config)) {
688
+ return;
689
+ }
690
+
691
+ this.config = config;
692
+ if (!this.parked) {
693
+ this.reconcile();
694
+ }
695
+ }
696
+
697
+ /**
698
+ * dispose parks the engine and drops every listener, for good.
699
+ *
700
+ * Idempotent, and every call after it is a no-op rather than an error: an owner torn down
701
+ * mid-save should not have to guard the calls it already queued. A save in flight still reaches
702
+ * the tool it was sent to; its answer changes nothing here.
703
+ */
704
+ dispose(): void {
705
+ if (this.disposed) {
706
+ return;
707
+ }
708
+
709
+ this.disposed = true;
710
+ if (!this.parked) {
711
+ this.park();
712
+ }
713
+ this.subscriptions.clear();
714
+ }
715
+
716
+ /**
717
+ * edit writes the given fields, and applies the rule each one carries:
718
+ *
719
+ * - `name` makes the name the reader's own, so it stops following the parameters. On a create
720
+ * whose draft a proposal named it also clears that name from the draft, so the one typed is
721
+ * shown.
722
+ * - `name`, `description`, `startAt` and `endAt` clear the previous save's failure.
723
+ * - `windowOpen: false` clears both bounds, so a hidden window never persists a constraint its
724
+ * reader cannot see.
725
+ * - `rangeType` resets `range` to that measure's default and never reinterprets the number,
726
+ * and a switch to `"distance"` drops the pace, which a distance does not depend on.
727
+ * - `speedKmh` holds beside a time budget only: on a distance budget it is dropped, so a later
728
+ * switch to `"time"` starts from the activity's own pace.
729
+ * - `organizationId` makes the organization the reader's own choice, `null` included: a create
730
+ * then stays personal beside a `defaultOrganizationId`. On a create whose draft a proposal
731
+ * filed, or whose draw was armed under another, it is also written on the draft, so the one
732
+ * picked is shown and saved.
733
+ * - `level`, while a draw is armed, also runs `studio.zone.setLevel`, which recolours the draft.
734
+ * A refusal leaves the draft as it was, and the form goes back to the severity it held. On a
735
+ * create it is also written on the store (`zoneCreatePickedLevel`), which the step of a
736
+ * proposal that joins the create records, so an undo of the proposal shows it again.
737
+ *
738
+ * `rangeType` and `windowOpen` are applied before the fields they reset, so an edit naming both
739
+ * keeps the value it names. `mode` is the shape a draw is armed with; once armed, and for a
740
+ * saved zone, the snapshot shows the session's or the zone's own. While the snapshot's
741
+ * `inherits` is true, `organizationId`, `activityId` and `collectionIds` follow the itinerary
742
+ * and an edit of one does not hold.
743
+ *
744
+ * A call while parked, or after {@link ZoneFormEngine.dispose}, does nothing.
745
+ */
746
+ edit(fields: Partial<ZoneFormFields>): void {
747
+ if (this.parked || this.disposed) {
748
+ return;
749
+ }
750
+
751
+ this.touched = true;
752
+
753
+ const { draft } = this;
754
+
755
+ if (fields.rangeType !== undefined) {
756
+ draft.rangeType = fields.rangeType;
757
+ draft.range =
758
+ fields.rangeType === "time"
759
+ ? ZONE_DEFAULT_TIME_RANGE_SECONDS
760
+ : ZONE_DEFAULT_DISTANCE_RANGE_METERS;
761
+ if (fields.rangeType === "distance") {
762
+ draft.speedKmh = null;
763
+ }
764
+ }
765
+
766
+ if (fields.windowOpen !== undefined) {
767
+ draft.windowOpen = fields.windowOpen;
768
+ if (!fields.windowOpen) {
769
+ draft.startAt = null;
770
+ draft.endAt = null;
771
+ }
772
+ }
773
+
774
+ if (fields.name !== undefined) {
775
+ draft.name = fields.name;
776
+ this.nameTouched = true;
777
+ // A create's name is its reader's from here on, and a draft a proposal named is shown
778
+ // under it: the proposal's name leaves the draft, which records no step.
779
+ const session = this.ui.getState().zoneEditSession;
780
+ if (this.bound === null && session?.intent === "create" && session.name !== null) {
781
+ this.ui.getState().setZoneEditName(null);
782
+ }
783
+ }
784
+
785
+ if (fields.description !== undefined) {
786
+ draft.description = fields.description;
787
+ }
788
+
789
+ if (fields.startAt !== undefined) {
790
+ draft.startAt = fields.startAt;
791
+ }
792
+
793
+ if (fields.endAt !== undefined) {
794
+ draft.endAt = fields.endAt;
795
+ }
796
+
797
+ if (
798
+ fields.name !== undefined ||
799
+ fields.description !== undefined ||
800
+ fields.startAt !== undefined ||
801
+ fields.endAt !== undefined
802
+ ) {
803
+ this.saveFailure = null;
804
+ }
805
+
806
+ if (fields.activityId !== undefined) {
807
+ draft.activityId = fields.activityId;
808
+ }
809
+
810
+ if (fields.collectionIds !== undefined && !sameIds(draft.collectionIds, fields.collectionIds)) {
811
+ draft.collectionIds = [...fields.collectionIds];
812
+ }
813
+
814
+ if (fields.mode !== undefined) {
815
+ draft.createMode = fields.mode;
816
+ }
817
+
818
+ if (fields.organizationId !== undefined) {
819
+ draft.organizationId = fields.organizationId;
820
+ this.organizationChosen = true;
821
+ // A create's organization is its reader's from here on, over a proposal's or the one its
822
+ // draw was armed under: the session is told, since the save and the co-pilot read it there.
823
+ const session = this.ui.getState().zoneEditSession;
824
+ if (
825
+ this.bound === null &&
826
+ session?.intent === "create" &&
827
+ session.organizationId !== fields.organizationId
828
+ ) {
829
+ this.ui.getState().setZoneEditOrganization(fields.organizationId);
830
+ }
831
+ }
832
+
833
+ if (fields.range !== undefined) {
834
+ draft.range = fields.range;
835
+ }
836
+
837
+ if (fields.speedKmh !== undefined) {
838
+ // A pace rides a time budget only. Held beside a distance it would ride the next switch to
839
+ // time, a pace its reader set on a form that showed none.
840
+ draft.speedKmh = draft.rangeType === "time" ? fields.speedKmh : null;
841
+ }
842
+
843
+ // The severity the form held before this edit, and the pick the store held, which a refused
844
+ // recolour goes back to.
845
+ const held = { level: draft.createLevel, pick: this.ui.getState().zoneCreatePickedLevel };
846
+ if (fields.level !== undefined) {
847
+ draft.createLevel = fields.level;
848
+ // A create's severity is its reader's from here on. The store is told, since the step of a
849
+ // proposal that joins the create records it.
850
+ if (this.bound === null && held.pick !== fields.level) {
851
+ this.ui.getState().setZoneCreatePickedLevel(fields.level);
852
+ }
853
+ }
854
+
855
+ this.reconcile();
856
+
857
+ if (fields.level !== undefined && this.snapshot.armed) {
858
+ void this.recolour(fields.level, held);
859
+ }
860
+ }
861
+
862
+ /**
863
+ * ask runs one tool and answers its result, or null where the host's bus rejected the call.
864
+ *
865
+ * A tool bus's dispatch never rejects, and a host's own may. A call it rejects made no answer:
866
+ * the rejection is held here, so none is left unhandled by a call the form does not await, and
867
+ * the caller goes on as it does for a tool that did nothing. A save is awaited by its caller
868
+ * and is not asked through here: its rejection is the caller's to read.
869
+ */
870
+ private async ask<TName extends ZoneFormTool>(
871
+ name: TName,
872
+ input: StudioToolInputs[TName],
873
+ ): Promise<ToolResultOf<StudioToolOutputs, TName> | null> {
874
+ try {
875
+ return await this.config.dispatch(name, input);
876
+ } catch {
877
+ return null;
878
+ }
879
+ }
880
+
881
+ /**
882
+ * recolour sets the armed draft's severity, through `studio.zone.setLevel`. A refusal leaves
883
+ * the draft painted as it was, and so does a call the bus rejects, so the form goes back to the
884
+ * severity it held and a create's pick to the one the store held, unless its reader has chosen
885
+ * another since or the form answers for another subject by then.
886
+ */
887
+ private async recolour(
888
+ level: ZoneEditLevel,
889
+ held: { readonly level: ZoneEditLevel; readonly pick: ZoneEditLevel | null },
890
+ ): Promise<void> {
891
+ const epoch = this.subjectEpoch;
892
+ const result = await this.ask("studio.zone.setLevel", { level });
893
+ if (
894
+ result?.ok !== true &&
895
+ !this.disposed &&
896
+ epoch === this.subjectEpoch &&
897
+ this.draft.createLevel === level
898
+ ) {
899
+ this.draft.createLevel = held.level;
900
+ if (this.bound === null && this.ui.getState().zoneCreatePickedLevel === level) {
901
+ this.ui.getState().setZoneCreatePickedLevel(held.pick);
902
+ }
903
+
904
+ this.reconcile();
905
+ }
906
+ }
907
+
908
+ /**
909
+ * setMethod switches how a create is authored, through `studio.zone.setCreateMethod`, and
910
+ * clears the preview's and the save's failures, which described the method left behind. The
911
+ * same two are cleared when another caller of that tool switches it. A switch the tool refuses
912
+ * left no method behind: the two failures stand again, for as long as the form answers for the
913
+ * same create. A call while parked, or after {@link ZoneFormEngine.dispose}, does nothing.
914
+ */
915
+ setMethod(method: ZoneCreateMethod): void {
916
+ if (this.parked || this.disposed) {
917
+ return;
918
+ }
919
+
920
+ this.touched = true;
921
+
922
+ void this.switchMethod(method);
923
+ }
924
+
925
+ /** switchMethod asks for the switch, and puts back what it cleared when the tool refuses. */
926
+ private async switchMethod(method: ZoneCreateMethod): Promise<void> {
927
+ // Read before the tool runs: a tool that switches at once moves the subject as it does.
928
+ const epoch = this.subjectEpoch;
929
+ const held = {
930
+ preview: this.previewFailure,
931
+ save: this.saveFailure,
932
+ source: this.sourceRefusal,
933
+ };
934
+ const answer = this.ask("studio.zone.setCreateMethod", { method });
935
+ this.saveFailure = null;
936
+ this.sourceRefusal = null;
937
+ this.previewFailure = null;
938
+ this.reconcile();
939
+
940
+ // A switch the bus rejected left no method behind either.
941
+ const result = await answer;
942
+ if (result?.ok === true || this.disposed || epoch !== this.subjectEpoch) {
943
+ return;
944
+ }
945
+
946
+ // The method stands, and so does what it failed with, unless a later answer said otherwise.
947
+ this.saveFailure ??= held.save;
948
+ this.sourceRefusal ??= held.source;
949
+ this.previewFailure ??= held.preview;
950
+ this.reconcile();
951
+ }
952
+
953
+ /**
954
+ * beginOriginPick arms the map for the click that places a reachability zone's origin, through
955
+ * `studio.zone.beginOriginPick`.
956
+ *
957
+ * A refusal is kept as the snapshot's `pickFailure`, for as long as the form answers for the
958
+ * create or the zone the pick was asked for and no later pick was asked.
959
+ *
960
+ * A call while parked, or after {@link ZoneFormEngine.dispose}, does nothing.
961
+ */
962
+ beginOriginPick(): void {
963
+ if (this.parked || this.disposed) {
964
+ return;
965
+ }
966
+
967
+ this.touched = true;
968
+
969
+ this.pickFailure = null;
970
+ this.reconcile();
971
+ void this.pick();
972
+ }
973
+
974
+ /** pick asks for the origin pick, and keeps a refusal while it is the latest and its form's. */
975
+ private async pick(): Promise<void> {
976
+ const epoch = this.subjectEpoch;
977
+ this.pickSerial += 1;
978
+ const asked = this.pickSerial;
979
+
980
+ // A pick the bus rejected answered no refusal to keep.
981
+ const result = await this.ask("studio.zone.beginOriginPick", {});
982
+ if (
983
+ result === null ||
984
+ result.ok ||
985
+ this.disposed ||
986
+ epoch !== this.subjectEpoch ||
987
+ asked !== this.pickSerial
988
+ ) {
989
+ return;
990
+ }
991
+
992
+ this.pickFailure = result;
993
+ this.reconcile();
994
+ }
995
+
996
+ /**
997
+ * beginDraw arms the map to draw a new zone, through `studio.zone.editBegin`, in the form's
998
+ * shape and severity and under its organization. The zone's id is minted by the `ids` seam: a
999
+ * zone cannot persist empty, so the draw session needs a handle before there is a zone to name.
1000
+ *
1001
+ * A refusal is kept as the snapshot's `drawFailure`, for as long as the form answers for the
1002
+ * create the draw was asked for.
1003
+ *
1004
+ * It does nothing while a zone is bound, while a draw or a reshape is armed, while an earlier
1005
+ * call is still unanswered, while no shape is chosen, while parked, or after
1006
+ * {@link ZoneFormEngine.dispose}.
1007
+ */
1008
+ beginDraw(): void {
1009
+ if (this.parked || this.disposed || this.drawing) {
1010
+ return;
1011
+ }
1012
+
1013
+ const facts = factsOf(this.ui.getState());
1014
+ const { createLevel, createMode, organizationId } = this.draft;
1015
+ if (facts.zone !== null || facts.session !== null || createMode === null) {
1016
+ return;
1017
+ }
1018
+
1019
+ this.drawing = true;
1020
+ this.drawFailure = null;
1021
+ this.reconcile();
1022
+
1023
+ void this.draw({
1024
+ intent: "create",
1025
+ level: createLevel,
1026
+ mode: createMode,
1027
+ organizationId: organizationId ?? undefined,
1028
+ zoneId: this.ids.next(),
1029
+ });
1030
+ }
1031
+
1032
+ /** draw asks for the draw session, and keeps a refusal while its create is the form's. */
1033
+ private async draw(input: StudioToolInputs["studio.zone.editBegin"]): Promise<void> {
1034
+ const epoch = this.subjectEpoch;
1035
+
1036
+ // A draw the bus rejected answered no refusal to keep, and is no draw in flight.
1037
+ const result = await this.ask("studio.zone.editBegin", input);
1038
+ if (result !== null && !result.ok && !this.disposed && epoch === this.subjectEpoch) {
1039
+ this.drawFailure = result;
1040
+ }
1041
+
1042
+ this.drawing = false;
1043
+ this.reconcile();
1044
+ }
1045
+
1046
+ /**
1047
+ * save persists the form through the one tool call {@link zoneSaveRequest} routes it to, and
1048
+ * resolves once the tool has answered. It resolves at once, having sent nothing, when a save
1049
+ * of the same zone or the same create is already in flight, when the form has nothing to
1050
+ * send, while parked, and after {@link ZoneFormEngine.dispose}. A save in flight for another
1051
+ * zone holds back no save of this one.
1052
+ *
1053
+ * A refusal is kept as the snapshot's `saveFailure` and the fields stay as typed, so a retry is
1054
+ * one more call. A refusal that lands once the form answers for another zone, or once a create
1055
+ * has switched method or changed the itinerary it inherits from, is dropped: it describes a
1056
+ * form nobody is looking at. One that lands once the form has come back to the zone or the
1057
+ * create it was sent for is kept, since the snapshot read `saving` for it all along. A refusal
1058
+ * of the reachability query the fields stated as the save left is kept as the snapshot's
1059
+ * `sourceFailure` instead, for the surface to show at the query's fields. A create
1060
+ * that lost some of its collections raises a warning through `studio.alert.show`: the zone
1061
+ * exists, and the reader should know where it was not filed.
1062
+ *
1063
+ * It never rejects while `dispatch` does not.
1064
+ */
1065
+ async save(): Promise<void> {
1066
+ // A running engine has seeded, so it has a subject. The latch is the subject's own: a save
1067
+ // of one zone in flight says nothing of the zone bound after it.
1068
+ const { subject } = this;
1069
+ if (this.parked || this.disposed || subject === null || this.saving.has(subject)) {
1070
+ return;
1071
+ }
1072
+
1073
+ this.saveFailure = null;
1074
+ this.sourceRefusal = null;
1075
+ const request = this.saveRequest();
1076
+ if (request === null) {
1077
+ this.reconcile();
1078
+
1079
+ return;
1080
+ }
1081
+
1082
+ // The query the fields state as the save leaves, which a refusal of its source answers for.
1083
+ const query = queryKeyOf(this.statedSource());
1084
+ this.saving.add(subject);
1085
+ this.reconcile();
1086
+
1087
+ try {
1088
+ const result = await this.run(request);
1089
+ if (this.disposed) {
1090
+ return;
1091
+ }
1092
+
1093
+ if (!result.ok) {
1094
+ // The refusal answers the subject it was sent under, read by name: a form that left its
1095
+ // zone and came back to it shows the save in flight the whole time, and is owed its
1096
+ // refusal. A save that binds its own zone changes the subject too, and succeeded, so
1097
+ // only a refusal is held to it.
1098
+ if (subject !== this.subject) {
1099
+ return;
1100
+ }
1101
+
1102
+ // A refused source is about the query, and is kept where the query's fields are. A form
1103
+ // that stated none shows no such field, so the refusal is its failed save.
1104
+ if (query !== null && zoneSourceRefused(result)) {
1105
+ this.sourceRefusal = { failure: result, query };
1106
+ } else {
1107
+ this.saveFailure = result;
1108
+ }
1109
+
1110
+ return;
1111
+ }
1112
+
1113
+ // Read off the tool's own answer: a create names the collections it lost, and a save that
1114
+ // creates nothing names none.
1115
+ const failed =
1116
+ result.data !== undefined && "failedCollectionIds" in result.data
1117
+ ? result.data.failedCollectionIds
1118
+ : [];
1119
+ if (failed.length > 0) {
1120
+ // Not awaited: the zone is saved whatever becomes of its warning.
1121
+ void this.ask("studio.alert.show", {
1122
+ level: "warning",
1123
+ message: this.config.strings.zoneForm.collectionAttachWarning(failed.length),
1124
+ });
1125
+ }
1126
+ } finally {
1127
+ this.saving.delete(subject);
1128
+ this.reconcile();
1129
+ }
1130
+ }
1131
+
1132
+ /** run dispatches a save request, each arm with its own tool's input. */
1133
+ private run(
1134
+ request: ZoneSaveRequest,
1135
+ ): Promise<ToolResultOf<StudioToolOutputs, ZoneSaveRequest["name"]>> {
1136
+ switch (request.name) {
1137
+ case "studio.zone.create":
1138
+ return this.config.dispatch(request.name, request.input);
1139
+ case "studio.zone.editCommit":
1140
+ return this.config.dispatch(request.name, request.input);
1141
+ case "studio.zone.update":
1142
+ return this.config.dispatch(request.name, request.input);
1143
+ }
1144
+ }
1145
+
1146
+ /** saveRequest routes the form as it stands to the tool call that persists it, or to null. */
1147
+ private saveRequest(): ZoneSaveRequest | null {
1148
+ const facts = factsOf(this.ui.getState());
1149
+ const { fields, method } = this.snapshot;
1150
+ const { zone } = facts;
1151
+
1152
+ return zoneSaveRequest({
1153
+ canEdit:
1154
+ zone === null ||
1155
+ canEditOwnedResource(
1156
+ { createdById: zone.created_by.id, organizationId: zone.organization_id },
1157
+ this.config.userId,
1158
+ this.config.writableOrganizationIds,
1159
+ ),
1160
+ fields,
1161
+ method,
1162
+ session: facts.session,
1163
+ source: this.sourceFor(facts, method),
1164
+ zone,
1165
+ });
1166
+ }
1167
+
1168
+ /** statedSource is the reachability query the fields state as the store stands, or null. */
1169
+ private statedSource(): ZoneSource | null {
1170
+ return this.sourceFor(factsOf(this.ui.getState()), this.snapshot.method);
1171
+ }
1172
+
1173
+ /**
1174
+ * publishUnsaved writes whether the form holds something unsaved on the store's
1175
+ * `zoneFormUnsaved`, where `studio.zone.publish` and the publication band read it, when that
1176
+ * answer moved. A parked engine writes nothing: its reads run inside a render, and a form
1177
+ * nobody watches holds nothing for anyone to lose.
1178
+ *
1179
+ * The store hears of the write at once, and so does this engine's own watch, which finds no slot
1180
+ * it reads moved and runs no pass.
1181
+ */
1182
+ private publishUnsaved(unsaved: boolean): void {
1183
+ if (this.parked || this.disposed || unsaved === this.unsavedWritten) {
1184
+ return;
1185
+ }
1186
+
1187
+ this.unsavedWritten = unsaved;
1188
+ this.ui.getState().setZoneFormUnsaved(unsaved);
1189
+ }
1190
+
1191
+ /**
1192
+ * park stops watching the store, drops the pending preview and forgets the one in flight. The
1193
+ * unsaved answer it wrote is taken back: a form that unmounts holds nothing any more.
1194
+ */
1195
+ private park(): void {
1196
+ if (this.unsavedWritten) {
1197
+ this.unsavedWritten = false;
1198
+ this.ui.getState().setZoneFormUnsaved(false);
1199
+ }
1200
+
1201
+ this.parked = true;
1202
+ this.unwatch?.();
1203
+ this.unwatch = null;
1204
+ this.cancelPending();
1205
+ // The next subscriber asks again, and an answer on its way belongs to nobody.
1206
+ this.previewKey = undefined;
1207
+ this.previewInput = null;
1208
+ this.previewEpoch += 1;
1209
+ }
1210
+
1211
+ /** settle brings a parked engine's snapshot in line with the store and the configuration. */
1212
+ private settle(): void {
1213
+ if (this.disposed || !this.parked) {
1214
+ return;
1215
+ }
1216
+
1217
+ const { settled } = this;
1218
+ if (
1219
+ settled !== null &&
1220
+ settled.config === this.config &&
1221
+ readsSame(settled.state, this.ui.getState())
1222
+ ) {
1223
+ return;
1224
+ }
1225
+
1226
+ this.reconcile();
1227
+ }
1228
+
1229
+ /**
1230
+ * watch answers one notification of the store: it runs a pass when a slot the form reads
1231
+ * moved, and nothing otherwise, so a hover or a selection costs the form one comparison.
1232
+ */
1233
+ private watch(state: UiStore): void {
1234
+ const { settled } = this;
1235
+ if (settled !== null && settled.config === this.config && readsSame(settled.state, state)) {
1236
+ this.settled = { config: settled.config, state };
1237
+
1238
+ return;
1239
+ }
1240
+
1241
+ this.reconcile();
1242
+ }
1243
+
1244
+ /**
1245
+ * reconcile seeds the fields from the store and the configuration, publishes the snapshot and
1246
+ * follows the preview it is worth. A change made while it runs, by a listener or by a tool a
1247
+ * preview runs at once, runs it again once it finishes rather than inside it.
1248
+ */
1249
+ private reconcile(): void {
1250
+ if (this.disposed) {
1251
+ return;
1252
+ }
1253
+
1254
+ if (this.reconciling) {
1255
+ this.stale = true;
1256
+
1257
+ return;
1258
+ }
1259
+
1260
+ this.reconciling = true;
1261
+ try {
1262
+ do {
1263
+ this.stale = false;
1264
+ const state = this.ui.getState();
1265
+ this.settled = { config: this.config, state };
1266
+
1267
+ const facts = factsOf(state);
1268
+ this.seed(facts);
1269
+ const view = this.view(facts);
1270
+ this.commit(view.snapshot);
1271
+ this.publishUnsaved(view.changed);
1272
+ this.followPreview(view);
1273
+ } while (this.stale && !this.disposed);
1274
+ } finally {
1275
+ this.reconciling = false;
1276
+ }
1277
+ }
1278
+
1279
+ /** seed brings the fields in line with the bound zone, the create's context and the catalog. */
1280
+ private seed(facts: StoreFacts): void {
1281
+ const { draft } = this;
1282
+ const { activities, defaultOrganizationId, inheritedCollectionIds } = this.config;
1283
+ const { inherited, zone } = facts;
1284
+ const previous = this.bound;
1285
+
1286
+ // What the zone says, keyed on the zone object. Another zone, and an unbind, seed every
1287
+ // field again. The same zone written again, by this form's save or a collaborator's, is
1288
+ // followed field by field, so what the reader typed and has not saved stays.
1289
+ if (zone !== previous) {
1290
+ this.bound = zone;
1291
+ if (zone !== null && previous != null && previous.id === zone.id) {
1292
+ this.follow(previous, zone, facts.session);
1293
+ } else {
1294
+ this.seedMetadata(zone);
1295
+ }
1296
+ } else if (zone === null && facts.createSerial !== this.createSerial) {
1297
+ // The create surface was entered again over a create: the fields typed into the last one
1298
+ // are not this one's.
1299
+ this.seedMetadata(null);
1300
+ }
1301
+ this.createSerial = zone === null ? facts.createSerial : undefined;
1302
+
1303
+ // The create the form stands on: its serial and the itinerary it inherits from, and
1304
+ // undefined while a zone is bound.
1305
+ const create =
1306
+ zone === null ? `${facts.createSerial}:${inherited?.itineraryId ?? ""}` : undefined;
1307
+
1308
+ // What a failure answers for, keyed on the zone's id where the fields above are keyed on
1309
+ // the object: a write that replaces the bound zone keeps its refusal on screen, and another
1310
+ // zone, an unbind, another create, a create's other method or a create that inherits from
1311
+ // elsewhere is another subject. No failure follows the form there, and an answer on its
1312
+ // way, a save's or a draw's refusal or a preview's failure, is dropped when it lands. The
1313
+ // preview's key stays as it is, so a subject that states the query already asked about asks
1314
+ // nothing again.
1315
+ const subject =
1316
+ zone === null
1317
+ ? `create:${facts.createMethod ?? DEFAULT_ZONE_CREATE_METHOD}:${create ?? ""}`
1318
+ : `zone:${zone.id}`;
1319
+ if (subject !== this.subject) {
1320
+ this.subject = subject;
1321
+ this.touched = false;
1322
+ this.drawFailure = null;
1323
+ this.pickFailure = null;
1324
+ this.saveFailure = null;
1325
+ this.sourceRefusal = null;
1326
+ this.previewFailure = null;
1327
+ this.subjectEpoch += 1;
1328
+ this.previewEpoch += 1;
1329
+ }
1330
+
1331
+ // An origin that moved is a pick that landed, whoever placed it.
1332
+ if (facts.origin !== this.origin) {
1333
+ this.origin = facts.origin;
1334
+ this.pickFailure = null;
1335
+ }
1336
+
1337
+ // A draw that is armed is no draw refused, whoever armed it.
1338
+ if (facts.session !== null) {
1339
+ this.drawFailure = null;
1340
+ }
1341
+
1342
+ // A create is seeded per create. One opens when the zone unbinds, when the create surface
1343
+ // is entered again, and when what it inherits changes hands: the fields the last zone or
1344
+ // the last create left are not this one's.
1345
+ if (create !== this.create) {
1346
+ this.create = create;
1347
+ if (create !== undefined) {
1348
+ this.resetCreate();
1349
+ }
1350
+ }
1351
+
1352
+ this.seedParameters(zone);
1353
+
1354
+ if (zone !== null) {
1355
+ return;
1356
+ }
1357
+
1358
+ if (inherited) {
1359
+ // Followed rather than seeded once: the itinerary is what the surface names, its
1360
+ // collections are a read of the host's own that may land after the form opened, and none
1361
+ // of the three is the reader's to change in this mode. A personal itinerary belongs to no
1362
+ // organization and its zone inherits exactly that, where falling back to the default one
1363
+ // would file it somewhere its reader never chose.
1364
+ draft.organizationId = inherited.organizationId;
1365
+ if (!sameIds(draft.collectionIds, inheritedCollectionIds)) {
1366
+ draft.collectionIds = [...inheritedCollectionIds];
1367
+ }
1368
+ if (activities.length > 0) {
1369
+ draft.activityId = inherited.activityId;
1370
+ }
1371
+ } else {
1372
+ // Seeded while empty: the default organization and the catalog are the host's to resolve
1373
+ // and may land after the form opened, and the reader's own choice is never replaced. No
1374
+ // organization is a choice too, once the reader made it: the create stays personal.
1375
+ if (draft.organizationId === null && !this.organizationChosen) {
1376
+ draft.organizationId = defaultOrganizationId;
1377
+ }
1378
+ if (draft.activityId === null && activities.length > 0) {
1379
+ draft.activityId = firstRoutableActivityId(activities);
1380
+ }
1381
+ }
1382
+
1383
+ if (!this.nameTouched) {
1384
+ const name = zoneAutoName({
1385
+ activityName: this.activityName(),
1386
+ language: this.config.language,
1387
+ method: facts.createMethod ?? DEFAULT_ZONE_CREATE_METHOD,
1388
+ proposedName: facts.session?.name ?? null,
1389
+ range: draft.range,
1390
+ rangeType: draft.rangeType,
1391
+ strings: this.config.strings.zoneForm,
1392
+ });
1393
+ if (name !== null) {
1394
+ draft.name = name;
1395
+ }
1396
+ }
1397
+ }
1398
+
1399
+ /**
1400
+ * seedParameters brings the reachability parameters in line with the query `zone` is stored
1401
+ * with and with the catalog, and drops an activity the catalog lists no more.
1402
+ */
1403
+ private seedParameters(zone: Zone | null): void {
1404
+ const { draft } = this;
1405
+ const { activities } = this.config;
1406
+
1407
+ // The parameters a computed zone is stored with. The catalog is part of the key because the
1408
+ // stored query names its activity by slug, which only the catalog resolves to an id.
1409
+ const seeded = this.sourceSeed;
1410
+ if (seeded?.zone !== zone || seeded.activities !== activities) {
1411
+ this.sourceSeed = { activities, zone };
1412
+ const source = zone?.source;
1413
+ if (source) {
1414
+ const says = parametersOf(activities, source);
1415
+ // The query this zone was last seeded from, or undefined for another zone's.
1416
+ const earlier = seeded?.zone?.id === zone?.id ? seeded?.zone?.source : undefined;
1417
+
1418
+ // A catalog replaced under the same zone resolves the stored activity again, and on its
1419
+ // own: an activity the form holds because the catalog before resolved it there, none
1420
+ // included while that catalog was empty, is no choice of the reader's, whatever they
1421
+ // did to the budget meanwhile.
1422
+ if (
1423
+ seeded &&
1424
+ earlier &&
1425
+ draft.activityId === activityIdForSlug(seeded.activities, earlier.activity)
1426
+ ) {
1427
+ draft.activityId = activityIdForSlug(activities, earlier.activity);
1428
+ }
1429
+
1430
+ // The same zone written again: the parameters are one answer, and the reader's stand
1431
+ // whole once any of them left what the zone said.
1432
+ const said = earlier ? parametersOf(activities, earlier) : null;
1433
+ const held: QueryParameters = {
1434
+ activityId: draft.activityId,
1435
+ range: draft.range,
1436
+ rangeType: draft.rangeType,
1437
+ speedKmh: draft.speedKmh,
1438
+ };
1439
+ if (said === null || sameMembers(held, said) || sameMembers(held, says)) {
1440
+ draft.activityId = says.activityId;
1441
+ draft.rangeType = says.rangeType;
1442
+ draft.range = says.range;
1443
+ draft.speedKmh = says.speedKmh;
1444
+ }
1445
+ }
1446
+ }
1447
+
1448
+ // An activity the catalog lists no more names nothing: no query can be stated from it, and a
1449
+ // form left on it withholds its save with nothing to say why. So the id is dropped. A
1450
+ // computed zone takes the activity it is stored with again, and a create is seeded again by
1451
+ // the caller. An empty catalog is one the host has not resolved yet, and drops nothing.
1452
+ if (
1453
+ draft.activityId !== null &&
1454
+ activities.length > 0 &&
1455
+ activityForId(activities, draft.activityId) === null
1456
+ ) {
1457
+ const stored = zone?.source?.activity;
1458
+ draft.activityId = stored === undefined ? null : activityIdForSlug(activities, stored);
1459
+ }
1460
+ }
1461
+
1462
+ /**
1463
+ * seedMetadata seeds what a zone says from `zone`, and from a create's defaults for none: the
1464
+ * name, the description, the window and the severity.
1465
+ */
1466
+ private seedMetadata(zone: Zone | null): void {
1467
+ const { draft } = this;
1468
+
1469
+ draft.name = zone?.name ?? "";
1470
+ draft.description = zone?.description ?? "";
1471
+ draft.startAt = zone?.start_at ?? null;
1472
+ draft.endAt = zone?.end_at ?? null;
1473
+ draft.windowOpen = draft.startAt !== null || draft.endAt !== null;
1474
+ draft.createLevel = zone?.level ?? DEFAULT_ZONE_LEVEL;
1475
+ // A saved zone's name is its own, whatever produced it; a create's follows again.
1476
+ this.nameTouched = zone !== null;
1477
+ }
1478
+
1479
+ /**
1480
+ * follow brings the fields in line with the bound zone written again: `previous` is what it
1481
+ * said and `next` what it says now.
1482
+ *
1483
+ * A field the reader has not moved off what the zone said takes what it says now, and so does
1484
+ * one that already says it, which is how the reader's own save lands in its stored spelling.
1485
+ * Any other is what the reader typed and has not saved, and stays. The window is one answer,
1486
+ * its bounds and whether it is open, taken whole from the reader once they moved any of it,
1487
+ * so no bound a collaborator chose is ever paired with one the reader did.
1488
+ *
1489
+ * The severity of a reshape armed on the zone is shown over the form's own, so it follows by
1490
+ * the same rule: while `session` still paints the severity the zone said, it is set to the one
1491
+ * the zone says now, through `studio.zone.setLevel`. One the reader moved is theirs and stays.
1492
+ * Left as it was, the form would read unsaved after a collaborator's change of severity, and
1493
+ * its save would write the old one back.
1494
+ */
1495
+ private follow(previous: Zone, next: Zone, session: ZoneEditSession | null): void {
1496
+ const { draft } = this;
1497
+
1498
+ if (
1499
+ session !== null &&
1500
+ session.zoneId === next.id &&
1501
+ session.level === previous.level &&
1502
+ next.level !== previous.level
1503
+ ) {
1504
+ // Not awaited: the fields below follow the zone whatever becomes of the recolour.
1505
+ void this.ask("studio.zone.setLevel", { level: next.level });
1506
+ }
1507
+
1508
+ if (!typedOver("name", draft.name, previous, next)) {
1509
+ draft.name = next.name;
1510
+ }
1511
+
1512
+ if (!typedOver("description", draft.description, previous, next)) {
1513
+ draft.description = next.description ?? "";
1514
+ }
1515
+
1516
+ if (!typedOver("level", draft.createLevel, previous, next)) {
1517
+ draft.createLevel = next.level;
1518
+ }
1519
+
1520
+ const windowTyped =
1521
+ typedOver("startAt", draft.startAt, previous, next) ||
1522
+ typedOver("endAt", draft.endAt, previous, next) ||
1523
+ (draft.windowOpen !== windowOpens(previous) && draft.windowOpen !== windowOpens(next));
1524
+ if (!windowTyped) {
1525
+ draft.startAt = next.start_at;
1526
+ draft.endAt = next.end_at;
1527
+ draft.windowOpen = windowOpens(next);
1528
+ }
1529
+ }
1530
+
1531
+ /**
1532
+ * resetCreate returns the fields a create seeds for itself to a create's defaults: where it is
1533
+ * filed, the shape it is drawn in and the parameters it is computed from. What the zone says
1534
+ * is seeded from the zone, bound or not.
1535
+ */
1536
+ private resetCreate(): void {
1537
+ const { draft } = this;
1538
+
1539
+ this.organizationChosen = false;
1540
+ draft.activityId = null;
1541
+ // Kept when already empty, so a reset that changes nothing leaves the snapshot's identity.
1542
+ if (draft.collectionIds.length > 0) {
1543
+ draft.collectionIds = [];
1544
+ }
1545
+ draft.createMode = DEFAULT_ZONE_MODE;
1546
+ draft.organizationId = null;
1547
+ draft.range = ZONE_DEFAULT_DISTANCE_RANGE_METERS;
1548
+ draft.rangeType = "distance";
1549
+ draft.speedKmh = null;
1550
+ }
1551
+
1552
+ /** activityName is the chosen activity's name in the reader's language, or null. */
1553
+ private activityName(): string | null {
1554
+ const { activityId } = this.draft;
1555
+ const activity = activityId === null ? null : activityForId(this.config.activities, activityId);
1556
+
1557
+ return activity ? localizedName(activity, this.config.language) : null;
1558
+ }
1559
+
1560
+ /** sourceFor is the reachability query the fields state under `facts`, or null. */
1561
+ private sourceFor(facts: StoreFacts, method: ZoneCreateMethod): ZoneSource | null {
1562
+ const { activityId, range, rangeType, speedKmh } = this.draft;
1563
+ const activity = activityId === null ? null : activityForId(this.config.activities, activityId);
1564
+
1565
+ return zoneSourceQuery({
1566
+ activitySlug: activity?.slug ?? null,
1567
+ method,
1568
+ origin: facts.origin,
1569
+ range,
1570
+ rangeType,
1571
+ speedKmh,
1572
+ });
1573
+ }
1574
+
1575
+ /** view reads the form as it stands under `facts`. */
1576
+ private view(facts: StoreFacts): View {
1577
+ const { draft } = this;
1578
+ const { session, zone } = facts;
1579
+ const method: ZoneCreateMethod =
1580
+ zone === null
1581
+ ? (facts.createMethod ?? DEFAULT_ZONE_CREATE_METHOD)
1582
+ : zone.source
1583
+ ? "reachability"
1584
+ : "draw";
1585
+ const fields: ZoneFormFields = {
1586
+ activityId: draft.activityId,
1587
+ collectionIds: draft.collectionIds,
1588
+ description: draft.description,
1589
+ endAt: draft.endAt,
1590
+ // An armed session carries the severity the draft is painted in.
1591
+ level: session?.level ?? draft.createLevel,
1592
+ mode: zone === null ? (session?.mode ?? draft.createMode) : zone.mode,
1593
+ // A create's draft a proposal named is shown under that name, and under the form's own
1594
+ // where none did or its reader typed over it.
1595
+ name: zone === null ? (session?.name ?? draft.name) : draft.name,
1596
+ // A create's session carries the organization it is filed under, a proposal's included.
1597
+ organizationId:
1598
+ zone === null ? (session?.organizationId ?? draft.organizationId) : draft.organizationId,
1599
+ range: draft.range,
1600
+ rangeType: draft.rangeType,
1601
+ speedKmh: draft.speedKmh,
1602
+ startAt: draft.startAt,
1603
+ windowOpen: draft.windowOpen,
1604
+ };
1605
+
1606
+ const source = this.sourceFor(facts, method);
1607
+ const armed = session !== null;
1608
+ const metadataDirty = zone !== null && isZoneMetadataDirty(fields, zone);
1609
+ const sourceDirty = zone !== null && isZoneSourceDirty(source, zone.source);
1610
+ const { descriptionValid, nameValid } = this.judge(fields.name, fields.description);
1611
+ const saving = this.subject !== null && this.saving.has(this.subject);
1612
+ const windowValid = !isZoneWindowInvalid(fields.startAt, fields.endAt);
1613
+ const reachabilityCreate = zone === null && method === "reachability";
1614
+ // A failure answers a query, so fields that state none carry none. A parked engine reads
1615
+ // it this way too, where nothing has dropped the one it holds.
1616
+ const previewFailure = source === null ? null : this.previewFailure;
1617
+ // A refused source answers for the query it was sent with, and for no other.
1618
+ const refused = this.sourceRefusal;
1619
+ const sourceFailure =
1620
+ refused !== null && refused.query === queryKeyOf(source) ? refused.failure : null;
1621
+ // A reachability create persists the query its preview proved computable; a drawn one
1622
+ // persists a shape, so it waits for one; an edit waits for something to have moved.
1623
+ const unsaved =
1624
+ zone === null
1625
+ ? reachabilityCreate
1626
+ ? source !== null && previewFailure === null
1627
+ : isZoneGeometryDirty(session)
1628
+ : isZoneGeometryDirty(session) || metadataDirty || sourceDirty;
1629
+ // What leaving would lose, which the store's `zoneFormUnsaved` says. A computed create can be
1630
+ // saved as it opened, and loses nothing the reader did until the reader changes it.
1631
+ const changed = reachabilityCreate ? unsaved && this.touched : unsaved;
1632
+
1633
+ const preview =
1634
+ source === null
1635
+ ? null
1636
+ : {
1637
+ activity: source.activity,
1638
+ level: fields.level,
1639
+ location: source.location,
1640
+ ranges: [source.range],
1641
+ rangeType: source.range_type,
1642
+ speed: source.speed,
1643
+ };
1644
+
1645
+ return {
1646
+ preview,
1647
+ previewKey: preview === null ? null : JSON.stringify(preview),
1648
+ snapshot: {
1649
+ armed,
1650
+ descriptionValid,
1651
+ drawFailure: this.drawFailure,
1652
+ fields,
1653
+ inherits: facts.inherited !== null,
1654
+ method,
1655
+ nameValid,
1656
+ pickFailure: this.pickFailure,
1657
+ previewFailure,
1658
+ saveFailure: this.saveFailure,
1659
+ saveOffered: reachabilityCreate || armed || metadataDirty || sourceDirty,
1660
+ saveReady: !saving && nameValid && descriptionValid && windowValid && unsaved,
1661
+ saving,
1662
+ sourceFailure,
1663
+ windowValid,
1664
+ zoneId: zone?.id ?? null,
1665
+ },
1666
+ changed,
1667
+ };
1668
+ }
1669
+
1670
+ /**
1671
+ * judge holds a name and a description to the bounds the tools hold them to. It parses only a
1672
+ * text it has not just judged, so a pass that moved neither, a drag's every frame among them,
1673
+ * parses nothing.
1674
+ */
1675
+ private judge(
1676
+ name: string,
1677
+ description: string,
1678
+ ): { readonly descriptionValid: boolean; readonly nameValid: boolean } {
1679
+ const last = this.judged;
1680
+ if (last !== null && last.name === name && last.description === description) {
1681
+ return last;
1682
+ }
1683
+
1684
+ const judged = {
1685
+ description,
1686
+ descriptionValid: zoneDescriptionSchema.safeParse(description).success,
1687
+ name,
1688
+ nameValid: zoneNameSchema.safeParse(name).success,
1689
+ };
1690
+ this.judged = judged;
1691
+
1692
+ return judged;
1693
+ }
1694
+
1695
+ /** commit publishes `next` when it differs from the snapshot, and tells every listener. */
1696
+ private commit(next: ZoneFormSnapshot): void {
1697
+ const fields = sameMembers(this.snapshot.fields, next.fields)
1698
+ ? this.snapshot.fields
1699
+ : next.fields;
1700
+ const snapshot: ZoneFormSnapshot = { ...next, fields };
1701
+
1702
+ if (sameMembers(this.snapshot, snapshot)) {
1703
+ return;
1704
+ }
1705
+
1706
+ this.snapshot = snapshot;
1707
+ notifyListeners(Array.from(this.subscriptions, (subscription) => subscription.listener));
1708
+ }
1709
+
1710
+ /**
1711
+ * followPreview asks for the preview `view` is worth, after the debounce, unless that very
1712
+ * preview is already asked for or waited on. A parked engine asks for none.
1713
+ */
1714
+ private followPreview(view: View): void {
1715
+ if (this.parked || view.previewKey === this.previewKey) {
1716
+ return;
1717
+ }
1718
+
1719
+ // Another question: the pending request and the answer on its way are for the previous one.
1720
+ this.cancelPending();
1721
+ this.previewKey = view.previewKey;
1722
+ this.previewInput = view.preview;
1723
+ this.previewEpoch += 1;
1724
+
1725
+ if (view.preview === null) {
1726
+ // No query to ask about: the failure of the last one asked leaves with it, so a query
1727
+ // stated again later shows nothing until its own preview answers.
1728
+ this.previewFailure = null;
1729
+
1730
+ return;
1731
+ }
1732
+
1733
+ if (this.debounceMs === 0) {
1734
+ this.askPreview();
1735
+
1736
+ return;
1737
+ }
1738
+
1739
+ this.timer = setTimeout(() => {
1740
+ this.timer = null;
1741
+ this.askPreview();
1742
+ }, this.debounceMs);
1743
+ }
1744
+
1745
+ /** askPreview runs the preview waited on, and keeps its answer while its question stands. */
1746
+ private askPreview(): void {
1747
+ const input = this.previewInput;
1748
+ if (input === null) {
1749
+ return;
1750
+ }
1751
+
1752
+ const epoch = this.previewEpoch;
1753
+ void this.ask("studio.zone.reachabilityPreview", input).then((result) => {
1754
+ // A preview the bus rejected answered nothing to show, and nothing to clear.
1755
+ if (result === null || epoch !== this.previewEpoch || this.parked) {
1756
+ return;
1757
+ }
1758
+
1759
+ // A failed preview is where the two ways a reachability zone goes wrong surface: no
1760
+ // routable way near the origin, and an activity no router routes. Both are fixed by
1761
+ // changing a field, so the reason is kept for the surface to show.
1762
+ this.previewFailure = result.ok ? null : result;
1763
+ this.reconcile();
1764
+ });
1765
+ }
1766
+
1767
+ private cancelPending(): void {
1768
+ if (this.timer !== null) {
1769
+ clearTimeout(this.timer);
1770
+ this.timer = null;
1771
+ }
1772
+ }
1773
+ }