@svgrid/enterprise 3.1.34 → 3.1.36

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 (250) hide show
  1. package/dist/ExpressionEditorHarness.svelte +1 -1
  2. package/dist/SvAdvancedFilter.svelte +1 -1
  3. package/dist/SvAlertRuleEditor.svelte +1 -1
  4. package/dist/SvAlertsManager.svelte +1 -1
  5. package/dist/SvAlertsPanel.svelte +1 -1
  6. package/dist/SvExpressionEditor.svelte +1 -1
  7. package/dist/SvGridBoard.svelte +1 -1
  8. package/dist/SvGridBulkEditDrawer.svelte +1 -1
  9. package/dist/SvGridEditPanel.svelte +1 -1
  10. package/dist/SvGridGallery.svelte +1 -1
  11. package/dist/SvGridMasterDetail.svelte +1 -1
  12. package/dist/SvGridScheduler.svelte +1 -1
  13. package/dist/SvGridSelectionBar.svelte +1 -1
  14. package/dist/SvPivotDesigner.svelte +1 -1
  15. package/dist/SvSchemaChart.svelte +1 -1
  16. package/dist/SvSchemaDashboard.svelte +1 -1
  17. package/dist/SvSheet.svelte +1 -1
  18. package/dist/SvSheetChartSetup.svelte +1 -1
  19. package/dist/SvSheetConditionalFormat.svelte +1 -1
  20. package/dist/SvSheetDataValidation.svelte +1 -1
  21. package/dist/SvSheetEditRanges.svelte +1 -1
  22. package/dist/SvSheetErrors.svelte +1 -1
  23. package/dist/SvSheetEvaluate.svelte +1 -1
  24. package/dist/SvSheetFindReplace.svelte +1 -1
  25. package/dist/SvSheetFormatCells.svelte +1 -1
  26. package/dist/SvSheetGoalSeek.svelte +1 -1
  27. package/dist/SvSheetInsertFunction.svelte +1 -1
  28. package/dist/SvSheetIteration.svelte +1 -1
  29. package/dist/SvSheetLink.svelte +1 -1
  30. package/dist/SvSheetManageRules.svelte +1 -1
  31. package/dist/SvSheetNameManager.svelte +1 -1
  32. package/dist/SvSheetPageSetup.svelte +1 -1
  33. package/dist/SvSheetPasteSpecial.svelte +1 -1
  34. package/dist/SvSheetPivot.svelte +1 -1
  35. package/dist/SvSheetProtectSheet.svelte +1 -1
  36. package/dist/SvSheetRemoveDuplicates.svelte +1 -1
  37. package/dist/SvSheetRibbon.svelte +1 -1
  38. package/dist/SvSheetSizeDialog.svelte +1 -1
  39. package/dist/SvSheetSort.svelte +1 -1
  40. package/dist/SvSheetSparklines.svelte +1 -1
  41. package/dist/SvSheetTable.svelte +1 -1
  42. package/dist/SvSheetTabs.svelte +1 -1
  43. package/dist/SvSheetTextToColumns.svelte +1 -1
  44. package/dist/SvSheetValidationAlert.svelte +1 -1
  45. package/dist/cdn/svgrid-enterprise.svelte-external.js +2 -2
  46. package/dist/designer/assets/{index-v61ZvIWw.js → index-CsdyIRos.js} +3 -3
  47. package/dist/designer/assets/{src-DkFgWld_.js → src-CSmsOfsG.js} +15 -15
  48. package/dist/designer/index.html +2 -2
  49. package/dist/fields/AiCell.svelte +41 -0
  50. package/dist/fields/AiCell.svelte.d.ts +5 -0
  51. package/dist/fields/AttachmentCell.svelte +1 -1
  52. package/dist/fields/AttachmentDialog.svelte +1 -1
  53. package/dist/fields/AttachmentEditor.svelte +1 -1
  54. package/dist/fields/AttachmentPreview.svelte +1 -1
  55. package/dist/fields/BaseAutomations.svelte +1 -1
  56. package/dist/fields/BaseChartView.svelte +1 -1
  57. package/dist/fields/BaseDashboardView.svelte +133 -0
  58. package/dist/fields/BaseDashboardView.svelte.d.ts +17 -0
  59. package/dist/fields/BaseImport.svelte +89 -0
  60. package/dist/fields/BaseImport.svelte.d.ts +15 -0
  61. package/dist/fields/BaseInboxView.svelte +112 -0
  62. package/dist/fields/BaseInboxView.svelte.d.ts +8 -0
  63. package/dist/fields/BaseListView.svelte +90 -0
  64. package/dist/fields/BaseListView.svelte.d.ts +8 -0
  65. package/dist/fields/BaseSearch.svelte +78 -0
  66. package/dist/fields/BaseSearch.svelte.d.ts +10 -0
  67. package/dist/fields/BaseTableView.svelte +28 -3
  68. package/dist/fields/BaseTableView.svelte.d.ts +5 -1
  69. package/dist/fields/BaseTabs.svelte +45 -8
  70. package/dist/fields/BaseTabs.svelte.d.ts +25 -1
  71. package/dist/fields/BaseTrash.svelte +63 -0
  72. package/dist/fields/BaseTrash.svelte.d.ts +15 -0
  73. package/dist/fields/CheckboxCell.svelte +1 -1
  74. package/dist/fields/ChecklistCell.svelte +22 -0
  75. package/dist/fields/ChecklistCell.svelte.d.ts +10 -0
  76. package/dist/fields/ChecklistEditor.svelte +81 -0
  77. package/dist/fields/ChecklistEditor.svelte.d.ts +12 -0
  78. package/dist/fields/ColorCell.svelte +13 -0
  79. package/dist/fields/ColorCell.svelte.d.ts +8 -0
  80. package/dist/fields/ColorEditor.svelte +60 -0
  81. package/dist/fields/ColorEditor.svelte.d.ts +11 -0
  82. package/dist/fields/DashboardRecords.svelte +35 -0
  83. package/dist/fields/DashboardRecords.svelte.d.ts +11 -0
  84. package/dist/fields/DashboardTileEditor.svelte +138 -0
  85. package/dist/fields/DashboardTileEditor.svelte.d.ts +15 -0
  86. package/dist/fields/DeleteFieldConfirm.svelte +1 -1
  87. package/dist/fields/DeleteRecordConfirm.svelte +1 -1
  88. package/dist/fields/FieldEditor.svelte +32 -3
  89. package/dist/fields/FieldInput.svelte +1 -1
  90. package/dist/fields/FieldsHeaderEnd.svelte +1 -1
  91. package/dist/fields/FootRowAdder.svelte +1 -1
  92. package/dist/fields/GroupHeader.svelte +3 -3
  93. package/dist/fields/LinkPickerEditor.svelte +1 -1
  94. package/dist/fields/LinkPreview.svelte +1 -1
  95. package/dist/fields/LinkedRecordView.svelte +1 -1
  96. package/dist/fields/LinkedRecordsCell.svelte +1 -1
  97. package/dist/fields/ListChips.svelte +21 -0
  98. package/dist/fields/ListChips.svelte.d.ts +9 -0
  99. package/dist/fields/LongTextEditor.svelte +1 -1
  100. package/dist/fields/MentionInput.svelte +59 -0
  101. package/dist/fields/MentionInput.svelte.d.ts +11 -0
  102. package/dist/fields/NumberEditor.svelte +1 -1
  103. package/dist/fields/OptionsEditor.svelte +1 -1
  104. package/dist/fields/PercentCell.svelte +1 -1
  105. package/dist/fields/PropertyInput.svelte +13 -10
  106. package/dist/fields/RatingCell.svelte +1 -1
  107. package/dist/fields/RatingEditor.svelte +1 -1
  108. package/dist/fields/RecordView.svelte +20 -25
  109. package/dist/fields/RowHeader.svelte +1 -1
  110. package/dist/fields/SelectCell.svelte +1 -1
  111. package/dist/fields/SelectEditor.svelte +1 -1
  112. package/dist/fields/SummaryCell.svelte +1 -1
  113. package/dist/fields/SvBase.svelte +48 -9
  114. package/dist/fields/SvBase.svelte.d.ts +33 -1
  115. package/dist/fields/SvBaseForm.svelte +2 -2
  116. package/dist/fields/SvBaseForm.svelte.d.ts +14 -0
  117. package/dist/fields/SvBaseViewBar.svelte +33 -12
  118. package/dist/fields/SvBaseViewBar.svelte.d.ts +2 -0
  119. package/dist/fields/TimeOfDayEditor.svelte +39 -0
  120. package/dist/fields/TimeOfDayEditor.svelte.d.ts +12 -0
  121. package/dist/fields/UserCell.svelte +1 -1
  122. package/dist/fields/activity.svelte.d.ts +29 -0
  123. package/dist/fields/activity.svelte.js +1 -1
  124. package/dist/fields/ai-field.svelte.d.ts +91 -0
  125. package/dist/fields/ai-field.svelte.js +1 -0
  126. package/dist/fields/ai-prompt.d.ts +64 -0
  127. package/dist/fields/ai-prompt.js +7 -0
  128. package/dist/fields/airtable.d.ts +90 -0
  129. package/dist/fields/airtable.js +1 -0
  130. package/dist/fields/bar-request.svelte.d.ts +1 -1
  131. package/dist/fields/base-history.d.ts +56 -0
  132. package/dist/fields/base-history.js +1 -0
  133. package/dist/fields/base-import.d.ts +54 -0
  134. package/dist/fields/base-import.js +2 -0
  135. package/dist/fields/base-search.d.ts +34 -0
  136. package/dist/fields/base-search.js +1 -0
  137. package/dist/fields/base-share.d.ts +45 -0
  138. package/dist/fields/base-share.js +1 -0
  139. package/dist/fields/base-sql.js +3 -3
  140. package/dist/fields/base-trash.d.ts +51 -0
  141. package/dist/fields/base-trash.js +1 -0
  142. package/dist/fields/builtin-types.js +1 -1
  143. package/dist/fields/chart-view.d.ts +12 -0
  144. package/dist/fields/chart-view.js +1 -1
  145. package/dist/fields/checklist.d.ts +36 -0
  146. package/dist/fields/checklist.js +4 -0
  147. package/dist/fields/color-value.d.ts +14 -0
  148. package/dist/fields/color-value.js +1 -0
  149. package/dist/fields/convert.js +1 -1
  150. package/dist/fields/copy-text.d.ts +1 -1
  151. package/dist/fields/copy-text.js +1 -1
  152. package/dist/fields/dashboard.d.ts +143 -0
  153. package/dist/fields/dashboard.js +1 -0
  154. package/dist/fields/field-access.svelte.d.ts +37 -0
  155. package/dist/fields/field-access.svelte.js +1 -0
  156. package/dist/fields/field-ops.js +1 -1
  157. package/dist/fields/filter-model.d.ts +4 -11
  158. package/dist/fields/filter-model.js +1 -1
  159. package/dist/fields/form-logic.d.ts +69 -0
  160. package/dist/fields/form-logic.js +1 -0
  161. package/dist/fields/formula.js +1 -1
  162. package/dist/fields/grid-access.d.ts +8 -0
  163. package/dist/fields/grid-access.js +1 -1
  164. package/dist/fields/index.d.ts +16 -0
  165. package/dist/fields/index.js +1 -1
  166. package/dist/fields/list-view.d.ts +40 -0
  167. package/dist/fields/list-view.js +1 -0
  168. package/dist/fields/mentions.d.ts +50 -0
  169. package/dist/fields/mentions.js +1 -0
  170. package/dist/fields/palette.d.ts +4 -2
  171. package/dist/fields/palette.js +1 -1
  172. package/dist/fields/record-menu.js +1 -1
  173. package/dist/fields/registry.svelte.d.ts +5 -0
  174. package/dist/fields/registry.svelte.js +1 -1
  175. package/dist/fields/time-of-day.d.ts +28 -0
  176. package/dist/fields/time-of-day.js +1 -0
  177. package/dist/fields/view-model.d.ts +24 -2
  178. package/dist/fields/view-model.js +1 -1
  179. package/dist/fields/viewbar/ChartPanel.svelte +1 -1
  180. package/dist/fields/viewbar/ColorPanel.svelte +1 -1
  181. package/dist/fields/viewbar/ConditionValue.svelte +4 -4
  182. package/dist/fields/viewbar/FilterPanel.svelte +1 -1
  183. package/dist/fields/viewbar/GanttPanel.svelte +1 -1
  184. package/dist/fields/viewbar/HideFieldsPanel.svelte +1 -1
  185. package/dist/fields/viewbar/ListPanel.svelte +36 -0
  186. package/dist/fields/viewbar/ListPanel.svelte.d.ts +11 -0
  187. package/dist/fields/viewbar/SortPanel.svelte +1 -1
  188. package/dist/fields/viewbar/ViewsMenu.svelte +27 -4
  189. package/dist/fields/viewbar/ViewsMenu.svelte.d.ts +6 -0
  190. package/dist/gantt/SvGridGantt.svelte +1 -1
  191. package/dist/node/studio.js +1 -1
  192. package/dist/review/RichCellMark.svelte +1 -1
  193. package/dist/review/SvReviewPanel.svelte +1 -1
  194. package/dist/server/SvGroupCell.svelte +1 -1
  195. package/dist/server/SvRowGroupPanel.svelte +1 -1
  196. package/dist/version.d.ts +2 -2
  197. package/dist/version.js +1 -1
  198. package/dist/wc/GridFind-DsTvdUXq.js +1 -0
  199. package/dist/wc/GridFooter-D-i8boBh.js +1 -0
  200. package/dist/wc/GridMenus-CYe9Fw2I.js +20 -0
  201. package/dist/wc/PinSplitter-LvyyrLhe.js +6 -0
  202. package/dist/wc/SvChartMenu-XKW_LOYw.js +1 -0
  203. package/dist/wc/SvDateRangeInput-CSOxqTB1.js +1 -0
  204. package/dist/wc/SvDateTimePicker-DvvFs2T9.js +4 -0
  205. package/dist/wc/SvField-BmQphyOs.js +20 -0
  206. package/dist/wc/SvForm-HD7y5vmk.js +46 -0
  207. package/dist/wc/SvGridCellEditor-776KAOe1.js +3 -0
  208. package/dist/wc/SvGridChart-DC7ZUhp8.js +171 -0
  209. package/dist/wc/SvGridChartBuilder-Dd3vWBvq.js +7 -0
  210. package/dist/wc/SvGridChartPanel-CwYjF46U.js +5 -0
  211. package/dist/wc/SvGridChartView-CSF38rBs.js +3 -0
  212. package/dist/wc/SvGridDropdown-4S1G7gsP.js +30 -0
  213. package/dist/wc/SvMenuList-D3ZLXjL_.js +1 -0
  214. package/dist/wc/SvModal-Dk0YwPWp.js +7 -0
  215. package/dist/wc/SvSwitchButton-DdZmc3ew.js +1 -0
  216. package/dist/wc/SvTabs-BI2cQHyw.js +2 -0
  217. package/dist/wc/base-react.d.ts +38 -0
  218. package/dist/wc/base-react.js +1 -0
  219. package/dist/wc/base-vue.d.ts +29 -0
  220. package/dist/wc/base-vue.js +1 -0
  221. package/dist/wc/board-RQp5fHPR.js +21 -0
  222. package/dist/wc/board-view.svelte-CpxuZcEg.js +1 -0
  223. package/dist/wc/card-marks.svelte-QwxIcKcZ.js +1 -0
  224. package/dist/wc/client-DNdLmGcu.js +3 -0
  225. package/dist/wc/createOverlay.svelte-CDw3RXgs.js +1 -0
  226. package/dist/wc/custom-filter-Dp8JxlQu.js +2 -0
  227. package/dist/wc/date-format-DtSmFyEB.js +18 -0
  228. package/dist/wc/editor-registry-CkKfcVLc.js +1 -0
  229. package/dist/wc/export-format-CGfE9_O5.js +5 -0
  230. package/dist/wc/gallery-CNOHNWEJ.js +4 -0
  231. package/dist/wc/gallery-view.svelte-27X-wCQH.js +1 -0
  232. package/dist/wc/grid-extension.svelte-hgqOteka.js +1 -0
  233. package/dist/wc/import-B9mIERCl.js +4 -0
  234. package/dist/wc/js-scroller.svelte-BP8Up6_q.js +1 -0
  235. package/dist/wc/license-CWVWqb-i.js +27 -0
  236. package/dist/wc/list-option-CI4nMshZ.js +1 -0
  237. package/dist/wc/react.d.ts +1 -0
  238. package/dist/wc/react.js +1 -1
  239. package/dist/wc/scheduler-CkVY4od-.js +147 -0
  240. package/dist/wc/scheduler-view.svelte-SzG7rU8b.js +1 -0
  241. package/dist/wc/sparkline-DWRBQubt.js +1 -0
  242. package/dist/wc/sv-base-element.d.ts +87 -0
  243. package/dist/wc/sv-base-element.js +273 -0
  244. package/dist/wc/sv-sheet-element.d.ts +2 -0
  245. package/dist/wc/sv-sheet-element.js +55 -55
  246. package/dist/wc/svelte-virtualizer.svelte-CSBwEZt9.js +1 -0
  247. package/dist/wc/types/sv-base-element.d.ts +87 -0
  248. package/dist/wc/vue.d.ts +1 -0
  249. package/dist/wc/vue.js +1 -1
  250. package/package.json +19 -4
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The prompt of an AI field, without the grid: `{Field name}` references,
3
+ * the message the field editor shows for a wrong one, the request a model
4
+ * gets for one record, and its answer read back as the value the field
5
+ * stores. Plain functions, so importers and unit tests use them without
6
+ * Svelte.
7
+ */
8
+ import type { AIRequest } from '@svgrid/grid';
9
+ /** What an AI field writes: text, one of its options, or a number. */
10
+ export type AIFieldOutput = 'text' | 'singleSelect' | 'number';
11
+ /** An AI field's properties (`fieldProps` of a column with `fieldType: 'ai'`). */
12
+ export type AIFieldProps = {
13
+ /** The instruction for the model, with `{Field name}` for the record's values. */
14
+ prompt?: string;
15
+ /** What the field stores. Default 'text'. */
16
+ output?: AIFieldOutput;
17
+ /** Generate again when a field the prompt names changes. Default true. */
18
+ auto?: boolean;
19
+ /** The options a 'singleSelect' field picks from. */
20
+ options?: ReadonlyArray<{
21
+ value: string | number;
22
+ label?: string;
23
+ color?: string;
24
+ }>;
25
+ /** Decimal places a 'number' field shows. */
26
+ precision?: number | string;
27
+ };
28
+ type Part = {
29
+ text: string;
30
+ } | {
31
+ ref: string;
32
+ at: number;
33
+ };
34
+ /** The prompt cut into text and `{name}` references. Throws on a `{` that is not closed or an empty `{}`. */
35
+ export declare function promptParts(src: string): Part[];
36
+ type Col = Record<string, unknown>;
37
+ /** The column a `{name}` names: by header, then by field key, ignoring case. */
38
+ export declare function promptColumn<C extends Col>(columns: ReadonlyArray<C>, name: string): C | undefined;
39
+ /**
40
+ * The prompt's message for the field editor, or null when it is fine. An
41
+ * empty prompt is fine (the cells stay empty). `self` lists the field's own
42
+ * names, which the prompt may not read.
43
+ */
44
+ export declare function aiPromptError(src: string, columns: ReadonlyArray<Col>, self?: ReadonlyArray<unknown>): string | null;
45
+ /** The columns the prompt names, each once, in the order it names them. A name no column has is left out. */
46
+ export declare function promptRefs<C extends Col>(src: string, columns: ReadonlyArray<C>): C[];
47
+ /** The prompt with each `{name}` replaced by `read(name)`. */
48
+ export declare function fillPrompt(src: string, read: (name: string) => string): string;
49
+ /** The prompt with each `{name}` that `rename` gives a new name for written as `{new name}`. */
50
+ export declare function renamePromptRefs(src: string, rename: (name: string) => string | null): string;
51
+ /**
52
+ * The request for one record: the filled-in prompt, what to answer with, and
53
+ * strict JSON (`{"value": ...}`) so a model's extra words do not end up in
54
+ * the cell. A select field asks the model to classify, the others to write.
55
+ */
56
+ export declare function aiFieldRequest(field: string, filled: string, p: AIFieldProps, signal?: AbortSignal): AIRequest;
57
+ /**
58
+ * A model's answer as the value the field stores. Reads `{"value": ...}`
59
+ * (or `text`, or a classifier's first prediction), with or without a code
60
+ * fence, else the answer as it is. Throws when a select's answer is not one
61
+ * of its options or a number field's is not a number.
62
+ */
63
+ export declare function readAIAnswer(raw: unknown, p: AIFieldProps): string | number | null;
64
+ export {};
@@ -0,0 +1,7 @@
1
+ export function promptParts(n){const o=[];let e=0;for(let r=0;r<n.length;r++){if(n[r]!=="{")continue;const i=n.indexOf("}",r);if(i<0)throw new Error(`The { at ${r+1} is not closed`);const t=n.slice(r+1,i).trim();if(!t)throw new Error(`Empty {} at ${r+1}: put a field name in it`);r>e&&o.push({text:n.slice(e,r)}),o.push({ref:t,at:r}),r=i,e=i+1}return e<n.length&&o.push({text:n.slice(e)}),o}const u=n=>String(n??"").trim().toLowerCase();export function promptColumn(n,o){const e=u(o);return n.find(r=>typeof r.header=="string"&&u(r.header)===e)??n.find(r=>r.field!=null&&u(r.field)===e)}export function aiPromptError(n,o,e=[]){if(!n.trim())return null;const r=new Set(e.filter(t=>t!=null&&String(t).trim()!=="").map(u));let i;try{i=promptParts(n)}catch(t){return t instanceof Error?t.message:"The prompt is not valid"}for(const t of i)if("ref"in t){if(r.has(u(t.ref)))return`A prompt cannot read its own field {${t.ref}}`;if(!promptColumn(o,t.ref))return`No field is named {${t.ref}}`}return null}export function promptRefs(n,o){let e;try{e=promptParts(n)}catch{return[]}const r=[];for(const i of e){if(!("ref"in i))continue;const t=promptColumn(o,i.ref);t&&!r.includes(t)&&r.push(t)}return r}export function fillPrompt(n,o){return promptParts(n).map(e=>"ref"in e?o(e.ref):e.text).join("")}export function renamePromptRefs(n,o){let e;try{e=promptParts(n)}catch{return n}let r=!1;const i=e.map(t=>{if(!("ref"in t))return t.text;const l=o(t.ref);return l==null?n.slice(t.at,n.indexOf("}",t.at)+1):(r=!0,`{${l}}`)});return r?i.join(""):n}const f=n=>(n.options??[]).map(o=>({value:o.value,label:o.label??String(o.value)}));export function aiFieldRequest(n,o,e,r){const i=e.output??"text",t=i==="singleSelect"?`Pick exactly one of these options: ${f(e).map(l=>JSON.stringify(l.label)).join(", ")}.
2
+ Reply with JSON only: {"value": "<the option>"}`:i==="number"?'Reply with JSON only: {"value": <a number>}':'Reply with JSON only: {"value": "<the text>"}. No preamble, no quotes around the text inside it.';return{prompt:`You fill in the field "${n}" of one record in a table.
3
+
4
+ Instruction:
5
+ ${o}
6
+
7
+ ${t}`,responseFormat:"json",task:i==="singleSelect"?"classify":"summarize",maxOutputTokens:i==="text"?400:30,signal:r}}export function readAIAnswer(n,o){let e=n;if(typeof n=="string"){const t=n.trim().replace(/^```(?:json)?\s*|\s*```$/g,"");try{e=JSON.parse(t)}catch{e=t}}if(e&&typeof e=="object"&&!Array.isArray(e)){const t=e,l=Array.isArray(t.predictions)?t.predictions[0]?.value:void 0;e=t.value??t.text??t.label??l??null}if(e==null)return null;const r=o.output??"text";if(r==="number"){if(typeof e=="number")return Number.isFinite(e)?e:null;const t=/-?\d[\d,]*(?:\.\d+)?|-?\.\d+/.exec(String(e));if(!t)throw new Error(`The model answered "${a(e)}", which is not a number`);return Number(t[0].replace(/,/g,""))}const i=String(e).trim();if(r==="singleSelect"){if(!i)return null;const t=u(i.replace(/^["']|["'.]$/g,"")),l=f(o).find(s=>u(s.value)===t||u(s.label)===t);if(!l)throw new Error(`The model answered "${a(i)}", which is not one of the options`);return typeof l.value=="number"?l.value:String(l.value)}return i||null}const a=n=>{const o=String(n);return o.length>60?`${o.slice(0,60)}...`:o};
@@ -0,0 +1,90 @@
1
+ import type { BaseTable } from './base-tables.js';
2
+ import type { FieldUser } from './sources.svelte.js';
3
+ export type AirtableField = {
4
+ id: string;
5
+ name: string;
6
+ type: string;
7
+ description?: string;
8
+ options?: Record<string, any>;
9
+ };
10
+ export type AirtableView = {
11
+ id: string;
12
+ name: string;
13
+ type: string;
14
+ };
15
+ export type AirtableTable = {
16
+ id: string;
17
+ name: string;
18
+ primaryFieldId?: string;
19
+ description?: string;
20
+ fields: AirtableField[];
21
+ views?: AirtableView[];
22
+ };
23
+ /** GET /v0/meta/bases/{baseId}/tables. */
24
+ export type AirtableSchema = {
25
+ tables: AirtableTable[];
26
+ };
27
+ /** A record: its cell values keyed by field name (or by field id, with `returnFieldsByFieldId`). */
28
+ export type AirtableRecord = {
29
+ id: string;
30
+ createdTime?: string;
31
+ fields: Record<string, unknown>;
32
+ };
33
+ /** A collaborator in a user, created by or last modified by cell. */
34
+ export type AirtableCollaborator = {
35
+ id: string;
36
+ email?: string;
37
+ name?: string;
38
+ };
39
+ /** Records per table, keyed by table id or name: a records response (`{ records }`) or the records themselves. */
40
+ export type AirtableRecords = Record<string, {
41
+ records: AirtableRecord[];
42
+ } | AirtableRecord[]>;
43
+ export type AirtableImportOptions = {
44
+ /** The tables to bring in, by id or name, in tab order. Default: every table. */
45
+ tables?: string[];
46
+ /** The user id a collaborator becomes. Default: the Airtable user id (`usrXXX`). */
47
+ userId?: (collaborator: AirtableCollaborator) => string;
48
+ };
49
+ /** One thing the import could not carry over as it was. */
50
+ export type AirtableReportItem = {
51
+ kind: 'field' | 'formula' | 'view' | 'link' | 'setting';
52
+ /** The Airtable table's name. */
53
+ table: string;
54
+ /** The Airtable field's or view's name. */
55
+ name: string;
56
+ message: string;
57
+ };
58
+ export type AirtableImport = {
59
+ /** For `<SvBase bind:tables>`. */
60
+ tables: BaseTable[];
61
+ /** The collaborators the records name, for `setFieldUsers`. */
62
+ users: FieldUser[];
63
+ report: AirtableReportItem[];
64
+ };
65
+ /** An Airtable color name ('blueLight2', 'greenBright') as the Base option color with the same hue and strength. */
66
+ export declare function airtableColor(name: unknown): string | undefined;
67
+ /** The functions a formula calls, upper-cased, outside text and references. */
68
+ export declare function formulaFunctionsUsed(src: string): string[];
69
+ /**
70
+ * Tables for `<SvBase bind:tables>` from an Airtable base's schema and,
71
+ * optionally, its records. Table, record and view ids stay Airtable's, so a
72
+ * link's record ids still point at the right records; each field gets a row
73
+ * key made from its name ('Due date' -> 'due_date').
74
+ */
75
+ export declare function baseFromAirtable(schema: AirtableSchema, records?: AirtableRecords, options?: AirtableImportOptions): AirtableImport;
76
+ export type AirtableFormulaGroup = 'Text' | 'Logical' | 'Numeric' | 'Date' | 'Array' | 'Record';
77
+ export type AirtableFormulaStatus = 'supported' | 'different' | 'unsupported';
78
+ export type AirtableFormulaSupport = {
79
+ name: string;
80
+ group: AirtableFormulaGroup;
81
+ status: AirtableFormulaStatus;
82
+ note: string;
83
+ };
84
+ /**
85
+ * Every function of Airtable's formula reference, with whether a Base
86
+ * formula has it: `supported`, `different` (it has it; `note` says how it
87
+ * differs) or `unsupported` (`note` says why). Read from FORMULA_FUNCTIONS,
88
+ * so it follows the formula language as it changes.
89
+ */
90
+ export declare function airtableFormulaSupport(): AirtableFormulaSupport[];
@@ -0,0 +1 @@
1
+ import{FORMULA_FUNCTIONS as _,columnResolver as j,formulaError as W}from"./formula.js";import{aiPromptError as G}from"./ai-prompt.js";import{OPTION_COLORS as H}from"./palette.js";const z=["blue","cyan","teal","green","yellow","orange","red","pink","purple","gray"],K={Light2:0,Light1:1,Bright:2,Dark1:3};export function airtableColor(t){const i=/^(blue|cyan|teal|green|yellow|orange|red|pink|purple|gray)(Light2|Light1|Bright|Dark1)?$/.exec(String(t??""));if(i)return H[K[i[2]??"Bright"]*10+z.indexOf(i[1])]?.value}const X=new Set(["local","friendly","us","european","iso"]),V=new Set(["h:mm","h:mm:ss","h:mm:ss.S","h:mm:ss.SS","h:mm:ss.SSS"]),U=new Set(["check","star","heart","thumbsUp","flag","dot"]),J={grid:"grid",kanban:"kanban",calendar:"calendar",gallery:"gallery",form:"form",timeline:"gantt",gantt:"gantt"},v=new Set(["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL","ARRAYJOIN","ARRAYUNIQUE","CONCATENATE","AND","OR"]),$=new Set(["number","currency","percent","duration","rating"]),Z=new Set(["formula","rollup","multipleLookupValues","count","button"]);function w(t,i){const e={time:i},l=t?.dateFormat?.name;return X.has(l)&&(e.dateFormat=l),i&&((t?.timeFormat?.name==="24hour"||t?.timeFormat?.name==="12hour")&&(e.timeFormat=t.timeFormat.name),t?.timeZone==="utc"&&(e.gmt=!0)),e}function Q(t,i){const e=t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"field";let l=e;for(let a=2;i.has(l);a++)l=`${e}_${a}`;return i.add(l),l}function B(t,i,e){let l="",a=0,T=0;const I=n=>{l+=i(t.slice(T,n))};for(;a<t.length;){const n=t[a];if(n==='"'||n==="'"){I(a);let r=a+1;for(;r<t.length&&t[r]!==n;)r+=t[r]==="\\"?2:1;l+=t.slice(a,r+1),a=T=r+1}else if(n==="{"){I(a);const r=t.indexOf("}",a);if(r<0){T=a;break}l+=`{${e(t.slice(a+1,r))}}`,a=T=r+1}else a++}return l+i(t.slice(T))}function q(t){let i="",e=0;for(;e<t.length;){const l=t[e];if(l!=='"'&&l!=="'"){i+=l,e++;continue}let a=e+1;for(;a<t.length&&t[a]!==l;)a+=t[a]==="\\"?2:1;i+=l+" ".repeat(Math.max(0,Math.min(a,t.length)-e-1))+(a<t.length?l:""),e=a+1}return i}function ee(t){const i=[...t.fields],e=[],l=n=>{const r=n.trim();return i.find(o=>o.id===r)?.id??i.find(o=>o.name===r)?.id},a=n=>{let r=n;for(let o=2;i.some(f=>f.name===r);o++)r=`${n} ${o}`;return r},T=(n,r)=>Array.isArray(n)&&n.length===r.length&&r.every(o=>n.includes(o)),I=(n,r)=>{const o=n===null?i.find(c=>c.type==="createdTime"):i.find(c=>c.type==="lastModifiedTime"&&(n.length?T(c.options?.referencedFieldIds,n):!c.options?.referencedFieldIds?.length));if(o)return o.id;const f=n===null?"Created":n.length?`${n.map(c=>i.find(s=>s.id===c).name).join(" and ")} modified`:"Last modified",h={id:n===null?"fldSvCreated":`fldSvModified${n.join("")}`,name:a(f),type:n===null?"createdTime":"lastModifiedTime",options:{...n?.length?{referencedFieldIds:n}:{},result:{type:"dateTime"}}};return i.push(h),e.push({field:h,usedBy:r}),h.id};for(const[n,r]of i.entries()){if(r.type!=="formula"||typeof r.options?.formula!="string")continue;const o=r.options.formula,f=q(o),h=[];for(const s of f.matchAll(/\bCREATED_TIME\s*\(\s*\)/gi))h.push([s.index,s.index+s[0].length,`{${I(null,r.name)}}`]);for(const s of f.matchAll(/\bLAST_MODIFIED_TIME\s*\(\s*((?:\{[^}]*\}\s*,?\s*)*)\)/gi)){const y=[...s[1].matchAll(/\{([^}]*)\}/g)].map(g=>l(g[1]));y.some(g=>!g)||h.push([s.index,s.index+s[0].length,`{${I(y,r.name)}}`])}if(!h.length)continue;let c=o;for(const[s,y,g]of h.sort((N,C)=>C[0]-N[0]))c=c.slice(0,s)+g+c.slice(y);i[n]={...r,options:{...r.options,formula:c}}}return{table:e.length||i.some((n,r)=>n!==t.fields[r])?{...t,fields:i}:t,added:e}}export function formulaFunctionsUsed(t){const i=new Set;return B(t,e=>{for(const l of e.matchAll(/([A-Za-z_][A-Za-z0-9_]*)\s*\(/g))i.add(l[1].toUpperCase());return e},e=>e),[...i]}function te(t,i){return B(t,e=>e,e=>i.get(e.trim())??e)}function ie(t,i){const e=t.options??{},l=i.keys.get(i.table.id),a=(n,r)=>i.report.push({kind:n,table:i.table.name,name:t.name,message:r}),T=n=>{const r=l.get(String(n));return r||a("link","The link field it reads is not in the table."),r},I=(n,r)=>{const o=i.table.fields.find(f=>f.id===n);return i.keys.get(String(o?.options?.linkedTableId))?.get(String(r))};switch(t.type){case"singleLineText":return{fieldType:"text"};case"multilineText":return{fieldType:"longText"};case"richText":return{fieldType:"longText",fieldProps:{richText:!0}};case"email":return{fieldType:"email"};case"url":return{fieldType:"url"};case"phoneNumber":return{fieldType:"phone"};case"number":{const n=Number(e.precision??0);return{fieldType:"number",fieldProps:n>0?{format:"decimal",precision:n}:{format:"integer",precision:0}}}case"currency":return{fieldType:"number",fieldProps:{format:"currency",precision:Number(e.precision??2),symbol:e.symbol??"$"}};case"percent":return{fieldType:"number",fieldProps:{format:"percent",precision:Number(e.precision??0)}};case"rating":{const n=airtableColor(e.color);return{fieldType:"rating",fieldProps:{max:Number(e.max??5),...U.has(e.icon)&&e.icon!=="check"?{icon:e.icon}:{},...n?{color:n}:{}}}}case"duration":return{fieldType:"duration",fieldProps:V.has(e.durationFormat)?{durationFormat:e.durationFormat}:{}};case"checkbox":{const n=airtableColor(e.color),r=e.icon==="xCheckbox"?"x":U.has(e.icon)?e.icon:void 0;return{fieldType:"checkbox",fieldProps:{...r?{icon:r}:{},...n?{color:n}:{}}}}case"singleSelect":case"multipleSelects":{const n=(Array.isArray(e.choices)?e.choices:[]).map(r=>{const o=airtableColor(r.color);return{value:String(r.name),...o?{color:o}:{}}});return{fieldType:t.type==="singleSelect"?"singleSelect":"multiSelect",fieldProps:{options:n}}}case"date":return{fieldType:"date",fieldProps:w(e,!1)};case"dateTime":return{fieldType:"date",fieldProps:w(e,!0)};case"singleCollaborator":return{fieldType:"user",fieldProps:{multiple:!1}};case"multipleCollaborators":return{fieldType:"user",fieldProps:{multiple:!0}};case"multipleRecordLinks":{const n=String(e.linkedTableId??"");i.tableIds.has(n)||a("link","It links to a table that was not imported; the record ids stay, the cells show none of them.");const r=e.inverseLinkFieldId?i.keys.get(n)?.get(String(e.inverseLinkFieldId)):void 0;return{fieldType:"link",fieldProps:{table:n,multiple:e.prefersSingleRecordLink!==!0,...r&&n!==i.table.id&&i.tableIds.has(n)?{inverse:r}:{}}}}case"multipleAttachments":return{fieldType:"attachment"};case"barcode":return{fieldType:"barcode"};case"autoNumber":return{fieldType:"autoNumber"};case"button":return a("setting","The API does not say what the button does: set its URL (fieldProps.url, with {Field name} for values) or fieldProps.onClick."),{fieldType:"button",fieldProps:{label:String(e.label??t.name)}};case"createdTime":return{fieldType:"createdTime",fieldProps:w(e.result?.options,e.result?.type!=="date")};case"lastModifiedTime":case"lastModifiedBy":{const n=(Array.isArray(e.referencedFieldIds)?e.referencedFieldIds:[]).map(o=>l.get(o)).filter(Boolean),r=n.length?{watch:"specific",watchFields:n}:{watch:"all"};return t.type==="lastModifiedTime"?{fieldType:"lastModifiedTime",fieldProps:{...r,...w(e.result?.options,e.result?.type!=="date")}}:{fieldType:"lastModifiedBy",fieldProps:r}}case"createdBy":return{fieldType:"createdBy"};case"aiText":{const n=new Map(i.table.fields.map(c=>[c.id,c.name])),o=(Array.isArray(e.prompt)?e.prompt:typeof e.prompt=="string"?[e.prompt]:[]).map(c=>{if(typeof c=="string")return c;const s=c?.field?.fieldId;return s!=null?`{${n.get(String(s))??String(s)}}`:""}).join(""),f=i.table.fields.filter(c=>c.id!==t.id).map(c=>({field:l.get(c.id),header:c.name})),h=G(o,f,[t.name]);return o.trim()?h?a("setting",`${h}: fix the prompt in the field editor. The generated values come over as they are.`):a("setting","The generated values come over as they are. New ones come from the AI provider your app sets with setAIProvider()."):a("setting","The API gave no prompt: write one in the field editor. The generated values come over as they are."),{fieldType:"ai",fieldProps:{prompt:o,output:"text",auto:!0}}}case"formula":{const n=new Map(i.table.fields.map(f=>[f.id,f.name])),r=te(String(e.formula??""),n),o=formulaFunctionsUsed(r).filter(f=>!_.includes(f));if(o.length)a("formula",`Uses ${o.join(", ")}, which Base formulas do not have: the cells show #ERROR until that part is rewritten.`);else{const f=i.table.fields.filter(c=>c.id!==t.id).map(c=>({field:l.get(c.id),header:c.name})),h=W(r,j(f,[t.name]));h&&a("formula",`${h}: the cells show #ERROR.`)}return{fieldType:"formula",fieldProps:{formula:r,...ne(e.result)}}}case"rollup":{const n=T(e.recordLinkFieldId),r=I(e.recordLinkFieldId,e.fieldIdInLinkedTable),o=/^\s*([A-Za-z_]+)\s*\(\s*values\s*\)\s*$/i.exec(String(e.formula??""))?.[1]?.toUpperCase(),f=o&&v.has(o)?o:$.has(e.result?.type)?"SUM":"ARRAYJOIN";o?v.has(o)||a("formula",`The rollup's ${o}(values) has no Base aggregation; it is set to ${f}.`):a("setting",`The schema does not include the rollup's aggregation; it is set to ${f}. Change it in the field editor if the base used another.`);const h=e.result?.options?.precision;return{fieldType:"rollup",fieldProps:{linkField:n,field:r,aggregation:f,...h!=null&&$.has(e.result?.type)?{precision:Number(h)}:{}}}}case"multipleLookupValues":return{fieldType:"lookup",fieldProps:{linkField:T(e.recordLinkFieldId),field:I(e.recordLinkFieldId,e.fieldIdInLinkedTable)}};case"count":return{fieldType:"count",fieldProps:{linkField:T(e.recordLinkFieldId)}};default:return null}}function ne(t){const i=t?.options??{},e=i.precision!=null?{precision:Number(i.precision)}:{};switch(t?.type){case"number":return{result:"number",...e};case"currency":return{result:"currency",...e,...i.symbol?{symbol:i.symbol}:{}};case"percent":return{result:"percent",...e};case"date":return{result:"date",...w(i,!1)};case"dateTime":return{result:"date",...w(i,!0)};default:return{result:"auto"}}}const M=t=>Array.isArray(t)?t:t==null?[]:[t];function re(t){const i=t.thumbnails?.large?.url??t.thumbnails?.small?.url;return{id:String(t.id??t.url),url:String(t.url??""),name:String(t.filename??t.name??""),type:String(t.type??""),...typeof t.size=="number"?{size:t.size}:{},...typeof t.width=="number"?{width:t.width}:{},...typeof t.height=="number"?{height:t.height}:{},...i?{thumbnailUrl:String(i)}:{}}}function F(t){if(t==null)return"";if(Array.isArray(t))return t.map(F).join(", ");if(typeof t=="object"){const i=t;return"value"in i?F(i.value):"name"in i?String(i.name):"text"in i?String(i.text):JSON.stringify(t)}return String(t)}export function baseFromAirtable(t,i={},e={}){const l=[],a=(Array.isArray(t?.tables)?t.tables:[]).map(ee),T=a.map(s=>s.table),I=e.tables?.length?e.tables.map(s=>T.find(y=>y.id===s||y.name===s)).filter(s=>!!s):T,n=new Set(I.map(s=>s.id)),r=new Map;for(const s of T){const y=new Set(["id"]);r.set(s.id,new Map(s.fields.map(g=>[g.id,Q(g.name,y)])))}const o=new Map,f=e.userId??(s=>s.id),h=s=>{if(s==null||typeof s!="object")return s==null?null:String(s);const y=s,g=f(y);return o.has(g)||o.set(g,{id:g,name:y.name??y.email??g,...y.email?{email:y.email}:{}}),g};return{tables:I.map(s=>{const y={table:s,keys:r,tableIds:n,report:l};for(const{field:d,usedBy:u}of a.find(E=>E.table===s)?.added??[]){const E=(d.options?.referencedFieldIds??[]).map(m=>s.fields.find(A=>A.id===m).name),p=m=>l.push({kind:"field",table:s.name,name:d.name,message:`Added for ${u}, ${m}`});d.type==="createdTime"?p("which reads CREATED_TIME(): a Base record keeps that time in a Created time field. It holds each record's createdTime from the API."):E.length?p(`which reads when ${E.join(" and ")} last changed: a Last modified time field that watches ${E.length>1?"them":"it"}. The API does not say when a field last changed, so it is empty until the next edit.`):p("which reads LAST_MODIFIED_TIME(): a Last modified time field. The API does not say when a record last changed, so it is empty until the next edit.")}const g=r.get(s.id),N=s.primaryFieldId??s.fields[0]?.id,P=[...s.fields].sort((d,u)=>+(u.id===N)-+(d.id===N)).map(d=>{let u=ie(d,y);return u||(l.push({kind:"field",table:s.name,name:d.name,message:`Base has no "${d.type}" field: it is a text field, with each value as text.`}),u={fieldType:"text"}),{f:d,key:g.get(d.id),fieldType:u.fieldType,fieldProps:u.fieldProps,known:u.fieldType!=="text"||d.type==="singleLineText"}}),S=P.map(({f:d,key:u,fieldType:E,fieldProps:p})=>({id:u,field:u,header:d.name,fieldType:E,...p&&Object.keys(p).length?{fieldProps:p}:{},...d.description?{description:d.description}:{}})),O=i[s.id]??i[s.name],Y=(Array.isArray(O)?O:O?.records??[]).map(d=>{const u={id:d.id};for(const{f:E,key:p,fieldType:m,fieldProps:A,known:k}of P){if(Z.has(E.type))continue;let b=d.fields?.[E.name]??d.fields?.[E.id];E.type==="createdTime"&&b==null&&(b=d.createdTime),b!==void 0&&(k?m==="user"||m==="createdBy"||m==="lastModifiedBy"?u[p]=A?.multiple?M(b).map(h).filter(R=>R!=null):h(Array.isArray(b)?b[0]:b):m==="attachment"?u[p]=M(b).filter(R=>R&&typeof R=="object").map(R=>re(R)):m==="link"?u[p]=M(b).map(R=>String(R&&typeof R=="object"?R.id:R)):m==="ai"?u[p]=b&&typeof b=="object"?b.value??null:b:u[p]=b:u[p]=F(b))}return u}),x=d=>S.find(d)?.field,D=[];for(const d of s.views??[]){const u=J[d.type],E=m=>l.push({kind:"view",table:s.name,name:d.name,message:m});if(!u){E(`Base has no "${d.type}" view; it was left out.`);continue}const p={id:d.id,name:d.name,type:u};if(u==="kanban"){const m=x(A=>A.fieldType==="singleSelect"||A.fieldType==="user"&&!A.fieldProps?.multiple);if(!m){E("A Kanban view needs a single select or a single user field; the table has none.");continue}p.stackBy=m,l.push({kind:"setting",table:s.name,name:d.name,message:`The API does not say which field the board stacks by; it uses ${S.find(A=>A.field===m).header}.`})}else if(u==="calendar"||u==="gantt"){const m=S.filter(A=>A.fieldType==="date").map(A=>String(A.field));if(!m.length){E(`A ${u==="gantt"?"timeline":"calendar"} needs a date field; the table has none.`);continue}p.dateField=m[0],u==="gantt"&&m[1]&&(p.endField=m[1]),l.push({kind:"setting",table:s.name,name:d.name,message:`The API does not say which dates the view uses; it uses ${[p.dateField,p.endField].filter(Boolean).map(A=>S.find(k=>k.field===A).header).join(" to ")}.`})}else if(u==="gallery"){const m=x(A=>A.fieldType==="attachment");m&&(p.coverField=m)}D.push(p)}return D.length||D.push({id:"grid",name:"Grid view",type:"grid"}),{id:s.id,name:s.name,primaryField:g.get(N??"")??String(S[0]?.field??""),columns:S,data:Y,views:D}}),users:[...o.values()],report:l}}const L="JavaScript regular expressions, not RE2.",se=[["CONCATENATE","Text"],["LEFT","Text"],["RIGHT","Text"],["MID","Text","The count may be left out for the rest of the text."],["LEN","Text"],["FIND","Text","Case matters; 0 when the text is not there."],["SEARCH","Text","Case matters; empty when the text is not there."],["SUBSTITUTE","Text"],["REPLACE","Text"],["TRIM","Text"],["UPPER","Text"],["LOWER","Text"],["REPT","Text","At most 1,000 repeats.",!0],["T","Text"],["ENCODE_URL_COMPONENT","Text"],["REGEX_MATCH","Text",`${L} A leading (?i) works; other inline flags do not.`,!0],["REGEX_EXTRACT","Text",`${L} Empty when nothing matches.`,!0],["REGEX_REPLACE","Text",`${L} Replaces every match; the new text names a group by its number after a dollar sign, as JavaScript's replace does.`,!0],["IF","Logical"],["SWITCH","Logical",'Compares as text, so 1 matches "1".',!0],["AND","Logical"],["OR","Logical"],["NOT","Logical"],["XOR","Logical"],["TRUE","Logical","With or without the parentheses."],["FALSE","Logical","With or without the parentheses."],["BLANK","Logical"],["ERROR","Logical","The cell shows #ERROR."],["ISERROR","Logical","Division by zero is empty in Base, not an error, so ISERROR(1 / 0) is false.",!0],["ABS","Numeric"],["AVERAGE","Numeric"],["CEILING","Numeric"],["COUNT","Numeric"],["COUNTA","Numeric"],["COUNTALL","Numeric"],["EVEN","Numeric"],["EXP","Numeric"],["FLOOR","Numeric"],["INT","Numeric"],["LOG","Numeric","Base 10 unless a base is given."],["MAX","Numeric"],["MIN","Numeric"],["MOD","Numeric"],["ODD","Numeric"],["POWER","Numeric"],["ROUND","Numeric","Halves round toward positive: ROUND(-2.5) is -2."],["ROUNDDOWN","Numeric","Toward zero."],["ROUNDUP","Numeric","Away from zero."],["SQRT","Numeric"],["SUM","Numeric"],["VALUE","Numeric",'Skips characters that are not part of a number: VALUE("1,200.50 USD") is 1200.5.'],["DATEADD","Date",'The units Airtable names, except that "M" is minutes here: write "months".',!0],["DATESTR","Date"],["DATETIME_DIFF","Date",'Units as in DATEADD: "M" is minutes, write "months".',!0],["DATETIME_FORMAT","Date","moment.js tokens (YYYY, MMMM, Do, HH, A, Z, L, LL and the rest); week-of-year tokens are not read.",!0],["DATETIME_PARSE","Date","Reads the tokens DATETIME_FORMAT writes, with the separators as written. Text without a zone is local time.",!0],["DAY","Date"],["HOUR","Date"],["IS_AFTER","Date"],["IS_BEFORE","Date"],["IS_SAME","Date"],["MINUTE","Date"],["MONTH","Date"],["NOW","Date"],["SECOND","Date"],["SET_LOCALE","Date","Changes the month and weekday names DATETIME_FORMAT writes; ordinals (Do) stay English.",!0],["SET_TIMEZONE","Date","Changes what DATETIME_FORMAT writes. An unknown zone leaves the cell empty.",!0],["TIMESTR","Date"],["TONOW","Date","Calendar days from the date to today, signed.",!0],["FROMNOW","Date","Calendar days from today to the date, signed.",!0],["TODAY","Date"],["WEEKDAY","Date",'0 for Sunday; "Monday" as the second argument makes Monday 0.'],["WEEKNUM","Date",'Weeks start on Sunday, or on Monday with "Monday".'],["WORKDAY","Date",'Holidays as text ("2026-12-25, 2026-12-26") or a list of dates.'],["WORKDAY_DIFF","Date","Both days count. Holidays as in WORKDAY."],["YEAR","Date"],["ARRAYCOMPACT","Array"],["ARRAYFLATTEN","Array"],["ARRAYJOIN","Array"],["ARRAYUNIQUE","Array"],["ARRAYSLICE","Array"],["RECORD_ID","Record","The record's id; after baseFromAirtable, the Airtable record id."],["CREATED_TIME","Record","A Base record keeps that time in a Created time field. baseFromAirtable rewrites CREATED_TIME() to read the table's, and adds one when the table has none."],["LAST_MODIFIED_TIME","Record","A Base record keeps that time in a Last modified time field. baseFromAirtable rewrites LAST_MODIFIED_TIME() to read one that watches every field, and LAST_MODIFIED_TIME({Field}) one that watches that field, and adds it when the table has none."]];export function airtableFormulaSupport(){return se.map(([t,i,e="",l])=>{const T=_.includes(t)?l?"different":"supported":"unsupported";return{name:t,group:i,status:T,note:e}})}
@@ -4,7 +4,7 @@
4
4
  * the grid's bar to show its Filter panel; without a bar the item is not
5
5
  * offered.
6
6
  */
7
- export type BarPanel = 'hide' | 'filter' | 'group' | 'sort' | 'color' | 'chart' | 'gantt';
7
+ export type BarPanel = 'hide' | 'filter' | 'group' | 'sort' | 'color' | 'chart' | 'gantt' | 'list';
8
8
  /** A bar mounted over this grid; the returned function unregisters it. */
9
9
  export declare function registerBar(ctrl: object): () => void;
10
10
  export declare const hasBar: (ctrl: unknown) => boolean;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Undo and redo for a base. A cell edit is already a step on the grid's own
3
+ * history; what the grid does not record (a record added or deleted, a field
4
+ * added, changed or deleted) goes onto the same history as a step that puts
5
+ * the tables back, so Ctrl+Z walks one stream in the order things happened.
6
+ *
7
+ * A table's grid is made again when another table is shown, and its history
8
+ * with it: the history is kept per table while the table is away and given
9
+ * to its next grid, so going back to a table still undoes what was done
10
+ * there. The steps name records by id, so they apply to the new grid.
11
+ */
12
+ import type { BaseTable } from './base-tables.js';
13
+ type HistoryStep = {
14
+ rowId: string;
15
+ columnId: string;
16
+ field: string;
17
+ before: unknown;
18
+ after: unknown;
19
+ custom?: {
20
+ undo: () => void;
21
+ redo: () => void;
22
+ };
23
+ label?: string;
24
+ };
25
+ /** A grid's history, kept while its table is not shown. */
26
+ export type KeptHistory = {
27
+ history: HistoryStep[];
28
+ ptr: number;
29
+ };
30
+ /**
31
+ * The tables as they are now, to put back later. Each table's list of rows
32
+ * is copied; the rows themselves are shared. A cell edit writes into its
33
+ * row, but every edit made after this point is undone before this one is,
34
+ * so the rows are as they were by the time it applies.
35
+ */
36
+ export declare function snapshot(tables: ReadonlyArray<BaseTable>): BaseTable[];
37
+ /**
38
+ * Put a step that is not a cell write on a grid's history: Ctrl+Z (or the
39
+ * Undo button) runs `undo`, Ctrl+Shift+Z or Ctrl+Y runs `redo`. Steps that
40
+ * were undone are dropped, as a new edit drops them.
41
+ */
42
+ export declare function pushUndoStep(ctrl: unknown, label: string, undo: () => void, redo: () => void): void;
43
+ /** What the next undo or redo would do, for the buttons' titles ("Undo delete 2 records"). */
44
+ export declare function nextStepLabel(ctrl: unknown, direction: 'undo' | 'redo'): string;
45
+ /** The history of a grid that is about to go. */
46
+ export declare function takeHistory(ctrl: unknown): KeptHistory | undefined;
47
+ /** Give a new grid the history its table had. */
48
+ export declare function giveHistory(ctrl: unknown, kept: KeptHistory | undefined): void;
49
+ /** "1 record" / "3 records". */
50
+ export declare const records: (n: number) => string;
51
+ export declare const useBase: (base: object) => void;
52
+ /** A base on a page where none was used yet takes the keys until another is. */
53
+ export declare const claimBase: (base: object) => void;
54
+ export declare const usedLast: (base: object) => boolean;
55
+ export declare const forgetBase: (base: object) => void;
56
+ export {};
@@ -0,0 +1 @@
1
+ export function snapshot(r){return r.map(t=>({...t,data:t.data.slice()}))}export function pushUndoStep(r,t,o,i){const s=r;if(!s||!Array.isArray(s.history))return;const n=s.history.slice(0,s.historyPtr+1);n.push({rowId:"",columnId:"",field:"",before:void 0,after:void 0,custom:{undo:o,redo:i},label:t});const c=s.UNDO_LIMIT||200;s.history=n.length>c?n.slice(n.length-c):n,s.historyPtr=s.history.length-1,s.historyVersion+=1}export function nextStepLabel(r,t){const o=r;if(!o||!Array.isArray(o.history))return"";o.historyVersion;const i=o.history[t==="undo"?o.historyPtr:o.historyPtr+1];return i?i.custom?i.label??"":"cell edit":""}export function takeHistory(r){const t=r;if(!(!t||!Array.isArray(t.history)||!t.history.length))return{history:t.history,ptr:t.historyPtr}}export function giveHistory(r,t){const o=r;!o||!t||!Array.isArray(o.history)||(o.history=t.history,o.historyPtr=t.ptr,o.historyVersion+=1)}export const records=r=>`${r} ${r===1?"record":"records"}`;let e=null;export const useBase=r=>{e=r},claimBase=r=>{e??(e=r)},usedLast=r=>e===r,forgetBase=r=>{e===r&&(e=null)};
@@ -0,0 +1,54 @@
1
+ import { type BaseTable } from './base-tables.js';
2
+ type Row = Record<string, unknown>;
3
+ type Def = Record<string, any>;
4
+ /** What the import dialog hands the base: a new table, or records for a table that is there. */
5
+ export type BaseImportResult = {
6
+ mode: 'new';
7
+ table: BaseTable;
8
+ } | {
9
+ mode: 'append';
10
+ table: string;
11
+ rows: Row[];
12
+ columns: Def[];
13
+ };
14
+ /** What a column of the file becomes when the file makes a new table. */
15
+ export type ImportedField = {
16
+ header: string;
17
+ fieldType: string;
18
+ fieldProps?: Record<string, unknown>;
19
+ };
20
+ /** The field type a column of text looks like, from its non-empty values. */
21
+ export declare function guessField(header: string, values: ReadonlyArray<string>): ImportedField;
22
+ /**
23
+ * A new table from a file's header row and rows: one field per column, typed
24
+ * from its values (`guessField`); the first column names the records. `types`
25
+ * overrides a guess, by column index.
26
+ */
27
+ export declare function tableFromMatrix(matrix: ReadonlyArray<ReadonlyArray<string>>, existing: ReadonlyArray<BaseTable>, name: string, types?: Record<number, string>): BaseTable;
28
+ /**
29
+ * The type the import dialog lists for a field: its `fieldType`, except a
30
+ * number shown as an amount or a share, which the dialog offers as
31
+ * 'currency' and 'percent'.
32
+ */
33
+ export declare function importTypeOf(f: {
34
+ fieldType: string;
35
+ fieldProps?: Record<string, unknown>;
36
+ }): string;
37
+ /** The fields of `table` a column of a file can go to. */
38
+ export declare function importTargets(table: BaseTable): Array<{
39
+ id: string;
40
+ header: string;
41
+ fieldType?: string;
42
+ }>;
43
+ /** Each header to the field of `table` it names (by header or field id, any case), or null. */
44
+ export declare function matchColumns(headers: ReadonlyArray<string>, table: BaseTable): Array<string | null>;
45
+ /**
46
+ * The file's rows as records of `table`: column `i` goes to field `map[i]`
47
+ * (null skips it). A select gets the options it does not have yet; the
48
+ * returned columns carry them.
49
+ */
50
+ export declare function recordsFromMatrix(matrix: ReadonlyArray<ReadonlyArray<string>>, table: BaseTable, map: ReadonlyArray<string | null>): {
51
+ rows: Row[];
52
+ columns: Def[];
53
+ };
54
+ export {};
@@ -0,0 +1,2 @@
1
+ import{BRIGHT as g}from"./palette.js";import{convertValue as h}from"./convert.js";import{parseTimeOfDay as E}from"./time-of-day.js";import{blankTable as M,colId as S,newRecordId as x,primaryOf as O}from"./base-tables.js";import{canEditField as I}from"./field-access.svelte.js";const P=12,k=/^(true|false|yes|no|y|n|x|1|0|checked|unchecked|done|on|off)$/i,B=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,C=/^(https?:\/\/|www\.)\S+$/i,L=/^\+?[\d\s().-]{7,}$/,N=/^\d{4}-\d{2}-\d{2}([ T]\d{2}:\d{2}(:\d{2})?)?/,_=/^\d{1,2}[/.]\d{1,2}[/.]\d{2,4}$/,v=/^[-+]?[\d,]*\.?\d+(e[-+]?\d+)?$/i,F=/^[-+]?[$€£¥]\s?[\d,]*\.?\d+$|^[-+]?[\d,]*\.?\d+\s?[$€£¥]$/,D=/^[-+]?[\d,]*\.?\d+\s?%$/,R=/^\d{1,2}:\d{2}(:\d{2})?(\s?[ap]\.?m\.?)?$/i,A=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,H=/^\s*(?:[-*]\s+)?\[( |x|X)?\]\s/;export function guessField(e,i){const t=i.map(n=>n.trim()).filter(Boolean);if(!t.length)return{header:e,fieldType:"text"};const o=n=>t.every(l=>n.test(l));if(o(F)){const n=t.map(l=>/[$€£¥]/.exec(l)?.[0]).find(Boolean)??"$";return{header:e,fieldType:"number",fieldProps:{format:"currency",symbol:n,precision:t.some(l=>/\.\d/.test(l))?2:0}}}if(o(D))return{header:e,fieldType:"number",fieldProps:{format:"percent",points:!0,precision:0}};if(o(k)&&t.some(n=>!/^[01]$/.test(n)))return{header:e,fieldType:"checkbox"};if(o(v)){const n=Math.max(0,...t.map(l=>/\.(\d+)$/.exec(l)?.[1]?.length??0));return{header:e,fieldType:"number",fieldProps:n?{format:"decimal",precision:Math.min(n,4)}:{format:"integer"}}}if(o(B))return{header:e,fieldType:"email"};if(o(C))return{header:e,fieldType:"url"};if(o(N)||o(_)&&t.every(n=>!Number.isNaN(new Date(n).getTime()))){const n=t.some(l=>/\d{2}:\d{2}/.test(l));return{header:e,fieldType:"date",fieldProps:n?{time:!0}:{}}}if(o(R)&&t.every(n=>E(n)!=null))return{header:e,fieldType:"timeOfDay",fieldProps:t.some(n=>/[ap]\.?m/i.test(n))?{}:{timeFormat:"24hour"}};if(o(A))return{header:e,fieldType:"color"};if(o(H))return{header:e,fieldType:"checklist"};if(o(L)&&t.every(n=>(n.match(/\d/g)?.length??0)>=7))return{header:e,fieldType:"phone"};if(t.some(n=>n.length>120||n.includes(`
2
+ `)))return{header:e,fieldType:"longText"};if(t.some(n=>n.includes(","))){const n=t.flatMap(c=>c.split(",").map(d=>d.trim()).filter(Boolean)),l=[...new Set(n)];return l.length<=P*2&&l.length<n.length/2&&l.every(c=>c.length<=40)?{header:e,fieldType:"multiSelect",fieldProps:{options:$(l)}}:{header:e,fieldType:"text"}}const s=[...new Set(t)];return t.length>=4&&s.length<=P&&s.length<=t.length/2&&s.every(n=>n.length<=40)?{header:e,fieldType:"singleSelect",fieldProps:{options:$(s)}}:{header:e,fieldType:"text"}}const $=e=>e.map((i,t)=>({value:i,color:g[t%g.length].value}));function U(e,i){const t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"field";let o=/^\d/.test(t)?`f_${t}`:t;for(let s=2;i.has(o)||o==="id";s+=1)o=`${t}_${s}`;return i.add(o),o}function b(e){return e.slice(1).filter(i=>i.some(t=>String(t??"").trim()!=="")).map(i=>i.map(t=>String(t??"")))}export function tableFromMatrix(e,i,t,o={}){const s=(e[0]??[]).map((p,f)=>String(p??"").trim()||`Field ${f+1}`),n=b(e),l=new Set,c=s.map((p,f)=>{const u=guessField(p,n.map(w=>w[f]??"")),a=U(p,l),y=f===0&&!o[0]?"text":o[f]??importTypeOf(u),{fieldType:m,fieldProps:T}=y===importTypeOf(u)?u:X(y,n.map(w=>w[f]??""));return{id:a,field:a,header:p,...f===0?{width:220}:{},fieldType:m,...T?{fieldProps:T}:{}}}),d=n.map(p=>{const f={id:x()};return c.forEach((u,a)=>f[u.field]=h(p[a]??"","text",u.fieldType,u.fieldProps)),f}),r=M(i,Y(t,i));return{...r,primaryField:String(c[0]?.field??"name"),columns:c.length?c:r.columns,data:d}}export function importTypeOf(e){const i=e.fieldProps?.format;return e.fieldType==="number"&&(i==="currency"||i==="percent")?i:e.fieldType}function X(e,i){return e==="currency"?{fieldType:"number",fieldProps:{format:"currency",symbol:i.map(o=>/[$€£¥]/.exec(o)?.[0]).find(Boolean)??"$",precision:2}}:e==="percent"?{fieldType:"number",fieldProps:{format:"percent",points:!0,precision:0}}:e==="singleSelect"?{fieldType:e,fieldProps:{options:$([...new Set(i.map(t=>t.trim()).filter(Boolean))].slice(0,200))}}:e==="multiSelect"?{fieldType:e,fieldProps:{options:$([...new Set(i.flatMap(t=>t.split(",").map(o=>o.trim())).filter(Boolean))].slice(0,200))}}:{fieldType:e}}function Y(e,i){const t=new Set(i.map(s=>s.name.toLowerCase()));let o=e.trim()||"Imported";for(let s=2;t.has(o.toLowerCase());s+=1)o=`${e.trim()||"Imported"} ${s}`;return o}const z=new Set(["formula","lookup","rollup","count","autoNumber","createdTime","lastModifiedTime","createdBy","lastModifiedBy","button","link"]);export function importTargets(e){return e.columns.filter(i=>i.field!=null&&!z.has(i.fieldType)&&I(i,i.fieldProps??{})).map(i=>({id:S(i),header:String(i.header??i.field),fieldType:i.fieldType}))}export function matchColumns(e,i){const t=n=>n.trim().toLowerCase().replace(/[^a-z0-9]+/g,""),o=importTargets(i),s=new Set;return e.map(n=>{const l=t(n),c=o.find(d=>!s.has(d.id)&&(t(d.header)===l||t(d.id)===l));return c&&s.add(c.id),c?.id??null})}export function recordsFromMatrix(e,i,t){const o=b(e),s=new Map(i.columns.map(r=>[S(r),r])),n=i.columns.map(r=>{const p=t.indexOf(S(r));if(p<0||r.fieldType!=="singleSelect"&&r.fieldType!=="multiSelect")return r;const f=r.fieldProps?.options??[],u=new Set(f.map(m=>m.value)),a=[...new Set(o.flatMap(m=>r.fieldType==="multiSelect"?(m[p]??"").split(","):[m[p]??""]).map(m=>m.trim()).filter(m=>m&&!u.has(m)))];if(!a.length)return r;const y=[...f,...a.map((m,T)=>({value:m,color:g[(f.length+T)%g.length].value}))];return{...r,fieldProps:{...r.fieldProps,options:y}}}),l=new Map(n.map(r=>[S(r),r])),c=o.map(r=>{const p={id:x()};return t.forEach((f,u)=>{if(!f||!s.has(f))return;const a=l.get(f);p[String(a.field)]=h(r[u]??"","text",a.fieldType??"text",a.fieldProps)}),p}),d=O(i);return t.some(r=>r&&String(l.get(r)?.field)===d)||c.forEach((r,p)=>r[d]??(r[d]=`Imported ${p+1}`)),{rows:c,columns:n}}
@@ -0,0 +1,34 @@
1
+ import { type BaseTable } from './base-tables.js';
2
+ type Def = Record<string, any>;
3
+ /** One record that matched. */
4
+ export type BaseSearchHit = {
5
+ table: string;
6
+ rowId: string;
7
+ /** The record's name: its primary field as the cell shows it. */
8
+ title: string;
9
+ /** The field the match is shown in: its column id and name. */
10
+ field: string;
11
+ fieldName: string;
12
+ /** Whether that field is the primary field (then `text` is the title). */
13
+ primary: boolean;
14
+ /** The field's text, cut around the match when it is long. */
15
+ text: string;
16
+ /** Where the query's words are in `text`: [start, end) pairs, in order. */
17
+ marks: Array<[number, number]>;
18
+ };
19
+ /** The records of one table that matched: the first `limit` of them, and how many there are. */
20
+ export type BaseSearchGroup = {
21
+ table: string;
22
+ name: string;
23
+ hits: BaseSearchHit[];
24
+ total: number;
25
+ };
26
+ export type BaseSearchOptions = {
27
+ /** Records listed per table (default 5); `total` still counts them all. */
28
+ limit?: number;
29
+ /** Whether to search a field of a table (default: every field a cell shows as text). */
30
+ field?: (table: BaseTable, column: Def) => boolean;
31
+ };
32
+ /** Search the records of every table for `query`. Tables without a match are left out. */
33
+ export declare function searchBase(tables: ReadonlyArray<BaseTable>, query: string, options?: BaseSearchOptions): BaseSearchGroup[];
34
+ export {};
@@ -0,0 +1 @@
1
+ import{cellText as G}from"./grid-access.js";import{fillFieldColumn as H}from"./registry.svelte.js";import{colId as F,primaryOf as L,rowIdOf as W}from"./base-tables.js";const J=new Set(["checkbox","button","rating","number","currency","percent","duration","autoNumber","rollup","count"]),j=90;function v(i){let o="";const t=[];let u=0;for(const a of i){const s=a.normalize("NFD").replace(/\p{M}/gu,"").toLowerCase();for(let p=0;p<s.length;p++)t.push(u);o+=s,u+=a.length}return t.push(i.length),{text:o,from:t}}const K=i=>!!i&&/[\p{L}\p{N}]/u.test(i);function z(i,o){if(!o)return-1;let t=i.indexOf(o);if(t<0)return-1;if(i===o)return 0;if(t===0)return 1;for(;t>=0;t=i.indexOf(o,t+1))if(!K(i[t-1]))return 2;return 3}const D=new WeakMap;function P(i){let o=D.get(i);return o||(o=i.filter(t=>t.field!=null||typeof t.fieldFn=="function").map(t=>{const u=H(t,i);return{id:F(t),field:String(t.field??F(t)),header:String(t.header??t.field??F(t)),fieldType:t.fieldType,def:u,visible:!0}}),D.set(i,o)),o}export function searchBase(i,o,t={}){const u=Math.max(0,t.limit??5),a=v(o.trim()).text.replace(/\s+/g," ");if(!a)return[];const s=[...new Set(a.split(" "))].sort((e,f)=>f.length-e.length),p=new Map,y=(e,f)=>{let n=p.get(e);if(!n){n=new Map;const r=i.find(c=>c.id===e);if(r){const c=L(r),k=P(r.columns).find(d=>d.field===c||d.id===c);for(const d of r.data)n.set(W(r,d),k&&k.fieldType!=="link"?m(k,d):String(d?.[c]??""))}p.set(e,n)}return n.get(f)??""};function m(e,f){if(e.fieldType==="link"){const r=f?.[e.field];return(Array.isArray(r)?r.map(String):r==null||r===""?[]:[String(r)]).map(k=>y(String(e.def.fieldProps?.table??""),k)).filter(Boolean).join(", ")}let n;try{n=typeof e.def.fieldFn=="function"?e.def.fieldFn(f):f?.[e.field]}catch{return""}return G(e,n,f)}const g=[];return i.forEach((e,f)=>{const n=L(e),r=P(e.columns).filter(l=>!J.has(l.fieldType??"")&&(!t.field||t.field(e,l.def))),c=r.find(l=>l.field===n||l.id===n),k=c??P(e.columns).find(l=>l.field===n||l.id===n),d=c?[c,...r.filter(l=>l!==c)]:r,w=[];e.data.forEach((l,S)=>{const C=d.map(h=>m(h,l)),A=C.map(h=>v(h).text);if(!s.every(h=>A.some(O=>O.includes(h))))return;let M=-1,N=[];if(A.forEach((h,O)=>{const E=z(h,a),B=s.filter(T=>h.includes(T)).length;if(!B)return;const q=E>=0?E:Math.min(...s.map(T=>z(h,T)).filter(T=>T>=0)),I=[E>=0?0:1,s.length-B,d[O]===c?0:1,q,O];(M<0||x(I,N))&&(M=O,N=I)}),M<0)return;const b=d[M],{text:U,marks:X}=Q(C[M],s),_=c?C[0]:k?m(k,l):"";w.push({hit:{table:e.id,rowId:W(e,l),title:_||"Untitled",field:b.id,fieldName:b.header,primary:b===c,text:U,marks:X},rank:[...N,S]})}),w.length&&(w.sort((l,S)=>x(l.rank,S.rank)?-1:x(S.rank,l.rank)?1:0),g.push({group:{table:e.id,name:e.name,hits:w.slice(0,u).map(l=>l.hit),total:w.length},best:w[0].rank.slice(0,4),order:f}))}),g.sort((e,f)=>x(e.best,f.best)?-1:x(f.best,e.best)?1:e.order-f.order),g.map(e=>e.group)}function x(i,o){for(let t=0;t<Math.min(i.length,o.length);t++)if(i[t]!==o[t])return i[t]<o[t];return!1}function Q(i,o){const{text:t,from:u}=v(i),a=[];for(const n of o)for(let r=t.indexOf(n);r>=0;r=t.indexOf(n,r+1))a.push([u[r],u[r+n.length]]);a.sort((n,r)=>n[0]-r[0]);const s=[];for(const n of a){const r=s[s.length-1];r&&n[0]<=r[1]?r[1]=Math.max(r[1],n[1]):s.push([n[0],n[1]])}if(i.length<=j)return{text:i,marks:s};const p=s[0]?.[0]??0,y=p>30?p-30:0,m=Math.min(i.length,y+j),g=y>0?"…":"",e=g+i.slice(y,m)+(m<i.length?"…":""),f=s.filter(([n])=>n<m).map(([n,r])=>[n-y+g.length,Math.min(r,m)-y+g.length]).filter(([n])=>n>=g.length);return{text:e,marks:f}}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * A base shown to people who may look but not change anything: `<SvBase
3
+ * readOnly>`, for a share link the app serves. The base is the same; what a
4
+ * viewer gets is decided here, as plain data, so the app can also build the
5
+ * shared copy on its server and send only that.
6
+ *
7
+ * `sharedTables` keeps the tables and views the share lists, and drops the
8
+ * fields it hides, with every field that would show what they hold: a link
9
+ * to a table that is not shared, the lookups, rollups and counts that read a
10
+ * dropped link, a lookup or rollup of a dropped field in the linked table,
11
+ * and the formulas that read any of them. A form view is not shared: there
12
+ * is nothing a viewer may send.
13
+ *
14
+ * The shared copy's records lose the dropped fields' values. A page that
15
+ * gets the whole base still has them in memory, so a share of something
16
+ * secret is the copy `sharedTables` makes on the server, sent alone.
17
+ */
18
+ import { type BaseTable } from './base-tables.js';
19
+ import type { FieldView } from './view-model.js';
20
+ /** What a read-only base shows. Every list is optional; without one, all of it is shown. */
21
+ export type BaseShare = {
22
+ /** The ids of the tables shown, in their order in the base. */
23
+ tables?: ReadonlyArray<string>;
24
+ /** The ids of the views shown. A table none of whose views is listed shows its first one. */
25
+ views?: ReadonlyArray<string>;
26
+ /** Fields left out: a column id (in every table) or `tableId.columnId`. The primary field always shows. */
27
+ hideFields?: ReadonlyArray<string>;
28
+ };
29
+ /** The share a `readOnly` prop describes, or null for a base people can edit. */
30
+ export declare function shareOf(readOnly: boolean | BaseShare | null | undefined): BaseShare | null;
31
+ /** A grid of a read-only base (`<SvBase readOnly>` hands its grids `baseReadOnly`). */
32
+ export declare const isReadOnlyGrid: (ctrl: any) => boolean;
33
+ /** The field menu of a read-only grid: filter, group, hide and color by, no field changes. */
34
+ export declare function viewOnlyItems<T extends {
35
+ key?: string;
36
+ }>(ctrl: any, items: T[]): T[];
37
+ /** The tables of `tables` a share shows, with its fields and views. */
38
+ export declare function sharedTables(tables: ReadonlyArray<BaseTable>, share: BaseShare): BaseTable[];
39
+ /** The views of a table a share shows: no form, only the listed ones, and at least one. */
40
+ export declare function sharedViews(views: ReadonlyArray<FieldView> | undefined, share: BaseShare): FieldView[] | undefined;
41
+ /**
42
+ * A `selectionBar` prop without the buttons that change records ("Edit
43
+ * fields", "Delete"). An app's own actions stay: they are the app's to judge.
44
+ */
45
+ export declare function readOnlySelectionBar(bar: unknown): unknown;
@@ -0,0 +1 @@
1
+ import{colId as d,linkReaders as k,primaryOf as P}from"./base-tables.js";import{formulaReaders as v}from"./formula.js";export function shareOf(i){return i?i===!0?{}:i:null}export const isReadOnlyGrid=i=>i?.props?.baseReadOnly===!0;const T=new Set(["field-rowcolor","field-filter","field-group","field-hide"]);export function viewOnlyItems(i,t){return isReadOnlyGrid(i)?t.filter(l=>T.has(String(l.key))):t}export function sharedTables(i,t){const l=t.tables?new Set(t.tables):null,r=l?i.filter(e=>l.has(e.id)):[...i],p=new Set(r.map(e=>e.id)),a=new Set(t.hideFields??[]),m=new Map(r.map(e=>[e.id,new Set])),S=new Map(r.map(e=>[e.id,P(e)])),y=(e,n)=>d(n)===S.get(e.id)||String(n.field??"")===S.get(e.id),h=(e,n)=>{const f=m.get(e.id);return f.has(d(n))||y(e,n)?!1:(f.add(d(n)),!0)};for(const e of r)for(const n of e.columns){const f=d(n);(a.has(f)||a.has(`${e.id}.${f}`)||n.fieldType==="link"&&!p.has(String(n.fieldProps?.table??"")))&&h(e,n)}for(let e=!0;e;){e=!1;for(const n of r){const f=m.get(n.id);for(const o of n.columns){if(!f.has(d(o)))continue;const s=[...o.fieldType==="link"?k(n,o):[],...v(n.columns,o)];for(const c of s)h(n,c)&&(e=!0)}for(const o of n.columns){if(o.fieldType!=="lookup"&&o.fieldType!=="rollup")continue;const s=n.columns.find(u=>d(u)===String(o.fieldProps?.linkField??"")||String(u.field??"")===String(o.fieldProps?.linkField??"")),c=r.find(u=>u.id===String(s?.fieldProps?.table??"")),g=c?.columns.find(u=>d(u)===String(o.fieldProps?.field??"")||String(u.field??"")===String(o.fieldProps?.field??""));c&&g&&m.get(c.id).has(d(g))&&h(n,o)&&(e=!0)}}}const w=e=>e.map(n=>({...n,editable:!1}));return r.map(e=>{const n=m.get(e.id);if(!n.size)return{...e,columns:w(e.columns),views:sharedViews(e.views,t)};const f=e.columns.filter(s=>n.has(d(s))&&s.field!=null).map(s=>String(s.field)),o=f.length?e.data.map(s=>{const c={...s};for(const g of f)delete c[g];return c}):e.data;return{...e,columns:w(e.columns.filter(s=>!n.has(d(s)))),data:o,views:sharedViews(e.views,t)}})}export function sharedViews(i,t){if(!i)return;const l=i.filter(a=>a.type!=="form"),r=t.views?new Set(t.views):null,p=r?l.filter(a=>r.has(a.id)):l;return p.length?p:l.length?[l[0]]:void 0}export function readOnlySelectionBar(i){const t=l=>l.filter(r=>r!=="editFields"&&r!=="deleteRows");return Array.isArray(i)?t(i):i&&typeof i=="object"&&Array.isArray(i.actions)?{...i,actions:t(i.actions)}:i}
@@ -1,13 +1,13 @@
1
- import{colId as q,primaryOf as z,rowIdOf as T}from"./base-tables.js";import{fillFieldColumn as C}from"./registry.svelte.js";export const SQL_COMMENT_PREFIX="svgrid:",BASE_ORDER_COLUMN="svgrid_order";export function sqlName(o){const f=String(o).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,"").toLowerCase();return/^[a-z_]/.test(f)?f:`t_${f}`}const F=new Set(["formula","lookup","rollup","count","button"]),s=o=>`"${o.replace(/"/g,'""')}"`,p=o=>`'${o.replace(/'/g,"''")}'`,y=o=>Array.isArray(o)?o.map(String):o==null||o===""?[]:[String(o)];function S(o){switch(o.fieldType){case"number":case"currency":case"percent":case"rating":case"duration":case"autoNumber":return"double precision";case"checkbox":return"boolean";case"date":return o.fieldProps?.time?"timestamptz":"date";case"createdTime":case"lastModifiedTime":return"timestamptz";case"multiSelect":return"text[]";case"user":case"createdBy":case"lastModifiedBy":return o.fieldProps?.multiple?"text[]":"text";case"attachment":return"jsonb";default:return J(o)}}const N=new WeakMap;function J(o){let f=N.get(o);if(f===void 0){const m=C(o).cellDataType;f=m==="number"?"double precision":m==="boolean"?"boolean":m==="date"?"timestamptz":m==="dateString"?"date":"text",N.set(o,f)}return f}const E=864e5;export function baseToSql(o,f={}){const m=f.today??new Date,A=Date.UTC(m.getFullYear(),m.getMonth(),m.getDate()),k=f.relativeDays??400,_=new Set,u=new Map;for(const e of o){let n=sqlName(e.name||e.id);for(;_.has(n);)n=`${n}_2`;_.add(n),u.set(e.id,n)}const j=e=>o.find(n=>n.id===e),D=(e,n)=>e.columns.find(t=>q(t)===n);function P(e,n){const t=j(String(n.fieldProps?.table??"")),r=n.fieldProps?.inverse&&t?D(t,String(n.fieldProps.inverse)):void 0,l=n.fieldProps?.multiple!==!1;if(!r||t===e)return l?"junction":"fk";const c=r.fieldProps?.multiple!==!1;return l?c&&o.indexOf(e)<=o.indexOf(t)?"junction":"derived":"fk"}const b=e=>JSON.parse(JSON.stringify(e??null),(n,t)=>n==="table"&&typeof t=="string"&&u.has(t)?u.get(t):t),g=[],$=[];for(const e of o){const n=u.get(e.id),t=[],r=[],l=new Set(["id",BASE_ORDER_COLUMN]),c=a=>{let d=sqlName(a);for(;l.has(d);)d=`${d}_2`;return l.add(d),d};for(const a of e.columns){if(a.field==null)continue;const d=String(a.field);if(F.has(String(a.fieldType))){r.push(a);continue}if(a.fieldType==="link"){const O=P(e,a),w=j(String(a.fieldProps?.table??""));if(!w)continue;if(O==="fk")t.push({def:a,column:c(`${d}_id`),fk:u.get(w.id)});else if(r.push(a),O==="junction"){const M=`${sqlName(n).replace(/s$/,"")}_id`;let h=`${sqlName(d).replace(/s$/,"")}_id`;h===M&&(h=`${h}_2`),$.push({name:`${n}_${sqlName(d)}`,owner:e,field:d,from:M,to:h,target:w})}continue}t.push({def:a,column:c(d)})}const x=[' "id" text primary key default gen_random_uuid()::text',` ${s(BASE_ORDER_COLUMN)} bigint generated always as identity`,...t.map(a=>` ${s(a.column)} ${a.fk?"text":S(a.def)}`)];g.push({table:e,columns:t,extra:r,sql:`create table ${s(n)} (
1
+ import{colId as q,primaryOf as z,rowIdOf as T}from"./base-tables.js";import{fillFieldColumn as C}from"./registry.svelte.js";export const SQL_COMMENT_PREFIX="svgrid:",BASE_ORDER_COLUMN="svgrid_order";export function sqlName(o){const f=String(o).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,"").toLowerCase();return/^[a-z_]/.test(f)?f:`t_${f}`}const F=new Set(["formula","lookup","rollup","count","button"]),s=o=>`"${o.replace(/"/g,'""')}"`,m=o=>`'${o.replace(/'/g,"''")}'`,y=o=>Array.isArray(o)?o.map(String):o==null||o===""?[]:[String(o)];function S(o){switch(o.fieldType){case"number":case"currency":case"percent":case"rating":case"duration":case"autoNumber":return"double precision";case"checkbox":return"boolean";case"date":return o.fieldProps?.time?"timestamptz":"date";case"createdTime":case"lastModifiedTime":return"timestamptz";case"multiSelect":return"text[]";case"user":case"createdBy":case"lastModifiedBy":return o.fieldProps?.multiple?"text[]":"text";case"attachment":case"checklist":return"jsonb";case"timeOfDay":return"time";default:return J(o)}}const N=new WeakMap;function J(o){let f=N.get(o);if(f===void 0){const p=C(o).cellDataType;f=p==="number"?"double precision":p==="boolean"?"boolean":p==="date"?"timestamptz":p==="dateString"?"date":"text",N.set(o,f)}return f}const E=864e5;export function baseToSql(o,f={}){const p=f.today??new Date,D=Date.UTC(p.getFullYear(),p.getMonth(),p.getDate()),w=f.relativeDays??400,_=new Set,u=new Map;for(const e of o){let n=sqlName(e.name||e.id);for(;_.has(n);)n=`${n}_2`;_.add(n),u.set(e.id,n)}const j=e=>o.find(n=>n.id===e),A=(e,n)=>e.columns.find(t=>q(t)===n);function P(e,n){const t=j(String(n.fieldProps?.table??"")),r=n.fieldProps?.inverse&&t?A(t,String(n.fieldProps.inverse)):void 0,l=n.fieldProps?.multiple!==!1;if(!r||t===e)return l?"junction":"fk";const c=r.fieldProps?.multiple!==!1;return l?c&&o.indexOf(e)<=o.indexOf(t)?"junction":"derived":"fk"}const b=e=>JSON.parse(JSON.stringify(e??null),(n,t)=>n==="table"&&typeof t=="string"&&u.has(t)?u.get(t):t),g=[],$=[];for(const e of o){const n=u.get(e.id),t=[],r=[],l=new Set(["id",BASE_ORDER_COLUMN]),c=a=>{let d=sqlName(a);for(;l.has(d);)d=`${d}_2`;return l.add(d),d};for(const a of e.columns){if(a.field==null)continue;const d=String(a.field);if(F.has(String(a.fieldType))){r.push(a);continue}if(a.fieldType==="link"){const O=P(e,a),k=j(String(a.fieldProps?.table??""));if(!k)continue;if(O==="fk")t.push({def:a,column:c(`${d}_id`),fk:u.get(k.id)});else if(r.push(a),O==="junction"){const M=`${sqlName(n).replace(/s$/,"")}_id`;let h=`${sqlName(d).replace(/s$/,"")}_id`;h===M&&(h=`${h}_2`),$.push({name:`${n}_${sqlName(d)}`,owner:e,field:d,from:M,to:h,target:k})}continue}t.push({def:a,column:c(d)})}const x=[' "id" text primary key default gen_random_uuid()::text',` ${s(BASE_ORDER_COLUMN)} bigint generated always as identity`,...t.map(a=>` ${s(a.column)} ${a.fk?"text":S(a.def)}`)];g.push({table:e,columns:t,extra:r,sql:`create table ${s(n)} (
2
2
  ${x.join(`,
3
3
  `)}
4
4
  );`})}const i=[];i.push(`-- ${f.title??"A base"}, as Postgres tables. Made by baseToSql (@svgrid/enterprise/base);`),i.push("-- the svgrid: comments keep what SQL has no type for, so baseFromDatabase opens it as the same base."),i.push("");for(const e of g)i.push(e.sql);for(const e of $)i.push(`create table ${s(e.name)} (
5
5
  "id" serial primary key,
6
6
  ${s(e.from)} text not null,
7
7
  ${s(e.to)} text not null
8
- );`);i.push("");for(const e of g){const n=u.get(e.table.id);for(const r of e.columns)i.push(`comment on column ${s(n)}.${s(r.column)} is ${p(SQL_COMMENT_PREFIX+JSON.stringify(b(r.def)))};`);const t={v:1,name:e.table.name,position:g.indexOf(e),primaryField:z(e.table),order:e.table.columns.filter(r=>r.field!=null).map(r=>String(r.field)),extra:b(e.extra),...e.table.views?{views:b(e.table.views)}:{},...e.table.automations?.length?{automations:b(e.table.automations)}:{}};i.push(`comment on table ${s(n)} is ${p(SQL_COMMENT_PREFIX+JSON.stringify(t))};`)}for(const e of $){const n={v:1,junction:{owner:u.get(e.owner.id),field:e.field,from:e.from,to:e.to}};i.push(`comment on table ${s(e.name)} is ${p(SQL_COMMENT_PREFIX+JSON.stringify(n))};`)}if(f.data!==!1){const e=(n,t)=>{if(t==null||t===""||Array.isArray(t)&&t.length===0&&S(n)!=="text[]"&&S(n)!=="jsonb")return"null";const r=S(n);if(r==="jsonb"){const l=Array.isArray(t)?t.filter(c=>!(c&&typeof c=="object"&&String(c.url??"").startsWith("blob:"))):t;return`${p(JSON.stringify(l))}::jsonb`}if(r==="text[]")return`array[${y(t).map(p).join(", ")}]::text[]`;if(r==="boolean")return t?"true":"false";if(r==="double precision")return Number.isFinite(Number(t))?String(Number(t)):"null";if(r==="date"&&typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)&&k>0){const l=Math.round((Date.parse(`${t}T00:00:00Z`)-A)/E);if(Math.abs(l)<=k)return l===0?"current_date":`current_date ${l>0?"+":"-"} ${Math.abs(l)}`}return p(String(t))};i.push("");for(const n of g){const t=n.table.data.filter(Boolean);if(!t.length)continue;const r=["id",...n.columns.map(c=>c.column)],l=t.map(c=>` (${[p(T(n.table,c)),...n.columns.map(a=>a.fk?y(c[String(a.def.field)])[0]!=null?p(y(c[String(a.def.field)])[0]):"null":e(a.def,c[String(a.def.field)]))].join(", ")})`);i.push(`insert into ${s(u.get(n.table.id))} (${r.map(s).join(", ")}) values
8
+ );`);i.push("");for(const e of g){const n=u.get(e.table.id);for(const r of e.columns)i.push(`comment on column ${s(n)}.${s(r.column)} is ${m(SQL_COMMENT_PREFIX+JSON.stringify(b(r.def)))};`);const t={v:1,name:e.table.name,position:g.indexOf(e),primaryField:z(e.table),order:e.table.columns.filter(r=>r.field!=null).map(r=>String(r.field)),extra:b(e.extra),...e.table.views?{views:b(e.table.views)}:{},...e.table.automations?.length?{automations:b(e.table.automations)}:{}};i.push(`comment on table ${s(n)} is ${m(SQL_COMMENT_PREFIX+JSON.stringify(t))};`)}for(const e of $){const n={v:1,junction:{owner:u.get(e.owner.id),field:e.field,from:e.from,to:e.to}};i.push(`comment on table ${s(e.name)} is ${m(SQL_COMMENT_PREFIX+JSON.stringify(n))};`)}if(f.data!==!1){const e=(n,t)=>{if(t==null||t===""||Array.isArray(t)&&t.length===0&&S(n)!=="text[]"&&S(n)!=="jsonb")return"null";const r=S(n);if(r==="jsonb"){const l=Array.isArray(t)?t.filter(c=>!(c&&typeof c=="object"&&String(c.url??"").startsWith("blob:"))):t;return`${m(JSON.stringify(l))}::jsonb`}if(r==="text[]")return`array[${y(t).map(m).join(", ")}]::text[]`;if(r==="boolean")return t?"true":"false";if(r==="double precision")return Number.isFinite(Number(t))?String(Number(t)):"null";if(r==="date"&&typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)&&w>0){const l=Math.round((Date.parse(`${t}T00:00:00Z`)-D)/E);if(Math.abs(l)<=w)return l===0?"current_date":`current_date ${l>0?"+":"-"} ${Math.abs(l)}`}return m(String(t))};i.push("");for(const n of g){const t=n.table.data.filter(Boolean);if(!t.length)continue;const r=["id",...n.columns.map(c=>c.column)],l=t.map(c=>` (${[m(T(n.table,c)),...n.columns.map(a=>a.fk?y(c[String(a.def.field)])[0]!=null?m(y(c[String(a.def.field)])[0]):"null":e(a.def,c[String(a.def.field)]))].join(", ")})`);i.push(`insert into ${s(u.get(n.table.id))} (${r.map(s).join(", ")}) values
9
9
  ${l.join(`,
10
- `)};`)}for(const n of $){const t=[];for(const r of n.owner.data)if(r)for(const l of y(r[n.field]))t.push(` (${p(T(n.owner,r))}, ${p(l)})`);t.length&&i.push(`insert into ${s(n.name)} (${s(n.from)}, ${s(n.to)}) values
10
+ `)};`)}for(const n of $){const t=[];for(const r of n.owner.data)if(r)for(const l of y(r[n.field]))t.push(` (${m(T(n.owner,r))}, ${m(l)})`);t.length&&i.push(`insert into ${s(n.name)} (${s(n.from)}, ${s(n.to)}) values
11
11
  ${t.join(`,
12
12
  `)};`)}}i.push("");for(const e of g){const n=u.get(e.table.id);for(const t of e.columns)t.fk&&i.push(`alter table ${s(n)} add foreign key (${s(t.column)}) references ${s(t.fk)}("id") on delete set null;`)}for(const e of $)i.push(`alter table ${s(e.name)} add foreign key (${s(e.from)}) references ${s(u.get(e.owner.id))}("id") on delete cascade;`),i.push(`alter table ${s(e.name)} add foreign key (${s(e.to)}) references ${s(u.get(e.target.id))}("id") on delete cascade;`);return i.join(`
13
13
  `)+`
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The trash of a base: records, fields and tables that were deleted, kept so
3
+ * they can be put back. Restoring puts a record back in its table at the
4
+ * place it had, a field back among its table's fields (its values were never
5
+ * taken out of the records), and a table back among the tabs. Links come
6
+ * back from the restored side: a record that linked to others lists them
7
+ * again, and so do they.
8
+ *
9
+ * The trash is plain data (`BaseTrashItem[]`), so an app can store it with
10
+ * the tables. Items older than the base's `trashDays` are dropped when the
11
+ * base opens.
12
+ */
13
+ import { type BaseTable } from './base-tables.js';
14
+ type Row = Record<string, unknown>;
15
+ type Def = Record<string, any>;
16
+ type Deleted = {
17
+ /** The item's own id in the trash. */
18
+ id: string;
19
+ /** When it was deleted (ISO). */
20
+ deletedAt: string;
21
+ /** Who deleted it: the current user's id (`setCurrentUser`), when there is one. */
22
+ deletedBy?: string;
23
+ };
24
+ export type BaseTrashItem = (Deleted & {
25
+ kind: 'record';
26
+ table: string;
27
+ row: Row;
28
+ index: number;
29
+ }) | (Deleted & {
30
+ kind: 'field';
31
+ table: string;
32
+ column: Def;
33
+ index: number;
34
+ }) | (Deleted & {
35
+ kind: 'table';
36
+ table: BaseTable;
37
+ index: number;
38
+ });
39
+ /** Trash items for records just deleted from `table`: `before` is its rows as they were. */
40
+ export declare function trashRecords(table: BaseTable, before: ReadonlyArray<Row>, ids: ReadonlyArray<string>, by?: string, now?: Date): BaseTrashItem[];
41
+ export declare function trashField(table: BaseTable, column: Def, index: number, by?: string, now?: Date): BaseTrashItem;
42
+ export declare function trashTable(table: BaseTable, index: number, by?: string, now?: Date): BaseTrashItem;
43
+ /** What an item is called in the trash: the record's name, the field's, the table's. */
44
+ export declare function trashLabel(item: BaseTrashItem, tables: ReadonlyArray<BaseTable>): string;
45
+ /** Why an item cannot go back now, or '' when it can. */
46
+ export declare function cannotRestore(item: BaseTrashItem, tables: ReadonlyArray<BaseTable>): string;
47
+ /** The tables with `items` put back (each one that can be). */
48
+ export declare function restoreItems(tables: BaseTable[], items: ReadonlyArray<BaseTrashItem>): BaseTable[];
49
+ /** The items deleted within the last `days` days. */
50
+ export declare function freshTrash(items: ReadonlyArray<BaseTrashItem>, days: number, now?: Date): BaseTrashItem[];
51
+ export {};
@@ -0,0 +1 @@
1
+ import{addInverse as u,colId as a,primaryOf as h,rowIdOf as c,syncAllInverses as p}from"./base-tables.js";let m=0;const x=()=>`trash-${Date.now().toString(36)}-${m+=1}`;function f(t,o){return{id:x(),deletedAt:o.toISOString(),...t?{deletedBy:t}:{}}}export function trashRecords(t,o,e,r,l=new Date){const s=new Set(e),n=[];return o.forEach((i,d)=>{i&&s.has(c(t,i))&&n.push({...f(r,l),kind:"record",table:t.id,row:i,index:d})}),n}export function trashField(t,o,e,r,l=new Date){return{...f(r,l),kind:"field",table:t.id,column:o,index:e}}export function trashTable(t,o,e,r=new Date){return{...f(e,r),kind:"table",table:t,index:o}}export function trashLabel(t,o){if(t.kind==="table")return t.table.name;if(t.kind==="field")return String(t.column.header??t.column.field??"Field");const e=o.find(s=>s.id===t.table),r=e?t.row[h(e)]:void 0;return(Array.isArray(r)?r.join(", "):r==null?"":String(r)).trim()||"Unnamed record"}export function cannotRestore(t,o){if(t.kind==="table")return o.some(r=>r.id===t.table.id)?"A table with its id is in the base":"";const e=o.find(r=>r.id===t.table);return e?t.kind==="record"?e.data.some(r=>r&&c(e,r)===c(e,t.row))?"The record is in its table":"":e.columns.some(r=>a(r)===a(t.column))?"A field with its id is in the table":"":"Its table was deleted: restore the table first"}export function restoreItems(t,o){let e=t;const r={table:0,field:1,record:2},l=[...o].sort((n,i)=>r[n.kind]-r[i.kind]||n.index-i.index),s=new Set;for(const n of l)if(!cannotRestore(n,e))if(n.kind==="table"){const i=e.slice();i.splice(Math.min(n.index,i.length),0,n.table),e=i;for(const d of n.table.columns)d.fieldType==="link"&&e.some(b=>b.id===d.fieldProps?.table)&&(e=u(e,n.table.id,a(d)));s.add(n.table.id)}else n.kind==="field"?(e=e.map(i=>{if(i.id!==n.table)return i;const d=i.columns.slice();return d.splice(Math.min(n.index,d.length),0,n.column),{...i,columns:d}}),n.column.fieldType==="link"&&(e=u(e,n.table,a(n.column))),s.add(n.table)):(e=e.map(i=>{if(i.id!==n.table)return i;const d=i.data.slice();return d.splice(Math.min(n.index,d.length),0,n.row),{...i,data:d}}),s.add(n.table));for(const n of s)e=p(e,n);return e}export function freshTrash(t,o,e=new Date){if(!(o>0))return[...t];const r=e.getTime()-o*864e5;return t.filter(l=>new Date(l.deletedAt).getTime()>=r)}