@svgrid/enterprise 3.1.40 → 3.1.42

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 (268) hide show
  1. package/dist/SvGridBoard.svelte +20 -3
  2. package/dist/SvGridScheduler.svelte +112 -6
  3. package/dist/cdn/svgrid-enterprise.svelte-external.js +546 -540
  4. package/dist/designer/assets/GridFind-DSgjlakI.js +1 -0
  5. package/dist/designer/assets/GridFooter-EjA_7y8w.js +1 -0
  6. package/dist/designer/assets/GridMenus-BBsuf2vC.js +1 -0
  7. package/dist/designer/assets/PinSplitter-oi6ffxQy.js +1 -0
  8. package/dist/designer/assets/SvChartMenu-Durtznhb.js +1 -0
  9. package/dist/designer/assets/SvDateRangeInput-oZyXTEr3.js +1 -0
  10. package/dist/designer/assets/SvDateTimePicker-CUobIgHE.js +1 -0
  11. package/dist/designer/assets/SvGridCellEditor-D_rvqE02.js +3 -0
  12. package/dist/designer/assets/SvGridChart-D0XxAoxS.js +2 -0
  13. package/dist/designer/assets/SvGridChartBuilder-CkuDEcl1.js +1 -0
  14. package/dist/designer/assets/SvGridChartPanel-BUsAzEtx.js +3 -0
  15. package/dist/designer/assets/SvGridChartView-CU_9mwuA.js +1 -0
  16. package/dist/designer/assets/SvGridDropdown-BtnFfHzX.js +1 -0
  17. package/dist/designer/assets/SvListBox-0SCz8lCl.js +2 -0
  18. package/dist/designer/assets/SvMenuList-DpXScUvp.js +1 -0
  19. package/dist/designer/assets/SvTabs-CYhfWOzJ.js +1 -0
  20. package/dist/designer/assets/{chart-panel-messages-BeJhiEym.js → chart-panel-messages-CUwx2rdP.js} +1 -1
  21. package/dist/designer/assets/date-format-C5MG3rPF.js +1 -0
  22. package/dist/designer/assets/grid-extension.svelte-BKJJBM8e.js +1 -0
  23. package/dist/designer/assets/{index-HLPzqCOg.js → index-CZZrEXgj.js} +652 -652
  24. package/dist/designer/assets/index-DY182YW4.css +1 -0
  25. package/dist/designer/assets/index-client-CwjHmKgT.js +2 -0
  26. package/dist/designer/assets/{range-commit-CvP8vrGh.js → range-commit-B_t6HYjs.js} +1 -1
  27. package/dist/designer/assets/row-drag-Dt3zdAss.js +1 -0
  28. package/dist/designer/assets/src-CYr2fa73.js +35 -0
  29. package/dist/designer/assets/src-rcijGyZS.js +1 -0
  30. package/dist/designer/index.html +15 -16
  31. package/dist/fields/AttachmentDialog.svelte +5 -1
  32. package/dist/fields/AutomationAction.svelte +170 -0
  33. package/dist/fields/AutomationAction.svelte.d.ts +25 -0
  34. package/dist/fields/AutomationSteps.svelte +32 -0
  35. package/dist/fields/AutomationSteps.svelte.d.ts +25 -0
  36. package/dist/fields/AutomationTrigger.svelte +54 -0
  37. package/dist/fields/AutomationTrigger.svelte.d.ts +15 -0
  38. package/dist/fields/BarcodeScanner.svelte +17 -0
  39. package/dist/fields/BarcodeScanner.svelte.d.ts +6 -0
  40. package/dist/fields/BaseAutomations.svelte +6 -126
  41. package/dist/fields/BasePivotView.svelte +56 -0
  42. package/dist/fields/BasePivotView.svelte.d.ts +9 -0
  43. package/dist/fields/BaseTableView.svelte +21 -2
  44. package/dist/fields/BaseTableView.svelte.d.ts +10 -1
  45. package/dist/fields/BaseTabs.svelte +54 -6
  46. package/dist/fields/BaseTabs.svelte.d.ts +7 -1
  47. package/dist/fields/DateEditor.svelte +8 -3
  48. package/dist/fields/FieldInput.svelte +9 -2
  49. package/dist/fields/LinkPickerEditor.svelte +3 -2
  50. package/dist/fields/RecordTemplates.svelte +52 -0
  51. package/dist/fields/RecordTemplates.svelte.d.ts +10 -0
  52. package/dist/fields/RecordView.svelte +15 -3
  53. package/dist/fields/RowAdder.svelte +21 -3
  54. package/dist/fields/RowHeader.svelte +21 -2
  55. package/dist/fields/SelectEditor.svelte +12 -6
  56. package/dist/fields/SummaryCell.svelte +1 -1
  57. package/dist/fields/SvBase.svelte +4 -1
  58. package/dist/fields/SvBaseAutomations.svelte +205 -0
  59. package/dist/fields/SvBaseAutomations.svelte.d.ts +27 -0
  60. package/dist/fields/SvBaseForm.svelte +69 -34
  61. package/dist/fields/SvBaseForm.svelte.d.ts +13 -0
  62. package/dist/fields/SvBaseViewBar.svelte +24 -6
  63. package/dist/fields/SvBaseViewBar.svelte.d.ts +4 -0
  64. package/dist/fields/TimerCell.svelte +28 -0
  65. package/dist/fields/TimerCell.svelte.d.ts +16 -0
  66. package/dist/fields/TimerEditor.svelte +7 -0
  67. package/dist/fields/TimerEditor.svelte.d.ts +14 -0
  68. package/dist/fields/airtable.js +1 -1
  69. package/dist/fields/attachments.d.ts +8 -0
  70. package/dist/fields/attachments.js +1 -1
  71. package/dist/fields/automation-edit.d.ts +36 -0
  72. package/dist/fields/automation-edit.js +12 -0
  73. package/dist/fields/automation-outbound.d.ts +37 -1
  74. package/dist/fields/automation-outbound.js +1 -1
  75. package/dist/fields/automation-script.d.ts +59 -0
  76. package/dist/fields/automation-script.js +101 -0
  77. package/dist/fields/automation-server.d.ts +6 -1
  78. package/dist/fields/automation-server.js +1 -1
  79. package/dist/fields/automations.svelte.d.ts +76 -5
  80. package/dist/fields/automations.svelte.js +1 -1
  81. package/dist/fields/barcode-scan.d.ts +8 -0
  82. package/dist/fields/barcode-scan.js +1 -0
  83. package/dist/fields/base-compute.js +1 -1
  84. package/dist/fields/base-export.js +1 -1
  85. package/dist/fields/base-import.js +1 -1
  86. package/dist/fields/base-search.js +1 -1
  87. package/dist/fields/base-sync.js +1 -1
  88. package/dist/fields/base-tables.d.ts +20 -0
  89. package/dist/fields/base-tables.js +1 -1
  90. package/dist/fields/builtin-types.js +1 -1
  91. package/dist/fields/chart-view.d.ts +4 -0
  92. package/dist/fields/chart-view.js +1 -1
  93. package/dist/fields/convert.js +1 -1
  94. package/dist/fields/copy-text.js +1 -1
  95. package/dist/fields/filter-model.js +1 -1
  96. package/dist/fields/index.d.ts +11 -3
  97. package/dist/fields/index.js +1 -1
  98. package/dist/fields/messages/extras.d.ts +108 -0
  99. package/dist/fields/messages/extras.js +1 -1
  100. package/dist/fields/messages/fields.d.ts +19 -0
  101. package/dist/fields/messages/fields.js +1 -1
  102. package/dist/fields/messages/record.d.ts +12 -0
  103. package/dist/fields/messages/record.js +1 -1
  104. package/dist/fields/messages/shell.d.ts +5 -0
  105. package/dist/fields/messages/shell.js +1 -1
  106. package/dist/fields/messages/viewbar.d.ts +35 -2
  107. package/dist/fields/messages/viewbar.js +1 -1
  108. package/dist/fields/messages.svelte.d.ts +179 -2
  109. package/dist/fields/phone-sheet.d.ts +6 -0
  110. package/dist/fields/phone-sheet.js +1 -0
  111. package/dist/fields/record-actions.d.ts +23 -0
  112. package/dist/fields/record-actions.js +1 -0
  113. package/dist/fields/record-menu.js +1 -1
  114. package/dist/fields/record-store.svelte.d.ts +6 -2
  115. package/dist/fields/record-store.svelte.js +1 -1
  116. package/dist/fields/sources.svelte.d.ts +8 -0
  117. package/dist/fields/summaries.js +1 -1
  118. package/dist/fields/timer-clock.svelte.d.ts +4 -0
  119. package/dist/fields/timer-clock.svelte.js +1 -0
  120. package/dist/fields/timer.d.ts +22 -0
  121. package/dist/fields/timer.js +1 -0
  122. package/dist/fields/tree-edit.d.ts +47 -0
  123. package/dist/fields/tree-edit.js +1 -0
  124. package/dist/fields/view-actions.d.ts +23 -0
  125. package/dist/fields/view-actions.js +1 -0
  126. package/dist/fields/view-model.d.ts +28 -3
  127. package/dist/fields/view-model.js +1 -1
  128. package/dist/fields/viewbar/FilterPanel.svelte +1 -1
  129. package/dist/fields/viewbar/GanttPanel.svelte +13 -3
  130. package/dist/fields/viewbar/GanttPanel.svelte.d.ts +3 -1
  131. package/dist/fields/viewbar/HideFieldsPanel.svelte +13 -2
  132. package/dist/fields/viewbar/ViewsMenu.svelte +69 -7
  133. package/dist/fields/viewbar/ViewsMenu.svelte.d.ts +4 -0
  134. package/dist/node/studio.js +2 -2
  135. package/dist/scheduler-config.d.ts +10 -0
  136. package/dist/studio/ui-components.generated.js +1 -1
  137. package/dist/version.d.ts +2 -2
  138. package/dist/version.js +1 -1
  139. package/dist/wc/CardMenu-D7hQ19pw.js +1 -0
  140. package/dist/wc/GridFind-CBZMU9J6.js +1 -0
  141. package/dist/wc/GridFind-DtGF31ks.js +1 -0
  142. package/dist/wc/GridFooter-DQq6qsE3.js +1 -0
  143. package/dist/wc/GridFooter-p4dE9uns.js +1 -0
  144. package/dist/wc/GridMenus-C4QZ5jnj.js +16 -0
  145. package/dist/wc/GridMenus-sqW-Y7S5.js +16 -0
  146. package/dist/wc/{PinSplitter-DyRfU4Wz.js → PinSplitter-3i65naKl.js} +2 -2
  147. package/dist/wc/{PinSplitter-1fKh3Bwq.js → PinSplitter-CLTE0bRc.js} +2 -2
  148. package/dist/wc/SvChartMenu-B9HnHez5.js +3 -0
  149. package/dist/wc/SvChartMenu-B_tNFTkg.js +1 -0
  150. package/dist/wc/SvDateRangeInput-BPlKigkO.js +1 -0
  151. package/dist/wc/SvDateRangeInput-Djc93m9x.js +1 -0
  152. package/dist/wc/SvDateTimePicker-BEAAe3-f.js +4 -0
  153. package/dist/wc/SvDateTimePicker-DgPz0cBp.js +4 -0
  154. package/dist/wc/{SvField-DUBHk-OY.js → SvField-JpRX8GTw.js} +2 -2
  155. package/dist/wc/SvGridCellEditor-BrFHlf2T.js +3 -0
  156. package/dist/wc/SvGridCellEditor-DK9sYePL.js +3 -0
  157. package/dist/wc/SvGridChart-BHlM2v-1.js +171 -0
  158. package/dist/wc/SvGridChart-CH3IBusu.js +171 -0
  159. package/dist/wc/SvGridChartBuilder-BPbq8uLi.js +7 -0
  160. package/dist/wc/SvGridChartBuilder-Dil4AM1y.js +8 -0
  161. package/dist/wc/SvGridChartPanel-BNX4ElVR.js +5 -0
  162. package/dist/wc/{SvGridChartPanel-BeRUjgjM.js → SvGridChartPanel-gLhTPhip.js} +3 -3
  163. package/dist/wc/{SvGridChartView-BG-qLHK8.js → SvGridChartView-CIogzaUy.js} +2 -2
  164. package/dist/wc/{SvGridChartView-s0BqDKZ9.js → SvGridChartView-TujvKvl6.js} +2 -2
  165. package/dist/wc/{SvGridDropdown-Co1FnDeB.js → SvGridDropdown-B1iMiyRf.js} +2 -2
  166. package/dist/wc/{SvGridDropdown-CbVCAI1K.js → SvGridDropdown-DauXQKai.js} +2 -2
  167. package/dist/wc/SvMenuList-DD8DyfUc.js +3 -0
  168. package/dist/wc/SvModal-BN4l4cAE.js +7 -0
  169. package/dist/wc/SvModal-CbOvVSpm.js +7 -0
  170. package/dist/wc/SvTabs-CGPGO9Vn.js +2 -0
  171. package/dist/wc/board-DS5OxhbF.js +23 -0
  172. package/dist/wc/board-view.svelte-DZiQ6CpS.js +1 -0
  173. package/dist/wc/{card-marks.svelte-DEmCHZCd.js → card-marks.svelte-Dym4W2PD.js} +1 -1
  174. package/dist/wc/chart-panel-messages-P6qAeRsp.js +1 -0
  175. package/dist/wc/client-CjVagnyk.js +3 -0
  176. package/dist/wc/client-DTHOsJhV.js +3 -0
  177. package/dist/wc/core-BhGMIO3G.js +1 -0
  178. package/dist/wc/date-format-DAQ3T50M.js +18 -0
  179. package/dist/wc/{date-format-C_AhjL_N.js → date-format-DYC0HfpK.js} +3 -3
  180. package/dist/wc/{dist-xwz8hbY3.js → dist-CU5leork.js} +1 -1
  181. package/dist/wc/{export-CCM-mATF.js → export-CzdwAsQD.js} +2 -2
  182. package/dist/wc/extent-Dg7_h_Do.js +1 -0
  183. package/dist/wc/gallery-Bij5kkwt.js +11 -0
  184. package/dist/wc/gantt-DkHZhrMS.js +114 -0
  185. package/dist/wc/grid-extension.svelte-BhPbpIEL.js +1 -0
  186. package/dist/wc/grid-extension.svelte-CgyuY7mw.js +1 -0
  187. package/dist/wc/{js-scroller.svelte-yqKev7S0.js → js-scroller.svelte-DhpfIqCT.js} +1 -1
  188. package/dist/wc/palette-DkaM8TCP.js +46 -0
  189. package/dist/wc/popover-sheets.svelte-DkljoAro.js +2 -0
  190. package/dist/wc/popover-sheets.svelte-ra8as21o.js +2 -0
  191. package/dist/wc/{range-commit-BeTBd6HK.js → range-commit-CGSw1ziH.js} +1 -1
  192. package/dist/wc/{range-commit-CKuvQBcr.js → range-commit-i3L3UjPV.js} +1 -1
  193. package/dist/wc/row-drag-DbVYQ0eO.js +1 -0
  194. package/dist/wc/row-drag-DevACK09.js +1 -0
  195. package/dist/wc/scheduler-B0UPSWNJ.js +159 -0
  196. package/dist/wc/scheduler-view.svelte-B4snqguw.js +1 -0
  197. package/dist/wc/{server-block-cache-CQ03vNXZ.js → server-block-cache-C9XwJyu2.js} +1 -1
  198. package/dist/wc/{server-row-model-DHuIO53Q.js → server-row-model-C-FV79zV.js} +1 -1
  199. package/dist/wc/sv-base-element.js +222 -81
  200. package/dist/wc/sv-sheet-element.js +54 -158
  201. package/dist/wc/{validate-Blppk1Na.js → validate--KGSlMvP.js} +1 -1
  202. package/package.json +3 -3
  203. package/dist/designer/assets/GridFind-PWsi9BvQ.js +0 -1
  204. package/dist/designer/assets/GridFooter-CsnWeWLs.js +0 -1
  205. package/dist/designer/assets/GridMenus-CDtNPHWk.js +0 -1
  206. package/dist/designer/assets/PinSplitter-66yg1L9j.js +0 -1
  207. package/dist/designer/assets/SvChartMenu-C0vyEINZ.js +0 -1
  208. package/dist/designer/assets/SvDateRangeInput-DsFP11vx.js +0 -1
  209. package/dist/designer/assets/SvDateTimePicker-BnjsZQZx.js +0 -1
  210. package/dist/designer/assets/SvGridCellEditor-BIyRn_Yg.js +0 -3
  211. package/dist/designer/assets/SvGridChart-BGMfcq66.js +0 -2
  212. package/dist/designer/assets/SvGridChartBuilder-5ICrrwzC.js +0 -1
  213. package/dist/designer/assets/SvGridChartPanel-Dcu3NUge.js +0 -3
  214. package/dist/designer/assets/SvGridChartView-T5tSN_S5.js +0 -1
  215. package/dist/designer/assets/SvGridDropdown-CvyfuIx7.js +0 -1
  216. package/dist/designer/assets/SvListBox-BZg4K2A3.js +0 -2
  217. package/dist/designer/assets/SvMenuList-COwzLYsg.js +0 -1
  218. package/dist/designer/assets/SvTabs-CmusmxDR.js +0 -1
  219. package/dist/designer/assets/date-format-rjHbB1Og.js +0 -1
  220. package/dist/designer/assets/grid-extension.svelte-BoCs0zu4.js +0 -1
  221. package/dist/designer/assets/index-Bmck0uP2.css +0 -1
  222. package/dist/designer/assets/index-client-C8cere9K.js +0 -2
  223. package/dist/designer/assets/row-drag-D5c8CRVe.js +0 -1
  224. package/dist/designer/assets/src--KGN0Gre.js +0 -1
  225. package/dist/designer/assets/src-B7p4SvJd.js +0 -35
  226. package/dist/wc/CardMenu-CvAlOSac.js +0 -1
  227. package/dist/wc/GridFind-BMXaq4Jr.js +0 -1
  228. package/dist/wc/GridFind-vvGzjjGo.js +0 -1
  229. package/dist/wc/GridFooter-DPREGhF6.js +0 -1
  230. package/dist/wc/GridFooter-DwsjY5ez.js +0 -1
  231. package/dist/wc/GridMenus-B762nokq.js +0 -16
  232. package/dist/wc/GridMenus-DuhBs36k.js +0 -16
  233. package/dist/wc/SvChartMenu-COh9NMzD.js +0 -3
  234. package/dist/wc/SvChartMenu-DblAgoRA.js +0 -1
  235. package/dist/wc/SvDateRangeInput-Fw2yWBDs.js +0 -1
  236. package/dist/wc/SvDateRangeInput-v249WzvQ.js +0 -1
  237. package/dist/wc/SvDateTimePicker-ggMYm4Pp.js +0 -4
  238. package/dist/wc/SvDateTimePicker-rbFCHbRQ.js +0 -4
  239. package/dist/wc/SvGridCellEditor-CODvFtka.js +0 -3
  240. package/dist/wc/SvGridCellEditor-N-j2l14U.js +0 -3
  241. package/dist/wc/SvGridChart-7UgF0l4W.js +0 -171
  242. package/dist/wc/SvGridChart-Cly6j21z.js +0 -171
  243. package/dist/wc/SvGridChartBuilder-CyVZ-lZQ.js +0 -7
  244. package/dist/wc/SvGridChartBuilder-D4BAUF_O.js +0 -8
  245. package/dist/wc/SvGridChartPanel-CeaYS-Vh.js +0 -5
  246. package/dist/wc/SvMenuList-QPKlIa2U.js +0 -3
  247. package/dist/wc/SvModal-CN10qQ5E.js +0 -7
  248. package/dist/wc/SvModal-y_CF6yXp.js +0 -7
  249. package/dist/wc/SvTabs-DhRSxzwH.js +0 -2
  250. package/dist/wc/board-view.svelte-BctMVU40.js +0 -1
  251. package/dist/wc/board-wkFIFCpH.js +0 -23
  252. package/dist/wc/chart-panel-messages-CvyfXnB0.js +0 -1
  253. package/dist/wc/client-BzI-P2yq.js +0 -3
  254. package/dist/wc/client-DA6JtMaz.js +0 -3
  255. package/dist/wc/core-SYwyf5FD.js +0 -1
  256. package/dist/wc/custom-filter-Dp8JxlQu.js +0 -2
  257. package/dist/wc/date-format-DFerRDR7.js +0 -18
  258. package/dist/wc/extent-CcmrrtGQ.js +0 -1
  259. package/dist/wc/gallery-vM0PqrWd.js +0 -11
  260. package/dist/wc/gantt-BlvgFAt_.js +0 -114
  261. package/dist/wc/grid-extension.svelte-CVqh736Q.js +0 -1
  262. package/dist/wc/grid-extension.svelte-DvHfl92l.js +0 -1
  263. package/dist/wc/palette-BPzVof_y.js +0 -46
  264. package/dist/wc/row-drag-DD3TudN_.js +0 -1
  265. package/dist/wc/row-drag-DLQMyiV3.js +0 -1
  266. package/dist/wc/scheduler-D2ksQuvM.js +0 -153
  267. package/dist/wc/scheduler-view.svelte-BFCITmR8.js +0 -1
  268. package/dist/wc/svelte-virtualizer.svelte-DYCT_xZg.js +0 -2
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";import{conditionCount,isGroup,isComplete}from"./filter-model";import{fieldColumns,gridOf,groupLeaves,leafFilter,primaryIdOf}from"./grid-access";import{findFieldUser,getCurrentUser,getLinkedTable,linkedRows}from"./sources.svelte";import{PLAIN_STATE,applyColor,applyGanttSettings,applyView,boardConfig,captureView,galleryConfig,colorSettingOf,newViewId,viewTypeInfo}from"./view-model";import{groupRules,userSorts}from"./viewbar/sort-state";import{recordHeightOf,syncGroupRowHeight}from"./row-height";import HideFieldsPanel from"./viewbar/HideFieldsPanel.svelte";import FilterPanel from"./viewbar/FilterPanel.svelte";import SortPanel from"./viewbar/SortPanel.svelte";import ColorPanel from"./viewbar/ColorPanel.svelte";import ChartPanel from"./viewbar/ChartPanel.svelte";import GanttPanel from"./viewbar/GanttPanel.svelte";import ListPanel from"./viewbar/ListPanel.svelte";import FormBuilder from"./viewbar/FormBuilder.svelte";import ViewsMenu from"./viewbar/ViewsMenu.svelte";import RecordView from"./RecordView.svelte";import{closeRecord,getRecordRequest}from"./editor-request.svelte";import DeleteRecordConfirm from"./DeleteRecordConfirm.svelte";import{askDeleteRecord,getDeleteRecordRequest}from"./record-delete.svelte";import{clearBarRequest,getBarRequest,registerBar}from"./bar-request.svelte";import{bm,bmCount}from"./messages.svelte";let{api,views=$bindable([{id:"grid",name:bm("viewbar.defaultViewName"),type:"grid"}]),activeView=$bindable(""),onViewsChange,onViewRemoved,viewTypes,automations=null,changed=null,lockViews=true,manageViews=true,viewList=true,rowHeights}=$props();const heights=$derived(rowHeights??[{label:bm("viewbar.rowShort"),height:34},{label:bm("viewbar.rowMedium"),height:56},{label:bm("viewbar.rowTall"),height:88},{label:bm("viewbar.rowExtraTall"),height:128}]);const ctrl=$derived(api?gridOf(api):void 0);const me=$derived(getCurrentUser()?.id);const visible=$derived(views.filter(v=>!v.personal||!me||v.personal===me));const active=$derived(visible.find(v=>v.id===activeView)??visible[0]??views[0]);const locked=$derived(!!active?.locked);let lockedDirty=$state(false);let lockedBaseline=null;const lockTitle=$derived.by(()=>{const by=active?.lockedBy?findFieldUser(active.lockedBy)?.name:void 0;return by?bm("viewbar.lockedTitleBy",{name:by}):bm("viewbar.lockedTitle")});const types=$derived(viewTypes??["grid","kanban","calendar","gantt"]);const linkNames=(table,value)=>{const t=getLinkedTable(table);return t?linkedRows(t,value).map(r=>String(r[t.primaryField]??"")):[]};const primaryField=$derived.by(()=>{if(!ctrl)return void 0;const id=primaryIdOf(ctrl);return fieldColumns(ctrl).find(c=>c.id===id)?.field});let appliedId=null;let appliedKey="";let applying=false;let showSeq=0;let showing=null;let viewShown=$state(0);let takingUp=false;const keyOf=v=>JSON.stringify(v);function setViews(next){views=next;const shown=next.find(v=>v.id===appliedId);if(shown)appliedKey=keyOf(shown);onViewsChange?.(next)}async function ready(t){if(t==="kanban")(await import("../board")).enableBoardView();else if(t==="calendar")(await import("../scheduler")).enableSchedulerView();else if(t==="gallery")(await import("../gallery")).enableGalleryView();else if(t==="gantt")(await import("../gantt")).enableGanttView()}async function show(view){const seq=showSeq+=1;appliedId=view.id;appliedKey=keyOf(view);applying=true;lockedDirty=false;lockedBaseline=null;const another=showing!==view.id;showing=view.id;if(another)ctrl?.props.baseFeed?.forgetCount?.();await ready(view.type);if(seq!==showSeq)return;applying=false;if(!ctrl)return;if(another){lastServerCount=null;takingUp=true;ctrl.props.rowModel?.letRowsGo?.();viewShown+=1;setTimeout(()=>{takingUp=false;viewShown+=1})}applyView(ctrl,api,view,{primaryField,linkNames});colorSetting=view.color??colorSettingOf(ctrl)}const capture=v=>captureView(ctrl,api,{...v,color:$state.snapshot(colorSetting)});const keptViews=()=>views.map(v=>v.id===active?.id&&!v.locked?capture(v):v);function switchTo(id){viewsOpen=false;if(!ctrl||!active||id===active.id)return;const next=keptViews();const target=next.find(v=>v.id===id);if(!target)return;setViews(next);activeView=id;void show(target)}function create(partial){if(!ctrl||!active)return;const select=columns.find(c=>c.fieldType==="singleSelect");const timed=partial.type==="calendar"||partial.type==="gantt";const view={...partial,id:newViewId(),state:{...PLAIN_STATE},color:timed&&select?{mode:"field",field:select.field}:{mode:"none"}};const next=[...keptViews(),view];setViews(next);activeView=view.id;void show(view);viewsOpen=false}function duplicate(id){if(!ctrl)return;const src=id===active?.id&&!active.locked?capture(active):views.find(v=>v.id===id);if(!src)return;const{locked:_locked,lockedBy:_by,...open}=JSON.parse(JSON.stringify(src));const copy={...open,id:newViewId(),name:bm("viewbar.viewCopy",{name:src.name}),...!manageViews&&me?{personal:me}:{}};const at=views.findIndex(v=>v.id===id);const next=[...views];next.splice(at+1,0,copy);setViews(next)}function remove(id){if(views.length<2||views.find(v=>v.id===id)?.locked)return;const at=views.findIndex(v=>v.id===id);const gone=id===active?.id?capture(views[at]):views[at];const next=views.filter(v=>v.id!==id);setViews(next);if(gone)onViewRemoved?.(gone,at);if(id===active?.id){const first=next.find(v=>!v.personal||!me||v.personal===me)??next[0];activeView=first.id;void show(first)}}function toggleLock(id){if(!lockViews)return;setViews(views.map(v=>{if(v.id!==id)return v;if(v.locked){const{locked:_locked,lockedBy:_by,...open}=v;return open}const kept=v.id===active?.id?capture(v):v;return{...kept,locked:true,...me?{lockedBy:me}:{}}}));lockedDirty=false;lockedBaseline=null}function resetLocked(){if(active)void show(active)}const rename=(id,name)=>setViews(views.map(v=>v.id===id?{...v,name}:v));function setGantt(next){if(!ctrl||!active)return;const updated={...active,...next};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}const NO_CHART={kind:"bar",x:""};const setChart=chart=>setViews(views.map(v=>v.id===active?.id?{...v,chart}:v));const setList=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));const setForm=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));let formOpen=$state(false);$effect(()=>{if(!ctrl||!active)return;const view=active;const key=keyOf(view);untrack(()=>{if(!activeView)activeView=view.id;if(view.id===appliedId&&key===appliedKey)return;if(appliedId===null&&!(view.state||view.type!=="grid"||view.color||view.rowHeight!=null)){appliedId=view.id;appliedKey=key;return}void show(view)})});$effect(()=>{if(!ctrl||!active)return;const snapshot=JSON.stringify([ctrl.gridStateVersion,api.getState(),recordHeightOf(api.getOption("rowHeight")),effectiveColor]);const view=active;const timer=setTimeout(()=>{untrack(()=>{if(applying||view.id!==appliedId||keyOf(view)!==appliedKey)return;const kept=capture(view);const before=JSON.stringify([view.state,view.rowHeight,view.color]);const after=JSON.stringify([kept.state,kept.rowHeight,kept.color]);if(view.locked){const{expanded:_open,...shown}=kept.state??{};const now=JSON.stringify([shown,kept.rowHeight,kept.color]);if(lockedBaseline===null)lockedBaseline=now;else lockedDirty=now!==lockedBaseline}else if(before!==after)setViews(views.map(v=>v.id===view.id?kept:v))})},400);void snapshot;return()=>clearTimeout(timer)});let viewsOpen=$state(false);let panel=$state(null);function setPanel(p,open){if(open)panel=p;else if(panel===p)panel=null}$effect(()=>{if(ctrl)return registerBar(ctrl)});$effect(()=>{const r=getBarRequest();if(!r||r.ctrl!==ctrl)return;untrack(()=>{if(!locked)panel=r.panel;clearBarRequest()})});let colorSetting=$state({mode:"none"});$effect(()=>{if(ctrl)untrack(()=>colorSetting=active?.color??colorSettingOf(ctrl))});function setColor(s){colorSetting=s;if(ctrl)applyColor(ctrl,s,linkNames);if(ctrl&&active&&(active.type==="calendar"||active.type==="gantt")){const updated={...active,color:$state.snapshot(s)};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}}const columns=$derived(ctrl?fieldColumns(ctrl):[]);const hiddenCount=$derived(columns.filter(c=>!c.visible).length);const filter=$derived.by(()=>{const f=ctrl?.advancedFilter;return f?.kind==="fieldFilter"?f:null});const filterCount=$derived(conditionCount(filter));const filterLabel=$derived.by(()=>{if(!filter||!filterCount)return bm("viewbar.filter");const ids=new Set;for(const c of filter.conditions)for(const x of isGroup(c)?c.conditions:[c])if(isComplete(x))ids.add(x.column);if(ids.size===1){const header=columns.find(c=>ids.has(c.id))?.header;return header!=null?bm("viewbar.filteredBy",{field:header}):bmCount("viewbar.filteredByFields",1)}return bmCount("viewbar.filteredByFields",ids.size)});const groupCount=$derived(ctrl?groupRules(ctrl).length:0);const sortCount=$derived(ctrl?userSorts(ctrl).length:0);const effectiveColor=$derived(ctrl?colorSettingOf(ctrl,colorSetting):colorSetting);const colorLabel=$derived.by(()=>{if(effectiveColor.mode==="field"){const header=columns.find(c=>c.field===effectiveColor.field)?.header;return header!=null?bm("viewbar.coloredBy",{field:header}):bm("viewbar.color")}return effectiveColor.mode==="conditions"&&effectiveColor.rules.length?bm("viewbar.coloredByConditions"):bm("viewbar.color")});const rowHeight=$derived(recordHeightOf(api?.getOption?.("rowHeight"))??0);let heightOpen=$state(false);const shownHeight=$derived(heights.some(h=>h.height===rowHeight)?rowHeight:heights[0]?.height);$effect(()=>{const grouped=groupCount>0;void rowHeight;void ctrl?.props?.rowModel;untrack(()=>syncGroupRowHeight(ctrl,api,grouped))});let lastServerCount=null;const records=$derived.by(()=>{void viewShown;if(!ctrl)return 0;if(ctrl.props.baseFeed&&!ctrl.props.rowModel&&active?.type!=="form")return ctrl.props.baseFeed.knownCount();const model=ctrl.props.rowModel;if(model?.getState){void ctrl.allRows;const own=takingUp?null:model.recordCount?.()??model.getState().rowCount;if(own!=null)lastServerCount=own;return lastServerCount}const tops=(ctrl.allRows??[]).filter(r=>(r.depth??0)===0&&!r.__treeRow&&typeof r.getCanExpand==="function"&&r.getCanExpand()&&r.leafCount!=null);if(!groupCount||!tops.length)return api.getDisplayedRows().length;const keep=leafFilter(ctrl);return keep?tops.reduce((n,r)=>n+groupLeaves(r,keep).length,0):tops.reduce((n,r)=>n+(r.leafCount??0),0)});let searching=$state(false);const quickSearch=$derived(active?.type!=="grid"||!!ctrl?.props?.rowModel||!!ctrl?.props?.basePhone);async function openSearch(){if(quickSearch){searching=true;return}ctrl.findOpen=true;await tick();const root=ctrl.scrollContainer?.closest(".sv-grid-root");for(let tries=0;tries<40;tries+=1){const box=root?.querySelector(".sv-grid-find-input");if(box)return box.focus();await new Promise(r=>setTimeout(r,25))}}function focusBox(node){node.focus()}const showFocused=e=>e.target.scrollIntoView?.({block:"nearest",inline:"nearest"});let searchButton=$state(null);let galleryKey="";$effect(()=>{if(!ctrl||active?.type!=="gallery"){galleryKey="";return}const view=active;const cfg=galleryConfig(ctrl,api,view);const key=JSON.stringify([cfg.coverField,cfg.titleField,cfg.cardFields]);if(key===galleryKey)return;galleryKey=key;untrack(()=>api.setOption("gallery",cfg))});let boardKey="";$effect(()=>{if(!ctrl||active?.type!=="kanban"){boardKey="";return}const cfg=boardConfig(ctrl,api,active);if(!cfg)return;const key=JSON.stringify([cfg.groupBy,cfg.titleField,cfg.cardFields,cfg.virtualized,cfg.lanes.map(l=>[l.title,l.color])]);if(key===boardKey)return;boardKey=key;untrack(()=>api.setOption("board",cfg))});const noHeader=$derived.by(()=>{const t=active?.type;return t==="kanban"||t==="calendar"||t==="gantt"||t==="gallery"||!!api?.getOption?.("gallery")});const record=$derived.by(()=>{const r=getRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const deleting=$derived.by(()=>{const r=getDeleteRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const has=$derived.by(()=>{const t=active?.type??"grid";if(t==="form")return new Set(manageViews?["form"]:[]);if(t==="dashboard")return new Set;if(t==="grid")return new Set(["hide","filter","group","sort","color","height"]);if(t==="chart")return new Set(["filter","chart"]);if(t==="gantt")return new Set(["hide","filter","sort","color","gantt"]);if(t==="calendar")return new Set(["hide","filter","sort","color"]);if(t==="list")return new Set(["hide","filter","group","sort","list"]);if(t==="inbox")return new Set(["hide","filter","sort","list"]);return new Set(["hide","filter","sort"])});const bare=$derived(!viewList&&!locked&&!changed&&!automations&&has.size===0);const ICON={hide:"M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 5.1A9.8 9.8 0 0 1 12 5c5 0 9 5 10 7a13.4 13.4 0 0 1-3 3.9M6.6 6.6A13.5 13.5 0 0 0 2 12c1 2 5 7 10 7a9.6 9.6 0 0 0 4.4-1.1",filter:"M4 5h16l-6 7v6l-4 2v-8z",group:"M4 5h16M4 10h10M4 15h16M4 20h10",sort:"M7 4v16M3 16l4 4 4-4M17 20V4M13 8l4-4 4 4",color:"M12 3l6 7a6.5 6.5 0 1 1-12 0l6-7z",chart:"M4 20h16M6 20V11M11 20V5M16 20v-7",gantt:"M4 5h9M7 10h11M10 15h8M4 20h16",height:"M4 6h16M4 12h16M4 18h16M20 3v18",search:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4",chevron:"M6 9l6 6 6-6",bolt:"M13 3L5 14h6l-1 7 8-11h-6z",lock:"M6 11h12v9H6zM8 11V8a4 4 0 0 1 8 0v3",person:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0"};
2
+ import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";import{conditionCount,isGroup,isComplete}from"./filter-model";import{dataRows,fieldColumns,gridOf,groupLeaves,leafFilter,primaryIdOf}from"./grid-access";import{barcodeScanSupported,scanBarcode}from"./barcode-scan";import{findFieldUser,getCurrentUser,getLinkedTable,linkedRows}from"./sources.svelte";import{PLAIN_STATE,applyColor,applyGanttSettings,applyView,boardConfig,captureView,galleryConfig,colorSettingOf,newViewId,viewTypeInfo}from"./view-model";import{groupRules,userSorts}from"./viewbar/sort-state";import{recordHeightOf,syncGroupRowHeight}from"./row-height";import HideFieldsPanel from"./viewbar/HideFieldsPanel.svelte";import FilterPanel from"./viewbar/FilterPanel.svelte";import SortPanel from"./viewbar/SortPanel.svelte";import ColorPanel from"./viewbar/ColorPanel.svelte";import ChartPanel from"./viewbar/ChartPanel.svelte";import GanttPanel from"./viewbar/GanttPanel.svelte";import ListPanel from"./viewbar/ListPanel.svelte";import FormBuilder from"./viewbar/FormBuilder.svelte";import ViewsMenu from"./viewbar/ViewsMenu.svelte";import RecordView from"./RecordView.svelte";import{closeRecord,getRecordRequest,closeFieldEditor,getFieldEditorRequest,getDeleteFieldRequest,askDeleteField,openRecord}from"./editor-request.svelte";import FieldEditor from"./FieldEditor.svelte";import DeleteFieldConfirm from"./DeleteFieldConfirm.svelte";import DeleteRecordConfirm from"./DeleteRecordConfirm.svelte";import{askDeleteRecord,getDeleteRecordRequest}from"./record-delete.svelte";import{clearBarRequest,getBarRequest,registerBar}from"./bar-request.svelte";import{bm,bmCount}from"./messages.svelte";let{api,views=$bindable([{id:"grid",name:bm("viewbar.defaultViewName"),type:"grid"}]),activeView=$bindable(""),onViewsChange,onViewRemoved,viewTypes,automations=null,changed=null,lockViews=true,manageViews=true,viewList=true,rowHeights,host=null,tableId}=$props();let barEl=$state(null);$effect(()=>{const el=barEl;const into=host;if(!el||!into)return;const home=document.createComment("");el.before(home);into.appendChild(el);return()=>{if(home.parentNode){home.after(el);home.remove()}else el.remove()}});const heights=$derived(rowHeights??[{label:bm("viewbar.rowShort"),height:34},{label:bm("viewbar.rowMedium"),height:56},{label:bm("viewbar.rowTall"),height:88},{label:bm("viewbar.rowExtraTall"),height:128}]);const ctrl=$derived(api?gridOf(api):void 0);const me=$derived(getCurrentUser()?.id);const visible=$derived(views.filter(v=>!v.personal||!me||v.personal===me));const active=$derived(visible.find(v=>v.id===activeView)??visible[0]??views[0]);const locked=$derived(!!active?.locked);let lockedDirty=$state(false);let lockedBaseline=null;const lockTitle=$derived.by(()=>{const by=active?.lockedBy?findFieldUser(active.lockedBy)?.name:void 0;return by?bm("viewbar.lockedTitleBy",{name:by}):bm("viewbar.lockedTitle")});const types=$derived(viewTypes??["grid","kanban","calendar","gantt"]);const linkNames=(table,value)=>{const t=getLinkedTable(table);return t?linkedRows(t,value).map(r=>String(r[t.primaryField]??"")):[]};const primaryField=$derived.by(()=>{if(!ctrl)return void 0;const id=primaryIdOf(ctrl);return fieldColumns(ctrl).find(c=>c.id===id)?.field});let appliedId=null;let appliedKey="";let applying=false;let showSeq=0;let showing=null;let viewShown=$state(0);let takingUp=false;const keyOf=v=>JSON.stringify(v);function setViews(next){views=next;const shown=next.find(v=>v.id===appliedId);if(shown)appliedKey=keyOf(shown);onViewsChange?.(next)}async function ready(t){if(t==="kanban")(await import("../board")).enableBoardView();else if(t==="calendar"||t==="timeline")(await import("../scheduler")).enableSchedulerView();else if(t==="gallery")(await import("../gallery")).enableGalleryView();else if(t==="gantt")(await import("../gantt")).enableGanttView()}async function show(view){const seq=showSeq+=1;appliedId=view.id;appliedKey=keyOf(view);applying=true;lockedDirty=false;lockedBaseline=null;const another=showing!==view.id;showing=view.id;if(another)ctrl?.props.baseFeed?.forgetCount?.();await ready(view.type);if(seq!==showSeq)return;applying=false;if(!ctrl)return;if(another){lastServerCount=null;takingUp=true;ctrl.props.rowModel?.letRowsGo?.();viewShown+=1;setTimeout(()=>{takingUp=false;viewShown+=1})}applyView(ctrl,api,view,{primaryField,linkNames});colorSetting=view.color??colorSettingOf(ctrl)}const capture=v=>captureView(ctrl,api,{...v,color:$state.snapshot(colorSetting)});const keptViews=()=>views.map(v=>v.id===active?.id&&!v.locked?capture(v):v);function switchTo(id){viewsOpen=false;if(!ctrl||!active||id===active.id)return;const next=keptViews();const target=next.find(v=>v.id===id);if(!target)return;setViews(next);activeView=id;void show(target)}function create(partial){if(!ctrl||!active)return;const select=columns.find(c=>c.fieldType==="singleSelect");const timed=partial.type==="calendar"||partial.type==="timeline"||partial.type==="gantt";const view={...partial,id:newViewId(),state:{...PLAIN_STATE},color:timed&&select?{mode:"field",field:select.field}:{mode:"none"}};const next=[...keptViews(),view];setViews(next);activeView=view.id;void show(view);viewsOpen=false}function duplicate(id){if(!ctrl)return;const src=id===active?.id&&!active.locked?capture(active):views.find(v=>v.id===id);if(!src)return;const{locked:_locked,lockedBy:_by,...open}=JSON.parse(JSON.stringify(src));const copy={...open,id:newViewId(),name:bm("viewbar.viewCopy",{name:src.name}),...!manageViews&&me?{personal:me}:{}};const at=views.findIndex(v=>v.id===id);const next=[...views];next.splice(at+1,0,copy);setViews(next)}function remove(id){if(views.length<2||views.find(v=>v.id===id)?.locked)return;const at=views.findIndex(v=>v.id===id);const gone=id===active?.id?capture(views[at]):views[at];const next=views.filter(v=>v.id!==id);setViews(next);if(gone)onViewRemoved?.(gone,at);if(id===active?.id){const first=next.find(v=>!v.personal||!me||v.personal===me)??next[0];activeView=first.id;void show(first)}}function toggleLock(id){if(!lockViews)return;setViews(views.map(v=>{if(v.id!==id)return v;if(v.locked){const{locked:_locked,lockedBy:_by,...open}=v;return open}const kept=v.id===active?.id?capture(v):v;return{...kept,locked:true,...me?{lockedBy:me}:{}}}));lockedDirty=false;lockedBaseline=null}function resetLocked(){if(active)void show(active)}const rename=(id,name)=>setViews(views.map(v=>v.id===id?{...v,name}:v));const setSection=(id,section)=>setViews(views.map(v=>{if(v.id!==id)return v;const{section:_was,...rest}=v;return section?{...rest,section:section.slice(0,60)}:rest}));function setGantt(next){if(!ctrl||!active)return;const updated={...active,...next};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}const NO_CHART={kind:"bar",x:""};const setChart=chart=>setViews(views.map(v=>v.id===active?.id?{...v,chart}:v));const setList=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));const setForm=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));let formOpen=$state(false);$effect(()=>{if(!ctrl||!active)return;const view=active;const key=keyOf(view);untrack(()=>{if(!activeView)activeView=view.id;if(view.id===appliedId&&key===appliedKey)return;if(appliedId===null&&!(view.state||view.type!=="grid"||view.color||view.rowHeight!=null)){appliedId=view.id;appliedKey=key;return}void show(view)})});$effect(()=>{if(!ctrl||!active)return;const snapshot=JSON.stringify([ctrl.gridStateVersion,api.getState(),recordHeightOf(api.getOption("rowHeight")),effectiveColor]);const view=active;const timer=setTimeout(()=>{untrack(()=>{if(applying||view.id!==appliedId||keyOf(view)!==appliedKey)return;const kept=capture(view);const before=JSON.stringify([view.state,view.rowHeight,view.color]);const after=JSON.stringify([kept.state,kept.rowHeight,kept.color]);if(view.locked){const{expanded:_open,...shown}=kept.state??{};const now=JSON.stringify([shown,kept.rowHeight,kept.color]);if(lockedBaseline===null)lockedBaseline=now;else lockedDirty=now!==lockedBaseline}else if(before!==after)setViews(views.map(v=>v.id===view.id?kept:v))})},400);void snapshot;return()=>clearTimeout(timer)});let viewsOpen=$state(false);let panel=$state(null);function setPanel(p,open){if(open)panel=p;else if(panel===p)panel=null}$effect(()=>{if(ctrl)return registerBar(ctrl)});$effect(()=>{const r=getBarRequest();if(!r||r.ctrl!==ctrl)return;untrack(()=>{if(!locked)panel=r.panel;clearBarRequest()})});let colorSetting=$state({mode:"none"});$effect(()=>{if(ctrl)untrack(()=>colorSetting=active?.color??colorSettingOf(ctrl))});function setColor(s){colorSetting=s;if(ctrl)applyColor(ctrl,s,linkNames);if(ctrl&&active&&(active.type==="calendar"||active.type==="timeline"||active.type==="gantt")){const updated={...active,color:$state.snapshot(s)};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}}const columns=$derived(ctrl?fieldColumns(ctrl):[]);const hiddenCount=$derived(columns.filter(c=>!c.visible).length);const filter=$derived.by(()=>{const f=ctrl?.advancedFilter;return f?.kind==="fieldFilter"?f:null});const filterCount=$derived(conditionCount(filter));const filterLabel=$derived.by(()=>{if(!filter||!filterCount)return bm("viewbar.filter");const ids=new Set;for(const c of filter.conditions)for(const x of isGroup(c)?c.conditions:[c])if(isComplete(x))ids.add(x.column);if(ids.size===1){const header=columns.find(c=>ids.has(c.id))?.header;return header!=null?bm("viewbar.filteredBy",{field:header}):bmCount("viewbar.filteredByFields",1)}return bmCount("viewbar.filteredByFields",ids.size)});const groupCount=$derived(ctrl?groupRules(ctrl).length:0);const sortCount=$derived(ctrl?userSorts(ctrl).length:0);const effectiveColor=$derived(ctrl?colorSettingOf(ctrl,colorSetting):colorSetting);const colorLabel=$derived.by(()=>{if(effectiveColor.mode==="field"){const header=columns.find(c=>c.field===effectiveColor.field)?.header;return header!=null?bm("viewbar.coloredBy",{field:header}):bm("viewbar.color")}return effectiveColor.mode==="conditions"&&effectiveColor.rules.length?bm("viewbar.coloredByConditions"):bm("viewbar.color")});const rowHeight=$derived(recordHeightOf(api?.getOption?.("rowHeight"))??0);let heightOpen=$state(false);const shownHeight=$derived(heights.some(h=>h.height===rowHeight)?rowHeight:heights[0]?.height);$effect(()=>{const grouped=groupCount>0;void rowHeight;void ctrl?.props?.rowModel;untrack(()=>syncGroupRowHeight(ctrl,api,grouped))});let lastServerCount=null;const records=$derived.by(()=>{void viewShown;if(!ctrl)return 0;if(ctrl.props.baseFeed&&!ctrl.props.rowModel&&active?.type!=="form")return ctrl.props.baseFeed.knownCount();const model=ctrl.props.rowModel;if(model?.getState){void ctrl.allRows;const own=takingUp?null:model.recordCount?.()??model.getState().rowCount;if(own!=null)lastServerCount=own;return lastServerCount}const all=ctrl.allRows??[];const trees=all.filter(r=>(r.depth??0)===0&&r.__treeRow);if(trees.length)return trees.reduce((n,r)=>n+(r.treeRecords??1+(r.leafCount??0)),0);const tops=all.filter(r=>(r.depth??0)===0&&!r.__treeRow&&typeof r.getCanExpand==="function"&&r.getCanExpand()&&r.leafCount!=null);if(!groupCount||!tops.length)return api.getDisplayedRows().length;const keep=leafFilter(ctrl);return keep?tops.reduce((n,r)=>n+groupLeaves(r,keep).length,0):tops.reduce((n,r)=>n+(r.leafCount??0),0)});let searching=$state(false);const quickSearch=$derived(active?.type!=="grid"||!!ctrl?.props?.rowModel||!!ctrl?.props?.basePhone);async function openSearch(){if(quickSearch){searching=true;return}ctrl.findOpen=true;await tick();const root=ctrl.scrollContainer?.closest(".sv-grid-root");for(let tries=0;tries<40;tries+=1){const box=root?.querySelector(".sv-grid-find-input");if(box)return box.focus();await new Promise(r=>setTimeout(r,25))}}function focusBox(node){node.focus()}const showFocused=e=>e.target.scrollIntoView?.({block:"nearest",inline:"nearest"});let searchButton=$state(null);const canScan=$derived(quickSearch&&barcodeScanSupported());async function scanToFind(){const code=await scanBarcode();if(!code||!ctrl)return;ctrl.globalFilter=code;searching=true;await tick();await new Promise(r=>setTimeout(r,60));const found=dataRows(ctrl);if(found.length===1)openRecord({ctrl,rowId:found[0].id})}let galleryKey="";$effect(()=>{if(!ctrl||active?.type!=="gallery"){galleryKey="";return}const view=active;const cfg=galleryConfig(ctrl,api,view);const key=JSON.stringify([cfg.coverField,cfg.titleField,cfg.cardFields]);if(key===galleryKey)return;galleryKey=key;untrack(()=>api.setOption("gallery",cfg))});let boardKey="";$effect(()=>{if(!ctrl||active?.type!=="kanban"){boardKey="";return}const cfg=boardConfig(ctrl,api,active);if(!cfg)return;const key=JSON.stringify([cfg.groupBy,cfg.titleField,cfg.cardFields,cfg.virtualized,cfg.lanes.map(l=>[l.title,l.color])]);if(key===boardKey)return;boardKey=key;untrack(()=>api.setOption("board",cfg))});const noHeader=$derived.by(()=>{const t=active?.type;return t==="kanban"||t==="calendar"||t==="timeline"||t==="gantt"||t==="gallery"||!!api?.getOption?.("gallery")});const record=$derived.by(()=>{const r=getRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const fieldEditing=$derived.by(()=>{const r=getFieldEditorRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const fieldDeleting=$derived.by(()=>{const r=getDeleteFieldRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});$effect(()=>{if(ctrl&&getFieldEditorRequest()?.ctrl===ctrl)untrack(()=>panel=null)});const deleting=$derived.by(()=>{const r=getDeleteRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const has=$derived.by(()=>{const t=active?.type??"grid";if(t==="form")return new Set(manageViews?["form"]:[]);if(t==="dashboard")return new Set;if(t==="grid")return new Set(["hide","filter","group","sort","color","height"]);if(t==="chart")return new Set(["filter","chart"]);if(t==="gantt"||t==="timeline")return new Set(["hide","filter","sort","color","gantt"]);if(t==="calendar")return new Set(["hide","filter","sort","color"]);if(t==="list")return new Set(["hide","filter","group","sort","list"]);if(t==="inbox")return new Set(["hide","filter","sort","list"]);return new Set(["hide","filter","sort"])});const bare=$derived(!viewList&&!locked&&!changed&&!automations&&has.size===0);const ICON={hide:"M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 5.1A9.8 9.8 0 0 1 12 5c5 0 9 5 10 7a13.4 13.4 0 0 1-3 3.9M6.6 6.6A13.5 13.5 0 0 0 2 12c1 2 5 7 10 7a9.6 9.6 0 0 0 4.4-1.1",filter:"M4 5h16l-6 7v6l-4 2v-8z",group:"M4 5h16M4 10h10M4 15h16M4 20h10",sort:"M7 4v16M3 16l4 4 4-4M17 20V4M13 8l4-4 4 4",color:"M12 3l6 7a6.5 6.5 0 1 1-12 0l6-7z",chart:"M4 20h16M6 20V11M11 20V5M16 20v-7",gantt:"M4 5h9M7 10h11M10 15h8M4 20h16",height:"M4 6h16M4 12h16M4 18h16M20 3v18",search:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4",chevron:"M6 9l6 6 6-6",bolt:"M13 3L5 14h6l-1 7 8-11h-6z",lock:"M6 11h12v9H6zM8 11V8a4 4 0 0 1 8 0v3",person:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0"};
3
3
  </script>
4
4
 
5
5
  {#snippet glyph(path: string, size = 15)}
@@ -8,7 +8,7 @@ import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";i
8
8
 
9
9
  {#if ctrl && active && !bare}
10
10
 
11
- <div class="sv-fvb" role="toolbar" aria-label={bm('viewbar.viewSettings')} onfocusin={showFocused}>
11
+ <div class="sv-fvb" role="toolbar" aria-label={bm('viewbar.viewSettings')} onfocusin={showFocused} bind:this={barEl}>
12
12
  {#if viewList}
13
13
  <SvPopover bind:open={viewsOpen} arrow={false} placement="bottom-start" ariaLabel={bm('viewbar.views')}>
14
14
  {#snippet anchor()}
@@ -29,9 +29,11 @@ import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";i
29
29
  onSwitch={switchTo}
30
30
  onCreate={create}
31
31
  onRename={rename}
32
+ onSection={manageViews ? setSection : undefined}
32
33
  onDuplicate={duplicate}
33
34
  onDelete={remove}
34
35
  onLock={toggleLock}
36
+ {tableId}
35
37
  />
36
38
  </SvPopover>
37
39
  {/if}
@@ -48,7 +50,7 @@ import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";i
48
50
  {#if has.has('hide')}
49
51
  <SvPopover open={panel === 'hide'} onOpenChange={(o) => setPanel('hide', o)} arrow={false} placement="bottom-start" ariaLabel={bm('viewbar.hideFields')}>
50
52
  {#snippet anchor()}
51
- <button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn" class:is-set={hiddenCount > 0} aria-haspopup="dialog" aria-expanded={panel === 'hide'}>
53
+ <button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn sv-fvb-hide" class:is-set={hiddenCount > 0} aria-haspopup="dialog" aria-expanded={panel === 'hide'}>
52
54
  {@render glyph(ICON.hide)}<span>{hiddenCount ? bmCount('viewbar.hiddenFields', hiddenCount) : bm('viewbar.hideFields')}</span>
53
55
  </button>
54
56
  {/snippet}
@@ -102,9 +104,10 @@ import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";i
102
104
  {/if}
103
105
  {#if has.has('gantt') && active}
104
106
  {@const settings = active}
105
- <SvPopover open={panel === 'gantt'} onOpenChange={(o) => setPanel('gantt', o)} arrow={false} placement="bottom-start" ariaLabel={bm('viewbar.customizeTimeline')}>
107
+ {@const what = active.type === 'timeline' ? bm('viewbar.customizeTimeline') : bm('viewbar.customizeGantt')}
108
+ <SvPopover open={panel === 'gantt'} onOpenChange={(o) => setPanel('gantt', o)} arrow={false} placement="bottom-start" ariaLabel={what}>
106
109
  {#snippet anchor()}
107
- <button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn" aria-haspopup="dialog" aria-expanded={panel === 'gantt'}>{@render glyph(ICON.gantt)}<span>{bm('viewbar.customizeTimeline')}</span></button>
110
+ <button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn" aria-haspopup="dialog" aria-expanded={panel === 'gantt'}>{@render glyph(ICON.gantt)}<span>{what}</span></button>
108
111
  {/snippet}
109
112
  <GanttPanel {ctrl} view={settings} onChange={setGantt} />
110
113
  </SvPopover>
@@ -184,6 +187,11 @@ import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";i
184
187
  {@render glyph(ICON.search)}
185
188
  </button>
186
189
  {/if}
190
+ {#if canScan}
191
+ <button type="button" class="sv-fvb-btn sv-fvb-icon-only sv-fvb-scan" aria-label={bm('viewbar.scanToFind')} title={bm('viewbar.scanToFind')} onclick={scanToFind}>
192
+ <svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true"><path d="M4 7V5a1 1 0 0 1 1-1h2M17 4h2a1 1 0 0 1 1 1v2M20 17v2a1 1 0 0 1-1 1h-2M7 20H5a1 1 0 0 1-1-1v-2M7 9v6M10 9v6M13 9v6M17 9v6" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" /></svg>
193
+ </button>
194
+ {/if}
187
195
  {/if}
188
196
  </div>
189
197
  {/if}
@@ -195,6 +203,16 @@ import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";i
195
203
  <RecordView {ctrl} rowId={record.rowId} editPrimary={record.editPrimary} onClose={closeRecord} />
196
204
  {/key}
197
205
  {/if}
206
+ {#if fieldEditing}
207
+ {#key fieldEditing}
208
+ <FieldEditor {ctrl} mode={fieldEditing.mode} columnId={fieldEditing.columnId} index={fieldEditing.index} onClose={closeFieldEditor} />
209
+ {/key}
210
+ {/if}
211
+ {#if fieldDeleting}
212
+ {#key fieldDeleting}
213
+ <DeleteFieldConfirm {ctrl} columnId={fieldDeleting.columnId} onClose={() => askDeleteField(null)} />
214
+ {/key}
215
+ {/if}
198
216
  {#if deleting}
199
217
  {#key deleting}
200
218
  <DeleteRecordConfirm {ctrl} api={deleting.api} row={deleting.row} onDeleted={deleting.onDeleted} onClose={() => askDeleteRecord(null)} />
@@ -202,5 +220,5 @@ import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";i
202
220
  {/if}
203
221
 
204
222
  <style>
205
- .sv-fvb-changed{color:var(--sg-fg, #0f172a)}.sv-fvb-changed-dot{width:7px;height:7px;border-radius:50%;background:var(--sg-accent, #2563eb);flex:none}.sv-fvb{container-type:inline-size;display:flex;align-items:center;gap:2px;flex-wrap:wrap;min-height:40px;padding:4px 6px;font-family:var(--sg-font, inherit);font-size:13px;color:var(--sg-fg, #0f172a);border-bottom:1px solid var(--sg-border, #e2e8f0);background:var(--sg-bg, #fff)}.sv-fvb-btn{position:relative;display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;border:0;border-radius:6px;background:none;color:inherit;font:inherit;cursor:pointer;white-space:nowrap}.sv-fvb-btn:hover{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fvb-btn:focus-visible{outline:2px solid var(--sg-accent, #2563eb);outline-offset:-2px}.sv-fvb-btn.is-set{background:color-mix(in srgb,var(--sg-accent, #2563eb) 13%,transparent)}.sv-fvb-view{font-weight:600;max-width:240px}.sv-fvb-view-name{overflow:hidden;text-overflow:ellipsis}.sv-fvb-icon-only{padding:0 6px}.sv-fvb-sep{width:1px;height:18px;margin:0 6px;background:var(--sg-border, #e2e8f0)}.sv-fvb-lock{display:inline-flex;flex:none;align-items:center;gap:4px;height:24px;margin-left:4px;padding:0 8px;border-radius:999px;font-size:12px;color:var(--sg-muted, #64748b);background:color-mix(in srgb,var(--sg-fg, #0f172a) 7%,transparent)}.sv-fvb-lock-reset{margin-left:2px;padding:0;border:0;background:none;font:inherit;font-weight:600;color:var(--sg-fg, #0f172a);text-decoration:underline;cursor:pointer}:global(.sv-fvb-btn:disabled){opacity:.45;cursor:default}.sv-fvb-spacer{flex:1}@container (max-width: 640px){.sv-fvb-btn:not(.sv-fvb-view)>span{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.sv-fvb-btn{padding:0 6px}.sv-fvb-view{max-width:150px}.sv-fvb-lock>span{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.sv-fvb-lock{padding:0 6px}}@container (max-width: 420px){.sv-fvb-count{display:none}}.sv-fvb-search{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;border-radius:6px;border:1px solid var(--sg-border, #cbd5e1);color:var(--sg-muted, #64748b)}.sv-fvb-search input{width:160px;border:0;outline:none;background:none;color:var(--sg-fg, #0f172a);font:inherit}.sv-fvb-search:focus-within{border-color:var(--sg-accent, #2563eb)}.sv-fvb-count{color:var(--sg-muted, #64748b);font-size:12px;margin-inline-end:4px;font-variant-numeric:tabular-nums}:global(.sv-pop__panel:has(.sv-fvb-panel-wide)){max-width:min(94vw,760px)}@media(max-width:800px){:global(.sv-pop__panel:has(.sv-fvb-panel-wide)){left:8px!important;right:8px;max-width:none}}:global(.sv-fvb-panel){font-size:13px;max-width:100%}:global(.sv-fvb-title){margin:0 0 6px;color:var(--sg-muted, #64748b);font-size:12px}:global(.sv-fvb-empty){margin:2px 0 8px;color:var(--sg-muted, #64748b)}:global(.sv-fvb-foot){display:flex;gap:12px;margin-top:8px;align-items:center}:global(.sv-fvb-select),:global(.sv-fvb-input){width:100%;min-width:0;height:28px;box-sizing:border-box;padding:0 6px;font:inherit;font-size:13px;color:inherit;background:var(--sg-bg, #fff);border:1px solid var(--sg-border, #cbd5e1);border-radius:6px}:global(.sv-fvb-select:focus-visible),:global(.sv-fvb-input:focus-visible){outline:2px solid var(--sg-accent, #2563eb);outline-offset:-1px}:global(.sv-fvb-text-btn){border:0;padding:2px 0;background:none;font:inherit;color:var(--sg-fg, #0f172a);text-decoration:underline;cursor:pointer}:global(.sv-fvb-text-btn:hover){text-decoration-thickness:2px}:global(.sv-fvb-solid-btn){border:0;border-radius:6px;padding:5px 12px;font:inherit;cursor:pointer;background:var(--sg-accent, #2563eb);color:var(--sg-on-accent, #fff)}:global(.sv-fvb-icon-btn){display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;padding:0;border:0;border-radius:6px;background:none;color:var(--sg-muted, #64748b);cursor:pointer}:global(.sv-fvb-icon-btn:hover){background:var(--sg-row-hover-bg, #f1f5f9);color:var(--sg-fg, #0f172a)}:global(.sv-fvb-switch){appearance:none;flex:none;position:relative;width:26px;height:15px;margin:0;border-radius:999px;cursor:pointer;background:color-mix(in srgb,var(--sg-fg, #0f172a) 22%,transparent);transition:background-color .12s}:global(.sv-fvb-switch:before){content:"";position:absolute;top:2px;left:2px;width:11px;height:11px;border-radius:50%;background:var(--sg-bg, #fff);transition:transform .12s}:global(.sv-fvb-switch:checked){background:var(--sg-accent, #2563eb)}:global(.sv-fvb-switch:checked:before){transform:translate(11px)}:global(.sv-fvb-switch:disabled){opacity:.5;cursor:default}:global(.sv-fvb-switch:focus-visible){outline:2px solid var(--sg-accent, #2563eb);outline-offset:2px}@media(forced-colors:active){:global(.sv-fvb-switch){forced-color-adjust:none;background:Canvas;border:1px solid ButtonText;box-sizing:content-box}:global(.sv-fvb-switch:before){background:ButtonText;top:1px;left:1px}:global(.sv-fvb-switch:checked){background:Highlight;border-color:Highlight}:global(.sv-fvb-switch:checked:before){background:HighlightText}.sv-fvb-btn.is-set,.sv-fvb-height.is-on{outline:1px solid Highlight;outline-offset:-1px}}.sv-fvb-heights{display:grid;min-width:150px}.sv-fvb-height{display:flex;align-items:center;gap:10px;padding:6px 8px;border:0;border-radius:6px;background:none;color:inherit;font:inherit;text-align:start;cursor:pointer}.sv-fvb-height-on{margin-inline-start:auto}.sv-fvb-height:hover,.sv-fvb-height.is-on{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fvb-height.is-on{font-weight:600}.sv-fvb-height-mark{width:14px;height:14px;border:1.5px solid currentColor;border-radius:3px;box-sizing:border-box;background:repeating-linear-gradient(to bottom,transparent 0 2px,currentColor 2px 3px) center / 8px calc(var(--lines) * 3px) no-repeat}
223
+ .sv-fvb-changed{color:var(--sg-fg, #0f172a)}.sv-fvb-changed-dot{width:7px;height:7px;border-radius:50%;background:var(--sg-accent, #2563eb);flex:none}.sv-fvb{container-type:inline-size;display:flex;align-items:center;gap:2px;flex-wrap:wrap;min-height:40px;padding:4px 6px;font-family:var(--sg-font, inherit);font-size:13px;color:var(--sg-fg, #0f172a);border-bottom:1px solid var(--sg-border, #e2e8f0);background:var(--sg-bg, #fff)}.sv-fvb-btn{position:relative;display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;border:0;border-radius:6px;background:none;color:inherit;font:inherit;cursor:pointer;white-space:nowrap}.sv-fvb-btn:hover{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fvb-btn:focus-visible{outline:2px solid var(--sg-accent, #2563eb);outline-offset:-2px}.sv-fvb-btn.is-set{background:color-mix(in srgb,var(--sg-accent, #2563eb) 13%,transparent)}.sv-fvb-view{font-weight:600;max-width:240px}.sv-fvb-view-name{overflow:hidden;text-overflow:ellipsis}.sv-fvb-icon-only{padding:0 6px}.sv-fvb-sep{width:1px;height:18px;margin:0 6px;background:var(--sg-border, #e2e8f0)}.sv-fvb-lock{display:inline-flex;flex:none;align-items:center;gap:4px;height:24px;margin-left:4px;padding:0 8px;border-radius:999px;font-size:12px;color:var(--sg-muted, #64748b);background:color-mix(in srgb,var(--sg-fg, #0f172a) 7%,transparent)}.sv-fvb-lock-reset{margin-left:2px;padding:0;border:0;background:none;font:inherit;font-weight:600;color:var(--sg-fg, #0f172a);text-decoration:underline;cursor:pointer}:global(.sv-fvb-btn:disabled){opacity:.45;cursor:default}.sv-fvb-spacer{flex:1}@container (max-width: 640px){.sv-fvb-btn:not(.sv-fvb-view)>span{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.sv-fvb-btn{padding:0 6px}.sv-fvb-view{max-width:150px}.sv-fvb-lock>span{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.sv-fvb-lock{padding:0 6px}}@container (max-width: 420px){.sv-fvb-count{display:none}}.sv-fvb-search{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;border-radius:6px;border:1px solid var(--sg-border, #cbd5e1);color:var(--sg-muted, #64748b)}.sv-fvb-search input{width:160px;border:0;outline:none;background:none;color:var(--sg-fg, #0f172a);font:inherit}.sv-fvb-search:focus-within{border-color:var(--sg-accent, #2563eb)}.sv-fvb-count{color:var(--sg-muted, #64748b);font-size:12px;margin-inline-end:4px;font-variant-numeric:tabular-nums}:global(.sv-pop__panel:has(.sv-fvb-panel-wide)){max-width:min(94vw,760px)}@media(max-width:800px){:global(.sv-pop__panel:has(.sv-fvb-panel-wide)){left:8px!important;right:8px;max-width:none}}:global(.sv-fvb-panel){font-size:13px;max-width:100%}:global(.sv-fvb-title){margin:0 0 6px;color:var(--sg-muted, #64748b);font-size:12px}:global(.sv-fvb-empty){margin:2px 0 8px;color:var(--sg-muted, #64748b)}:global(.sv-fvb-foot){display:flex;gap:12px;margin-top:8px;align-items:center}:global(.sv-fvb-select),:global(.sv-fvb-input){width:100%;min-width:0;height:28px;box-sizing:border-box;padding:0 6px;font:inherit;font-size:13px;color:inherit;background:var(--sg-bg, #fff);border:1px solid var(--sg-border, #cbd5e1);border-radius:6px}:global(.sv-fvb-select:focus-visible),:global(.sv-fvb-input:focus-visible){outline:2px solid var(--sg-accent, #2563eb);outline-offset:-1px}:global(.sv-fvb-text-btn){border:0;padding:2px 0;background:none;font:inherit;color:var(--sg-fg, #0f172a);text-decoration:underline;cursor:pointer}:global(.sv-fvb-text-btn:hover){text-decoration-thickness:2px}:global(.sv-pop__panel--sheet .sv-fvb-foot){flex-direction:column;align-items:stretch;gap:8px}:global(.sv-pop__panel--sheet .sv-fvb-text-btn){display:flex;align-items:center;justify-content:center;width:100%;min-height:44px;box-sizing:border-box;border:1px solid var(--sg-border, #e2e8f0);border-radius:10px;text-decoration:none;font-weight:600}:global(.sv-fvb-solid-btn){border:0;border-radius:6px;padding:5px 12px;font:inherit;cursor:pointer;background:var(--sg-accent, #2563eb);color:var(--sg-on-accent, #fff)}:global(.sv-fvb-icon-btn){display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;padding:0;border:0;border-radius:6px;background:none;color:var(--sg-muted, #64748b);cursor:pointer}:global(.sv-fvb-icon-btn:hover){background:var(--sg-row-hover-bg, #f1f5f9);color:var(--sg-fg, #0f172a)}:global(.sv-fvb-switch){appearance:none;flex:none;position:relative;width:26px;height:15px;margin:0;border-radius:999px;cursor:pointer;background:color-mix(in srgb,var(--sg-fg, #0f172a) 22%,transparent);transition:background-color .12s}:global(.sv-fvb-switch:before){content:"";position:absolute;top:2px;left:2px;width:11px;height:11px;border-radius:50%;background:var(--sg-bg, #fff);transition:transform .12s}:global(.sv-fvb-switch:checked){background:var(--sg-accent, #2563eb)}:global(.sv-fvb-switch:checked:before){transform:translate(11px)}:global(.sv-fvb-switch:disabled){opacity:.5;cursor:default}:global(.sv-fvb-switch:focus-visible){outline:2px solid var(--sg-accent, #2563eb);outline-offset:2px}@media(forced-colors:active){:global(.sv-fvb-switch){forced-color-adjust:none;background:Canvas;border:1px solid ButtonText;box-sizing:content-box}:global(.sv-fvb-switch:before){background:ButtonText;top:1px;left:1px}:global(.sv-fvb-switch:checked){background:Highlight;border-color:Highlight}:global(.sv-fvb-switch:checked:before){background:HighlightText}.sv-fvb-btn.is-set,.sv-fvb-height.is-on{outline:1px solid Highlight;outline-offset:-1px}}.sv-fvb-heights{display:grid;min-width:150px}.sv-fvb-height{display:flex;align-items:center;gap:10px;padding:6px 8px;border:0;border-radius:6px;background:none;color:inherit;font:inherit;text-align:start;cursor:pointer}.sv-fvb-height-on{margin-inline-start:auto}.sv-fvb-height:hover,.sv-fvb-height.is-on{background:var(--sg-row-hover-bg, #f1f5f9)}.sv-fvb-height.is-on{font-weight:600}.sv-fvb-height-mark{width:14px;height:14px;border:1.5px solid currentColor;border-radius:3px;box-sizing:border-box;background:repeating-linear-gradient(to bottom,transparent 0 2px,currentColor 2px 3px) center / 8px calc(var(--lines) * 3px) no-repeat}
206
224
  </style>
@@ -15,6 +15,10 @@ type Props = {
15
15
  label: string;
16
16
  height: number;
17
17
  }>;
18
+ /** Where to draw the bar instead of its own place: a phone's tables row (SvBase puts it there). */
19
+ host?: HTMLElement | null;
20
+ /** The table the views are of, for the app's view actions (setViewActions). */
21
+ tableId?: string;
18
22
  /** The Automations button: how many rules, and what its buttons open. */
19
23
  automations?: {
20
24
  count: number;
@@ -0,0 +1,28 @@
1
+ <script lang="ts">
2
+ import{cellPress}from"./cell-press";import{timerRunning,timerSeconds}from"./timer";import{clockNow,holdClock}from"./timer-clock.svelte";import{formatDuration}from"./format";import{safeColor}from"./palette";import{bm}from"./messages.svelte";let{ctrl,row,column,value,props}=$props();const running=$derived(timerRunning(value)!=null);$effect(()=>{if(running)return holdClock()});const seconds=$derived(timerSeconds(value,running?clockNow():Date.now()));const shown=$derived(seconds==null?"":formatDuration(seconds,running?"h:mm:ss":props.durationFormat??"h:mm:ss"));const g=$derived(ctrl);const interactive=$derived(!!g?.editingEnabled&&column.columnDef.editable!==false);const color=$derived(safeColor(props.color)??"var(--sg-accent, #2563eb)");const label=$derived(running?bm("record.timerStop"):bm("record.timerStart"));const press=cellPress(()=>ctrl,{direct:true});const stop=e=>e.stopPropagation();function toggle(e){if(!press.click(e)||!interactive)return;const rowIndex=g.allRows.findIndex(r=>r.id===row.id);if(rowIndex>=0)g.startEditing?.(rowIndex,column.id)}
3
+ </script>
4
+
5
+ <span class="sv-ftimer" class:is-running={running} style:--c={color}>
6
+ <button
7
+ type="button"
8
+ class="sv-ftimer-btn"
9
+ disabled={!interactive}
10
+ aria-pressed={running}
11
+ aria-label={label}
12
+ title={label}
13
+ onpointerdown={press.press}
14
+ ondblclick={stop}
15
+ onclick={toggle}
16
+ >
17
+ {#if running}
18
+ <svg viewBox="0 0 24 24" width="12" height="12" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2" /></svg>
19
+ {:else}
20
+ <svg viewBox="0 0 24 24" width="12" height="12" aria-hidden="true"><path d="M8 5.5v13l11-6.5z" /></svg>
21
+ {/if}
22
+ </button>
23
+ <span class="sv-ftimer-time" aria-live={running ? 'off' : undefined}>{shown}</span>
24
+ </span>
25
+
26
+ <style>
27
+ .sv-ftimer{display:inline-flex;align-items:center;gap:8px;min-width:0;font-variant-numeric:tabular-nums}.sv-ftimer-btn{flex:none;display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;padding:0;box-sizing:border-box;border:1px solid var(--sg-border, #e2e8f0);border-radius:999px;background:transparent;color:var(--c);cursor:pointer}.sv-ftimer-btn svg{fill:currentColor}.sv-ftimer-btn:disabled{cursor:default;opacity:.6}.sv-ftimer-btn:not(:disabled):hover{border-color:var(--c);background:color-mix(in srgb,var(--c) 10%,transparent)}.sv-ftimer-btn:focus-visible{outline:2px solid var(--sg-focus-ring, var(--sg-accent, #2563eb));outline-offset:1px}.sv-ftimer.is-running .sv-ftimer-btn{border-color:var(--c);background:var(--c);color:#fff}.sv-ftimer.is-running .sv-ftimer-time{color:var(--c);font-weight:600}.sv-ftimer-time{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}@media(forced-colors:active){.sv-ftimer.is-running .sv-ftimer-btn{background:ButtonText;color:ButtonFace}}
28
+ </style>
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Timer cells: a start button and the time counted, or, while the timer
3
+ * runs, a stop button and the time ticking each second (h:mm:ss). A click
4
+ * on the button (or Enter, Space) starts or stops it through the timer
5
+ * editor and the grid's own edit commit, so undo, `onCellValueChange` and
6
+ * protected fields behave as for any edit. A click on the rest of the cell
7
+ * only selects it; a typed number sets the time ("1:30").
8
+ */
9
+ import type { FieldCellProps } from './registry.svelte.js';
10
+ import { type DurationFormat } from './format.js';
11
+ declare const TimerCell: import("svelte").Component<FieldCellProps<{
12
+ durationFormat?: DurationFormat;
13
+ color?: string;
14
+ }>, {}, "">;
15
+ type TimerCell = ReturnType<typeof TimerCell>;
16
+ export default TimerCell;
@@ -0,0 +1,7 @@
1
+ <script lang="ts">
2
+ import{onMount}from"svelte";import NumberEditor from"./NumberEditor.svelte";import{timerSeconds,timerToggle}from"./timer";let{value,typed=false,row,rowId,columnDef,onCommit,onCancel,onCommitAndMove,onCommitAndMoveDown}=$props();const inForm=rowId==="";const typing=inForm||typed&&/^[0-9.:+-]/.test(String(value??""));const boxValue=typed?value:timerSeconds(value);const asDuration=$derived({...columnDef??{},fieldType:"duration",fieldProps:{durationFormat:"h:mm:ss",...columnDef?.fieldProps??{}}});onMount(()=>{if(typing)return;const field=String(columnDef?.field??"");const before=typed?row?.[field]:value;queueMicrotask(()=>onCommit(timerToggle(before)))});
3
+ </script>
4
+
5
+ {#if typing}
6
+ <NumberEditor value={boxValue} typed={typed} columnDef={asDuration} {onCommit} {onCancel} {onCommitAndMove} {onCommitAndMoveDown} />
7
+ {/if}
@@ -0,0 +1,14 @@
1
+ type $$ComponentProps = {
2
+ value: unknown;
3
+ typed?: boolean;
4
+ row?: unknown;
5
+ rowId?: string | null;
6
+ columnDef?: Record<string, unknown>;
7
+ onCommit: (v?: unknown) => void;
8
+ onCancel: () => void;
9
+ onCommitAndMove?: (v: unknown, direction: 1 | -1) => void;
10
+ onCommitAndMoveDown?: (v: unknown, up?: boolean) => void;
11
+ };
12
+ declare const TimerEditor: import("svelte").Component<$$ComponentProps, {}, "">;
13
+ type TimerEditor = ReturnType<typeof TimerEditor>;
14
+ export default TimerEditor;
@@ -1 +1 @@
1
- import{FORMULA_FUNCTIONS as _,columnResolver as j,formulaError as W}from"./formula.js";import{aiPromptError as G}from"./ai-prompt.js";import{OPTION_COLORS as H}from"./palette.js";const z=["blue","cyan","teal","green","yellow","orange","red","pink","purple","gray"],K={Light2:0,Light1:1,Bright:2,Dark1:3};export function airtableColor(t){const i=/^(blue|cyan|teal|green|yellow|orange|red|pink|purple|gray)(Light2|Light1|Bright|Dark1)?$/.exec(String(t??""));if(i)return H[K[i[2]??"Bright"]*10+z.indexOf(i[1])]?.value}const X=new Set(["local","friendly","us","european","iso"]),J=new Set(["h:mm","h:mm:ss","h:mm:ss.S","h:mm:ss.SS","h:mm:ss.SSS"]),U=new Set(["check","star","heart","thumbsUp","flag","dot"]),V={grid:"grid",kanban:"kanban",calendar:"calendar",gallery:"gallery",form:"form",timeline:"gantt",gantt:"gantt"},v=new Set(["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL","ARRAYJOIN","ARRAYUNIQUE","CONCATENATE","AND","OR"]),$=new Set(["number","currency","percent","duration","rating"]),Z=new Set(["formula","rollup","multipleLookupValues","count","button"]);function w(t,i){const e={time:i},l=t?.dateFormat?.name;return X.has(l)&&(e.dateFormat=l),i&&((t?.timeFormat?.name==="24hour"||t?.timeFormat?.name==="12hour")&&(e.timeFormat=t.timeFormat.name),t?.timeZone==="utc"&&(e.gmt=!0)),e}function Q(t,i){const e=t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"field";let l=e;for(let s=2;i.has(l);s++)l=`${e}_${s}`;return i.add(l),l}function B(t,i,e){let l="",s=0,T=0;const I=n=>{l+=i(t.slice(T,n))};for(;s<t.length;){const n=t[s];if(n==='"'||n==="'"){I(s);let r=s+1;for(;r<t.length&&t[r]!==n;)r+=t[r]==="\\"?2:1;l+=t.slice(s,r+1),s=T=r+1}else if(n==="{"){I(s);const r=t.indexOf("}",s);if(r<0){T=s;break}l+=`{${e(t.slice(s+1,r))}}`,s=T=r+1}else s++}return l+i(t.slice(T))}function q(t){let i="",e=0;for(;e<t.length;){const l=t[e];if(l!=='"'&&l!=="'"){i+=l,e++;continue}let s=e+1;for(;s<t.length&&t[s]!==l;)s+=t[s]==="\\"?2:1;i+=l+" ".repeat(Math.max(0,Math.min(s,t.length)-e-1))+(s<t.length?l:""),e=s+1}return i}function ee(t){const i=[...t.fields],e=[],l=n=>{const r=n.trim();return i.find(o=>o.id===r)?.id??i.find(o=>o.name===r)?.id},s=n=>{let r=n;for(let o=2;i.some(f=>f.name===r);o++)r=`${n} ${o}`;return r},T=(n,r)=>Array.isArray(n)&&n.length===r.length&&r.every(o=>n.includes(o)),I=(n,r)=>{const o=n===null?i.find(c=>c.type==="createdTime"):i.find(c=>c.type==="lastModifiedTime"&&(n.length?T(c.options?.referencedFieldIds,n):!c.options?.referencedFieldIds?.length));if(o)return o.id;const f=n===null?"Created":n.length?`${n.map(c=>i.find(a=>a.id===c).name).join(" and ")} modified`:"Last modified",h={id:n===null?"fldSvCreated":`fldSvModified${n.join("")}`,name:s(f),type:n===null?"createdTime":"lastModifiedTime",options:{...n?.length?{referencedFieldIds:n}:{},result:{type:"dateTime"}}};return i.push(h),e.push({field:h,usedBy:r}),h.id};for(const[n,r]of i.entries()){if(r.type!=="formula"||typeof r.options?.formula!="string")continue;const o=r.options.formula,f=q(o),h=[];for(const a of f.matchAll(/\bCREATED_TIME\s*\(\s*\)/gi))h.push([a.index,a.index+a[0].length,`{${I(null,r.name)}}`]);for(const a of f.matchAll(/\bLAST_MODIFIED_TIME\s*\(\s*((?:\{[^}]*\}\s*,?\s*)*)\)/gi)){const y=[...a[1].matchAll(/\{([^}]*)\}/g)].map(g=>l(g[1]));y.some(g=>!g)||h.push([a.index,a.index+a[0].length,`{${I(y,r.name)}}`])}if(!h.length)continue;let c=o;for(const[a,y,g]of h.sort((N,C)=>C[0]-N[0]))c=c.slice(0,a)+g+c.slice(y);i[n]={...r,options:{...r.options,formula:c}}}return{table:e.length||i.some((n,r)=>n!==t.fields[r])?{...t,fields:i}:t,added:e}}export function formulaFunctionsUsed(t){const i=new Set;return B(t,e=>{for(const l of e.matchAll(/([A-Za-z_][A-Za-z0-9_]*)\s*\(/g))i.add(l[1].toUpperCase());return e},e=>e),[...i]}function te(t,i){return B(t,e=>e,e=>i.get(e.trim())??e)}function ie(t,i){const e=t.options??{},l=i.keys.get(i.table.id),s=(n,r)=>i.report.push({kind:n,table:i.table.name,name:t.name,message:r}),T=n=>{const r=l.get(String(n));return r||s("link","The link field it reads is not in the table."),r},I=(n,r)=>{const o=i.table.fields.find(f=>f.id===n);return i.keys.get(String(o?.options?.linkedTableId))?.get(String(r))};switch(t.type){case"singleLineText":return{fieldType:"text"};case"multilineText":return{fieldType:"longText"};case"richText":return{fieldType:"longText",fieldProps:{richText:!0}};case"email":return{fieldType:"email"};case"url":return{fieldType:"url"};case"phoneNumber":return{fieldType:"phone"};case"number":{const n=Number(e.precision??0);return{fieldType:"number",fieldProps:n>0?{format:"decimal",precision:n}:{format:"integer",precision:0}}}case"currency":return{fieldType:"number",fieldProps:{format:"currency",precision:Number(e.precision??2),symbol:e.symbol??"$"}};case"percent":return{fieldType:"number",fieldProps:{format:"percent",precision:Number(e.precision??0)}};case"rating":{const n=airtableColor(e.color);return{fieldType:"rating",fieldProps:{max:Number(e.max??5),...U.has(e.icon)&&e.icon!=="check"?{icon:e.icon}:{},...n?{color:n}:{}}}}case"duration":return{fieldType:"duration",fieldProps:J.has(e.durationFormat)?{durationFormat:e.durationFormat}:{}};case"checkbox":{const n=airtableColor(e.color),r=e.icon==="xCheckbox"?"x":U.has(e.icon)?e.icon:void 0;return{fieldType:"checkbox",fieldProps:{...r?{icon:r}:{},...n?{color:n}:{}}}}case"singleSelect":case"multipleSelects":{const n=(Array.isArray(e.choices)?e.choices:[]).map(r=>{const o=airtableColor(r.color);return{value:String(r.name),...o?{color:o}:{}}});return{fieldType:t.type==="singleSelect"?"singleSelect":"multiSelect",fieldProps:{options:n}}}case"date":return{fieldType:"date",fieldProps:w(e,!1)};case"dateTime":return{fieldType:"date",fieldProps:w(e,!0)};case"singleCollaborator":return{fieldType:"user",fieldProps:{multiple:!1}};case"multipleCollaborators":return{fieldType:"user",fieldProps:{multiple:!0}};case"multipleRecordLinks":{const n=String(e.linkedTableId??"");i.tableIds.has(n)||s("link","It links to a table that was not imported; the record ids stay, the cells show none of them.");const r=e.inverseLinkFieldId?i.keys.get(n)?.get(String(e.inverseLinkFieldId)):void 0;return{fieldType:"link",fieldProps:{table:n,multiple:e.prefersSingleRecordLink!==!0,...r&&n!==i.table.id&&i.tableIds.has(n)?{inverse:r}:{}}}}case"multipleAttachments":return{fieldType:"attachment"};case"barcode":return{fieldType:"barcode"};case"autoNumber":return{fieldType:"autoNumber"};case"button":return s("setting","The API does not say what the button does: set its URL (fieldProps.url, with {Field name} for values) or fieldProps.onClick."),{fieldType:"button",fieldProps:{label:String(e.label??t.name)}};case"createdTime":return{fieldType:"createdTime",fieldProps:w(e.result?.options,e.result?.type!=="date")};case"lastModifiedTime":case"lastModifiedBy":{const n=(Array.isArray(e.referencedFieldIds)?e.referencedFieldIds:[]).map(o=>l.get(o)).filter(Boolean),r=n.length?{watch:"specific",watchFields:n}:{watch:"all"};return t.type==="lastModifiedTime"?{fieldType:"lastModifiedTime",fieldProps:{...r,...w(e.result?.options,e.result?.type!=="date")}}:{fieldType:"lastModifiedBy",fieldProps:r}}case"createdBy":return{fieldType:"createdBy"};case"aiText":{const n=new Map(i.table.fields.map(c=>[c.id,c.name])),o=(Array.isArray(e.prompt)?e.prompt:typeof e.prompt=="string"?[e.prompt]:[]).map(c=>{if(typeof c=="string")return c;const a=c?.field?.fieldId;return a!=null?`{${n.get(String(a))??String(a)}}`:""}).join(""),f=i.table.fields.filter(c=>c.id!==t.id).map(c=>({field:l.get(c.id),header:c.name})),h=G(o,f,[t.name]);return o.trim()?h?s("setting",`${h}: fix the prompt in the field editor. The generated values come over as they are.`):s("setting","The generated values come over as they are. New ones come from the AI provider your app sets with setAIProvider()."):s("setting","The API gave no prompt: write one in the field editor. The generated values come over as they are."),{fieldType:"ai",fieldProps:{prompt:o,output:"text",auto:!0}}}case"formula":{const n=new Map(i.table.fields.map(f=>[f.id,f.name])),r=te(String(e.formula??""),n),o=formulaFunctionsUsed(r).filter(f=>!_.includes(f));if(o.length)s("formula",`Uses ${o.join(", ")}, which Base formulas do not have: the cells show #ERROR until that part is rewritten.`);else{const f=i.table.fields.filter(c=>c.id!==t.id).map(c=>({field:l.get(c.id),header:c.name})),h=W(r,j(f,[t.name]));h&&s("formula",`${h}: the cells show #ERROR.`)}return{fieldType:"formula",fieldProps:{formula:r,...ne(e.result)}}}case"rollup":{const n=T(e.recordLinkFieldId),r=I(e.recordLinkFieldId,e.fieldIdInLinkedTable),o=/^\s*([A-Za-z_]+)\s*\(\s*values\s*\)\s*$/i.exec(String(e.formula??""))?.[1]?.toUpperCase(),f=o&&v.has(o)?o:$.has(e.result?.type)?"SUM":"ARRAYJOIN";o?v.has(o)||s("formula",`The rollup's ${o}(values) has no Base aggregation; it is set to ${f}.`):s("setting",`The schema does not include the rollup's aggregation; it is set to ${f}. Change it in the field editor if the base used another.`);const h=e.result?.options?.precision;return{fieldType:"rollup",fieldProps:{linkField:n,field:r,aggregation:f,...h!=null&&$.has(e.result?.type)?{precision:Number(h)}:{}}}}case"multipleLookupValues":return{fieldType:"lookup",fieldProps:{linkField:T(e.recordLinkFieldId),field:I(e.recordLinkFieldId,e.fieldIdInLinkedTable)}};case"count":return{fieldType:"count",fieldProps:{linkField:T(e.recordLinkFieldId)}};default:return null}}function ne(t){const i=t?.options??{},e=i.precision!=null?{precision:Number(i.precision)}:{};switch(t?.type){case"number":return{result:"number",...e};case"currency":return{result:"currency",...e,...i.symbol?{symbol:i.symbol}:{}};case"percent":return{result:"percent",...e};case"date":return{result:"date",...w(i,!1)};case"dateTime":return{result:"date",...w(i,!0)};default:return{result:"auto"}}}const F=t=>Array.isArray(t)?t:t==null?[]:[t];function re(t){const i=t.thumbnails?.large?.url??t.thumbnails?.small?.url;return{id:String(t.id??t.url),url:String(t.url??""),name:String(t.filename??t.name??""),type:String(t.type??""),...typeof t.size=="number"?{size:t.size}:{},...typeof t.width=="number"?{width:t.width}:{},...typeof t.height=="number"?{height:t.height}:{},...i?{thumbnailUrl:String(i)}:{}}}function M(t){if(t==null)return"";if(Array.isArray(t))return t.map(M).join(", ");if(typeof t=="object"){const i=t;return"value"in i?M(i.value):"name"in i?String(i.name):"text"in i?String(i.text):JSON.stringify(t)}return String(t)}export function baseFromAirtable(t,i={},e={}){const l=[];for(const a of Array.isArray(t?.tables)?t.tables:[])if(!a||!Array.isArray(a.fields))throw Object.assign(new Error(`baseFromAirtable: a table in this file has no list of fields. Pass the JSON of Airtable's "Get base schema" call.`),{code:"bad-airtable-schema"});const s=(Array.isArray(t?.tables)?t.tables:[]).map(ee),T=s.map(a=>a.table),I=e.tables?.length?e.tables.map(a=>T.find(y=>y.id===a||y.name===a)).filter(a=>!!a):T,n=new Set(I.map(a=>a.id)),r=new Map;for(const a of T){const y=new Set(["id"]);r.set(a.id,new Map(a.fields.map(g=>[g.id,Q(g.name,y)])))}const o=new Map,f=e.userId??(a=>a.id),h=a=>{if(a==null||typeof a!="object")return a==null?null:String(a);const y=a,g=f(y);return o.has(g)||o.set(g,{id:g,name:y.name??y.email??g,...y.email?{email:y.email}:{}}),g};return{tables:I.map(a=>{const y={table:a,keys:r,tableIds:n,report:l};for(const{field:d,usedBy:u}of s.find(b=>b.table===a)?.added??[]){const b=(d.options?.referencedFieldIds??[]).map(m=>a.fields.find(A=>A.id===m).name),p=m=>l.push({kind:"field",table:a.name,name:d.name,message:`Added for ${u}, ${m}`});d.type==="createdTime"?p("which reads CREATED_TIME(): a Base record keeps that time in a Created time field. It holds each record's createdTime from the API."):b.length?p(`which reads when ${b.join(" and ")} last changed: a Last modified time field that watches ${b.length>1?"them":"it"}. The API does not say when a field last changed, so it is empty until the next edit.`):p("which reads LAST_MODIFIED_TIME(): a Last modified time field. The API does not say when a record last changed, so it is empty until the next edit.")}const g=r.get(a.id),N=a.primaryFieldId??a.fields[0]?.id,P=[...a.fields].sort((d,u)=>+(u.id===N)-+(d.id===N)).map(d=>{let u=ie(d,y);return u||(l.push({kind:"field",table:a.name,name:d.name,message:`Base has no "${d.type}" field: it is a text field, with each value as text.`}),u={fieldType:"text"}),{f:d,key:g.get(d.id),fieldType:u.fieldType,fieldProps:u.fieldProps,known:u.fieldType!=="text"||d.type==="singleLineText"}}),S=P.map(({f:d,key:u,fieldType:b,fieldProps:p})=>({id:u,field:u,header:d.name,fieldType:b,...p&&Object.keys(p).length?{fieldProps:p}:{},...d.description?{description:d.description}:{}})),O=i[a.id]??i[a.name],Y=(Array.isArray(O)?O:O?.records??[]).map(d=>{const u={id:d.id};for(const{f:b,key:p,fieldType:m,fieldProps:A,known:k}of P){if(Z.has(b.type))continue;let E=d.fields?.[b.name]??d.fields?.[b.id];b.type==="createdTime"&&E==null&&(E=d.createdTime),E!==void 0&&(k?m==="user"||m==="createdBy"||m==="lastModifiedBy"?u[p]=A?.multiple?F(E).map(h).filter(R=>R!=null):h(Array.isArray(E)?E[0]:E):m==="attachment"?u[p]=F(E).filter(R=>R&&typeof R=="object").map(R=>re(R)):m==="link"?u[p]=F(E).map(R=>String(R&&typeof R=="object"?R.id:R)):m==="ai"?u[p]=E&&typeof E=="object"?E.value??null:E:u[p]=E:u[p]=M(E))}return u}),x=d=>S.find(d)?.field,D=[];for(const d of a.views??[]){const u=V[d.type],b=m=>l.push({kind:"view",table:a.name,name:d.name,message:m});if(!u){b(`Base has no "${d.type}" view; it was left out.`);continue}const p={id:d.id,name:d.name,type:u};if(u==="kanban"){const m=x(A=>A.fieldType==="singleSelect"||A.fieldType==="user"&&!A.fieldProps?.multiple);if(!m){b("A Kanban view needs a single select or a single user field; the table has none.");continue}p.stackBy=m,l.push({kind:"setting",table:a.name,name:d.name,message:`The API does not say which field the board stacks by; it uses ${S.find(A=>A.field===m).header}.`})}else if(u==="calendar"||u==="gantt"){const m=S.filter(A=>A.fieldType==="date").map(A=>String(A.field));if(!m.length){b(`A ${u==="gantt"?"timeline":"calendar"} needs a date field; the table has none.`);continue}p.dateField=m[0],u==="gantt"&&m[1]&&(p.endField=m[1]),l.push({kind:"setting",table:a.name,name:d.name,message:`The API does not say which dates the view uses; it uses ${[p.dateField,p.endField].filter(Boolean).map(A=>S.find(k=>k.field===A).header).join(" to ")}.`})}else if(u==="gallery"){const m=x(A=>A.fieldType==="attachment");m&&(p.coverField=m)}D.push(p)}return D.length||D.push({id:"grid",name:"Grid view",type:"grid"}),{id:a.id,name:a.name,primaryField:g.get(N??"")??String(S[0]?.field??""),columns:S,data:Y,views:D}}),users:[...o.values()],report:l}}const L="JavaScript regular expressions, not RE2.",ae=[["CONCATENATE","Text"],["LEFT","Text"],["RIGHT","Text"],["MID","Text","The count may be left out for the rest of the text."],["LEN","Text"],["FIND","Text","Case matters; 0 when the text is not there."],["SEARCH","Text","Case matters; empty when the text is not there."],["SUBSTITUTE","Text"],["REPLACE","Text"],["TRIM","Text"],["UPPER","Text"],["LOWER","Text"],["REPT","Text","At most 1,000 repeats.",!0],["T","Text"],["ENCODE_URL_COMPONENT","Text"],["REGEX_MATCH","Text",`${L} A leading (?i) works; other inline flags do not.`,!0],["REGEX_EXTRACT","Text",`${L} Empty when nothing matches.`,!0],["REGEX_REPLACE","Text",`${L} Replaces every match; the new text names a group by its number after a dollar sign, as JavaScript's replace does.`,!0],["IF","Logical"],["SWITCH","Logical",'Compares as text, so 1 matches "1".',!0],["AND","Logical"],["OR","Logical"],["NOT","Logical"],["XOR","Logical"],["TRUE","Logical","With or without the parentheses."],["FALSE","Logical","With or without the parentheses."],["BLANK","Logical"],["ERROR","Logical","The cell shows #ERROR."],["ISERROR","Logical","Division by zero is empty in Base, not an error, so ISERROR(1 / 0) is false.",!0],["ABS","Numeric"],["AVERAGE","Numeric"],["CEILING","Numeric"],["COUNT","Numeric"],["COUNTA","Numeric"],["COUNTALL","Numeric"],["EVEN","Numeric"],["EXP","Numeric"],["FLOOR","Numeric"],["INT","Numeric"],["LOG","Numeric","Base 10 unless a base is given."],["MAX","Numeric"],["MIN","Numeric"],["MOD","Numeric"],["ODD","Numeric"],["POWER","Numeric"],["ROUND","Numeric","Halves round toward positive: ROUND(-2.5) is -2."],["ROUNDDOWN","Numeric","Toward zero."],["ROUNDUP","Numeric","Away from zero."],["SQRT","Numeric"],["SUM","Numeric"],["VALUE","Numeric",'Skips characters that are not part of a number: VALUE("1,200.50 USD") is 1200.5.'],["DATEADD","Date",'The units Airtable names, except that "M" is minutes here: write "months".',!0],["DATESTR","Date"],["DATETIME_DIFF","Date",'Units as in DATEADD: "M" is minutes, write "months".',!0],["DATETIME_FORMAT","Date","moment.js tokens (YYYY, MMMM, Do, HH, A, Z, L, LL and the rest); week-of-year tokens are not read.",!0],["DATETIME_PARSE","Date","Reads the tokens DATETIME_FORMAT writes, with the separators as written. Text without a zone is local time.",!0],["DAY","Date"],["HOUR","Date"],["IS_AFTER","Date"],["IS_BEFORE","Date"],["IS_SAME","Date"],["MINUTE","Date"],["MONTH","Date"],["NOW","Date"],["SECOND","Date"],["SET_LOCALE","Date","Changes the month and weekday names DATETIME_FORMAT writes; ordinals (Do) stay English.",!0],["SET_TIMEZONE","Date","Changes what DATETIME_FORMAT writes. An unknown zone leaves the cell empty.",!0],["TIMESTR","Date"],["TONOW","Date","Calendar days from the date to today, signed.",!0],["FROMNOW","Date","Calendar days from today to the date, signed.",!0],["TODAY","Date"],["WEEKDAY","Date",'0 for Sunday; "Monday" as the second argument makes Monday 0.'],["WEEKNUM","Date",'Weeks start on Sunday, or on Monday with "Monday".'],["WORKDAY","Date",'Holidays as text ("2026-12-25, 2026-12-26") or a list of dates.'],["WORKDAY_DIFF","Date","Both days count. Holidays as in WORKDAY."],["YEAR","Date"],["ARRAYCOMPACT","Array"],["ARRAYFLATTEN","Array"],["ARRAYJOIN","Array"],["ARRAYUNIQUE","Array"],["ARRAYSLICE","Array"],["RECORD_ID","Record","The record's id; after baseFromAirtable, the Airtable record id."],["CREATED_TIME","Record","A Base record keeps that time in a Created time field. baseFromAirtable rewrites CREATED_TIME() to read the table's, and adds one when the table has none."],["LAST_MODIFIED_TIME","Record","A Base record keeps that time in a Last modified time field. baseFromAirtable rewrites LAST_MODIFIED_TIME() to read one that watches every field, and LAST_MODIFIED_TIME({Field}) one that watches that field, and adds it when the table has none."]];export function airtableFormulaSupport(){return ae.map(([t,i,e="",l])=>{const T=_.includes(t)?l?"different":"supported":"unsupported";return{name:t,group:i,status:T,note:e}})}
1
+ import{FORMULA_FUNCTIONS as _,columnResolver as j,formulaError as G}from"./formula.js";import{aiPromptError as W}from"./ai-prompt.js";import{OPTION_COLORS as z}from"./palette.js";const H=["blue","cyan","teal","green","yellow","orange","red","pink","purple","gray"],K={Light2:0,Light1:1,Bright:2,Dark1:3};export function airtableColor(t){const i=/^(blue|cyan|teal|green|yellow|orange|red|pink|purple|gray)(Light2|Light1|Bright|Dark1)?$/.exec(String(t??""));if(i)return z[K[i[2]??"Bright"]*10+H.indexOf(i[1])]?.value}const X=new Set(["local","friendly","us","european","iso"]),J=new Set(["h:mm","h:mm:ss","h:mm:ss.S","h:mm:ss.SS","h:mm:ss.SSS"]),U=new Set(["check","star","heart","thumbsUp","flag","dot"]),V={grid:"grid",kanban:"kanban",calendar:"calendar",gallery:"gallery",form:"form",timeline:"timeline",gantt:"gantt"},v=new Set(["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL","ARRAYJOIN","ARRAYUNIQUE","CONCATENATE","AND","OR"]),$=new Set(["number","currency","percent","duration","rating"]),Z=new Set(["formula","rollup","multipleLookupValues","count","button"]);function w(t,i){const e={time:i},l=t?.dateFormat?.name;return X.has(l)&&(e.dateFormat=l),i&&((t?.timeFormat?.name==="24hour"||t?.timeFormat?.name==="12hour")&&(e.timeFormat=t.timeFormat.name),t?.timeZone==="utc"&&(e.gmt=!0)),e}function Q(t,i){const e=t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"field";let l=e;for(let o=2;i.has(l);o++)l=`${e}_${o}`;return i.add(l),l}function B(t,i,e){let l="",o=0,T=0;const I=n=>{l+=i(t.slice(T,n))};for(;o<t.length;){const n=t[o];if(n==='"'||n==="'"){I(o);let r=o+1;for(;r<t.length&&t[r]!==n;)r+=t[r]==="\\"?2:1;l+=t.slice(o,r+1),o=T=r+1}else if(n==="{"){I(o);const r=t.indexOf("}",o);if(r<0){T=o;break}l+=`{${e(t.slice(o+1,r))}}`,o=T=r+1}else o++}return l+i(t.slice(T))}function q(t){let i="",e=0;for(;e<t.length;){const l=t[e];if(l!=='"'&&l!=="'"){i+=l,e++;continue}let o=e+1;for(;o<t.length&&t[o]!==l;)o+=t[o]==="\\"?2:1;i+=l+" ".repeat(Math.max(0,Math.min(o,t.length)-e-1))+(o<t.length?l:""),e=o+1}return i}function ee(t){const i=[...t.fields],e=[],l=n=>{const r=n.trim();return i.find(s=>s.id===r)?.id??i.find(s=>s.name===r)?.id},o=n=>{let r=n;for(let s=2;i.some(f=>f.name===r);s++)r=`${n} ${s}`;return r},T=(n,r)=>Array.isArray(n)&&n.length===r.length&&r.every(s=>n.includes(s)),I=(n,r)=>{const s=n===null?i.find(u=>u.type==="createdTime"):i.find(u=>u.type==="lastModifiedTime"&&(n.length?T(u.options?.referencedFieldIds,n):!u.options?.referencedFieldIds?.length));if(s)return s.id;const f=n===null?"Created":n.length?`${n.map(u=>i.find(a=>a.id===u).name).join(" and ")} modified`:"Last modified",h={id:n===null?"fldSvCreated":`fldSvModified${n.join("")}`,name:o(f),type:n===null?"createdTime":"lastModifiedTime",options:{...n?.length?{referencedFieldIds:n}:{},result:{type:"dateTime"}}};return i.push(h),e.push({field:h,usedBy:r}),h.id};for(const[n,r]of i.entries()){if(r.type!=="formula"||typeof r.options?.formula!="string")continue;const s=r.options.formula,f=q(s),h=[];for(const a of f.matchAll(/\bCREATED_TIME\s*\(\s*\)/gi))h.push([a.index,a.index+a[0].length,`{${I(null,r.name)}}`]);for(const a of f.matchAll(/\bLAST_MODIFIED_TIME\s*\(\s*((?:\{[^}]*\}\s*,?\s*)*)\)/gi)){const y=[...a[1].matchAll(/\{([^}]*)\}/g)].map(g=>l(g[1]));y.some(g=>!g)||h.push([a.index,a.index+a[0].length,`{${I(y,r.name)}}`])}if(!h.length)continue;let u=s;for(const[a,y,g]of h.sort((N,C)=>C[0]-N[0]))u=u.slice(0,a)+g+u.slice(y);i[n]={...r,options:{...r.options,formula:u}}}return{table:e.length||i.some((n,r)=>n!==t.fields[r])?{...t,fields:i}:t,added:e}}export function formulaFunctionsUsed(t){const i=new Set;return B(t,e=>{for(const l of e.matchAll(/([A-Za-z_][A-Za-z0-9_]*)\s*\(/g))i.add(l[1].toUpperCase());return e},e=>e),[...i]}function te(t,i){return B(t,e=>e,e=>i.get(e.trim())??e)}function ie(t,i){const e=t.options??{},l=i.keys.get(i.table.id),o=(n,r)=>i.report.push({kind:n,table:i.table.name,name:t.name,message:r}),T=n=>{const r=l.get(String(n));return r||o("link","The link field it reads is not in the table."),r},I=(n,r)=>{const s=i.table.fields.find(f=>f.id===n);return i.keys.get(String(s?.options?.linkedTableId))?.get(String(r))};switch(t.type){case"singleLineText":return{fieldType:"text"};case"multilineText":return{fieldType:"longText"};case"richText":return{fieldType:"longText",fieldProps:{richText:!0}};case"email":return{fieldType:"email"};case"url":return{fieldType:"url"};case"phoneNumber":return{fieldType:"phone"};case"number":{const n=Number(e.precision??0);return{fieldType:"number",fieldProps:n>0?{format:"decimal",precision:n}:{format:"integer",precision:0}}}case"currency":return{fieldType:"number",fieldProps:{format:"currency",precision:Number(e.precision??2),symbol:e.symbol??"$"}};case"percent":return{fieldType:"number",fieldProps:{format:"percent",precision:Number(e.precision??0)}};case"rating":{const n=airtableColor(e.color);return{fieldType:"rating",fieldProps:{max:Number(e.max??5),...U.has(e.icon)&&e.icon!=="check"?{icon:e.icon}:{},...n?{color:n}:{}}}}case"duration":return{fieldType:"duration",fieldProps:J.has(e.durationFormat)?{durationFormat:e.durationFormat}:{}};case"checkbox":{const n=airtableColor(e.color),r=e.icon==="xCheckbox"?"x":U.has(e.icon)?e.icon:void 0;return{fieldType:"checkbox",fieldProps:{...r?{icon:r}:{},...n?{color:n}:{}}}}case"singleSelect":case"multipleSelects":{const n=(Array.isArray(e.choices)?e.choices:[]).map(r=>{const s=airtableColor(r.color);return{value:String(r.name),...s?{color:s}:{}}});return{fieldType:t.type==="singleSelect"?"singleSelect":"multiSelect",fieldProps:{options:n}}}case"date":return{fieldType:"date",fieldProps:w(e,!1)};case"dateTime":return{fieldType:"date",fieldProps:w(e,!0)};case"singleCollaborator":return{fieldType:"user",fieldProps:{multiple:!1}};case"multipleCollaborators":return{fieldType:"user",fieldProps:{multiple:!0}};case"multipleRecordLinks":{const n=String(e.linkedTableId??"");i.tableIds.has(n)||o("link","It links to a table that was not imported; the record ids stay, the cells show none of them.");const r=e.inverseLinkFieldId?i.keys.get(n)?.get(String(e.inverseLinkFieldId)):void 0,s=typeof e.viewIdForRecordSelection=="string"&&e.viewIdForRecordSelection?{pickFrom:e.viewIdForRecordSelection}:{};return{fieldType:"link",fieldProps:{table:n,multiple:e.prefersSingleRecordLink!==!0,...r&&n!==i.table.id&&i.tableIds.has(n)?{inverse:r}:{},...s}}}case"multipleAttachments":return{fieldType:"attachment"};case"barcode":return{fieldType:"barcode"};case"autoNumber":return{fieldType:"autoNumber"};case"button":return o("setting","The API does not say what the button does: set its URL (fieldProps.url, with {Field name} for values) or fieldProps.onClick."),{fieldType:"button",fieldProps:{label:String(e.label??t.name)}};case"createdTime":return{fieldType:"createdTime",fieldProps:w(e.result?.options,e.result?.type!=="date")};case"lastModifiedTime":case"lastModifiedBy":{const n=(Array.isArray(e.referencedFieldIds)?e.referencedFieldIds:[]).map(s=>l.get(s)).filter(Boolean),r=n.length?{watch:"specific",watchFields:n}:{watch:"all"};return t.type==="lastModifiedTime"?{fieldType:"lastModifiedTime",fieldProps:{...r,...w(e.result?.options,e.result?.type!=="date")}}:{fieldType:"lastModifiedBy",fieldProps:r}}case"createdBy":return{fieldType:"createdBy"};case"aiText":{const n=new Map(i.table.fields.map(u=>[u.id,u.name])),s=(Array.isArray(e.prompt)?e.prompt:typeof e.prompt=="string"?[e.prompt]:[]).map(u=>{if(typeof u=="string")return u;const a=u?.field?.fieldId;return a!=null?`{${n.get(String(a))??String(a)}}`:""}).join(""),f=i.table.fields.filter(u=>u.id!==t.id).map(u=>({field:l.get(u.id),header:u.name})),h=W(s,f,[t.name]);return s.trim()?h?o("setting",`${h}: fix the prompt in the field editor. The generated values come over as they are.`):o("setting","The generated values come over as they are. New ones come from the AI provider your app sets with setAIProvider()."):o("setting","The API gave no prompt: write one in the field editor. The generated values come over as they are."),{fieldType:"ai",fieldProps:{prompt:s,output:"text",auto:!0}}}case"formula":{const n=new Map(i.table.fields.map(f=>[f.id,f.name])),r=te(String(e.formula??""),n),s=formulaFunctionsUsed(r).filter(f=>!_.includes(f));if(s.length)o("formula",`Uses ${s.join(", ")}, which Base formulas do not have: the cells show #ERROR until that part is rewritten.`);else{const f=i.table.fields.filter(u=>u.id!==t.id).map(u=>({field:l.get(u.id),header:u.name})),h=G(r,j(f,[t.name]));h&&o("formula",`${h}: the cells show #ERROR.`)}return{fieldType:"formula",fieldProps:{formula:r,...ne(e.result)}}}case"rollup":{const n=T(e.recordLinkFieldId),r=I(e.recordLinkFieldId,e.fieldIdInLinkedTable),s=/^\s*([A-Za-z_]+)\s*\(\s*values\s*\)\s*$/i.exec(String(e.formula??""))?.[1]?.toUpperCase(),f=s&&v.has(s)?s:$.has(e.result?.type)?"SUM":"ARRAYJOIN";s?v.has(s)||o("formula",`The rollup's ${s}(values) has no Base aggregation; it is set to ${f}.`):o("setting",`The schema does not include the rollup's aggregation; it is set to ${f}. Change it in the field editor if the base used another.`);const h=e.result?.options?.precision;return{fieldType:"rollup",fieldProps:{linkField:n,field:r,aggregation:f,...h!=null&&$.has(e.result?.type)?{precision:Number(h)}:{}}}}case"multipleLookupValues":return{fieldType:"lookup",fieldProps:{linkField:T(e.recordLinkFieldId),field:I(e.recordLinkFieldId,e.fieldIdInLinkedTable)}};case"count":return{fieldType:"count",fieldProps:{linkField:T(e.recordLinkFieldId)}};default:return null}}function ne(t){const i=t?.options??{},e=i.precision!=null?{precision:Number(i.precision)}:{};switch(t?.type){case"number":return{result:"number",...e};case"currency":return{result:"currency",...e,...i.symbol?{symbol:i.symbol}:{}};case"percent":return{result:"percent",...e};case"date":return{result:"date",...w(i,!1)};case"dateTime":return{result:"date",...w(i,!0)};default:return{result:"auto"}}}const F=t=>Array.isArray(t)?t:t==null?[]:[t];function re(t){const i=t.thumbnails?.large?.url??t.thumbnails?.small?.url;return{id:String(t.id??t.url),url:String(t.url??""),name:String(t.filename??t.name??""),type:String(t.type??""),...typeof t.size=="number"?{size:t.size}:{},...typeof t.width=="number"?{width:t.width}:{},...typeof t.height=="number"?{height:t.height}:{},...i?{thumbnailUrl:String(i)}:{}}}function M(t){if(t==null)return"";if(Array.isArray(t))return t.map(M).join(", ");if(typeof t=="object"){const i=t;return"value"in i?M(i.value):"name"in i?String(i.name):"text"in i?String(i.text):JSON.stringify(t)}return String(t)}export function baseFromAirtable(t,i={},e={}){const l=[];for(const a of Array.isArray(t?.tables)?t.tables:[])if(!a||!Array.isArray(a.fields))throw Object.assign(new Error(`baseFromAirtable: a table in this file has no list of fields. Pass the JSON of Airtable's "Get base schema" call.`),{code:"bad-airtable-schema"});const o=(Array.isArray(t?.tables)?t.tables:[]).map(ee),T=o.map(a=>a.table),I=e.tables?.length?e.tables.map(a=>T.find(y=>y.id===a||y.name===a)).filter(a=>!!a):T,n=new Set(I.map(a=>a.id)),r=new Map;for(const a of T){const y=new Set(["id"]);r.set(a.id,new Map(a.fields.map(g=>[g.id,Q(g.name,y)])))}const s=new Map,f=e.userId??(a=>a.id),h=a=>{if(a==null||typeof a!="object")return a==null?null:String(a);const y=a,g=f(y);return s.has(g)||s.set(g,{id:g,name:y.name??y.email??g,...y.email?{email:y.email}:{}}),g};return{tables:I.map(a=>{const y={table:a,keys:r,tableIds:n,report:l};for(const{field:d,usedBy:c}of o.find(b=>b.table===a)?.added??[]){const b=(d.options?.referencedFieldIds??[]).map(m=>a.fields.find(A=>A.id===m).name),p=m=>l.push({kind:"field",table:a.name,name:d.name,message:`Added for ${c}, ${m}`});d.type==="createdTime"?p("which reads CREATED_TIME(): a Base record keeps that time in a Created time field. It holds each record's createdTime from the API."):b.length?p(`which reads when ${b.join(" and ")} last changed: a Last modified time field that watches ${b.length>1?"them":"it"}. The API does not say when a field last changed, so it is empty until the next edit.`):p("which reads LAST_MODIFIED_TIME(): a Last modified time field. The API does not say when a record last changed, so it is empty until the next edit.")}const g=r.get(a.id),N=a.primaryFieldId??a.fields[0]?.id,P=[...a.fields].sort((d,c)=>+(c.id===N)-+(d.id===N)).map(d=>{let c=ie(d,y);return c||(l.push({kind:"field",table:a.name,name:d.name,message:`Base has no "${d.type}" field: it is a text field, with each value as text.`}),c={fieldType:"text"}),{f:d,key:g.get(d.id),fieldType:c.fieldType,fieldProps:c.fieldProps,known:c.fieldType!=="text"||d.type==="singleLineText"}}),S=P.map(({f:d,key:c,fieldType:b,fieldProps:p})=>({id:c,field:c,header:d.name,fieldType:b,...p&&Object.keys(p).length?{fieldProps:p}:{},...d.description?{description:d.description}:{}})),k=i[a.id]??i[a.name],Y=(Array.isArray(k)?k:k?.records??[]).map(d=>{const c={id:d.id};for(const{f:b,key:p,fieldType:m,fieldProps:A,known:O}of P){if(Z.has(b.type))continue;let E=d.fields?.[b.name]??d.fields?.[b.id];b.type==="createdTime"&&E==null&&(E=d.createdTime),E!==void 0&&(O?m==="user"||m==="createdBy"||m==="lastModifiedBy"?c[p]=A?.multiple?F(E).map(h).filter(R=>R!=null):h(Array.isArray(E)?E[0]:E):m==="attachment"?c[p]=F(E).filter(R=>R&&typeof R=="object").map(R=>re(R)):m==="link"?c[p]=F(E).map(R=>String(R&&typeof R=="object"?R.id:R)):m==="ai"?c[p]=E&&typeof E=="object"?E.value??null:E:c[p]=E:c[p]=M(E))}return c}),x=d=>S.find(d)?.field,D=[];for(const d of a.views??[]){const c=V[d.type],b=m=>l.push({kind:"view",table:a.name,name:d.name,message:m});if(!c){b(`Base has no "${d.type}" view; it was left out.`);continue}const p={id:d.id,name:d.name,type:c};if(c==="kanban"){const m=x(A=>A.fieldType==="singleSelect"||A.fieldType==="user"&&!A.fieldProps?.multiple);if(!m){b("A Kanban view needs a single select or a single user field; the table has none.");continue}p.stackBy=m,l.push({kind:"setting",table:a.name,name:d.name,message:`The API does not say which field the board stacks by; it uses ${S.find(A=>A.field===m).header}.`})}else if(c==="calendar"||c==="timeline"||c==="gantt"){const m=S.filter(A=>A.fieldType==="date").map(A=>String(A.field));if(!m.length){b(`A ${c==="calendar"?"calendar":c==="gantt"?"Gantt":"timeline"} needs a date field; the table has none.`);continue}p.dateField=m[0],c!=="calendar"&&m[1]&&(p.endField=m[1]),l.push({kind:"setting",table:a.name,name:d.name,message:`The API does not say which dates the view uses; it uses ${[p.dateField,p.endField].filter(Boolean).map(A=>S.find(O=>O.field===A).header).join(" to ")}.`}),c==="timeline"&&l.push({kind:"setting",table:a.name,name:d.name,message:"The API does not say which field the swimlanes are; pick it under Customize timeline, Lanes by."})}else if(c==="gallery"){const m=x(A=>A.fieldType==="attachment");m&&(p.coverField=m)}D.push(p)}return D.length||D.push({id:"grid",name:"Grid view",type:"grid"}),{id:a.id,name:a.name,primaryField:g.get(N??"")??String(S[0]?.field??""),columns:S,data:Y,views:D}}),users:[...s.values()],report:l}}const L="JavaScript regular expressions, not RE2.",ae=[["CONCATENATE","Text"],["LEFT","Text"],["RIGHT","Text"],["MID","Text","The count may be left out for the rest of the text."],["LEN","Text"],["FIND","Text","Case matters; 0 when the text is not there."],["SEARCH","Text","Case matters; empty when the text is not there."],["SUBSTITUTE","Text"],["REPLACE","Text"],["TRIM","Text"],["UPPER","Text"],["LOWER","Text"],["REPT","Text","At most 1,000 repeats.",!0],["T","Text"],["ENCODE_URL_COMPONENT","Text"],["REGEX_MATCH","Text",`${L} A leading (?i) works; other inline flags do not.`,!0],["REGEX_EXTRACT","Text",`${L} Empty when nothing matches.`,!0],["REGEX_REPLACE","Text",`${L} Replaces every match; the new text names a group by its number after a dollar sign, as JavaScript's replace does.`,!0],["IF","Logical"],["SWITCH","Logical",'Compares as text, so 1 matches "1".',!0],["AND","Logical"],["OR","Logical"],["NOT","Logical"],["XOR","Logical"],["TRUE","Logical","With or without the parentheses."],["FALSE","Logical","With or without the parentheses."],["BLANK","Logical"],["ERROR","Logical","The cell shows #ERROR."],["ISERROR","Logical","Division by zero is empty in Base, not an error, so ISERROR(1 / 0) is false.",!0],["ABS","Numeric"],["AVERAGE","Numeric"],["CEILING","Numeric"],["COUNT","Numeric"],["COUNTA","Numeric"],["COUNTALL","Numeric"],["EVEN","Numeric"],["EXP","Numeric"],["FLOOR","Numeric"],["INT","Numeric"],["LOG","Numeric","Base 10 unless a base is given."],["MAX","Numeric"],["MIN","Numeric"],["MOD","Numeric"],["ODD","Numeric"],["POWER","Numeric"],["ROUND","Numeric","Halves round toward positive: ROUND(-2.5) is -2."],["ROUNDDOWN","Numeric","Toward zero."],["ROUNDUP","Numeric","Away from zero."],["SQRT","Numeric"],["SUM","Numeric"],["VALUE","Numeric",'Skips characters that are not part of a number: VALUE("1,200.50 USD") is 1200.5.'],["DATEADD","Date",'The units Airtable names, except that "M" is minutes here: write "months".',!0],["DATESTR","Date"],["DATETIME_DIFF","Date",'Units as in DATEADD: "M" is minutes, write "months".',!0],["DATETIME_FORMAT","Date","moment.js tokens (YYYY, MMMM, Do, HH, A, Z, L, LL and the rest); week-of-year tokens are not read.",!0],["DATETIME_PARSE","Date","Reads the tokens DATETIME_FORMAT writes, with the separators as written. Text without a zone is local time.",!0],["DAY","Date"],["HOUR","Date"],["IS_AFTER","Date"],["IS_BEFORE","Date"],["IS_SAME","Date"],["MINUTE","Date"],["MONTH","Date"],["NOW","Date"],["SECOND","Date"],["SET_LOCALE","Date","Changes the month and weekday names DATETIME_FORMAT writes; ordinals (Do) stay English.",!0],["SET_TIMEZONE","Date","Changes what DATETIME_FORMAT writes. An unknown zone leaves the cell empty.",!0],["TIMESTR","Date"],["TONOW","Date","Calendar days from the date to today, signed.",!0],["FROMNOW","Date","Calendar days from today to the date, signed.",!0],["TODAY","Date"],["WEEKDAY","Date",'0 for Sunday; "Monday" as the second argument makes Monday 0.'],["WEEKNUM","Date",'Weeks start on Sunday, or on Monday with "Monday".'],["WORKDAY","Date",'Holidays as text ("2026-12-25, 2026-12-26") or a list of dates.'],["WORKDAY_DIFF","Date","Both days count. Holidays as in WORKDAY."],["YEAR","Date"],["ARRAYCOMPACT","Array"],["ARRAYFLATTEN","Array"],["ARRAYJOIN","Array"],["ARRAYUNIQUE","Array"],["ARRAYSLICE","Array"],["RECORD_ID","Record","The record's id; after baseFromAirtable, the Airtable record id."],["CREATED_TIME","Record","A Base record keeps that time in a Created time field. baseFromAirtable rewrites CREATED_TIME() to read the table's, and adds one when the table has none."],["LAST_MODIFIED_TIME","Record","A Base record keeps that time in a Last modified time field. baseFromAirtable rewrites LAST_MODIFIED_TIME() to read one that watches every field, and LAST_MODIFIED_TIME({Field}) one that watches that field, and adds it when the table has none."]];export function airtableFormulaSupport(){return ae.map(([t,i,e="",l])=>{const T=_.includes(t)?l?"different":"supported":"unsupported";return{name:t,group:i,status:T,note:e}})}
@@ -45,6 +45,14 @@ export declare function setAttachmentUploader(upload: AttachmentUploader | null)
45
45
  export declare const newAttachmentId: () => string;
46
46
  /** Upload one file with the column's uploader, the app's, or as a local blob URL. */
47
47
  export declare function uploadAttachment(file: File, props: AttachmentFieldProps, ctx: AttachmentUploadContext): Promise<Attachment>;
48
+ /** Whether a field takes pictures: no `accept`, or one that names images. */
49
+ export declare function takesImages(props: AttachmentFieldProps): boolean;
50
+ /**
51
+ * A photo from a phone's camera, made small enough to send: at most `max`
52
+ * pixels on its longer side, as a JPEG. A picture already that small, or one
53
+ * this browser cannot draw, is answered as it was.
54
+ */
55
+ export declare function shrinkPhoto(file: File, max?: number, quality?: number): Promise<File>;
48
56
  /** 'At most 1 file', 'At most 20 files'. */
49
57
  export declare const tooManyFiles: (maxFiles: number) => string;
50
58
  /**
@@ -1 +1 @@
1
- let p=null;export function setAttachmentUploader(t){p=t}let s=0;export const newAttachmentId=()=>`att-${Date.now().toString(36)}-${(s++).toString(36)}`;export async function uploadAttachment(t,e,n){const o=e.upload??p;return o?o(t,n):(n.onProgress(1),{id:newAttachmentId(),url:URL.createObjectURL(t),name:t.name,type:t.type||guessType(t.name),size:t.size})}export const tooManyFiles=t=>`At most ${t} ${t===1?"file":"files"}`;export function rejectReason(t,e,n){const o=e.maxFiles??20,r=e.maxSize??25*1024*1024;return n>=o?tooManyFiles(o):t.size!=null&&t.size>r?`Larger than ${formatBytes(r)}`:e.accept&&!accepts(e.accept,t)?"Not an accepted type":null}export function limitAttachments(t,e,n=0){const o=[],r=[];for(const i of t){const a=rejectReason(i,e,n+o.length);a?r.push(`${i.name}: ${a}`):o.push(i)}return{kept:o,rejected:r}}export function parseAttachments(t,e){const n=Array.isArray(t)?toAttachments(t):attachmentsFromText(String(t??""));return limitAttachments(n,e).kept}export function accepts(t,e){const n=e.name.toLowerCase(),o=(e.type||guessType(e.name)).toLowerCase();return t.split(",").map(r=>r.trim().toLowerCase()).filter(Boolean).some(r=>r.startsWith(".")?n.endsWith(r):r.endsWith("/*")?o.startsWith(r.slice(0,-1)):o===r)}const c={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",avif:"image/avif",pdf:"application/pdf",txt:"text/plain",csv:"text/csv",json:"application/json",zip:"application/zip",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",mp3:"audio/mpeg",wav:"audio/wav"};export function guessType(t){const e=t.split(/[?#]/)[0].split(".").pop()?.toLowerCase()??"";return c[e]??"application/octet-stream"}export const isImage=t=>(t.type||guessType(t.name??"")).startsWith("image/"),isPdf=t=>(t.type||guessType(t.name??""))==="application/pdf";export function formatBytes(t){if(t==null||!Number.isFinite(t))return"";if(t<1024)return`${t} B`;const e=n=>n<10?n.toFixed(1).replace(/\.0$/,""):String(Math.round(n));return t<1024*1024?`${e(t/1024)} KB`:t<1024*1024*1024?`${e(t/1024/1024)} MB`:`${e(t/1024/1024/1024)} GB`}export function toAttachments(t){return Array.isArray(t)?t.filter(e=>!!e&&typeof e=="object"&&typeof e.url=="string"):[]}export function attachmentsText(t){return toAttachments(t).map(e=>e.name).join(", ")}export function attachmentsFromText(t){const e=[];for(const n of t.split(/[\s,]+/)){let o;try{o=new URL(n)}catch{continue}if(o.protocol!=="http:"&&o.protocol!=="https:")continue;const r=decodeURIComponent(o.pathname.split("/").filter(Boolean).pop()??o.hostname);e.push({id:newAttachmentId(),url:o.href,name:r,type:guessType(r)})}return e}export async function pdfFrameUrl(t,e=fetch){try{const n=await e(t);if(!n.ok)return null;const o=new Uint8Array(await n.arrayBuffer());return String.fromCharCode(...o.subarray(0,1024)).includes("%PDF-")?URL.createObjectURL(new Blob([o],{type:"application/pdf"})):null}catch{return null}}export function safeUrl(t,e=!1){if(typeof t!="string")return null;if(e&&/^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/i.test(t))return t;try{const n=new URL(t,typeof location<"u"?location.href:"https://x.invalid/");return n.protocol==="http:"||n.protocol==="https:"||n.protocol==="blob:"?n.href:null}catch{return null}}
1
+ let p=null;export function setAttachmentUploader(t){p=t}let m=0;export const newAttachmentId=()=>`att-${Date.now().toString(36)}-${(m++).toString(36)}`;export async function uploadAttachment(t,e,o){const n=e.upload??p;return n?n(t,o):(o.onProgress(1),{id:newAttachmentId(),url:URL.createObjectURL(t),name:t.name,type:t.type||guessType(t.name),size:t.size})}export function takesImages(t){return!t.accept||t.accept.split(",").some(e=>/^\s*(image\/|\.(jpe?g|png|webp|heic|gif)\b)/i.test(e))}export async function shrinkPhoto(t,e=2e3,o=.85){if(!/^image\/(jpeg|png|webp)$/.test(t.type)||typeof createImageBitmap!="function"||typeof document>"u")return t;try{const n=await createImageBitmap(t),r=Math.min(1,e/Math.max(n.width,n.height));if(r>=1)return n.close?.(),t;const a=document.createElement("canvas");a.width=Math.round(n.width*r),a.height=Math.round(n.height*r),a.getContext("2d")?.drawImage(n,0,0,a.width,a.height),n.close?.();const i=await new Promise(s=>a.toBlob(s,"image/jpeg",o));if(!i)return t;const c=t.name.replace(/\.[^.]+$/,"")+".jpg";return new File([i],c,{type:"image/jpeg",lastModified:t.lastModified})}catch{return t}}export const tooManyFiles=t=>`At most ${t} ${t===1?"file":"files"}`;export function rejectReason(t,e,o){const n=e.maxFiles??20,r=e.maxSize??25*1024*1024;return o>=n?tooManyFiles(n):t.size!=null&&t.size>r?`Larger than ${formatBytes(r)}`:e.accept&&!accepts(e.accept,t)?"Not an accepted type":null}export function limitAttachments(t,e,o=0){const n=[],r=[];for(const a of t){const i=rejectReason(a,e,o+n.length);i?r.push(`${a.name}: ${i}`):n.push(a)}return{kept:n,rejected:r}}export function parseAttachments(t,e){const o=Array.isArray(t)?toAttachments(t):attachmentsFromText(String(t??""));return limitAttachments(o,e).kept}export function accepts(t,e){const o=e.name.toLowerCase(),n=(e.type||guessType(e.name)).toLowerCase();return t.split(",").map(r=>r.trim().toLowerCase()).filter(Boolean).some(r=>r.startsWith(".")?o.endsWith(r):r.endsWith("/*")?n.startsWith(r.slice(0,-1)):n===r)}const u={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",avif:"image/avif",pdf:"application/pdf",txt:"text/plain",csv:"text/csv",json:"application/json",zip:"application/zip",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",mp4:"video/mp4",webm:"video/webm",mov:"video/quicktime",mp3:"audio/mpeg",wav:"audio/wav"};export function guessType(t){const e=t.split(/[?#]/)[0].split(".").pop()?.toLowerCase()??"";return u[e]??"application/octet-stream"}export const isImage=t=>(t.type||guessType(t.name??"")).startsWith("image/"),isPdf=t=>(t.type||guessType(t.name??""))==="application/pdf";export function formatBytes(t){if(t==null||!Number.isFinite(t))return"";if(t<1024)return`${t} B`;const e=o=>o<10?o.toFixed(1).replace(/\.0$/,""):String(Math.round(o));return t<1024*1024?`${e(t/1024)} KB`:t<1024*1024*1024?`${e(t/1024/1024)} MB`:`${e(t/1024/1024/1024)} GB`}export function toAttachments(t){return Array.isArray(t)?t.filter(e=>!!e&&typeof e=="object"&&typeof e.url=="string"):[]}export function attachmentsText(t){return toAttachments(t).map(e=>e.name).join(", ")}export function attachmentsFromText(t){const e=[];for(const o of t.split(/[\s,]+/)){let n;try{n=new URL(o)}catch{continue}if(n.protocol!=="http:"&&n.protocol!=="https:")continue;const r=decodeURIComponent(n.pathname.split("/").filter(Boolean).pop()??n.hostname);e.push({id:newAttachmentId(),url:n.href,name:r,type:guessType(r)})}return e}export async function pdfFrameUrl(t,e=fetch){try{const o=await e(t);if(!o.ok)return null;const n=new Uint8Array(await o.arrayBuffer());return String.fromCharCode(...n.subarray(0,1024)).includes("%PDF-")?URL.createObjectURL(new Blob([n],{type:"application/pdf"})):null}catch{return null}}export function safeUrl(t,e=!1){if(typeof t!="string")return null;if(e&&/^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/i.test(t))return t;try{const o=new URL(t,typeof location<"u"?location.href:"https://x.invalid/");return o.protocol==="http:"||o.protocol==="https:"||o.protocol==="blob:"?o.href:null}catch{return null}}
@@ -0,0 +1,36 @@
1
+ import { type BaseTable } from './base-tables.js';
2
+ import { type AutomationAction, type AutomationTrigger, type BaseAutomation } from './automations.svelte.js';
3
+ import type { FieldColumn } from './grid-access.js';
4
+ import { type BaseMessageKey } from './messages.svelte.js';
5
+ /** Field types an automation cannot write: the base computes them. */
6
+ export declare const COMPUTED_TYPES: Set<string>;
7
+ /** A table's fields, as the editors list them. */
8
+ export declare const fieldsOf: (t: BaseTable | undefined) => FieldColumn[];
9
+ /** The fields an action can set. */
10
+ export declare const writableFields: (t: BaseTable | undefined) => FieldColumn[];
11
+ /** The triggers, in the order the editors offer them. */
12
+ export declare const TRIGGER_CHOICES: ReadonlyArray<{
13
+ value: AutomationTrigger['type'];
14
+ key: BaseMessageKey;
15
+ }>;
16
+ /** A webhook trigger's secret: 32 random hex digits. */
17
+ export declare function newWebhookToken(): string;
18
+ /** A trigger of a type, with what it needs to start from. */
19
+ export declare function newTrigger(type: AutomationTrigger['type'], table: BaseTable): AutomationTrigger;
20
+ /**
21
+ * The actions, as `<option>`s: the base's own, then the app's (`run:<id>`).
22
+ * Inside an "If" or a "Find records" (`nested`), no script and no color; one
23
+ * level down, no further "If" or "Find records".
24
+ */
25
+ export declare function actionChoices(nested?: number): Array<{
26
+ value: string;
27
+ label: string;
28
+ }>;
29
+ /** An action of a choice, empty, on `table` (a new record goes there first). */
30
+ export declare function newAction(value: string, table: BaseTable): AutomationAction;
31
+ /** A new script's first lines: what it can read and do. */
32
+ export declare const SCRIPT_START = "// The record that set it off: input.config() has its fields by name.\nconst config = input.config()\nconsole.log('Record', config.recordId)\n\n// Read and change any table of the base:\n// const table = base.getTable('Tasks')\n// const query = await table.selectRecordsAsync()\n// await table.updateRecordAsync(config.recordId, { Status: 'Done' })\n\n// Hand values to the next steps as {script.name}:\n// output.set('name', 'value')\n";
33
+ /** The `<option>` value of an action. */
34
+ export declare const actionKey: (a: AutomationAction) => string;
35
+ /** A new automation on a table: when a record is created, show a notice naming it. */
36
+ export declare function newAutomation(table: BaseTable): BaseAutomation;
@@ -0,0 +1,12 @@
1
+ import{CRON_PRESETS as i}from"../scheduling.js";import{primaryOf as s}from"./base-tables.js";import{listAutomationActions as n,tableFields as c}from"./automations.svelte.js";import{bm as t}from"./messages.svelte.js";export const COMPUTED_TYPES=new Set(["formula","lookup","rollup","count","button","autoNumber","createdTime","lastModifiedTime","createdBy","lastModifiedBy"]),fieldsOf=e=>e?[...c(e).values()]:[],writableFields=e=>fieldsOf(e).filter(r=>!COMPUTED_TYPES.has(String(r.fieldType??""))),TRIGGER_CHOICES=[{value:"recordCreated",key:"extras.triggerCreated"},{value:"recordUpdated",key:"extras.triggerUpdated"},{value:"recordMatches",key:"extras.triggerMatches"},{value:"formSubmitted",key:"extras.triggerForm"},{value:"button",key:"extras.triggerButton"},{value:"scheduled",key:"extras.triggerScheduled"},{value:"webhookReceived",key:"extras.triggerWebhook"}];export function newWebhookToken(){const e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),[...e].map(r=>r.toString(16).padStart(2,"0")).join("")}export function newTrigger(e,r){switch(e){case"recordUpdated":return{type:e,fields:[]};case"formSubmitted":return{type:e};case"button":return{type:e,field:fieldsOf(r).find(a=>a.fieldType==="button")?.id??""};case"scheduled":return{type:e,cron:i[3].cron};case"webhookReceived":return{type:e,token:newWebhookToken()};default:return{type:e}}}export function actionChoices(e=0){const r=[{value:"updateRecord",label:t("extras.doUpdateRecord")},{value:"createRecord",label:t("extras.doCreateRecord")},{value:"repeat",label:t("extras.doRepeat")},{value:"if",label:t("extras.doIf")},{value:"notify",label:t("extras.actionNotify")},{value:"highlight",label:t("extras.doHighlight")},{value:"email",label:t("extras.actionEmail")},{value:"chat",label:t("extras.doChat")},{value:"textMessage",label:t("extras.doText")},{value:"webhook",label:t("extras.actionWebhook")},{value:"ai",label:t("extras.doAi")},{value:"script",label:t("extras.doScript")},...n().map(a=>({value:`run:${a.id}`,label:a.label}))];return e?r.filter(a=>a.value!=="script"&&a.value!=="highlight"&&(e<2||a.value!=="if"&&a.value!=="repeat")):r}export function newAction(e,r){if(e.startsWith("run:"))return{type:"run",action:e.slice(4)};switch(e){case"updateRecord":return{type:"updateRecord",values:{}};case"createRecord":return{type:"createRecord",table:r.id,values:{}};case"highlight":return{type:"highlight",background:"#fee2e2",color:"#991b1b"};case"webhook":return{type:"webhook",url:"https://",body:""};case"email":return{type:"email",to:"",subject:"",body:""};case"chat":return{type:"chat",service:"slack",url:"https://hooks.slack.com/services/",text:""};case"textMessage":return{type:"textMessage",channel:"sms",to:"",text:""};case"repeat":return{type:"repeat",table:r.id,limit:100,actions:[]};case"if":return{type:"if",then:[],else:[]};case"ai":return{type:"ai",prompt:""};case"script":return{type:"script",code:SCRIPT_START};default:return{type:"notify",message:"",severity:"info"}}}export const SCRIPT_START=`// The record that set it off: input.config() has its fields by name.
2
+ const config = input.config()
3
+ console.log('Record', config.recordId)
4
+
5
+ // Read and change any table of the base:
6
+ // const table = base.getTable('Tasks')
7
+ // const query = await table.selectRecordsAsync()
8
+ // await table.updateRecordAsync(config.recordId, { Status: 'Done' })
9
+
10
+ // Hand values to the next steps as {script.name}:
11
+ // output.set('name', 'value')
12
+ `,actionKey=e=>e.type==="run"?`run:${e.action}`:e.type;export function newAutomation(e){const r=fieldsOf(e),a=r.find(o=>o.id===s(e))??r[0];return{id:`auto-${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,name:t("extras.newAutomation"),enabled:!0,trigger:{type:"recordCreated"},actions:[{type:"notify",message:t("extras.newRecordMessage",{field:a?.header??t("extras.nameFallback")})}]}}
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Automation actions that leave the base: call a webhook, send an email.
2
+ * Automation actions that leave the base: call a webhook, send an email, a
3
+ * chat message or a text message.
3
4
  *
4
5
  * Both fill `{Field name}` tokens from the record. A webhook may also name
5
6
  * secrets, `{secret:SLACK_TOKEN}`, which only the server runner reads (from
@@ -28,6 +29,34 @@ export type EmailAction = {
28
29
  subject: string;
29
30
  body: string;
30
31
  };
32
+ /**
33
+ * A text message to phones, sent by the server runner's `sendText` (your SMS
34
+ * or Viber provider). `channel` "viber" asks for Viber, with an SMS to a phone
35
+ * that is not on Viber when the provider can send one. `to` and `text` name fields.
36
+ */
37
+ export type TextMessageAction = {
38
+ type: 'textMessage';
39
+ channel?: 'sms' | 'viber';
40
+ to: string;
41
+ text: string;
42
+ };
43
+ /**
44
+ * A message to a chat channel through its incoming webhook: Slack's
45
+ * "Incoming Webhooks", a Teams channel's "Post to a channel when a webhook
46
+ * request is received" workflow, or a Google Chat space's webhook. `url` is
47
+ * the address the chat app gave (it may name a secret); `text` names fields.
48
+ */
49
+ export type ChatAction = {
50
+ type: 'chat';
51
+ service: 'slack' | 'teams' | 'googleChat';
52
+ url: string;
53
+ text: string;
54
+ };
55
+ /** What each chat app reads from its webhook. */
56
+ export declare function chatPayload(service: ChatAction['service'], text: string): Record<string, unknown>;
57
+ /** The chat apps' own addresses: a chat action calls only these, so it cannot be pointed anywhere else. */
58
+ export declare function chatHostOk(service: ChatAction['service'], url: URL): boolean;
59
+ export declare function sendChat(action: ChatAction, ctx: OutboundContext): Promise<string>;
31
60
  export type OutboundContext = {
32
61
  automation: string;
33
62
  table: string;
@@ -53,4 +82,11 @@ export type OutgoingEmail = {
53
82
  text: string;
54
83
  };
55
84
  export declare function sendEmailAction(action: EmailAction, ctx: OutboundContext, send: ((email: OutgoingEmail) => Promise<unknown> | unknown) | undefined): Promise<string>;
85
+ /** A text message as `sendText` gets it: the phones as written, the text filled in. */
86
+ export type OutgoingText = {
87
+ to: string[];
88
+ text: string;
89
+ channel: 'sms' | 'viber';
90
+ };
91
+ export declare function sendTextAction(action: TextMessageAction, ctx: OutboundContext, send: ((message: OutgoingText) => Promise<unknown> | unknown) | undefined): Promise<string>;
56
92
  export {};
@@ -1 +1 @@
1
- const b=/\{([^{}\n]+)\}/g,y=/^secret:([A-Za-z0-9_.-]+)$/;function E(t,e){if(!e.secret)throw new Error(`{secret:${t}} is read on the server only; run this automation on the server`);const r=e.secret(t);if(r==null)throw new Error(`No secret named ${t}`);return r}function h(t,e,r=o=>o,n=o=>o){return t.replace(b,(o,s)=>{const l=y.exec(s);if(l)return n(E(l[1],e));const c=e.fill(o);return c===o?o:r(c)})}const d=t=>JSON.stringify(t).slice(1,-1);export async function callWebhook(t,e){if(!(e.fetch??globalThis.fetch))throw new Error("No fetch here to call the webhook with");const r=h(t.url,e,encodeURIComponent);if(!/^https?:\/\//i.test(r))throw new Error("A webhook URL starts with https:// or http://");const o=(e.checkUrl?await e.checkUrl(new URL(r)):void 0)??e.fetch??globalThis.fetch,s={"content-type":"application/json"};for(const[f,w]of Object.entries(t.headers??{}))s[f.toLowerCase()]=h(w,e);const l=(s["content-type"]??"").includes("json"),c=t.body?.trim()?l?h(t.body,e,d,d):h(t.body,e):JSON.stringify({automation:e.automation,table:e.table,record:e.record?{id:e.record.id??null,...e.fields()}:null}),a=t.method??"POST",i=await o(r,{method:a,headers:s,body:c,...e.checkUrl?{redirect:"manual"}:{}}),u=(()=>{try{return new URL(r).host}catch{return r}})();if(!i.ok)throw new Error(`${a} ${u} answered ${i.status}${i.statusText?` ${i.statusText}`:""}`);return`${a} ${u}: ${i.status}`}export async function sendEmailAction(t,e,r){if(!r)throw new Error("Email is sent by the server runner; give createAutomationServer a sendEmail");const n=e.fill(t.to).split(/\s*[,;]\s*/).filter(Boolean);if(!n.length)throw new Error("No address to send to");return await r({to:n,subject:e.fill(t.subject),text:e.fill(t.body)}),`To ${n.join(", ")}: ${e.fill(t.subject)}`}
1
+ export function chatPayload(t,e){return t==="teams"?{type:"message",attachments:[{contentType:"application/vnd.microsoft.card.adaptive",contentUrl:null,content:{$schema:"http://adaptivecards.io/schemas/adaptive-card.json",type:"AdaptiveCard",version:"1.4",body:[{type:"TextBlock",text:e,wrap:!0}]}}]}:{text:e}}export function chatHostOk(t,e){const r=e.hostname.toLowerCase();return e.protocol!=="https:"?!1:t==="slack"?r==="hooks.slack.com":t==="googleChat"?r==="chat.googleapis.com":/(^|\.)logic\.azure\.com$/.test(r)||/(^|\.)powerplatform\.com$/.test(r)||/(^|\.)webhook\.office\.com$/.test(r)}export async function sendChat(t,e){const r=c(t.url,e,encodeURIComponent);let s;try{s=new URL(r)}catch{throw new Error("The chat address is not a URL")}if(!chatHostOk(t.service,s))throw new Error(`That is not a ${t.service==="googleChat"?"Google Chat":t.service==="teams"?"Teams":"Slack"} webhook address`);const o=e.fill(t.text);if(!o.trim())throw new Error("The message is empty");const n=e.fetch??globalThis.fetch;if(!n)throw new Error("No fetch here to send the message with");const a=await n(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(chatPayload(t.service,o))});if(!a.ok)throw new Error(`${s.host} answered ${a.status}`);return o.length>120?o.slice(0,117)+"...":o}const p=/\{([^{}\n]+)\}/g,m=/^secret:([A-Za-z0-9_.-]+)$/;function y(t,e){if(!e.secret)throw new Error(`{secret:${t}} is read on the server only; run this automation on the server`);const r=e.secret(t);if(r==null)throw new Error(`No secret named ${t}`);return r}function c(t,e,r=o=>o,s=o=>o){return t.replace(p,(o,n)=>{const a=m.exec(n);if(a)return s(y(a[1],e));const h=e.fill(o);return h===o?o:r(h)})}const d=t=>JSON.stringify(t).slice(1,-1);export async function callWebhook(t,e){if(!(e.fetch??globalThis.fetch))throw new Error("No fetch here to call the webhook with");const r=c(t.url,e,encodeURIComponent);if(!/^https?:\/\//i.test(r))throw new Error("A webhook URL starts with https:// or http://");const o=(e.checkUrl?await e.checkUrl(new URL(r)):void 0)??e.fetch??globalThis.fetch,n={"content-type":"application/json"};for(const[u,w]of Object.entries(t.headers??{}))n[u.toLowerCase()]=c(w,e);const a=(n["content-type"]??"").includes("json"),h=t.body?.trim()?a?c(t.body,e,d,d):c(t.body,e):JSON.stringify({automation:e.automation,table:e.table,record:e.record?{id:e.record.id??null,...e.fields()}:null}),l=t.method??"POST",i=await o(r,{method:l,headers:n,body:h,...e.checkUrl?{redirect:"manual"}:{}}),f=(()=>{try{return new URL(r).host}catch{return r}})();if(!i.ok)throw new Error(`${l} ${f} answered ${i.status}${i.statusText?` ${i.statusText}`:""}`);return`${l} ${f}: ${i.status}`}export async function sendEmailAction(t,e,r){if(!r)throw new Error("Email is sent by the server runner; give createAutomationServer a sendEmail");const s=e.fill(t.to).split(/\s*[,;]\s*/).filter(Boolean);if(!s.length)throw new Error("No address to send to");return await r({to:s,subject:e.fill(t.subject),text:e.fill(t.body)}),`To ${s.join(", ")}: ${e.fill(t.subject)}`}export async function sendTextAction(t,e,r){if(!r)throw new Error("Text messages are sent by the server runner; give createAutomationServer a sendText");const s=e.fill(t.to).split(/\s*[,;]\s*/).map(a=>a.trim()).filter(Boolean);if(!s.length)throw new Error("No phone number to send to");const o=e.fill(t.text).trim();if(!o)throw new Error("The message is empty");const n=t.channel==="viber"?"viber":"sms";return await r({to:s,text:o,channel:n}),`${n==="viber"?"Viber":"SMS"} to ${s.join(", ")}`}