@svgrid/enterprise 3.1.34 → 3.1.35

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 (171) hide show
  1. package/dist/SvGridBoard.svelte +1 -1
  2. package/dist/cdn/svgrid-enterprise.svelte-external.js +2 -2
  3. package/dist/designer/assets/{index-v61ZvIWw.js → index-Eyxa9vgS.js} +3 -3
  4. package/dist/designer/assets/{src-DkFgWld_.js → src-CSmsOfsG.js} +15 -15
  5. package/dist/designer/index.html +2 -2
  6. package/dist/fields/AiCell.svelte +41 -0
  7. package/dist/fields/AiCell.svelte.d.ts +5 -0
  8. package/dist/fields/BaseChartView.svelte +1 -1
  9. package/dist/fields/BaseDashboardView.svelte +133 -0
  10. package/dist/fields/BaseDashboardView.svelte.d.ts +17 -0
  11. package/dist/fields/BaseImport.svelte +89 -0
  12. package/dist/fields/BaseImport.svelte.d.ts +15 -0
  13. package/dist/fields/BaseInboxView.svelte +112 -0
  14. package/dist/fields/BaseInboxView.svelte.d.ts +8 -0
  15. package/dist/fields/BaseListView.svelte +90 -0
  16. package/dist/fields/BaseListView.svelte.d.ts +8 -0
  17. package/dist/fields/BaseSearch.svelte +78 -0
  18. package/dist/fields/BaseSearch.svelte.d.ts +10 -0
  19. package/dist/fields/BaseTableView.svelte +28 -3
  20. package/dist/fields/BaseTableView.svelte.d.ts +5 -1
  21. package/dist/fields/BaseTabs.svelte +45 -8
  22. package/dist/fields/BaseTabs.svelte.d.ts +25 -1
  23. package/dist/fields/BaseTrash.svelte +63 -0
  24. package/dist/fields/BaseTrash.svelte.d.ts +15 -0
  25. package/dist/fields/ChecklistCell.svelte +22 -0
  26. package/dist/fields/ChecklistCell.svelte.d.ts +10 -0
  27. package/dist/fields/ChecklistEditor.svelte +81 -0
  28. package/dist/fields/ChecklistEditor.svelte.d.ts +12 -0
  29. package/dist/fields/ColorCell.svelte +13 -0
  30. package/dist/fields/ColorCell.svelte.d.ts +8 -0
  31. package/dist/fields/ColorEditor.svelte +60 -0
  32. package/dist/fields/ColorEditor.svelte.d.ts +11 -0
  33. package/dist/fields/DashboardRecords.svelte +35 -0
  34. package/dist/fields/DashboardRecords.svelte.d.ts +11 -0
  35. package/dist/fields/DashboardTileEditor.svelte +138 -0
  36. package/dist/fields/DashboardTileEditor.svelte.d.ts +15 -0
  37. package/dist/fields/FieldEditor.svelte +32 -3
  38. package/dist/fields/FieldInput.svelte +1 -1
  39. package/dist/fields/GroupHeader.svelte +3 -3
  40. package/dist/fields/ListChips.svelte +21 -0
  41. package/dist/fields/ListChips.svelte.d.ts +9 -0
  42. package/dist/fields/MentionInput.svelte +59 -0
  43. package/dist/fields/MentionInput.svelte.d.ts +11 -0
  44. package/dist/fields/PropertyInput.svelte +13 -10
  45. package/dist/fields/RecordView.svelte +20 -25
  46. package/dist/fields/SvBase.svelte +48 -9
  47. package/dist/fields/SvBase.svelte.d.ts +33 -1
  48. package/dist/fields/SvBaseForm.svelte +2 -2
  49. package/dist/fields/SvBaseForm.svelte.d.ts +14 -0
  50. package/dist/fields/SvBaseViewBar.svelte +33 -12
  51. package/dist/fields/SvBaseViewBar.svelte.d.ts +2 -0
  52. package/dist/fields/TimeOfDayEditor.svelte +39 -0
  53. package/dist/fields/TimeOfDayEditor.svelte.d.ts +12 -0
  54. package/dist/fields/activity.svelte.d.ts +29 -0
  55. package/dist/fields/activity.svelte.js +1 -1
  56. package/dist/fields/ai-field.svelte.d.ts +91 -0
  57. package/dist/fields/ai-field.svelte.js +1 -0
  58. package/dist/fields/ai-prompt.d.ts +64 -0
  59. package/dist/fields/ai-prompt.js +7 -0
  60. package/dist/fields/airtable.d.ts +90 -0
  61. package/dist/fields/airtable.js +1 -0
  62. package/dist/fields/bar-request.svelte.d.ts +1 -1
  63. package/dist/fields/base-history.d.ts +56 -0
  64. package/dist/fields/base-history.js +1 -0
  65. package/dist/fields/base-import.d.ts +54 -0
  66. package/dist/fields/base-import.js +2 -0
  67. package/dist/fields/base-search.d.ts +34 -0
  68. package/dist/fields/base-search.js +1 -0
  69. package/dist/fields/base-share.d.ts +45 -0
  70. package/dist/fields/base-share.js +1 -0
  71. package/dist/fields/base-sql.js +3 -3
  72. package/dist/fields/base-trash.d.ts +51 -0
  73. package/dist/fields/base-trash.js +1 -0
  74. package/dist/fields/builtin-types.js +1 -1
  75. package/dist/fields/chart-view.d.ts +12 -0
  76. package/dist/fields/chart-view.js +1 -1
  77. package/dist/fields/checklist.d.ts +36 -0
  78. package/dist/fields/checklist.js +4 -0
  79. package/dist/fields/color-value.d.ts +14 -0
  80. package/dist/fields/color-value.js +1 -0
  81. package/dist/fields/convert.js +1 -1
  82. package/dist/fields/copy-text.d.ts +1 -1
  83. package/dist/fields/copy-text.js +1 -1
  84. package/dist/fields/dashboard.d.ts +143 -0
  85. package/dist/fields/dashboard.js +1 -0
  86. package/dist/fields/field-access.svelte.d.ts +37 -0
  87. package/dist/fields/field-access.svelte.js +1 -0
  88. package/dist/fields/field-ops.js +1 -1
  89. package/dist/fields/filter-model.d.ts +4 -11
  90. package/dist/fields/filter-model.js +1 -1
  91. package/dist/fields/form-logic.d.ts +69 -0
  92. package/dist/fields/form-logic.js +1 -0
  93. package/dist/fields/formula.js +1 -1
  94. package/dist/fields/grid-access.d.ts +8 -0
  95. package/dist/fields/grid-access.js +1 -1
  96. package/dist/fields/index.d.ts +16 -0
  97. package/dist/fields/index.js +1 -1
  98. package/dist/fields/list-view.d.ts +40 -0
  99. package/dist/fields/list-view.js +1 -0
  100. package/dist/fields/mentions.d.ts +50 -0
  101. package/dist/fields/mentions.js +1 -0
  102. package/dist/fields/palette.d.ts +4 -2
  103. package/dist/fields/palette.js +1 -1
  104. package/dist/fields/record-menu.js +1 -1
  105. package/dist/fields/registry.svelte.d.ts +5 -0
  106. package/dist/fields/registry.svelte.js +1 -1
  107. package/dist/fields/time-of-day.d.ts +28 -0
  108. package/dist/fields/time-of-day.js +1 -0
  109. package/dist/fields/view-model.d.ts +24 -2
  110. package/dist/fields/view-model.js +1 -1
  111. package/dist/fields/viewbar/ConditionValue.svelte +3 -3
  112. package/dist/fields/viewbar/ListPanel.svelte +36 -0
  113. package/dist/fields/viewbar/ListPanel.svelte.d.ts +11 -0
  114. package/dist/fields/viewbar/ViewsMenu.svelte +27 -4
  115. package/dist/fields/viewbar/ViewsMenu.svelte.d.ts +6 -0
  116. package/dist/node/studio.js +1 -1
  117. package/dist/version.d.ts +2 -2
  118. package/dist/version.js +1 -1
  119. package/dist/wc/GridFind-DsTvdUXq.js +1 -0
  120. package/dist/wc/GridFooter-D-i8boBh.js +1 -0
  121. package/dist/wc/GridMenus-CYe9Fw2I.js +20 -0
  122. package/dist/wc/PinSplitter-LvyyrLhe.js +6 -0
  123. package/dist/wc/SvChartMenu-XKW_LOYw.js +1 -0
  124. package/dist/wc/SvDateRangeInput-CSOxqTB1.js +1 -0
  125. package/dist/wc/SvDateTimePicker-DvvFs2T9.js +4 -0
  126. package/dist/wc/SvField-BmQphyOs.js +20 -0
  127. package/dist/wc/SvForm-HD7y5vmk.js +46 -0
  128. package/dist/wc/SvGridCellEditor-776KAOe1.js +3 -0
  129. package/dist/wc/SvGridChart-DC7ZUhp8.js +171 -0
  130. package/dist/wc/SvGridChartBuilder-Dd3vWBvq.js +7 -0
  131. package/dist/wc/SvGridChartPanel-CwYjF46U.js +5 -0
  132. package/dist/wc/SvGridChartView-CSF38rBs.js +3 -0
  133. package/dist/wc/SvGridDropdown-4S1G7gsP.js +30 -0
  134. package/dist/wc/SvMenuList-D3ZLXjL_.js +1 -0
  135. package/dist/wc/SvModal-Dk0YwPWp.js +7 -0
  136. package/dist/wc/SvSwitchButton-DdZmc3ew.js +1 -0
  137. package/dist/wc/SvTabs-BI2cQHyw.js +2 -0
  138. package/dist/wc/base-react.d.ts +38 -0
  139. package/dist/wc/base-react.js +1 -0
  140. package/dist/wc/base-vue.d.ts +29 -0
  141. package/dist/wc/base-vue.js +1 -0
  142. package/dist/wc/board-RQp5fHPR.js +21 -0
  143. package/dist/wc/board-view.svelte-CpxuZcEg.js +1 -0
  144. package/dist/wc/card-marks.svelte-QwxIcKcZ.js +1 -0
  145. package/dist/wc/client-DNdLmGcu.js +3 -0
  146. package/dist/wc/createOverlay.svelte-CDw3RXgs.js +1 -0
  147. package/dist/wc/custom-filter-Dp8JxlQu.js +2 -0
  148. package/dist/wc/date-format-DtSmFyEB.js +18 -0
  149. package/dist/wc/editor-registry-CkKfcVLc.js +1 -0
  150. package/dist/wc/export-format-CGfE9_O5.js +5 -0
  151. package/dist/wc/gallery-CNOHNWEJ.js +4 -0
  152. package/dist/wc/gallery-view.svelte-27X-wCQH.js +1 -0
  153. package/dist/wc/grid-extension.svelte-hgqOteka.js +1 -0
  154. package/dist/wc/import-B9mIERCl.js +4 -0
  155. package/dist/wc/js-scroller.svelte-BP8Up6_q.js +1 -0
  156. package/dist/wc/license-CWVWqb-i.js +27 -0
  157. package/dist/wc/list-option-CI4nMshZ.js +1 -0
  158. package/dist/wc/react.d.ts +1 -0
  159. package/dist/wc/react.js +1 -1
  160. package/dist/wc/scheduler-CkVY4od-.js +147 -0
  161. package/dist/wc/scheduler-view.svelte-SzG7rU8b.js +1 -0
  162. package/dist/wc/sparkline-DWRBQubt.js +1 -0
  163. package/dist/wc/sv-base-element.d.ts +87 -0
  164. package/dist/wc/sv-base-element.js +273 -0
  165. package/dist/wc/sv-sheet-element.d.ts +2 -0
  166. package/dist/wc/sv-sheet-element.js +55 -55
  167. package/dist/wc/svelte-virtualizer.svelte-CSBwEZt9.js +1 -0
  168. package/dist/wc/types/sv-base-element.d.ts +87 -0
  169. package/dist/wc/vue.d.ts +1 -0
  170. package/dist/wc/vue.js +1 -1
  171. package/package.json +18 -4
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Dashboards: a view of tiles that sum up the base. A tile reads one table
3
+ * (any table of the base, not only the one the view is on), keeps the
4
+ * records its filter matches, and shows one number, a chart, the first few
5
+ * records by a sort, or how many of the records match. The tiles are kept on
6
+ * the view (`FieldView.dashboard`); this module turns them into what each
7
+ * tile draws, from plain tables, with no grid.
8
+ */
9
+ import type { ChartSpec } from '@svgrid/grid';
10
+ import { type ChartSetting } from './chart-view.js';
11
+ import { type FieldFilter } from './filter-model.js';
12
+ import { type FieldColumn } from './grid-access.js';
13
+ import { type BaseTable } from './base-tables.js';
14
+ type Row = Record<string, unknown>;
15
+ export type DashboardTileKind = 'number' | 'chart' | 'list' | 'progress';
16
+ /** Columns x rows of the dashboard's grid a tile takes. */
17
+ export type DashboardTileSize = '1x1' | '2x1' | '2x2';
18
+ export type NumberAggregation = 'count' | 'sum' | 'avg' | 'min' | 'max';
19
+ /** One tile of a dashboard view. */
20
+ export type DashboardTile = {
21
+ id: string;
22
+ kind: DashboardTileKind;
23
+ /** Shown over the tile. Default: what it shows ("Sum of Value"). */
24
+ title?: string;
25
+ /** The table it reads (a table id of the base). Default: the view's own table. */
26
+ table?: string;
27
+ /** Default: 1x1 for a number or progress, 2x2 for a chart or list. */
28
+ size?: DashboardTileSize;
29
+ /** Only the records it matches count. A progress tile shows how many of all the records match. */
30
+ filter?: FieldFilter;
31
+ /** Number: how the records become one number (default 'count'). */
32
+ aggregation?: NumberAggregation;
33
+ /** Number: the field added up, averaged or compared (not for a count). */
34
+ field?: string;
35
+ /** Number: a line under the number to compare it with ("Target $500,000"). */
36
+ caption?: string;
37
+ /** Chart: what it groups the records by and counts or adds up, as a chart view does. */
38
+ chart?: ChartSetting;
39
+ /** List: the field the records are sorted by, and whether high to low. */
40
+ sortBy?: string;
41
+ sortDesc?: boolean;
42
+ /** List: how many records it shows (default 5). */
43
+ limit?: number;
44
+ /** List: the field shown beside each record's name (default: the sort field). */
45
+ detail?: string;
46
+ };
47
+ export declare const TILE_KINDS: ReadonlyArray<{
48
+ kind: DashboardTileKind;
49
+ label: string;
50
+ }>;
51
+ export declare const TILE_SIZES: ReadonlyArray<{
52
+ size: DashboardTileSize;
53
+ label: string;
54
+ }>;
55
+ export declare const AGGREGATIONS: ReadonlyArray<{
56
+ aggregation: NumberAggregation;
57
+ label: string;
58
+ }>;
59
+ export declare const tileSize: (tile: DashboardTile) => DashboardTileSize;
60
+ export declare const newTileId: () => string;
61
+ /**
62
+ * A table as the grid helpers read one (`fieldColumns`, the chart view, the
63
+ * filter panel): its fields filled in by their types, all shown.
64
+ */
65
+ export declare function tableCtrl(t: BaseTable): any;
66
+ /** Fields a tile can add up or compare: the ones a chart can add up. */
67
+ export declare const numberColumns: (t: BaseTable) => FieldColumn[];
68
+ /** Fields a list can sort by and show. */
69
+ export declare const tileFieldColumns: (t: BaseTable) => FieldColumn[];
70
+ /** The records of `t` a filter keeps (every record without one). */
71
+ export declare function tileRows(t: BaseTable, filter: FieldFilter | undefined): Row[];
72
+ /** The table a tile reads: its own, else the view's (`home`). */
73
+ export declare const tileTable: (tile: DashboardTile, tables: ReadonlyArray<BaseTable>, home: string) => BaseTable | undefined;
74
+ export type TileResult = {
75
+ kind: 'missing';
76
+ message: string;
77
+ } | {
78
+ kind: 'number';
79
+ value: number | null;
80
+ text: string;
81
+ records: number;
82
+ } | {
83
+ kind: 'chart';
84
+ spec: ChartSpec | null;
85
+ formatValue?: (value: number) => string;
86
+ records: number;
87
+ } | {
88
+ kind: 'list';
89
+ items: Array<{
90
+ id: string;
91
+ title: string;
92
+ detail: string;
93
+ }>;
94
+ records: number;
95
+ } | {
96
+ kind: 'progress';
97
+ part: number;
98
+ whole: number;
99
+ percent: number;
100
+ };
101
+ /** What a tile draws, read from the base's tables; `home` is the table the view is on. */
102
+ export declare function tileResult(tile: DashboardTile, tables: ReadonlyArray<BaseTable>, home: string): TileResult;
103
+ /** What a tile opens: the records it counts, with a few of their fields to show. */
104
+ export type TileRecords = {
105
+ table: BaseTable;
106
+ /** Each record: its id, its name, and the fields' text in `fields` order. */
107
+ items: Array<{
108
+ id: string;
109
+ title: string;
110
+ cells: string[];
111
+ }>;
112
+ /** The headers of the fields beside each name. */
113
+ fields: string[];
114
+ /** For a chart's bucket: the field and the bucket ("Stage", "Won"). */
115
+ bucket?: {
116
+ field: string;
117
+ label: string;
118
+ };
119
+ };
120
+ /**
121
+ * The records a tile counts: a number's and a progress tile's matching
122
+ * records, or for a chart the ones in the bucket `category` too. Beside each
123
+ * name, the field the tile adds up or sorts by, then the table's next
124
+ * fields, up to `extra`.
125
+ */
126
+ export declare function tileRecords(tile: DashboardTile, tables: ReadonlyArray<BaseTable>, home: string, category?: string, extra?: number): TileRecords | null;
127
+ /** A tile's title: its own, else what it shows ("Sum of Value", "Deals by Stage"). */
128
+ export declare function tileTitle(tile: DashboardTile, tables: ReadonlyArray<BaseTable>, home: string): string;
129
+ /** A first tile of a kind for table `t`: a count, a chart by its first select, the first records by its primary field. */
130
+ export declare function newTile(kind: DashboardTileKind, t: BaseTable | undefined, home: string): DashboardTile;
131
+ /** A new dashboard's tiles, over the grid's own table: its record count, and a chart by its first select. */
132
+ export declare function starterTiles(ctrl: any): DashboardTile[];
133
+ /** Fields a chart tile on `t` can group by and add up. */
134
+ export declare const tileChartColumns: (t: BaseTable) => {
135
+ x: FieldColumn[];
136
+ y: FieldColumn[];
137
+ };
138
+ /** The tiles with `tile` in place of the one with its id, or added at the end. */
139
+ export declare function putTile(tiles: ReadonlyArray<DashboardTile>, tile: DashboardTile): DashboardTile[];
140
+ export declare const removeTile: (tiles: ReadonlyArray<DashboardTile>, id: string) => DashboardTile[];
141
+ /** The tiles with the one at `from` moved to `to` (both clamped to the list). */
142
+ export declare function moveTile(tiles: ReadonlyArray<DashboardTile>, from: number, to: number): DashboardTile[];
143
+ export {};
@@ -0,0 +1 @@
1
+ import{chartBucketRows as C,chartFormatter as v,chartSpec as $,chartXColumns as w,chartYColumns as x,defaultChart as k,withValueGutter as F}from"./chart-view.js";import{compileFieldFilter as L,describeFieldFilter as N}from"./filter-model.js";import{fieldColumns as I}from"./grid-access.js";import{primaryOf as m,rowIdOf as y}from"./base-tables.js";import{tableFields as d}from"./automations.svelte.js";import{fieldText as g,fieldValue as b,linkNames as M}from"./base-alerts.js";export const TILE_KINDS=[{kind:"number",label:"Number"},{kind:"chart",label:"Chart"},{kind:"list",label:"List"},{kind:"progress",label:"Progress"}],TILE_SIZES=[{size:"1x1",label:"Small"},{size:"2x1",label:"Wide"},{size:"2x2",label:"Large"}],AGGREGATIONS=[{aggregation:"count",label:"Number of records"},{aggregation:"sum",label:"Sum"},{aggregation:"avg",label:"Average"},{aggregation:"min",label:"Smallest"},{aggregation:"max",label:"Largest"}],tileSize=e=>e.size??(e.kind==="chart"||e.kind==="list"?"2x2":"1x1");let A=0;export const newTileId=()=>`tile-${Date.now().toString(36)}-${A+=1}`;const T=new WeakMap;export function tableCtrl(e){const t=T.get(e.columns);if(t)return t;const n={internalColumns:[...d(e).values()].map(i=>i.def),allColumns:[...d(e).keys()].map(i=>({id:i})),hiddenColumns:{}};return T.set(e.columns,n),n}export const numberColumns=e=>x(tableCtrl(e)),tileFieldColumns=e=>I(tableCtrl(e)).filter(t=>t.fieldType!=="button"&&t.fieldType!=="attachment");export function tileRows(e,t){const o=e.data.filter(r=>r!=null);if(!t)return o;const n=d(e),i=L(t,(r,a)=>{const s=n.get(a);return s?b(s,r):r[a]},M);return i?o.filter(i):o}export const tileTable=(e,t,o)=>t.find(n=>n.id===(e.table||o));const B=e=>{if(e==null||e===""||typeof e=="boolean")return null;const t=Number(e);return Number.isFinite(t)?t:null};function O(e,t){const o=e?.def.formatter;if(e&&o)try{return String(o({value:t,row:{},column:{id:e.id,columnDef:e.def}})??t)}catch{}return(Math.round(t*100)/100).toLocaleString()}function R(e,t,o){const n=e.aggregation??"count";if(n==="count")return{kind:"number",value:o.length,text:o.length.toLocaleString(),records:o.length};const i=d(t).get(e.field??"");if(!i)return{kind:"missing",message:"Choose a field to add up."};const r=o.map(s=>B(b(i,s))).filter(s=>s!=null);let a;return n==="sum"?a=r.reduce((s,l)=>s+l,0):r.length?n==="avg"?a=r.reduce((s,l)=>s+l,0)/r.length:a=n==="min"?Math.min(...r):Math.max(...r):a=null,{kind:"number",value:a,text:a==null?"No values":O(i,a),records:o.length}}function z(e,t,o){const n=e.def.groupOrder??((s,l)=>String(s).localeCompare(String(l),void 0,{numeric:!0})),i=s=>s==null||s===""||Array.isArray(s)&&!s.length,r=t.map(s=>({r:s,v:b(e,s)})),a=r.filter(s=>!i(s.v));return a.sort((s,l)=>(o?-1:1)*n(s.v,l.v)),[...a,...r.filter(s=>i(s.v))].map(s=>s.r)}function E(e,t,o){const n=d(t),i=n.get(m(t))??[...n.values()].find(u=>u.field===m(t))??[...n.values()][0],r=e.sortBy?n.get(e.sortBy):void 0,a=e.detail?n.get(e.detail):r;return{kind:"list",items:(r?z(r,o,!!e.sortDesc):o).slice(0,Math.max(1,e.limit??5)).map(u=>({id:y(t,u),title:(i?g(i,u):"")||"Unnamed record",detail:a&&a!==i?g(a,u):""})),records:o.length}}export function tileResult(e,t,o){const n=tileTable(e,t,o);if(!n)return{kind:"missing",message:"The table this tile reads is gone. Edit the tile to pick another."};if(e.kind==="progress"){const l=n.data.filter(h=>h!=null).length,u=e.filter?tileRows(n,e.filter).length:l;return{kind:"progress",part:u,whole:l,percent:l?u/l:0}}const i=tileRows(n,e.filter);if(e.kind==="number")return R(e,n,i);if(e.kind==="list")return E(e,n,i);const r=tableCtrl(n),a=e.chart?$(r,e.chart,i):null;if(!a)return{kind:"missing",message:"Choose a field to group the records by."};const s=v(r,e.chart);return{kind:"chart",spec:F(a,s),formatValue:s,records:i.length}}export function tileRecords(e,t,o,n,i=3){const r=tileTable(e,t,o);if(!r)return null;let a=tileRows(r,e.filter),s;e.kind==="chart"&&e.chart&&n!=null&&(a=C(tableCtrl(r),e.chart,a,n),s={field:d(r).get(e.chart.x)?.header??e.chart.x,label:n});const l=tileFieldColumns(r),u=l.find(c=>c.field===m(r))??l[0],h=[e.field,e.chart?.y,e.sortBy,e.detail].map(c=>l.find(p=>p.id===c)).filter(c=>!!c),S=new Set([u?.id,s?e.chart?.x:void 0]),f=[];for(const c of[...h,...l])f.length<i&&!S.has(c.id)&&!f.includes(c)&&f.push(c);return{table:r,items:a.map(c=>({id:y(r,c),title:(u?g(u,c):"")||"Unnamed record",cells:f.map(p=>g(p,c))})),fields:f.map(c=>c.header),...s?{bucket:s}:{}}}export function tileTitle(e,t,o){if(e.title?.trim())return e.title.trim();const n=tileTable(e,t,o);if(!n)return"Tile";const i=r=>r?d(n).get(r)?.header:void 0;if(e.kind==="number"){const r=e.aggregation??"count",a=i(e.field);return r==="count"||!a?n.name:r==="sum"?`Total ${a}`:r==="avg"?`Average ${a}`:r==="min"?`Smallest ${a}`:`Largest ${a}`}if(e.kind==="chart"){const r=i(e.chart?.x),a=i(e.chart?.y);return r?`${a??n.name} by ${r}`:n.name}if(e.kind==="list"){const r=i(e.sortBy);return r?`${n.name} by ${r}`:n.name}return e.filter?N(e.filter,r=>i(r)??r):n.name}export function newTile(e,t,o){const n={id:newTileId(),kind:e,...t&&t.id!==o?{table:t.id}:{}};if(!t)return n;if(e==="number")return{...n,aggregation:"count"};if(e==="chart"){const i=k(tableCtrl(t));return i?{...n,chart:i}:n}if(e==="list"){const i=tileFieldColumns(t).find(r=>r.field===m(t))??tileFieldColumns(t)[0];return{...n,...i?{sortBy:i.id}:{},limit:5}}return n}export function starterTiles(e){const t=k(e);return[{id:newTileId(),kind:"number",aggregation:"count"},...t?[{id:newTileId(),kind:"chart",chart:t}]:[]]}export const tileChartColumns=e=>({x:w(tableCtrl(e)),y:x(tableCtrl(e))});export function putTile(e,t){return e.some(o=>o.id===t.id)?e.map(o=>o.id===t.id?t:o):[...e,t]}export const removeTile=(e,t)=>e.filter(o=>o.id!==t);export function moveTile(e,t,o){const n=[...e];if(t<0||t>=n.length)return n;const[i]=n.splice(t,1);return n.splice(Math.max(0,Math.min(n.length,o)),0,i),n}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Protected fields: who may change a field's values. `fieldProps.editors`
3
+ * lists the user ids that may; everyone else sees the field read-only in the
4
+ * grid, the record view, a board's lanes and a calendar's dates. Without the
5
+ * list, anyone who can edit the base can edit the field. `setCanEditField`
6
+ * replaces the check with the app's own (roles, a server's answer).
7
+ *
8
+ * The browser enforces this, for the person in front of it. A base whose
9
+ * records live in a database still needs the server to refuse the writes.
10
+ */
11
+ import { type FieldUser } from './sources.svelte.js';
12
+ /** The field as the check sees it. */
13
+ export type FieldAccessField = {
14
+ id: string;
15
+ name: string;
16
+ fieldType: string;
17
+ fieldProps: Record<string, unknown>;
18
+ };
19
+ /** Whether `user` may change the values of `field`. */
20
+ export type CanEditField = (field: FieldAccessField, user: FieldUser | null) => boolean;
21
+ /** The people a field's values are limited to, or null when it is not protected. */
22
+ export declare function fieldEditors(fieldProps: Record<string, unknown> | undefined): string[] | null;
23
+ /** The built-in check: a field with `editors` takes edits from those people only. */
24
+ export declare const defaultCanEditField: CanEditField;
25
+ /** Use the app's own check for every field of every base on the page; null goes back to `editors`. */
26
+ export declare function setCanEditField(fn: CanEditField | null): void;
27
+ /** Take `fn` off again, if it is still the check (a base unmounting leaves another's alone). */
28
+ export declare function releaseCanEditField(fn: CanEditField): void;
29
+ /** Whether an app check is set (a field without `editors` may still be read-only then). */
30
+ export declare const hasCanEditField: () => boolean;
31
+ /** Whether the signed-in person may say who edits a field (the field editor's "Who can edit"). */
32
+ export declare function setFieldProtection(allowed: boolean): void;
33
+ export declare const canProtectFields: () => boolean;
34
+ /** Whether the signed-in person may change the values of the field `def` (its `fieldProps` in `props`). */
35
+ export declare function canEditField(def: Record<string, any>, props?: Record<string, unknown>): boolean;
36
+ /** "Only Ana Ruiz and Ben Okafor can edit this field." for a protected field; null otherwise. */
37
+ export declare function protectionText(def: Record<string, any>, props?: Record<string, unknown>): string | null;
@@ -0,0 +1 @@
1
+ import{findFieldUser,getCurrentUser}from"./sources.svelte.js";let check=$state.raw(null);let protecting=$state(true);export function fieldEditors(fieldProps){const list=fieldProps?.editors;return Array.isArray(list)?list.map(String):null}export const defaultCanEditField=(field,user)=>{const editors=fieldEditors(field.fieldProps);return!editors||!!user&&editors.includes(user.id)};export function setCanEditField(fn){check=fn}export function releaseCanEditField(fn){if(check===fn)check=null}export const hasCanEditField=()=>check!==null;export function setFieldProtection(allowed){protecting=allowed}export const canProtectFields=()=>protecting;export function canEditField(def,props=def.fieldProps??{}){const field={id:String(def.id??def.field??""),name:String(def.header??def.id??def.field??""),fieldType:String(def.fieldType??""),fieldProps:props};try{return(check??defaultCanEditField)(field,getCurrentUser())!==false}catch{return false}}export function protectionText(def,props=def.fieldProps??{}){const editors=fieldEditors(props);if(editors){const names=editors.map(id=>findFieldUser(id)?.name??id);if(!names.length)return"Nobody can edit this field.";const list=names.length===1?names[0]:`${names.slice(0,-1).join(", ")} and ${names.at(-1)}`;return`Only ${list} can edit this field.`}return check&&!canEditField(def,props)?"You cannot edit this field.":null}
@@ -1 +1 @@
1
- import{convertValue as A,countCleared as v,keepsStoredValues as D,optionsFromValues as b}from"./convert.js";import{renameFormulaRefs as L}from"./formula.js";import{fieldPropsOf as C,fillFieldColumn as T,getFieldType as y,originalColumn as f}from"./registry.svelte.js";import{getLinkedTable as R,linkedRows as I}from"./sources.svelte.js";const M=["editorType","cellDataType","format","align","editorOptions","editorMultiple","formatter","valueParser"];export const defId=e=>String(e.id??e.field??"");export function plainDef(e){return{...f(e)}}export const plainColumns=e=>e.internalColumns.map(t=>plainDef(t));export function uniqueId(e,t){const i=new Set(t),n=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"field";let o=n;for(let l=2;i.has(o);l++)o=`${n}_${l}`;return o}export function nameTaken(e,t,i){const n=t.trim().toLowerCase();return e.internalColumns.some(o=>defId(o)!==i&&String(o.header??"").trim().toLowerCase()===n)}function g(e){const t={};for(const[i,n]of Object.entries(e))n!==void 0&&n!==""&&!(Array.isArray(n)&&n.length===0&&i!=="options")&&(t[i]=n);return t}function p(e){return e.map(t=>f(t).fieldType?T(f(t),e):t)}function x(e,t){typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{const i=e.scrollContainer,n=i?.querySelector(`[data-svgrid-header-col="${t}"]`);if(!i||!n)return;const o=i.getBoundingClientRect(),l=n.getBoundingClientRect(),r=o.left+i.clientWidth;l.right>r?i.scrollLeft+=Math.min(l.right-r,l.left-o.left):l.left<o.left&&(i.scrollLeft-=o.left-l.left)})}function S(e,t,i){const n=e.slice();return n.splice(i==="end"?n.length:Math.max(0,Math.min(i,n.length)),0,t),n}export function addField(e,t,i="end"){const n=uniqueId(t.name,e.internalColumns.map(defId)),o=y(t.fieldType),l={id:n,field:n,header:t.name.trim(),width:o?.width??150,fieldType:t.fieldType,fieldProps:g(t.fieldProps),...t.description?.trim()?{description:t.description.trim()}:{}};let r;const s=o?.onCreate?.({props:C(l),field:n,rows:e.internalData});return s&&(r=e.internalData.map((a,u)=>a==null?a:{...a,[n]:s[u]}),e.internalData=r),e.internalColumns=p(S(e.internalColumns,l,i)),e.props.onColumnAdd?.({column:l,columns:plainColumns(e),...r?{data:r}:{}}),x(e,n),l}let h=0;export function newRecordId(){return h=(h+1)%1296,`rec${Date.now().toString(36).slice(-5)}${Math.random().toString(36).slice(2,4)}${h.toString(36).padStart(2,"0")}`}export function newRowValues(e,t={}){const i={};for(const n of e.internalColumns){const o=f(n);if(!o.fieldType||!n.field)continue;const l=String(n.field),r=C(o),s=y(o.fieldType)?.newRowValue?.({props:r,field:l,rows:e.internalData}),a=s!==void 0?s:r.default;a!==void 0&&(i[l]=Array.isArray(a)?a.slice():a)}return!("id"in t)&&(e.internalData??[]).some(n=>n&&typeof n=="object"&&"id"in n)&&(i.id=newRecordId()),{...i,...t}}const $=new Set(["autoNumber","createdTime","createdBy","lastModifiedTime","lastModifiedBy"]),k=e=>$.has(String(e))||y(e)?.copy===!1;export function recordCopyValues(e,t){const i={};for(const n of e.internalColumns){const o=f(n);if(!n.field||n.fieldFn||o.fieldFn||k(o.fieldType))continue;const l=t[String(n.field)];l!==void 0&&(i[String(n.field)]=Array.isArray(l)?l.slice():l)}return i}function w(e,t,i){const n=String(t.field),o=e.internalData.map(s=>s?.[n]);if(D(i))return o;const l=f(t),r=(l.fieldType?T(l,e.internalColumns):t).fieldFn;if(typeof r=="function")return e.internalData.map(s=>{if(s==null)return;const a=r(s);return a==="#ERROR"?null:a});if(l.fieldType==="link"&&i!=="link"){const s=R(C(l).table);if(s)return o.map(a=>I(s,a).map(u=>u[s.primaryField]).filter(u=>u!=null&&u!==""))}return o}export function previewChange(e,t,i){const n=e.internalColumns.find(o=>defId(o)===t);return!n||n.fieldType===i.fieldType||!n.field?0:v(w(e,n,i.fieldType),n.fieldType,i.fieldType,g(i.fieldProps))}function V(e,t,i,n){const o=i.trim().toLowerCase();return!o||o===n.trim().toLowerCase()?e:e.map(l=>{const r=f(l);if(r.fieldType!=="formula"||String(r.field??r.id)===t)return l;const s=String(r.fieldProps?.formula??""),a=L(s,u=>u.trim().toLowerCase()===o?n:null);return a===s?l:{...r,fieldProps:{...r.fieldProps,formula:a}}})}export function updateField(e,t,i){const n=e.internalColumns.findIndex(d=>defId(d)===t);if(n<0)return null;const o=plainDef(e.internalColumns[n]),l=o.fieldType!==i.fieldType,r=g(i.fieldProps);let s;if(l&&o.field){const d=String(o.field),F=w(e,e.internalColumns[n],i.fieldType);s=e.internalData.map((m,P)=>m==null?m:{...m,[d]:A(F[P],o.fieldType,i.fieldType,r)}),(i.fieldType==="singleSelect"||i.fieldType==="multiSelect")&&!r.options?.length&&(r.options=b(s.map(m=>m?.[d])))}const a={...o};if(l)for(const d of M)delete a[d];const u={...a,header:i.name.trim(),fieldType:i.fieldType,fieldProps:r};i.description?.trim()?u.description=i.description.trim():delete u.description;let c=e.internalColumns.slice();return c[n]=u,typeof o.header=="string"&&o.field&&(c=V(c,String(o.field),o.header,String(u.header))),e.internalColumns=p(c),s&&(e.internalData=s),e.props.onColumnChange?.({column:u,previous:o,columns:plainColumns(e),...s?{data:s}:{}}),u}export function addSelectOptions(e,t,i){const n=e.internalColumns.findIndex(u=>defId(u)===t);if(n<0||!i.length)return null;const o=plainDef(e.internalColumns[n]),l=Array.isArray(o.fieldProps?.options)?o.fieldProps.options.slice():[],r=new Set(l.map(u=>String(u.value)));for(const u of i)r.has(u.value)||(r.add(u.value),l.push({...u}));const s={...o,fieldProps:{...o.fieldProps,options:l}},a=e.internalColumns.slice();return a[n]=s,e.internalColumns=p(a),e.props.onColumnChange?.({column:s,previous:o,columns:plainColumns(e)}),s}export function setFieldSummary(e,t,i){const n=e.internalColumns.findIndex(a=>defId(a)===t);if(n<0)return null;const o=plainDef(e.internalColumns[n]),l={...o.fieldProps};i==="none"?delete l.summary:l.summary=i;const r={...o,fieldProps:l},s=e.internalColumns.slice();return s[n]=r,e.internalColumns=p(s),e.props.onColumnChange?.({column:r,previous:o,columns:plainColumns(e)}),r}export function duplicateField(e,t){const i=e.internalColumns.findIndex(a=>defId(a)===t);if(i<0)return null;const n=plainDef(e.internalColumns[i]),o=`${String(n.header??t)} copy`,l=uniqueId(o,e.internalColumns.map(defId)),r={...n,id:l,field:l,header:o};let s;if(n.field){const a=String(n.field);s=e.internalData.map(u=>u==null?u:{...u,[l]:O(u[a])}),e.internalData=s}return e.internalColumns=p(S(e.internalColumns,r,i+1)),e.props.onColumnAdd?.({column:r,columns:plainColumns(e),...s?{data:s}:{}}),x(e,l),r}export function removeField(e,t){e.internalColumns=p(e.internalColumns.filter(i=>defId(i)!==t)),e.props.onColumnRemove?.({columnId:t,columns:plainColumns(e)})}export function hideField(e,t){e.buildApi?.()?.setColumnVisible?.(t,!1)}export function indexBeside(e,t,i){const n=e.internalColumns.findIndex(o=>defId(o)===t);return n<0?e.internalColumns.length:i==="left"?n:n+1}function O(e){if(e==null||typeof e!="object")return e;try{return structuredClone(e)}catch{return Array.isArray(e)?e.slice():{...e}}}
1
+ import{convertValue as A,countCleared as v,keepsStoredValues as D,optionsFromValues as b}from"./convert.js";import{renameFormulaRefs as L}from"./formula.js";import{renamePromptRefs as R}from"./ai-prompt.js";import{fieldPropsOf as C,fillFieldColumn as T,getFieldType as y,originalColumn as p}from"./registry.svelte.js";import{getLinkedTable as I,linkedRows as M}from"./sources.svelte.js";const $=["editorType","cellDataType","format","align","editorOptions","editorMultiple","formatter","valueParser"];export const defId=e=>String(e.id??e.field??"");export function plainDef(e){return{...p(e)}}export const plainColumns=e=>e.internalColumns.map(t=>plainDef(t));export function uniqueId(e,t){const i=new Set(t),n=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"field";let o=n;for(let r=2;i.has(o);r++)o=`${n}_${r}`;return o}export function nameTaken(e,t,i){const n=t.trim().toLowerCase();return e.internalColumns.some(o=>defId(o)!==i&&String(o.header??"").trim().toLowerCase()===n)}function g(e){const t={};for(const[i,n]of Object.entries(e))n!==void 0&&n!==""&&!(Array.isArray(n)&&n.length===0&&i!=="options"&&i!=="editors")&&(t[i]=n);return t}function m(e){return e.map(t=>p(t).fieldType?T(p(t),e):t)}function x(e,t){typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{const i=e.scrollContainer,n=i?.querySelector(`[data-svgrid-header-col="${t}"]`);if(!i||!n)return;const o=i.getBoundingClientRect(),r=n.getBoundingClientRect(),l=o.left+i.clientWidth;r.right>l?i.scrollLeft+=Math.min(r.right-l,r.left-o.left):r.left<o.left&&(i.scrollLeft-=o.left-r.left)})}function S(e,t,i){const n=e.slice();return n.splice(i==="end"?n.length:Math.max(0,Math.min(i,n.length)),0,t),n}export function addField(e,t,i="end"){const n=uniqueId(t.name,e.internalColumns.map(defId)),o=y(t.fieldType),r={id:n,field:n,header:t.name.trim(),width:o?.width??150,fieldType:t.fieldType,fieldProps:g(t.fieldProps),...t.description?.trim()?{description:t.description.trim()}:{}};let l;const s=o?.onCreate?.({props:C(r),field:n,rows:e.internalData});return s&&(l=e.internalData.map((u,a)=>u==null?u:{...u,[n]:s[a]}),e.internalData=l),e.internalColumns=m(S(e.internalColumns,r,i)),e.props.onColumnAdd?.({column:r,columns:plainColumns(e),...l?{data:l}:{}}),x(e,n),r}let h=0;export function newRecordId(){return h=(h+1)%1296,`rec${Date.now().toString(36).slice(-5)}${Math.random().toString(36).slice(2,4)}${h.toString(36).padStart(2,"0")}`}export function newRowValues(e,t={}){const i={};for(const n of e.internalColumns){const o=p(n);if(!o.fieldType||!n.field)continue;const r=String(n.field),l=C(o),s=y(o.fieldType)?.newRowValue?.({props:l,field:r,rows:e.internalData}),u=s!==void 0?s:l.default;u!==void 0&&(i[r]=Array.isArray(u)?u.slice():u)}return!("id"in t)&&(e.internalData??[]).some(n=>n&&typeof n=="object"&&"id"in n)&&(i.id=newRecordId()),{...i,...t}}const k=new Set(["autoNumber","createdTime","createdBy","lastModifiedTime","lastModifiedBy"]),V=e=>k.has(String(e))||y(e)?.copy===!1;export function recordCopyValues(e,t){const i={};for(const n of e.internalColumns){const o=p(n);if(!n.field||n.fieldFn||o.fieldFn||V(o.fieldType))continue;const r=t[String(n.field)];r!==void 0&&(i[String(n.field)]=Array.isArray(r)?r.slice():r)}return i}function w(e,t,i){const n=String(t.field),o=e.internalData.map(s=>s?.[n]);if(D(i))return o;const r=p(t),l=(r.fieldType?T(r,e.internalColumns):t).fieldFn;if(typeof l=="function")return e.internalData.map(s=>{if(s==null)return;const u=l(s);return u==="#ERROR"?null:u});if(r.fieldType==="link"&&i!=="link"){const s=I(C(r).table);if(s)return o.map(u=>M(s,u).map(a=>a[s.primaryField]).filter(a=>a!=null&&a!==""))}return o}export function previewChange(e,t,i){const n=e.internalColumns.find(o=>defId(o)===t);return!n||n.fieldType===i.fieldType||!n.field?0:v(w(e,n,i.fieldType),n.fieldType,i.fieldType,g(i.fieldProps))}function O(e,t,i,n){const o=i.trim().toLowerCase();return!o||o===n.trim().toLowerCase()?e:e.map(r=>{const l=p(r);if(String(l.field??l.id)===t)return r;if(l.fieldType==="ai"){const a=String(l.fieldProps?.prompt??""),d=R(a,f=>f.trim().toLowerCase()===o?n:null);return d===a?r:{...l,fieldProps:{...l.fieldProps,prompt:d}}}if(l.fieldType!=="formula")return r;const s=String(l.fieldProps?.formula??""),u=L(s,a=>a.trim().toLowerCase()===o?n:null);return u===s?r:{...l,fieldProps:{...l.fieldProps,formula:u}}})}export function updateField(e,t,i){const n=e.internalColumns.findIndex(f=>defId(f)===t);if(n<0)return null;const o=plainDef(e.internalColumns[n]),r=o.fieldType!==i.fieldType,l=g(i.fieldProps);let s;if(r&&o.field){const f=String(o.field),P=w(e,e.internalColumns[n],i.fieldType);s=e.internalData.map((c,F)=>c==null?c:{...c,[f]:A(P[F],o.fieldType,i.fieldType,l)}),(i.fieldType==="singleSelect"||i.fieldType==="multiSelect")&&!l.options?.length&&(l.options=b(s.map(c=>c?.[f])))}const u={...o};if(r)for(const f of $)delete u[f];const a={...u,header:i.name.trim(),fieldType:i.fieldType,fieldProps:l};i.description?.trim()?a.description=i.description.trim():delete a.description;let d=e.internalColumns.slice();return d[n]=a,typeof o.header=="string"&&o.field&&(d=O(d,String(o.field),o.header,String(a.header))),e.internalColumns=m(d),s&&(e.internalData=s),e.props.onColumnChange?.({column:a,previous:o,columns:plainColumns(e),...s?{data:s}:{}}),a}export function addSelectOptions(e,t,i){const n=e.internalColumns.findIndex(a=>defId(a)===t);if(n<0||!i.length)return null;const o=plainDef(e.internalColumns[n]),r=Array.isArray(o.fieldProps?.options)?o.fieldProps.options.slice():[],l=new Set(r.map(a=>String(a.value)));for(const a of i)l.has(a.value)||(l.add(a.value),r.push({...a}));const s={...o,fieldProps:{...o.fieldProps,options:r}},u=e.internalColumns.slice();return u[n]=s,e.internalColumns=m(u),e.props.onColumnChange?.({column:s,previous:o,columns:plainColumns(e)}),s}export function setFieldSummary(e,t,i){const n=e.internalColumns.findIndex(u=>defId(u)===t);if(n<0)return null;const o=plainDef(e.internalColumns[n]),r={...o.fieldProps};i==="none"?delete r.summary:r.summary=i;const l={...o,fieldProps:r},s=e.internalColumns.slice();return s[n]=l,e.internalColumns=m(s),e.props.onColumnChange?.({column:l,previous:o,columns:plainColumns(e)}),l}export function duplicateField(e,t){const i=e.internalColumns.findIndex(u=>defId(u)===t);if(i<0)return null;const n=plainDef(e.internalColumns[i]),o=`${String(n.header??t)} copy`,r=uniqueId(o,e.internalColumns.map(defId)),l={...n,id:r,field:r,header:o};let s;if(n.field){const u=String(n.field);s=e.internalData.map(a=>a==null?a:{...a,[r]:q(a[u])}),e.internalData=s}return e.internalColumns=m(S(e.internalColumns,l,i+1)),e.props.onColumnAdd?.({column:l,columns:plainColumns(e),...s?{data:s}:{}}),x(e,r),l}export function removeField(e,t){e.internalColumns=m(e.internalColumns.filter(i=>defId(i)!==t)),e.props.onColumnRemove?.({columnId:t,columns:plainColumns(e)})}export function hideField(e,t){e.buildApi?.()?.setColumnVisible?.(t,!1)}export function indexBeside(e,t,i){const n=e.internalColumns.findIndex(o=>defId(o)===t);return n<0?e.internalColumns.length:i==="left"?n:n+1}function q(e){if(e==null||typeof e!="object")return e;try{return structuredClone(e)}catch{return Array.isArray(e)?e.slice():{...e}}}
@@ -1,12 +1,3 @@
1
- /**
2
- * The view bar's filter: conditions on fields, each with the operators that
3
- * fit its type ("has any of" for a multiple select, "is within the past
4
- * week" for a date), joined by "and" or "or", one level of groups deep.
5
- *
6
- * It is the grid's advanced filter (`api.setAdvancedFilter`) with its own
7
- * expression kind, `fieldFilter`, so it is saved and restored with the rest
8
- * of the grid's state.
9
- */
10
1
  /**
11
2
  * A person condition's value meaning whoever is signed in (`setCurrentUser`)
12
3
  * when the filter runs, so one "My tasks" view works for everyone. With
@@ -15,8 +6,8 @@
15
6
  export declare const ME = "@me";
16
7
  export declare function resolveMeWith(fn: () => string | undefined): void;
17
8
  /** What a condition compares, from the field's type. */
18
- export type FilterKind = 'text' | 'number' | 'select' | 'multi' | 'checkbox' | 'date' | 'files' | 'link';
19
- export type FilterOp = 'contains' | 'notContains' | 'is' | 'isNot' | 'isEmpty' | 'isNotEmpty' | 'eq' | 'neq' | 'lt' | 'gt' | 'lte' | 'gte' | 'isAnyOf' | 'isNoneOf' | 'hasAnyOf' | 'hasAllOf' | 'hasNoneOf' | 'isExactly' | 'isBefore' | 'isAfter' | 'isOnOrBefore' | 'isOnOrAfter' | 'isWithin';
9
+ export type FilterKind = 'text' | 'number' | 'select' | 'multi' | 'checkbox' | 'date' | 'files' | 'link' | 'checklist' | 'time';
10
+ export type FilterOp = 'contains' | 'notContains' | 'is' | 'isNot' | 'isEmpty' | 'isNotEmpty' | 'eq' | 'neq' | 'lt' | 'gt' | 'lte' | 'gte' | 'isAnyOf' | 'isNoneOf' | 'hasAnyOf' | 'hasAllOf' | 'hasNoneOf' | 'isExactly' | 'isBefore' | 'isAfter' | 'isOnOrBefore' | 'isOnOrAfter' | 'isWithin' | 'allDone' | 'notAllDone';
20
11
  /** A day a date condition names, relative to today or exact. */
21
12
  export type DateTarget = {
22
13
  mode: 'today' | 'tomorrow' | 'yesterday' | 'oneWeekAgo' | 'oneWeekFromNow' | 'oneMonthAgo' | 'oneMonthFromNow';
@@ -60,6 +51,8 @@ export declare function operatorsFor(kind: FilterKind): ReadonlyArray<{
60
51
  op: FilterOp;
61
52
  label: string;
62
53
  }>;
54
+ /** Operators that take no value: "is empty", "is complete". */
55
+ export declare const NO_VALUE: ReadonlySet<FilterOp>;
63
56
  /** The value a new condition starts with for an operator. */
64
57
  export declare function defaultValue(kind: FilterKind, op: FilterOp): unknown;
65
58
  /** A new condition on a column, with its first operator. */
@@ -1 +1 @@
1
- export const ME="@me";let h=()=>{};export function resolveMeWith(e){h=e}export const isGroup=e=>Array.isArray(e.conditions);const b=new Set(["text","longText","url","email","phone","barcode"]),y=new Set(["number","currency","percent","rating","duration","autoNumber","count"]),x=new Set(["date","createdTime","lastModifiedTime"]),N={formula:"text",lookup:"text",rollup:"text"},k=new Set(["AND","OR"]);function g(e){const t=e.cellDataType;return t==="number"?"number":t==="date"||t==="dateString"?"date":t==="boolean"?"checkbox":null}export function filterKindOf(e){const t=e.fieldType;if(t==="button")return null;if(t==="singleSelect")return"select";if(t==="multiSelect")return"multi";if(t==="user"||t==="createdBy"||t==="lastModifiedBy")return e.fieldProps?.multiple?"multi":"select";if(t==="checkbox")return"checkbox";if(t==="attachment")return"files";if(t==="link")return"link";if(t&&x.has(t))return"date";if(t&&y.has(t))return"number";if(t&&b.has(t))return"text";if(t==="rollup"&&!e.cellDataType&&k.has(String(e.fieldProps?.aggregation)))return"checkbox";const r=t==="formula"?e.fieldProps?.result:void 0;return r==="number"||r==="currency"||r==="percent"?"number":r==="date"?"date":g(e)??(t?N[t]:void 0)??"text"}const p=[{op:"isEmpty",label:"is empty"},{op:"isNotEmpty",label:"is not empty"}];export function operatorsFor(e){switch(e){case"number":return[{op:"eq",label:"="},{op:"neq",label:"≠"},{op:"lt",label:"<"},{op:"gt",label:">"},{op:"lte",label:"≤"},{op:"gte",label:"≥"},...p];case"select":return[{op:"is",label:"is"},{op:"isNot",label:"is not"},{op:"isAnyOf",label:"is any of"},{op:"isNoneOf",label:"is none of"},...p];case"multi":return[{op:"hasAnyOf",label:"has any of"},{op:"hasAllOf",label:"has all of"},{op:"isExactly",label:"is exactly"},{op:"hasNoneOf",label:"has none of"},...p];case"checkbox":return[{op:"is",label:"is"}];case"date":return[{op:"is",label:"is"},{op:"isBefore",label:"is before"},{op:"isAfter",label:"is after"},{op:"isOnOrBefore",label:"is on or before"},{op:"isOnOrAfter",label:"is on or after"},{op:"isWithin",label:"is within"},...p];case"files":return[{op:"contains",label:"file name contains"},...p];case"link":case"text":return[{op:"contains",label:"contains"},{op:"notContains",label:"does not contain"},{op:"is",label:"is"},{op:"isNot",label:"is not"},...p]}}export function defaultValue(e,t){if(!(t==="isEmpty"||t==="isNotEmpty"))return e==="checkbox"?!0:e==="date"?t==="isWithin"?{span:"pastWeek"}:{mode:"today"}:e==="select"&&(t==="is"||t==="isNot")?"":e==="select"||e==="multi"?[]:""}export function newCondition(e,t){const r=filterKindOf(t);if(!r)return null;const n=operatorsFor(r)[0].op,s=r==="link"&&typeof t.fieldProps?.table=="string"?t.fieldProps.table:void 0;return{column:e,kind:r,op:n,value:defaultValue(r,n),...s?{table:s}:{}}}export function isComplete(e){if(e.op==="isEmpty"||e.op==="isNotEmpty"||e.kind==="checkbox")return!0;const t=e.value;if(t==null)return!1;if(Array.isArray(t))return t.length>0;if(typeof t=="string")return t.trim()!=="";if(e.kind==="date"&&typeof t=="object"){const r=t;if(r.mode==="exactDate")return!!r.date;if(r.span==="pastDays"||r.span==="nextDays")return Number(r.days)>0}return!0}export function conditionCount(e){if(!e)return 0;let t=0;for(const r of e.conditions)isGroup(r)?t+=r.conditions.filter(isComplete).length:isComplete(r)&&(t+=1);return t}const m=e=>String(e??"").trim().toLocaleLowerCase(),f=e=>e==null||e===""?[]:Array.isArray(e)?e.map(t=>String(t&&typeof t=="object"?t.id??t.name??"":t)):[String(e)],d=e=>e==null||e===""||Array.isArray(e)&&e.length===0||typeof e=="number"&&Number.isNaN(e),w=864e5;export function dayOf(e){if(e==null||e==="")return null;let t;if(e instanceof Date)t=e;else if(typeof e=="number")t=new Date(e);else{const r=String(e),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(r);t=n?new Date(Number(n[1]),Number(n[2])-1,Number(n[3])):new Date(r)}return Number.isNaN(t.getTime())?null:Math.floor((t.getTime()-t.getTimezoneOffset()*6e4)/w)}function A(e,t){switch(e.mode){case"today":return t;case"tomorrow":return t+1;case"yesterday":return t-1;case"oneWeekAgo":return t-7;case"oneWeekFromNow":return t+7;case"oneMonthAgo":return t-30;case"oneMonthFromNow":return t+30;case"exactDate":return dayOf(e.date)}}function O(e,t){const r=Math.max(1,Math.floor(Number(e.days)||1));switch(e.span){case"pastWeek":return[t-7,t];case"pastMonth":return[t-30,t];case"pastYear":return[t-365,t];case"nextWeek":return[t,t+7];case"nextMonth":return[t,t+30];case"nextYear":return[t,t+365];case"pastDays":return[t-r,t];case"nextDays":return[t,t+r]}}export function compileCondition(e,t,r=new Date){if(e.op==="isEmpty")return d;if(e.op==="isNotEmpty")return n=>!d(n);switch(e.kind){case"number":{const n=Number(e.value);if(!Number.isFinite(n))return()=>!0;const s=o=>d(o)?NaN:Number(o),i={eq:o=>o===n,neq:o=>o!==n,lt:o=>o<n,gt:o=>o>n,lte:o=>o<=n,gte:o=>o>=n}[e.op]??(()=>!0);return o=>{const u=s(o);return Number.isNaN(u)?e.op==="neq":i(u)}}case"checkbox":{const n=e.value!==!1;return s=>!!s===n}case"select":case"multi":{const n=h(),s=f(e.value).map(i=>i==="@me"&&n!=null?n:i),a=new Set(s);return e.op==="is"?i=>f(i)[0]===s[0]:e.op==="isNot"?i=>f(i)[0]!==s[0]:e.op==="isAnyOf"||e.op==="hasAnyOf"?i=>f(i).some(o=>a.has(o)):e.op==="isNoneOf"||e.op==="hasNoneOf"?i=>!f(i).some(o=>a.has(o)):e.op==="hasAllOf"?i=>{const o=new Set(f(i));return[...a].every(u=>o.has(u))}:e.op==="isExactly"?i=>{const o=new Set(f(i));return o.size===a.size&&[...a].every(u=>o.has(u))}:()=>!0}case"date":{const n=dayOf(r);if(e.op==="isWithin"){const[o,u]=O(e.value??{span:"pastWeek"},n);return l=>{const c=dayOf(l);return c!=null&&c>=o&&c<=u}}const s=A(e.value??{mode:"today"},n);if(s==null)return()=>!0;const i={is:o=>o===s,isBefore:o=>o<s,isAfter:o=>o>s,isOnOrBefore:o=>o<=s,isOnOrAfter:o=>o>=s}[e.op]??(()=>!0);return o=>{const u=dayOf(o);return u!=null&&i(u)}}case"files":{const n=m(e.value);return s=>(Array.isArray(s)?s:[]).some(a=>m(a?.name).includes(n))}case"link":case"text":{const n=m(e.value),s=a=>e.kind==="link"&&e.table&&t?m(t(e.table,a).join(", ")):m(Array.isArray(a)?a.map(i=>i&&typeof i=="object"?i.name??"":i).join(", "):a);return e.op==="contains"?a=>s(a).includes(n):e.op==="notContains"?a=>!s(a).includes(n):e.op==="is"?a=>s(a)===n:e.op==="isNot"?a=>s(a)!==n:()=>!0}}}export function compileFieldFilter(e,t,r,n){const s=o=>{const u=compileCondition(o,r,n);return l=>u(t(l,o.column))},a=(o,u)=>o==="or"?l=>u.some(c=>c(l)):l=>u.every(c=>c(l)),i=[];for(const o of e.conditions)if(isGroup(o)){const u=o.conditions.filter(isComplete).map(s);u.length&&i.push(a(o.conjunction,u))}else isComplete(o)&&i.push(s(o));return i.length?a(e.conjunction,i):null}const D={today:"today",tomorrow:"tomorrow",yesterday:"yesterday",oneWeekAgo:"one week ago",oneWeekFromNow:"one week from now",oneMonthAgo:"one month ago",oneMonthFromNow:"one month from now"},S={pastWeek:"the past week",pastMonth:"the past month",pastYear:"the past year",nextWeek:"the next week",nextMonth:"the next month",nextYear:"the next year"};function E(e){if(e.op==="isEmpty"||e.op==="isNotEmpty")return"";if(e.kind==="checkbox")return e.value===!1?"unchecked":"checked";if(e.kind==="date"){if(e.op==="isWithin"){const n=e.value??{span:"pastWeek"};return n.span==="pastDays"?`the past ${n.days??0} days`:n.span==="nextDays"?`the next ${n.days??0} days`:S[n.span]??n.span}const r=e.value??{mode:"today"};return r.mode==="exactDate"?r.date:D[r.mode]??r.mode}const t=r=>r==="@me"?"me":String(r);return Array.isArray(e.value)?e.value.map(t).join(", "):t(e.value??"")}export function describeCondition(e,t=r=>r){const r=operatorsFor(e.kind).find(n=>n.op===e.op)?.label??e.op;return[t(e.column),r,E(e)].filter(Boolean).join(" ")}export function describeFieldFilter(e,t){const r=[];for(const n of e.conditions)if(isGroup(n)){const s=n.conditions.filter(isComplete).map(a=>describeCondition(a,t));s.length&&r.push(s.length>1?`(${s.join(` ${n.conjunction} `)})`:s[0])}else isComplete(n)&&r.push(describeCondition(n,t));return r.length?r.join(` ${e.conjunction} `):"every record"}export function fieldFilterColumns(e){const t=new Set;for(const r of e.conditions)for(const n of isGroup(r)?r.conditions:[r])isComplete(n)&&t.add(n.column);return[...t]}
1
+ import{checklistProgress as y,checklistSortValue as x,toChecklist as g}from"./checklist.js";import{parseTimeOfDay as k,timeSeconds as h}from"./time-of-day.js";export const ME="@me";let b=()=>{};export function resolveMeWith(e){b=e}export const isGroup=e=>Array.isArray(e.conditions);const A=new Set(["text","longText","url","email","phone","barcode","color"]),N=new Set(["number","currency","percent","rating","duration","autoNumber","count"]),O=new Set(["date","createdTime","lastModifiedTime"]),w={formula:"text",lookup:"text",rollup:"text"},D=new Set(["AND","OR"]);function S(e){const t=e.cellDataType;return t==="number"?"number":t==="date"||t==="dateString"?"date":t==="boolean"?"checkbox":null}export function filterKindOf(e){const t=e.fieldType;if(t==="button")return null;if(t==="singleSelect")return"select";if(t==="multiSelect")return"multi";if(t==="user"||t==="createdBy"||t==="lastModifiedBy")return e.fieldProps?.multiple?"multi":"select";if(t==="checkbox")return"checkbox";if(t==="attachment")return"files";if(t==="link")return"link";if(t==="checklist")return"checklist";if(t==="timeOfDay")return"time";if(t&&O.has(t))return"date";if(t&&N.has(t))return"number";if(t&&A.has(t))return"text";if(t==="ai")return e.fieldProps?.output==="singleSelect"?"select":e.fieldProps?.output==="number"?"number":"text";if(t==="rollup"&&!e.cellDataType&&D.has(String(e.fieldProps?.aggregation)))return"checkbox";const o=t==="formula"?e.fieldProps?.result:void 0;return o==="number"||o==="currency"||o==="percent"?"number":o==="date"?"date":S(e)??(t?w[t]:void 0)??"text"}const f=[{op:"isEmpty",label:"is empty"},{op:"isNotEmpty",label:"is not empty"}];export function operatorsFor(e){switch(e){case"number":return[{op:"eq",label:"="},{op:"neq",label:"≠"},{op:"lt",label:"<"},{op:"gt",label:">"},{op:"lte",label:"≤"},{op:"gte",label:"≥"},...f];case"select":return[{op:"is",label:"is"},{op:"isNot",label:"is not"},{op:"isAnyOf",label:"is any of"},{op:"isNoneOf",label:"is none of"},...f];case"multi":return[{op:"hasAnyOf",label:"has any of"},{op:"hasAllOf",label:"has all of"},{op:"isExactly",label:"is exactly"},{op:"hasNoneOf",label:"has none of"},...f];case"checkbox":return[{op:"is",label:"is"}];case"date":return[{op:"is",label:"is"},{op:"isBefore",label:"is before"},{op:"isAfter",label:"is after"},{op:"isOnOrBefore",label:"is on or before"},{op:"isOnOrAfter",label:"is on or after"},{op:"isWithin",label:"is within"},...f];case"files":return[{op:"contains",label:"file name contains"},...f];case"checklist":return[{op:"allDone",label:"is complete"},{op:"notAllDone",label:"is not complete"},{op:"gte",label:"% done ≥"},{op:"lt",label:"% done <"},{op:"contains",label:"has an item containing"},...f];case"time":return[{op:"is",label:"is"},{op:"isBefore",label:"is before"},{op:"isAfter",label:"is after"},{op:"isOnOrBefore",label:"is at or before"},{op:"isOnOrAfter",label:"is at or after"},...f];case"link":case"text":return[{op:"contains",label:"contains"},{op:"notContains",label:"does not contain"},{op:"is",label:"is"},{op:"isNot",label:"is not"},...f]}}export const NO_VALUE=new Set(["isEmpty","isNotEmpty","allDone","notAllDone"]);export function defaultValue(e,t){if(!NO_VALUE.has(t))return e==="checkbox"?!0:e==="date"?t==="isWithin"?{span:"pastWeek"}:{mode:"today"}:e==="select"&&(t==="is"||t==="isNot")?"":e==="select"||e==="multi"?[]:""}export function newCondition(e,t){const o=filterKindOf(t);if(!o)return null;const n=operatorsFor(o)[0].op,i=o==="link"&&typeof t.fieldProps?.table=="string"?t.fieldProps.table:void 0;return{column:e,kind:o,op:n,value:defaultValue(o,n),...i?{table:i}:{}}}export function isComplete(e){if(NO_VALUE.has(e.op)||e.kind==="checkbox")return!0;const t=e.value;if(t==null)return!1;if(Array.isArray(t))return t.length>0;if(typeof t=="string")return t.trim()!=="";if(e.kind==="date"&&typeof t=="object"){const o=t;if(o.mode==="exactDate")return!!o.date;if(o.span==="pastDays"||o.span==="nextDays")return Number(o.days)>0}return!0}export function conditionCount(e){if(!e)return 0;let t=0;for(const o of e.conditions)isGroup(o)?t+=o.conditions.filter(isComplete).length:isComplete(o)&&(t+=1);return t}const p=e=>String(e??"").trim().toLocaleLowerCase(),m=e=>e==null||e===""?[]:Array.isArray(e)?e.map(t=>String(t&&typeof t=="object"?t.id??t.name??"":t)):[String(e)],d=e=>e==null||e===""||Array.isArray(e)&&e.length===0||typeof e=="number"&&Number.isNaN(e),E=864e5;export function dayOf(e){if(e==null||e==="")return null;let t;if(e instanceof Date)t=e;else if(typeof e=="number")t=new Date(e);else{const o=String(e),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(o);t=n?new Date(Number(n[1]),Number(n[2])-1,Number(n[3])):new Date(o)}return Number.isNaN(t.getTime())?null:Math.floor((t.getTime()-t.getTimezoneOffset()*6e4)/E)}function M(e,t){switch(e.mode){case"today":return t;case"tomorrow":return t+1;case"yesterday":return t-1;case"oneWeekAgo":return t-7;case"oneWeekFromNow":return t+7;case"oneMonthAgo":return t-30;case"oneMonthFromNow":return t+30;case"exactDate":return dayOf(e.date)}}function T(e,t){const o=Math.max(1,Math.floor(Number(e.days)||1));switch(e.span){case"pastWeek":return[t-7,t];case"pastMonth":return[t-30,t];case"pastYear":return[t-365,t];case"nextWeek":return[t,t+7];case"nextMonth":return[t,t+30];case"nextYear":return[t,t+365];case"pastDays":return[t-o,t];case"nextDays":return[t,t+o]}}export function compileCondition(e,t,o=new Date){if(e.op==="isEmpty")return d;if(e.op==="isNotEmpty")return n=>!d(n);switch(e.kind){case"number":{const n=Number(e.value);if(!Number.isFinite(n))return()=>!0;const i=r=>d(r)?NaN:Number(r),s={eq:r=>r===n,neq:r=>r!==n,lt:r=>r<n,gt:r=>r>n,lte:r=>r<=n,gte:r=>r>=n}[e.op]??(()=>!0);return r=>{const l=i(r);return Number.isNaN(l)?e.op==="neq":s(l)}}case"checkbox":{const n=e.value!==!1;return i=>!!i===n}case"select":case"multi":{const n=b(),i=m(e.value).map(s=>s===ME&&n!=null?n:s),a=new Set(i);return e.op==="is"?s=>m(s)[0]===i[0]:e.op==="isNot"?s=>m(s)[0]!==i[0]:e.op==="isAnyOf"||e.op==="hasAnyOf"?s=>m(s).some(r=>a.has(r)):e.op==="isNoneOf"||e.op==="hasNoneOf"?s=>!m(s).some(r=>a.has(r)):e.op==="hasAllOf"?s=>{const r=new Set(m(s));return[...a].every(l=>r.has(l))}:e.op==="isExactly"?s=>{const r=new Set(m(s));return r.size===a.size&&[...a].every(l=>r.has(l))}:()=>!0}case"date":{const n=dayOf(o);if(e.op==="isWithin"){const[r,l]=T(e.value??{span:"pastWeek"},n);return u=>{const c=dayOf(u);return c!=null&&c>=r&&c<=l}}const i=M(e.value??{mode:"today"},n);if(i==null)return()=>!0;const s={is:r=>r===i,isBefore:r=>r<i,isAfter:r=>r>i,isOnOrBefore:r=>r<=i,isOnOrAfter:r=>r>=i}[e.op]??(()=>!0);return r=>{const l=dayOf(r);return l!=null&&s(l)}}case"files":{const n=p(e.value);return i=>(Array.isArray(i)?i:[]).some(a=>p(a?.name).includes(n))}case"checklist":{const n=a=>{const s=y(a);return s.total>0&&s.done===s.total};if(e.op==="allDone")return n;if(e.op==="notAllDone")return a=>!n(a);if(e.op==="contains"){const a=p(e.value);return s=>g(s).some(r=>p(r.text).includes(a))}const i=parseFloat(String(e.value??""));return Number.isFinite(i)?a=>{const s=x(a);return s==null?!1:e.op==="lt"?s*100<i:s*100>=i}:()=>!0}case"time":{const n=k(String(e.value??"")),i=h(n);if(n==null||i==null)return()=>!0;const a=n.length>5?1:60,s=Math.floor(i/a),l={is:u=>u===s,isBefore:u=>u<s,isAfter:u=>u>s,isOnOrBefore:u=>u<=s,isOnOrAfter:u=>u>=s}[e.op]??(()=>!0);return u=>{const c=h(u);return c!=null&&l(Math.floor(c/a))}}case"link":case"text":{const n=p(e.value),i=a=>e.kind==="link"&&e.table&&t?p(t(e.table,a).join(", ")):p(Array.isArray(a)?a.map(s=>s&&typeof s=="object"?s.name??"":s).join(", "):a);return e.op==="contains"?a=>i(a).includes(n):e.op==="notContains"?a=>!i(a).includes(n):e.op==="is"?a=>i(a)===n:e.op==="isNot"?a=>i(a)!==n:()=>!0}}}export function compileFieldFilter(e,t,o,n){const i=r=>{const l=compileCondition(r,o,n);return u=>l(t(u,r.column))},a=(r,l)=>r==="or"?u=>l.some(c=>c(u)):u=>l.every(c=>c(u)),s=[];for(const r of e.conditions)if(isGroup(r)){const l=r.conditions.filter(isComplete).map(i);l.length&&s.push(a(r.conjunction,l))}else isComplete(r)&&s.push(i(r));return s.length?a(e.conjunction,s):null}const W={today:"today",tomorrow:"tomorrow",yesterday:"yesterday",oneWeekAgo:"one week ago",oneWeekFromNow:"one week from now",oneMonthAgo:"one month ago",oneMonthFromNow:"one month from now"},P={pastWeek:"the past week",pastMonth:"the past month",pastYear:"the past year",nextWeek:"the next week",nextMonth:"the next month",nextYear:"the next year"};function j(e){if(NO_VALUE.has(e.op))return"";if(e.kind==="checkbox")return e.value===!1?"unchecked":"checked";if(e.kind==="date"){if(e.op==="isWithin"){const n=e.value??{span:"pastWeek"};return n.span==="pastDays"?`the past ${n.days??0} days`:n.span==="nextDays"?`the next ${n.days??0} days`:P[n.span]??n.span}const o=e.value??{mode:"today"};return o.mode==="exactDate"?o.date:W[o.mode]??o.mode}const t=o=>o===ME?"me":String(o);return Array.isArray(e.value)?e.value.map(t).join(", "):t(e.value??"")}export function describeCondition(e,t=o=>o){const o=operatorsFor(e.kind).find(n=>n.op===e.op)?.label??e.op;return[t(e.column),o,j(e)].filter(Boolean).join(" ")}export function describeFieldFilter(e,t){const o=[];for(const n of e.conditions)if(isGroup(n)){const i=n.conditions.filter(isComplete).map(a=>describeCondition(a,t));i.length&&o.push(i.length>1?`(${i.join(` ${n.conjunction} `)})`:i[0])}else isComplete(n)&&o.push(describeCondition(n,t));return o.length?o.join(` ${e.conjunction} `):"every record"}export function fieldFilterColumns(e){const t=new Set;for(const o of e.conditions)for(const n of isGroup(o)?o.conditions:[o])isComplete(n)&&t.add(n.column);return[...t]}
@@ -0,0 +1,69 @@
1
+ import { type FieldFilter } from './filter-model.js';
2
+ import type { FieldColumn } from './grid-access.js';
3
+ /**
4
+ * Where a form's prefilled answers come from: the link's query string (a
5
+ * whole URL, `?prefill_...` or `URLSearchParams`), `true` for the page's own
6
+ * URL, or values by field name or column id.
7
+ */
8
+ export type FormPrefill = Record<string, unknown> | URLSearchParams | string | boolean;
9
+ /**
10
+ * A value as the grid would store it from a cell edit: coerced for the
11
+ * editor type, then through the column's valueParser, so a custom field
12
+ * type parses the same in a form.
13
+ */
14
+ export declare function formValue(c: FieldColumn, raw: unknown, row: Record<string, unknown>): unknown;
15
+ /**
16
+ * A prefilled answer as the field's value, or undefined when it gives none:
17
+ * text a number field cannot read, a select option the field does not have
18
+ * (dropped, never added), a link to no record, a file.
19
+ */
20
+ export declare function prefillValue(c: FieldColumn, raw: unknown, row?: Record<string, unknown>): unknown;
21
+ /** The column a name in a link means: its name, its id, then either one in any case. */
22
+ export declare function formFieldNamed<C extends Pick<FieldColumn, 'id' | 'header'>>(columns: ReadonlyArray<C>, name: string): C | undefined;
23
+ /**
24
+ * The answers a prefill source gives the form's fields, by column id, still
25
+ * as written, and the ids a `hide_` parameter names. A name no field has is
26
+ * ignored.
27
+ */
28
+ export declare function readFormPrefill(source: FormPrefill | null | undefined, columns: ReadonlyArray<Pick<FieldColumn, 'id' | 'header'>>): {
29
+ values: Record<string, unknown>;
30
+ hide: Set<string>;
31
+ };
32
+ /** What a prefill source reads as now, to tell when it names other answers. */
33
+ export declare function formPrefillKey(source: FormPrefill | null | undefined): string;
34
+ /**
35
+ * A link that opens a form with answers filled in: `baseUrl` (the page the
36
+ * form is on, its own query kept) plus `prefill_<Field name>=value` for each
37
+ * value, keyed by column id or field. With `columns`, the parameter carries
38
+ * the field's name; without, the key itself. A list is comma-separated, a
39
+ * date `YYYY-MM-DD`. `hide` names the fields the form leaves out of sight.
40
+ */
41
+ export declare function formPrefillLink(baseUrl: string, values: Record<string, unknown>, columns?: ReadonlyArray<{
42
+ id?: string;
43
+ field?: string;
44
+ header?: unknown;
45
+ }>, options?: {
46
+ hide?: ReadonlyArray<string>;
47
+ }): string;
48
+ /**
49
+ * The form's conditions as one test per column id: given the answers so
50
+ * far (by field), whether the field is shown. A condition reads the other
51
+ * fields by column id, the way the view bar's filter does; one with no
52
+ * complete condition always shows its field.
53
+ */
54
+ export declare function compileFormConditions(conditions: Record<string, FieldFilter> | undefined, columns: ReadonlyArray<Pick<FieldColumn, 'id' | 'field'>>): Map<string, (values: Record<string, unknown>) => boolean>;
55
+ /**
56
+ * The answers with every hidden field taken out, and the ids hidden. Taking
57
+ * one out can hide another that depends on it, so it runs until nothing
58
+ * moves. A field shown again (hidden in `was`) gets back what it started
59
+ * with (`initial`). `context` holds values of fields the form does not ask
60
+ * for, which conditions may read.
61
+ */
62
+ export declare function settleFormAnswers(draft: Record<string, unknown>, columns: ReadonlyArray<Pick<FieldColumn, 'id' | 'field'>>, tests: Map<string, (values: Record<string, unknown>) => boolean>, opts?: {
63
+ initial?: Record<string, unknown>;
64
+ context?: Record<string, unknown>;
65
+ was?: ReadonlySet<string>;
66
+ }): {
67
+ draft: Record<string, unknown>;
68
+ hidden: Set<string>;
69
+ };
@@ -0,0 +1 @@
1
+ import{parseEditorValue as y}from"@svgrid/grid";import{compileFieldFilter as S}from"./filter-model.js";import{linkNames as g}from"./base-alerts.js";const h=e=>e==null||e===""||Array.isArray(e)&&e.length===0||typeof e=="number"&&Number.isNaN(e);function w(e,t){if(t instanceof Date&&e.def.cellDataType==="dateString"){const i=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${i(t.getMonth()+1)}-${i(t.getDate())}`}return t}export function formValue(e,t,i){const r=e.def,n=y(String(r.editorType??"text"),w(e,t),{multiple:r.editorMultiple===!0,dateOnly:r.cellDataType==="dateString"}),f=r.valueParser;return f?f({newValue:n,oldValue:i[e.field],rawInput:t,data:i,columnId:e.id}):n}const x=new Set(["attachment","formula","lookup","rollup","count","autoNumber","createdTime","lastModifiedTime","createdBy","lastModifiedBy","button"]),A=new Set(["singleSelect","multiSelect","user"]);export function prefillValue(e,t,i={}){if(x.has(e.fieldType??""))return;let r=t;Array.isArray(t)&&(r=t.map(f=>String(f)).join(",")),e.def.editorType==="checkbox"&&typeof r=="string"&&(r=/^(true|1|yes|on|checked)$/i.test(r.trim()));let n=formValue(e,r,i);if(A.has(e.fieldType??"")&&Array.isArray(e.def.editorOptions)){const f=new Set(e.def.editorOptions.map(o=>String(o.value)));n=Array.isArray(n)?n.filter(o=>f.has(String(o))):n!=null&&f.has(String(n))?n:void 0}return h(n)?void 0:n}function m(e){if(e instanceof URLSearchParams)return e;if(e===!0)return typeof window>"u"?new URLSearchParams:new URLSearchParams(window.location.search);if(typeof e=="string"){const t=e.split("#")[0]??"",i=t.indexOf("?");return new URLSearchParams(i>=0?t.slice(i+1):t)}return null}export function formFieldNamed(e,t){const i=t.trim(),r=i.toLocaleLowerCase();return e.find(n=>n.header===i)??e.find(n=>n.id===i)??e.find(n=>n.header.toLocaleLowerCase()===r||n.id.toLocaleLowerCase()===r)}export function readFormPrefill(e,t){const i={},r=new Set;if(e==null||e===!1)return{values:i,hide:r};const n=m(e);if(!n){for(const[f,o]of Object.entries(e)){const a=formFieldNamed(t,f);a&&(i[a.id]=o)}return{values:i,hide:r}}for(const[f,o]of n){const a=/^(prefill|hide)_(.+)$/.exec(f);if(!a)continue;const s=formFieldNamed(t,a[2]);s&&(a[1]==="prefill"?i[s.id]=o:/^(true|1|yes)$/i.test(o.trim())&&r.add(s.id))}return{values:i,hide:r}}export function formPrefillKey(e){if(e==null||e===!1)return"";const t=m(e);if(t)return t.toString();try{return JSON.stringify(e)}catch{return String(e)}}export function formPrefillLink(e,t,i,r={}){const n=l=>{const c=i?.find(d=>(d.id??d.field)===l||d.field===l);return c&&typeof c.header=="string"&&c.header?c.header:l},f=l=>Array.isArray(l)?l.map(f).join(","):l instanceof Date?l.toISOString().slice(0,10):String(l),o=e.indexOf("#")>=0?e.slice(e.indexOf("#")):"",a=o?e.slice(0,e.length-o.length):e,s=[];for(const[l,c]of Object.entries(t))h(c)||s.push(`prefill_${encodeURIComponent(n(l))}=${encodeURIComponent(f(c))}`);for(const l of r.hide??[])s.push(`hide_${encodeURIComponent(n(l))}=true`);if(!s.length)return e;const u=a.includes("?")?a.endsWith("?")||a.endsWith("&")?"":"&":"?";return`${a}${u}${s.join("&")}${o}`}export function compileFormConditions(e,t){const i=new Map;if(!e)return i;const r=new Map(t.map(n=>[n.id,n.field]));for(const[n,f]of Object.entries(e)){if(!f||!Array.isArray(f.conditions))continue;const o=S(f,(a,s)=>a[r.get(s)??s],g);o&&i.set(n,o)}return i}export function settleFormAnswers(e,t,i,r={}){const n=r.initial??{},f=r.context??{},o={...e};let a=new Set(r.was??[]);if(!i.size)return{draft:o,hidden:new Set};for(let s=0;s<=t.length;s++){const u={...f,...o},l=new Set(t.filter(d=>i.has(d.id)&&!i.get(d.id)(u)).map(d=>d.id));let c=!1;for(const d of t)if(l.has(d.id))d.field in o&&(delete o[d.field],c=!0);else if(a.has(d.id)&&!(d.field in o)&&d.field in n){const p=n[d.field];o[d.field]=Array.isArray(p)?p.slice():p,c=!0}if(a=l,!c)break}return{draft:o,hidden:a}}
@@ -1 +1 @@
1
- import{toDate as y}from"./format.js";export class FormulaError extends Error{}function w(t){const e=[];let n=0;for(;n<t.length;){const r=t[n];if(/\s/.test(r)){n++;continue}if(r==="{"){const i=t.indexOf("}",n);if(i<0)throw new FormulaError(`Unclosed "{" at ${n+1}`);e.push({k:"ref",v:t.slice(n+1,i).trim(),at:n}),n=i+1;continue}if(r==='"'||r==="'"){let i=n+1,a="";for(;i<t.length&&t[i]!==r;){if(t[i]==="\\"&&i+1<t.length){a+=t[i+1],i+=2;continue}a+=t[i++]}if(i>=t.length)throw new FormulaError(`Unclosed text at ${n+1}`);e.push({k:"str",v:a,at:n}),n=i+1;continue}const l=/^\d+(\.\d+)?|^\.\d+/.exec(t.slice(n));if(l){e.push({k:"num",v:l[0],at:n}),n+=l[0].length;continue}const o=/^[A-Za-z_][A-Za-z0-9_]*/.exec(t.slice(n));if(o){e.push({k:"id",v:o[0],at:n}),n+=o[0].length;continue}const c=/^(!=|<=|>=|<>|[-+*/&=<>])/.exec(t.slice(n));if(c){e.push({k:"op",v:c[0]==="<>"?"!=":c[0],at:n}),n+=c[0].length;continue}if(r==="("||r===")"||r===","){e.push({k:r,v:r,at:n}),n++;continue}throw new FormulaError(`Unexpected "${r}" at ${n+1}`)}return e}const g=t=>t==null||t===""||Array.isArray(t)&&t.length===0,s=t=>{if(typeof t=="number")return t;if(typeof t=="boolean")return t?1:0;if(t instanceof Date)return t.getTime();if(t==null||t==="")return 0;if(Array.isArray(t))return t.reduce((n,r)=>n+s(r),0);const e=Number(t);return Number.isFinite(e)?e:NaN},u=t=>t==null?"":t instanceof Date?t.toISOString():Array.isArray(t)?t.map(u).join(", "):String(t),d=t=>!g(t)&&t!==!1&&t!==0,I=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;export function isoDate(t){const e=t.trim();return I.test(e)?y(e):null}const h=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(t==null||t===""||typeof t=="boolean")return null;if(typeof t=="number")return y(t);const e=u(t).trim();return isoDate(e)??(/\d{4}/.test(e)&&/[/\s,.-]/.test(e)?y(e):null)},f=t=>t.flatMap(e=>Array.isArray(e)?e:[e]),A=t=>String(t).padStart(2,"0"),k=t=>Number(t.toPrecision(12)),U={milliseconds:"ms",millisecond:"ms",ms:"ms",seconds:"s",second:"s",s:"s",minutes:"m",minute:"m",m:"m",hours:"h",hour:"h",h:"h",days:"d",day:"d",d:"d",weeks:"w",week:"w",w:"w",months:"mo",month:"mo",years:"y",year:"y",y:"y"},T={ms:1,s:1e3,m:6e4,h:36e5},D=t=>U[u(t).trim().toLowerCase()]??null;function x(t,e){const n=new Date(t),r=n.getDate();return n.setDate(1),n.setMonth(n.getMonth()+e),n.setDate(Math.min(r,new Date(n.getFullYear(),n.getMonth()+1,0).getDate())),n}function F(t,e,n){if(T[n])return new Date(t.getTime()+e*T[n]);if(n==="mo"||n==="y")return x(t,Math.trunc(e)*(n==="y"?12:1));const r=e*(n==="w"?7:1),l=new Date(t);return l.setDate(l.getDate()+Math.trunc(r)),new Date(l.getTime()+(r-Math.trunc(r))*864e5)}const E=t=>t.getTime()-t.getTimezoneOffset()*6e4;function $(t,e,n){if(T[n])return Math.trunc((t.getTime()-e.getTime())/T[n]);if(n==="d"||n==="w")return Math.trunc((E(t)-E(e))/(n==="w"?6048e5:864e5));let r=(t.getFullYear()-e.getFullYear())*12+t.getMonth()-e.getMonth();const l=x(e,r).getTime();return r>0&&l>t.getTime()?r-=1:r<0&&l<t.getTime()&&(r+=1),n==="y"?Math.trunc(r/12):r}const S={IF:t=>d(t[0]??null)?t[1]??null:t[2]??null,AND:t=>f(t).every(d),OR:t=>f(t).some(d),NOT:t=>!d(t[0]??null),XOR:t=>f(t).filter(d).length%2===1,BLANK:()=>null,SWITCH:t=>{for(let e=1;e+1<t.length;e+=2)if(u(t[0]??null)===u(t[e]??null))return t[e+1]??null;return t.length%2===0?t[t.length-1]??null:null},CONCATENATE:t=>t.map(u).join(""),LEN:t=>u(t[0]??null).length,UPPER:t=>u(t[0]??null).toUpperCase(),LOWER:t=>u(t[0]??null).toLowerCase(),TRIM:t=>u(t[0]??null).trim(),LEFT:t=>u(t[0]??null).slice(0,s(t[1]??1)),RIGHT:t=>{const e=u(t[0]??null),n=s(t[1]??1);return n<=0?"":e.slice(-n)},MID:t=>{const e=u(t[0]??null),n=Math.max(0,s(t[1]??1)-1);return t.length>2?e.slice(n,n+Math.max(0,s(t[2]??0))):e.slice(n)},FIND:t=>u(t[1]??null).indexOf(u(t[0]??null),Math.max(0,s(t[2]??1)-1))+1,SUBSTITUTE:t=>u(t[0]??null).split(u(t[1]??null)).join(u(t[2]??null)),REPT:t=>u(t[0]??null).repeat(Math.max(0,Math.min(1e3,s(t[1]??0)))),T:t=>typeof t[0]=="string"?t[0]:"",VALUE:t=>{const e=u(t[0]??null).replace(/[^0-9.eE+-]/g,""),n=/\d/.test(e)?Number(e):NaN;return Number.isFinite(n)?n:null},ARRAYJOIN:t=>f([t[0]??null]).map(u).filter(Boolean).join(t.length>1?u(t[1]??null):", "),SUM:t=>f(t).reduce((e,n)=>e+s(n),0),AVERAGE:t=>{const e=f(t).filter(n=>!g(n));return e.length?e.reduce((n,r)=>n+s(r),0)/e.length:null},MAX:t=>{const e=f(t).filter(n=>!g(n)).map(s);return e.length?Math.max(...e):null},MIN:t=>{const e=f(t).filter(n=>!g(n)).map(s);return e.length?Math.min(...e):null},COUNT:t=>f(t).filter(e=>typeof e=="number").length,COUNTA:t=>f(t).filter(e=>!g(e)).length,ROUND:t=>{const e=10**s(t[1]??0);return Math.round(s(t[0]??null)*e)/e},ROUNDUP:t=>{const e=10**s(t[1]??0);return Math.ceil(s(t[0]??null)*e)/e},ROUNDDOWN:t=>{const e=10**s(t[1]??0);return Math.floor(s(t[0]??null)*e)/e},INT:t=>Math.floor(s(t[0]??null)),ABS:t=>Math.abs(s(t[0]??null)),MOD:t=>s(t[0]??null)%s(t[1]??1),POWER:t=>s(t[0]??null)**s(t[1]??1),SQRT:t=>Math.sqrt(s(t[0]??null)),CEILING:t=>{const e=s(t[1]??1);return e===0?0:k(Math.ceil(k(s(t[0]??null)/e))*e)},FLOOR:t=>{const e=s(t[1]??1);return e===0?0:k(Math.floor(k(s(t[0]??null)/e))*e)},TODAY:()=>{const t=new Date;return t.setHours(0,0,0,0),t},NOW:()=>new Date,YEAR:t=>h(t[0]??null)?.getFullYear()??null,MONTH:t=>{const e=h(t[0]??null);return e?e.getMonth()+1:null},DAY:t=>h(t[0]??null)?.getDate()??null,WEEKDAY:t=>h(t[0]??null)?.getDay()??null,DATEADD:t=>{const e=h(t[0]??null),n=t.length>2?D(t[2]??null):"d";return e&&n?F(e,s(t[1]??0),n):null},DATETIME_DIFF:t=>{const e=h(t[0]??null),n=h(t[1]??null),r=t.length>2?D(t[2]??null):"s";return e&&n&&r?$(e,n,r):null},IS_BEFORE:t=>{const e=h(t[0]??null),n=h(t[1]??null);return!!e&&!!n&&e<n},IS_AFTER:t=>{const e=h(t[0]??null),n=h(t[1]??null);return!!e&&!!n&&e>n},DATESTR:t=>{const e=h(t[0]??null);return e?`${e.getFullYear()}-${A(e.getMonth()+1)}-${A(e.getDate())}`:null}};function O(t,e,n){switch(t){case"=":return e===n;case"!=":return e!==n;case"<":return e<n;case">":return e>n;case"<=":return e<=n;default:return e>=n}}const b=new Set(["DATEADD","DATETIME_DIFF"]);export const FORMULA_FUNCTIONS=Object.keys(S).sort(),selfReferenceError=t=>new FormulaError(`A formula cannot read its own field {${t.trim()}}`);export function columnResolver(t,e=[]){const n=new Set(e.filter(r=>r!=null&&String(r).trim()!=="").map(r=>String(r).trim().toLowerCase()));return r=>{const l=r.trim().toLowerCase();if(n.has(l))throw selfReferenceError(r);const o=t.find(c=>String(c.header??"").trim().toLowerCase()===l||String(c.field??"").toLowerCase()===l);return o?String(o.field??o.id):null}}class C{constructor(e,n,r){this.toks=e,this.resolve=n,this.refs=r,this.i=0}peek(){return this.toks[this.i]}next(){return this.toks[this.i++]}expect(e,n){const r=this.next();if(!r||r.k!==e||n&&r.v!==n)throw new FormulaError(`Expected "${n??e}"${r?` at ${r.at+1}`:" at the end"}`);return r}parse(){const e=this.compare();if(this.peek())throw new FormulaError(`Unexpected "${this.peek().v}" at ${this.peek().at+1}`);return e}compare(){let e=this.concat();for(let n=this.peek();n&&n.k==="op"&&["=","!=","<",">","<=",">="].includes(n.v);n=this.peek()){this.next();const r=n.v,l=e,o=this.concat();e=c=>{const i=l(c),a=o(c);if(i instanceof Date||a instanceof Date){const M=h(i),N=h(a);return!M||!N?r==="!=":O(r,M.getTime(),N.getTime())}const m=typeof i=="number"||typeof a=="number",p=m?s(i):u(i),R=m?s(a):u(a);return O(r,p,R)}}return e}concat(){let e=this.add();for(;this.peek()?.k==="op"&&this.peek().v==="&";){this.next();const n=e,r=this.add();e=l=>u(n(l))+u(r(l))}return e}add(){let e=this.mul();for(let n=this.peek();n&&n.k==="op"&&(n.v==="+"||n.v==="-");n=this.peek()){this.next();const r=e,l=this.mul(),o=n.v==="+";e=c=>o?s(r(c))+s(l(c)):s(r(c))-s(l(c))}return e}mul(){let e=this.unary();for(let n=this.peek();n&&n.k==="op"&&(n.v==="*"||n.v==="/");n=this.peek()){this.next();const r=e,l=this.unary(),o=n.v==="*";e=c=>{if(o)return s(r(c))*s(l(c));const i=s(l(c));return i===0?null:s(r(c))/i}}return e}unary(){const e=this.peek();if(e?.k==="op"&&e.v==="-"){this.next();const n=this.unary();return r=>-s(n(r))}return this.primary()}primary(){const e=this.next();if(!e)throw new FormulaError("The formula ends too early");if(e.k==="num"){const n=Number(e.v);return()=>n}if(e.k==="str"){const n=e.v;return()=>n}if(e.k==="ref"){const n=this.resolve(e.v);if(n==null)throw new FormulaError(`No field named "${e.v}"`);return this.refs.add(n),r=>r?.[n]??null}if(e.k==="("){const n=this.compare();return this.expect(")"),n}if(e.k==="id"){const n=e.v.toUpperCase();if(n==="TRUE"&&this.peek()?.k!=="(")return()=>!0;if(n==="FALSE"&&this.peek()?.k!=="(")return()=>!1;const r=S[n];if(!r)throw new FormulaError(`Unknown function ${e.v}`);this.expect("(");const l=[],o=[],c=()=>{const a=this.i;l.push(this.compare());const m=this.i===a+1?this.toks[a]:void 0;o.push(m?.k==="str"?m.v:void 0)};if(this.peek()?.k!==")")for(c();this.peek()?.k===",";)this.next(),c();this.expect(")");const i=o[2];if(b.has(n)&&i!==void 0&&!D(i))throw new FormulaError(`Unknown unit "${i}" in ${n}: use ms, seconds, minutes, hours, days, weeks, months or years`);return n==="IF"?a=>d(l[0]?.(a)??null)?l[1]?.(a)??null:l[2]?.(a)??null:n==="SWITCH"?a=>{if(!l.length)return null;const m=u(l[0](a));for(let p=1;p+1<l.length;p+=2)if(m===u(l[p](a)))return l[p+1](a);return l.length%2===0?l[l.length-1](a):null}:a=>r(l.map(m=>m(a)))}throw new FormulaError(`Unexpected "${e.v}" at ${e.at+1}`)}}export function compileFormula(t,e){if(!t.trim())throw new FormulaError("The formula is empty");const n=new Set,r=new C(w(t),e,n).parse();return{fn:l=>{try{const o=r(l);return typeof o=="number"&&!Number.isFinite(o)?null:o}catch{return null}},refs:[...n]}}export function renameFormulaRefs(t,e){let n;try{n=w(t)}catch{return t}let r="",l=0;for(const o of n){if(o.k!=="ref")continue;const c=e(o.v);if(c==null)continue;const i=t.indexOf("}",o.at);r+=`${t.slice(l,o.at)}{${c}}`,l=i+1}return l?r+t.slice(l):t}export function formulaRefs(t,e){let n;try{n=w(t)}catch{return[]}const r=new Set;for(const l of n)if(l.k==="ref")try{const o=e(l.v);o!=null&&r.add(o)}catch{}return[...r]}export function formulaReaders(t,e){const n=new Set([e.field,e.id].filter(l=>l!=null&&l!=="").map(String));if(!n.size)return[];const r=columnResolver(t);return t.filter(l=>l.fieldType!=="formula"||n.has(String(l.field??l.id??""))?!1:formulaRefs(String(l.fieldProps?.formula??""),r).some(o=>n.has(o)))}export function formulaError(t,e){try{return compileFormula(t,e),null}catch(n){return n instanceof FormulaError?n.message:"The formula is not valid"}}
1
+ import{toDate as $}from"./format.js";export class FormulaError extends Error{}function b(e){const n=[];let t=0;for(;t<e.length;){const r=e[t];if(/\s/.test(r)){t++;continue}if(r==="{"){const i=e.indexOf("}",t);if(i<0)throw new FormulaError(`Unclosed "{" at ${t+1}`);n.push({k:"ref",v:e.slice(t+1,i).trim(),at:t}),t=i+1;continue}if(r==='"'||r==="'"){let i=t+1,c="";for(;i<e.length&&e[i]!==r;){if(e[i]==="\\"&&i+1<e.length){c+=e[i+1],i+=2;continue}c+=e[i++]}if(i>=e.length)throw new FormulaError(`Unclosed text at ${t+1}`);n.push({k:"str",v:c,at:t}),t=i+1;continue}const l=/^\d+(\.\d+)?|^\.\d+/.exec(e.slice(t));if(l){n.push({k:"num",v:l[0],at:t}),t+=l[0].length;continue}const s=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(t));if(s){n.push({k:"id",v:s[0],at:t}),t+=s[0].length;continue}const f=/^(!=|<=|>=|<>|[-+*/&=<>])/.exec(e.slice(t));if(f){n.push({k:"op",v:f[0]==="<>"?"!=":f[0],at:t}),t+=f[0].length;continue}if(r==="("||r===")"||r===","){n.push({k:r,v:r,at:t}),t++;continue}throw new FormulaError(`Unexpected "${r}" at ${t+1}`)}return n}const y=e=>e==null||e===""||Array.isArray(e)&&e.length===0,o=e=>{if(typeof e=="number")return e;if(typeof e=="boolean")return e?1:0;if(e instanceof Date)return e.getTime();if(e==null||e==="")return 0;if(Array.isArray(e))return e.reduce((t,r)=>t+o(r),0);const n=Number(e);return Number.isFinite(n)?n:NaN},u=e=>e==null?"":e instanceof Date?e.toISOString():Array.isArray(e)?e.map(u).join(", "):String(e),A=e=>!y(e)&&e!==!1&&e!==0,ne=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;export function isoDate(e){const n=e.trim();return ne.test(n)?$(n):null}const h=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e==null||e===""||typeof e=="boolean")return null;if(typeof e=="number")return $(e);const n=u(e).trim();return isoDate(n)??(/\d{4}/.test(n)&&/[/\s,.-]/.test(n)?$(n):null)},d=e=>e.flatMap(n=>Array.isArray(n)?n:[n]),M=e=>String(e).padStart(2,"0"),R=e=>Number(e.toPrecision(12)),re={milliseconds:"ms",millisecond:"ms",ms:"ms",seconds:"s",second:"s",s:"s",minutes:"m",minute:"m",m:"m",hours:"h",hour:"h",h:"h",days:"d",day:"d",d:"d",weeks:"w",week:"w",w:"w",months:"mo",month:"mo",quarters:"q",quarter:"q",q:"q",years:"y",year:"y",y:"y"},k={ms:1,s:1e3,m:6e4,h:36e5},x=e=>re[u(e).trim().toLowerCase()]??null;function W(e,n){const t=new Date(e),r=t.getDate();return t.setDate(1),t.setMonth(t.getMonth()+n),t.setDate(Math.min(r,new Date(t.getFullYear(),t.getMonth()+1,0).getDate())),t}function le(e,n,t){if(k[t])return new Date(e.getTime()+n*k[t]);if(t==="mo"||t==="q"||t==="y")return W(e,Math.trunc(n)*(t==="y"?12:t==="q"?3:1));const r=n*(t==="w"?7:1),l=new Date(e);return l.setDate(l.getDate()+Math.trunc(r)),new Date(l.getTime()+(r-Math.trunc(r))*864e5)}const L=e=>e.getTime()-e.getTimezoneOffset()*6e4;function _(e,n,t){if(k[t])return Math.trunc((e.getTime()-n.getTime())/k[t]);if(t==="d"||t==="w")return Math.trunc((L(e)-L(n))/(t==="w"?6048e5:864e5));let r=(e.getFullYear()-n.getFullYear())*12+e.getMonth()-n.getMonth();const l=W(n,r).getTime();return r>0&&l>e.getTime()?r-=1:r<0&&l<e.getTime()&&(r+=1),t==="y"?Math.trunc(r/12):t==="q"?Math.trunc(r/3):r}function Y(e,n){if(n==="ms")return e.getTime();const t=new Date(e);return n==="s"?t.setMilliseconds(0):n==="m"?t.setSeconds(0,0):n==="h"?t.setMinutes(0,0,0):(t.setHours(0,0,0,0),n==="w"&&t.setDate(t.getDate()-t.getDay()),(n==="mo"||n==="q"||n==="y")&&t.setDate(1),n==="q"&&t.setMonth(t.getMonth()-t.getMonth()%3),n==="y"&&t.setMonth(0),t.getTime())}const O=e=>`${e.getFullYear()}-${M(e.getMonth()+1)}-${M(e.getDate())}`;function z(e){const n=d([e??null]).flatMap(t=>typeof t=="string"?t.split(","):[t]);return new Set(n.map(t=>h(typeof t=="string"?t.trim():t)).filter(t=>!!t).map(O))}const X=(e,n)=>e.getDay()!==0&&e.getDay()!==6&&!n.has(O(e)),q=1e5;class se extends Date{}function v(e,n){const t=new se(e.getTime()),r=e;return t.locale=n.locale??r.locale,t.zone=n.zone??r.zone,t}const j=new Map;function G(e){let n=j.get(e);return n||(n=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",weekday:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}),j.set(e,n)),n}const oe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function ue(e){const n=e.zone,t=e.getMilliseconds();if(!n)return{y:e.getFullYear(),mo:e.getMonth(),d:e.getDate(),h:e.getHours(),mi:e.getMinutes(),s:e.getSeconds(),ms:t,wd:e.getDay(),offset:-e.getTimezoneOffset()};const r={};for(const s of G(n).formatToParts(e))r[s.type]=s.value;const l={y:+r.year,mo:+r.month-1,d:+r.day,h:+r.hour%24,mi:+r.minute,s:+r.second,ms:t,wd:oe.indexOf(r.weekday),offset:0};return l.offset=Math.round((Date.UTC(l.y,l.mo,l.d,l.h,l.mi,l.s,t)-e.getTime())/6e4),l}const K=new Map;function I(e,n,t,r){const l=`${e??"en"}|${n}|${t}`;let s=K.get(l);return s||K.set(l,s=new Intl.DateTimeFormat(e??"en",{[n]:t,timeZone:"UTC"})),s.format(n==="month"?Date.UTC(2023,r,1):Date.UTC(2023,0,1+r))}const ie=e=>{const n=e%100;return`${e}${n>=11&&n<=13?"th":["th","st","nd","rd"][e%10]??"th"}`},B=(e,n)=>{const t=Math.abs(e);return`${e<0?"-":"+"}${M(Math.floor(t/60))}${n?":":""}${M(t%60)}`},ce={LTS:"h:mm:ss A",LT:"h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A",LLL:"MMMM D, YYYY h:mm A",LL:"MMMM D, YYYY",L:"MM/DD/YYYY"},ae=/\[([^\]]*)]|YYYY|YY|Q|MMMM|MMM|MM|M|DDDD|DDD|Do|DD|D|dddd|ddd|d|HH|H|hh|h|mm|m|ss|s|SSS|SS|S|A|a|ZZ|Z|X|x/g;function fe(e,n){const t=ue(e),r=e.locale,l=n.replace(/\[[^\]]*]|LTS|LT|LLLL|LLL|LL|L/g,i=>ce[i]??i),s=t.h%12||12,f=Math.round((Date.UTC(t.y,t.mo,t.d)-Date.UTC(t.y,0,1))/864e5)+1;return l.replace(ae,(i,c)=>{if(c!==void 0)return c;switch(i){case"YYYY":return String(t.y).padStart(4,"0");case"YY":return M(t.y%100);case"Q":return String(Math.floor(t.mo/3)+1);case"MMMM":return I(r,"month","long",t.mo);case"MMM":return I(r,"month","short",t.mo);case"MM":return M(t.mo+1);case"M":return String(t.mo+1);case"DDDD":return String(f).padStart(3,"0");case"DDD":return String(f);case"Do":return ie(t.d);case"DD":return M(t.d);case"D":return String(t.d);case"dddd":return I(r,"weekday","long",t.wd);case"ddd":return I(r,"weekday","short",t.wd);case"d":return String(t.wd);case"HH":return M(t.h);case"H":return String(t.h);case"hh":return M(s);case"h":return String(s);case"mm":return M(t.mi);case"m":return String(t.mi);case"ss":return M(t.s);case"s":return String(t.s);case"SSS":return String(t.ms).padStart(3,"0");case"SS":return M(Math.floor(t.ms/10));case"S":return String(Math.floor(t.ms/100));case"A":return t.h<12?"AM":"PM";case"a":return t.h<12?"am":"pm";case"ZZ":return B(t.offset,!1);case"Z":return B(t.offset,!0);case"X":return String(Math.floor(e.getTime()/1e3));default:return String(e.getTime())}})}const he=["january","february","march","april","may","june","july","august","september","october","november","december"],me=/\[([^\]]*)]|YYYY|YY|MMMM|MMM|MM|M|Do|DD|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|SSS|A|a|ZZ|Z|X|x/g;function de(e,n){const t=[];let r="^\\s*",l=0;const s=D=>D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s+");for(const D of n.matchAll(me)){if(r+=s(n.slice(l,D.index)),l=D.index+D[0].length,D[1]!==void 0){r+=s(D[1]);continue}const a=D[0];t.push(a),r+=a==="YYYY"?"(\\d{4})":a==="MMMM"||a==="MMM"||a==="dddd"||a==="ddd"?"([A-Za-z]+)\\.?":a==="Do"?"(\\d{1,2})(?:st|nd|rd|th)":a==="SSS"?"(\\d{1,3})":a==="A"||a==="a"?"([AaPp][Mm])":a==="Z"||a==="ZZ"?"(Z|[+-]\\d{2}:?\\d{2})":a==="X"||a==="x"?"(-?\\d+)":"(\\d{1,2})"}r+=`${s(n.slice(l))}\\s*$`;const f=new RegExp(r,"i").exec(e);if(!f)return null;let i=new Date().getFullYear(),c=0,m=1,g=0,E=0,S=0,w=0,U=null,N=null;for(let D=0;D<t.length;D++){const a=t[D],T=f[D+1],p=Number(T);if(a==="X"||a==="x")return new Date(a==="X"?p*1e3:p);if(a==="YYYY")i=p;else if(a==="YY")i=p+(p<69?2e3:1900);else if(a==="MMMM"||a==="MMM"){const P=he.findIndex(te=>te.startsWith(T.toLowerCase().slice(0,3)));if(P<0)return null;c=P}else a==="MM"||a==="M"?c=p-1:a==="DD"||a==="D"||a==="Do"?m=p:a==="HH"||a==="H"||a==="hh"||a==="h"?g=p:a==="mm"||a==="m"?E=p:a==="ss"||a==="s"?S=p:a==="SSS"?w=Number(T.padEnd(3,"0")):a==="A"||a==="a"?U=T.toLowerCase()==="pm":(a==="Z"||a==="ZZ")&&(N=T.toUpperCase()==="Z"?0:(T[0]==="-"?-1:1)*(Number(T.slice(1,3))*60+Number(T.slice(-2))))}if(U!=null&&(g=g%12+(U?12:0)),c<0||c>11||m<1||m>31||g>23||E>59||S>59)return null;const C=N==null?new Date(i,c,m,g,E,S,w):new Date(Date.UTC(i,c,m,g,E,S,w)-N*6e4);return N==null&&C.getDate()!==m||Number.isNaN(C.getTime())?null:C}const F=new Map;function H(e,n=!1){const t=`${n?"g":""}|${e}`;let r=F.get(t);if(!r){const l=/^\(\?([ims]+)\)/.exec(e);r=new RegExp(l?e.slice(l[0].length):e,`${l?.[1]??""}${n?"g":""}`),F.size>200&&F.clear(),F.set(t,r)}return r.lastIndex=0,r}const Z="#ERROR",V=e=>`${e instanceof Date?"d":typeof e}:${u(e)}`;function Me(e,n,t){const r=n<0?e.length+n:Math.max(0,n-1),l=t==null?e.length:t<0?e.length+t+1:t;return e.slice(r,l)}function Q(e,n){const t=e<0?-1:1;let r=Math.ceil(Math.abs(e));return r%2===1!==n&&(r+=1),t*r}const J={IF:e=>A(e[0]??null)?e[1]??null:e[2]??null,AND:e=>d(e).every(A),OR:e=>d(e).some(A),NOT:e=>!A(e[0]??null),XOR:e=>d(e).filter(A).length%2===1,TRUE:()=>!0,FALSE:()=>!1,BLANK:()=>null,ERROR:()=>{throw new FormulaError("ERROR()")},ISERROR:e=>e[0]===Z,RECORD_ID:()=>null,SWITCH:e=>{for(let n=1;n+1<e.length;n+=2)if(u(e[0]??null)===u(e[n]??null))return e[n+1]??null;return e.length%2===0?e[e.length-1]??null:null},CONCATENATE:e=>e.map(u).join(""),LEN:e=>u(e[0]??null).length,UPPER:e=>u(e[0]??null).toUpperCase(),LOWER:e=>u(e[0]??null).toLowerCase(),TRIM:e=>u(e[0]??null).trim(),LEFT:e=>u(e[0]??null).slice(0,o(e[1]??1)),RIGHT:e=>{const n=u(e[0]??null),t=o(e[1]??1);return t<=0?"":n.slice(-t)},MID:e=>{const n=u(e[0]??null),t=Math.max(0,o(e[1]??1)-1);return e.length>2?n.slice(t,t+Math.max(0,o(e[2]??0))):n.slice(t)},FIND:e=>u(e[1]??null).indexOf(u(e[0]??null),Math.max(0,o(e[2]??1)-1))+1,SEARCH:e=>{const n=u(e[1]??null).indexOf(u(e[0]??null),Math.max(0,o(e[2]??1)-1));return n<0?null:n+1},SUBSTITUTE:e=>{const n=u(e[0]??null).split(u(e[1]??null));if(e.length<4)return n.join(u(e[2]??null));const t=o(e[3]??null);return n.reduce((r,l,s)=>s===0?l:r+u(s===t?e[2]??null:e[1]??null)+l,"")},REPLACE:e=>{const n=u(e[0]??null),t=Math.max(0,o(e[1]??1)-1);return n.slice(0,t)+u(e[3]??null)+n.slice(t+Math.max(0,o(e[2]??0)))},ENCODE_URL_COMPONENT:e=>encodeURIComponent(u(e[0]??null)),REGEX_MATCH:e=>H(u(e[1]??null)).test(u(e[0]??null)),REGEX_EXTRACT:e=>H(u(e[1]??null)).exec(u(e[0]??null))?.[0]??null,REGEX_REPLACE:e=>u(e[0]??null).replace(H(u(e[1]??null),!0),u(e[2]??null)),REPT:e=>u(e[0]??null).repeat(Math.max(0,Math.min(1e3,o(e[1]??0)))),T:e=>typeof e[0]=="string"?e[0]:"",VALUE:e=>{const n=u(e[0]??null).replace(/[^0-9.eE+-]/g,""),t=/\d/.test(n)?Number(n):NaN;return Number.isFinite(t)?t:null},ARRAYJOIN:e=>d([e[0]??null]).map(u).filter(Boolean).join(e.length>1?u(e[1]??null):", "),ARRAYCOMPACT:e=>d([e[0]??null]).filter(n=>n!=null&&n!==""),ARRAYFLATTEN:e=>e.flat(1/0),ARRAYUNIQUE:e=>{const n=new Set;return d([e[0]??null]).filter(t=>!n.has(V(t))&&!!n.add(V(t)))},ARRAYSLICE:e=>Me(d([e[0]??null]),o(e[1]??1),e.length>2?o(e[2]??null):void 0),SUM:e=>d(e).reduce((n,t)=>n+o(t),0),AVERAGE:e=>{const n=d(e).filter(t=>!y(t));return n.length?n.reduce((t,r)=>t+o(r),0)/n.length:null},MAX:e=>{const n=d(e).filter(t=>!y(t)).map(o);return n.length?Math.max(...n):null},MIN:e=>{const n=d(e).filter(t=>!y(t)).map(o);return n.length?Math.min(...n):null},COUNT:e=>d(e).filter(n=>typeof n=="number").length,COUNTA:e=>d(e).filter(n=>!y(n)).length,COUNTALL:e=>d(e).length,ROUND:e=>{const n=10**o(e[1]??0);return Math.round(o(e[0]??null)*n)/n},ROUNDUP:e=>{const n=10**o(e[1]??0),t=o(e[0]??null);return Math.sign(t)*Math.ceil(R(Math.abs(t)*n))/n},ROUNDDOWN:e=>{const n=10**o(e[1]??0),t=o(e[0]??null);return Math.sign(t)*Math.floor(R(Math.abs(t)*n))/n},INT:e=>Math.floor(o(e[0]??null)),ABS:e=>Math.abs(o(e[0]??null)),MOD:e=>o(e[0]??null)%o(e[1]??1),POWER:e=>o(e[0]??null)**o(e[1]??1),SQRT:e=>Math.sqrt(o(e[0]??null)),EXP:e=>Math.exp(o(e[0]??null)),LOG:e=>Math.log(o(e[0]??null))/Math.log(e.length>1?o(e[1]??null):10),EVEN:e=>Q(o(e[0]??null),!1),ODD:e=>Q(o(e[0]??null),!0),CEILING:e=>{const n=o(e[1]??1);return n===0?0:R(Math.ceil(R(o(e[0]??null)/n))*n)},FLOOR:e=>{const n=o(e[1]??1);return n===0?0:R(Math.floor(R(o(e[0]??null)/n))*n)},TODAY:()=>{const e=new Date;return e.setHours(0,0,0,0),e},NOW:()=>new Date,YEAR:e=>h(e[0]??null)?.getFullYear()??null,MONTH:e=>{const n=h(e[0]??null);return n?n.getMonth()+1:null},DAY:e=>h(e[0]??null)?.getDate()??null,HOUR:e=>h(e[0]??null)?.getHours()??null,MINUTE:e=>h(e[0]??null)?.getMinutes()??null,SECOND:e=>h(e[0]??null)?.getSeconds()??null,WEEKDAY:e=>{const n=h(e[0]??null);return n?/^mon/i.test(u(e[1]??null))?(n.getDay()+6)%7:n.getDay():null},WEEKNUM:e=>{const n=h(e[0]??null);if(!n)return null;const t=/^mon/i.test(u(e[1]??null))?1:0,r=new Date(n.getFullYear(),0,1),l=Math.round((L(new Date(n.getFullYear(),n.getMonth(),n.getDate()))-L(r))/864e5);return Math.floor((l+(r.getDay()-t+7)%7)/7)+1},DATEADD:e=>{const n=h(e[0]??null),t=e.length>2?x(e[2]??null):"d";return n&&t?le(n,o(e[1]??0),t):null},DATETIME_DIFF:e=>{const n=h(e[0]??null),t=h(e[1]??null),r=e.length>2?x(e[2]??null):"s";return n&&t&&r?_(n,t,r):null},IS_BEFORE:e=>{const n=h(e[0]??null),t=h(e[1]??null);return!!n&&!!t&&n<t},IS_AFTER:e=>{const n=h(e[0]??null),t=h(e[1]??null);return!!n&&!!t&&n>t},IS_SAME:e=>{const n=h(e[0]??null),t=h(e[1]??null),r=e.length>2?x(e[2]??null):"ms";return!!n&&!!t&&!!r&&Y(n,r)===Y(t,r)},DATESTR:e=>{const n=h(e[0]??null);return n?O(n):null},TIMESTR:e=>{const n=h(e[0]??null);return n?`${M(n.getHours())}:${M(n.getMinutes())}:${M(n.getSeconds())}`:null},DATETIME_FORMAT:e=>{const n=h(e[0]??null);return n?fe(n,e.length>1&&!y(e[1]??null)?u(e[1]??null):"YYYY-MM-DDTHH:mm:ss.SSSZ"):null},DATETIME_PARSE:e=>e.length>1&&!y(e[1]??null)?de(u(e[0]??null),u(e[1]??null)):h(e[0]??null),SET_LOCALE:e=>{const n=h(e[0]??null),t=u(e[1]??null).trim();return!n||!t?n:v(n,{locale:Intl.DateTimeFormat.supportedLocalesOf(t)[0]??t})},SET_TIMEZONE:e=>{const n=h(e[0]??null),t=u(e[1]??null).trim();return!n||!t?n:(G(t),v(n,{zone:t}))},TONOW:e=>{const n=h(e[0]??null);return n?_(new Date(Y(new Date,"d")),new Date(Y(n,"d")),"d"):null},FROMNOW:e=>{const n=h(e[0]??null);return n?_(new Date(Y(n,"d")),new Date(Y(new Date,"d")),"d"):null},WORKDAY:e=>{const n=h(e[0]??null);if(!n)return null;const t=Math.trunc(o(e[1]??0)),r=t<0?-1:1,l=z(e[2]),s=new Date(n);for(let f=Math.abs(t),i=0;f>0;){if(++i>q)return null;s.setDate(s.getDate()+r),X(s,l)&&(f-=1)}return s},WORKDAY_DIFF:e=>{const n=h(e[0]??null),t=h(e[1]??null);if(!n||!t)return null;const r=z(e[2]),l=n>t?-1:1,s=new Date(l>0?n:t),f=O(l>0?t:n);let i=0;for(let c=0;O(s)<=f;c++){if(c>q)return null;X(s,r)&&(i+=1),s.setDate(s.getDate()+1)}return l*i}};function ee(e,n,t){switch(e){case"=":return n===t;case"!=":return n!==t;case"<":return n<t;case">":return n>t;case"<=":return n<=t;default:return n>=t}}const ge=new Set(["DATEADD","DATETIME_DIFF","IS_SAME"]);export const FORMULA_FUNCTIONS=Object.keys(J).sort(),selfReferenceError=e=>new FormulaError(`A formula cannot read its own field {${e.trim()}}`);export function columnResolver(e,n=[]){const t=new Set(n.filter(r=>r!=null&&String(r).trim()!=="").map(r=>String(r).trim().toLowerCase()));return r=>{const l=r.trim().toLowerCase();if(t.has(l))throw selfReferenceError(r);const s=e.find(f=>String(f.header??"").trim().toLowerCase()===l||String(f.field??"").toLowerCase()===l);return s?String(s.field??s.id):null}}class De{constructor(n,t,r){this.toks=n,this.resolve=t,this.refs=r,this.i=0}peek(){return this.toks[this.i]}next(){return this.toks[this.i++]}expect(n,t){const r=this.next();if(!r||r.k!==n||t&&r.v!==t)throw new FormulaError(`Expected "${t??n}"${r?` at ${r.at+1}`:" at the end"}`);return r}parse(){const n=this.compare();if(this.peek())throw new FormulaError(`Unexpected "${this.peek().v}" at ${this.peek().at+1}`);return n}compare(){let n=this.concat();for(let t=this.peek();t&&t.k==="op"&&["=","!=","<",">","<=",">="].includes(t.v);t=this.peek()){this.next();const r=t.v,l=n,s=this.concat();n=f=>{const i=l(f),c=s(f);if(i instanceof Date||c instanceof Date){const S=h(i),w=h(c);return!S||!w?r==="!=":ee(r,S.getTime(),w.getTime())}const m=typeof i=="number"||typeof c=="number",g=m?o(i):u(i),E=m?o(c):u(c);return ee(r,g,E)}}return n}concat(){let n=this.add();for(;this.peek()?.k==="op"&&this.peek().v==="&";){this.next();const t=n,r=this.add();n=l=>u(t(l))+u(r(l))}return n}add(){let n=this.mul();for(let t=this.peek();t&&t.k==="op"&&(t.v==="+"||t.v==="-");t=this.peek()){this.next();const r=n,l=this.mul(),s=t.v==="+";n=f=>s?o(r(f))+o(l(f)):o(r(f))-o(l(f))}return n}mul(){let n=this.unary();for(let t=this.peek();t&&t.k==="op"&&(t.v==="*"||t.v==="/");t=this.peek()){this.next();const r=n,l=this.unary(),s=t.v==="*";n=f=>{if(s)return o(r(f))*o(l(f));const i=o(l(f));return i===0?null:o(r(f))/i}}return n}unary(){const n=this.peek();if(n?.k==="op"&&n.v==="-"){this.next();const t=this.unary();return r=>-o(t(r))}return this.primary()}primary(){const n=this.next();if(!n)throw new FormulaError("The formula ends too early");if(n.k==="num"){const t=Number(n.v);return()=>t}if(n.k==="str"){const t=n.v;return()=>t}if(n.k==="ref"){const t=this.resolve(n.v);if(t==null)throw new FormulaError(`No field named "${n.v}"`);return this.refs.add(t),r=>r?.[t]??null}if(n.k==="("){const t=this.compare();return this.expect(")"),t}if(n.k==="id"){const t=n.v.toUpperCase();if(t==="TRUE"&&this.peek()?.k!=="(")return()=>!0;if(t==="FALSE"&&this.peek()?.k!=="(")return()=>!1;const r=J[t];if(!r)throw new FormulaError(`Unknown function ${n.v}`);this.expect("(");const l=[],s=[],f=()=>{const c=this.i;l.push(this.compare());const m=this.i===c+1?this.toks[c]:void 0;s.push(m?.k==="str"?m.v:void 0)};if(this.peek()?.k!==")")for(f();this.peek()?.k===",";)this.next(),f();this.expect(")");const i=s[2];if(ge.has(t)&&i!==void 0&&!x(i))throw new FormulaError(`Unknown unit "${i}" in ${t}: use ms, seconds, minutes, hours, days, weeks, months, quarters or years`);return t==="RECORD_ID"?c=>c?.id==null?null:String(c.id):t==="ISERROR"?c=>{try{const m=l[0]?.(c)??null;return m===Z||typeof m=="number"&&!Number.isFinite(m)}catch{return!0}}:t==="IF"?c=>A(l[0]?.(c)??null)?l[1]?.(c)??null:l[2]?.(c)??null:t==="SWITCH"?c=>{if(!l.length)return null;const m=u(l[0](c));for(let g=1;g+1<l.length;g+=2)if(m===u(l[g](c)))return l[g+1](c);return l.length%2===0?l[l.length-1](c):null}:c=>r(l.map(m=>m(c)))}throw new FormulaError(`Unexpected "${n.v}" at ${n.at+1}`)}}export function compileFormula(e,n){if(!e.trim())throw new FormulaError("The formula is empty");const t=new Set,r=new De(b(e),n,t).parse();return{fn:l=>{try{const s=r(l);return typeof s=="number"&&!Number.isFinite(s)?null:s}catch(s){return s instanceof FormulaError?Z:null}},refs:[...t]}}export function renameFormulaRefs(e,n){let t;try{t=b(e)}catch{return e}let r="",l=0;for(const s of t){if(s.k!=="ref")continue;const f=n(s.v);if(f==null)continue;const i=e.indexOf("}",s.at);r+=`${e.slice(l,s.at)}{${f}}`,l=i+1}return l?r+e.slice(l):e}export function formulaRefs(e,n){let t;try{t=b(e)}catch{return[]}const r=new Set;for(const l of t)if(l.k==="ref")try{const s=n(l.v);s!=null&&r.add(s)}catch{}return[...r]}export function formulaReaders(e,n){const t=new Set([n.field,n.id].filter(l=>l!=null&&l!=="").map(String));if(!t.size)return[];const r=columnResolver(e);return e.filter(l=>l.fieldType!=="formula"||t.has(String(l.field??l.id??""))?!1:formulaRefs(String(l.fieldProps?.formula??""),r).some(s=>t.has(s)))}export function formulaError(e,n){try{return compileFormula(e,n),null}catch(t){return t instanceof FormulaError?t.message:"The formula is not valid"}}
@@ -57,4 +57,12 @@ type TreeRow = {
57
57
  export declare function leafFilter(ctrl: any): ((row: unknown) => boolean) | null;
58
58
  /** The records under a group row, those the filter keeps. */
59
59
  export declare function groupLeaves<TRow extends TreeRow>(row: TRow, keep: ((row: unknown) => boolean) | null): TRow[];
60
+ /**
61
+ * Bring the row at display `index` into view, scrolling only when it is not
62
+ * already all on screen: a record added where the user is looking must not
63
+ * move the grid under them. A row the virtualizer has not drawn is off screen.
64
+ */
65
+ export declare function revealRow(ctrl: any, api: {
66
+ scrollToRow(index: number): void;
67
+ }, index: number): void;
60
68
  export {};
@@ -1 +1 @@
1
- import{getAdvancedFilterEngine as d}from"@svgrid/grid";const s=new WeakMap,u=new WeakMap;export function rememberGrid(e){const n=e?.buildApi?.();n&&!s.has(n)&&(s.set(n,e),typeof n.getData=="function"&&u.set(n.getData,e))}export function gridOf(e){if(!e||typeof e!="object")return;const n=e.getData;return s.get(e)??(typeof n=="function"?u.get(n):void 0)}export const columnIdOf=e=>String(e.id??e.field??"");export function fieldColumns(e){const n=e?.hiddenColumns??{},t=f(e?.internalColumns??[]).filter(o=>o.field!=null),r=new Map(t.map(o=>[columnIdOf(o),o])),i=(e?.allColumns??[]).map(o=>o.id).filter(o=>r.has(o)),l=t.map(columnIdOf).filter(o=>!i.includes(o));return[...i,...l].map(o=>{const a=r.get(o);return{id:o,field:String(a.field),header:typeof a.header=="string"?a.header:o,fieldType:a.fieldType,def:a,visible:!n[o]&&a.visible!==!1&&i.includes(o)}})}function f(e){return e.flatMap(n=>Array.isArray(n.columns)&&n.columns.length?f(n.columns):[n])}export function primaryIdOf(e){const n=e?.props?.primaryField;if(typeof n!="string"||!n)return null;const t=f(e?.internalColumns??[]),r=t.find(i=>columnIdOf(i)===n)??t.find(i=>i.field===n);return r?columnIdOf(r):null}export function writeCell(e,n,t,r){const i=(e?.allRows??[]).findIndex(l=>l.id===n);return i<0||!e.startEditing?.(i,t)?!1:(e.updateEditingCellValue(r),e.saveEditingCell(),!0)}export function cellValue(e,n,t){const r=n.getCellValueByColumnId?n.getCellValueByColumnId(t.id):n.original?.[t.field];return e?.getCellDisplayValue?e.getCellDisplayValue(n.id,t.id,r):r}export function cellText(e,n,t){const r=e.def.formatter;if(r)try{return String(r({value:n,row:t,column:{id:e.id,columnDef:e.def}})??"")}catch{}return Array.isArray(n)?n.map(i=>i&&typeof i=="object"?i.name??"":String(i)).join(", "):n==null?"":String(n)}export function dataRows(e){return(e?.allRows??[]).filter(n=>n.__treeRow||!(typeof n.getCanExpand=="function"&&n.getCanExpand()))}const p=e=>!e.__treeRow&&typeof e.getCanExpand=="function"&&e.getCanExpand();export function leafFilter(e){const n=e?.advancedFilter,t=n?d():null;if(!t)return null;try{return t(n,{getValue:e.getRowColumnValue,rows:[]})??null}catch{return null}}export function groupLeaves(e,n){const t=[],r=i=>{for(const l of i.subRows??[])p(l)?r(l):(!n||n(l))&&t.push(l)};return r(e),t}
1
+ import{getAdvancedFilterEngine as c}from"@svgrid/grid";const s=new WeakMap,d=new WeakMap;export function rememberGrid(e){const t=e?.buildApi?.();t&&!s.has(t)&&(s.set(t,e),typeof t.getData=="function"&&d.set(t.getData,e))}export function gridOf(e){if(!e||typeof e!="object")return;const t=e.getData;return s.get(e)??(typeof t=="function"?d.get(t):void 0)}export const columnIdOf=e=>String(e.id??e.field??"");export function fieldColumns(e){const t=e?.hiddenColumns??{},n=u(e?.internalColumns??[]).filter(r=>r.field!=null),o=new Map(n.map(r=>[columnIdOf(r),r])),i=(e?.allColumns??[]).map(r=>r.id).filter(r=>o.has(r)),l=n.map(columnIdOf).filter(r=>!i.includes(r));return[...i,...l].map(r=>{const a=o.get(r);return{id:r,field:String(a.field),header:typeof a.header=="string"?a.header:r,fieldType:a.fieldType,def:a,visible:!t[r]&&a.visible!==!1&&i.includes(r)}})}function u(e){return e.flatMap(t=>Array.isArray(t.columns)&&t.columns.length?u(t.columns):[t])}export function primaryIdOf(e){const t=e?.props?.primaryField;if(typeof t!="string"||!t)return null;const n=u(e?.internalColumns??[]),o=n.find(i=>columnIdOf(i)===t)??n.find(i=>i.field===t);return o?columnIdOf(o):null}export function writeCell(e,t,n,o){const i=(e?.allRows??[]).findIndex(l=>l.id===t);return i<0||!e.startEditing?.(i,n)?!1:(e.updateEditingCellValue(o),e.saveEditingCell(),!0)}export function cellValue(e,t,n){const o=t.getCellValueByColumnId?t.getCellValueByColumnId(n.id):t.original?.[n.field];return e?.getCellDisplayValue?e.getCellDisplayValue(t.id,n.id,o):o}export function cellText(e,t,n){const o=e.def.formatter;if(o)try{return String(o({value:t,row:n,column:{id:e.id,columnDef:e.def}})??"")}catch{}return Array.isArray(t)?t.map(i=>i&&typeof i=="object"?i.name??"":String(i)).join(", "):t==null?"":String(t)}export function dataRows(e){return(e?.allRows??[]).filter(t=>t.__treeRow||!(typeof t.getCanExpand=="function"&&t.getCanExpand()))}const p=e=>!e.__treeRow&&typeof e.getCanExpand=="function"&&e.getCanExpand();export function leafFilter(e){const t=e?.advancedFilter,n=t?c():null;if(!n)return null;try{return n(t,{getValue:e.getRowColumnValue,rows:[]})??null}catch{return null}}export function groupLeaves(e,t){const n=[],o=i=>{for(const l of i.subRows??[])p(l)?o(l):(!t||t(l))&&n.push(l)};return o(e),n}export function revealRow(e,t,n){const o=e?.scrollContainer??null,i=o?.querySelector(`[role="gridcell"][aria-rowindex="${n+1}"]`);if(o&&i){const l=o.getBoundingClientRect(),r=o.querySelector('[role="columnheader"]')?.getBoundingClientRect(),a=Math.max(l.top,r&&r.bottom>l.top?r.bottom:l.top),f=i.getBoundingClientRect();if(f.top>=a-1&&f.bottom<=l.top+o.clientHeight+1)return}t.scrollToRow(n)}
@@ -1,6 +1,7 @@
1
1
  export { registerFieldType, getFieldType, listFieldTypes, fieldPropsOf, fillFieldColumn, type FieldTypeDef, type FieldCellProps, } from './registry.svelte.js';
2
2
  export { linkHref, linkText, type LinkKind } from './links.js';
3
3
  export { setFieldUsers, getFieldUsers, setCurrentUser, getCurrentUser, registerLinkedTable, unregisterLinkedTable, getLinkedTable, listLinkedTables, type FieldUser, type LinkedTable, } from './sources.svelte.js';
4
+ export { canEditField, defaultCanEditField, fieldEditors, setCanEditField, setFieldProtection, type CanEditField, type FieldAccessField, } from './field-access.svelte.js';
4
5
  export { compileFormula, formulaError, FORMULA_FUNCTIONS, FormulaError } from './formula.js';
5
6
  export { formatNumber, formatCurrency, formatPercent, formatDuration, parseDuration, formatDate } from './format.js';
6
7
  export { BRIGHT, OPTION_COLORS } from './palette.js';
@@ -8,17 +9,23 @@ export { convertValue, countCleared } from './convert.js';
8
9
  export { openFieldEditor, closeFieldEditor, openRecord, closeRecord, type OpenRecordRequest } from './editor-request.svelte.js';
9
10
  export { default as SvBaseViewBar } from './SvBaseViewBar.svelte';
10
11
  export { default as SvBaseForm } from './SvBaseForm.svelte';
12
+ export { formPrefillLink, readFormPrefill, type FormPrefill } from './form-logic.js';
11
13
  export { default as SvBase } from './SvBase.svelte';
12
14
  export { blankTable, newRecordId, type BaseTable } from './base-tables.js';
13
15
  export { baseSource, createBaseSync, type BaseSource, type BaseSourceOptions, type BaseSyncStatus, type BaseRemoteChange, type ForeignKeyLink, type JunctionLink, } from './base-sync.js';
14
16
  export { baseFieldsFromSchema, baseTablesFromSchemas, baseSpecFromSchemas, baseTablesFromSpec, type BaseTableSpec, type BaseLinkSpec } from './base-schema.js';
15
17
  export { baseToSql, sqlName, type BaseToSqlOptions, type BaseTableComment, type BaseJunctionComment } from './base-sql.js';
16
18
  export { applyBaseComments, withInverses, type BaseComments } from './base-schema.js';
19
+ export { restoreItems, trashLabel, type BaseTrashItem } from './base-trash.js';
20
+ export { guessField, tableFromMatrix, recordsFromMatrix, matchColumns, type BaseImportResult, type ImportedField } from './base-import.js';
17
21
  export { baseFromDatabase, describeDatabase, createBaseEndpoint, baseFromEndpoint, baseFromSupabase, type DatabaseOptions, type BaseEndpointOptions, type SupabaseBaseOptions } from './base-connect.js';
22
+ export { baseFromAirtable, airtableFormulaSupport, airtableColor, formulaFunctionsUsed, type AirtableSchema, type AirtableTable, type AirtableField, type AirtableView, type AirtableRecord, type AirtableRecords, type AirtableCollaborator, type AirtableImportOptions, type AirtableImport, type AirtableReportItem, type AirtableFormulaSupport, type AirtableFormulaStatus, type AirtableFormulaGroup } from './airtable.js';
18
23
  export { registerAutomationAction, listAutomationActions, MAX_DEPTH as AUTOMATION_MAX_DEPTH, type BaseAutomation, type AutomationTrigger, type AutomationAction, type AutomationRun, type AutomationStep, type AutomationActionContext, type RegisteredAutomationAction, } from './automations.svelte.js';
19
24
  export { createAutomationServer, type AutomationServer, type AutomationServerOptions, type AutomationNotice } from './automation-server.js';
20
25
  export type { WebhookAction, EmailAction, OutgoingEmail } from './automation-outbound.js';
21
26
  export { setRecordComments, type RecordComment, type RecordCommentContext, type RecordCommentStore } from './activity.svelte.js';
27
+ export { setMentionHandler, type MentionEvent, type MentionHandler } from './activity.svelte.js';
28
+ export { mentionToken, mentionIds, mentionText, parseMentions, encodeMentions, type MentionPart } from './mentions.js';
22
29
  export { baseCondition, baseFilterOf } from './base-alerts.js';
23
30
  export { compileFieldFilter, describeFieldFilter, filterKindOf, operatorsFor, ME, type FieldFilter, type FieldCondition, type FieldConditionGroup, type FilterKind, type FilterOp, } from './filter-model.js';
24
31
  export type { FieldView, FieldViewType, ColorSetting } from './view-model.js';
@@ -50,3 +57,12 @@ export declare function baseReviewApplied(api: unknown): (applied: ReadonlyArray
50
57
  * grid shows the Enterprise watermark and the feature still runs.
51
58
  */
52
59
  export declare function enableFields(): void;
60
+ export { inboxRecords, listColumns, listGroups, viewRecords, type ListGroup } from './list-view.js';
61
+ export { generateAIField, regenerateAIFields, cancelAIField, pendingAIField, setAIFieldConcurrency, type AIFieldRun, type AIFieldCellState, type AIFieldChange } from './ai-field.svelte.js';
62
+ export { aiPromptError, readAIAnswer, type AIFieldProps, type AIFieldOutput } from './ai-prompt.js';
63
+ export { moveTile, newTile, putTile, removeTile, tileResult, tileRows, tileTitle, type DashboardTile, type DashboardTileKind, type DashboardTileSize, type NumberAggregation, type TileResult, } from './dashboard.js';
64
+ export { sharedTables, sharedViews, shareOf, type BaseShare } from './base-share.js';
65
+ export { searchBase, type BaseSearchGroup, type BaseSearchHit, type BaseSearchOptions } from './base-search.js';
66
+ export { toChecklist, parseChecklist, checklistText, checklistProgress, type ChecklistItem } from './checklist.js';
67
+ export { parseColor } from './color-value.js';
68
+ export { parseTimeOfDay, formatTimeOfDay, timeSeconds, type TimeOfDayProps } from './time-of-day.js';