@svgrid/enterprise 3.1.47 → 3.1.49
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 +264 -264
- package/dist/designer/assets/{index-Bu6aNQcY.js → index-CRDbNW8P.js} +1 -1
- package/dist/designer/index.html +1 -1
- package/dist/fields/BaseTabs.svelte +7 -2
- package/dist/fields/BaseTabs.svelte.d.ts +2 -0
- package/dist/fields/SvBase.svelte +2 -1
- package/dist/fields/SvBase.svelte.d.ts +8 -0
- package/dist/fields/base-export.d.ts +24 -0
- package/dist/fields/base-export.js +1 -1
- package/dist/fields/filter-model.js +1 -1
- package/dist/fields/formula-docs.js +1 -1
- package/dist/fields/formula.js +1 -1
- package/dist/fields/index.d.ts +1 -1
- package/dist/fields/index.js +1 -1
- package/dist/fields/messages/shell.d.ts +3 -0
- package/dist/fields/messages/shell.js +1 -1
- package/dist/fields/messages.svelte.d.ts +3 -0
- package/dist/node/studio.js +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/wc/sv-base-element.js +89 -89
- package/package.json +1 -1
|
@@ -67,6 +67,7 @@ import { type AutomationRun, type BaseAutomation } from './automations.svelte.js
|
|
|
67
67
|
import { type BaseTrashItem, type BaseTrashStore } from './base-trash.js';
|
|
68
68
|
import { type CanEditField } from './field-access.svelte.js';
|
|
69
69
|
import { type BaseShare } from './base-share.js';
|
|
70
|
+
import { type BaseFilesExport } from './base-export.js';
|
|
70
71
|
import { type BasePermissions } from './base-permissions.js';
|
|
71
72
|
type $$ComponentProps = {
|
|
72
73
|
/** Several tables, shown as tabs. Without it, `data` and `columns` are the one table. */
|
|
@@ -87,6 +88,13 @@ type $$ComponentProps = {
|
|
|
87
88
|
* the table is made in the page. Not undone with Ctrl+Z: it is yours.
|
|
88
89
|
*/
|
|
89
90
|
onImportTable?: (table: BaseTable) => BaseTable | null | void | Promise<BaseTable | null | void>;
|
|
91
|
+
/**
|
|
92
|
+
* Download the shown view's files as a ZIP. Given, the list of tables offers it for a
|
|
93
|
+
* table with a file field; SvBase hands over the view's records in their order, each with
|
|
94
|
+
* its folder (the values the view is grouped by, else the record's name), and the file
|
|
95
|
+
* fields shown. The app reads the files and sends the ZIP (it holds them, and they may be large).
|
|
96
|
+
*/
|
|
97
|
+
onExportFiles?: (request: BaseFilesExport) => void | Promise<void>;
|
|
90
98
|
/**
|
|
91
99
|
* Read the files the import is given yourself, first: an app that reads
|
|
92
100
|
* .xls, .ods or .xlsb (with SheetJS, say) answers the rows as text, the
|
|
@@ -3,6 +3,30 @@ type Row = Record<string, unknown>;
|
|
|
3
3
|
export type BaseExportFormat = 'csv' | 'xlsx';
|
|
4
4
|
/** Rows of `{ column id: what the cell shows }` for these columns. */
|
|
5
5
|
export declare function recordsAsShown(columns: ReadonlyArray<FieldColumn>, rows: ReadonlyArray<Row>): Row[];
|
|
6
|
+
/** One record of a ZIP of a view's files (SvBase's `onExportFiles`): its id, and the folder its files go in. */
|
|
7
|
+
export interface BaseFilesRecord {
|
|
8
|
+
id: string;
|
|
9
|
+
folder: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* What SvBase hands `onExportFiles` for a ZIP of the shown view's files: the table, the
|
|
13
|
+
* view, the file fields it shows, and its records in their order, each with its folder.
|
|
14
|
+
* The app reads the files (it holds them) and sends the ZIP.
|
|
15
|
+
*/
|
|
16
|
+
export interface BaseFilesExport {
|
|
17
|
+
table: string;
|
|
18
|
+
view: string;
|
|
19
|
+
fields: string[];
|
|
20
|
+
records: BaseFilesRecord[];
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Each record with the folder its files go in: the values the view is grouped by (grouped
|
|
24
|
+
* by client, a folder for each client, a folder inside it for each further group), else
|
|
25
|
+
* the record's name (the first column given). A folder name keeps to what every system saves.
|
|
26
|
+
*/
|
|
27
|
+
export declare function filesFolders(columns: ReadonlyArray<FieldColumn>, groupBy: ReadonlyArray<string>, rows: ReadonlyArray<Row>, empty?: string): BaseFilesRecord[];
|
|
28
|
+
/** A folder name every system saves: no slashes, colons or wildcards, no leading dots, at most 80 characters. */
|
|
29
|
+
export declare function safeFolder(text: string): string;
|
|
6
30
|
/**
|
|
7
31
|
* The columns and rows of an Excel file: `recordsAsShown`, with what is a number,
|
|
8
32
|
* a date or a time as a number under the field's format, and a checkbox a boolean. A value that is none
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fieldText as d,fieldValue as c}from"./base-alerts.js";import{fieldCopyText as
|
|
1
|
+
import{fieldText as d,fieldValue as c}from"./base-alerts.js";import{fieldCopyText as $}from"./copy-text.js";import{excelDateFormat as M,excelDays as D,exactNumber as p,formatDuration as N,numberBoxText as P,numberFieldShape as w,numberKind as h}from"./format.js";import{isoDate as A}from"./formula.js";import{fieldPropsOf as E,fillFieldColumn as C}from"./registry.svelte.js";import{timeSeconds as k}from"./time-of-day.js";import{timerSeconds as G}from"./timer.js";export function recordsAsShown(e,t){return t.map(r=>{const n={};for(const o of e)n[o.id]=b(o,r);return n})}function b(e,t){const r=String(e.def.fieldType),n=r==="timer"?G(c(e,t)):c(e,t);if(r==="checkbox")return I(n);if(O.has(r))return String($({value:n,column:{id:e.id,columnDef:e.def},row:t})??"");const o=y(e.def)?p(n):n;return typeof o=="number"&&Number.isFinite(o)&&(y(e.def)||r==="formula"||!e.def.formatter)?K(e,o)??o:d(e,t)}const y=e=>e.cellDataType==="number"||e.fieldType==="rating";export function filesFolders(e,t,r,n="(empty)"){const o=t.map(l=>e.find(u=>u.id===l)).filter(l=>!!l),i=o.length?o:e.slice(0,1);return r.map(l=>({id:String(l.id??""),folder:i.map(u=>safeFolder(String(b(u,l)??""))||n).join("/")})).filter(l=>l.id!=="")}export function safeFolder(e){return e.replace(/[\\/:*?"<>|\u0000-\u001f]+/g," ").replace(/\s+/g," ").trim().replace(/^\.+/,"").slice(0,80).trim()}function I(e){return e==null||e===""?"":e===!0||e===1||e==="true"?"true":"false"}const O=new Set(["multiSelect","user","link","vote"]),B=e=>h(e.def.fieldType,e.def.fieldProps??{})==="percent";function K(e,t){return e.def.fieldType==="duration"||e.def.fieldType==="timer"?N(t,Number.isInteger(t)?"h:mm:ss":"h:mm:ss.SSS"):B(e)?`${P(t,"percent",{...e.def.fieldProps,separators:"comma-period"})}%`:null}const a=e=>{const t=p(e);return typeof t=="number"?t:null};function S(e,t){const{places:r}=w(e,t),n=`${t.showThousands===!1?"0":"#,##0"}${r?`.${"0".repeat(r)}`:""}`;if(e==="percent")return`${n}%`;const o={thousand:',"K"',million:',,"M"',billion:',,,"B"'}[String(t.abbreviation)]??"",i=e==="currency"?String(t.symbol??"$").replace(/"/g,""):"";return i?t.symbolPosition==="after"?`${n}${o}" ${i}"`:`"${i}"${n}${o}`:n+o}function x(e,t){const r=e==="percent"&&!!t.points,n=o=>{const i=a(o);return i!=null&&r?Number((i/100).toPrecision(15)):i};return{numFmt:S(e,t),cell:n}}const g=(e,t=r=>r)=>({numFmt:M(e),cell:r=>D(t(r),e)}),W=e=>({numFmt:`${e.timeFormat==="24hour"?"hh":"h"}:mm${e.showSeconds?":ss":""}${e.timeFormat==="24hour"?"":" AM/PM"}`,cell:t=>{const r=k(t);return r==null?null:r/86400}}),j=e=>typeof e=="string"?A(e):e instanceof Date?e:null;function F(e,t){const r=e.fieldSource?.();return r?.fieldType?C({...r,fieldProps:{...r.fieldProps,...t==null?{}:{precision:t}}}):null}function f(e,t){const r=E(e);switch(e.fieldType){case"checkbox":return null;case"number":case"currency":case"percent":return x(h(e.fieldType,r),r);case"date":case"createdTime":case"lastModifiedTime":return g(r);case"timeOfDay":return W(r);case"rating":case"autoNumber":return{cell:a};case"count":return{numFmt:"#,##0",cell:a};case"formula":return r.result==="number"||r.result==="currency"||r.result==="percent"?x(r.result,{...r,format:void 0}):r.result==="date"||t()instanceof Date?g(r,j):{cell:n=>typeof n=="number"?n:null};case"rollup":{if(!e.cellDataType)return null;const n=["SUM","AVERAGE","MIN","MAX"].includes(String(r.aggregation)),o=n?F(e,r.precision):null;return(o?f(o,t):null)??{numFmt:n?S("number",{precision:r.precision??0,format:"decimal"}):"#,##0",cell:a}}case"lookup":{const n=F(e),o=n?f(n,t):null;return o?{numFmt:o.numFmt,cell:i=>Array.isArray(i)&&i.length===1?o.cell(i[0]):null}:null}default:return!e.formatter&&typeof t()=="number"?{cell:n=>typeof n=="number"?n:null}:null}}function J(e,t){let r=e.header.length;for(let n=0;n<Math.min(t.length,200);n++)r=Math.max(r,d(e,t[n]).length);return Math.max(48,Math.min(400,r*7+14))}export function recordsForExcel(e,t){const r=recordsAsShown(e,t),n=e.map(o=>f(o.def,()=>{for(const i of t){const l=c(o,i);if(l!=null&&l!=="")return l}return null}));return e.forEach((o,i)=>{if(o.def.fieldType==="checkbox")return t.forEach((u,m)=>{const s=c(o,u);r[m][o.id]=s===!0||s==="true"||s===1});const l=n[i];l&&t.forEach((u,m)=>{const s=l.cell(c(o,u));s!=null&&Number.isFinite(s)&&(r[m][o.id]=s)})}),{columns:e.map((o,i)=>({field:o.id,header:o.header,numFmt:n[i]?.numFmt,width:J(o,t)})),records:r}}let T;export function canWriteExcel(){return globalThis.JSZip!=null?Promise.resolve(!0):T??(T=import("jszip").then(()=>!0,()=>!1))}export async function downloadAsShown(e,t,r,n,o){const{exportGrid:i}=await import("../export.js"),l=t==="xlsx"?recordsForExcel(n,o):{columns:n.map(u=>({field:u.id,header:u.header})),records:recordsAsShown(n,o)};await i(e,{format:t,filename:r.replace(/[\\/:*?"<>|]+/g," ").trim()||"base",columns:l.columns,rows:l.records,rawValues:!0,autoGroup:!1})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{checklistProgress as T,checklistSortValue as I,toChecklist as M}from"./checklist.js";import{parseTimeOfDay as W,timeSeconds as O}from"./time-of-day.js";import{isRichHtml as F,richPlain as R}from"./rich-html.js";import{VIEWBAR_MESSAGES as C}from"./messages/viewbar.js";import{tokenize as U}from"./formula.js";export const ME="@me";let N=()=>{};export function resolveMeWith(e){N=e}const k=(e,t)=>t;let D=k;export function setFilterWords(e){D=e??k}const l=(e,t)=>{const n=D(e,C[e]);return t?n.replace(/\{(\w+)\}/g,(s,r)=>r in t?String(t[r]):s):n};export const isGroup=e=>Array.isArray(e.conditions);const B=new Set(["text","longText","richText","url","email","phone","barcode","color"]),P=new Set(["number","currency","percent","rating","duration","timer","autoNumber","count"]),_=new Set(["date","createdTime","lastModifiedTime"]),L={formula:"text",lookup:"text",rollup:"text"},Y=new Set(["AND","OR"]),j=new Set(["LEN","FIND","SEARCH","VALUE","SUM","AVERAGE","MAX","MIN","COUNT","COUNTA","COUNTALL","ROUND","ROUNDUP","ROUNDDOWN","INT","ABS","MOD","POWER","SQRT","EXP","LOG","EVEN","ODD","CEILING","FLOOR","YEAR","MONTH","DAY","HOUR","MINUTE","SECOND","WEEKDAY","WEEKNUM","DATETIME_DIFF","TONOW","FROMNOW","WORKDAY_DIFF"]),H=new Set(["TODAY","NOW","DATEADD","DATETIME_PARSE","SET_LOCALE","SET_TIMEZONE","WORKDAY"]),V=new Set(["AND","OR","NOT","XOR","TRUE","FALSE","ISERROR","REGEX_MATCH","IS_BEFORE","IS_AFTER","IS_SAME"]);function K(e){let t;try{t=U(String(e??""))}catch{return null}let n=0;const s=(...f)=>t[n]?.k==="op"&&f.includes(t[n].v),r=f=>f.reduce((m,b)=>m==="blank"?b:b==="blank"||m===b?m:null,"blank"),a=()=>{let f=i();for(;s("=","!=","<",">","<=",">=");)n+=1,i(),f="checkbox";return f},i=()=>{let f=o();for(;s("&");)n+=1,o(),f="text";return f},o=()=>{let f=u();for(;s("+","-");)n+=1,u(),f="number";return f},u=()=>{let f=p();for(;s("*","/");)n+=1,p(),f="number";return f},p=()=>s("-")?(n+=1,p(),"number"):c(),c=()=>{const f=t[n++];if(!f)throw new Error("the formula ends");if(f.k==="num")return"number";if(f.k==="str")return f.v===""?"blank":"text";if(f.k==="ref")return null;if(f.k==="("){const d=a();if(t[n++]?.k!==")")throw new Error("no closing bracket");return d}if(f.k!=="id")throw new Error("not a value");const m=f.v.toUpperCase();if(t[n]?.k!=="(")return m==="TRUE"||m==="FALSE"?"checkbox":null;n+=1;const b=[];if(t[n]?.k!==")")for(b.push(a());t[n]?.k===",";)n+=1,b.push(a());if(t[n++]?.k!==")")throw new Error("no closing bracket");return m==="BLANK"?"blank":m==="IF"?r(b.slice(1)):m==="SWITCH"?r(b.filter((d,h)=>h>0&&h%2===0||h===b.length-1&&h%2===1)):j.has(m)?"number":H.has(m)?"date":V.has(m)?"checkbox":null};try{const f=a();return n===t.length&&f!=="blank"?f:null}catch{return null}}function G(e){const t=e.cellDataType;return t==="number"?"number":t==="date"||t==="dateString"?"date":t==="boolean"?"checkbox":null}export function filterKindOf(e){const t=e.fieldType;if(t==="button")return null;if(t==="singleSelect")return"select";if(t==="multiSelect")return"multi";if(t==="user"||t==="createdBy"||t==="lastModifiedBy")return e.fieldProps?.multiple?"multi":"select";if(t==="checkbox")return"checkbox";if(t==="vote")return"multi";if(t==="sparkline")return null;if(t==="attachment")return"files";if(t==="link")return"link";if(t==="checklist")return"checklist";if(t==="timeOfDay")return"time";if(t&&_.has(t))return"date";if(t&&P.has(t))return"number";if(t&&B.has(t))return"text";if(t==="ai")return e.fieldProps?.output==="singleSelect"?"select":e.fieldProps?.output==="number"?"number":"text";if(t==="rollup"&&!e.cellDataType&&Y.has(String(e.fieldProps?.aggregation)))return"checkbox";const n=t==="formula"?e.fieldProps?.result:void 0;return n==="number"||n==="currency"||n==="percent"?"number":n==="date"?"date":G(e)??(t==="formula"?K(e.fieldProps?.formula):null)??(t?L[t]:void 0)??"text"}export function operatorsFor(e){const t=[{op:"isEmpty",label:l("viewbar.opIsEmpty")},{op:"isNotEmpty",label:l("viewbar.opIsNotEmpty")}];switch(e){case"number":return[{op:"eq",label:"="},{op:"neq",label:"≠"},{op:"lt",label:"<"},{op:"gt",label:">"},{op:"lte",label:"≤"},{op:"gte",label:"≥"},...t];case"select":return[{op:"is",label:l("viewbar.opIs")},{op:"isNot",label:l("viewbar.opIsNot")},{op:"isAnyOf",label:l("viewbar.opIsAnyOf")},{op:"isNoneOf",label:l("viewbar.opIsNoneOf")},...t];case"multi":return[{op:"hasAnyOf",label:l("viewbar.opHasAnyOf")},{op:"hasAllOf",label:l("viewbar.opHasAllOf")},{op:"isExactly",label:l("viewbar.opIsExactly")},{op:"hasNoneOf",label:l("viewbar.opHasNoneOf")},...t];case"checkbox":return[{op:"is",label:l("viewbar.opIs")}];case"date":return[{op:"is",label:l("viewbar.opIs")},{op:"isBefore",label:l("viewbar.opIsBefore")},{op:"isAfter",label:l("viewbar.opIsAfter")},{op:"isOnOrBefore",label:l("viewbar.opIsOnOrBefore")},{op:"isOnOrAfter",label:l("viewbar.opIsOnOrAfter")},{op:"isWithin",label:l("viewbar.opIsWithin")},...t];case"files":return[{op:"contains",label:l("viewbar.opFileNameContains")},...t];case"checklist":return[{op:"allDone",label:l("viewbar.opIsComplete")},{op:"notAllDone",label:l("viewbar.opIsNotComplete")},{op:"gte",label:l("viewbar.opDoneAtLeast")},{op:"lt",label:l("viewbar.opDoneUnder")},{op:"contains",label:l("viewbar.opHasItemContaining")},...t];case"time":return[{op:"is",label:l("viewbar.opIs")},{op:"isBefore",label:l("viewbar.opIsBefore")},{op:"isAfter",label:l("viewbar.opIsAfter")},{op:"isOnOrBefore",label:l("viewbar.opIsAtOrBefore")},{op:"isOnOrAfter",label:l("viewbar.opIsAtOrAfter")},...t];case"linked":return[{op:"hasAnyOf",label:l("viewbar.opHasAnyOf")},{op:"hasNoneOf",label:l("viewbar.opHasNoneOf")}];case"link":case"text":return[{op:"contains",label:l("viewbar.opContains")},{op:"notContains",label:l("viewbar.opDoesNotContain")},{op:"is",label:l("viewbar.opIs")},{op:"isNot",label:l("viewbar.opIsNot")},...t]}}export const NO_VALUE=new Set(["isEmpty","isNotEmpty","allDone","notAllDone"]);export function defaultValue(e,t){if(!NO_VALUE.has(t))return e==="checkbox"?!0:e==="date"?t==="isWithin"?{span:"pastWeek"}:{mode:"today"}:e==="select"&&(t==="is"||t==="isNot")?"":e==="select"||e==="multi"?[]:""}export function newCondition(e,t){const n=filterKindOf(t);if(!n)return null;const s=operatorsFor(n)[0].op,r=n==="link"&&typeof t.fieldProps?.table=="string"?t.fieldProps.table:void 0;return{column:e,kind:n,op:s,value:defaultValue(n,s),...r?{table:r}:{}}}export function isComplete(e){if(NO_VALUE.has(e.op)||e.kind==="checkbox")return!0;const t=e.value;if(t==null)return!1;if(Array.isArray(t))return t.length>0;if(typeof t=="string")return t.trim()!=="";if(e.kind==="date"&&typeof t=="object"){const n=t;if(n.mode==="exactDate")return!!n.date;if(n.span==="pastDays"||n.span==="nextDays")return Number(n.days)>0}return!0}export function conditionCount(e){if(!e)return 0;let t=0;for(const n of e.conditions)isGroup(n)?t+=n.conditions.filter(isComplete).length:isComplete(n)&&(t+=1);return t}const w=e=>String(e??"").trim().toLocaleLowerCase(),y=e=>e==null||e===""?[]:Array.isArray(e)?e.map(t=>String(t&&typeof t=="object"?t.id??t.name??"":t)):[String(e)],A=e=>e==null||e===""||Array.isArray(e)&&e.length===0||typeof e=="number"&&Number.isNaN(e),E=864e5;export function dayOf(e){if(e==null||e==="")return null;let t;if(e instanceof Date)t=e;else if(typeof e=="number")t=new Date(e);else{const n=String(e),s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n);t=s?new Date(Number(s[1]),Number(s[2])-1,Number(s[3])):new Date(n)}return Number.isNaN(t.getTime())?null:Math.floor((t.getTime()-t.getTimezoneOffset()*6e4)/E)}function S(e,t){switch(e.mode){case"today":return t;case"tomorrow":return t+1;case"yesterday":return t-1;case"oneWeekAgo":return t-7;case"oneWeekFromNow":return t+7;case"oneMonthAgo":return t-30;case"oneMonthFromNow":return t+30;case"exactDate":return dayOf(e.date)}}function g(e,t){const n=Math.max(1,Math.floor(Number(e.days)||1));switch(e.span){case"pastWeek":return[t-7,t];case"pastMonth":return[t-30,t];case"pastYear":return[t-365,t];case"nextWeek":return[t,t+7];case"nextMonth":return[t,t+30];case"nextYear":return[t,t+365];case"pastDays":return[t-n,t];case"nextDays":return[t,t+n]}}export function dateConditionDays(e,t=new Date){const n=dayOf(t);if(e.op==="isWithin")return g(e.value??{span:"pastWeek"},n);const s=S(e.value??{mode:"today"},n);if(s==null)return null;switch(e.op){case"is":return[s,s];case"isBefore":return[null,s-1];case"isAfter":return[s+1,null];case"isOnOrBefore":return[null,s];case"isOnOrAfter":return[s,null];default:return null}}export function conditionMoment(e){const t=e.value;return(e.op==="isBefore"||e.op==="isOnOrAfter")&&t?.mode==="exactDate"&&typeof t.at=="string"?t.at:null}export const isMoment=e=>e instanceof Date||typeof e=="string"&&e.length>10&&/(?:z|[+-]\d{2}(?::?\d{2})?)$/i.test(e);const v=e=>{const t=new Date(e*E);return new Date(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())};export function viewerMoments(e,t=new Date){if(e.kind!=="date"||e.op==="isEmpty"||e.op==="isNotEmpty"||conditionMoment(e))return null;const n=dateConditionDays(e,t);if(!n)return null;const[s,r]=n;return{from:s==null?null:v(s).toISOString(),to:r==null?null:v(r+1).toISOString()}}export function withViewerDays(e,t=new Date){let n=!1;const s=a=>{const i=viewerMoments(a,t);return i?(n=!0,{...a,moments:i}):a},r=e.conditions.map(a=>isGroup(a)?{...a,conditions:a.conditions.map(s)}:s(a));return n?{...e,conditions:r}:e}export function expressionWithViewerDays(e,t=new Date){const n=e;if(!n||typeof n!="object")return e;if(n.kind==="fieldFilter"&&Array.isArray(n.conditions))return withViewerDays(n,t);const s=n.payload;if(n.kind==="ext"&&n.type==="fieldFilter"&&s&&Array.isArray(s.conditions)){const r=withViewerDays({...s,kind:"fieldFilter",conjunction:s.conjunction??"and"},t);return r.conditions===s.conditions?e:{...n,payload:{...s,conditions:r.conditions}}}return e}export function compileCondition(e,t,n=new Date){const s=e.kind==="link"&&e.table&&t?.isEmpty?r=>A(r)||t.isEmpty(e.table,r):A;if(e.op==="isEmpty")return s;if(e.op==="isNotEmpty")return r=>!s(r);if(e.kind==="linked"){const r=new Set((Array.isArray(e.value)?e.value:[e.value]).map(i=>String(i))),a=i=>(Array.isArray(i)?i:A(i)?[]:[i]).map(o=>String(o&&typeof o=="object"?o.id??"":o));return e.op==="hasNoneOf"?i=>!a(i).some(o=>r.has(o)):i=>a(i).some(o=>r.has(o))}switch(e.kind){case"number":{const r=Number(e.value);if(!Number.isFinite(r))return()=>!0;const a=u=>A(u)?NaN:Number(u),o={eq:u=>u===r,neq:u=>u!==r,lt:u=>u<r,gt:u=>u>r,lte:u=>u<=r,gte:u=>u>=r}[e.op]??(()=>!0);return u=>{const p=a(u);return Number.isNaN(p)?e.op==="neq":o(p)}}case"checkbox":{const r=e.value!==!1;return a=>!!a===r}case"select":case"multi":{const r=N(),a=y(e.value).map(o=>o===ME&&r!=null?r:o),i=new Set(a);return e.op==="is"?o=>y(o)[0]===a[0]:e.op==="isNot"?o=>y(o)[0]!==a[0]:e.op==="isAnyOf"||e.op==="hasAnyOf"?o=>y(o).some(u=>i.has(u)):e.op==="isNoneOf"||e.op==="hasNoneOf"?o=>!y(o).some(u=>i.has(u)):e.op==="hasAllOf"?o=>{const u=new Set(y(o));return[...i].every(p=>u.has(p))}:e.op==="isExactly"?o=>{const u=new Set(y(o));return u.size===i.size&&[...i].every(p=>u.has(p))}:()=>!0}case"date":{const r=dayOf(n),a=conditionMoment(e),i=a?e.op==="isBefore"?{from:null,to:a}:{from:a,to:null}:e.moments;if(i&&(i.from!=null||i.to!=null)){const c=i.from==null?-1/0:Date.parse(i.from),f=i.to==null?1/0:Date.parse(i.to),m={...e,moments:void 0,value:a?{...e.value,at:void 0}:e.value},b=compileCondition(m,t,n);return d=>{if(!isMoment(d))return b(d);const h=d instanceof Date?d.getTime():Date.parse(String(d));return Number.isFinite(h)&&h>=c&&h<f}}if(e.op==="isWithin"){const[c,f]=g(e.value??{span:"pastWeek"},r);return m=>{const b=dayOf(m);return b!=null&&b>=c&&b<=f}}const o=S(e.value??{mode:"today"},r);if(o==null)return()=>!0;const p={is:c=>c===o,isBefore:c=>c<o,isAfter:c=>c>o,isOnOrBefore:c=>c<=o,isOnOrAfter:c=>c>=o}[e.op]??(()=>!0);return c=>{const f=dayOf(c);return f!=null&&p(f)}}case"files":{const r=w(e.value);return a=>(Array.isArray(a)?a:[]).some(i=>w(i?.name).includes(r))}case"checklist":{const r=i=>{const o=T(i);return o.total>0&&o.done===o.total};if(e.op==="allDone")return r;if(e.op==="notAllDone")return i=>!r(i);if(e.op==="contains"){const i=w(e.value);return o=>M(o).some(u=>w(u.text).includes(i))}const a=parseFloat(String(e.value??""));return Number.isFinite(a)?i=>{const o=I(i);return o==null?!1:e.op==="lt"?o*100<a:o*100>=a}:()=>!0}case"time":{const r=W(String(e.value??"")),a=O(r);if(r==null||a==null)return()=>!0;const i=r.length>5?1:60,o=Math.floor(a/i),p={is:c=>c===o,isBefore:c=>c<o,isAfter:c=>c>o,isOnOrBefore:c=>c<=o,isOnOrAfter:c=>c>=o}[e.op]??(()=>!0);return c=>{const f=O(c);return f!=null&&p(Math.floor(f/i))}}case"link":case"text":{const r=w(e.value),a=i=>F(i)?w(R(i)):e.kind==="link"&&e.table&&t?w(t(e.table,i).join(", ")):w(Array.isArray(i)?i.map(o=>o&&typeof o=="object"?o.name??"":o).join(", "):i);return e.op==="contains"?i=>a(i).includes(r):e.op==="notContains"?i=>!a(i).includes(r):e.op==="is"?i=>a(i)===r:e.op==="isNot"?i=>a(i)!==r:()=>!0}}}export function compileFieldFilter(e,t,n,s){const r=o=>{const u=compileCondition(o,n,s);return p=>{const c=t(p,o.column);return u(Array.isArray(c)&&c.some(Array.isArray)?c.flat(1/0):c)}},a=(o,u)=>o==="or"?p=>u.some(c=>c(p)):p=>u.every(c=>c(p)),i=[];for(const o of e.conditions)if(isGroup(o)){const u=o.conditions.filter(isComplete).map(r);u.length&&i.push(a(o.conjunction,u))}else isComplete(o)&&i.push(r(o));return i.length?a(e.conjunction,i):null}const X={today:"viewbar.dayToday",tomorrow:"viewbar.dayTomorrow",yesterday:"viewbar.dayYesterday",oneWeekAgo:"viewbar.dayOneWeekAgo",oneWeekFromNow:"viewbar.dayOneWeekFromNow",oneMonthAgo:"viewbar.dayOneMonthAgo",oneMonthFromNow:"viewbar.dayOneMonthFromNow"},q={pastWeek:"viewbar.spanPastWeek",pastMonth:"viewbar.spanPastMonth",pastYear:"viewbar.spanPastYear",nextWeek:"viewbar.spanNextWeek",nextMonth:"viewbar.spanNextMonth",nextYear:"viewbar.spanNextYear"},x=e=>e==="or"?l("viewbar.conjOr"):e==="and"?l("viewbar.conjAnd"):e;function z(e){if(NO_VALUE.has(e.op))return"";if(e.kind==="checkbox")return e.value===!1?l("viewbar.valueUnchecked"):l("viewbar.valueChecked");if(e.kind==="date"){if(e.op==="isWithin"){const r=e.value??{span:"pastWeek"};if(r.span==="pastDays")return l("viewbar.spanPastDays",{days:r.days??0});if(r.span==="nextDays")return l("viewbar.spanNextDays",{days:r.days??0});const a=q[r.span];return a?l(a):r.span}const n=e.value??{mode:"today"};if(n.mode==="exactDate")return n.date;const s=X[n.mode];return s?l(s):n.mode}const t=n=>n===ME?l("viewbar.valueMe"):String(n);return Array.isArray(e.value)?e.value.map(t).join(", "):t(e.value??"")}export function describeCondition(e,t=n=>n){const n=operatorsFor(e.kind).find(s=>s.op===e.op)?.label??e.op;return[t(e.column),n,z(e)].filter(Boolean).join(" ")}export function describeFieldFilter(e,t){const n=[];for(const s of e.conditions)if(isGroup(s)){const r=s.conditions.filter(isComplete).map(a=>describeCondition(a,t));r.length&&n.push(r.length>1?`(${r.join(` ${x(s.conjunction)} `)})`:r[0])}else isComplete(s)&&n.push(describeCondition(s,t));return n.length?n.join(` ${x(e.conjunction)} `):l("viewbar.everyRecord")}export function fieldFilterColumns(e){const t=new Set;for(const n of e.conditions)for(const s of isGroup(n)?n.conditions:[n])isComplete(s)&&t.add(s.column);return[...t]}
|
|
1
|
+
import{checklistProgress as T,checklistSortValue as I,toChecklist as M}from"./checklist.js";import{parseTimeOfDay as W,timeSeconds as O}from"./time-of-day.js";import{isRichHtml as F,richPlain as R}from"./rich-html.js";import{VIEWBAR_MESSAGES as C}from"./messages/viewbar.js";import{tokenize as U}from"./formula.js";export const ME="@me";let N=()=>{};export function resolveMeWith(e){N=e}const k=(e,t)=>t;let D=k;export function setFilterWords(e){D=e??k}const l=(e,t)=>{const n=D(e,C[e]);return t?n.replace(/\{(\w+)\}/g,(s,r)=>r in t?String(t[r]):s):n};export const isGroup=e=>Array.isArray(e.conditions);const B=new Set(["text","longText","richText","url","email","phone","barcode","color"]),P=new Set(["number","currency","percent","rating","duration","timer","autoNumber","count"]),_=new Set(["date","createdTime","lastModifiedTime"]),L={formula:"text",lookup:"text",rollup:"text"},Y=new Set(["AND","OR"]),j=new Set(["LEN","FIND","SEARCH","VALUE","SUM","AVERAGE","MAX","MIN","COUNT","COUNTA","COUNTALL","ROUND","ROUNDUP","ROUNDDOWN","INT","ABS","MOD","POWER","SQRT","EXP","LOG","EVEN","ODD","CEILING","FLOOR","DISTANCE","YEAR","MONTH","DAY","HOUR","MINUTE","SECOND","WEEKDAY","WEEKNUM","DATETIME_DIFF","TONOW","FROMNOW","WORKDAY_DIFF"]),H=new Set(["TODAY","NOW","DATEADD","DATETIME_PARSE","SET_LOCALE","SET_TIMEZONE","WORKDAY"]),V=new Set(["AND","OR","NOT","XOR","TRUE","FALSE","ISERROR","REGEX_MATCH","IS_BEFORE","IS_AFTER","IS_SAME"]);function K(e){let t;try{t=U(String(e??""))}catch{return null}let n=0;const s=(...f)=>t[n]?.k==="op"&&f.includes(t[n].v),r=f=>f.reduce((m,b)=>m==="blank"?b:b==="blank"||m===b?m:null,"blank"),a=()=>{let f=i();for(;s("=","!=","<",">","<=",">=");)n+=1,i(),f="checkbox";return f},i=()=>{let f=o();for(;s("&");)n+=1,o(),f="text";return f},o=()=>{let f=u();for(;s("+","-");)n+=1,u(),f="number";return f},u=()=>{let f=p();for(;s("*","/");)n+=1,p(),f="number";return f},p=()=>s("-")?(n+=1,p(),"number"):c(),c=()=>{const f=t[n++];if(!f)throw new Error("the formula ends");if(f.k==="num")return"number";if(f.k==="str")return f.v===""?"blank":"text";if(f.k==="ref")return null;if(f.k==="("){const d=a();if(t[n++]?.k!==")")throw new Error("no closing bracket");return d}if(f.k!=="id")throw new Error("not a value");const m=f.v.toUpperCase();if(t[n]?.k!=="(")return m==="TRUE"||m==="FALSE"?"checkbox":null;n+=1;const b=[];if(t[n]?.k!==")")for(b.push(a());t[n]?.k===",";)n+=1,b.push(a());if(t[n++]?.k!==")")throw new Error("no closing bracket");return m==="BLANK"?"blank":m==="IF"?r(b.slice(1)):m==="SWITCH"?r(b.filter((d,h)=>h>0&&h%2===0||h===b.length-1&&h%2===1)):j.has(m)?"number":H.has(m)?"date":V.has(m)?"checkbox":null};try{const f=a();return n===t.length&&f!=="blank"?f:null}catch{return null}}function G(e){const t=e.cellDataType;return t==="number"?"number":t==="date"||t==="dateString"?"date":t==="boolean"?"checkbox":null}export function filterKindOf(e){const t=e.fieldType;if(t==="button")return null;if(t==="singleSelect")return"select";if(t==="multiSelect")return"multi";if(t==="user"||t==="createdBy"||t==="lastModifiedBy")return e.fieldProps?.multiple?"multi":"select";if(t==="checkbox")return"checkbox";if(t==="vote")return"multi";if(t==="sparkline")return null;if(t==="attachment")return"files";if(t==="link")return"link";if(t==="checklist")return"checklist";if(t==="timeOfDay")return"time";if(t&&_.has(t))return"date";if(t&&P.has(t))return"number";if(t&&B.has(t))return"text";if(t==="ai")return e.fieldProps?.output==="singleSelect"?"select":e.fieldProps?.output==="number"?"number":"text";if(t==="rollup"&&!e.cellDataType&&Y.has(String(e.fieldProps?.aggregation)))return"checkbox";const n=t==="formula"?e.fieldProps?.result:void 0;return n==="number"||n==="currency"||n==="percent"?"number":n==="date"?"date":G(e)??(t==="formula"?K(e.fieldProps?.formula):null)??(t?L[t]:void 0)??"text"}export function operatorsFor(e){const t=[{op:"isEmpty",label:l("viewbar.opIsEmpty")},{op:"isNotEmpty",label:l("viewbar.opIsNotEmpty")}];switch(e){case"number":return[{op:"eq",label:"="},{op:"neq",label:"≠"},{op:"lt",label:"<"},{op:"gt",label:">"},{op:"lte",label:"≤"},{op:"gte",label:"≥"},...t];case"select":return[{op:"is",label:l("viewbar.opIs")},{op:"isNot",label:l("viewbar.opIsNot")},{op:"isAnyOf",label:l("viewbar.opIsAnyOf")},{op:"isNoneOf",label:l("viewbar.opIsNoneOf")},...t];case"multi":return[{op:"hasAnyOf",label:l("viewbar.opHasAnyOf")},{op:"hasAllOf",label:l("viewbar.opHasAllOf")},{op:"isExactly",label:l("viewbar.opIsExactly")},{op:"hasNoneOf",label:l("viewbar.opHasNoneOf")},...t];case"checkbox":return[{op:"is",label:l("viewbar.opIs")}];case"date":return[{op:"is",label:l("viewbar.opIs")},{op:"isBefore",label:l("viewbar.opIsBefore")},{op:"isAfter",label:l("viewbar.opIsAfter")},{op:"isOnOrBefore",label:l("viewbar.opIsOnOrBefore")},{op:"isOnOrAfter",label:l("viewbar.opIsOnOrAfter")},{op:"isWithin",label:l("viewbar.opIsWithin")},...t];case"files":return[{op:"contains",label:l("viewbar.opFileNameContains")},...t];case"checklist":return[{op:"allDone",label:l("viewbar.opIsComplete")},{op:"notAllDone",label:l("viewbar.opIsNotComplete")},{op:"gte",label:l("viewbar.opDoneAtLeast")},{op:"lt",label:l("viewbar.opDoneUnder")},{op:"contains",label:l("viewbar.opHasItemContaining")},...t];case"time":return[{op:"is",label:l("viewbar.opIs")},{op:"isBefore",label:l("viewbar.opIsBefore")},{op:"isAfter",label:l("viewbar.opIsAfter")},{op:"isOnOrBefore",label:l("viewbar.opIsAtOrBefore")},{op:"isOnOrAfter",label:l("viewbar.opIsAtOrAfter")},...t];case"linked":return[{op:"hasAnyOf",label:l("viewbar.opHasAnyOf")},{op:"hasNoneOf",label:l("viewbar.opHasNoneOf")}];case"link":case"text":return[{op:"contains",label:l("viewbar.opContains")},{op:"notContains",label:l("viewbar.opDoesNotContain")},{op:"is",label:l("viewbar.opIs")},{op:"isNot",label:l("viewbar.opIsNot")},...t]}}export const NO_VALUE=new Set(["isEmpty","isNotEmpty","allDone","notAllDone"]);export function defaultValue(e,t){if(!NO_VALUE.has(t))return e==="checkbox"?!0:e==="date"?t==="isWithin"?{span:"pastWeek"}:{mode:"today"}:e==="select"&&(t==="is"||t==="isNot")?"":e==="select"||e==="multi"?[]:""}export function newCondition(e,t){const n=filterKindOf(t);if(!n)return null;const s=operatorsFor(n)[0].op,r=n==="link"&&typeof t.fieldProps?.table=="string"?t.fieldProps.table:void 0;return{column:e,kind:n,op:s,value:defaultValue(n,s),...r?{table:r}:{}}}export function isComplete(e){if(NO_VALUE.has(e.op)||e.kind==="checkbox")return!0;const t=e.value;if(t==null)return!1;if(Array.isArray(t))return t.length>0;if(typeof t=="string")return t.trim()!=="";if(e.kind==="date"&&typeof t=="object"){const n=t;if(n.mode==="exactDate")return!!n.date;if(n.span==="pastDays"||n.span==="nextDays")return Number(n.days)>0}return!0}export function conditionCount(e){if(!e)return 0;let t=0;for(const n of e.conditions)isGroup(n)?t+=n.conditions.filter(isComplete).length:isComplete(n)&&(t+=1);return t}const w=e=>String(e??"").trim().toLocaleLowerCase(),y=e=>e==null||e===""?[]:Array.isArray(e)?e.map(t=>String(t&&typeof t=="object"?t.id??t.name??"":t)):[String(e)],A=e=>e==null||e===""||Array.isArray(e)&&e.length===0||typeof e=="number"&&Number.isNaN(e),E=864e5;export function dayOf(e){if(e==null||e==="")return null;let t;if(e instanceof Date)t=e;else if(typeof e=="number")t=new Date(e);else{const n=String(e),s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n);t=s?new Date(Number(s[1]),Number(s[2])-1,Number(s[3])):new Date(n)}return Number.isNaN(t.getTime())?null:Math.floor((t.getTime()-t.getTimezoneOffset()*6e4)/E)}function S(e,t){switch(e.mode){case"today":return t;case"tomorrow":return t+1;case"yesterday":return t-1;case"oneWeekAgo":return t-7;case"oneWeekFromNow":return t+7;case"oneMonthAgo":return t-30;case"oneMonthFromNow":return t+30;case"exactDate":return dayOf(e.date)}}function g(e,t){const n=Math.max(1,Math.floor(Number(e.days)||1));switch(e.span){case"pastWeek":return[t-7,t];case"pastMonth":return[t-30,t];case"pastYear":return[t-365,t];case"nextWeek":return[t,t+7];case"nextMonth":return[t,t+30];case"nextYear":return[t,t+365];case"pastDays":return[t-n,t];case"nextDays":return[t,t+n]}}export function dateConditionDays(e,t=new Date){const n=dayOf(t);if(e.op==="isWithin")return g(e.value??{span:"pastWeek"},n);const s=S(e.value??{mode:"today"},n);if(s==null)return null;switch(e.op){case"is":return[s,s];case"isBefore":return[null,s-1];case"isAfter":return[s+1,null];case"isOnOrBefore":return[null,s];case"isOnOrAfter":return[s,null];default:return null}}export function conditionMoment(e){const t=e.value;return(e.op==="isBefore"||e.op==="isOnOrAfter")&&t?.mode==="exactDate"&&typeof t.at=="string"?t.at:null}export const isMoment=e=>e instanceof Date||typeof e=="string"&&e.length>10&&/(?:z|[+-]\d{2}(?::?\d{2})?)$/i.test(e);const v=e=>{const t=new Date(e*E);return new Date(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())};export function viewerMoments(e,t=new Date){if(e.kind!=="date"||e.op==="isEmpty"||e.op==="isNotEmpty"||conditionMoment(e))return null;const n=dateConditionDays(e,t);if(!n)return null;const[s,r]=n;return{from:s==null?null:v(s).toISOString(),to:r==null?null:v(r+1).toISOString()}}export function withViewerDays(e,t=new Date){let n=!1;const s=a=>{const i=viewerMoments(a,t);return i?(n=!0,{...a,moments:i}):a},r=e.conditions.map(a=>isGroup(a)?{...a,conditions:a.conditions.map(s)}:s(a));return n?{...e,conditions:r}:e}export function expressionWithViewerDays(e,t=new Date){const n=e;if(!n||typeof n!="object")return e;if(n.kind==="fieldFilter"&&Array.isArray(n.conditions))return withViewerDays(n,t);const s=n.payload;if(n.kind==="ext"&&n.type==="fieldFilter"&&s&&Array.isArray(s.conditions)){const r=withViewerDays({...s,kind:"fieldFilter",conjunction:s.conjunction??"and"},t);return r.conditions===s.conditions?e:{...n,payload:{...s,conditions:r.conditions}}}return e}export function compileCondition(e,t,n=new Date){const s=e.kind==="link"&&e.table&&t?.isEmpty?r=>A(r)||t.isEmpty(e.table,r):A;if(e.op==="isEmpty")return s;if(e.op==="isNotEmpty")return r=>!s(r);if(e.kind==="linked"){const r=new Set((Array.isArray(e.value)?e.value:[e.value]).map(i=>String(i))),a=i=>(Array.isArray(i)?i:A(i)?[]:[i]).map(o=>String(o&&typeof o=="object"?o.id??"":o));return e.op==="hasNoneOf"?i=>!a(i).some(o=>r.has(o)):i=>a(i).some(o=>r.has(o))}switch(e.kind){case"number":{const r=Number(e.value);if(!Number.isFinite(r))return()=>!0;const a=u=>A(u)?NaN:Number(u),o={eq:u=>u===r,neq:u=>u!==r,lt:u=>u<r,gt:u=>u>r,lte:u=>u<=r,gte:u=>u>=r}[e.op]??(()=>!0);return u=>{const p=a(u);return Number.isNaN(p)?e.op==="neq":o(p)}}case"checkbox":{const r=e.value!==!1;return a=>!!a===r}case"select":case"multi":{const r=N(),a=y(e.value).map(o=>o===ME&&r!=null?r:o),i=new Set(a);return e.op==="is"?o=>y(o)[0]===a[0]:e.op==="isNot"?o=>y(o)[0]!==a[0]:e.op==="isAnyOf"||e.op==="hasAnyOf"?o=>y(o).some(u=>i.has(u)):e.op==="isNoneOf"||e.op==="hasNoneOf"?o=>!y(o).some(u=>i.has(u)):e.op==="hasAllOf"?o=>{const u=new Set(y(o));return[...i].every(p=>u.has(p))}:e.op==="isExactly"?o=>{const u=new Set(y(o));return u.size===i.size&&[...i].every(p=>u.has(p))}:()=>!0}case"date":{const r=dayOf(n),a=conditionMoment(e),i=a?e.op==="isBefore"?{from:null,to:a}:{from:a,to:null}:e.moments;if(i&&(i.from!=null||i.to!=null)){const c=i.from==null?-1/0:Date.parse(i.from),f=i.to==null?1/0:Date.parse(i.to),m={...e,moments:void 0,value:a?{...e.value,at:void 0}:e.value},b=compileCondition(m,t,n);return d=>{if(!isMoment(d))return b(d);const h=d instanceof Date?d.getTime():Date.parse(String(d));return Number.isFinite(h)&&h>=c&&h<f}}if(e.op==="isWithin"){const[c,f]=g(e.value??{span:"pastWeek"},r);return m=>{const b=dayOf(m);return b!=null&&b>=c&&b<=f}}const o=S(e.value??{mode:"today"},r);if(o==null)return()=>!0;const p={is:c=>c===o,isBefore:c=>c<o,isAfter:c=>c>o,isOnOrBefore:c=>c<=o,isOnOrAfter:c=>c>=o}[e.op]??(()=>!0);return c=>{const f=dayOf(c);return f!=null&&p(f)}}case"files":{const r=w(e.value);return a=>(Array.isArray(a)?a:[]).some(i=>w(i?.name).includes(r))}case"checklist":{const r=i=>{const o=T(i);return o.total>0&&o.done===o.total};if(e.op==="allDone")return r;if(e.op==="notAllDone")return i=>!r(i);if(e.op==="contains"){const i=w(e.value);return o=>M(o).some(u=>w(u.text).includes(i))}const a=parseFloat(String(e.value??""));return Number.isFinite(a)?i=>{const o=I(i);return o==null?!1:e.op==="lt"?o*100<a:o*100>=a}:()=>!0}case"time":{const r=W(String(e.value??"")),a=O(r);if(r==null||a==null)return()=>!0;const i=r.length>5?1:60,o=Math.floor(a/i),p={is:c=>c===o,isBefore:c=>c<o,isAfter:c=>c>o,isOnOrBefore:c=>c<=o,isOnOrAfter:c=>c>=o}[e.op]??(()=>!0);return c=>{const f=O(c);return f!=null&&p(Math.floor(f/i))}}case"link":case"text":{const r=w(e.value),a=i=>F(i)?w(R(i)):e.kind==="link"&&e.table&&t?w(t(e.table,i).join(", ")):w(Array.isArray(i)?i.map(o=>o&&typeof o=="object"?o.name??"":o).join(", "):i);return e.op==="contains"?i=>a(i).includes(r):e.op==="notContains"?i=>!a(i).includes(r):e.op==="is"?i=>a(i)===r:e.op==="isNot"?i=>a(i)!==r:()=>!0}}}export function compileFieldFilter(e,t,n,s){const r=o=>{const u=compileCondition(o,n,s);return p=>{const c=t(p,o.column);return u(Array.isArray(c)&&c.some(Array.isArray)?c.flat(1/0):c)}},a=(o,u)=>o==="or"?p=>u.some(c=>c(p)):p=>u.every(c=>c(p)),i=[];for(const o of e.conditions)if(isGroup(o)){const u=o.conditions.filter(isComplete).map(r);u.length&&i.push(a(o.conjunction,u))}else isComplete(o)&&i.push(r(o));return i.length?a(e.conjunction,i):null}const X={today:"viewbar.dayToday",tomorrow:"viewbar.dayTomorrow",yesterday:"viewbar.dayYesterday",oneWeekAgo:"viewbar.dayOneWeekAgo",oneWeekFromNow:"viewbar.dayOneWeekFromNow",oneMonthAgo:"viewbar.dayOneMonthAgo",oneMonthFromNow:"viewbar.dayOneMonthFromNow"},q={pastWeek:"viewbar.spanPastWeek",pastMonth:"viewbar.spanPastMonth",pastYear:"viewbar.spanPastYear",nextWeek:"viewbar.spanNextWeek",nextMonth:"viewbar.spanNextMonth",nextYear:"viewbar.spanNextYear"},x=e=>e==="or"?l("viewbar.conjOr"):e==="and"?l("viewbar.conjAnd"):e;function z(e){if(NO_VALUE.has(e.op))return"";if(e.kind==="checkbox")return e.value===!1?l("viewbar.valueUnchecked"):l("viewbar.valueChecked");if(e.kind==="date"){if(e.op==="isWithin"){const r=e.value??{span:"pastWeek"};if(r.span==="pastDays")return l("viewbar.spanPastDays",{days:r.days??0});if(r.span==="nextDays")return l("viewbar.spanNextDays",{days:r.days??0});const a=q[r.span];return a?l(a):r.span}const n=e.value??{mode:"today"};if(n.mode==="exactDate")return n.date;const s=X[n.mode];return s?l(s):n.mode}const t=n=>n===ME?l("viewbar.valueMe"):String(n);return Array.isArray(e.value)?e.value.map(t).join(", "):t(e.value??"")}export function describeCondition(e,t=n=>n){const n=operatorsFor(e.kind).find(s=>s.op===e.op)?.label??e.op;return[t(e.column),n,z(e)].filter(Boolean).join(" ")}export function describeFieldFilter(e,t){const n=[];for(const s of e.conditions)if(isGroup(s)){const r=s.conditions.filter(isComplete).map(a=>describeCondition(a,t));r.length&&n.push(r.length>1?`(${r.join(` ${x(s.conjunction)} `)})`:r[0])}else isComplete(s)&&n.push(describeCondition(s,t));return n.length?n.join(` ${x(e.conjunction)} `):l("viewbar.everyRecord")}export function fieldFilterColumns(e){const t=new Set;for(const n of e.conditions)for(const s of isGroup(n)?n.conditions:[n])isComplete(s)&&t.add(s.column);return[...t]}
|
|
@@ -1 +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)}
|
|
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"},DISTANCE:{syntax:"DISTANCE(place, place)",summary:'Metres between two places given as coordinates ("42.6977, 23.3219"), as a phone saves them.',example:"DISTANCE({Where the phone was}, '42.6977, 23.3219')",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/formula.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toDate as $}from"./format.js";import{maxOf as te,minOf as ne}from"../extent.js";export class FormulaError extends Error{}export function tokenize(e){const n=[];let t=0;for(;t<e.length;){const r=e[t];if(/\s/.test(r)){t++;continue}if(r==="{"){const i=e.indexOf("}",t);if(i<0)throw new FormulaError(`Unclosed "{" at ${t+1}`);n.push({k:"ref",v:e.slice(t+1,i).trim(),at:t}),t=i+1;continue}if(r==='"'||r==="'"){let i=t+1,c="";for(;i<e.length&&e[i]!==r;){if(e[i]==="\\"&&i+1<e.length){c+=e[i+1],i+=2;continue}c+=e[i++]}if(i>=e.length)throw new FormulaError(`Unclosed text at ${t+1}`);n.push({k:"str",v:c,at:t}),t=i+1;continue}const l=/^\d+(\.\d+)?|^\.\d+/.exec(e.slice(t));if(l){n.push({k:"num",v:l[0],at:t}),t+=l[0].length;continue}const s=/^[A-Za-z_][A-Za-z0-9_]*/.exec(e.slice(t));if(s){n.push({k:"id",v:s[0],at:t}),t+=s[0].length;continue}const f=/^(!=|<=|>=|<>|[-+*/&=<>])/.exec(e.slice(t));if(f){n.push({k:"op",v:f[0]==="<>"?"!=":f[0],at:t}),t+=f[0].length;continue}if(r==="("||r===")"||r===","){n.push({k:r,v:r,at:t}),t++;continue}throw new FormulaError(`Unexpected "${r}" at ${t+1}`)}return n}const y=e=>e==null||e===""||Array.isArray(e)&&e.length===0,o=e=>{if(typeof e=="number")return e;if(typeof e=="boolean")return e?1:0;if(e instanceof Date)return e.getTime();if(e==null||e==="")return 0;if(Array.isArray(e))return e.reduce((t,r)=>t+o(r),0);const n=Number(e);return Number.isFinite(n)?n:NaN},u=e=>e==null?"":e instanceof Date?e.toISOString():Array.isArray(e)?e.map(u).join(", "):String(e),A=e=>!y(e)&&e!==!1&&e!==0,re=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;export function isoDate(e){const n=e.trim();return re.test(n)?$(n):null}const h=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(e==null||e===""||typeof e=="boolean")return null;if(typeof e=="number")return $(e);const n=u(e).trim();return isoDate(n)??(/\d{4}/.test(n)&&/[/\s,.-]/.test(n)?$(n):null)},d=e=>e.flatMap(n=>Array.isArray(n)?n:[n]),M=e=>String(e).padStart(2,"0"),R=e=>Number(e.toPrecision(12)),le={milliseconds:"ms",millisecond:"ms",ms:"ms",seconds:"s",second:"s",s:"s",minutes:"m",minute:"m",m:"m",hours:"h",hour:"h",h:"h",days:"d",day:"d",d:"d",weeks:"w",week:"w",w:"w",months:"mo",month:"mo",quarters:"q",quarter:"q",q:"q",years:"y",year:"y",y:"y"},k={ms:1,s:1e3,m:6e4,h:36e5},x=e=>le[u(e).trim().toLowerCase()]??null;function P(e,n){const t=new Date(e),r=t.getDate();return t.setDate(1),t.setMonth(t.getMonth()+n),t.setDate(Math.min(r,new Date(t.getFullYear(),t.getMonth()+1,0).getDate())),t}function se(e,n,t){if(k[t])return new Date(e.getTime()+n*k[t]);if(t==="mo"||t==="q"||t==="y")return P(e,Math.trunc(n)*(t==="y"?12:t==="q"?3:1));const r=n*(t==="w"?7:1),l=new Date(e);return l.setDate(l.getDate()+Math.trunc(r)),new Date(l.getTime()+(r-Math.trunc(r))*864e5)}const L=e=>e.getTime()-e.getTimezoneOffset()*6e4;function b(e,n,t){if(k[t])return Math.trunc((e.getTime()-n.getTime())/k[t]);if(t==="d"||t==="w")return Math.trunc((L(e)-L(n))/(t==="w"?6048e5:864e5));let r=(e.getFullYear()-n.getFullYear())*12+e.getMonth()-n.getMonth();const l=P(n,r).getTime();return r>0&&l>e.getTime()?r-=1:r<0&&l<e.getTime()&&(r+=1),t==="y"?Math.trunc(r/12):t==="q"?Math.trunc(r/3):r}function O(e,n){if(n==="ms")return e.getTime();const t=new Date(e);return n==="s"?t.setMilliseconds(0):n==="m"?t.setSeconds(0,0):n==="h"?t.setMinutes(0,0,0):(t.setHours(0,0,0,0),n==="w"&&t.setDate(t.getDate()-t.getDay()),(n==="mo"||n==="q"||n==="y")&&t.setDate(1),n==="q"&&t.setMonth(t.getMonth()-t.getMonth()%3),n==="y"&&t.setMonth(0),t.getTime())}const Y=e=>`${e.getFullYear()}-${M(e.getMonth()+1)}-${M(e.getDate())}`;function W(e){const n=d([e??null]).flatMap(t=>typeof t=="string"?t.split(","):[t]);return new Set(n.map(t=>h(typeof t=="string"?t.trim():t)).filter(t=>!!t).map(Y))}const z=(e,n)=>e.getDay()!==0&&e.getDay()!==6&&!n.has(Y(e)),X=1e5;class oe extends Date{}function q(e,n){const t=new oe(e.getTime()),r=e;return t.locale=n.locale??r.locale,t.zone=n.zone??r.zone,t}const v=new Map;function j(e){let n=v.get(e);return n||(n=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",weekday:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}),v.set(e,n)),n}const ue=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function ie(e){const n=e.zone,t=e.getMilliseconds();if(!n)return{y:e.getFullYear(),mo:e.getMonth(),d:e.getDate(),h:e.getHours(),mi:e.getMinutes(),s:e.getSeconds(),ms:t,wd:e.getDay(),offset:-e.getTimezoneOffset()};const r={};for(const s of j(n).formatToParts(e))r[s.type]=s.value;const l={y:+r.year,mo:+r.month-1,d:+r.day,h:+r.hour%24,mi:+r.minute,s:+r.second,ms:t,wd:ue.indexOf(r.weekday),offset:0};return l.offset=Math.round((Date.UTC(l.y,l.mo,l.d,l.h,l.mi,l.s,t)-e.getTime())/6e4),l}const G=new Map;function I(e,n,t,r){const l=`${e??"en"}|${n}|${t}`;let s=G.get(l);return s||G.set(l,s=new Intl.DateTimeFormat(e??"en",{[n]:t,timeZone:"UTC"})),s.format(n==="month"?Date.UTC(2023,r,1):Date.UTC(2023,0,1+r))}const ce=e=>{const n=e%100;return`${e}${n>=11&&n<=13?"th":["th","st","nd","rd"][e%10]??"th"}`},K=(e,n)=>{const t=Math.abs(e);return`${e<0?"-":"+"}${M(Math.floor(t/60))}${n?":":""}${M(t%60)}`},ae={LTS:"h:mm:ss A",LT:"h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A",LLL:"MMMM D, YYYY h:mm A",LL:"MMMM D, YYYY",L:"MM/DD/YYYY"},fe=/\[([^\]]*)]|YYYY|YY|Q|MMMM|MMM|MM|M|DDDD|DDD|Do|DD|D|dddd|ddd|d|HH|H|hh|h|mm|m|ss|s|SSS|SS|S|A|a|ZZ|Z|X|x/g;function he(e,n){const t=ie(e),r=e.locale,l=n.replace(/\[[^\]]*]|LTS|LT|LLLL|LLL|LL|L/g,i=>ae[i]??i),s=t.h%12||12,f=Math.round((Date.UTC(t.y,t.mo,t.d)-Date.UTC(t.y,0,1))/864e5)+1;return l.replace(fe,(i,c)=>{if(c!==void 0)return c;switch(i){case"YYYY":return String(t.y).padStart(4,"0");case"YY":return M(t.y%100);case"Q":return String(Math.floor(t.mo/3)+1);case"MMMM":return I(r,"month","long",t.mo);case"MMM":return I(r,"month","short",t.mo);case"MM":return M(t.mo+1);case"M":return String(t.mo+1);case"DDDD":return String(f).padStart(3,"0");case"DDD":return String(f);case"Do":return ce(t.d);case"DD":return M(t.d);case"D":return String(t.d);case"dddd":return I(r,"weekday","long",t.wd);case"ddd":return I(r,"weekday","short",t.wd);case"d":return String(t.wd);case"HH":return M(t.h);case"H":return String(t.h);case"hh":return M(s);case"h":return String(s);case"mm":return M(t.mi);case"m":return String(t.mi);case"ss":return M(t.s);case"s":return String(t.s);case"SSS":return String(t.ms).padStart(3,"0");case"SS":return M(Math.floor(t.ms/10));case"S":return String(Math.floor(t.ms/100));case"A":return t.h<12?"AM":"PM";case"a":return t.h<12?"am":"pm";case"ZZ":return K(t.offset,!1);case"Z":return K(t.offset,!0);case"X":return String(Math.floor(e.getTime()/1e3));default:return String(e.getTime())}})}const me=["january","february","march","april","may","june","july","august","september","october","november","december"],de=/\[([^\]]*)]|YYYY|YY|MMMM|MMM|MM|M|Do|DD|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|SSS|A|a|ZZ|Z|X|x/g;function Me(e,n){const t=[];let r="^\\s*",l=0;const s=D=>D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s+");for(const D of n.matchAll(de)){if(r+=s(n.slice(l,D.index)),l=D.index+D[0].length,D[1]!==void 0){r+=s(D[1]);continue}const a=D[0];t.push(a),r+=a==="YYYY"?"(\\d{4})":a==="MMMM"||a==="MMM"||a==="dddd"||a==="ddd"?"([A-Za-z]+)\\.?":a==="Do"?"(\\d{1,2})(?:st|nd|rd|th)":a==="SSS"?"(\\d{1,3})":a==="A"||a==="a"?"([AaPp][Mm])":a==="Z"||a==="ZZ"?"(Z|[+-]\\d{2}:?\\d{2})":a==="X"||a==="x"?"(-?\\d+)":"(\\d{1,2})"}r+=`${s(n.slice(l))}\\s*$`;const f=new RegExp(r,"i").exec(e);if(!f)return null;let i=new Date().getFullYear(),c=0,m=1,g=0,E=0,S=0,w=0,U=null,N=null;for(let D=0;D<t.length;D++){const a=t[D],T=f[D+1],p=Number(T);if(a==="X"||a==="x")return new Date(a==="X"?p*1e3:p);if(a==="YYYY")i=p;else if(a==="YY")i=p+(p<69?2e3:1900);else if(a==="MMMM"||a==="MMM"){const Z=me.findIndex(ee=>ee.startsWith(T.toLowerCase().slice(0,3)));if(Z<0)return null;c=Z}else a==="MM"||a==="M"?c=p-1:a==="DD"||a==="D"||a==="Do"?m=p:a==="HH"||a==="H"||a==="hh"||a==="h"?g=p:a==="mm"||a==="m"?E=p:a==="ss"||a==="s"?S=p:a==="SSS"?w=Number(T.padEnd(3,"0")):a==="A"||a==="a"?U=T.toLowerCase()==="pm":(a==="Z"||a==="ZZ")&&(N=T.toUpperCase()==="Z"?0:(T[0]==="-"?-1:1)*(Number(T.slice(1,3))*60+Number(T.slice(-2))))}if(U!=null&&(g=g%12+(U?12:0)),c<0||c>11||m<1||m>31||g>23||E>59||S>59)return null;const C=N==null?new Date(i,c,m,g,E,S,w):new Date(Date.UTC(i,c,m,g,E,S,w)-N*6e4);return N==null&&C.getDate()!==m||Number.isNaN(C.getTime())?null:C}const F=new Map;function _(e,n=!1){const t=`${n?"g":""}|${e}`;let r=F.get(t);if(!r){const l=/^\(\?([ims]+)\)/.exec(e);r=new RegExp(l?e.slice(l[0].length):e,`${l?.[1]??""}${n?"g":""}`),F.size>200&&F.clear(),F.set(t,r)}return r.lastIndex=0,r}const H="#ERROR",B=e=>`${e instanceof Date?"d":typeof e}:${u(e)}`;function ge(e,n,t){const r=n<0?e.length+n:Math.max(0,n-1),l=t==null?e.length:t<0?e.length+t+1:t;return e.slice(r,l)}function V(e,n){const t=e<0?-1:1;let r=Math.ceil(Math.abs(e));return r%2===1!==n&&(r+=1),t*r}const Q={IF:e=>A(e[0]??null)?e[1]??null:e[2]??null,AND:e=>d(e).every(A),OR:e=>d(e).some(A),NOT:e=>!A(e[0]??null),XOR:e=>d(e).filter(A).length%2===1,TRUE:()=>!0,FALSE:()=>!1,BLANK:()=>null,ERROR:()=>{throw new FormulaError("ERROR()")},ISERROR:e=>e[0]===H,RECORD_ID:()=>null,SWITCH:e=>{for(let n=1;n+1<e.length;n+=2)if(u(e[0]??null)===u(e[n]??null))return e[n+1]??null;return e.length%2===0?e[e.length-1]??null:null},CONCATENATE:e=>e.map(u).join(""),LEN:e=>u(e[0]??null).length,UPPER:e=>u(e[0]??null).toUpperCase(),LOWER:e=>u(e[0]??null).toLowerCase(),TRIM:e=>u(e[0]??null).trim(),LEFT:e=>u(e[0]??null).slice(0,o(e[1]??1)),RIGHT:e=>{const n=u(e[0]??null),t=o(e[1]??1);return t<=0?"":n.slice(-t)},MID:e=>{const n=u(e[0]??null),t=Math.max(0,o(e[1]??1)-1);return e.length>2?n.slice(t,t+Math.max(0,o(e[2]??0))):n.slice(t)},FIND:e=>u(e[1]??null).indexOf(u(e[0]??null),Math.max(0,o(e[2]??1)-1))+1,SEARCH:e=>{const n=u(e[1]??null).indexOf(u(e[0]??null),Math.max(0,o(e[2]??1)-1));return n<0?null:n+1},SUBSTITUTE:e=>{const n=u(e[0]??null).split(u(e[1]??null));if(e.length<4)return n.join(u(e[2]??null));const t=o(e[3]??null);return n.reduce((r,l,s)=>s===0?l:r+u(s===t?e[2]??null:e[1]??null)+l,"")},REPLACE:e=>{const n=u(e[0]??null),t=Math.max(0,o(e[1]??1)-1);return n.slice(0,t)+u(e[3]??null)+n.slice(t+Math.max(0,o(e[2]??0)))},ENCODE_URL_COMPONENT:e=>encodeURIComponent(u(e[0]??null)),REGEX_MATCH:e=>_(u(e[1]??null)).test(u(e[0]??null)),REGEX_EXTRACT:e=>_(u(e[1]??null)).exec(u(e[0]??null))?.[0]??null,REGEX_REPLACE:e=>u(e[0]??null).replace(_(u(e[1]??null),!0),u(e[2]??null)),REPT:e=>u(e[0]??null).repeat(Math.max(0,Math.min(1e3,o(e[1]??0)))),T:e=>typeof e[0]=="string"?e[0]:"",VALUE:e=>{const n=u(e[0]??null).replace(/[^0-9.eE+-]/g,""),t=/\d/.test(n)?Number(n):NaN;return Number.isFinite(t)?t:null},ARRAYJOIN:e=>d([e[0]??null]).map(u).filter(Boolean).join(e.length>1?u(e[1]??null):", "),ARRAYCOMPACT:e=>d([e[0]??null]).filter(n=>n!=null&&n!==""),ARRAYFLATTEN:e=>e.flat(1/0),ARRAYUNIQUE:e=>{const n=new Set;return d([e[0]??null]).filter(t=>!n.has(B(t))&&!!n.add(B(t)))},ARRAYSLICE:e=>ge(d([e[0]??null]),o(e[1]??1),e.length>2?o(e[2]??null):void 0),SUM:e=>d(e).reduce((n,t)=>n+o(t),0),AVERAGE:e=>{const n=d(e).filter(t=>!y(t));return n.length?n.reduce((t,r)=>t+o(r),0)/n.length:null},MAX:e=>{const n=d(e).filter(t=>!y(t)).map(o);return n.length?te(n):null},MIN:e=>{const n=d(e).filter(t=>!y(t)).map(o);return n.length?ne(n):null},COUNT:e=>d(e).filter(n=>typeof n=="number").length,COUNTA:e=>d(e).filter(n=>!y(n)).length,COUNTALL:e=>d(e).length,ROUND:e=>{const n=10**o(e[1]??0);return Math.round(o(e[0]??null)*n)/n},ROUNDUP:e=>{const n=10**o(e[1]??0),t=o(e[0]??null);return Math.sign(t)*Math.ceil(R(Math.abs(t)*n))/n},ROUNDDOWN:e=>{const n=10**o(e[1]??0),t=o(e[0]??null);return Math.sign(t)*Math.floor(R(Math.abs(t)*n))/n},INT:e=>Math.floor(o(e[0]??null)),ABS:e=>Math.abs(o(e[0]??null)),MOD:e=>o(e[0]??null)%o(e[1]??1),POWER:e=>o(e[0]??null)**o(e[1]??1),SQRT:e=>Math.sqrt(o(e[0]??null)),EXP:e=>Math.exp(o(e[0]??null)),LOG:e=>Math.log(o(e[0]??null))/Math.log(e.length>1?o(e[1]??null):10),EVEN:e=>V(o(e[0]??null),!1),ODD:e=>V(o(e[0]??null),!0),CEILING:e=>{const n=o(e[1]??1);return n===0?0:R(Math.ceil(R(o(e[0]??null)/n))*n)},FLOOR:e=>{const n=o(e[1]??1);return n===0?0:R(Math.floor(R(o(e[0]??null)/n))*n)},TODAY:()=>{const e=new Date;return e.setHours(0,0,0,0),e},NOW:()=>new Date,YEAR:e=>h(e[0]??null)?.getFullYear()??null,MONTH:e=>{const n=h(e[0]??null);return n?n.getMonth()+1:null},DAY:e=>h(e[0]??null)?.getDate()??null,HOUR:e=>h(e[0]??null)?.getHours()??null,MINUTE:e=>h(e[0]??null)?.getMinutes()??null,SECOND:e=>h(e[0]??null)?.getSeconds()??null,WEEKDAY:e=>{const n=h(e[0]??null);return n?/^mon/i.test(u(e[1]??null))?(n.getDay()+6)%7:n.getDay():null},WEEKNUM:e=>{const n=h(e[0]??null);if(!n)return null;const t=/^mon/i.test(u(e[1]??null))?1:0,r=new Date(n.getFullYear(),0,1),l=Math.round((L(new Date(n.getFullYear(),n.getMonth(),n.getDate()))-L(r))/864e5);return Math.floor((l+(r.getDay()-t+7)%7)/7)+1},DATEADD:e=>{const n=h(e[0]??null),t=e.length>2?x(e[2]??null):"d";return n&&t?se(n,o(e[1]??0),t):null},DATETIME_DIFF:e=>{const n=h(e[0]??null),t=h(e[1]??null),r=e.length>2?x(e[2]??null):"s";return n&&t&&r?b(n,t,r):null},IS_BEFORE:e=>{const n=h(e[0]??null),t=h(e[1]??null);return!!n&&!!t&&n<t},IS_AFTER:e=>{const n=h(e[0]??null),t=h(e[1]??null);return!!n&&!!t&&n>t},IS_SAME:e=>{const n=h(e[0]??null),t=h(e[1]??null),r=e.length>2?x(e[2]??null):"ms";return!!n&&!!t&&!!r&&O(n,r)===O(t,r)},DATESTR:e=>{const n=h(e[0]??null);return n?Y(n):null},TIMESTR:e=>{const n=h(e[0]??null);return n?`${M(n.getHours())}:${M(n.getMinutes())}:${M(n.getSeconds())}`:null},DATETIME_FORMAT:e=>{const n=h(e[0]??null);return n?he(n,e.length>1&&!y(e[1]??null)?u(e[1]??null):"YYYY-MM-DDTHH:mm:ss.SSSZ"):null},DATETIME_PARSE:e=>e.length>1&&!y(e[1]??null)?Me(u(e[0]??null),u(e[1]??null)):h(e[0]??null),SET_LOCALE:e=>{const n=h(e[0]??null),t=u(e[1]??null).trim();return!n||!t?n:q(n,{locale:Intl.DateTimeFormat.supportedLocalesOf(t)[0]??t})},SET_TIMEZONE:e=>{const n=h(e[0]??null),t=u(e[1]??null).trim();return!n||!t?n:(j(t),q(n,{zone:t}))},TONOW:e=>{const n=h(e[0]??null);return n?b(new Date(O(new Date,"d")),new Date(O(n,"d")),"d"):null},FROMNOW:e=>{const n=h(e[0]??null);return n?b(new Date(O(n,"d")),new Date(O(new Date,"d")),"d"):null},WORKDAY:e=>{const n=h(e[0]??null);if(!n)return null;const t=Math.trunc(o(e[1]??0)),r=t<0?-1:1,l=W(e[2]),s=new Date(n);for(let f=Math.abs(t),i=0;f>0;){if(++i>X)return null;s.setDate(s.getDate()+r),z(s,l)&&(f-=1)}return s},WORKDAY_DIFF:e=>{const n=h(e[0]??null),t=h(e[1]??null);if(!n||!t)return null;const r=W(e[2]),l=n>t?-1:1,s=new Date(l>0?n:t),f=Y(l>0?t:n);let i=0;for(let c=0;Y(s)<=f;c++){if(c>X)return null;z(s,r)&&(i+=1),s.setDate(s.getDate()+1)}return l*i}};function J(e,n,t){switch(e){case"=":return n===t;case"!=":return n!==t;case"<":return n<t;case">":return n>t;case"<=":return n<=t;default:return n>=t}}const De=new Set(["DATEADD","DATETIME_DIFF","IS_SAME"]);export const FORMULA_FUNCTIONS=Object.keys(Q).sort(),selfReferenceError=e=>new FormulaError(`A formula cannot read its own field {${e.trim()}}`);export function columnResolver(e,n=[]){const t=new Set(n.filter(r=>r!=null&&String(r).trim()!=="").map(r=>String(r).trim().toLowerCase()));return r=>{const l=r.trim().toLowerCase();if(t.has(l))throw selfReferenceError(r);const s=e.find(f=>String(f.header??"").trim().toLowerCase()===l||String(f.field??"").toLowerCase()===l);return s?String(s.field??s.id):null}}class pe{constructor(n,t,r){this.toks=n,this.resolve=t,this.refs=r,this.i=0}peek(){return this.toks[this.i]}next(){return this.toks[this.i++]}expect(n,t){const r=this.next();if(!r||r.k!==n||t&&r.v!==t)throw new FormulaError(`Expected "${t??n}"${r?` at ${r.at+1}`:" at the end"}`);return r}parse(){const n=this.compare();if(this.peek())throw new FormulaError(`Unexpected "${this.peek().v}" at ${this.peek().at+1}`);return n}compare(){let n=this.concat();for(let t=this.peek();t&&t.k==="op"&&["=","!=","<",">","<=",">="].includes(t.v);t=this.peek()){this.next();const r=t.v,l=n,s=this.concat();n=f=>{const i=l(f),c=s(f);if(i instanceof Date||c instanceof Date){const S=h(i),w=h(c);return!S||!w?r==="!=":J(r,S.getTime(),w.getTime())}const m=typeof i=="number"||typeof c=="number",g=m?o(i):u(i),E=m?o(c):u(c);return J(r,g,E)}}return n}concat(){let n=this.add();for(;this.peek()?.k==="op"&&this.peek().v==="&";){this.next();const t=n,r=this.add();n=l=>u(t(l))+u(r(l))}return n}add(){let n=this.mul();for(let t=this.peek();t&&t.k==="op"&&(t.v==="+"||t.v==="-");t=this.peek()){this.next();const r=n,l=this.mul(),s=t.v==="+";n=f=>s?o(r(f))+o(l(f)):o(r(f))-o(l(f))}return n}mul(){let n=this.unary();for(let t=this.peek();t&&t.k==="op"&&(t.v==="*"||t.v==="/");t=this.peek()){this.next();const r=n,l=this.unary(),s=t.v==="*";n=f=>{if(s)return o(r(f))*o(l(f));const i=o(l(f));return i===0?null:o(r(f))/i}}return n}unary(){const n=this.peek();if(n?.k==="op"&&n.v==="-"){this.next();const t=this.unary();return r=>-o(t(r))}return this.primary()}primary(){const n=this.next();if(!n)throw new FormulaError("The formula ends too early");if(n.k==="num"){const t=Number(n.v);return()=>t}if(n.k==="str"){const t=n.v;return()=>t}if(n.k==="ref"){const t=this.resolve(n.v);if(t==null)throw new FormulaError(`No field named "${n.v}"`);return this.refs.add(t),r=>r?.[t]??null}if(n.k==="("){const t=this.compare();return this.expect(")"),t}if(n.k==="id"){const t=n.v.toUpperCase();if(t==="TRUE"&&this.peek()?.k!=="(")return()=>!0;if(t==="FALSE"&&this.peek()?.k!=="(")return()=>!1;const r=Q[t];if(!r)throw new FormulaError(`Unknown function ${n.v}`);this.expect("(");const l=[],s=[],f=()=>{const c=this.i;l.push(this.compare());const m=this.i===c+1?this.toks[c]:void 0;s.push(m?.k==="str"?m.v:void 0)};if(this.peek()?.k!==")")for(f();this.peek()?.k===",";)this.next(),f();this.expect(")");const i=s[2];if(De.has(t)&&i!==void 0&&!x(i))throw new FormulaError(`Unknown unit "${i}" in ${t}: use ms, seconds, minutes, hours, days, weeks, months, quarters or years`);return t==="RECORD_ID"?c=>c?.id==null?null:String(c.id):t==="ISERROR"?c=>{try{const m=l[0]?.(c)??null;return m===H||typeof m=="number"&&!Number.isFinite(m)}catch{return!0}}:t==="IF"?c=>A(l[0]?.(c)??null)?l[1]?.(c)??null:l[2]?.(c)??null:t==="SWITCH"?c=>{if(!l.length)return null;const m=u(l[0](c));for(let g=1;g+1<l.length;g+=2)if(m===u(l[g](c)))return l[g+1](c);return l.length%2===0?l[l.length-1](c):null}:c=>r(l.map(m=>m(c)))}throw new FormulaError(`Unexpected "${n.v}" at ${n.at+1}`)}}export function compileFormula(e,n){if(!e.trim())throw new FormulaError("The formula is empty");const t=new Set,r=new pe(tokenize(e),n,t).parse();return{fn:l=>{try{const s=r(l);return typeof s=="number"&&!Number.isFinite(s)?null:s}catch(s){return s instanceof FormulaError?H:null}},refs:[...t]}}export function renameFormulaRefs(e,n){let t;try{t=tokenize(e)}catch{return e}let r="",l=0;for(const s of t){if(s.k!=="ref")continue;const f=n(s.v);if(f==null)continue;const i=e.indexOf("}",s.at);r+=`${e.slice(l,s.at)}{${f}}`,l=i+1}return l?r+e.slice(l):e}export function formulaRefs(e,n){let t;try{t=tokenize(e)}catch{return[]}const r=new Set;for(const l of t)if(l.k==="ref")try{const s=n(l.v);s!=null&&r.add(s)}catch{}return[...r]}export function formulaReaders(e,n){const t=new Set([n.field,n.id].filter(l=>l!=null&&l!=="").map(String));if(!t.size)return[];const r=columnResolver(e);return e.filter(l=>l.fieldType!=="formula"||t.has(String(l.field??l.id??""))?!1:formulaRefs(String(l.fieldProps?.formula??""),r).some(s=>t.has(s)))}export function formulaError(e,n){try{return compileFormula(e,n),null}catch(t){return t instanceof FormulaError?t.message:"The formula is not valid"}}
|
|
1
|
+
import{toDate as b}from"./format.js";import{maxOf as nt,minOf as rt}from"../extent.js";export class FormulaError extends Error{}export function tokenize(t){const n=[];let e=0;for(;e<t.length;){const r=t[e];if(/\s/.test(r)){e++;continue}if(r==="{"){const i=t.indexOf("}",e);if(i<0)throw new FormulaError(`Unclosed "{" at ${e+1}`);n.push({k:"ref",v:t.slice(e+1,i).trim(),at:e}),e=i+1;continue}if(r==='"'||r==="'"){let i=e+1,c="";for(;i<t.length&&t[i]!==r;){if(t[i]==="\\"&&i+1<t.length){c+=t[i+1],i+=2;continue}c+=t[i++]}if(i>=t.length)throw new FormulaError(`Unclosed text at ${e+1}`);n.push({k:"str",v:c,at:e}),e=i+1;continue}const l=/^\d+(\.\d+)?|^\.\d+/.exec(t.slice(e));if(l){n.push({k:"num",v:l[0],at:e}),e+=l[0].length;continue}const s=/^[A-Za-z_][A-Za-z0-9_]*/.exec(t.slice(e));if(s){n.push({k:"id",v:s[0],at:e}),e+=s[0].length;continue}const f=/^(!=|<=|>=|<>|[-+*/&=<>])/.exec(t.slice(e));if(f){n.push({k:"op",v:f[0]==="<>"?"!=":f[0],at:e}),e+=f[0].length;continue}if(r==="("||r===")"||r===","){n.push({k:r,v:r,at:e}),e++;continue}throw new FormulaError(`Unexpected "${r}" at ${e+1}`)}return n}const S=t=>t==null||t===""||Array.isArray(t)&&t.length===0,u=t=>{if(typeof t=="number")return t;if(typeof t=="boolean")return t?1:0;if(t instanceof Date)return t.getTime();if(t==null||t==="")return 0;if(Array.isArray(t))return t.reduce((e,r)=>e+u(r),0);const n=Number(t);return Number.isFinite(n)?n:NaN},o=t=>t==null?"":t instanceof Date?t.toISOString():Array.isArray(t)?t.map(o).join(", "):String(t),A=t=>!S(t)&&t!==!1&&t!==0,lt=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;export function isoDate(t){const n=t.trim();return lt.test(n)?b(n):null}const h=t=>{if(t instanceof Date)return Number.isNaN(t.getTime())?null:t;if(t==null||t===""||typeof t=="boolean")return null;if(typeof t=="number")return b(t);const n=o(t).trim();return isoDate(n)??(/\d{4}/.test(n)&&/[/\s,.-]/.test(n)?b(n):null)},d=t=>t.flatMap(n=>Array.isArray(n)?n:[n]),k=t=>{const n=o(Array.isArray(t)?t.find(s=>!S(s))??null:t).replace(/%2C/gi,","),e=/(?<![\d.])(-?\d{1,2}(?:\.\d+)?)\s*,\s*(-?\d{1,3}(?:\.\d+)?)/.exec(n);if(!e)return null;const r=Number(e[1]),l=Number(e[2]);return Math.abs(r)<=90&&Math.abs(l)<=180?{lat:r,lng:l}:null},st=(t,n)=>{const e=l=>l*Math.PI/180,r=Math.sin(e(n.lat-t.lat)/2)**2+Math.cos(e(t.lat))*Math.cos(e(n.lat))*Math.sin(e(n.lng-t.lng)/2)**2;return Math.round(2*6371e3*Math.asin(Math.min(1,Math.sqrt(r))))},M=t=>String(t).padStart(2,"0"),R=t=>Number(t.toPrecision(12)),ot={milliseconds:"ms",millisecond:"ms",ms:"ms",seconds:"s",second:"s",s:"s",minutes:"m",minute:"m",m:"m",hours:"h",hour:"h",h:"h",days:"d",day:"d",d:"d",weeks:"w",week:"w",w:"w",months:"mo",month:"mo",quarters:"q",quarter:"q",q:"q",years:"y",year:"y",y:"y"},x={ms:1,s:1e3,m:6e4,h:36e5},L=t=>ot[o(t).trim().toLowerCase()]??null;function W(t,n){const e=new Date(t),r=e.getDate();return e.setDate(1),e.setMonth(e.getMonth()+n),e.setDate(Math.min(r,new Date(e.getFullYear(),e.getMonth()+1,0).getDate())),e}function ut(t,n,e){if(x[e])return new Date(t.getTime()+n*x[e]);if(e==="mo"||e==="q"||e==="y")return W(t,Math.trunc(n)*(e==="y"?12:e==="q"?3:1));const r=n*(e==="w"?7:1),l=new Date(t);return l.setDate(l.getDate()+Math.trunc(r)),new Date(l.getTime()+(r-Math.trunc(r))*864e5)}const I=t=>t.getTime()-t.getTimezoneOffset()*6e4;function _(t,n,e){if(x[e])return Math.trunc((t.getTime()-n.getTime())/x[e]);if(e==="d"||e==="w")return Math.trunc((I(t)-I(n))/(e==="w"?6048e5:864e5));let r=(t.getFullYear()-n.getFullYear())*12+t.getMonth()-n.getMonth();const l=W(n,r).getTime();return r>0&&l>t.getTime()?r-=1:r<0&&l<t.getTime()&&(r+=1),e==="y"?Math.trunc(r/12):e==="q"?Math.trunc(r/3):r}function O(t,n){if(n==="ms")return t.getTime();const e=new Date(t);return n==="s"?e.setMilliseconds(0):n==="m"?e.setSeconds(0,0):n==="h"?e.setMinutes(0,0,0):(e.setHours(0,0,0,0),n==="w"&&e.setDate(e.getDate()-e.getDay()),(n==="mo"||n==="q"||n==="y")&&e.setDate(1),n==="q"&&e.setMonth(e.getMonth()-e.getMonth()%3),n==="y"&&e.setMonth(0),e.getTime())}const N=t=>`${t.getFullYear()}-${M(t.getMonth()+1)}-${M(t.getDate())}`;function z(t){const n=d([t??null]).flatMap(e=>typeof e=="string"?e.split(","):[e]);return new Set(n.map(e=>h(typeof e=="string"?e.trim():e)).filter(e=>!!e).map(N))}const X=(t,n)=>t.getDay()!==0&&t.getDay()!==6&&!n.has(N(t)),q=1e5;class it extends Date{}function j(t,n){const e=new it(t.getTime()),r=t;return e.locale=n.locale??r.locale,e.zone=n.zone??r.zone,e}const v=new Map;function G(t){let n=v.get(t);return n||(n=new Intl.DateTimeFormat("en-US",{timeZone:t,hourCycle:"h23",weekday:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}),v.set(t,n)),n}const ct=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function at(t){const n=t.zone,e=t.getMilliseconds();if(!n)return{y:t.getFullYear(),mo:t.getMonth(),d:t.getDate(),h:t.getHours(),mi:t.getMinutes(),s:t.getSeconds(),ms:e,wd:t.getDay(),offset:-t.getTimezoneOffset()};const r={};for(const s of G(n).formatToParts(t))r[s.type]=s.value;const l={y:+r.year,mo:+r.month-1,d:+r.day,h:+r.hour%24,mi:+r.minute,s:+r.second,ms:e,wd:ct.indexOf(r.weekday),offset:0};return l.offset=Math.round((Date.UTC(l.y,l.mo,l.d,l.h,l.mi,l.s,e)-t.getTime())/6e4),l}const K=new Map;function $(t,n,e,r){const l=`${t??"en"}|${n}|${e}`;let s=K.get(l);return s||K.set(l,s=new Intl.DateTimeFormat(t??"en",{[n]:e,timeZone:"UTC"})),s.format(n==="month"?Date.UTC(2023,r,1):Date.UTC(2023,0,1+r))}const ft=t=>{const n=t%100;return`${t}${n>=11&&n<=13?"th":["th","st","nd","rd"][t%10]??"th"}`},B=(t,n)=>{const e=Math.abs(t);return`${t<0?"-":"+"}${M(Math.floor(e/60))}${n?":":""}${M(e%60)}`},ht={LTS:"h:mm:ss A",LT:"h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A",LLL:"MMMM D, YYYY h:mm A",LL:"MMMM D, YYYY",L:"MM/DD/YYYY"},mt=/\[([^\]]*)]|YYYY|YY|Q|MMMM|MMM|MM|M|DDDD|DDD|Do|DD|D|dddd|ddd|d|HH|H|hh|h|mm|m|ss|s|SSS|SS|S|A|a|ZZ|Z|X|x/g;function dt(t,n){const e=at(t),r=t.locale,l=n.replace(/\[[^\]]*]|LTS|LT|LLLL|LLL|LL|L/g,i=>ht[i]??i),s=e.h%12||12,f=Math.round((Date.UTC(e.y,e.mo,e.d)-Date.UTC(e.y,0,1))/864e5)+1;return l.replace(mt,(i,c)=>{if(c!==void 0)return c;switch(i){case"YYYY":return String(e.y).padStart(4,"0");case"YY":return M(e.y%100);case"Q":return String(Math.floor(e.mo/3)+1);case"MMMM":return $(r,"month","long",e.mo);case"MMM":return $(r,"month","short",e.mo);case"MM":return M(e.mo+1);case"M":return String(e.mo+1);case"DDDD":return String(f).padStart(3,"0");case"DDD":return String(f);case"Do":return ft(e.d);case"DD":return M(e.d);case"D":return String(e.d);case"dddd":return $(r,"weekday","long",e.wd);case"ddd":return $(r,"weekday","short",e.wd);case"d":return String(e.wd);case"HH":return M(e.h);case"H":return String(e.h);case"hh":return M(s);case"h":return String(s);case"mm":return M(e.mi);case"m":return String(e.mi);case"ss":return M(e.s);case"s":return String(e.s);case"SSS":return String(e.ms).padStart(3,"0");case"SS":return M(Math.floor(e.ms/10));case"S":return String(Math.floor(e.ms/100));case"A":return e.h<12?"AM":"PM";case"a":return e.h<12?"am":"pm";case"ZZ":return B(e.offset,!1);case"Z":return B(e.offset,!0);case"X":return String(Math.floor(t.getTime()/1e3));default:return String(t.getTime())}})}const Mt=["january","february","march","april","may","june","july","august","september","october","november","december"],gt=/\[([^\]]*)]|YYYY|YY|MMMM|MMM|MM|M|Do|DD|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|SSS|A|a|ZZ|Z|X|x/g;function Dt(t,n){const e=[];let r="^\\s*",l=0;const s=D=>D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s+");for(const D of n.matchAll(gt)){if(r+=s(n.slice(l,D.index)),l=D.index+D[0].length,D[1]!==void 0){r+=s(D[1]);continue}const a=D[0];e.push(a),r+=a==="YYYY"?"(\\d{4})":a==="MMMM"||a==="MMM"||a==="dddd"||a==="ddd"?"([A-Za-z]+)\\.?":a==="Do"?"(\\d{1,2})(?:st|nd|rd|th)":a==="SSS"?"(\\d{1,3})":a==="A"||a==="a"?"([AaPp][Mm])":a==="Z"||a==="ZZ"?"(Z|[+-]\\d{2}:?\\d{2})":a==="X"||a==="x"?"(-?\\d+)":"(\\d{1,2})"}r+=`${s(n.slice(l))}\\s*$`;const f=new RegExp(r,"i").exec(t);if(!f)return null;let i=new Date().getFullYear(),c=0,m=1,g=0,E=0,y=0,w=0,C=null,Y=null;for(let D=0;D<e.length;D++){const a=e[D],T=f[D+1],p=Number(T);if(a==="X"||a==="x")return new Date(a==="X"?p*1e3:p);if(a==="YYYY")i=p;else if(a==="YY")i=p+(p<69?2e3:1900);else if(a==="MMMM"||a==="MMM"){const P=Mt.findIndex(et=>et.startsWith(T.toLowerCase().slice(0,3)));if(P<0)return null;c=P}else a==="MM"||a==="M"?c=p-1:a==="DD"||a==="D"||a==="Do"?m=p:a==="HH"||a==="H"||a==="hh"||a==="h"?g=p:a==="mm"||a==="m"?E=p:a==="ss"||a==="s"?y=p:a==="SSS"?w=Number(T.padEnd(3,"0")):a==="A"||a==="a"?C=T.toLowerCase()==="pm":(a==="Z"||a==="ZZ")&&(Y=T.toUpperCase()==="Z"?0:(T[0]==="-"?-1:1)*(Number(T.slice(1,3))*60+Number(T.slice(-2))))}if(C!=null&&(g=g%12+(C?12:0)),c<0||c>11||m<1||m>31||g>23||E>59||y>59)return null;const U=Y==null?new Date(i,c,m,g,E,y,w):new Date(Date.UTC(i,c,m,g,E,y,w)-Y*6e4);return Y==null&&U.getDate()!==m||Number.isNaN(U.getTime())?null:U}const F=new Map;function H(t,n=!1){const e=`${n?"g":""}|${t}`;let r=F.get(e);if(!r){const l=/^\(\?([ims]+)\)/.exec(t);r=new RegExp(l?t.slice(l[0].length):t,`${l?.[1]??""}${n?"g":""}`),F.size>200&&F.clear(),F.set(e,r)}return r.lastIndex=0,r}const Z="#ERROR",V=t=>`${t instanceof Date?"d":typeof t}:${o(t)}`;function pt(t,n,e){const r=n<0?t.length+n:Math.max(0,n-1),l=e==null?t.length:e<0?t.length+e+1:e;return t.slice(r,l)}function Q(t,n){const e=t<0?-1:1;let r=Math.ceil(Math.abs(t));return r%2===1!==n&&(r+=1),e*r}const J={IF:t=>A(t[0]??null)?t[1]??null:t[2]??null,AND:t=>d(t).every(A),OR:t=>d(t).some(A),NOT:t=>!A(t[0]??null),XOR:t=>d(t).filter(A).length%2===1,TRUE:()=>!0,FALSE:()=>!1,BLANK:()=>null,ERROR:()=>{throw new FormulaError("ERROR()")},ISERROR:t=>t[0]===Z,RECORD_ID:()=>null,SWITCH:t=>{for(let n=1;n+1<t.length;n+=2)if(o(t[0]??null)===o(t[n]??null))return t[n+1]??null;return t.length%2===0?t[t.length-1]??null:null},CONCATENATE:t=>t.map(o).join(""),LEN:t=>o(t[0]??null).length,UPPER:t=>o(t[0]??null).toUpperCase(),LOWER:t=>o(t[0]??null).toLowerCase(),TRIM:t=>o(t[0]??null).trim(),LEFT:t=>o(t[0]??null).slice(0,u(t[1]??1)),RIGHT:t=>{const n=o(t[0]??null),e=u(t[1]??1);return e<=0?"":n.slice(-e)},MID:t=>{const n=o(t[0]??null),e=Math.max(0,u(t[1]??1)-1);return t.length>2?n.slice(e,e+Math.max(0,u(t[2]??0))):n.slice(e)},FIND:t=>o(t[1]??null).indexOf(o(t[0]??null),Math.max(0,u(t[2]??1)-1))+1,SEARCH:t=>{const n=o(t[1]??null).indexOf(o(t[0]??null),Math.max(0,u(t[2]??1)-1));return n<0?null:n+1},SUBSTITUTE:t=>{const n=o(t[0]??null).split(o(t[1]??null));if(t.length<4)return n.join(o(t[2]??null));const e=u(t[3]??null);return n.reduce((r,l,s)=>s===0?l:r+o(s===e?t[2]??null:t[1]??null)+l,"")},REPLACE:t=>{const n=o(t[0]??null),e=Math.max(0,u(t[1]??1)-1);return n.slice(0,e)+o(t[3]??null)+n.slice(e+Math.max(0,u(t[2]??0)))},ENCODE_URL_COMPONENT:t=>encodeURIComponent(o(t[0]??null)),REGEX_MATCH:t=>H(o(t[1]??null)).test(o(t[0]??null)),REGEX_EXTRACT:t=>H(o(t[1]??null)).exec(o(t[0]??null))?.[0]??null,REGEX_REPLACE:t=>o(t[0]??null).replace(H(o(t[1]??null),!0),o(t[2]??null)),REPT:t=>o(t[0]??null).repeat(Math.max(0,Math.min(1e3,u(t[1]??0)))),T:t=>typeof t[0]=="string"?t[0]:"",VALUE:t=>{const n=o(t[0]??null).replace(/[^0-9.eE+-]/g,""),e=/\d/.test(n)?Number(n):NaN;return Number.isFinite(e)?e:null},ARRAYJOIN:t=>d([t[0]??null]).map(o).filter(Boolean).join(t.length>1?o(t[1]??null):", "),ARRAYCOMPACT:t=>d([t[0]??null]).filter(n=>n!=null&&n!==""),ARRAYFLATTEN:t=>t.flat(1/0),ARRAYUNIQUE:t=>{const n=new Set;return d([t[0]??null]).filter(e=>!n.has(V(e))&&!!n.add(V(e)))},ARRAYSLICE:t=>pt(d([t[0]??null]),u(t[1]??1),t.length>2?u(t[2]??null):void 0),SUM:t=>d(t).reduce((n,e)=>n+u(e),0),AVERAGE:t=>{const n=d(t).filter(e=>!S(e));return n.length?n.reduce((e,r)=>e+u(r),0)/n.length:null},MAX:t=>{const n=d(t).filter(e=>!S(e)).map(u);return n.length?nt(n):null},MIN:t=>{const n=d(t).filter(e=>!S(e)).map(u);return n.length?rt(n):null},COUNT:t=>d(t).filter(n=>typeof n=="number").length,COUNTA:t=>d(t).filter(n=>!S(n)).length,COUNTALL:t=>d(t).length,ROUND:t=>{const n=10**u(t[1]??0);return Math.round(u(t[0]??null)*n)/n},ROUNDUP:t=>{const n=10**u(t[1]??0),e=u(t[0]??null);return Math.sign(e)*Math.ceil(R(Math.abs(e)*n))/n},ROUNDDOWN:t=>{const n=10**u(t[1]??0),e=u(t[0]??null);return Math.sign(e)*Math.floor(R(Math.abs(e)*n))/n},INT:t=>Math.floor(u(t[0]??null)),ABS:t=>Math.abs(u(t[0]??null)),MOD:t=>u(t[0]??null)%u(t[1]??1),POWER:t=>u(t[0]??null)**u(t[1]??1),SQRT:t=>Math.sqrt(u(t[0]??null)),EXP:t=>Math.exp(u(t[0]??null)),LOG:t=>Math.log(u(t[0]??null))/Math.log(t.length>1?u(t[1]??null):10),EVEN:t=>Q(u(t[0]??null),!1),ODD:t=>Q(u(t[0]??null),!0),CEILING:t=>{const n=u(t[1]??1);return n===0?0:R(Math.ceil(R(u(t[0]??null)/n))*n)},FLOOR:t=>{const n=u(t[1]??1);return n===0?0:R(Math.floor(R(u(t[0]??null)/n))*n)},DISTANCE:t=>{const n=t.length>=4?k(`${o(t[0]??null)}, ${o(t[1]??null)}`):k(t[0]??null),e=t.length>=4?k(`${o(t[2]??null)}, ${o(t[3]??null)}`):k(t[1]??null);return n&&e?st(n,e):null},TODAY:()=>{const t=new Date;return t.setHours(0,0,0,0),t},NOW:()=>new Date,YEAR:t=>h(t[0]??null)?.getFullYear()??null,MONTH:t=>{const n=h(t[0]??null);return n?n.getMonth()+1:null},DAY:t=>h(t[0]??null)?.getDate()??null,HOUR:t=>h(t[0]??null)?.getHours()??null,MINUTE:t=>h(t[0]??null)?.getMinutes()??null,SECOND:t=>h(t[0]??null)?.getSeconds()??null,WEEKDAY:t=>{const n=h(t[0]??null);return n?/^mon/i.test(o(t[1]??null))?(n.getDay()+6)%7:n.getDay():null},WEEKNUM:t=>{const n=h(t[0]??null);if(!n)return null;const e=/^mon/i.test(o(t[1]??null))?1:0,r=new Date(n.getFullYear(),0,1),l=Math.round((I(new Date(n.getFullYear(),n.getMonth(),n.getDate()))-I(r))/864e5);return Math.floor((l+(r.getDay()-e+7)%7)/7)+1},DATEADD:t=>{const n=h(t[0]??null),e=t.length>2?L(t[2]??null):"d";return n&&e?ut(n,u(t[1]??0),e):null},DATETIME_DIFF:t=>{const n=h(t[0]??null),e=h(t[1]??null),r=t.length>2?L(t[2]??null):"s";return n&&e&&r?_(n,e,r):null},IS_BEFORE:t=>{const n=h(t[0]??null),e=h(t[1]??null);return!!n&&!!e&&n<e},IS_AFTER:t=>{const n=h(t[0]??null),e=h(t[1]??null);return!!n&&!!e&&n>e},IS_SAME:t=>{const n=h(t[0]??null),e=h(t[1]??null),r=t.length>2?L(t[2]??null):"ms";return!!n&&!!e&&!!r&&O(n,r)===O(e,r)},DATESTR:t=>{const n=h(t[0]??null);return n?N(n):null},TIMESTR:t=>{const n=h(t[0]??null);return n?`${M(n.getHours())}:${M(n.getMinutes())}:${M(n.getSeconds())}`:null},DATETIME_FORMAT:t=>{const n=h(t[0]??null);return n?dt(n,t.length>1&&!S(t[1]??null)?o(t[1]??null):"YYYY-MM-DDTHH:mm:ss.SSSZ"):null},DATETIME_PARSE:t=>t.length>1&&!S(t[1]??null)?Dt(o(t[0]??null),o(t[1]??null)):h(t[0]??null),SET_LOCALE:t=>{const n=h(t[0]??null),e=o(t[1]??null).trim();return!n||!e?n:j(n,{locale:Intl.DateTimeFormat.supportedLocalesOf(e)[0]??e})},SET_TIMEZONE:t=>{const n=h(t[0]??null),e=o(t[1]??null).trim();return!n||!e?n:(G(e),j(n,{zone:e}))},TONOW:t=>{const n=h(t[0]??null);return n?_(new Date(O(new Date,"d")),new Date(O(n,"d")),"d"):null},FROMNOW:t=>{const n=h(t[0]??null);return n?_(new Date(O(n,"d")),new Date(O(new Date,"d")),"d"):null},WORKDAY:t=>{const n=h(t[0]??null);if(!n)return null;const e=Math.trunc(u(t[1]??0)),r=e<0?-1:1,l=z(t[2]),s=new Date(n);for(let f=Math.abs(e),i=0;f>0;){if(++i>q)return null;s.setDate(s.getDate()+r),X(s,l)&&(f-=1)}return s},WORKDAY_DIFF:t=>{const n=h(t[0]??null),e=h(t[1]??null);if(!n||!e)return null;const r=z(t[2]),l=n>e?-1:1,s=new Date(l>0?n:e),f=N(l>0?e:n);let i=0;for(let c=0;N(s)<=f;c++){if(c>q)return null;X(s,r)&&(i+=1),s.setDate(s.getDate()+1)}return l*i}};function tt(t,n,e){switch(t){case"=":return n===e;case"!=":return n!==e;case"<":return n<e;case">":return n>e;case"<=":return n<=e;default:return n>=e}}const Tt=new Set(["DATEADD","DATETIME_DIFF","IS_SAME"]);export const FORMULA_FUNCTIONS=Object.keys(J).sort(),selfReferenceError=t=>new FormulaError(`A formula cannot read its own field {${t.trim()}}`);export function columnResolver(t,n=[]){const e=new Set(n.filter(r=>r!=null&&String(r).trim()!=="").map(r=>String(r).trim().toLowerCase()));return r=>{const l=r.trim().toLowerCase();if(e.has(l))throw selfReferenceError(r);const s=t.find(f=>String(f.header??"").trim().toLowerCase()===l||String(f.field??"").toLowerCase()===l);return s?String(s.field??s.id):null}}class St{constructor(n,e,r){this.toks=n,this.resolve=e,this.refs=r,this.i=0}peek(){return this.toks[this.i]}next(){return this.toks[this.i++]}expect(n,e){const r=this.next();if(!r||r.k!==n||e&&r.v!==e)throw new FormulaError(`Expected "${e??n}"${r?` at ${r.at+1}`:" at the end"}`);return r}parse(){const n=this.compare();if(this.peek())throw new FormulaError(`Unexpected "${this.peek().v}" at ${this.peek().at+1}`);return n}compare(){let n=this.concat();for(let e=this.peek();e&&e.k==="op"&&["=","!=","<",">","<=",">="].includes(e.v);e=this.peek()){this.next();const r=e.v,l=n,s=this.concat();n=f=>{const i=l(f),c=s(f);if(i instanceof Date||c instanceof Date){const y=h(i),w=h(c);return!y||!w?r==="!=":tt(r,y.getTime(),w.getTime())}const m=typeof i=="number"||typeof c=="number",g=m?u(i):o(i),E=m?u(c):o(c);return tt(r,g,E)}}return n}concat(){let n=this.add();for(;this.peek()?.k==="op"&&this.peek().v==="&";){this.next();const e=n,r=this.add();n=l=>o(e(l))+o(r(l))}return n}add(){let n=this.mul();for(let e=this.peek();e&&e.k==="op"&&(e.v==="+"||e.v==="-");e=this.peek()){this.next();const r=n,l=this.mul(),s=e.v==="+";n=f=>s?u(r(f))+u(l(f)):u(r(f))-u(l(f))}return n}mul(){let n=this.unary();for(let e=this.peek();e&&e.k==="op"&&(e.v==="*"||e.v==="/");e=this.peek()){this.next();const r=n,l=this.unary(),s=e.v==="*";n=f=>{if(s)return u(r(f))*u(l(f));const i=u(l(f));return i===0?null:u(r(f))/i}}return n}unary(){const n=this.peek();if(n?.k==="op"&&n.v==="-"){this.next();const e=this.unary();return r=>-u(e(r))}return this.primary()}primary(){const n=this.next();if(!n)throw new FormulaError("The formula ends too early");if(n.k==="num"){const e=Number(n.v);return()=>e}if(n.k==="str"){const e=n.v;return()=>e}if(n.k==="ref"){const e=this.resolve(n.v);if(e==null)throw new FormulaError(`No field named "${n.v}"`);return this.refs.add(e),r=>r?.[e]??null}if(n.k==="("){const e=this.compare();return this.expect(")"),e}if(n.k==="id"){const e=n.v.toUpperCase();if(e==="TRUE"&&this.peek()?.k!=="(")return()=>!0;if(e==="FALSE"&&this.peek()?.k!=="(")return()=>!1;const r=J[e];if(!r)throw new FormulaError(`Unknown function ${n.v}`);this.expect("(");const l=[],s=[],f=()=>{const c=this.i;l.push(this.compare());const m=this.i===c+1?this.toks[c]:void 0;s.push(m?.k==="str"?m.v:void 0)};if(this.peek()?.k!==")")for(f();this.peek()?.k===",";)this.next(),f();this.expect(")");const i=s[2];if(Tt.has(e)&&i!==void 0&&!L(i))throw new FormulaError(`Unknown unit "${i}" in ${e}: use ms, seconds, minutes, hours, days, weeks, months, quarters or years`);return e==="RECORD_ID"?c=>c?.id==null?null:String(c.id):e==="ISERROR"?c=>{try{const m=l[0]?.(c)??null;return m===Z||typeof m=="number"&&!Number.isFinite(m)}catch{return!0}}:e==="IF"?c=>A(l[0]?.(c)??null)?l[1]?.(c)??null:l[2]?.(c)??null:e==="SWITCH"?c=>{if(!l.length)return null;const m=o(l[0](c));for(let g=1;g+1<l.length;g+=2)if(m===o(l[g](c)))return l[g+1](c);return l.length%2===0?l[l.length-1](c):null}:c=>r(l.map(m=>m(c)))}throw new FormulaError(`Unexpected "${n.v}" at ${n.at+1}`)}}export function compileFormula(t,n){if(!t.trim())throw new FormulaError("The formula is empty");const e=new Set,r=new St(tokenize(t),n,e).parse();return{fn:l=>{try{const s=r(l);return typeof s=="number"&&!Number.isFinite(s)?null:s}catch(s){return s instanceof FormulaError?Z:null}},refs:[...e]}}export function renameFormulaRefs(t,n){let e;try{e=tokenize(t)}catch{return t}let r="",l=0;for(const s of e){if(s.k!=="ref")continue;const f=n(s.v);if(f==null)continue;const i=t.indexOf("}",s.at);r+=`${t.slice(l,s.at)}{${f}}`,l=i+1}return l?r+t.slice(l):t}export function formulaRefs(t,n){let e;try{e=tokenize(t)}catch{return[]}const r=new Set;for(const l of e)if(l.k==="ref")try{const s=n(l.v);s!=null&&r.add(s)}catch{}return[...r]}export function formulaReaders(t,n){const e=new Set([n.field,n.id].filter(l=>l!=null&&l!=="").map(String));if(!e.size)return[];const r=columnResolver(t);return t.filter(l=>l.fieldType!=="formula"||e.has(String(l.field??l.id??""))?!1:formulaRefs(String(l.fieldProps?.formula??""),r).some(s=>e.has(s)))}export function formulaError(t,n){try{return compileFormula(t,n),null}catch(e){return e instanceof FormulaError?e.message:"The formula is not valid"}}
|
package/dist/fields/index.d.ts
CHANGED
|
@@ -77,7 +77,7 @@ export { generateAIField, regenerateAIFields, cancelAIField, pendingAIField, set
|
|
|
77
77
|
export { aiPromptError, readAIAnswer, type AIFieldProps, type AIFieldOutput } from './ai-prompt.js';
|
|
78
78
|
export { moveTile, newTile, putTile, removeTile, tileResult, tileRows, tileTitle, type DashboardTile, type DashboardTileKind, type DashboardTileSize, type NumberAggregation, type TileResult, } from './dashboard.js';
|
|
79
79
|
export { sharedTables, sharedViews, shareOf, type BaseShare } from './base-share.js';
|
|
80
|
-
export { recordsAsShown, downloadAsShown, type BaseExportFormat } from './base-export.js';
|
|
80
|
+
export { recordsAsShown, downloadAsShown, filesFolders, safeFolder, type BaseExportFormat, type BaseFilesExport, type BaseFilesRecord } from './base-export.js';
|
|
81
81
|
export { permittedTables, permittedRecords, permittedViews, tablePermissions, gridPermissions, type BasePermissions, type TablePermissions } from './base-permissions.js';
|
|
82
82
|
export { computeRecords, computeRecord, computedValues, computedFields, evaluateFilter, filterRecords, type ComputeTable, type ComputeOptions, type FilterContext } from './base-compute.js';
|
|
83
83
|
export { queryRecords, fieldFilterToSql, fieldFilterToPostgrest, supabaseFieldFilter, viewFilterOf, type QueryOptions, type FieldFilterSqlOptions, type FieldFilterPostgrestOptions } from './base-query.js';
|
package/dist/fields/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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{setDictation,dictationSupported,dictate}from"./dictation.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 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";
|
|
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 h,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 Fe from"./RatingEditor.svelte";import he 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 F,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{setDictation,dictationSupported,dictate}from"./dictation.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 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=F(o)===r,l=e&&q(o)?[...h(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===F(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=h(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)=>F(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:Fe,props:o,typeToEdit:e=>/^[0-9]$/.test(e)}),f("fieldLink",{component:he,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,filesFolders,safeFolder}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";
|
|
@@ -265,6 +265,9 @@ export declare const SHELL_MESSAGES: {
|
|
|
265
265
|
readonly 'shell.excelNeedsZip': "This app cannot write Excel files yet: it needs the jszip package. Ask whoever runs it to install jszip.";
|
|
266
266
|
readonly 'shell.exportFailed': "Could not make the file. Try again.";
|
|
267
267
|
readonly 'shell.downloadSql': "Download as SQL";
|
|
268
|
+
readonly 'shell.downloadFiles': "Download the files (ZIP)";
|
|
269
|
+
readonly 'shell.downloadFilesTitle': "Every file this view shows, in a folder for each group, or for each record";
|
|
270
|
+
readonly 'shell.exportNoFiles': "This view shows no files.";
|
|
268
271
|
readonly 'shell.downloadSqlTitle': "The tables, links, records, views and automations, ready for Postgres or Supabase";
|
|
269
272
|
readonly 'shell.addTable': "Add table";
|
|
270
273
|
readonly 'shell.addTableWays': "More ways to add a table";
|