@svgrid/enterprise 3.1.44 → 3.1.46
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/cdn/svgrid-enterprise.svelte-external.js +1 -1
- package/dist/designer/assets/{index-CltOvNJn.js → index-BBI_8Aky.js} +214 -214
- package/dist/designer/index.html +1 -1
- package/dist/fields/BaseTableView.svelte +3 -2
- package/dist/fields/BaseTabs.svelte +26 -6
- package/dist/fields/FieldEditor.svelte +1 -1
- package/dist/fields/FieldEditor.svelte.d.ts +3 -0
- package/dist/fields/FieldsHeaderEnd.svelte +1 -1
- package/dist/fields/FormulaInput.svelte +122 -0
- package/dist/fields/FormulaInput.svelte.d.ts +10 -0
- package/dist/fields/FormulaInputHarness.svelte +5 -0
- package/dist/fields/FormulaInputHarness.svelte.d.ts +11 -0
- package/dist/fields/NumberEditor.svelte +1 -1
- package/dist/fields/PasteFields.svelte +33 -0
- package/dist/fields/PasteFields.svelte.d.ts +6 -0
- package/dist/fields/PropertyInput.svelte +4 -8
- package/dist/fields/SvBase.svelte +1 -1
- package/dist/fields/SvBase.svelte.d.ts +7 -0
- package/dist/fields/SvBaseViewBar.svelte +2 -2
- package/dist/fields/barcode-scan.d.ts +15 -4
- package/dist/fields/barcode-scan.js +1 -1
- package/dist/fields/base-import.js +2 -2
- package/dist/fields/celebrate.d.ts +29 -0
- package/dist/fields/celebrate.js +1 -0
- package/dist/fields/cell-colors.svelte.d.ts +17 -0
- package/dist/fields/cell-colors.svelte.js +1 -0
- package/dist/fields/editor-request.svelte.d.ts +7 -0
- package/dist/fields/excel-habits.svelte.d.ts +98 -0
- package/dist/fields/excel-habits.svelte.js +1 -0
- package/dist/fields/formula-docs.d.ts +24 -0
- package/dist/fields/formula-docs.js +1 -0
- package/dist/fields/index.d.ts +2 -0
- package/dist/fields/index.js +1 -1
- package/dist/fields/messages/fields.d.ts +28 -0
- package/dist/fields/messages/fields.js +1 -1
- package/dist/fields/messages/record.d.ts +1 -0
- package/dist/fields/messages/record.js +1 -1
- package/dist/fields/messages/shell.d.ts +24 -0
- package/dist/fields/messages/shell.js +1 -1
- package/dist/fields/messages/viewbar.d.ts +9 -0
- package/dist/fields/messages/viewbar.js +1 -1
- package/dist/fields/messages.svelte.d.ts +62 -0
- package/dist/fields/view-model.d.ts +3 -0
- package/dist/fields/view-model.js +1 -1
- package/dist/fields/viewbar/ColorPanel.svelte +54 -2
- package/dist/fields/viewbar/ColorPanel.svelte.d.ts +3 -0
- package/dist/node/studio.js +1 -1
- package/dist/version.d.ts +2 -2
- package/dist/version.js +1 -1
- package/dist/wc/sv-base-element.js +101 -96
- package/dist/wc/sv-sheet-element.js +43 -43
- package/package.json +3 -3
|
@@ -170,6 +170,13 @@ type $$ComponentProps = {
|
|
|
170
170
|
readOnly?: boolean | BaseShare;
|
|
171
171
|
/** The search box in the tab bar, over every table's records (default true; Ctrl+K focuses it). */
|
|
172
172
|
search?: boolean;
|
|
173
|
+
/**
|
|
174
|
+
* Fireworks for a moment where someone finishes a record: a single select set
|
|
175
|
+
* to Done, Completed, Shipped, Paid or Won, or a Done checkbox ticked (see
|
|
176
|
+
* celebrate.ts). Default false; never for an undo, a block of cells, or
|
|
177
|
+
* someone whose system asks for less motion.
|
|
178
|
+
*/
|
|
179
|
+
celebrate?: boolean;
|
|
173
180
|
/**
|
|
174
181
|
* What the signed-in person may do: `{ canCreate, canDelete, canEditSchema,
|
|
175
182
|
* canEditViews, canComment, fields, viewsOnly }`. A table's own
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
-
import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";import{conditionCount,isGroup,isComplete}from"./filter-model";import{dataRows,fieldColumns,gridOf,groupLeaves,leafFilter,primaryIdOf}from"./grid-access";import{barcodeScanSupported,scanBarcode}from"./barcode-scan";import{findFieldUser,getCurrentUser,getLinkedTable,linkedRows}from"./sources.svelte";import{PLAIN_STATE,applyColor,applyGanttSettings,applyView,boardConfig,captureView,galleryConfig,colorSettingOf,newViewId,viewTypeInfo}from"./view-model";import{groupRules,userSorts}from"./viewbar/sort-state";import{recordHeightOf,syncGroupRowHeight}from"./row-height";import HideFieldsPanel from"./viewbar/HideFieldsPanel.svelte";import FilterPanel from"./viewbar/FilterPanel.svelte";import SortPanel from"./viewbar/SortPanel.svelte";import ColorPanel from"./viewbar/ColorPanel.svelte";import ChartPanel from"./viewbar/ChartPanel.svelte";import GanttPanel from"./viewbar/GanttPanel.svelte";import ListPanel from"./viewbar/ListPanel.svelte";import FormBuilder from"./viewbar/FormBuilder.svelte";import ViewsMenu from"./viewbar/ViewsMenu.svelte";import RecordView from"./RecordView.svelte";import{closeRecord,getRecordRequest,closeFieldEditor,getFieldEditorRequest,getDeleteFieldRequest,askDeleteField,openRecord}from"./editor-request.svelte";import FieldEditor from"./FieldEditor.svelte";import DeleteFieldConfirm from"./DeleteFieldConfirm.svelte";import DeleteRecordConfirm from"./DeleteRecordConfirm.svelte";import{askDeleteRecord,getDeleteRecordRequest}from"./record-delete.svelte";import{clearBarRequest,getBarRequest,registerBar}from"./bar-request.svelte";import{bm,bmCount}from"./messages.svelte";let{api,views=$bindable([{id:"grid",name:bm("viewbar.defaultViewName"),type:"grid"}]),activeView=$bindable(""),onViewsChange,onViewRemoved,viewTypes,automations=null,changed=null,lockViews=true,manageViews=true,viewList=true,rowHeights,host=null,tableId}=$props();let barEl=$state(null);$effect(()=>{const el=barEl;const into=host;if(!el||!into)return;const home=document.createComment("");el.before(home);into.appendChild(el);return()=>{if(home.parentNode){home.after(el);home.remove()}else el.remove()}});const heights=$derived(rowHeights??[{label:bm("viewbar.rowShort"),height:34},{label:bm("viewbar.rowMedium"),height:56},{label:bm("viewbar.rowTall"),height:88},{label:bm("viewbar.rowExtraTall"),height:128}]);const ctrl=$derived(api?gridOf(api):void 0);const me=$derived(getCurrentUser()?.id);const visible=$derived(views.filter(v=>!v.personal||!me||v.personal===me));const active=$derived(visible.find(v=>v.id===activeView)??visible[0]??views[0]);const locked=$derived(!!active?.locked);let lockedDirty=$state(false);let lockedBaseline=null;const lockTitle=$derived.by(()=>{const by=active?.lockedBy?findFieldUser(active.lockedBy)?.name:void 0;return by?bm("viewbar.lockedTitleBy",{name:by}):bm("viewbar.lockedTitle")});const types=$derived(viewTypes??["grid","kanban","calendar","gantt"]);const linkNames=(table,value)=>{const t=getLinkedTable(table);return t?linkedRows(t,value).map(r=>String(r[t.primaryField]??"")):[]};const primaryField=$derived.by(()=>{if(!ctrl)return void 0;const id=primaryIdOf(ctrl);return fieldColumns(ctrl).find(c=>c.id===id)?.field});let appliedId=null;let appliedKey="";let applying=false;let showSeq=0;let showing=null;let viewShown=$state(0);let takingUp=false;const keyOf=v=>JSON.stringify(v);function setViews(next){views=next;const shown=next.find(v=>v.id===appliedId);if(shown)appliedKey=keyOf(shown);onViewsChange?.(next)}async function ready(t){if(t==="kanban")(await import("../board")).enableBoardView();else if(t==="calendar"||t==="timeline")(await import("../scheduler")).enableSchedulerView();else if(t==="gallery")(await import("../gallery")).enableGalleryView();else if(t==="gantt")(await import("../gantt")).enableGanttView()}async function show(view){const seq=showSeq+=1;appliedId=view.id;appliedKey=keyOf(view);applying=true;lockedDirty=false;lockedBaseline=null;const another=showing!==view.id;showing=view.id;if(another)ctrl?.props.baseFeed?.forgetCount?.();await ready(view.type);if(seq!==showSeq)return;applying=false;if(!ctrl)return;if(another){lastServerCount=null;takingUp=true;ctrl.props.rowModel?.letRowsGo?.();viewShown+=1;setTimeout(()=>{takingUp=false;viewShown+=1})}applyView(ctrl,api,view,{primaryField,linkNames});colorSetting=view.color??colorSettingOf(ctrl)}const capture=v=>captureView(ctrl,api,{...v,color:$state.snapshot(colorSetting)});const keptViews=()=>views.map(v=>v.id===active?.id&&!v.locked?capture(v):v);function switchTo(id){viewsOpen=false;if(!ctrl||!active||id===active.id)return;const next=keptViews();const target=next.find(v=>v.id===id);if(!target)return;setViews(next);activeView=id;void show(target)}function create(partial){if(!ctrl||!active)return;const select=columns.find(c=>c.fieldType==="singleSelect");const timed=partial.type==="calendar"||partial.type==="timeline"||partial.type==="gantt";const view={...partial,id:newViewId(),state:{...PLAIN_STATE},color:timed&&select?{mode:"field",field:select.field}:{mode:"none"}};const next=[...keptViews(),view];setViews(next);activeView=view.id;void show(view);viewsOpen=false}function duplicate(id){if(!ctrl)return;const src=id===active?.id&&!active.locked?capture(active):views.find(v=>v.id===id);if(!src)return;const{locked:_locked,lockedBy:_by,...open}=JSON.parse(JSON.stringify(src));const copy={...open,id:newViewId(),name:bm("viewbar.viewCopy",{name:src.name}),...!manageViews&&me?{personal:me}:{}};const at=views.findIndex(v=>v.id===id);const next=[...views];next.splice(at+1,0,copy);setViews(next)}function remove(id){if(views.length<2||views.find(v=>v.id===id)?.locked)return;const at=views.findIndex(v=>v.id===id);const gone=id===active?.id?capture(views[at]):views[at];const next=views.filter(v=>v.id!==id);setViews(next);if(gone)onViewRemoved?.(gone,at);if(id===active?.id){const first=next.find(v=>!v.personal||!me||v.personal===me)??next[0];activeView=first.id;void show(first)}}function toggleLock(id){if(!lockViews)return;setViews(views.map(v=>{if(v.id!==id)return v;if(v.locked){const{locked:_locked,lockedBy:_by,...open}=v;return open}const kept=v.id===active?.id?capture(v):v;return{...kept,locked:true,...me?{lockedBy:me}:{}}}));lockedDirty=false;lockedBaseline=null}function resetLocked(){if(active)void show(active)}const rename=(id,name)=>setViews(views.map(v=>v.id===id?{...v,name}:v));const setSection=(id,section)=>setViews(views.map(v=>{if(v.id!==id)return v;const{section:_was,...rest}=v;return section?{...rest,section:section.slice(0,60)}:rest}));function setGantt(next){if(!ctrl||!active)return;const updated={...active,...next};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}const NO_CHART={kind:"bar",x:""};const setChart=chart=>setViews(views.map(v=>v.id===active?.id?{...v,chart}:v));const setList=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));const setForm=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));let formOpen=$state(false);$effect(()=>{if(!ctrl||!active)return;const view=active;const key=keyOf(view);untrack(()=>{if(!activeView)activeView=view.id;if(view.id===appliedId&&key===appliedKey)return;if(appliedId===null&&!(view.state||view.type!=="grid"||view.color||view.rowHeight!=null)){appliedId=view.id;appliedKey=key;return}void show(view)})});$effect(()=>{if(!ctrl||!active)return;const snapshot=JSON.stringify([ctrl.gridStateVersion,api.getState(),recordHeightOf(api.getOption("rowHeight")),effectiveColor]);const view=active;const timer=setTimeout(()=>{untrack(()=>{if(applying||view.id!==appliedId||keyOf(view)!==appliedKey)return;const kept=capture(view);const before=JSON.stringify([view.state,view.rowHeight,view.color]);const after=JSON.stringify([kept.state,kept.rowHeight,kept.color]);if(view.locked){const{expanded:_open,...shown}=kept.state??{};const now=JSON.stringify([shown,kept.rowHeight,kept.color]);if(lockedBaseline===null)lockedBaseline=now;else lockedDirty=now!==lockedBaseline}else if(before!==after)setViews(views.map(v=>v.id===view.id?kept:v))})},400);void snapshot;return()=>clearTimeout(timer)});let viewsOpen=$state(false);let panel=$state(null);function setPanel(p,open){if(open)panel=p;else if(panel===p)panel=null}$effect(()=>{if(ctrl)return registerBar(ctrl)});$effect(()=>{const r=getBarRequest();if(!r||r.ctrl!==ctrl)return;untrack(()=>{if(!locked)panel=r.panel;clearBarRequest()})});let colorSetting=$state({mode:"none"});$effect(()=>{if(ctrl)untrack(()=>colorSetting=active?.color??colorSettingOf(ctrl))});function setColor(s){colorSetting=s;if(ctrl)applyColor(ctrl,s,linkNames);if(ctrl&&active&&(active.type==="calendar"||active.type==="timeline"||active.type==="gantt")){const updated={...active,color:$state.snapshot(s)};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}}const columns=$derived(ctrl?fieldColumns(ctrl):[]);const hiddenCount=$derived(columns.filter(c=>!c.visible).length);const filter=$derived.by(()=>{const f=ctrl?.advancedFilter;return f?.kind==="fieldFilter"?f:null});const filterCount=$derived(conditionCount(filter));const filterLabel=$derived.by(()=>{if(!filter||!filterCount)return bm("viewbar.filter");const ids=new Set;for(const c of filter.conditions)for(const x of isGroup(c)?c.conditions:[c])if(isComplete(x))ids.add(x.column);if(ids.size===1){const header=columns.find(c=>ids.has(c.id))?.header;return header!=null?bm("viewbar.filteredBy",{field:header}):bmCount("viewbar.filteredByFields",1)}return bmCount("viewbar.filteredByFields",ids.size)});const groupCount=$derived(ctrl?groupRules(ctrl).length:0);const sortCount=$derived(ctrl?userSorts(ctrl).length:0);const effectiveColor=$derived(ctrl?colorSettingOf(ctrl,colorSetting):colorSetting);const colorLabel=$derived.by(()=>{if(effectiveColor.mode==="field"){const header=columns.find(c=>c.field===effectiveColor.field)?.header;return header!=null?bm("viewbar.coloredBy",{field:header}):bm("viewbar.color")}return effectiveColor.mode==="conditions"&&effectiveColor.rules.length?bm("viewbar.coloredByConditions"):bm("viewbar.color")});const rowHeight=$derived(recordHeightOf(api?.getOption?.("rowHeight"))??0);let heightOpen=$state(false);const shownHeight=$derived(heights.some(h=>h.height===rowHeight)?rowHeight:heights[0]?.height);$effect(()=>{const grouped=groupCount>0;void rowHeight;void ctrl?.props?.rowModel;untrack(()=>syncGroupRowHeight(ctrl,api,grouped))});let lastServerCount=null;const records=$derived.by(()=>{void viewShown;if(!ctrl)return 0;if(ctrl.props.baseFeed&&!ctrl.props.rowModel&&active?.type!=="form")return ctrl.props.baseFeed.knownCount();const model=ctrl.props.rowModel;if(model?.getState){void ctrl.allRows;const own=takingUp?null:model.recordCount?.()??model.getState().rowCount;if(own!=null)lastServerCount=own;return lastServerCount}const all=ctrl.allRows??[];const trees=all.filter(r=>(r.depth??0)===0&&r.__treeRow);if(trees.length)return trees.reduce((n,r)=>n+(r.treeRecords??1+(r.leafCount??0)),0);const tops=all.filter(r=>(r.depth??0)===0&&!r.__treeRow&&typeof r.getCanExpand==="function"&&r.getCanExpand()&&r.leafCount!=null);if(!groupCount||!tops.length)return api.getDisplayedRows().length;const keep=leafFilter(ctrl);return keep?tops.reduce((n,r)=>n+groupLeaves(r,keep).length,0):tops.reduce((n,r)=>n+(r.leafCount??0),0)});let searching=$state(false);const quickSearch=$derived(active?.type!=="grid"||!!ctrl?.props?.rowModel||!!ctrl?.props?.basePhone);async function openSearch(){if(quickSearch){searching=true;return}ctrl.findOpen=true;await tick();const root=ctrl.scrollContainer?.closest(".sv-grid-root");for(let tries=0;tries<40;tries+=1){const box=root?.querySelector(".sv-grid-find-input");if(box)return box.focus();await new Promise(r=>setTimeout(r,25))}}function focusBox(node){node.focus()}const showFocused=e=>e.target.scrollIntoView?.({block:"nearest",inline:"nearest"});let searchButton=$state(null);const canScan=$derived(quickSearch&&barcodeScanSupported());async function scanToFind(){const code=await scanBarcode();if(!code||!ctrl)return;ctrl.globalFilter=code;searching=true;await tick();await new Promise(r=>setTimeout(r,60));const found=dataRows(ctrl);if(found.length===1)openRecord({ctrl,rowId:found[0].id})}let galleryKey="";$effect(()=>{if(!ctrl||active?.type!=="gallery"){galleryKey="";return}const view=active;const cfg=galleryConfig(ctrl,api,view);const key=JSON.stringify([cfg.coverField,cfg.titleField,cfg.cardFields]);if(key===galleryKey)return;galleryKey=key;untrack(()=>api.setOption("gallery",cfg))});let boardKey="";$effect(()=>{if(!ctrl||active?.type!=="kanban"){boardKey="";return}const cfg=boardConfig(ctrl,api,active);if(!cfg)return;const key=JSON.stringify([cfg.groupBy,cfg.titleField,cfg.cardFields,cfg.virtualized,cfg.lanes.map(l=>[l.title,l.color])]);if(key===boardKey)return;boardKey=key;untrack(()=>api.setOption("board",cfg))});const noHeader=$derived.by(()=>{const t=active?.type;return t==="kanban"||t==="calendar"||t==="timeline"||t==="gantt"||t==="gallery"||!!api?.getOption?.("gallery")});const record=$derived.by(()=>{const r=getRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const fieldEditing=$derived.by(()=>{const r=getFieldEditorRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const fieldDeleting=$derived.by(()=>{const r=getDeleteFieldRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});$effect(()=>{if(ctrl&&getFieldEditorRequest()?.ctrl===ctrl)untrack(()=>panel=null)});const deleting=$derived.by(()=>{const r=getDeleteRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const has=$derived.by(()=>{const t=active?.type??"grid";if(t==="form")return new Set(manageViews?["form"]:[]);if(t==="dashboard")return new Set;if(t==="grid")return new Set(["hide","filter","group","sort","color","height"]);if(t==="chart")return new Set(["filter","chart"]);if(t==="gantt"||t==="timeline")return new Set(["hide","filter","sort","color","gantt"]);if(t==="calendar")return new Set(["hide","filter","sort","color"]);if(t==="list")return new Set(["hide","filter","group","sort","list"]);if(t==="inbox")return new Set(["hide","filter","sort","list"]);return new Set(["hide","filter","sort"])});const bare=$derived(!viewList&&!locked&&!changed&&!automations&&has.size===0);const ICON={hide:"M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 5.1A9.8 9.8 0 0 1 12 5c5 0 9 5 10 7a13.4 13.4 0 0 1-3 3.9M6.6 6.6A13.5 13.5 0 0 0 2 12c1 2 5 7 10 7a9.6 9.6 0 0 0 4.4-1.1",filter:"M4 5h16l-6 7v6l-4 2v-8z",group:"M4 5h16M4 10h10M4 15h16M4 20h10",sort:"M7 4v16M3 16l4 4 4-4M17 20V4M13 8l4-4 4 4",color:"M12 3l6 7a6.5 6.5 0 1 1-12 0l6-7z",chart:"M4 20h16M6 20V11M11 20V5M16 20v-7",gantt:"M4 5h9M7 10h11M10 15h8M4 20h16",height:"M4 6h16M4 12h16M4 18h16M20 3v18",search:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4",chevron:"M6 9l6 6 6-6",bolt:"M13 3L5 14h6l-1 7 8-11h-6z",lock:"M6 11h12v9H6zM8 11V8a4 4 0 0 1 8 0v3",person:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0"};
|
|
2
|
+
import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";import{conditionCount,isGroup,isComplete}from"./filter-model";import{dataRows,fieldColumns,gridOf,groupLeaves,leafFilter,primaryIdOf}from"./grid-access";import{barcodeScanSupported,scanBarcode}from"./barcode-scan";import{findFieldUser,getCurrentUser,getLinkedTable,linkedRows}from"./sources.svelte";import{PLAIN_STATE,applyColor,applyGanttSettings,applyView,boardConfig,captureView,galleryConfig,colorSettingOf,newViewId,viewTypeInfo}from"./view-model";import{groupRules,userSorts}from"./viewbar/sort-state";import{recordHeightOf,syncGroupRowHeight}from"./row-height";import HideFieldsPanel from"./viewbar/HideFieldsPanel.svelte";import FilterPanel from"./viewbar/FilterPanel.svelte";import SortPanel from"./viewbar/SortPanel.svelte";import ColorPanel from"./viewbar/ColorPanel.svelte";import{cellRulesOf,setCellRules}from"./cell-colors.svelte";import ChartPanel from"./viewbar/ChartPanel.svelte";import GanttPanel from"./viewbar/GanttPanel.svelte";import ListPanel from"./viewbar/ListPanel.svelte";import FormBuilder from"./viewbar/FormBuilder.svelte";import ViewsMenu from"./viewbar/ViewsMenu.svelte";import RecordView from"./RecordView.svelte";import{closeRecord,getRecordRequest,closeFieldEditor,getFieldEditorRequest,getDeleteFieldRequest,askDeleteField,openRecord}from"./editor-request.svelte";import FieldEditor from"./FieldEditor.svelte";import DeleteFieldConfirm from"./DeleteFieldConfirm.svelte";import DeleteRecordConfirm from"./DeleteRecordConfirm.svelte";import{askDeleteRecord,getDeleteRecordRequest}from"./record-delete.svelte";import{clearBarRequest,getBarRequest,registerBar}from"./bar-request.svelte";import{bm,bmCount}from"./messages.svelte";let{api,views=$bindable([{id:"grid",name:bm("viewbar.defaultViewName"),type:"grid"}]),activeView=$bindable(""),onViewsChange,onViewRemoved,viewTypes,automations=null,changed=null,lockViews=true,manageViews=true,viewList=true,rowHeights,host=null,tableId}=$props();let barEl=$state(null);$effect(()=>{const el=barEl;const into=host;if(!el||!into)return;const home=document.createComment("");el.before(home);into.appendChild(el);return()=>{if(home.parentNode){home.after(el);home.remove()}else el.remove()}});const heights=$derived(rowHeights??[{label:bm("viewbar.rowShort"),height:34},{label:bm("viewbar.rowMedium"),height:56},{label:bm("viewbar.rowTall"),height:88},{label:bm("viewbar.rowExtraTall"),height:128}]);const ctrl=$derived(api?gridOf(api):void 0);const me=$derived(getCurrentUser()?.id);const visible=$derived(views.filter(v=>!v.personal||!me||v.personal===me));const active=$derived(visible.find(v=>v.id===activeView)??visible[0]??views[0]);const locked=$derived(!!active?.locked);let lockedDirty=$state(false);let lockedBaseline=null;const lockTitle=$derived.by(()=>{const by=active?.lockedBy?findFieldUser(active.lockedBy)?.name:void 0;return by?bm("viewbar.lockedTitleBy",{name:by}):bm("viewbar.lockedTitle")});const types=$derived(viewTypes??["grid","kanban","calendar","gantt"]);const linkNames=(table,value)=>{const t=getLinkedTable(table);return t?linkedRows(t,value).map(r=>String(r[t.primaryField]??"")):[]};const primaryField=$derived.by(()=>{if(!ctrl)return void 0;const id=primaryIdOf(ctrl);return fieldColumns(ctrl).find(c=>c.id===id)?.field});let appliedId=null;let appliedKey="";let applying=false;let showSeq=0;let showing=null;let viewShown=$state(0);let takingUp=false;const keyOf=v=>JSON.stringify(v);function setViews(next){views=next;const shown=next.find(v=>v.id===appliedId);if(shown)appliedKey=keyOf(shown);onViewsChange?.(next)}async function ready(t){if(t==="kanban")(await import("../board")).enableBoardView();else if(t==="calendar"||t==="timeline")(await import("../scheduler")).enableSchedulerView();else if(t==="gallery")(await import("../gallery")).enableGalleryView();else if(t==="gantt")(await import("../gantt")).enableGanttView()}async function show(view){const seq=showSeq+=1;appliedId=view.id;appliedKey=keyOf(view);applying=true;lockedDirty=false;lockedBaseline=null;const another=showing!==view.id;showing=view.id;if(another)ctrl?.props.baseFeed?.forgetCount?.();await ready(view.type);if(seq!==showSeq)return;applying=false;if(!ctrl)return;if(another){lastServerCount=null;takingUp=true;ctrl.props.rowModel?.letRowsGo?.();viewShown+=1;setTimeout(()=>{takingUp=false;viewShown+=1})}applyView(ctrl,api,view,{primaryField,linkNames});colorSetting=view.color??colorSettingOf(ctrl)}const capture=v=>captureView(ctrl,api,{...v,color:$state.snapshot(colorSetting)});const keptViews=()=>views.map(v=>v.id===active?.id&&!v.locked?capture(v):v);function switchTo(id){viewsOpen=false;if(!ctrl||!active||id===active.id)return;const next=keptViews();const target=next.find(v=>v.id===id);if(!target)return;setViews(next);activeView=id;void show(target)}function create(partial){if(!ctrl||!active)return;const select=columns.find(c=>c.fieldType==="singleSelect");const timed=partial.type==="calendar"||partial.type==="timeline"||partial.type==="gantt";const view={...partial,id:newViewId(),state:{...PLAIN_STATE},color:timed&&select?{mode:"field",field:select.field}:{mode:"none"}};const next=[...keptViews(),view];setViews(next);activeView=view.id;void show(view);viewsOpen=false}function duplicate(id){if(!ctrl)return;const src=id===active?.id&&!active.locked?capture(active):views.find(v=>v.id===id);if(!src)return;const{locked:_locked,lockedBy:_by,...open}=JSON.parse(JSON.stringify(src));const copy={...open,id:newViewId(),name:bm("viewbar.viewCopy",{name:src.name}),...!manageViews&&me?{personal:me}:{}};const at=views.findIndex(v=>v.id===id);const next=[...views];next.splice(at+1,0,copy);setViews(next)}function remove(id){if(views.length<2||views.find(v=>v.id===id)?.locked)return;const at=views.findIndex(v=>v.id===id);const gone=id===active?.id?capture(views[at]):views[at];const next=views.filter(v=>v.id!==id);setViews(next);if(gone)onViewRemoved?.(gone,at);if(id===active?.id){const first=next.find(v=>!v.personal||!me||v.personal===me)??next[0];activeView=first.id;void show(first)}}function toggleLock(id){if(!lockViews)return;setViews(views.map(v=>{if(v.id!==id)return v;if(v.locked){const{locked:_locked,lockedBy:_by,...open}=v;return open}const kept=v.id===active?.id?capture(v):v;return{...kept,locked:true,...me?{lockedBy:me}:{}}}));lockedDirty=false;lockedBaseline=null}function resetLocked(){if(active)void show(active)}const rename=(id,name)=>setViews(views.map(v=>v.id===id?{...v,name}:v));const setSection=(id,section)=>setViews(views.map(v=>{if(v.id!==id)return v;const{section:_was,...rest}=v;return section?{...rest,section:section.slice(0,60)}:rest}));function setGantt(next){if(!ctrl||!active)return;const updated={...active,...next};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}const NO_CHART={kind:"bar",x:""};const setChart=chart=>setViews(views.map(v=>v.id===active?.id?{...v,chart}:v));const setList=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));const setForm=next=>setViews(views.map(v=>v.id===active?.id?{...v,...next}:v));let formOpen=$state(false);$effect(()=>{if(!ctrl||!active)return;const view=active;const key=keyOf(view);untrack(()=>{if(!activeView)activeView=view.id;if(view.id===appliedId&&key===appliedKey)return;if(appliedId===null&&!(view.state||view.type!=="grid"||view.color||view.cellColors?.length||view.rowHeight!=null)){appliedId=view.id;appliedKey=key;return}void show(view)})});$effect(()=>{if(!ctrl||!active)return;const snapshot=JSON.stringify([ctrl.gridStateVersion,api.getState(),recordHeightOf(api.getOption("rowHeight")),effectiveColor,cellRules]);const view=active;const timer=setTimeout(()=>{untrack(()=>{if(applying||view.id!==appliedId||keyOf(view)!==appliedKey)return;const kept=capture(view);const before=JSON.stringify([view.state,view.rowHeight,view.color,view.cellColors??[]]);const after=JSON.stringify([kept.state,kept.rowHeight,kept.color,kept.cellColors??[]]);if(view.locked){const{expanded:_open,...shown}=kept.state??{};const now=JSON.stringify([shown,kept.rowHeight,kept.color,kept.cellColors??[]]);if(lockedBaseline===null)lockedBaseline=now;else lockedDirty=now!==lockedBaseline}else if(before!==after)setViews(views.map(v=>v.id===view.id?kept:v))})},400);void snapshot;return()=>clearTimeout(timer)});let viewsOpen=$state(false);let panel=$state(null);function setPanel(p,open){if(open)panel=p;else if(panel===p)panel=null}$effect(()=>{if(ctrl)return registerBar(ctrl)});$effect(()=>{const r=getBarRequest();if(!r||r.ctrl!==ctrl)return;untrack(()=>{if(!locked)panel=r.panel;clearBarRequest()})});let colorSetting=$state({mode:"none"});$effect(()=>{if(ctrl)untrack(()=>colorSetting=active?.color??colorSettingOf(ctrl))});function setColor(s){colorSetting=s;if(ctrl)applyColor(ctrl,s,linkNames);if(ctrl&&active&&(active.type==="calendar"||active.type==="timeline"||active.type==="gantt")){const updated={...active,color:$state.snapshot(s)};setViews(views.map(v=>v.id===active.id?updated:v));applyGanttSettings(ctrl,api,updated,primaryField)}}const columns=$derived(ctrl?fieldColumns(ctrl):[]);const hiddenCount=$derived(columns.filter(c=>!c.visible).length);const filter=$derived.by(()=>{const f=ctrl?.advancedFilter;return f?.kind==="fieldFilter"?f:null});const filterCount=$derived(conditionCount(filter));const filterLabel=$derived.by(()=>{if(!filter||!filterCount)return bm("viewbar.filter");const ids=new Set;for(const c of filter.conditions)for(const x of isGroup(c)?c.conditions:[c])if(isComplete(x))ids.add(x.column);if(ids.size===1){const header=columns.find(c=>ids.has(c.id))?.header;return header!=null?bm("viewbar.filteredBy",{field:header}):bmCount("viewbar.filteredByFields",1)}return bmCount("viewbar.filteredByFields",ids.size)});const groupCount=$derived(ctrl?groupRules(ctrl).length:0);const sortCount=$derived(ctrl?userSorts(ctrl).length:0);const effectiveColor=$derived(ctrl?colorSettingOf(ctrl,colorSetting):colorSetting);const colorLabel=$derived.by(()=>{if(effectiveColor.mode==="field"){const header=columns.find(c=>c.field===effectiveColor.field)?.header;return header!=null?bm("viewbar.coloredBy",{field:header}):bm("viewbar.color")}if(effectiveColor.mode==="conditions"&&effectiveColor.rules.length)return bm("viewbar.coloredByConditions");return cellRules.length?bm("viewbar.coloredCells"):bm("viewbar.color")});const cellRules=$derived(ctrl?cellRulesOf(ctrl):[]);function setCells(next){if(ctrl)setCellRules(ctrl,next)}const rowHeight=$derived(recordHeightOf(api?.getOption?.("rowHeight"))??0);let heightOpen=$state(false);const shownHeight=$derived(heights.some(h=>h.height===rowHeight)?rowHeight:heights[0]?.height);$effect(()=>{const grouped=groupCount>0;void rowHeight;void ctrl?.props?.rowModel;untrack(()=>syncGroupRowHeight(ctrl,api,grouped))});let lastServerCount=null;const records=$derived.by(()=>{void viewShown;if(!ctrl)return 0;if(ctrl.props.baseFeed&&!ctrl.props.rowModel&&active?.type!=="form")return ctrl.props.baseFeed.knownCount();const model=ctrl.props.rowModel;if(model?.getState){void ctrl.allRows;const own=takingUp?null:model.recordCount?.()??model.getState().rowCount;if(own!=null)lastServerCount=own;return lastServerCount}const all=ctrl.allRows??[];const trees=all.filter(r=>(r.depth??0)===0&&r.__treeRow);if(trees.length)return trees.reduce((n,r)=>n+(r.treeRecords??1+(r.leafCount??0)),0);const tops=all.filter(r=>(r.depth??0)===0&&!r.__treeRow&&typeof r.getCanExpand==="function"&&r.getCanExpand()&&r.leafCount!=null);if(!groupCount||!tops.length)return api.getDisplayedRows().length;const keep=leafFilter(ctrl);return keep?tops.reduce((n,r)=>n+groupLeaves(r,keep).length,0):tops.reduce((n,r)=>n+(r.leafCount??0),0)});let searching=$state(false);const quickSearch=$derived(active?.type!=="grid"||!!ctrl?.props?.rowModel||!!ctrl?.props?.basePhone);async function openSearch(){if(quickSearch){searching=true;return}ctrl.findOpen=true;await tick();const root=ctrl.scrollContainer?.closest(".sv-grid-root");for(let tries=0;tries<40;tries+=1){const box=root?.querySelector(".sv-grid-find-input");if(box)return box.focus();await new Promise(r=>setTimeout(r,25))}}function focusBox(node){node.focus()}const showFocused=e=>e.target.scrollIntoView?.({block:"nearest",inline:"nearest"});let searchButton=$state(null);const canScan=$derived(quickSearch&&barcodeScanSupported());async function scanToFind(){const code=await scanBarcode();if(!code||!ctrl)return;ctrl.globalFilter=code;searching=true;await tick();await new Promise(r=>setTimeout(r,60));const found=dataRows(ctrl);if(found.length===1)openRecord({ctrl,rowId:found[0].id})}let galleryKey="";$effect(()=>{if(!ctrl||active?.type!=="gallery"){galleryKey="";return}const view=active;const cfg=galleryConfig(ctrl,api,view);const key=JSON.stringify([cfg.coverField,cfg.titleField,cfg.cardFields]);if(key===galleryKey)return;galleryKey=key;untrack(()=>api.setOption("gallery",cfg))});let boardKey="";$effect(()=>{if(!ctrl||active?.type!=="kanban"){boardKey="";return}const cfg=boardConfig(ctrl,api,active);if(!cfg)return;const key=JSON.stringify([cfg.groupBy,cfg.titleField,cfg.cardFields,cfg.virtualized,cfg.lanes.map(l=>[l.title,l.color])]);if(key===boardKey)return;boardKey=key;untrack(()=>api.setOption("board",cfg))});const noHeader=$derived.by(()=>{const t=active?.type;return t==="kanban"||t==="calendar"||t==="timeline"||t==="gantt"||t==="gallery"||!!api?.getOption?.("gallery")});const record=$derived.by(()=>{const r=getRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const fieldEditing=$derived.by(()=>{const r=getFieldEditorRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const fieldDeleting=$derived.by(()=>{const r=getDeleteFieldRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});$effect(()=>{if(ctrl&&getFieldEditorRequest()?.ctrl===ctrl)untrack(()=>panel=null)});const deleting=$derived.by(()=>{const r=getDeleteRecordRequest();return r&&ctrl&&r.ctrl===ctrl&&noHeader?r:null});const has=$derived.by(()=>{const t=active?.type??"grid";if(t==="form")return new Set(manageViews?["form"]:[]);if(t==="dashboard")return new Set;if(t==="grid")return new Set(["hide","filter","group","sort","color","height"]);if(t==="chart")return new Set(["filter","chart"]);if(t==="gantt"||t==="timeline")return new Set(["hide","filter","sort","color","gantt"]);if(t==="calendar")return new Set(["hide","filter","sort","color"]);if(t==="list")return new Set(["hide","filter","group","sort","list"]);if(t==="inbox")return new Set(["hide","filter","sort","list"]);return new Set(["hide","filter","sort"])});const bare=$derived(!viewList&&!locked&&!changed&&!automations&&has.size===0);const ICON={hide:"M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 5.1A9.8 9.8 0 0 1 12 5c5 0 9 5 10 7a13.4 13.4 0 0 1-3 3.9M6.6 6.6A13.5 13.5 0 0 0 2 12c1 2 5 7 10 7a9.6 9.6 0 0 0 4.4-1.1",filter:"M4 5h16l-6 7v6l-4 2v-8z",group:"M4 5h16M4 10h10M4 15h16M4 20h10",sort:"M7 4v16M3 16l4 4 4-4M17 20V4M13 8l4-4 4 4",color:"M12 3l6 7a6.5 6.5 0 1 1-12 0l6-7z",chart:"M4 20h16M6 20V11M11 20V5M16 20v-7",gantt:"M4 5h9M7 10h11M10 15h8M4 20h16",height:"M4 6h16M4 12h16M4 18h16M20 3v18",search:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4",chevron:"M6 9l6 6 6-6",bolt:"M13 3L5 14h6l-1 7 8-11h-6z",lock:"M6 11h12v9H6zM8 11V8a4 4 0 0 1 8 0v3",person:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0"};
|
|
3
3
|
</script>
|
|
4
4
|
|
|
5
5
|
{#snippet glyph(path: string, size = 15)}
|
|
@@ -90,7 +90,7 @@ import{tick,untrack}from"svelte";import{SvPopover,menuFocus}from"@svgrid/grid";i
|
|
|
90
90
|
{#snippet anchor()}
|
|
91
91
|
<button type="button" disabled={locked} title={locked ? lockTitle : undefined} class="sv-fvb-btn" class:is-set={colorLabel !== bm('viewbar.color')} aria-haspopup="dialog" aria-expanded={panel === 'color'}>{@render glyph(ICON.color)}<span>{colorLabel}</span></button>
|
|
92
92
|
{/snippet}
|
|
93
|
-
<ColorPanel {ctrl} setting={effectiveColor} onChange={setColor} />
|
|
93
|
+
<ColorPanel {ctrl} setting={effectiveColor} onChange={setColor} {cellRules} onCellsChange={setCells} />
|
|
94
94
|
</SvPopover>
|
|
95
95
|
{/if}
|
|
96
96
|
{#if has.has('chart')}
|
|
@@ -1,8 +1,19 @@
|
|
|
1
|
+
/** A scanner of the app's own: a phone app's native one, say. Answers the code read, or null when cancelled. */
|
|
2
|
+
export type BarcodeScannerFn = () => Promise<string | null>;
|
|
1
3
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
4
|
+
* Read codes with the app's own scanner in place of the camera screen here: a
|
|
5
|
+
* phone app (Capacitor, Cordova) hands over its native one, which works where
|
|
6
|
+
* the browser has no BarcodeDetector (an iPhone). null goes back to the
|
|
7
|
+
* browser's. Page-wide: the scan buttons of barcode fields and the view bar's
|
|
8
|
+
* "Scan to find" use it.
|
|
9
|
+
*/
|
|
10
|
+
export declare function setBarcodeScanner(scan: BarcodeScannerFn | null): void;
|
|
11
|
+
/**
|
|
12
|
+
* Whether codes can be read here: the app gave its own scanner
|
|
13
|
+
* (setBarcodeScanner), or the browser has the BarcodeDetector (Chrome and
|
|
14
|
+
* Edge on Android, among others) and a camera to ask for. Safari on an iPhone
|
|
15
|
+
* has neither today.
|
|
5
16
|
*/
|
|
6
17
|
export declare function barcodeScanSupported(): boolean;
|
|
7
|
-
/** Opens the camera full screen; answers the first code it reads, or null when the person cancels. */
|
|
18
|
+
/** Opens the camera full screen (or the app's own scanner); answers the first code it reads, or null when the person cancels. */
|
|
8
19
|
export declare function scanBarcode(): Promise<string | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mount as
|
|
1
|
+
import{mount as i,unmount as a}from"svelte";import u from"./BarcodeScanner.svelte";let t=null;export function setBarcodeScanner(n){t=n}export function barcodeScanSupported(){return t?!0:typeof window<"u"&&"BarcodeDetector"in window&&typeof navigator<"u"&&!!navigator.mediaDevices&&typeof navigator.mediaDevices.getUserMedia=="function"}export function scanBarcode(){if(t){const n=t;return Promise.resolve().then(()=>n()).then(e=>typeof e=="string"&&e!==""?e:null,()=>null)}return new Promise(n=>{const e=document.createElement("div");document.body.appendChild(e);let o=null;o=i(u,{target:e,props:{onDone:r=>{queueMicrotask(()=>{o&&a(o),o=null,e.remove()}),n(r)}}})})}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{BRIGHT as h}from"./palette.js";import{convertValue as P,countCleared as R}from"./convert.js";import{parseTimeOfDay as v}from"./time-of-day.js";import{blankTable as I,colId as g,newRecordId as N,primaryOf as
|
|
2
|
-
`)))return{header:t,fieldType:"longText"};if(e.some(r=>r.includes(","))){const r=e.flatMap(c=>c.split(",").map(m=>m.trim()).filter(Boolean)),s=[...new Set(r)];return s.length<=
|
|
1
|
+
import{BRIGHT as h}from"./palette.js";import{convertValue as P,countCleared as R}from"./convert.js";import{parseTimeOfDay as v}from"./time-of-day.js";import{blankTable as I,colId as g,newRecordId as N,primaryOf as L}from"./base-tables.js";import{canEditField as k}from"./field-access.svelte.js";import{bm as w}from"./messages.svelte.js";import{splitNames as F}from"./name-list.js";const O=12,U=/^(true|false|yes|no|y|n|x|1|0|checked|unchecked|done|on|off)$/i,H=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,X=/^(https?:\/\/|www\.)\S+$/i,Y=/^\+?[\d\s().-]{7,}$/,K=/^\d{4}-\d{2}-\d{2}([ T]\d{2}:\d{2}(:\d{2})?)?/,V=/^\d{1,2}[/.]\d{1,2}[/.]\d{2,4}$/,$=String.raw`(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)`,q=new RegExp(String.raw`^[-+]?${$}(e[-+]?\d+)?$`,"i"),z=new RegExp(String.raw`^[-+]?[$€£¥]\s?${$}$|^[-+]?${$}\s?[$€£¥]$`),G=new RegExp(String.raw`^[-+]?${$}\s?%$`),C=/^([-+]?[$€£¥]?\s?)((?:\d{1,3}(?:[.\s]\d{3})+|\d+)(?:,\d+)?)(\s?[$€£¥%]?)$/,W=/^\d{1,2}:\d{2}(:\d{2})?(\s?[ap]\.?m\.?)?$/i,j=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i,J=/^\s*(?:[-*]\s+)?\[( |x|X)?\]\s/;export function commaDecimals(t){const n=t.map(e=>e.trim()).filter(Boolean);return n.length>0&&n.every(e=>C.test(e))&&n.some(e=>/,\d{1,2}(\D*)$|,\d{4,}(\D*)$/.test(e)||/\.\d{3}.*,/.test(e))}function D(t){return t.trim().replace(C,(n,e,o,i)=>`${e}${o.replace(/[.\s]/g,"").replace(",",".")}${i}`)}const Q=new Set(["number","currency","percent","rating","duration","timer"]),_=/^(\d{1,2})([/.-])(\d{1,2})\2(\d{4}|\d{2})(.*)$/;function Z(t){const n=t.map(i=>_.exec(i.trim())).filter(i=>!!i),e=n.some(i=>Number(i[1])>12),o=n.some(i=>Number(i[3])>12);return e===o?null:i=>{const r=_.exec(i.trim());if(!r)return i;const s=r[4].length===2?`20${r[4]}`:r[4],[c,m]=e?[r[3],r[1]]:[r[1],r[3]];return`${s}-${c.padStart(2,"0")}-${m.padStart(2,"0")}${r[5]}`}}function b(t,n){const e=String(n?.fieldType);if(e==="date")return Z(t)??(i=>i);const o=n?.fieldProps?.separators;return Q.has(e)&&(o==="period-comma"||o==="space-comma"||commaDecimals(t))?D:i=>i}export function guessField(t,n){const e=n.map(r=>r.trim()).filter(Boolean);if(!e.length)return{header:t,fieldType:"text"};if(commaDecimals(e))return guessField(t,e.map(D));const o=r=>e.every(s=>r.test(s));if(o(z)){const r=e.map(s=>/[$€£¥]/.exec(s)?.[0]).find(Boolean)??"$";return{header:t,fieldType:"number",fieldProps:{format:"currency",symbol:r,precision:e.some(s=>/\.\d/.test(s))?2:0}}}if(o(G))return{header:t,fieldType:"number",fieldProps:{format:"percent",points:!0,precision:0}};if(o(U)&&e.some(r=>!/^[01]$/.test(r)))return{header:t,fieldType:"checkbox"};if(o(q)){const r=e.reduce((s,c)=>Math.max(s,/\.(\d+)$/.exec(c)?.[1]?.length??0),0);return{header:t,fieldType:"number",fieldProps:r?{format:"decimal",precision:Math.min(r,4)}:{format:"integer"}}}if(o(H))return{header:t,fieldType:"email"};if(o(X))return{header:t,fieldType:"url"};if(o(K)||o(V)&&e.every(r=>!Number.isNaN(new Date(r).getTime()))){const r=e.some(s=>/\d{2}:\d{2}/.test(s));return{header:t,fieldType:"date",fieldProps:r?{time:!0}:{}}}if(o(W)&&e.every(r=>v(r)!=null))return{header:t,fieldType:"timeOfDay",fieldProps:e.some(r=>/[ap]\.?m/i.test(r))?{}:{timeFormat:"24hour"}};if(o(j))return{header:t,fieldType:"color"};if(o(J))return{header:t,fieldType:"checklist"};if(o(Y)&&e.every(r=>(r.match(/\d/g)?.length??0)>=7))return{header:t,fieldType:"phone"};if(e.some(r=>r.length>120||r.includes(`
|
|
2
|
+
`)))return{header:t,fieldType:"longText"};if(e.some(r=>r.includes(","))){const r=e.flatMap(c=>c.split(",").map(m=>m.trim()).filter(Boolean)),s=[...new Set(r)];return s.length<=O*2&&s.length<r.length/2&&s.every(c=>c.length<=40)?{header:t,fieldType:"multiSelect",fieldProps:{options:x(s)}}:{header:t,fieldType:"text"}}const i=[...new Set(e)];return e.length>=4&&i.length<=O&&i.length<=e.length/2&&i.every(r=>r.length<=40)?{header:t,fieldType:"singleSelect",fieldProps:{options:x(i)}}:{header:t,fieldType:"text"}}const x=t=>t.map((n,e)=>({value:n,color:h[e%h.length].value}));function ee(t,n){const e=t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"field";let o=/^\d/.test(e)?`f_${e}`:e;for(let i=2;n.has(o)||o==="id";i+=1)o=`${e}_${i}`;return n.add(o),o}function E(t){return t.slice(1).filter(n=>n.some(e=>String(e??"").trim()!=="")).map(n=>n.map(e=>String(e??"")))}export function tableFromMatrix(t,n,e,o={}){const i=(t[0]??[]).map((p,f)=>String(p??"").trim()||w("shell.importFieldName",{n:f+1})),r=E(t),s=new Set,c=i.map((p,f)=>{const d=guessField(p,r.map(M=>M[f]??"")),u=ee(p,s),T=f===0&&!o[0]?"text":o[f]??importTypeOf(d),{fieldType:a,fieldProps:S}=T===importTypeOf(d)?d:te(T,r.map(M=>M[f]??""));return{id:u,field:u,header:p,...f===0?{width:220}:{},fieldType:a,...S?{fieldProps:S}:{}}}),m=c.map((p,f)=>b(r.map(d=>d[f]??""),p)),y=r.map(p=>{const f={id:N()};return c.forEach((d,u)=>f[d.field]=P(m[u](p[u]??""),"text",d.fieldType,d.fieldProps)),f}),l=I(n,ne(e,n));return{...l,primaryField:String(c[0]?.field??"name"),columns:c.length?c:l.columns,data:y}}export function importTypeOf(t){const n=t.fieldProps?.format;return t.fieldType==="number"&&(n==="currency"||n==="percent")?n:t.fieldType}function te(t,n){return t==="currency"?{fieldType:"number",fieldProps:{format:"currency",symbol:n.map(o=>/[$€£¥]/.exec(o)?.[0]).find(Boolean)??"$",precision:2}}:t==="percent"?{fieldType:"number",fieldProps:{format:"percent",points:!0,precision:0}}:t==="singleSelect"?{fieldType:t,fieldProps:{options:x([...new Set(n.map(e=>e.trim()).filter(Boolean))].slice(0,200))}}:t==="multiSelect"?{fieldType:t,fieldProps:{options:x([...new Set(n.flatMap(e=>e.split(",").map(o=>o.trim())).filter(Boolean))].slice(0,200))}}:{fieldType:t}}function ne(t,n){const e=new Set(n.map(i=>i.name.toLowerCase()));let o=t.trim()||w("shell.importedName");for(let i=2;e.has(o.toLowerCase());i+=1)o=`${t.trim()||w("shell.importedName")} ${i}`;return o}const re=new Set(["formula","lookup","rollup","count","autoNumber","createdTime","lastModifiedTime","createdBy","lastModifiedBy","button"]),oe=new Set(["text","longText","singleSelect","multiSelect"]);export function importTargets(t){return t.columns.filter(n=>n.field!=null&&n.recordKey!==!0&&!re.has(n.fieldType)&&k(n,n.fieldProps??{})).map(n=>({id:g(n),header:String(n.header??n.field),fieldType:n.fieldType}))}export function withEveryColumn(t){const n=t.reduce((i,r)=>Math.max(i,r.length),0),[e=[],...o]=t;return e.length>=n?t:[[...e,...new Array(n-e.length).fill("")],...o]}export function cellsLost(t,n){return B(t,n,e=>!oe.has(e)&&!A.has(e))}export function cellsUnmatched(t,n){return B(t,n,e=>A.has(e))}const A=new Set(["user","vote","link"]);function B(t,n,e){const o=E(t);let i=0;return n.forEach((r,s)=>{if(!r?.fieldType||!e(r.fieldType))return;const c=o.map(m=>m[s]??"");i+=R(c.map(b(c,r)),"text",r.fieldType,r.fieldProps)}),i}export function repeatedRecords(t,n,e){const o=L(n),i=e.findIndex(s=>s!=null&&(s===o||String(n.columns.find(c=>g(c)===s)?.field)===o));if(i<0)return 0;const r=new Set(n.data.map(s=>String(s[o]??"").trim().toLowerCase()).filter(Boolean));return E(t).filter(s=>r.has(String(s[i]??"").trim().toLowerCase())).length}export function matchColumns(t,n){const e=r=>r.trim().toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),o=importTargets(n),i=new Set;return t.map(r=>{const s=e(r),c=s?o.find(m=>!i.has(m.id)&&(e(m.header)===s||e(m.id)===s)):void 0;return c&&i.add(c.id),c?.id??null})}export function recordsFromMatrix(t,n,e){const o=E(t),i=new Map(n.columns.map(l=>[g(l),l])),r=n.columns.map(l=>{const p=e.indexOf(g(l));if(p<0||l.fieldType!=="singleSelect"&&l.fieldType!=="multiSelect")return l;const f=l.fieldProps?.options??[],d=new Set(f.flatMap(a=>[a.value,a.label??a.value]).map(a=>String(a).toLowerCase())),u=[...new Set(o.flatMap(a=>l.fieldType==="multiSelect"?F(a[p]??""):[a[p]??""]).map(a=>a.trim()).filter(a=>a&&!d.has(a.toLowerCase())))];if(!u.length)return l;const T=[...f,...u.map((a,S)=>({value:a,color:h[(f.length+S)%h.length].value}))];return{...l,fieldProps:{...l.fieldProps,options:T}}}),s=new Map(r.map(l=>[g(l),l])),c=e.map((l,p)=>b(o.map(f=>f[p]??""),l?s.get(l):void 0)),m=o.map(l=>{const p={id:N()};return e.forEach((f,d)=>{if(!f||!i.has(f))return;const u=s.get(f);p[String(u.field)]=P(c[d](l[d]??""),"text",u.fieldType??"text",u.fieldProps)}),p}),y=L(n);return e.some(l=>l&&String(s.get(l)?.field)===y)||m.forEach((l,p)=>l[y]??(l[y]=w("shell.importedRecordName",{n:p+1}))),{rows:m,columns:r}}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A small celebration when someone finishes something: a burst of fireworks
|
|
3
|
+
* where they did it, for a moment, when one record turns done. "Done" is a
|
|
4
|
+
* single select set to an option such as Done, Completed, Shipped, Paid or Won
|
|
5
|
+
* (Готово, Завършено, Платено), or a checkbox field with such a name ticked.
|
|
6
|
+
* A field opts out with `fieldProps.celebrate: false`, or in with `true`
|
|
7
|
+
* (any option or tick then counts).
|
|
8
|
+
*
|
|
9
|
+
* Off unless SvBase's `celebrate` prop is on. Never for an undo or redo, a
|
|
10
|
+
* paste or fill of several cells, or a page whose reader asks the system for
|
|
11
|
+
* less motion; at most once every two seconds. The canvas lies over the page
|
|
12
|
+
* without taking clicks, and is gone when the sparks are.
|
|
13
|
+
*/
|
|
14
|
+
type Def = Record<string, any>;
|
|
15
|
+
/** Whether `value` is "done" in this field. */
|
|
16
|
+
export declare function isDone(def: Def | undefined, value: unknown): boolean;
|
|
17
|
+
/** Whether a change turned this field done: it was not, and now is. */
|
|
18
|
+
export declare const becameDone: (def: Def | undefined, before: unknown, after: unknown) => boolean;
|
|
19
|
+
/**
|
|
20
|
+
* A cell changed (SvBase's onCellValueChange). Every change of this moment is
|
|
21
|
+
* counted; when only one was made and it turned a record done, the sparks fly.
|
|
22
|
+
*/
|
|
23
|
+
export declare function noteChange(ctrl: any, def: Def | undefined, before: unknown, after: unknown, row?: unknown, columnId?: string): void;
|
|
24
|
+
/** Three bursts above `at`, about a second and a half, then the canvas goes. */
|
|
25
|
+
export declare function fireworks(at: {
|
|
26
|
+
x: number;
|
|
27
|
+
y: number;
|
|
28
|
+
}): void;
|
|
29
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const M=/^(done|complete|completed|finished|closed|resolved|shipped|delivered|paid|won|approved|published|live|fixed|готово|завършен[оаи]?|приключен[оаи]?|платен[оаи]?|доставен[оаи]?|одобрен[оаи]?|спечелен[оаи]?|решен[оаи]?|изпратен[оаи]?|erledigt|fertig|terminé|hecho|completato)$/iu,E=e=>e&&typeof e=="object"?String(e.name??e.value??""):e==null?"":String(e),P=e=>e===!0||e===1||e==="true";export function isDone(e,t){if(!e)return!1;const i=e.fieldProps?.celebrate;if(i===!1)return!1;if(e.fieldType==="checkbox")return P(t)&&(i===!0||M.test(String(e.header??"").trim()));if(e.fieldType==="singleSelect"){const r=E(t).trim();return!!r&&(i===!0||M.test(r))}return!1}export const becameDone=(e,t,i)=>isDone(e,i)&&!isDone(e,t);let m=null,S=!1,v=0,c=null;function $(){if(S||typeof window>"u")return;S=!0;const e=t=>m={x:t.clientX,y:t.clientY,at:Date.now()};window.addEventListener("pointerdown",e,!0),window.addEventListener("pointerup",e,!0)}const k=()=>typeof window<"u"&&!!window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;$();const C=e=>e&&e.width?{x:e.left+e.width/2,y:e.top+e.height/2}:null;function T(e,t,i){const r=e?.gridRootEl;let s=null;try{const o=t!=null?e?.props?.getRowId?.(t,0):void 0;s=o==null?null:String(o)}catch{s=null}const a=t!=null&&i?(e?.allRows??[]).findIndex(o=>o.original===t||s!=null&&o.id===s):-1;if(r&&a>=0){const l=r.querySelector(`[data-svgrid-row="${a}"][data-col-id="${typeof CSS<"u"&&CSS.escape?CSS.escape(String(i)):String(i).replace(/["\\]/g,"\\$&")}"]`)?.getBoundingClientRect();if(l&&l.width&&l.bottom>0&&l.top<innerHeight&&l.right>0&&l.left<innerWidth)return C(l)}return m&&Date.now()-m.at<2500?m:C(r?.getBoundingClientRect())??{x:(typeof innerWidth=="number"?innerWidth:800)/2,y:(typeof innerHeight=="number"?innerHeight:600)/2}}export function noteChange(e,t,i,r,s,a){e?.props?.celebrate&&(c||(c={changes:0,done:[]},setTimeout(()=>{const o=c;if(c=null,o.changes!==1||o.done.length!==1||k())return;const l=Date.now();l-v<2e3||(v=l,fireworks(o.done[0]))},0)),c.changes+=1,becameDone(t,i,r)&&c.done.push(T(e,s,a)))}const R=["#fcb400","#f82b60","#20c933","#2d7ff9","#8b46ff","#18bfff","#ff6f2c"];export function fireworks(e){if(typeof document>"u")return;const t=document.createElement("canvas"),i=t.getContext?.("2d");if(!i)return;const r=Math.min(2,window.devicePixelRatio||1),s=window.innerWidth,a=window.innerHeight;t.width=s*r,t.height=a*r,t.setAttribute("aria-hidden","true"),t.className="sv-celebrate",Object.assign(t.style,{position:"fixed",inset:"0",width:`${s}px`,height:`${a}px`,pointerEvents:"none",zIndex:"2147483000"}),document.body.appendChild(t),i.scale(r,r);const o=[],l=(w,x,n)=>{for(let f=0;f<n;f++){const p=Math.PI*2*f/n+Math.random()*.3,b=2.2+Math.random()*3.2;o.push({x:w,y:x,vx:Math.cos(p)*b,vy:Math.sin(p)*b-1,life:1,color:R[Math.random()*R.length|0],size:1.6+Math.random()*1.8})}},h=Math.max(40,Math.min(s-40,e.x)),g=Math.max(60,Math.min(a-20,e.y)),u=[[0,h,g-10,46],[180,h-70,g-70,34],[340,h+80,g-55,34]],D=performance.now();let d=0;const y=w=>{const x=w-D;for(;d<u.length&&x>=u[d][0];){const[,n,f,p]=u[d];l(Math.max(20,Math.min(s-20,n)),Math.max(20,f),p),d++}i.clearRect(0,0,s,a);for(const n of o)n.vy+=.07,n.vx*=.985,n.vy*=.985,n.x+=n.vx,n.y+=n.vy,n.life-=.016,!(n.life<=0)&&(i.globalAlpha=Math.max(0,n.life),i.fillStyle=n.color,i.beginPath(),i.arc(n.x,n.y,n.size,0,Math.PI*2),i.fill());d<u.length||o.some(n=>n.life>0)?requestAnimationFrame(y):t.remove()};requestAnimationFrame(y),setTimeout(()=>t.remove(),4e3)}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type FieldCondition, type LinkNames } from './filter-model.js';
|
|
2
|
+
export type CellColorRule = {
|
|
3
|
+
color: string;
|
|
4
|
+
condition: FieldCondition;
|
|
5
|
+
};
|
|
6
|
+
/** The cell rules this grid's view shows. */
|
|
7
|
+
export declare function cellRulesOf(ctrl: unknown): CellColorRule[];
|
|
8
|
+
/** Show these cell rules on this grid (an empty list: none). */
|
|
9
|
+
export declare function setCellRules(ctrl: unknown, rules: ReadonlyArray<CellColorRule>): void;
|
|
10
|
+
/** A tint of the rule's color behind the cell: the text stays readable in a light or dark theme. */
|
|
11
|
+
export declare const cellTint: (color: string) => string;
|
|
12
|
+
/**
|
|
13
|
+
* The grid's `conditionalFormats` for the rules: one per rule, on the field it
|
|
14
|
+
* tests, drawn while it matches and no earlier rule of that field does. A rule on
|
|
15
|
+
* a field the grid no longer has, or not finished yet, draws nothing.
|
|
16
|
+
*/
|
|
17
|
+
export declare function cellColorFormats(ctrl: unknown, rules: ReadonlyArray<CellColorRule>, linkNames?: LinkNames): unknown[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{fieldColumns}from"./grid-access.js";import{safeColor}from"./palette.js";import{compileFieldFilter}from"./filter-model.js";const chosen=new WeakMap;let version=$state(0);export function cellRulesOf(ctrl){void version;return(ctrl&&typeof ctrl==="object"?chosen.get(ctrl):void 0)??[]}export function setCellRules(ctrl,rules){if(!ctrl||typeof ctrl!=="object")return;chosen.set(ctrl,rules.map(r=>({color:r.color,condition:{...r.condition}})));version+=1}export const cellTint=color=>`color-mix(in srgb, ${safeColor(color)??"#fcb400"} 30%, transparent)`;export function cellColorFormats(ctrl,rules,linkNames){if(!rules.length)return[];const cols=new Map(fieldColumns(ctrl).map(c=>[c.id,c]));const valueOf=(row,id)=>{const col=cols.get(id);if(!col)return void 0;const fn=col.def.fieldFn;return fn?fn(row):row?.[col.field]};const tests=rules.map(r=>{if(!cols.has(r.condition.column))return null;const test=compileFieldFilter({kind:"fieldFilter",conjunction:"and",conditions:[r.condition]},valueOf,linkNames);return test?{column:r.condition.column,color:r.color,test}:null});const safe=(test,row)=>{try{return test(row)}catch{return false}};const out=[];tests.forEach((t,i)=>{if(!t)return;const earlier=tests.slice(0,i).filter(e=>!!e&&e.column===t.column);out.push({type:"rule",columns:[t.column],when:({row})=>safe(t.test,row)&&!earlier.some(e=>safe(e.test,row)),background:cellTint(t.color)})});return out}
|
|
@@ -5,6 +5,13 @@ export type FieldEditorRequest = {
|
|
|
5
5
|
columnId?: string;
|
|
6
6
|
/** Where a new field goes (mode 'add'). */
|
|
7
7
|
index?: number | 'end';
|
|
8
|
+
/** What a new field starts as (mode 'add'): its type, and properties such as a formula. */
|
|
9
|
+
preset?: FieldPreset;
|
|
10
|
+
};
|
|
11
|
+
export type FieldPreset = {
|
|
12
|
+
fieldType: string;
|
|
13
|
+
name?: string;
|
|
14
|
+
fieldProps?: Record<string, unknown>;
|
|
8
15
|
};
|
|
9
16
|
export declare const getFieldEditorRequest: () => FieldEditorRequest | null;
|
|
10
17
|
export declare function openFieldEditor(r: FieldEditorRequest): void;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { type ImportedField } from './base-import.js';
|
|
2
|
+
type Ctrl = any;
|
|
3
|
+
/** A grid SvBase drew: these hints are a base's, not a plain grid's. */
|
|
4
|
+
export declare const isBaseGrid: (ctrl: Ctrl) => boolean;
|
|
5
|
+
/** What a sheet's formula is in a base: a formula field's, or a summary of one field. */
|
|
6
|
+
export type SheetFormula = {
|
|
7
|
+
formula: string;
|
|
8
|
+
} | {
|
|
9
|
+
summary: {
|
|
10
|
+
columnId: string;
|
|
11
|
+
kind: 'sum' | 'avg' | 'min' | 'max' | 'median' | 'filled';
|
|
12
|
+
};
|
|
13
|
+
} | null;
|
|
14
|
+
/**
|
|
15
|
+
* A sheet's formula as a base's. `fields` are the names of the shown fields,
|
|
16
|
+
* column A first; `row` is the row the formula was typed on, counted from 1.
|
|
17
|
+
* References on that row become `{Field}` references. A function of one
|
|
18
|
+
* column's run of rows (`=SUM(C2:C9)`) is that field's summary. Anything else
|
|
19
|
+
* reaching other rows has no formula field like it: null.
|
|
20
|
+
*/
|
|
21
|
+
export declare function sheetFormula(text: string, fields: ReadonlyArray<{
|
|
22
|
+
id: string;
|
|
23
|
+
header: string;
|
|
24
|
+
}>, row: number): SheetFormula;
|
|
25
|
+
/** Whether text typed in a cell is a sheet's formula: "=" and something after it. */
|
|
26
|
+
export declare const looksLikeFormula: (value: unknown) => value is string;
|
|
27
|
+
/**
|
|
28
|
+
* A formula was typed in a cell of a field that is not a formula: the base says
|
|
29
|
+
* where formulas go, with a button that makes one from it. `rowIndex` is the
|
|
30
|
+
* row it was typed on; `columnId` the field.
|
|
31
|
+
*/
|
|
32
|
+
export declare function formulaTyped(api: unknown, columnId: string, text: string, rowIndex: number): void;
|
|
33
|
+
/**
|
|
34
|
+
* Alt+= in a base: a sheet's AutoSum writes `=SUM(B1:B9)` into the cell, which
|
|
35
|
+
* a base has no use for. Here the field's sum goes in the summary bar instead,
|
|
36
|
+
* where it keeps up as records change. Registered above the sheet keymap.
|
|
37
|
+
*/
|
|
38
|
+
export declare function autoSumKey(e: KeyboardEvent, cmd: {
|
|
39
|
+
api: unknown;
|
|
40
|
+
editing: boolean;
|
|
41
|
+
activeCell?: {
|
|
42
|
+
colIndex: number;
|
|
43
|
+
} | null;
|
|
44
|
+
}): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* A sheet's formatting keys in a base: bold, italic, underline, Format Cells. A
|
|
47
|
+
* base keeps no formatting typed into a cell, so every screen reads the same
|
|
48
|
+
* data; color comes from rules in the view bar's Color. Said once per grid, with
|
|
49
|
+
* a button that opens Color. The key does nothing else.
|
|
50
|
+
*/
|
|
51
|
+
export declare function formatKey(e: KeyboardEvent, cmd: {
|
|
52
|
+
api: unknown;
|
|
53
|
+
editing: boolean;
|
|
54
|
+
}): boolean;
|
|
55
|
+
/**
|
|
56
|
+
* A record's name typed as "Total": a sheet's totals row. Said once per grid:
|
|
57
|
+
* the summary bar adds up the number fields, with a button that turns it on.
|
|
58
|
+
*/
|
|
59
|
+
export declare function totalTyped(api: unknown, columnId: string, value: unknown): void;
|
|
60
|
+
export type PastePlan = {
|
|
61
|
+
/** The first line is the names of the fields it lands on. */
|
|
62
|
+
named: boolean;
|
|
63
|
+
/** The first line could be names for the fields to add. */
|
|
64
|
+
namesLikely: boolean;
|
|
65
|
+
/** Where the paste starts, among the shown columns. */
|
|
66
|
+
startCol: number;
|
|
67
|
+
/** How many columns of the paste land on a field. */
|
|
68
|
+
room: number;
|
|
69
|
+
/** How many columns have no field to land on. */
|
|
70
|
+
extra: number;
|
|
71
|
+
lines: string[][];
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* What a paste's shape asks of the base, or null when it lands as it is: a
|
|
75
|
+
* first line that is the fields' names, and columns past the last field.
|
|
76
|
+
*/
|
|
77
|
+
export declare function pastePlan(ctrl: Ctrl, lines: string[][]): PastePlan | null;
|
|
78
|
+
/** The fields a paste would add, named from its first line or numbered, typed from their values. */
|
|
79
|
+
export declare function fieldsToAdd(ctrl: Ctrl, plan: PastePlan, namesFromFirst: boolean): ImportedField[];
|
|
80
|
+
export type PasteQuestion = {
|
|
81
|
+
ctrl: Ctrl;
|
|
82
|
+
plan: PastePlan;
|
|
83
|
+
text: string;
|
|
84
|
+
};
|
|
85
|
+
export declare const pasteQuestion: () => PasteQuestion | null;
|
|
86
|
+
export declare const endPasteQuestion: () => void;
|
|
87
|
+
/** The lines to paste now, set by `pasteAgain`, once. */
|
|
88
|
+
export declare function takeReplay(ctrl: Ctrl): string[][] | undefined;
|
|
89
|
+
/** Paste these lines at the selection: the grid's own paste, so it is one undo step and new rows become records. */
|
|
90
|
+
export declare function pasteAgain(ctrl: Ctrl, text: string, lines: string[][]): void;
|
|
91
|
+
/**
|
|
92
|
+
* The lines a paste writes, once the base has looked at its shape. A first line
|
|
93
|
+
* that is the fields' names is left out, and said. Columns with no field to go
|
|
94
|
+
* in: whoever may add fields is asked (the paste waits, and nothing is written
|
|
95
|
+
* now: `[]`); anyone else gets what fits, and is told what was left out.
|
|
96
|
+
*/
|
|
97
|
+
export declare function shapePaste(ctrl: Ctrl, lines: string[][], text: string): string[][];
|
|
98
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toast}from"@svgrid/grid";import{bm,bmCount}from"./messages.svelte.js";import{fieldColumns,gridOf,primaryIdOf}from"./grid-access.js";import{openFieldEditor}from"./editor-request.svelte.js";import{nameTaken,setFieldSummary}from"./field-ops.js";import{summaryChoices}from"./summaries.js";import{guessField}from"./base-import.js";import{hasBar,openBarPanel}from"./bar-request.svelte.js";export const isBaseGrid=ctrl=>ctrl?.props?.baseTableId!=null;function shownFields(ctrl){return(ctrl?.allColumns??[]).filter(c=>c.columnDef?.field!=null&&c.columnDef?.fieldType!=null)}const SUMMARY_OF={SUM:"sum",AVERAGE:"avg",MIN:"min",MAX:"max",MEDIAN:"median",COUNT:"filled",COUNTA:"filled"};const letterIndex=letters=>[...letters.toUpperCase()].reduce((n,c)=>n*26+(c.charCodeAt(0)-64),0)-1;export function sheetFormula(text,fields,row){const src=text.trim().replace(/^=+/,"").trim();if(!src)return null;const whole=/^([A-Za-z]+)\(\s*\$?([A-Za-z]{1,3})\$?(\d+)\s*:\s*\$?([A-Za-z]{1,3})\$?(\d+)\s*\)$/.exec(src);if(whole){const[,fn,c1,r1,c2,r2]=whole;const kind=SUMMARY_OF[fn.toUpperCase()];const col=letterIndex(c1);if(kind&&col===letterIndex(c2)&&r1!==r2&&fields[col])return{summary:{columnId:fields[col].id,kind}}}const ref=letters=>{const f=fields[letterIndex(letters)];return f?`{${f.header}}`:null};let out="";let other=false;let i=0;while(i<src.length){const c=src[i];if(c==='"'){const end=src.indexOf('"',i+1);const stop=end<0?src.length:end+1;out+=src.slice(i,stop);i=stop;continue}if(c===";"){out+=",";i++;continue}const at=/^\$?([A-Za-z]{1,3})\$?(\d+)(?:\s*:\s*\$?([A-Za-z]{1,3})\$?(\d+))?/.exec(src.slice(i));const before=i>0?src[i-1]:"";if(at&&!/[A-Za-z0-9_.{]/.test(before)&&src[i+at[0].length]!=="("){const[all,c1,r1,c2,r2]=at;if(c2==null){const name=ref(c1);if(!name||Number(r1)!==row)other=true;out+=name??all}else{if(r1!==r2||Number(r1)!==row)other=true;const from=Math.min(letterIndex(c1),letterIndex(c2));const to=Math.max(letterIndex(c1),letterIndex(c2));const names=Array.from({length:to-from+1},(_,k)=>fields[from+k]).map(f=>f?`{${f.header}}`:null);if(names.some(n=>n==null))other=true;out+=names.join(", ")}i+=all.length;continue}out+=c;i++}return other?null:{formula:out}}export const looksLikeFormula=value=>typeof value==="string"&&/^=\s*[^=\s]/.test(value.trim());function showSummary(ctrl,columnId,kind){if(!ctrl?.props?.summary)return false;setFieldSummary(ctrl,columnId,kind);return true}const headerOf=(ctrl,columnId)=>fieldColumns(ctrl).find(c=>c.id===columnId)?.header??columnId;export function formulaTyped(api,columnId,text,rowIndex){const ctrl=gridOf(api)??api;if(!isBaseGrid(ctrl))return;const fields=shownFields(ctrl).map(c=>({id:c.id,header:String(c.columnDef.header??c.id)}));const read=sheetFormula(text,fields,rowIndex+1);if(read&&"summary"in read&&ctrl.props.summary){const{columnId:target,kind}=read.summary;const field=headerOf(ctrl,target);toast(bm("shell.formulaIsSummary",{field}),{action:{label:bm("shell.formulaShowSummary",{field}),onClick:()=>void showSummary(ctrl,target,kind)}});return}if(ctrl.props.columnAdder===false){toast(bm("shell.formulaInField"));return}const at=shownFields(ctrl).findIndex(c=>c.id===columnId);const index=ctrl.internalColumns.findIndex(d=>String(d.id??d.field)===columnId);const formula=read&&"formula"in read?read.formula:"";toast(bm("shell.formulaInField"),{action:{label:bm("shell.formulaMakeField"),onClick:()=>openFieldEditor({ctrl,mode:"add",index:index>=0?index+1:at>=0?at+1:"end",preset:{fieldType:"formula",fieldProps:{formula}}})}})}const summable=def=>summaryChoices(def).some(c=>c.value==="sum");export function autoSumKey(e,cmd){if(e.key!=="="||!e.altKey||e.ctrlKey||e.metaKey||cmd.editing)return false;const ctrl=gridOf(cmd.api);if(!isBaseGrid(ctrl))return false;const column=ctrl.allColumns[cmd.activeCell?.colIndex??ctrl.activeCell?.colIndex??-1];if(!column?.columnDef?.fieldType)return false;const field=String(column.columnDef.header??column.id);e.preventDefault();if(!summable(column.columnDef))toast(bm("shell.sumNotNumbers",{field}));else if(showSummary(ctrl,column.id,"sum"))toast(bm("shell.sumShown",{field}));else toast(bm("shell.sumNoBar"));return true}const FORMAT_KEYS=new Set(["b","i","u","1"]);const toldFormat=new WeakSet;export function formatKey(e,cmd){if(cmd.editing||!(e.ctrlKey||e.metaKey)||e.altKey||e.shiftKey||!FORMAT_KEYS.has(e.key.toLowerCase()))return false;const ctrl=gridOf(cmd.api);if(!isBaseGrid(ctrl))return false;e.preventDefault();if(toldFormat.has(ctrl))return true;toldFormat.add(ctrl);toast(bm("shell.formatInBase"),hasBar(ctrl)?{action:{label:bm("shell.formatOpenColor"),onClick:()=>openBarPanel(ctrl,"color")}}:void 0);return true}const TOTAL=/^(grand\s+)?(total|totals|sub\s*total|sum|общо|сума|всичко|итого|gesamt|summe|totale)\s*:?$/iu;const toldTotal=new WeakSet;export function totalTyped(api,columnId,value){const ctrl=gridOf(api)??api;if(!isBaseGrid(ctrl)||typeof value!=="string"||!TOTAL.test(value.trim()))return;if(columnId!==primaryIdOf(ctrl)||!ctrl.props.summary||toldTotal.has(ctrl))return;const numbers=shownFields(ctrl).filter(c=>summable(c.columnDef));if(!numbers.length)return;toldTotal.add(ctrl);toast(bm("shell.totalRecord"),{action:{label:bm("shell.totalShowSums"),onClick:()=>{for(const c of numbers)if(!c.columnDef.fieldProps?.summary)setFieldSummary(ctrl,c.id,"sum")}}})}const key=s=>s.trim().toLocaleLowerCase().replace(/[^\p{L}\p{N}]+/gu,"");const NUMBERISH=/^[\s$€£¥+\-−(]*\d[\d\s.,]*(%|[kmb])?\)?\s*(лв\.?|€|\$)?$/iu;function startColumn(ctrl){const anchor=ctrl.selectionRange?.anchor??ctrl.activeCell;const focus=ctrl.selectionRange?.focus??anchor;if(!anchor)return-1;return Math.min(anchor.colIndex,focus?.colIndex??anchor.colIndex)}export function pastePlan(ctrl,lines){if(!isBaseGrid(ctrl)||!lines.length||lines.length===1&&(lines[0]?.length??0)<=1)return null;const startCol=startColumn(ctrl);if(startCol<0)return null;const columns=ctrl.allColumns;const width=lines.reduce((n,l)=>Math.max(n,l.length),0);const room=Math.max(0,Math.min(width,columns.length-startCol));const first=lines[0]??[];let same=0;let differ=0;for(let j=0;j<room;j++){const cell=key(first[j]??"");if(!cell)continue;const header=key(String(columns[startCol+j]?.columnDef?.header??""));if(header&&cell===header)same++;else differ++}const named=lines.length>1&&same>0&&differ===0;const extra=width-room;if(!named&&extra<=0)return null;const filled=first.filter(c=>c.trim());const namesLikely=named||lines.length>1&&filled.length===first.length&&filled.every(c=>!NUMBERISH.test(c))&&lines.slice(1).some(l=>l.some((c,j)=>NUMBERISH.test(c)&&!NUMBERISH.test(first[j]??"")));return{named,namesLikely,startCol,room,extra:Math.max(0,extra),lines}}export function fieldsToAdd(ctrl,plan,namesFromFirst){const body=namesFromFirst?plan.lines.slice(1):plan.lines;const taken=new Set;const free=name=>!nameTaken(ctrl,name)&&!taken.has(name.toLowerCase());return Array.from({length:plan.extra},(_,k)=>{const j=plan.room+k;const base=(namesFromFirst?(plan.lines[0]?.[j]??"").trim():"")||`${bm("fields.fallbackName")} ${plan.startCol+j+1}`;let name=base;for(let n=2;!free(name);n++)name=`${base} ${n}`;taken.add(name.toLowerCase());return guessField(name,body.map(l=>l[j]??""))})}let question=$state.raw(null);export const pasteQuestion=()=>question;export const endPasteQuestion=()=>void(question=null);const replays=new WeakMap;export function takeReplay(ctrl){const lines=ctrl?replays.get(ctrl):void 0;if(lines)replays.delete(ctrl);return lines}export function pasteAgain(ctrl,text,lines){replays.set(ctrl,lines);ctrl.pasteText(text);replays.delete(ctrl)}export function shapePaste(ctrl,lines,text){const plan=pastePlan(ctrl,lines);if(!plan)return lines;const body=plan.named?lines.slice(1):lines;if(plan.extra>0&&ctrl.props.columnAdder!==false&&ctrl.props.editable!==false){question={ctrl,plan,text};return[]}if(plan.extra>0)toast(bmCount("shell.pasteNoField",plan.extra));else toast(bm("shell.pasteNamesLeftOut"));return body}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A short reference for every function a formula field can call, for the
|
|
3
|
+
* editor's autocomplete and its function list. Each entry says how the
|
|
4
|
+
* function is called, what it gives in one plain sentence, and one example
|
|
5
|
+
* with the kind of fields a small business has. The text follows what
|
|
6
|
+
* formula.ts does, not what a spreadsheet does where the two differ.
|
|
7
|
+
*/
|
|
8
|
+
export type FormulaDocGroup = 'logic' | 'text' | 'numbers' | 'dates' | 'lists' | 'records';
|
|
9
|
+
export type FormulaDoc = {
|
|
10
|
+
/** How it is called, Excel style: IF(condition, value if true, value if false). Optional arguments in [square brackets]. */
|
|
11
|
+
syntax: string;
|
|
12
|
+
/** One plain sentence, at most about 90 characters, saying what it gives. */
|
|
13
|
+
summary: string;
|
|
14
|
+
/** One example using realistic {Field} names of a small business (Qty, Unit price, Status, Due date, Client, Email...), commas between arguments. */
|
|
15
|
+
example: string;
|
|
16
|
+
group: FormulaDocGroup;
|
|
17
|
+
};
|
|
18
|
+
export declare const FORMULA_DOCS: Record<string, FormulaDoc>;
|
|
19
|
+
/**
|
|
20
|
+
* The argument names of a syntax, for showing which one the caret is in:
|
|
21
|
+
* 'IF(condition, value if true, value if false)' -> ['condition', 'value if true', 'value if false'].
|
|
22
|
+
* Square brackets are dropped and "..." is not a name: 'SUM(number1, [number2, ...])' -> ['number1', 'number2'].
|
|
23
|
+
*/
|
|
24
|
+
export declare function syntaxArgs(syntax: string): string[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const FORMULA_DOCS={IF:{syntax:"IF(condition, value if true, [value if false])",summary:"One value when the condition is true, another when it is not (empty if left out).",example:'IF({Qty} > 10, "Bulk", "Small")',group:"logic"},AND:{syntax:"AND(condition1, [condition2, ...])",summary:"True when every condition is true.",example:'AND({Paid}, {Status} = "Shipped")',group:"logic"},OR:{syntax:"OR(condition1, [condition2, ...])",summary:"True when at least one condition is true.",example:'OR({Status} = "Late", {Status} = "Lost")',group:"logic"},NOT:{syntax:"NOT(condition)",summary:"True when the condition is false or empty, false when it is true.",example:"NOT({Paid})",group:"logic"},XOR:{syntax:"XOR(condition1, [condition2, ...])",summary:"True when an odd number of the conditions are true.",example:"XOR({Paid}, {Refunded})",group:"logic"},TRUE:{syntax:"TRUE()",summary:"The value true. You can also write TRUE without the brackets.",example:"IF({Qty} > 0, TRUE(), FALSE())",group:"logic"},FALSE:{syntax:"FALSE()",summary:"The value false. You can also write FALSE without the brackets.",example:'IF({Status} = "Cancelled", FALSE(), TRUE())',group:"logic"},BLANK:{syntax:"BLANK()",summary:"An empty value, for leaving the cell empty.",example:"IF({Qty} = 0, BLANK(), {Qty} * {Unit price})",group:"logic"},ERROR:{syntax:"ERROR()",summary:"Makes the cell show #ERROR, to flag a record that needs a look.",example:"IF({Qty} < 0, ERROR(), {Qty})",group:"logic"},ISERROR:{syntax:"ISERROR(value)",summary:"True when the value is an error, such as ERROR() or a number that cannot be worked out.",example:"IF(ISERROR({Discount}), 0, {Discount})",group:"logic"},SWITCH:{syntax:"SWITCH(value, match1, result1, [match2, result2, ...], [default])",summary:"The result next to the first match for the value, or the default when none match.",example:'SWITCH({Status}, "New", 1, "Paid", 2, "Shipped", 3, 0)',group:"logic"},RECORD_ID:{syntax:"RECORD_ID()",summary:"The id of this record, as text.",example:'"https://example.com/orders/" & RECORD_ID()',group:"records"},CONCATENATE:{syntax:"CONCATENATE(text1, [text2, ...])",summary:"All the values joined into one text, in order. The & sign does the same.",example:'CONCATENATE({First name}, " ", {Last name})',group:"text"},LEN:{syntax:"LEN(text)",summary:"The number of characters in the text.",example:"LEN({Phone})",group:"text"},UPPER:{syntax:"UPPER(text)",summary:"The text in capital letters.",example:"UPPER({Country code})",group:"text"},LOWER:{syntax:"LOWER(text)",summary:"The text in small letters.",example:"LOWER({Email})",group:"text"},TRIM:{syntax:"TRIM(text)",summary:"The text without spaces at the start and the end.",example:"TRIM({Client})",group:"text"},LEFT:{syntax:"LEFT(text, [count])",summary:"The first characters of the text; one character if no count is given.",example:"LEFT({Postcode}, 2)",group:"text"},RIGHT:{syntax:"RIGHT(text, [count])",summary:"The last characters of the text; one character if no count is given.",example:"RIGHT({Phone}, 4)",group:"text"},MID:{syntax:"MID(text, start, [count])",summary:"Characters from a position (1 is the first); the rest of the text if no count.",example:"MID({Invoice no}, 5, 3)",group:"text"},FIND:{syntax:"FIND(text to find, text, [start])",summary:"Where the text is found (1 is the first character), or 0 if not. Case matters.",example:'FIND("@", {Email})',group:"text"},SEARCH:{syntax:"SEARCH(text to find, text, [start])",summary:"Where the text is found (1 is the first character), or empty if not. Case matters.",example:'SEARCH("urgent", {Notes})',group:"text"},SUBSTITUTE:{syntax:"SUBSTITUTE(text, old text, new text, [which one])",summary:"The text with the old text swapped for the new; only the nth one if you give n.",example:'SUBSTITUTE({Phone}, " ", "")',group:"text"},REPLACE:{syntax:"REPLACE(text, start, count, new text)",summary:"The text with count characters from the start position swapped for the new text.",example:'REPLACE({Card number}, 1, 12, "************")',group:"text"},ENCODE_URL_COMPONENT:{syntax:"ENCODE_URL_COMPONENT(text)",summary:"The text made safe to put in a web address.",example:'"https://maps.google.com/?q=" & ENCODE_URL_COMPONENT({Address})',group:"text"},REGEX_MATCH:{syntax:"REGEX_MATCH(text, pattern)",summary:"True when the text fits the pattern (a regular expression).",example:'REGEX_MATCH({Email}, "^[^@ ]+@[^@ ]+[.][a-z]+$")',group:"text"},REGEX_EXTRACT:{syntax:"REGEX_EXTRACT(text, pattern)",summary:"The first part of the text that fits the pattern, or empty if none does.",example:'REGEX_EXTRACT({Notes}, "[0-9]+")',group:"text"},REGEX_REPLACE:{syntax:"REGEX_REPLACE(text, pattern, new text)",summary:"The text with every part that fits the pattern swapped for the new text.",example:'REGEX_REPLACE({Phone}, "[^0-9]", "")',group:"text"},REPT:{syntax:"REPT(text, times)",summary:"The text repeated a number of times (at most 1,000).",example:'REPT("*", {Rating})',group:"text"},T:{syntax:"T(value)",summary:"The value if it is text, otherwise empty text.",example:"T({Notes})",group:"text"},VALUE:{syntax:"VALUE(text)",summary:"The number in the text, ignoring signs like $ and spaces; empty if there is none.",example:"VALUE({Price text}) * {Qty}",group:"text"},ARRAYJOIN:{syntax:"ARRAYJOIN(list, [separator])",summary:'The items of a list joined into one text, with ", " between them unless you say.',example:'ARRAYJOIN({Tags}, " / ")',group:"text"},ARRAYCOMPACT:{syntax:"ARRAYCOMPACT(list)",summary:"The list without its empty items.",example:"ARRAYCOMPACT({Phone numbers})",group:"lists"},ARRAYFLATTEN:{syntax:"ARRAYFLATTEN(list1, [list2, ...])",summary:"One flat list of all the items, with lists inside lists opened up.",example:"ARRAYFLATTEN({Tags}, {Categories})",group:"lists"},ARRAYUNIQUE:{syntax:"ARRAYUNIQUE(list)",summary:"The list with each item only once.",example:"ARRAYUNIQUE({Order cities})",group:"lists"},ARRAYSLICE:{syntax:"ARRAYSLICE(list, start, [end])",summary:"The items from start to end (1 is the first; a negative number counts from the end).",example:"ARRAYSLICE({Tags}, 1, 3)",group:"lists"},SUM:{syntax:"SUM(number1, [number2, ...])",summary:"All the numbers added up.",example:"SUM({Subtotal}, {Shipping}, {Tax})",group:"numbers"},AVERAGE:{syntax:"AVERAGE(number1, [number2, ...])",summary:"The average of the numbers, leaving out empty ones.",example:"AVERAGE({Q1 sales}, {Q2 sales}, {Q3 sales})",group:"numbers"},MAX:{syntax:"MAX(number1, [number2, ...])",summary:"The largest of the numbers.",example:"MAX({Quote A}, {Quote B})",group:"numbers"},MIN:{syntax:"MIN(number1, [number2, ...])",summary:"The smallest of the numbers.",example:"MIN({Stock}, {Qty})",group:"numbers"},COUNT:{syntax:"COUNT(value1, [value2, ...])",summary:"How many of the values are numbers.",example:"COUNT({Mon hours}, {Tue hours}, {Wed hours})",group:"numbers"},COUNTA:{syntax:"COUNTA(value1, [value2, ...])",summary:"How many of the values are not empty.",example:"COUNTA({Phone}, {Email}, {Address})",group:"numbers"},COUNTALL:{syntax:"COUNTALL(value1, [value2, ...])",summary:"How many values there are, empty ones included.",example:"COUNTALL({Attendees})",group:"numbers"},ROUND:{syntax:"ROUND(number, [decimals])",summary:"The number rounded to that many decimal places (none if left out).",example:"ROUND({Qty} * {Unit price}, 2)",group:"numbers"},ROUNDUP:{syntax:"ROUNDUP(number, [decimals])",summary:"The number rounded away from zero to that many decimal places.",example:"ROUNDUP({Hours worked}, 0)",group:"numbers"},ROUNDDOWN:{syntax:"ROUNDDOWN(number, [decimals])",summary:"The number rounded toward zero to that many decimal places.",example:"ROUNDDOWN({Total} * 0.1, 2)",group:"numbers"},INT:{syntax:"INT(number)",summary:"The number rounded down to a whole number.",example:"INT({Hours worked})",group:"numbers"},ABS:{syntax:"ABS(number)",summary:"The number without its minus sign.",example:"ABS({Balance})",group:"numbers"},MOD:{syntax:"MOD(number, divisor)",summary:"What is left after dividing; it takes the sign of the first number.",example:"MOD({Qty}, 12)",group:"numbers"},POWER:{syntax:"POWER(number, power)",summary:"The number raised to the power.",example:"{Deposit} * POWER(1 + {Rate}, {Years})",group:"numbers"},SQRT:{syntax:"SQRT(number)",summary:"The square root of the number.",example:"SQRT({Floor area})",group:"numbers"},EXP:{syntax:"EXP(number)",summary:"The number e (about 2.718) raised to the power you give.",example:"{Deposit} * EXP({Rate} * {Years})",group:"numbers"},LOG:{syntax:"LOG(number, [base])",summary:"The logarithm of the number, in base 10 unless you give another base.",example:"LOG({Visitors}, 10)",group:"numbers"},EVEN:{syntax:"EVEN(number)",summary:"The number rounded away from zero to the next even whole number.",example:"EVEN({Guests})",group:"numbers"},ODD:{syntax:"ODD(number)",summary:"The number rounded away from zero to the next odd whole number.",example:"ODD({Team size})",group:"numbers"},CEILING:{syntax:"CEILING(number, [multiple])",summary:"The number rounded up to a multiple (1 if left out): CEILING(7, 5) is 10.",example:"CEILING({Qty}, 6)",group:"numbers"},FLOOR:{syntax:"FLOOR(number, [multiple])",summary:"The number rounded down to a multiple (1 if left out): FLOOR(7, 5) is 5.",example:"FLOOR({Price}, 0.5)",group:"numbers"},TODAY:{syntax:"TODAY()",summary:"Today's date, at midnight.",example:'DATETIME_DIFF({Due date}, TODAY(), "days")',group:"dates"},NOW:{syntax:"NOW()",summary:"The date and time right now.",example:'DATETIME_DIFF(NOW(), {Created}, "hours")',group:"dates"},YEAR:{syntax:"YEAR(date)",summary:"The year of a date, such as 2026.",example:"YEAR({Invoice date})",group:"dates"},MONTH:{syntax:"MONTH(date)",summary:"The month of a date, from 1 (January) to 12 (December).",example:"MONTH({Invoice date})",group:"dates"},DAY:{syntax:"DAY(date)",summary:"The day of the month of a date, from 1 to 31.",example:"DAY({Due date})",group:"dates"},HOUR:{syntax:"HOUR(date)",summary:"The hour of a date and time, from 0 to 23.",example:"HOUR({Appointment})",group:"dates"},MINUTE:{syntax:"MINUTE(date)",summary:"The minute of a date and time, from 0 to 59.",example:"MINUTE({Appointment})",group:"dates"},SECOND:{syntax:"SECOND(date)",summary:"The second of a date and time, from 0 to 59.",example:"SECOND({Logged at})",group:"dates"},WEEKDAY:{syntax:"WEEKDAY(date, [first day])",summary:'The day of the week, 0 for Sunday to 6; with "Monday" as first day, 0 is Monday.',example:'WEEKDAY({Delivery date}, "Monday")',group:"dates"},WEEKNUM:{syntax:"WEEKNUM(date, [first day])",summary:'The week of the year (week 1 holds January 1); weeks start Sunday, or "Monday".',example:'WEEKNUM({Order date}, "Monday")',group:"dates"},DATEADD:{syntax:"DATEADD(date, count, [unit])",summary:"The date moved on by a number of days, weeks, months, years... (days if no unit).",example:'DATEADD({Invoice date}, 30, "days")',group:"dates"},DATETIME_DIFF:{syntax:"DATETIME_DIFF(date1, date2, [unit])",summary:"The time between two dates: the first minus the second, in days or another unit.",example:'DATETIME_DIFF({Due date}, TODAY(), "days")',group:"dates"},IS_BEFORE:{syntax:"IS_BEFORE(date1, date2)",summary:"True when the first date is before the second.",example:"IS_BEFORE({Due date}, TODAY())",group:"dates"},IS_AFTER:{syntax:"IS_AFTER(date1, date2)",summary:"True when the first date is after the second.",example:"IS_AFTER({Delivered on}, {Due date})",group:"dates"},IS_SAME:{syntax:"IS_SAME(date1, date2, [unit])",summary:"True when two dates are the same moment, or the same day, month, year... by unit.",example:'IS_SAME({Order date}, TODAY(), "month")',group:"dates"},DATESTR:{syntax:"DATESTR(date)",summary:"The date as text, year first: 2026-12-04.",example:"DATESTR({Due date})",group:"dates"},TIMESTR:{syntax:"TIMESTR(date)",summary:"The time of a date as text, in 24 hours: 14:30:00.",example:"TIMESTR({Appointment})",group:"dates"},DATETIME_FORMAT:{syntax:"DATETIME_FORMAT(date, [format])",summary:'The date as text in the format you write, such as "DD/MM/YYYY" or "MMMM D".',example:'DATETIME_FORMAT({Due date}, "DD/MM/YYYY")',group:"dates"},DATETIME_PARSE:{syntax:"DATETIME_PARSE(text, [format])",summary:"The date written in the text, read with the format if you give one.",example:'DATETIME_PARSE({Date text}, "DD.MM.YYYY")',group:"dates"},SET_LOCALE:{syntax:"SET_LOCALE(date, locale)",summary:'The date, set to show month and day names in a language, such as "fr" or "de".',example:'DATETIME_FORMAT(SET_LOCALE({Due date}, "fr"), "D MMMM YYYY")',group:"dates"},SET_TIMEZONE:{syntax:"SET_TIMEZONE(date, time zone)",summary:'The date, set to show the clock of a time zone, such as "Europe/London".',example:'DATETIME_FORMAT(SET_TIMEZONE({Appointment}, "Europe/London"), "HH:mm")',group:"dates"},TONOW:{syntax:"TONOW(date)",summary:"The number of days from the date to today.",example:"TONOW({Last contacted})",group:"dates"},FROMNOW:{syntax:"FROMNOW(date)",summary:"The number of days from today to the date.",example:"FROMNOW({Due date})",group:"dates"},WORKDAY:{syntax:"WORKDAY(start date, days, [holidays])",summary:"The date that many working days on, skipping weekends and the holidays.",example:'WORKDAY({Order date}, 5, "2026-12-25, 2026-12-26")',group:"dates"},WORKDAY_DIFF:{syntax:"WORKDAY_DIFF(start date, end date, [holidays])",summary:"The working days from start to end, both days counted, skipping the holidays.",example:'WORKDAY_DIFF({Start date}, {End date}, "2026-12-25")',group:"dates"}};export function syntaxArgs(e){const t=e.indexOf("("),a=e.lastIndexOf(")");return t<0||a<=t?[]:e.slice(t+1,a).replace(/[[\]]/g,"").split(",").map(s=>s.replace(/\.{3}|…/g,"").trim()).filter(Boolean)}
|
package/dist/fields/index.d.ts
CHANGED
|
@@ -3,11 +3,13 @@ export { linkHref, linkText, type LinkKind } from './links.js';
|
|
|
3
3
|
export { setFieldUsers, getFieldUsers, setCurrentUser, getCurrentUser, registerLinkedTable, unregisterLinkedTable, getLinkedTable, listLinkedTables, type FieldUser, type LinkedTable, } from './sources.svelte.js';
|
|
4
4
|
export { canEditField, defaultCanEditField, fieldEditors, setCanEditField, setFieldProtection, type CanEditField, type FieldAccessField, } from './field-access.svelte.js';
|
|
5
5
|
export { compileFormula, formulaError, FORMULA_FUNCTIONS, FormulaError } from './formula.js';
|
|
6
|
+
export { FORMULA_DOCS, syntaxArgs, type FormulaDoc, type FormulaDocGroup } from './formula-docs.js';
|
|
6
7
|
export { formatNumber, formatCurrency, formatPercent, formatDuration, parseDuration, formatDate } from './format.js';
|
|
7
8
|
export { timerRunning, timerSeconds, timerToggle, timerTotal, type TimerRunning, type TimerValue } from './timer.js';
|
|
8
9
|
export { BRIGHT, OPTION_COLORS } from './palette.js';
|
|
9
10
|
export { convertValue, countCleared } from './convert.js';
|
|
10
11
|
export { openFieldEditor, closeFieldEditor, openRecord, closeRecord, type OpenRecordRequest } from './editor-request.svelte.js';
|
|
12
|
+
export { setBarcodeScanner, barcodeScanSupported, scanBarcode, type BarcodeScannerFn } from './barcode-scan.js';
|
|
11
13
|
export { default as SvBaseViewBar } from './SvBaseViewBar.svelte';
|
|
12
14
|
export { default as SvBaseForm } from './SvBaseForm.svelte';
|
|
13
15
|
export { default as SvBaseAutomations } from './SvBaseAutomations.svelte';
|
package/dist/fields/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{registerCellEditor as f,registerGridExtension as O,registerGridShortcuts as g}from"@svgrid/grid";import{nudgeEnterpriseFor as P}from"../license.js";import B from"./FieldCell.svelte";import L from"./RowAdder.svelte";import V from"./FootRowAdder.svelte";import H from"./AttachmentEditor.svelte";import N from"./FieldsHeaderEnd.svelte";import{askDeleteField as U,openFieldEditor as C,openRecord as _}from"./editor-request.svelte.js";import{enableAdvancedFilter as G,registerFilterKind as K}from"../advanced-filter-enable.js";import{compileFieldFilter as z,newCondition as w,resolveMeWith as $}from"./filter-model.js";import{hasBar as q,openBarPanel as F}from"./bar-request.svelte.js";import{groupRules as X,userSorts as j,writeSortState as W}from"./viewbar/sort-state.js";import{sortLabels as Y}from"./view-model.js";import{changesOf as J,noteChange as T}from"./activity.svelte.js";import{fieldUses as Q}from"./field-uses.js";import{getLinkedTable as Z}from"./sources.svelte.js";import{linkNames as ee,registerBaseCondition as oe}from"./base-alerts.js";import{duplicateField as re,hideField as ie,indexBeside as v,removeField as te}from"./field-ops.js";import{linkReaders as ne}from"./base-tables.js";import{viewOnlyItems as le}from"./base-share.js";import{canEditSchemaIn as se}from"./base-permissions.js";import{formulaReaders as de}from"./formula.js";import{BUILTIN_FIELD_TYPES as me}from"./builtin-types.js";import{rowColorOf as ae,rowColorRootClass as fe,tallRowClass as pe,rowMarkColor as ue,rowMarkLabel as ce}from"./row-colors.js";import{chooseRowColor as M}from"./row-color-choice.svelte.js";import{fieldPropsOf as A,fillFieldColumn as ge,getFieldType as E,isServerGroupRow as Ce,originalColumn as b,registerFieldType as be,typeDrawsCell as ye}from"./registry.svelte.js";import he from"./RatingEditor.svelte";import we from"./LinkPickerEditor.svelte";import Fe from"./DateEditor.svelte";import Te from"./SelectEditor.svelte";import ve from"./NumberEditor.svelte";import Me from"./LongTextEditor.svelte";import Ae from"./RichTextEditor.svelte";import Ee from"./VoteEditor.svelte";import xe from"./TimerEditor.svelte";import ke from"./ChecklistEditor.svelte";import Se from"./ColorEditor.svelte";import Re from"./TimeOfDayEditor.svelte";import De from"./RowHeader.svelte";import Ie from"./GroupHeader.svelte";import Oe from"./SummaryCell.svelte";import{getCurrentUser as x}from"./sources.svelte.js";import{fieldColumns as Pe,gridOf as y,primaryIdOf as h,rememberGrid as Be}from"./grid-access.js";import{bm as p}from"./messages.svelte.js";export{registerFieldType,getFieldType,listFieldTypes,fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";export{linkHref,linkText}from"./links.js";export{setFieldUsers,getFieldUsers,setCurrentUser,getCurrentUser,registerLinkedTable,unregisterLinkedTable,getLinkedTable,listLinkedTables}from"./sources.svelte.js";export{canEditField,defaultCanEditField,fieldEditors,setCanEditField,setFieldProtection}from"./field-access.svelte.js";import{protectionText as Le}from"./field-access.svelte.js";export{compileFormula,formulaError,FORMULA_FUNCTIONS,FormulaError}from"./formula.js";export{formatNumber,formatCurrency,formatPercent,formatDuration,parseDuration,formatDate}from"./format.js";export{timerRunning,timerSeconds,timerToggle,timerTotal}from"./timer.js";export{BRIGHT,OPTION_COLORS}from"./palette.js";export{convertValue,countCleared}from"./convert.js";export{openFieldEditor,closeFieldEditor,openRecord,closeRecord}from"./editor-request.svelte.js";export{default as SvBaseViewBar}from"./SvBaseViewBar.svelte";export{default as SvBaseForm}from"./SvBaseForm.svelte";export{default as SvBaseAutomations}from"./SvBaseAutomations.svelte";export{formPrefillLink,readFormPrefill}from"./form-logic.js";export{default as SvBase}from"./SvBase.svelte";export{addSubtasks,blankTable,newRecordId}from"./base-tables.js";export{baseSource,createBaseSync}from"./base-sync.js";export{baseFieldsFromSchema,baseTablesFromSchemas,baseSpecFromSchemas,baseTablesFromSpec}from"./base-schema.js";export{baseToSql,sqlName}from"./base-sql.js";export{applyBaseComments,withInverses}from"./base-schema.js";export{restoreItems,trashLabel}from"./base-trash.js";export{guessField,tableFromMatrix,recordsFromMatrix,matchColumns}from"./base-import.js";export{baseFromDatabase,describeDatabase,createBaseEndpoint,baseFromEndpoint,createBaseFeed,baseFromSupabase,isSecretColumn}from"./base-connect.js";export{baseFromAirtable,airtableFormulaSupport,airtableColor,formulaFunctionsUsed}from"./airtable.js";export{registerAutomationAction,listAutomationActions,MAX_DEPTH as AUTOMATION_MAX_DEPTH,REPEAT_MOST as AUTOMATION_REPEAT_MOST,allActions as allAutomationActions,scriptRecord,scriptInput,webhookValues,triggerValues}from"./automations.svelte.js";export{createAutomationServer}from"./automation-server.js";export{chatPayload,chatHostOk}from"./automation-outbound.js";export{runScript,SCRIPT_MAX_LENGTH}from"./automation-script.js";export{newWebhookToken}from"./automation-edit.js";export{setViewActions}from"./view-actions.js";export{setRecordActions}from"./record-actions.js";export{setRecordComments}from"./activity.svelte.js";export{setCommentSnippets}from"./comment-snippets.svelte.js";export{setFormSuggestions}from"./form-suggestions.svelte.js";export{setBaseMessages,baseMessages,BASE_MESSAGES}from"./messages.svelte.js";export{setRecordHistory,historyOf,loadHistory}from"./activity.svelte.js";export{setMentionHandler}from"./activity.svelte.js";export{mentionToken,mentionIds,mentionText,parseMentions,encodeMentions}from"./mentions.js";export{baseCondition,baseFilterOf}from"./base-alerts.js";export{compileFieldFilter,describeFieldFilter,filterKindOf,operatorsFor,ME}from"./filter-model.js";export{BUILTIN_FIELD_TYPES}from"./builtin-types.js";export{setAttachmentUploader,attachmentsFromText,attachmentsText,toAttachments}from"./attachments.js";const a={edit:"M4 20h4L19 9l-4-4L4 16zM14 6l4 4",left:"M10 6l-6 6 6 6M4 12h11M20 5v14",right:"M14 6l6 6-6 6M20 12H9M4 5v14",duplicate:"M8 8h12v12H8zM16 8V4H4v12h4",hide:"M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 5.1A9.8 9.8 0 0 1 12 5c5 0 9 5 10 7a13.4 13.4 0 0 1-3 3.9M6.6 6.6A13.5 13.5 0 0 0 2 12c1 2 5 7 10 7a9.6 9.6 0 0 0 4.4-1.1",remove:"M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13",color:"M12 3l6 7a6.5 6.5 0 1 1-12 0l6-7z",filter:"M4 5h16l-6 7v6l-4 2v-8z",group:"M4 5h16M4 10h10M4 15h16M4 20h10",info:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 11v5M12 8h.01",lock:"M6 11h12v9H6zM8.5 11V8a3.5 3.5 0 0 1 7 0v3"};function Ve(o,r){const e=(o?.internalColumns??[]).find(d=>String(d.id??d.field)===r),i=e?.fieldType==="singleSelect"&&e.field?ae(o)?.field===e.field?{key:"field-rowcolor",label:p("fields.menuStopColoring"),icon:a.color,run:()=>M(o,null)}:{key:"field-rowcolor",label:p("fields.menuColorRows"),icon:a.color,run:()=>M(o,{field:String(e.field),...o.props.rowColor?.target?{target:o.props.rowColor.target}:{}})}:null,t=h(o)===r,l=e&&q(o)?[...w(r,e)?[{key:"field-filter",label:p("fields.menuFilter"),icon:a.filter,separatorBefore:!0,run:()=>He(o,r,e)}]:[],...o.groupingControlsEnabled?[]:[{key:"field-group",label:p("fields.menuGroup"),icon:a.group,run:()=>Ne(o,r)}]]:[];return[...i?[i]:[],{key:"field-edit",label:p("fields.menuEdit"),icon:a.edit,run:()=>C({ctrl:o,mode:"edit",columnId:r})},...t?[]:[{key:"field-left",label:p("fields.menuInsertLeft"),icon:a.left,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"left")})}],{key:"field-right",label:p("fields.menuInsertRight"),icon:a.right,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"right")})},{key:"field-duplicate",label:p("fields.menuDuplicate"),icon:a.duplicate,run:()=>{o.props.baseRefuseDuplicate?.(r)||re(o,r)}},...t?[]:[{key:"field-move-left",label:p("fields.menuMoveLeft"),icon:a.left,disabled:!S(o,r,-1),run:()=>R(o,r,-1)},{key:"field-move-right",label:p("fields.menuMoveRight"),icon:a.right,disabled:!S(o,r,1),run:()=>R(o,r,1)}],...l,...je(o,r,e),...t?[]:[{key:"field-hide",label:p("fields.menuHide"),icon:a.hide,run:()=>ie(o,r)},{key:"field-delete",label:p("fields.menuDelete"),icon:a.remove,separatorBefore:!0,run:()=>e?.fieldType==="link"&&(e.fieldProps?.inverse&&Z(e.fieldProps.table)||ne({columns:o.internalColumns},e).length)||e&&de(o.internalColumns??[],e).length||Q(o,e).length?U({ctrl:o,columnId:r}):te(o,r)}]]}function k(o,r,e){const i=(o.allColumns??[]).map(l=>l.id),t=i[i.indexOf(r)+e];if(!(!t||t===h(o)||o.isColumnPinned?.(t)!==o.isColumnPinned?.(r)))return t}const S=(o,r,e)=>!!k(o,r,e);function R(o,r,e){const i=k(o,r,e);if(!i)return;const t=o.allColumns.map(n=>n.id),l=t.indexOf(r),d=t.indexOf(i);t[l]=i,t[d]=r;const m=o.grid.getAllColumns().map(n=>n.id),s=o.userColumnOrder??[];o.moveColumnsByUser(qe(s.length?[...s,...m.filter(n=>!s.includes(n))]:m,t))}function He(o,r,e){const i=w(r,e);if(!i)return;const t=o.advancedFilter,l=t?.kind==="fieldFilter"?t:{kind:"fieldFilter",conjunction:"and",conditions:[]};o.buildApi().setAdvancedFilter({...l,conditions:[...l.conditions,i]}),F(o,"filter")}function Ne(o,r){const e=X(o);e.some(i=>i.id===r)||W(o.buildApi(),[...e,{id:r,desc:!1}],j(o)),F(o,"group")}function D(o,r,e,i,t){if(!r)return;const l=x()?.id,d=i??o.buildApi?.().getRowId?.(r),m=(s,n)=>{d!=null&&!t&&o.editedCellValues&&(o.editedCellValues={...o.editedCellValues,[`${d}:${s}`]:n})};for(const s of o?.internalColumns??[]){if(s.fieldType!=="lastModifiedTime"&&s.fieldType!=="lastModifiedBy")continue;const n=String(s.id??s.field);if(n===e||!s.field)continue;const u=A(b(s));u.watch==="specific"&&!(u.watchFields??[]).includes(e)||(s.fieldType==="lastModifiedTime"?m(n,r[s.field]=new Date().toISOString()):l!==void 0&&m(n,r[s.field]=l))}}export function baseReviewApplied(o){return(r,e,i)=>{const t=y(typeof o=="function"?o():o);if(!t)return;const l=t.buildApi?.(),d=l?.getOption?.("getRowId"),m=new Map;(i??l?.getData?.()??[]).forEach((n,u)=>m.set(String(d?d(n,u):u),n));const s=new Map((t.allColumns??[]).map(n=>[n.columnDef?.field,n.id]));for(const n of r){const u=m.get(n.rowId),c=s.get(n.field);!u||!c||(D(t,u,c),T(t,n.rowId,c,u[n.field],void 0,e==="undo"?void 0:n.source.label))}}}function Ue(o,r,e,i){if(!r)return;const t=(o?.allColumns??[]).find(c=>c.id===e)?.columnDef;if(!t?.field)return;const l=i??o.buildApi?.().getRowId?.(r);if(l==null)return;const d=String(l),m=r[t.field],s=o.history?.[o.historyPtr],n=[...J(o,d)].reverse().find(c=>c.columnId===e),u=s?.rowId===d&&s.columnId===e&&s.after===m?{from:s.before}:n?{from:n.value}:void 0;T(o,d,e,m,void 0,void 0,u)}function _e(o,r){if(o.key!==" "||o.ctrlKey||o.metaKey||o.altKey||o.shiftKey||r.editing||!r.activeCell)return!1;const e=y(r.api);if(!e?.props?.expandRows)return!1;const i=(e.allColumns??[]).find(l=>l.id===r.activeCell.columnId);if(i?.columnDef.editorType==="checkbox"||i?.columnDef.editorType==="fieldVote")return!1;const t=(e.allRows??[])[r.activeCell.rowIndex];return!t||e.isGroupRow?.(t)||Ce(t.original)?!1:(o.preventDefault(),_({ctrl:e,rowId:t.id}),!0)}function Ge(o,r){if(o.key!=="Enter"&&o.key!==" "||o.ctrlKey||o.metaKey||o.altKey||o.shiftKey||r.editing||!r.activeCell)return!1;const e=y(r.api);if(!e?.props?.baseDeleteSelection)return!1;const{rowIndex:i,colIndex:t}=r.activeCell,l=e.allColumns?.[t]?.columnDef.editorType,d=l==="checkbox";if(o.key===" "&&!d&&l!=="fieldVote")return!1;const m=r.ranges.at(-1);return o.key==="Enter"&&(r.ranges.length>1||m&&(m[0]!==m[2]||m[1]!==m[3]))||!e.isCellEditableAt(i,t)?!1:(o.preventDefault(),d?(e.toggleBooleanCell(i,t),!0):(r.startEditing(i,t),!!e.editingCell))}import{baseGridKey as Ke}from"./base-keys.svelte.js";import{treeGridKey as ze}from"./tree-edit.js";import{fillDownKey as $e}from"./base-fill.js";import{orderKeepingScreen as qe}from"./column-order.js";let I=!1;export function enableFields(){if(I)return;I=!0;for(const e of me)E(e.id)||be(e);O({column:(e,i)=>ge(e,i),cell:B,hasCell:e=>ye(e??{}),cellEdited:(e,i)=>{D(e,i.row,i.columnId,i.rowId,i.offGrid),Ue(e,i.row,i.columnId,i.rowId),Xe(e,i.row,i.columnId,i.rowId)},rangeAction:(e,i)=>e.props?.baseRangeAction?.(i)===!0,bodyEnd:L,footEnd:V,rowMarkColor:(e,i)=>ue(e,i),rowMarkLabel:(e,i)=>ce(e,i),headerIcon:e=>e?.fieldType?E(e.fieldType)?.icon:null,headerNote:e=>{if(!e?.fieldType)return null;const i=typeof e.description=="string"?e.description:"",t=Le(b(e),A(b(e)));return t?{text:i?`${t} ${i}`:t,icon:a.lock}:i?{text:i,icon:a.info}:null},sortLabels:e=>e?.fieldType?Y(e):null,lockColumn:(e,i)=>h(e)===i,rowHeader:e=>e?.props?.expandRows?De:null,groupRow:e=>!e?.props?.rowModel&&Pe(e).some(i=>i.fieldType)?Ie:null,summaryCell:e=>e?.props?.rowModel?null:Oe,rootClass:e=>{Be(e);const i=e?.advancedFilter?.kind==="fieldFilter"?"sv-fields-own-filter":"",t=i&&!e?.toolPanelEnabled&&!e?.chartingEnabled?"sv-fields-filter-only":"",l=e?.groupingColumns?.length?"sv-fields-grouped":"";return[fe(e),pe(e),i,t,l].filter(Boolean).join(" ")||null},headerEnd:N,columnMenuItems:(e,i)=>e?.props?.fieldMenu?le(e,Ve(e,i),!se(e)):[]});const o=e=>({value:e.value,typed:e.typed,columnDef:e.columnDef,columnId:e.columnId,row:e.row,onCommit:e.onCommit,onCancel:e.onCancel});f("fieldRating",{component:he,props:o,typeToEdit:e=>/^[0-9]$/.test(e)}),f("fieldLink",{component:we,props:o,typeToEdit:e=>e!==" "}),f("fieldNumber",{component:ve,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9.,:+\-(]/.test(e)}),f("fieldLongText",{component:Me,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove})}),f("fieldSelect",{component:Te,props:e=>({...o(e),grid:e.grid,onChange:e.onChange,onCommitAndMove:e.onCommitAndMove})}),f("attachment",{component:H,props:e=>({value:e.value,columnDef:e.columnDef,columnId:e.columnId,row:e.row,onCommit:e.onCommit,onCancel:e.onCancel}),typeToEdit:!1});const r=e=>({...o(e),onCommitAndMove:e.onCommitAndMove});f("fieldChecklist",{component:ke,props:r}),f("fieldRichText",{component:Ae,props:r}),f("fieldVote",{component:Ee,props:r,typeToEdit:e=>e===" "}),f("fieldTimer",{component:xe,props:e=>({...r(e),rowId:e.rowId,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>e===" "||/[0-9:]/.test(e)}),f("fieldColor",{component:Se,props:r}),f("fieldTime",{component:Re,props:e=>({...r(e),onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9]/.test(e)}),f("fieldDate",{component:Fe,props:e=>({...r(e),onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9a-z]/i.test(e)}),K("fieldFilter",(e,i)=>z(e,i.getValue,ee)),$(()=>x()?.id),oe(),G(),g(_e,{id:"svgrid-fields-space"}),g(Ke,{id:"svgrid-fields-keys"}),g(Ge,{id:"svgrid-base-keys"}),g($e,{id:"svgrid-base-fill-down"}),g(ze,{id:"svgrid-base-tree"}),P("base","SvGrid Base")}export{inboxRecords,listColumns,listGroups,viewRecords}from"./list-view.js";import{aiFieldEdited as Xe,aiFieldMenuItems as je}from"./ai-field.svelte.js";export{generateAIField,regenerateAIFields,cancelAIField,pendingAIField,setAIFieldConcurrency}from"./ai-field.svelte.js";export{aiPromptError,readAIAnswer}from"./ai-prompt.js";export{moveTile,newTile,putTile,removeTile,tileResult,tileRows,tileTitle}from"./dashboard.js";export{sharedTables,sharedViews,shareOf}from"./base-share.js";export{recordsAsShown,downloadAsShown}from"./base-export.js";export{permittedTables,permittedRecords,permittedViews,tablePermissions,gridPermissions}from"./base-permissions.js";export{computeRecords,computeRecord,computedValues,computedFields,evaluateFilter,filterRecords}from"./base-compute.js";export{queryRecords,fieldFilterToSql,fieldFilterToPostgrest,supabaseFieldFilter,viewFilterOf}from"./base-query.js";export{searchBase}from"./base-search.js";export{toChecklist,parseChecklist,checklistText,checklistProgress}from"./checklist.js";export{parseColor}from"./color-value.js";export{parseTimeOfDay,formatTimeOfDay,timeSeconds}from"./time-of-day.js";
|
|
1
|
+
import{registerCellEditor as f,registerGridExtension as I,registerGridShortcuts as g}from"@svgrid/grid";import{nudgeEnterpriseFor as B}from"../license.js";import P from"./FieldCell.svelte";import L from"./RowAdder.svelte";import V from"./FootRowAdder.svelte";import H from"./AttachmentEditor.svelte";import K from"./FieldsHeaderEnd.svelte";import{askDeleteField as U,openFieldEditor as C,openRecord as _}from"./editor-request.svelte.js";import{enableAdvancedFilter as N,registerFilterKind as G}from"../advanced-filter-enable.js";import{compileFieldFilter as z,newCondition as F,resolveMeWith as $}from"./filter-model.js";import{hasBar as q,openBarPanel as w}from"./bar-request.svelte.js";import{groupRules as X,userSorts as j,writeSortState as W}from"./viewbar/sort-state.js";import{sortLabels as Y}from"./view-model.js";import{changesOf as J,noteChange as T}from"./activity.svelte.js";import{fieldUses as Q}from"./field-uses.js";import{getLinkedTable as Z}from"./sources.svelte.js";import{linkNames as ee,registerBaseCondition as oe}from"./base-alerts.js";import{duplicateField as re,hideField as ie,indexBeside as v,removeField as te}from"./field-ops.js";import{linkReaders as ne}from"./base-tables.js";import{viewOnlyItems as le}from"./base-share.js";import{canEditSchemaIn as se}from"./base-permissions.js";import{formulaReaders as de}from"./formula.js";import{BUILTIN_FIELD_TYPES as ae}from"./builtin-types.js";import{rowColorOf as me,rowColorRootClass as fe,tallRowClass as pe,rowMarkColor as ue,rowMarkLabel as ce}from"./row-colors.js";import{chooseRowColor as M}from"./row-color-choice.svelte.js";import{fieldPropsOf as A,fillFieldColumn as ge,getFieldType as E,isServerGroupRow as Ce,originalColumn as b,registerFieldType as be,typeDrawsCell as ye}from"./registry.svelte.js";import he from"./RatingEditor.svelte";import Fe from"./LinkPickerEditor.svelte";import we from"./DateEditor.svelte";import Te from"./SelectEditor.svelte";import ve from"./NumberEditor.svelte";import Me from"./LongTextEditor.svelte";import Ae from"./RichTextEditor.svelte";import Ee from"./VoteEditor.svelte";import xe from"./TimerEditor.svelte";import ke from"./ChecklistEditor.svelte";import Se from"./ColorEditor.svelte";import Re from"./TimeOfDayEditor.svelte";import De from"./RowHeader.svelte";import Oe from"./GroupHeader.svelte";import Ie from"./SummaryCell.svelte";import{getCurrentUser as x}from"./sources.svelte.js";import{fieldColumns as Be,gridOf as y,primaryIdOf as h,rememberGrid as Pe}from"./grid-access.js";import{bm as p}from"./messages.svelte.js";export{registerFieldType,getFieldType,listFieldTypes,fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";export{linkHref,linkText}from"./links.js";export{setFieldUsers,getFieldUsers,setCurrentUser,getCurrentUser,registerLinkedTable,unregisterLinkedTable,getLinkedTable,listLinkedTables}from"./sources.svelte.js";export{canEditField,defaultCanEditField,fieldEditors,setCanEditField,setFieldProtection}from"./field-access.svelte.js";import{protectionText as Le}from"./field-access.svelte.js";export{compileFormula,formulaError,FORMULA_FUNCTIONS,FormulaError}from"./formula.js";export{FORMULA_DOCS,syntaxArgs}from"./formula-docs.js";export{formatNumber,formatCurrency,formatPercent,formatDuration,parseDuration,formatDate}from"./format.js";export{timerRunning,timerSeconds,timerToggle,timerTotal}from"./timer.js";export{BRIGHT,OPTION_COLORS}from"./palette.js";export{convertValue,countCleared}from"./convert.js";export{openFieldEditor,closeFieldEditor,openRecord,closeRecord}from"./editor-request.svelte.js";export{setBarcodeScanner,barcodeScanSupported,scanBarcode}from"./barcode-scan.js";export{default as SvBaseViewBar}from"./SvBaseViewBar.svelte";export{default as SvBaseForm}from"./SvBaseForm.svelte";export{default as SvBaseAutomations}from"./SvBaseAutomations.svelte";export{formPrefillLink,readFormPrefill}from"./form-logic.js";export{default as SvBase}from"./SvBase.svelte";export{addSubtasks,blankTable,newRecordId}from"./base-tables.js";export{baseSource,createBaseSync}from"./base-sync.js";export{baseFieldsFromSchema,baseTablesFromSchemas,baseSpecFromSchemas,baseTablesFromSpec}from"./base-schema.js";export{baseToSql,sqlName}from"./base-sql.js";export{applyBaseComments,withInverses}from"./base-schema.js";export{restoreItems,trashLabel}from"./base-trash.js";export{guessField,tableFromMatrix,recordsFromMatrix,matchColumns}from"./base-import.js";export{baseFromDatabase,describeDatabase,createBaseEndpoint,baseFromEndpoint,createBaseFeed,baseFromSupabase,isSecretColumn}from"./base-connect.js";export{baseFromAirtable,airtableFormulaSupport,airtableColor,formulaFunctionsUsed}from"./airtable.js";export{registerAutomationAction,listAutomationActions,MAX_DEPTH as AUTOMATION_MAX_DEPTH,REPEAT_MOST as AUTOMATION_REPEAT_MOST,allActions as allAutomationActions,scriptRecord,scriptInput,webhookValues,triggerValues}from"./automations.svelte.js";export{createAutomationServer}from"./automation-server.js";export{chatPayload,chatHostOk}from"./automation-outbound.js";export{runScript,SCRIPT_MAX_LENGTH}from"./automation-script.js";export{newWebhookToken}from"./automation-edit.js";export{setViewActions}from"./view-actions.js";export{setRecordActions}from"./record-actions.js";export{setRecordComments}from"./activity.svelte.js";export{setCommentSnippets}from"./comment-snippets.svelte.js";export{setFormSuggestions}from"./form-suggestions.svelte.js";export{setBaseMessages,baseMessages,BASE_MESSAGES}from"./messages.svelte.js";export{setRecordHistory,historyOf,loadHistory}from"./activity.svelte.js";export{setMentionHandler}from"./activity.svelte.js";export{mentionToken,mentionIds,mentionText,parseMentions,encodeMentions}from"./mentions.js";export{baseCondition,baseFilterOf}from"./base-alerts.js";export{compileFieldFilter,describeFieldFilter,filterKindOf,operatorsFor,ME}from"./filter-model.js";export{BUILTIN_FIELD_TYPES}from"./builtin-types.js";export{setAttachmentUploader,attachmentsFromText,attachmentsText,toAttachments}from"./attachments.js";const m={edit:"M4 20h4L19 9l-4-4L4 16zM14 6l4 4",left:"M10 6l-6 6 6 6M4 12h11M20 5v14",right:"M14 6l6 6-6 6M20 12H9M4 5v14",duplicate:"M8 8h12v12H8zM16 8V4H4v12h4",hide:"M3 3l18 18M10.6 10.6a2 2 0 0 0 2.8 2.8M9.9 5.1A9.8 9.8 0 0 1 12 5c5 0 9 5 10 7a13.4 13.4 0 0 1-3 3.9M6.6 6.6A13.5 13.5 0 0 0 2 12c1 2 5 7 10 7a9.6 9.6 0 0 0 4.4-1.1",remove:"M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13",color:"M12 3l6 7a6.5 6.5 0 1 1-12 0l6-7z",filter:"M4 5h16l-6 7v6l-4 2v-8z",group:"M4 5h16M4 10h10M4 15h16M4 20h10",info:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 11v5M12 8h.01",lock:"M6 11h12v9H6zM8.5 11V8a3.5 3.5 0 0 1 7 0v3"};function Ve(o,r){const e=(o?.internalColumns??[]).find(d=>String(d.id??d.field)===r),i=e?.fieldType==="singleSelect"&&e.field?me(o)?.field===e.field?{key:"field-rowcolor",label:p("fields.menuStopColoring"),icon:m.color,run:()=>M(o,null)}:{key:"field-rowcolor",label:p("fields.menuColorRows"),icon:m.color,run:()=>M(o,{field:String(e.field),...o.props.rowColor?.target?{target:o.props.rowColor.target}:{}})}:null,t=h(o)===r,l=e&&q(o)?[...F(r,e)?[{key:"field-filter",label:p("fields.menuFilter"),icon:m.filter,separatorBefore:!0,run:()=>He(o,r,e)}]:[],...o.groupingControlsEnabled?[]:[{key:"field-group",label:p("fields.menuGroup"),icon:m.group,run:()=>Ke(o,r)}]]:[];return[...i?[i]:[],{key:"field-edit",label:p("fields.menuEdit"),icon:m.edit,run:()=>C({ctrl:o,mode:"edit",columnId:r})},...t?[]:[{key:"field-left",label:p("fields.menuInsertLeft"),icon:m.left,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"left")})}],{key:"field-right",label:p("fields.menuInsertRight"),icon:m.right,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"right")})},{key:"field-duplicate",label:p("fields.menuDuplicate"),icon:m.duplicate,run:()=>{o.props.baseRefuseDuplicate?.(r)||re(o,r)}},...t?[]:[{key:"field-move-left",label:p("fields.menuMoveLeft"),icon:m.left,disabled:!S(o,r,-1),run:()=>R(o,r,-1)},{key:"field-move-right",label:p("fields.menuMoveRight"),icon:m.right,disabled:!S(o,r,1),run:()=>R(o,r,1)}],...l,...Ye(o,r,e),...t?[]:[{key:"field-hide",label:p("fields.menuHide"),icon:m.hide,run:()=>ie(o,r)},{key:"field-delete",label:p("fields.menuDelete"),icon:m.remove,separatorBefore:!0,run:()=>e?.fieldType==="link"&&(e.fieldProps?.inverse&&Z(e.fieldProps.table)||ne({columns:o.internalColumns},e).length)||e&&de(o.internalColumns??[],e).length||Q(o,e).length?U({ctrl:o,columnId:r}):te(o,r)}]]}function k(o,r,e){const i=(o.allColumns??[]).map(l=>l.id),t=i[i.indexOf(r)+e];if(!(!t||t===h(o)||o.isColumnPinned?.(t)!==o.isColumnPinned?.(r)))return t}const S=(o,r,e)=>!!k(o,r,e);function R(o,r,e){const i=k(o,r,e);if(!i)return;const t=o.allColumns.map(n=>n.id),l=t.indexOf(r),d=t.indexOf(i);t[l]=i,t[d]=r;const a=o.grid.getAllColumns().map(n=>n.id),s=o.userColumnOrder??[];o.moveColumnsByUser(je(s.length?[...s,...a.filter(n=>!s.includes(n))]:a,t))}function He(o,r,e){const i=F(r,e);if(!i)return;const t=o.advancedFilter,l=t?.kind==="fieldFilter"?t:{kind:"fieldFilter",conjunction:"and",conditions:[]};o.buildApi().setAdvancedFilter({...l,conditions:[...l.conditions,i]}),w(o,"filter")}function Ke(o,r){const e=X(o);e.some(i=>i.id===r)||W(o.buildApi(),[...e,{id:r,desc:!1}],j(o)),w(o,"group")}function D(o,r,e,i,t){if(!r)return;const l=x()?.id,d=i??o.buildApi?.().getRowId?.(r),a=(s,n)=>{d!=null&&!t&&o.editedCellValues&&(o.editedCellValues={...o.editedCellValues,[`${d}:${s}`]:n})};for(const s of o?.internalColumns??[]){if(s.fieldType!=="lastModifiedTime"&&s.fieldType!=="lastModifiedBy")continue;const n=String(s.id??s.field);if(n===e||!s.field)continue;const u=A(b(s));u.watch==="specific"&&!(u.watchFields??[]).includes(e)||(s.fieldType==="lastModifiedTime"?a(n,r[s.field]=new Date().toISOString()):l!==void 0&&a(n,r[s.field]=l))}}export function baseReviewApplied(o){return(r,e,i)=>{const t=y(typeof o=="function"?o():o);if(!t)return;const l=t.buildApi?.(),d=l?.getOption?.("getRowId"),a=new Map;(i??l?.getData?.()??[]).forEach((n,u)=>a.set(String(d?d(n,u):u),n));const s=new Map((t.allColumns??[]).map(n=>[n.columnDef?.field,n.id]));for(const n of r){const u=a.get(n.rowId),c=s.get(n.field);!u||!c||(D(t,u,c),T(t,n.rowId,c,u[n.field],void 0,e==="undo"?void 0:n.source.label))}}}function Ue(o,r,e,i){if(!r)return;const t=(o?.allColumns??[]).find(c=>c.id===e)?.columnDef;if(!t?.field)return;const l=i??o.buildApi?.().getRowId?.(r);if(l==null)return;const d=String(l),a=r[t.field],s=o.history?.[o.historyPtr],n=[...J(o,d)].reverse().find(c=>c.columnId===e),u=s?.rowId===d&&s.columnId===e&&s.after===a?{from:s.before}:n?{from:n.value}:void 0;T(o,d,e,a,void 0,void 0,u)}function _e(o,r){if(o.key!==" "||o.ctrlKey||o.metaKey||o.altKey||o.shiftKey||r.editing||!r.activeCell)return!1;const e=y(r.api);if(!e?.props?.expandRows)return!1;const i=(e.allColumns??[]).find(l=>l.id===r.activeCell.columnId);if(i?.columnDef.editorType==="checkbox"||i?.columnDef.editorType==="fieldVote")return!1;const t=(e.allRows??[])[r.activeCell.rowIndex];return!t||e.isGroupRow?.(t)||Ce(t.original)?!1:(o.preventDefault(),_({ctrl:e,rowId:t.id}),!0)}function Ne(o,r){if(o.key!=="Enter"&&o.key!==" "||o.ctrlKey||o.metaKey||o.altKey||o.shiftKey||r.editing||!r.activeCell)return!1;const e=y(r.api);if(!e?.props?.baseDeleteSelection)return!1;const{rowIndex:i,colIndex:t}=r.activeCell,l=e.allColumns?.[t]?.columnDef.editorType,d=l==="checkbox";if(o.key===" "&&!d&&l!=="fieldVote")return!1;const a=r.ranges.at(-1);return o.key==="Enter"&&(r.ranges.length>1||a&&(a[0]!==a[2]||a[1]!==a[3]))||!e.isCellEditableAt(i,t)?!1:(o.preventDefault(),d?(e.toggleBooleanCell(i,t),!0):(r.startEditing(i,t),!!e.editingCell))}import{baseGridKey as Ge}from"./base-keys.svelte.js";import{treeGridKey as ze}from"./tree-edit.js";import{fillDownKey as $e}from"./base-fill.js";import{autoSumKey as qe,formatKey as Xe}from"./excel-habits.svelte.js";import{orderKeepingScreen as je}from"./column-order.js";let O=!1;export function enableFields(){if(O)return;O=!0;for(const e of ae)E(e.id)||be(e);I({column:(e,i)=>ge(e,i),cell:P,hasCell:e=>ye(e??{}),cellEdited:(e,i)=>{D(e,i.row,i.columnId,i.rowId,i.offGrid),Ue(e,i.row,i.columnId,i.rowId),We(e,i.row,i.columnId,i.rowId)},rangeAction:(e,i)=>e.props?.baseRangeAction?.(i)===!0,bodyEnd:L,footEnd:V,rowMarkColor:(e,i)=>ue(e,i),rowMarkLabel:(e,i)=>ce(e,i),headerIcon:e=>e?.fieldType?E(e.fieldType)?.icon:null,headerNote:e=>{if(!e?.fieldType)return null;const i=typeof e.description=="string"?e.description:"",t=Le(b(e),A(b(e)));return t?{text:i?`${t} ${i}`:t,icon:m.lock}:i?{text:i,icon:m.info}:null},sortLabels:e=>e?.fieldType?Y(e):null,lockColumn:(e,i)=>h(e)===i,rowHeader:e=>e?.props?.expandRows?De:null,groupRow:e=>!e?.props?.rowModel&&Be(e).some(i=>i.fieldType)?Oe:null,summaryCell:e=>e?.props?.rowModel?null:Ie,rootClass:e=>{Pe(e);const i=e?.advancedFilter?.kind==="fieldFilter"?"sv-fields-own-filter":"",t=i&&!e?.toolPanelEnabled&&!e?.chartingEnabled?"sv-fields-filter-only":"",l=e?.groupingColumns?.length?"sv-fields-grouped":"";return[fe(e),pe(e),i,t,l].filter(Boolean).join(" ")||null},headerEnd:K,columnMenuItems:(e,i)=>e?.props?.fieldMenu?le(e,Ve(e,i),!se(e)):[]});const o=e=>({value:e.value,typed:e.typed,columnDef:e.columnDef,columnId:e.columnId,row:e.row,onCommit:e.onCommit,onCancel:e.onCancel});f("fieldRating",{component:he,props:o,typeToEdit:e=>/^[0-9]$/.test(e)}),f("fieldLink",{component:Fe,props:o,typeToEdit:e=>e!==" "}),f("fieldNumber",{component:ve,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9.,:+\-(=]/.test(e)}),f("fieldLongText",{component:Me,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove})}),f("fieldSelect",{component:Te,props:e=>({...o(e),grid:e.grid,onChange:e.onChange,onCommitAndMove:e.onCommitAndMove})}),f("attachment",{component:H,props:e=>({value:e.value,columnDef:e.columnDef,columnId:e.columnId,row:e.row,onCommit:e.onCommit,onCancel:e.onCancel}),typeToEdit:!1});const r=e=>({...o(e),onCommitAndMove:e.onCommitAndMove});f("fieldChecklist",{component:ke,props:r}),f("fieldRichText",{component:Ae,props:r}),f("fieldVote",{component:Ee,props:r,typeToEdit:e=>e===" "}),f("fieldTimer",{component:xe,props:e=>({...r(e),rowId:e.rowId,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>e===" "||/[0-9:]/.test(e)}),f("fieldColor",{component:Se,props:r}),f("fieldTime",{component:Re,props:e=>({...r(e),onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9]/.test(e)}),f("fieldDate",{component:we,props:e=>({...r(e),onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9a-z]/i.test(e)}),G("fieldFilter",(e,i)=>z(e,i.getValue,ee)),$(()=>x()?.id),oe(),N(),g(_e,{id:"svgrid-fields-space"}),g(Ge,{id:"svgrid-fields-keys"}),g(Ne,{id:"svgrid-base-keys"}),g($e,{id:"svgrid-base-fill-down"}),g(qe,{id:"svgrid-base-autosum",priority:200}),g(Xe,{id:"svgrid-base-format-keys",priority:200}),g(ze,{id:"svgrid-base-tree"}),B("base","SvGrid Base")}export{inboxRecords,listColumns,listGroups,viewRecords}from"./list-view.js";import{aiFieldEdited as We,aiFieldMenuItems as Ye}from"./ai-field.svelte.js";export{generateAIField,regenerateAIFields,cancelAIField,pendingAIField,setAIFieldConcurrency}from"./ai-field.svelte.js";export{aiPromptError,readAIAnswer}from"./ai-prompt.js";export{moveTile,newTile,putTile,removeTile,tileResult,tileRows,tileTitle}from"./dashboard.js";export{sharedTables,sharedViews,shareOf}from"./base-share.js";export{recordsAsShown,downloadAsShown}from"./base-export.js";export{permittedTables,permittedRecords,permittedViews,tablePermissions,gridPermissions}from"./base-permissions.js";export{computeRecords,computeRecord,computedValues,computedFields,evaluateFilter,filterRecords}from"./base-compute.js";export{queryRecords,fieldFilterToSql,fieldFilterToPostgrest,supabaseFieldFilter,viewFilterOf}from"./base-query.js";export{searchBase}from"./base-search.js";export{toChecklist,parseChecklist,checklistText,checklistProgress}from"./checklist.js";export{parseColor}from"./color-value.js";export{parseTimeOfDay,formatTimeOfDay,timeSeconds}from"./time-of-day.js";
|
|
@@ -77,6 +77,34 @@ export declare const FIELDS_MESSAGES: {
|
|
|
77
77
|
readonly 'fields.insertField': "Insert a field";
|
|
78
78
|
readonly 'fields.functions': "Functions";
|
|
79
79
|
readonly 'fields.hideFunctions': "Hide functions";
|
|
80
|
+
readonly 'fields.formulaAskPlaceholder': "Describe it, such as \"total with 20% VAT\"";
|
|
81
|
+
readonly 'fields.formulaAskLabel': "Describe the formula in your own words";
|
|
82
|
+
readonly 'fields.formulaAskButton': "Write it";
|
|
83
|
+
readonly 'fields.formulaAskWorking': "Writing…";
|
|
84
|
+
readonly 'fields.formulaAiFailed': "The AI could not write a formula that works. Try describing it another way.";
|
|
85
|
+
readonly 'fields.formulaSuggestions': "Suggestions";
|
|
86
|
+
readonly 'fields.formulaFieldHint': "Field";
|
|
87
|
+
readonly 'fields.formulaPreview': "Result:";
|
|
88
|
+
readonly 'fields.formulaUnnamed': "Unnamed record";
|
|
89
|
+
readonly 'fields.formulaEmpty': "(empty)";
|
|
90
|
+
readonly 'fields.formulaTrue': "true";
|
|
91
|
+
readonly 'fields.formulaFalse': "false";
|
|
92
|
+
readonly 'fields.formulaTips': "Tips";
|
|
93
|
+
readonly 'fields.formulaHideTips': "Hide tips";
|
|
94
|
+
readonly 'fields.formulaTip1': "Start with a field: click its name below, or type { and pick it from the list.";
|
|
95
|
+
readonly 'fields.formulaTip2': "Do math as in a spreadsheet, with field names instead of cells:";
|
|
96
|
+
readonly 'fields.formulaTip3': "Put text in quotes, and join pieces with &:";
|
|
97
|
+
readonly 'fields.formulaTip4': "Choose between two answers with IF:";
|
|
98
|
+
readonly 'fields.formulaTip5': "No = at the start, and commas between the parts of a function. The result for your first records shows as you type.";
|
|
99
|
+
readonly 'fields.formulaTip6': "Not sure how? Describe what you want in the box at the top, and AI writes the formula for you.";
|
|
100
|
+
readonly 'fields.formulaFindFunction': "Find a function";
|
|
101
|
+
readonly 'fields.formulaNoFunction': "No function matches";
|
|
102
|
+
readonly 'fields.formulaGroup.logic': "Logic";
|
|
103
|
+
readonly 'fields.formulaGroup.text': "Text";
|
|
104
|
+
readonly 'fields.formulaGroup.numbers': "Numbers";
|
|
105
|
+
readonly 'fields.formulaGroup.dates': "Dates";
|
|
106
|
+
readonly 'fields.formulaGroup.lists': "Lists";
|
|
107
|
+
readonly 'fields.formulaGroup.records': "Records";
|
|
80
108
|
readonly 'fields.optionsList': "Options";
|
|
81
109
|
readonly 'fields.colorOf': "Color of {name}";
|
|
82
110
|
readonly 'fields.colorOfOption': "Color of option {n}";
|