@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.
- package/dist/SvGridBoard.svelte +1 -1
- package/dist/cdn/svgrid-enterprise.svelte-external.js +2 -2
- package/dist/designer/assets/{index-v61ZvIWw.js → index-Eyxa9vgS.js} +3 -3
- package/dist/designer/assets/{src-DkFgWld_.js → src-CSmsOfsG.js} +15 -15
- package/dist/designer/index.html +2 -2
- package/dist/fields/AiCell.svelte +41 -0
- package/dist/fields/AiCell.svelte.d.ts +5 -0
- package/dist/fields/BaseChartView.svelte +1 -1
- package/dist/fields/BaseDashboardView.svelte +133 -0
- package/dist/fields/BaseDashboardView.svelte.d.ts +17 -0
- package/dist/fields/BaseImport.svelte +89 -0
- package/dist/fields/BaseImport.svelte.d.ts +15 -0
- package/dist/fields/BaseInboxView.svelte +112 -0
- package/dist/fields/BaseInboxView.svelte.d.ts +8 -0
- package/dist/fields/BaseListView.svelte +90 -0
- package/dist/fields/BaseListView.svelte.d.ts +8 -0
- package/dist/fields/BaseSearch.svelte +78 -0
- package/dist/fields/BaseSearch.svelte.d.ts +10 -0
- package/dist/fields/BaseTableView.svelte +28 -3
- package/dist/fields/BaseTableView.svelte.d.ts +5 -1
- package/dist/fields/BaseTabs.svelte +45 -8
- package/dist/fields/BaseTabs.svelte.d.ts +25 -1
- package/dist/fields/BaseTrash.svelte +63 -0
- package/dist/fields/BaseTrash.svelte.d.ts +15 -0
- package/dist/fields/ChecklistCell.svelte +22 -0
- package/dist/fields/ChecklistCell.svelte.d.ts +10 -0
- package/dist/fields/ChecklistEditor.svelte +81 -0
- package/dist/fields/ChecklistEditor.svelte.d.ts +12 -0
- package/dist/fields/ColorCell.svelte +13 -0
- package/dist/fields/ColorCell.svelte.d.ts +8 -0
- package/dist/fields/ColorEditor.svelte +60 -0
- package/dist/fields/ColorEditor.svelte.d.ts +11 -0
- package/dist/fields/DashboardRecords.svelte +35 -0
- package/dist/fields/DashboardRecords.svelte.d.ts +11 -0
- package/dist/fields/DashboardTileEditor.svelte +138 -0
- package/dist/fields/DashboardTileEditor.svelte.d.ts +15 -0
- package/dist/fields/FieldEditor.svelte +32 -3
- package/dist/fields/FieldInput.svelte +1 -1
- package/dist/fields/GroupHeader.svelte +3 -3
- package/dist/fields/ListChips.svelte +21 -0
- package/dist/fields/ListChips.svelte.d.ts +9 -0
- package/dist/fields/MentionInput.svelte +59 -0
- package/dist/fields/MentionInput.svelte.d.ts +11 -0
- package/dist/fields/PropertyInput.svelte +13 -10
- package/dist/fields/RecordView.svelte +20 -25
- package/dist/fields/SvBase.svelte +48 -9
- package/dist/fields/SvBase.svelte.d.ts +33 -1
- package/dist/fields/SvBaseForm.svelte +2 -2
- package/dist/fields/SvBaseForm.svelte.d.ts +14 -0
- package/dist/fields/SvBaseViewBar.svelte +33 -12
- package/dist/fields/SvBaseViewBar.svelte.d.ts +2 -0
- package/dist/fields/TimeOfDayEditor.svelte +39 -0
- package/dist/fields/TimeOfDayEditor.svelte.d.ts +12 -0
- package/dist/fields/activity.svelte.d.ts +29 -0
- package/dist/fields/activity.svelte.js +1 -1
- package/dist/fields/ai-field.svelte.d.ts +91 -0
- package/dist/fields/ai-field.svelte.js +1 -0
- package/dist/fields/ai-prompt.d.ts +64 -0
- package/dist/fields/ai-prompt.js +7 -0
- package/dist/fields/airtable.d.ts +90 -0
- package/dist/fields/airtable.js +1 -0
- package/dist/fields/bar-request.svelte.d.ts +1 -1
- package/dist/fields/base-history.d.ts +56 -0
- package/dist/fields/base-history.js +1 -0
- package/dist/fields/base-import.d.ts +54 -0
- package/dist/fields/base-import.js +2 -0
- package/dist/fields/base-search.d.ts +34 -0
- package/dist/fields/base-search.js +1 -0
- package/dist/fields/base-share.d.ts +45 -0
- package/dist/fields/base-share.js +1 -0
- package/dist/fields/base-sql.js +3 -3
- package/dist/fields/base-trash.d.ts +51 -0
- package/dist/fields/base-trash.js +1 -0
- package/dist/fields/builtin-types.js +1 -1
- package/dist/fields/chart-view.d.ts +12 -0
- package/dist/fields/chart-view.js +1 -1
- package/dist/fields/checklist.d.ts +36 -0
- package/dist/fields/checklist.js +4 -0
- package/dist/fields/color-value.d.ts +14 -0
- package/dist/fields/color-value.js +1 -0
- package/dist/fields/convert.js +1 -1
- package/dist/fields/copy-text.d.ts +1 -1
- package/dist/fields/copy-text.js +1 -1
- package/dist/fields/dashboard.d.ts +143 -0
- package/dist/fields/dashboard.js +1 -0
- package/dist/fields/field-access.svelte.d.ts +37 -0
- package/dist/fields/field-access.svelte.js +1 -0
- package/dist/fields/field-ops.js +1 -1
- package/dist/fields/filter-model.d.ts +4 -11
- package/dist/fields/filter-model.js +1 -1
- package/dist/fields/form-logic.d.ts +69 -0
- package/dist/fields/form-logic.js +1 -0
- package/dist/fields/formula.js +1 -1
- package/dist/fields/grid-access.d.ts +8 -0
- package/dist/fields/grid-access.js +1 -1
- package/dist/fields/index.d.ts +16 -0
- package/dist/fields/index.js +1 -1
- package/dist/fields/list-view.d.ts +40 -0
- package/dist/fields/list-view.js +1 -0
- package/dist/fields/mentions.d.ts +50 -0
- package/dist/fields/mentions.js +1 -0
- package/dist/fields/palette.d.ts +4 -2
- package/dist/fields/palette.js +1 -1
- package/dist/fields/record-menu.js +1 -1
- package/dist/fields/registry.svelte.d.ts +5 -0
- package/dist/fields/registry.svelte.js +1 -1
- package/dist/fields/time-of-day.d.ts +28 -0
- package/dist/fields/time-of-day.js +1 -0
- package/dist/fields/view-model.d.ts +24 -2
- package/dist/fields/view-model.js +1 -1
- package/dist/fields/viewbar/ConditionValue.svelte +3 -3
- package/dist/fields/viewbar/ListPanel.svelte +36 -0
- package/dist/fields/viewbar/ListPanel.svelte.d.ts +11 -0
- package/dist/fields/viewbar/ViewsMenu.svelte +27 -4
- package/dist/fields/viewbar/ViewsMenu.svelte.d.ts +6 -0
- package/dist/node/studio.js +1 -1
- package/dist/version.d.ts +2 -2
- package/dist/version.js +1 -1
- package/dist/wc/GridFind-DsTvdUXq.js +1 -0
- package/dist/wc/GridFooter-D-i8boBh.js +1 -0
- package/dist/wc/GridMenus-CYe9Fw2I.js +20 -0
- package/dist/wc/PinSplitter-LvyyrLhe.js +6 -0
- package/dist/wc/SvChartMenu-XKW_LOYw.js +1 -0
- package/dist/wc/SvDateRangeInput-CSOxqTB1.js +1 -0
- package/dist/wc/SvDateTimePicker-DvvFs2T9.js +4 -0
- package/dist/wc/SvField-BmQphyOs.js +20 -0
- package/dist/wc/SvForm-HD7y5vmk.js +46 -0
- package/dist/wc/SvGridCellEditor-776KAOe1.js +3 -0
- package/dist/wc/SvGridChart-DC7ZUhp8.js +171 -0
- package/dist/wc/SvGridChartBuilder-Dd3vWBvq.js +7 -0
- package/dist/wc/SvGridChartPanel-CwYjF46U.js +5 -0
- package/dist/wc/SvGridChartView-CSF38rBs.js +3 -0
- package/dist/wc/SvGridDropdown-4S1G7gsP.js +30 -0
- package/dist/wc/SvMenuList-D3ZLXjL_.js +1 -0
- package/dist/wc/SvModal-Dk0YwPWp.js +7 -0
- package/dist/wc/SvSwitchButton-DdZmc3ew.js +1 -0
- package/dist/wc/SvTabs-BI2cQHyw.js +2 -0
- package/dist/wc/base-react.d.ts +38 -0
- package/dist/wc/base-react.js +1 -0
- package/dist/wc/base-vue.d.ts +29 -0
- package/dist/wc/base-vue.js +1 -0
- package/dist/wc/board-RQp5fHPR.js +21 -0
- package/dist/wc/board-view.svelte-CpxuZcEg.js +1 -0
- package/dist/wc/card-marks.svelte-QwxIcKcZ.js +1 -0
- package/dist/wc/client-DNdLmGcu.js +3 -0
- package/dist/wc/createOverlay.svelte-CDw3RXgs.js +1 -0
- package/dist/wc/custom-filter-Dp8JxlQu.js +2 -0
- package/dist/wc/date-format-DtSmFyEB.js +18 -0
- package/dist/wc/editor-registry-CkKfcVLc.js +1 -0
- package/dist/wc/export-format-CGfE9_O5.js +5 -0
- package/dist/wc/gallery-CNOHNWEJ.js +4 -0
- package/dist/wc/gallery-view.svelte-27X-wCQH.js +1 -0
- package/dist/wc/grid-extension.svelte-hgqOteka.js +1 -0
- package/dist/wc/import-B9mIERCl.js +4 -0
- package/dist/wc/js-scroller.svelte-BP8Up6_q.js +1 -0
- package/dist/wc/license-CWVWqb-i.js +27 -0
- package/dist/wc/list-option-CI4nMshZ.js +1 -0
- package/dist/wc/react.d.ts +1 -0
- package/dist/wc/react.js +1 -1
- package/dist/wc/scheduler-CkVY4od-.js +147 -0
- package/dist/wc/scheduler-view.svelte-SzG7rU8b.js +1 -0
- package/dist/wc/sparkline-DWRBQubt.js +1 -0
- package/dist/wc/sv-base-element.d.ts +87 -0
- package/dist/wc/sv-base-element.js +273 -0
- package/dist/wc/sv-sheet-element.d.ts +2 -0
- package/dist/wc/sv-sheet-element.js +55 -55
- package/dist/wc/svelte-virtualizer.svelte-CSBwEZt9.js +1 -0
- package/dist/wc/types/sv-base-element.d.ts +87 -0
- package/dist/wc/vue.d.ts +1 -0
- package/dist/wc/vue.js +1 -1
- package/package.json +18 -4
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
<script lang="ts">
|
|
2
|
+
import{onMount}from"svelte";import{fieldPropsOf}from"./registry.svelte";import{formatTimeOfDay,parseTimeOfDay,timeFromSeconds,timeSeconds}from"./time-of-day";let{value,typed=false,columnDef,onCommit,onCancel,onCommitAndMove,onCommitAndMoveDown}=$props();const p=$derived(fieldPropsOf(columnDef??{}));const seeded=typed;let text=$state(typed?String(value??""):value==null||value===""?"":formatTimeOfDay(value,fieldPropsOf(columnDef??{})));const result=$derived(text.trim()?parseTimeOfDay(text,{seconds:!!p.showSeconds}):null);const error=$derived(text.trim()&&result==null?"Not a time (9:30 am, 14:05, 2pm)":null);const reads=$derived(result?formatTimeOfDay(result,p):"");function bump(dir,big){const now=text.trim()?timeSeconds(result):9*3600-dir*900;if(now==null)return;text=formatTimeOfDay(timeFromSeconds(now+dir*(big?3600:900)),p)}let box=$state(null);let input=$state(null);let noteAt=$state(null);function place(){const cell=box?.closest("td")??box;if(!cell)return;const r=cell.getBoundingClientRect();noteAt={top:r.bottom+2,left:r.left}}function takeFocus(){if(!input||document.activeElement===input)return;input.focus({preventScroll:true});if(!seeded)input.select();else input.setSelectionRange(text.length,text.length)}onMount(()=>{place();takeFocus();const frame=requestAnimationFrame(takeFocus);const onDown=e=>{if(finished||box?.contains(e.target))return;if(error){finished=true;onCancel()}else finish("commit")};window.addEventListener("resize",place);window.addEventListener("scroll",place,true);document.addEventListener("pointerdown",onDown,true);return()=>{cancelAnimationFrame(frame);window.removeEventListener("resize",place);window.removeEventListener("scroll",place,true);document.removeEventListener("pointerdown",onDown,true)}});let finished=false;function finish(how){if(finished||error)return;finished=true;if((how==="down"||how==="up")&&onCommitAndMoveDown)onCommitAndMoveDown(result,how==="up");else if((how==="next"||how==="prev")&&onCommitAndMove)onCommitAndMove(result,how==="next"?1:-1);else onCommit(result)}function onKey(e){if(e.key==="Enter")finish(e.shiftKey?"up":"down");else if(e.key==="Tab")finish(e.shiftKey?"prev":"next");else if(e.key==="ArrowUp"||e.key==="ArrowDown")bump(e.key==="ArrowUp"?1:-1,e.shiftKey);else if(e.key==="Escape"){finished=true;onCancel()}else{e.stopPropagation();return}e.preventDefault();e.stopPropagation()}const inputValue=e=>e.currentTarget.value;
|
|
3
|
+
</script>
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
<span
|
|
9
|
+
class="sv-fte"
|
|
10
|
+
class:is-invalid={!!error}
|
|
11
|
+
bind:this={box}
|
|
12
|
+
onpointerdown={(e) => e.stopPropagation()}
|
|
13
|
+
onmousedown={(e) => e.stopPropagation()}
|
|
14
|
+
onclick={(e) => e.stopPropagation()}
|
|
15
|
+
ondblclick={(e) => e.stopPropagation()}
|
|
16
|
+
>
|
|
17
|
+
<input
|
|
18
|
+
bind:this={input}
|
|
19
|
+
class="sv-fte-input"
|
|
20
|
+
autocomplete="off"
|
|
21
|
+
spellcheck="false"
|
|
22
|
+
placeholder={p.timeFormat === '24hour' ? '14:05' : '2:05 PM'}
|
|
23
|
+
aria-label="Time of day"
|
|
24
|
+
aria-invalid={error ? 'true' : undefined}
|
|
25
|
+
value={text}
|
|
26
|
+
oninput={(e) => (text = inputValue(e))}
|
|
27
|
+
onkeydown={onKey}
|
|
28
|
+
/>
|
|
29
|
+
</span>
|
|
30
|
+
|
|
31
|
+
{#if noteAt && (error || (reads && reads !== text.trim()))}
|
|
32
|
+
<div class="sv-fte-note" class:is-error={!!error} role={error ? 'alert' : 'status'} use:portalToBody style:top={`${noteAt.top}px`} style:left={`${noteAt.left}px`}>
|
|
33
|
+
{error ?? reads}
|
|
34
|
+
</div>
|
|
35
|
+
{/if}
|
|
36
|
+
|
|
37
|
+
<style>
|
|
38
|
+
.sv-fte{position:absolute;inset:0;z-index:1;display:flex;align-items:center;padding:0 var(--sg-cell-px, 7px);box-sizing:border-box;background:var(--sg-input-bg, var(--sg-bg, #fff))}.sv-fte:focus-within{box-shadow:inset 0 0 0 2px var(--sg-accent, #2563eb)}.sv-fte.is-invalid{box-shadow:inset 0 0 0 2px var(--sg-danger, #dc2626)}.sv-fte-input{width:100%;min-width:0;height:100%;padding:0;margin:0;border:0;outline:none;background:none;color:var(--sg-fg, #0f172a);font:inherit;font-variant-numeric:tabular-nums}.sv-fte-note{position:fixed;z-index:2147483646;padding:3px 8px;border-radius:var(--sg-radius, 6px);pointer-events:none;background:var(--sg-fg, #0f172a);color:var(--sg-bg, #fff);font-size:12px;white-space:nowrap}.sv-fte-note.is-error{background:var(--sg-danger, #dc2626);color:#fff}
|
|
39
|
+
</style>
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
type $$ComponentProps = {
|
|
2
|
+
value: unknown;
|
|
3
|
+
typed?: boolean;
|
|
4
|
+
columnDef?: Record<string, unknown>;
|
|
5
|
+
onCommit: (v?: unknown) => void;
|
|
6
|
+
onCancel: () => void;
|
|
7
|
+
onCommitAndMove?: (v: unknown, direction: 1 | -1) => void;
|
|
8
|
+
onCommitAndMoveDown?: (v: unknown, up?: boolean) => void;
|
|
9
|
+
};
|
|
10
|
+
declare const TimeOfDayEditor: import("svelte").Component<$$ComponentProps, {}, "">;
|
|
11
|
+
type TimeOfDayEditor = ReturnType<typeof TimeOfDayEditor>;
|
|
12
|
+
export default TimeOfDayEditor;
|
|
@@ -1,11 +1,19 @@
|
|
|
1
|
+
import { type FieldUser } from './sources.svelte.js';
|
|
1
2
|
export type RecordComment = {
|
|
2
3
|
id: string;
|
|
3
4
|
rowId: string;
|
|
4
5
|
/** The table of `<SvBase tables>` the record is in. */
|
|
5
6
|
tableId?: string;
|
|
7
|
+
/**
|
|
8
|
+
* What was written. A mention is kept inline as `@[Name](userId)` (see
|
|
9
|
+
* `mentionToken`): the record view draws it as the person's current name,
|
|
10
|
+
* so a rename does not break it. `mentionText` gives the text with `@Name`.
|
|
11
|
+
*/
|
|
6
12
|
text: string;
|
|
7
13
|
at: number;
|
|
8
14
|
by?: string;
|
|
15
|
+
/** The ids of the people the text mentions, in order; absent when it mentions nobody. */
|
|
16
|
+
mentions?: string[];
|
|
9
17
|
};
|
|
10
18
|
/** Which record a comment store is asked about, beyond its row id. */
|
|
11
19
|
export type RecordCommentContext = {
|
|
@@ -14,10 +22,26 @@ export type RecordCommentContext = {
|
|
|
14
22
|
/** The grid's api. */
|
|
15
23
|
api: unknown;
|
|
16
24
|
};
|
|
25
|
+
/** What a mention hook hears: a comment that mentions people, once per comment. */
|
|
26
|
+
export type MentionEvent = {
|
|
27
|
+
comment: RecordComment;
|
|
28
|
+
/** The people it mentions; one not in `setFieldUsers` comes with the name written in the comment. */
|
|
29
|
+
mentioned: FieldUser[];
|
|
30
|
+
rowId: string;
|
|
31
|
+
/** The table of `<SvBase tables>` the record is in; undefined for a single table or a plain grid. */
|
|
32
|
+
tableId?: string;
|
|
33
|
+
/** The record's row object, when the grid still has it. */
|
|
34
|
+
record: Record<string, unknown> | undefined;
|
|
35
|
+
/** The grid's api. */
|
|
36
|
+
api: unknown;
|
|
37
|
+
};
|
|
38
|
+
export type MentionHandler = (event: MentionEvent) => void;
|
|
17
39
|
/** Where comments are kept: the app's backend, or memory by default. */
|
|
18
40
|
export type RecordCommentStore = {
|
|
19
41
|
list: (rowId: string, api: unknown, context: RecordCommentContext) => ReadonlyArray<RecordComment>;
|
|
20
42
|
add: (rowId: string, comment: RecordComment, api: unknown, context: RecordCommentContext) => void;
|
|
43
|
+
/** A comment that mentions people was added (after `add`): send the notifications here. */
|
|
44
|
+
onMention?: MentionHandler;
|
|
21
45
|
};
|
|
22
46
|
export type RecordChange = {
|
|
23
47
|
at: number;
|
|
@@ -59,6 +83,11 @@ export type ActivityScope = object | string | {
|
|
|
59
83
|
export declare function tableIdOf(ctrl: any): string | undefined;
|
|
60
84
|
/** Keep comments in the app's store (null: back to memory). */
|
|
61
85
|
export declare function setRecordComments(next: RecordCommentStore | null): void;
|
|
86
|
+
/**
|
|
87
|
+
* Hear every comment that mentions people, whichever store keeps it (memory
|
|
88
|
+
* too); null stops. A store's own `onMention` is called as well, first.
|
|
89
|
+
*/
|
|
90
|
+
export declare function setMentionHandler(next: MentionHandler | null): void;
|
|
62
91
|
/**
|
|
63
92
|
* Note a change to a cell (called after every edit, paste, fill and clear).
|
|
64
93
|
* `scope` is the grid, or the table (its base and id) for a change made
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getCurrentUser}from"./sources.svelte.js";let version=$state(0);const changes={bases:new WeakMap,grids:new WeakMap};const memory={bases:new WeakMap,grids:new WeakMap};const unseen={bases:new WeakMap,grids:new WeakMap};const ANY_BASE={};let store=null;export function tableIdOf(ctrl){const id=ctrl?.props?.baseTableId;return typeof id==="string"&&id?id:void 0}function rowsOf(kept,scope,create){const named=typeof scope==="string"?{tableId:scope}:"tableId"in scope&&typeof scope.tableId==="string"?scope:null;const tableId=named?named.tableId:tableIdOf(scope);if(!tableId){let byRow2=kept.grids.get(scope);if(!byRow2&&create)kept.grids.set(scope,byRow2=new Map);return byRow2}const base=(named?named.base:scope?.props?.baseScope)??ANY_BASE;let byTable=kept.bases.get(base);if(!byTable&&create)kept.bases.set(base,byTable=new Map);let byRow=byTable?.get(tableId);if(!byRow&&byTable&&create)byTable.set(tableId,byRow=new Map);return byRow}export function setRecordComments(next){store=next;version+=1}export function noteChange(scope,rowId,columnId,value,automation,via){const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];list.push({at:Date.now(),...automation?{automation}:{by:getCurrentUser()?.id},...via?{via}:{},columnId,value:Array.isArray(value)?[...value]:value});if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);version+=1}export function changesOf(scope,rowId){void version;return rowsOf(changes,scope,false)?.get(rowId)??[]}export function noteRemoteChange(scope,rowId,change){const at=Date.now();const fields=change.fields??[];if(!change.added&&!fields.length)return;const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];const by=change.by?{by:change.by}:{};if(change.added)list.push({at,...by,remote:true,added:true,columnId:"",value:void 0});for(const f of fields)list.push({at,...by,remote:true,columnId:f.columnId,value:copy(f.to),from:copy(f.from)});if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);const marks=rowsOf(unseen,scope,true);const was=marks.get(rowId)?.[0];const columns=new Set([...was?.columns??[],...fields.map(f=>f.columnId)]);marks.set(rowId,[{at,...by,columns,...change.added||was?.added?{added:true}:{}}]);version+=1}const copy=v=>Array.isArray(v)?[...v]:v;export function unseenOf(scope,rowId){void version;return rowsOf(unseen,scope,false)?.get(rowId)?.[0]}export function unseenIn(scope){void version;const out=new Map;for(const[id,list]of rowsOf(unseen,scope,false)??[])if(list[0])out.set(id,list[0]);return out}export function markSeen(scope,rowId){const marks=rowsOf(unseen,scope,false);if(marks?.delete(rowId))version+=1}export function markAllSeen(scope){const marks=rowsOf(unseen,scope,false);if(marks?.size){marks.clear();version+=1}}const contextOf=ctrl=>({tableId:tableIdOf(ctrl),api:ctrl?.buildApi?.()});export function commentsOf(ctrl,rowId){void version;if(store){const context=contextOf(ctrl);return store.list(rowId,context.api,context)}return rowsOf(memory,ctrl,false)?.get(rowId)??[]}let seq=0;export function addComment(ctrl,rowId,text){const body=text.trim();if(!body)return;const context=contextOf(ctrl);const comment={id:`c${Date.now().toString(36)}${seq+=1}`,rowId,...context.tableId?{tableId:context.tableId}:{},text:body,at:Date.now(),by:getCurrentUser()?.id};if(
|
|
1
|
+
import{untrack}from"svelte";import{findFieldUser,getCurrentUser}from"./sources.svelte.js";import{mentionIds,parseMentions}from"./mentions.js";let version=$state(0);const changes={bases:new WeakMap,grids:new WeakMap};const memory={bases:new WeakMap,grids:new WeakMap};const unseen={bases:new WeakMap,grids:new WeakMap};const ANY_BASE={};let store=null;let mentionHandler=null;export function tableIdOf(ctrl){const id=ctrl?.props?.baseTableId;return typeof id==="string"&&id?id:void 0}function rowsOf(kept,scope,create){const named=typeof scope==="string"?{tableId:scope}:"tableId"in scope&&typeof scope.tableId==="string"?scope:null;const tableId=named?named.tableId:tableIdOf(scope);if(!tableId){let byRow2=kept.grids.get(scope);if(!byRow2&&create)kept.grids.set(scope,byRow2=new Map);return byRow2}const base=(named?named.base:scope?.props?.baseScope)??ANY_BASE;let byTable=kept.bases.get(base);if(!byTable&&create)kept.bases.set(base,byTable=new Map);let byRow=byTable?.get(tableId);if(!byRow&&byTable&&create)byTable.set(tableId,byRow=new Map);return byRow}export function setRecordComments(next){store=next;untrack(()=>version+=1)}export function setMentionHandler(next){mentionHandler=next}export function noteChange(scope,rowId,columnId,value,automation,via){const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];list.push({at:Date.now(),...automation?{automation}:{by:getCurrentUser()?.id},...via?{via}:{},columnId,value:Array.isArray(value)?[...value]:value});if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);version+=1}export function changesOf(scope,rowId){void version;return rowsOf(changes,scope,false)?.get(rowId)??[]}export function noteRemoteChange(scope,rowId,change){const at=Date.now();const fields=change.fields??[];if(!change.added&&!fields.length)return;const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];const by=change.by?{by:change.by}:{};if(change.added)list.push({at,...by,remote:true,added:true,columnId:"",value:void 0});for(const f of fields)list.push({at,...by,remote:true,columnId:f.columnId,value:copy(f.to),from:copy(f.from)});if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);const marks=rowsOf(unseen,scope,true);const was=marks.get(rowId)?.[0];const columns=new Set([...was?.columns??[],...fields.map(f=>f.columnId)]);marks.set(rowId,[{at,...by,columns,...change.added||was?.added?{added:true}:{}}]);version+=1}const copy=v=>Array.isArray(v)?[...v]:v;export function unseenOf(scope,rowId){void version;return rowsOf(unseen,scope,false)?.get(rowId)?.[0]}export function unseenIn(scope){void version;const out=new Map;for(const[id,list]of rowsOf(unseen,scope,false)??[])if(list[0])out.set(id,list[0]);return out}export function markSeen(scope,rowId){const marks=rowsOf(unseen,scope,false);if(marks?.delete(rowId))version+=1}export function markAllSeen(scope){const marks=rowsOf(unseen,scope,false);if(marks?.size){marks.clear();version+=1}}const contextOf=ctrl=>({tableId:tableIdOf(ctrl),api:ctrl?.buildApi?.()});const commentScope=ctrl=>{const tableId=tableIdOf(ctrl);return tableId?{tableId}:ctrl};export function commentsOf(ctrl,rowId){void version;if(store){const context=contextOf(ctrl);return store.list(rowId,context.api,context)}return rowsOf(memory,commentScope(ctrl),false)?.get(rowId)??[]}let seq=0;export function addComment(ctrl,rowId,text){const body=text.trim();if(!body)return;const context=contextOf(ctrl);const mentions=mentionIds(body);const comment={id:`c${Date.now().toString(36)}${seq+=1}`,rowId,...context.tableId?{tableId:context.tableId}:{},text:body,at:Date.now(),by:getCurrentUser()?.id,...mentions.length?{mentions}:{}};const kept=store;if(kept)kept.add(rowId,comment,context.api,context);else{const byRow=rowsOf(memory,commentScope(ctrl),true);byRow.set(rowId,[...byRow.get(rowId)??[],comment])}version+=1;if(!mentions.length||!kept?.onMention&&!mentionHandler)return;const written=new Map(parseMentions(body).flatMap(p=>"mention"in p?[[p.mention,p.name]]:[]));const event={comment,mentioned:mentions.map(id=>findFieldUser(id)??{id,name:written.get(id)||id}),rowId,...context.tableId?{tableId:context.tableId}:{},record:(ctrl?.allRows??[]).find(r=>r.id===rowId)?.original,api:context.api};for(const hook of[kept?.onMention,mentionHandler]){try{hook?.(event)}catch(err){console.error(err)}}}export function timeAgo(at,now=Date.now()){const s=Math.max(0,Math.round((now-at)/1e3));if(s<45)return"just now";const m=Math.round(s/60);if(m<60)return`${m} minute${m===1?"":"s"} ago`;const h=Math.round(m/60);if(h<24)return`${h} hour${h===1?"":"s"} ago`;return new Date(at).toLocaleDateString()}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { type FieldTypeDef } from './registry.svelte.js';
|
|
2
|
+
export type { AIFieldProps, AIFieldOutput } from './ai-prompt.js';
|
|
3
|
+
/** A cell's generation, while it waits or runs, or after it failed. Nothing once its value is written. */
|
|
4
|
+
export type AIFieldCellState = {
|
|
5
|
+
status: 'queued' | 'running' | 'error';
|
|
6
|
+
message?: string;
|
|
7
|
+
};
|
|
8
|
+
/** What `generateAIField` did: values written, and cells that failed or were cancelled. */
|
|
9
|
+
export type AIFieldRun = {
|
|
10
|
+
written: number;
|
|
11
|
+
failed: number;
|
|
12
|
+
};
|
|
13
|
+
export declare const NO_PROVIDER = "No AI provider. The app sets one with setAIProvider() from @svgrid/grid.";
|
|
14
|
+
export declare const AI_ICON = "M10 3l1.8 5.2L17 10l-5.2 1.8L10 17l-1.8-5.2L3 10l5.2-1.8zM18 14l.9 2.1L21 17l-2.1.9L18 20l-.9-2.1L15 17l2.1-.9z";
|
|
15
|
+
/** A cell's generation state (reactive), or undefined when nothing is pending or failed. */
|
|
16
|
+
export declare function aiCellState(ctrl: object, rowId: string, columnId: string): AIFieldCellState | undefined;
|
|
17
|
+
/** How many requests run at once, over every grid on the page. Default 3. */
|
|
18
|
+
export declare function setAIFieldConcurrency(n: number): void;
|
|
19
|
+
/**
|
|
20
|
+
* Generate the AI field `columnId` for records of a grid (its api, or the
|
|
21
|
+
* grid itself): 'empty' (default) the records whose cell is empty, 'all'
|
|
22
|
+
* every record the grid shows, or the records with these ids. Resolves when
|
|
23
|
+
* they are all written, failed or cancelled.
|
|
24
|
+
*/
|
|
25
|
+
export declare function generateAIField(target: unknown, columnId: string, which?: 'empty' | 'all' | ReadonlyArray<string>): Promise<AIFieldRun>;
|
|
26
|
+
/** Stop a grid's generations (of one field, or all): queued ones are dropped, running ones aborted. */
|
|
27
|
+
export declare function cancelAIField(target: unknown, columnId?: string): void;
|
|
28
|
+
/** Cells of a grid's field waiting or running. */
|
|
29
|
+
export declare function pendingAIField(target: unknown, columnId?: string): number;
|
|
30
|
+
/** One cell, from its button. Clears an earlier error first. */
|
|
31
|
+
export declare function generateAICell(ctrl: any, rowId: string, columnId: string): Promise<boolean>;
|
|
32
|
+
/** Forget a cell's error (the person edited the value by hand). */
|
|
33
|
+
export declare function clearAICellError(ctrl: object, rowId: string, columnId: string): void;
|
|
34
|
+
/** Called by each AI cell as it mounts; the returned function as it unmounts. */
|
|
35
|
+
export declare function holdAIGrid(ctrl: object): () => void;
|
|
36
|
+
/**
|
|
37
|
+
* After an edit (the grid's `cellEdited`): every AI field with `auto` on
|
|
38
|
+
* whose prompt names the edited field generates again for that record. A
|
|
39
|
+
* record whose named fields are all empty is left alone.
|
|
40
|
+
*/
|
|
41
|
+
export declare function aiFieldEdited(ctrl: any, row: unknown, columnId: string): void;
|
|
42
|
+
/** A record changed outside the grid: `BaseRemoteChange` from `<SvBase onRemoteChange>`, or one the app makes. */
|
|
43
|
+
export type AIFieldChange = {
|
|
44
|
+
/** The record's id. */
|
|
45
|
+
id: string;
|
|
46
|
+
/** The base table's id; a change to a table other than the grid's is skipped. */
|
|
47
|
+
table?: string;
|
|
48
|
+
/** 'insert' generates the record's empty AI fields; 'delete' is skipped. Default 'update'. */
|
|
49
|
+
type?: 'insert' | 'update' | 'delete';
|
|
50
|
+
/** The fields that moved, by field key. */
|
|
51
|
+
fields?: ReadonlyArray<{
|
|
52
|
+
field: string;
|
|
53
|
+
}>;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Generate the AI fields with `auto` on that changes made outside the grid
|
|
57
|
+
* set off, as an edit in the grid would: for an update, the fields whose
|
|
58
|
+
* prompt names a field that moved (unless the change wrote the AI field
|
|
59
|
+
* itself); for an insert, the record's empty ones. Only records of the table
|
|
60
|
+
* the grid shows.
|
|
61
|
+
*
|
|
62
|
+
* Nothing calls this by itself: a change made in another `<SvBase>` was
|
|
63
|
+
* generated in that page, and its value arrives as a change of its own. Call
|
|
64
|
+
* it for changes nothing generated (a server job, a script, a database
|
|
65
|
+
* console), from one page only, or every page that hears the change calls
|
|
66
|
+
* the model and writes.
|
|
67
|
+
*/
|
|
68
|
+
export declare function regenerateAIFields(target: unknown, changes: ReadonlyArray<AIFieldChange>): Promise<AIFieldRun>;
|
|
69
|
+
/** The column menu's items for an AI field (`fieldMenu`): generate the empty cells or all, or stop. */
|
|
70
|
+
export declare function aiFieldMenuItems(ctrl: any, columnId: string, def: Record<string, any> | undefined): {
|
|
71
|
+
key: string;
|
|
72
|
+
label: string;
|
|
73
|
+
icon: string;
|
|
74
|
+
separatorBefore: boolean;
|
|
75
|
+
run: () => void;
|
|
76
|
+
}[] | ({
|
|
77
|
+
key: string;
|
|
78
|
+
label: string;
|
|
79
|
+
icon: string;
|
|
80
|
+
separatorBefore: boolean;
|
|
81
|
+
disabled: boolean;
|
|
82
|
+
run: () => undefined;
|
|
83
|
+
} | {
|
|
84
|
+
key: string;
|
|
85
|
+
label: string;
|
|
86
|
+
icon: string;
|
|
87
|
+
disabled: boolean;
|
|
88
|
+
run: () => undefined;
|
|
89
|
+
separatorBefore?: undefined;
|
|
90
|
+
})[];
|
|
91
|
+
export declare const AI_FIELD_TYPE: FieldTypeDef<any>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{tick}from"svelte";import{getAIProvider}from"@svgrid/grid";import{fieldPropsOf,getFieldType,originalColumn}from"./registry.svelte.js";import{canEditField}from"./field-access.svelte.js";import{cellText,cellValue,dataRows,fieldColumns,gridOf,writeCell}from"./grid-access.js";import{aiFieldRequest,fillPrompt,promptColumn,promptRefs,readAIAnswer}from"./ai-prompt.js";import AiCell from"./AiCell.svelte";export const NO_PROVIDER="No AI provider. The app sets one with setAIProvider() from @svgrid/grid.";const NOT_EDITABLE="You cannot edit this field, so nothing was written.";const NOT_SHOWN="The record is not in the grid (filtered out or deleted).";export const AI_ICON="M10 3l1.8 5.2L17 10l-5.2 1.8L10 17l-1.8-5.2L3 10l5.2-1.8zM18 14l.9 2.1L21 17l-2.1.9L18 20l-.9-2.1L15 17l2.1-.9z";const gridKeys=new WeakMap;let nextGrid=1;const gridKey=ctrl=>{let k=gridKeys.get(ctrl);if(!k)gridKeys.set(ctrl,k=nextGrid++);return k};const keyOf=(ctrl,rowId,columnId)=>`${gridKey(ctrl)}\0${rowId}\0${columnId}`;const cells=$state({});export function aiCellState(ctrl,rowId,columnId){return cells[keyOf(ctrl,rowId,columnId)]}const setCell=(key,s)=>{if(s)cells[key]=s;else delete cells[key]};const queue=[];const active=new Set;const latest=new Map;let limit=3;export function setAIFieldConcurrency(n){limit=Math.max(1,Math.floor(n)||1);pump()}const alive=ctrl=>{const el=ctrl?.scrollContainer;return!el||el.isConnected};function enqueue(ctrl,rowId,columnId){const key=keyOf(ctrl,rowId,columnId);const was=latest.get(key);if(was&&queue.includes(was))return new Promise(r=>{const prev=was.done;was.done=ok=>{prev(ok);r(ok)}});if(was)was.abort.abort();return new Promise(done=>{const job={ctrl,rowId,columnId,key,abort:new AbortController,done};latest.set(key,job);queue.push(job);setCell(key,{status:"queued"});pump()})}function pump(){while(active.size<limit&&queue.length){const job=queue.shift();if(!alive(job.ctrl)){queue.unshift(job);cancelAIField(job.ctrl);continue}active.add(job);setCell(job.key,{status:"running"});void run(job).finally(()=>{active.delete(job);pump()})}}async function run(job){const signal=job.abort.signal;try{const value=await produce(job.ctrl,job.rowId,job.columnId,signal);while(job.ctrl.editingCell&&!signal.aborted)await new Promise(r=>setTimeout(r,150));if(signal.aborted)return job.done(false);if(!alive(job.ctrl)){cancelAIField(job.ctrl);return job.done(false)}if(!writeKeepingCursor(job.ctrl,job.rowId,job.columnId,value))throw new Error(NOT_EDITABLE);if(latest.get(job.key)===job){latest.delete(job.key);setCell(job.key,null)}job.done(true)}catch(e){if(!signal.aborted&&latest.get(job.key)===job){latest.delete(job.key);setCell(job.key,{status:"error",message:messageOf(e)})}job.done(false)}}const messageOf=e=>{const m=e instanceof Error?e.message:String(e??"The request failed");return m.length>240?`${m.slice(0,240)}...`:m};function fieldOf(ctrl,columnId){const columns=fieldColumns(ctrl);const column=columns.find(c=>c.id===columnId);if(!column||column.fieldType!=="ai")return null;const props=fieldPropsOf(originalColumn(column.def));const named=columns.map(c=>({header:c.header,field:c.field,c}));return{column,props,named}}const shown=(ctrl,row,c)=>cellText(c,cellValue(ctrl,row,c),row);async function produce(ctrl,rowId,columnId,signal){const f=fieldOf(ctrl,columnId);if(!f)throw new Error("The field is no longer an AI field.");const provider=getAIProvider();if(!provider)throw new Error(NO_PROVIDER);if(!String(f.props.prompt??"").trim())throw new Error("The field has no prompt yet: write one in Edit field.");if(!canEditField(originalColumn(f.column.def),f.props))throw new Error(NOT_EDITABLE);const row=dataRows(ctrl).find(r=>r.id===rowId);if(!row)throw new Error(NOT_SHOWN);const filled=fillPrompt(String(f.props.prompt),name=>{const hit=promptColumn(f.named,name);return hit?shown(ctrl,row,hit.c):`{${name}}`});const raw=await provider(aiFieldRequest(f.column.header,filled,f.props,signal));return readAIAnswer(raw,f.props)}function writeKeepingCursor(ctrl,rowId,columnId,value){const cursor=ctrl.grid?.getState?.().activeCell??null;const range=ctrl.selectionRange;const ranges=ctrl.selectionRanges;const activated=ctrl.userHasActivatedCell;if(!writeCell(ctrl,rowId,columnId,value))return false;try{ctrl.grid?.setActiveCell?.(cursor);if(range!==void 0)ctrl.selectionRange=range;if(ranges!==void 0)ctrl.selectionRanges=ranges;if(activated!==void 0)ctrl.userHasActivatedCell=activated}catch{}return true}const ctrlOf=target=>gridOf(target)??target;const blank=v=>v==null||v===""||Array.isArray(v)&&!v.length;export async function generateAIField(target,columnId,which="empty"){const ctrl=ctrlOf(target);const f=fieldOf(ctrl,columnId);if(!f)return{written:0,failed:0};const ids=typeof which==="string"?dataRows(ctrl).filter(r=>which==="all"||blank(cellValue(ctrl,r,f.column))).map(r=>r.id):[...which];const results=await Promise.all(ids.map(id=>enqueue(ctrl,id,columnId)));const written=results.filter(Boolean).length;return{written,failed:results.length-written}}export function cancelAIField(target,columnId){const ctrl=ctrlOf(target);const mine=j=>j.ctrl===ctrl&&(columnId==null||j.columnId===columnId);for(let i=queue.length-1;i>=0;i--){const j=queue[i];if(!mine(j))continue;queue.splice(i,1);j.abort.abort();j.done(false)}for(const j of active)if(mine(j))j.abort.abort();for(const[key,j]of latest){if(!mine(j))continue;latest.delete(key);setCell(key,null)}}export function pendingAIField(target,columnId){const ctrl=ctrlOf(target);let n=0;for(const j of latest.values())if(j.ctrl===ctrl&&(columnId==null||j.columnId===columnId))n+=1;return n}export function generateAICell(ctrl,rowId,columnId){return enqueue(ctrl,rowId,columnId)}export function clearAICellError(ctrl,rowId,columnId){const key=keyOf(ctrl,rowId,columnId);if(cells[key]?.status==="error")setCell(key,null)}const drawn=new WeakMap;export function holdAIGrid(ctrl){drawn.set(ctrl,(drawn.get(ctrl)??0)+1);return()=>{const n=(drawn.get(ctrl)??1)-1;drawn.set(ctrl,n);if(n===0)setTimeout(()=>{const el=ctrl.scrollContainer;if(!drawn.get(ctrl)&&!el?.isConnected)cancelAIField(ctrl)},0)}}export function aiFieldEdited(ctrl,row,columnId){const columns=fieldColumns(ctrl);const edited=columns.find(c=>c.id===columnId);if(!edited||!row||!columns.some(c=>c.fieldType==="ai"&&c.id!==columnId))return;const id=ctrl.buildApi?.().getRowId?.(row);const gridRow=dataRows(ctrl).find(r=>id!=null?r.id===String(id):r.original===row);if(!gridRow)return;for(const ai of autoFieldsFor(ctrl,gridRow,columns,[edited]))void enqueue(ctrl,gridRow.id,ai.id)}function autoFieldsFor(ctrl,row,columns,moved){const named=columns.map(c=>({header:c.header,field:c.field,c}));return columns.filter(ai=>{if(ai.fieldType!=="ai"||moved?.includes(ai))return false;const p=fieldPropsOf(originalColumn(ai.def));if(p.auto===false||!String(p.prompt??"").trim())return false;const refs=promptRefs(String(p.prompt),named).map(x=>x.c);if(moved?!refs.some(c=>moved.includes(c)):!blank(cellValue(ctrl,row,ai)))return false;return refs.some(c=>shown(ctrl,row,c).trim())})}export async function regenerateAIFields(target,changes){const ctrl=ctrlOf(target);await tick();const table=ctrl?.props?.baseTableId;const columns=fieldColumns(ctrl);const runs=[];if(columns.some(c=>c.fieldType==="ai")){for(const change of changes){if(change.type==="delete"||table&&change.table&&change.table!==table)continue;const row=dataRows(ctrl).find(r=>r.id===String(change.id));if(!row)continue;const moved=change.type==="insert"?null:columns.filter(c=>change.fields?.some(f=>f.field===c.field));if(moved&&!moved.length)continue;for(const ai of autoFieldsFor(ctrl,row,columns,moved))runs.push(enqueue(ctrl,row.id,ai.id))}}const results=await Promise.all(runs);const written=results.filter(Boolean).length;return{written,failed:results.length-written}}export function aiFieldMenuItems(ctrl,columnId,def){if(def?.fieldType!=="ai")return[];const waiting=pendingAIField(ctrl,columnId);if(waiting){return[{key:"field-ai-stop",label:`Stop generating (${waiting} left)`,icon:AI_ICON,separatorBefore:true,run:()=>cancelAIField(ctrl,columnId)}]}const f=fieldOf(ctrl,columnId);const rows=f?dataRows(ctrl):[];const empty=f?rows.filter(r=>blank(cellValue(ctrl,r,f.column))).length:0;const locked=!f||!ctrl.editingEnabled||!canEditField(originalColumn(f.column.def),f.props);const records=n=>`${n} ${n===1?"record":"records"}`;return[{key:"field-ai-empty",label:`Generate for ${empty} empty ${empty===1?"record":"records"}`,icon:AI_ICON,separatorBefore:true,disabled:locked||!empty,run:()=>void generateAIField(ctrl,columnId,"empty")},{key:"field-ai-all",label:`Generate for all ${records(rows.length)}`,icon:AI_ICON,disabled:locked||!rows.length,run:()=>void generateAIField(ctrl,columnId,"all")}]}const PRECISION=Array.from({length:5},(_,d)=>({value:String(d),label:d===0?"1":`1.${"0".repeat(d)}`}));export const AI_FIELD_TYPE={id:"ai",label:"AI",description:"A model writes the value from a prompt that names the record's fields. Stored, and editable by hand.",icon:AI_ICON,group:"computed",width:280,defaults:{prompt:"",output:"text",auto:true,options:[]},properties:[{key:"prompt",label:"Prompt",kind:"prompt",placeholder:"Write a one-line pitch for {Name}, aimed at {Audience}",hint:"Use {Field name} for that field's value in the record."},{key:"output",label:"The model writes",kind:"segmented",choices:[{value:"text",label:"Text"},{value:"singleSelect",label:"One option"},{value:"number",label:"A number"}]},{key:"options",label:"Options",kind:"options",visible:p=>p.output==="singleSelect"},{key:"precision",label:"Precision",kind:"choice",choices:PRECISION,visible:p=>p.output==="number"},{key:"auto",label:"Generate again when a field the prompt names changes",kind:"checkbox",hint:"Off: only when someone presses the button or uses the column menu."}],fill:(d,p,ctx)=>{const as=p.output==="singleSelect"?"singleSelect":p.output==="number"?"number":"longText";const type=getFieldType(as);const props=as==="singleSelect"?{options:p.options??[]}:as==="number"?{...type?.defaults??{},format:"decimal",precision:p.precision??1}:{};return type?.fill?type.fill(d,props,ctx):{...d}},cell:AiCell};
|
|
@@ -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}}
|