@svgrid/enterprise 3.1.46 → 3.1.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/SvGridBoard.svelte +14 -4
- package/dist/cdn/svgrid-enterprise.svelte-external.js +383 -380
- package/dist/designer/assets/{index-BBI_8Aky.js → index-niFUiHOa.js} +1 -1
- package/dist/designer/index.html +1 -1
- package/dist/fields/RecordView.svelte +13 -2
- package/dist/fields/SvBase.svelte +1 -1
- package/dist/fields/dictation.svelte.d.ts +18 -0
- package/dist/fields/dictation.svelte.js +1 -0
- 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 -0
- package/dist/fields/index.js +1 -1
- package/dist/fields/messages/record.d.ts +3 -0
- package/dist/fields/messages/record.js +1 -1
- package/dist/fields/messages.svelte.d.ts +3 -0
- package/dist/node/studio.js +1 -1
- package/dist/server/server-row-model.d.ts +10 -0
- package/dist/server/server-row-model.js +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/wc/board-C2hPY2IP.js +26 -0
- package/dist/wc/server-row-model-aLsfzGo3.js +1 -0
- package/dist/wc/sv-base-element.js +92 -88
- package/package.json +1 -1
- package/dist/wc/board-DS5OxhbF.js +0 -23
- package/dist/wc/server-row-model-C-FV79zV.js +0 -1
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Speaking instead of typing: the app's own speech recognition (a phone app's
|
|
3
|
+
* native one, or the browser's where it works), handed over with setDictation.
|
|
4
|
+
* The record view then draws a microphone beside each text field it may change
|
|
5
|
+
* and in the comment box; what is said is added to the field or the comment.
|
|
6
|
+
* Without one, no microphone is drawn: a browser that has the Web Speech API but
|
|
7
|
+
* never hears (an Android web view) is the app's to leave out.
|
|
8
|
+
*/
|
|
9
|
+
/** Listens once; answers what was said, '' for nothing (the app says why: no permission, no signal). */
|
|
10
|
+
export type DictationFn = () => Promise<string>;
|
|
11
|
+
/** The app's speech recognition, page-wide; null takes the microphones away. */
|
|
12
|
+
export declare function setDictation(listen: DictationFn | null): void;
|
|
13
|
+
/** Whether a microphone is drawn: the app gave its speech recognition. */
|
|
14
|
+
export declare function dictationSupported(): boolean;
|
|
15
|
+
/** Listens once with the app's speech recognition: what was said, trimmed, '' for nothing or a failure. */
|
|
16
|
+
export declare function dictate(): Promise<string>;
|
|
17
|
+
/** A field's value with what was said added: a new line in a long text, a space in a line of text. */
|
|
18
|
+
export declare function withSaid(value: unknown, said: string, multiline: boolean): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let ownDictation=$state(null);export function setDictation(listen){ownDictation=listen}export function dictationSupported(){return ownDictation!==null}export async function dictate(){const listen=ownDictation;if(!listen)return"";try{return String(await listen()??"").trim()}catch{return""}}export function withSaid(value,said,multiline){const had=value==null?"":String(value).replace(/\s+$/,"");if(!had)return said;return had+(multiline?"\n":" ")+said}
|
|
@@ -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
|
@@ -10,6 +10,7 @@ export { BRIGHT, OPTION_COLORS } from './palette.js';
|
|
|
10
10
|
export { convertValue, countCleared } from './convert.js';
|
|
11
11
|
export { openFieldEditor, closeFieldEditor, openRecord, closeRecord, type OpenRecordRequest } from './editor-request.svelte.js';
|
|
12
12
|
export { setBarcodeScanner, barcodeScanSupported, scanBarcode, type BarcodeScannerFn } from './barcode-scan.js';
|
|
13
|
+
export { setDictation, dictationSupported, dictate, type DictationFn } from './dictation.svelte.js';
|
|
13
14
|
export { default as SvBaseViewBar } from './SvBaseViewBar.svelte';
|
|
14
15
|
export { default as SvBaseForm } from './SvBaseForm.svelte';
|
|
15
16
|
export { default as SvBaseAutomations } from './SvBaseAutomations.svelte';
|
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{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 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";
|
|
@@ -143,6 +143,9 @@ export declare const RECORD_MESSAGES: {
|
|
|
143
143
|
readonly 'record.addFiles': "Add files";
|
|
144
144
|
readonly 'record.takePhoto': "Take a photo";
|
|
145
145
|
readonly 'record.scanCode': "Scan a code";
|
|
146
|
+
readonly 'record.dictateField': "Speak into {field}";
|
|
147
|
+
readonly 'record.dictateComment': "Speak a comment";
|
|
148
|
+
readonly 'record.listening': "Listening...";
|
|
146
149
|
readonly 'record.scanHint': "Point the camera at a barcode or a QR code.";
|
|
147
150
|
readonly 'record.scanUnsupported': "This browser cannot read codes from the camera.";
|
|
148
151
|
readonly 'record.scanNoCamera': "The camera is not available: allow it for this site, or close another app using it.";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const RECORD_MESSAGES={"record.untitled":"Untitled","record.record":"Record","record.protected":"protected","record.readOnly":"read-only","record.hiddenInGrid":"hidden in the grid","record.notInGridView":"This row is not in the grid's view any more.","record.showHiddenFields.one":"Show {count} hidden field","record.showHiddenFields.other":"Show {count} hidden fields","record.hideHiddenFields.one":"Hide {count} hidden field","record.hideHiddenFields.other":"Hide {count} hidden fields","record.activity":"Activity","record.someone":"Someone","record.someoneElse":"Someone else","record.you":"You","record.byAutomation":"Automation: {name}","record.acceptedBy":"{source} (accepted by {person})","record.through":"{person} via {source}","record.changedField":"changed {field}","record.undidField":"undid a change to {field}","record.redidField":"redid a change to {field}","record.addedRecord":"added this record","record.changedTo":"to","record.cleared":"(cleared)","record.noActivity":"No changes or comments yet.","record.loadingHistory":"Loading the history...","record.historyError":"The history could not be read: {error}","record.comment":"Comment","record.attachFiles":"Attach files","record.commentFiles":"Files","record.commentUploadFailed":"{name} was not uploaded: {error}","record.internalNote":"Internal note","record.internalNoteHint":"Only your team sees it, never a client.","record.internalTag":"Internal","record.savedReplies":"Saved replies","record.formSuggestTitle":"These may already answer it","record.formSolved":"This solved it","record.formSolvedTitle":"Glad it helped","record.formSolvedNote":"Nothing was sent.","record.formAskAnother":"Ask something else","record.searchReplies":"Search the saved replies","record.noReplies":"No saved replies yet.","record.noRepliesFound":"No saved reply matches.","record.loadingReplies":"Loading the saved replies...","record.repliesFailed":"The saved replies could not be read: {error}","record.saveAsReply":"Save this text as a reply","record.replyName":"Name of the reply","record.replySaved":"Saved as a reply.","record.replyNotSaved":"The reply was not saved: {error}","record.editComment":"Edit","record.deleteComment":"Delete","record.deleteCommentAsk":"Delete this comment?","record.commentNotSent":"This comment is not sent. Send it, or clear the box, and Esc closes the record.","record.commentNotSaved":"This change is not saved. Save or cancel it, and Esc closes the record.","record.commentHoldsStep":"This change is not saved. Save or cancel it, then move to another record.","record.fileRemoved":"{file} removed.","record.commentAddedSay":"Comment added.","record.commentKept":"Your comment was not sent. It is still in this record, ready to send.","record.commentSavedSay":"Comment saved.","record.commentDeletedSay":"Comment deleted.","record.commentEdited":"(edited)","record.saveComment":"Save","record.cancelComment":"Cancel","record.previousRecord":"Previous record","record.nextRecord":"Next record","record.position":"{index} of {total}","record.newRecord":"New record","record.linkedOf":"{table} of {owner} ({count})","record.filteredOut":"This record is filtered out of this view.","record.notInView.one":"Not in view ({count} record)","record.notInView.other":"Not in view ({count} records)","record.close":"Close","record.justNow":"just now","record.minutesAgo.one":"{count} minute ago","record.minutesAgo.other":"{count} minutes ago","record.hoursAgo.one":"{count} hour ago","record.hoursAgo.other":"{count} hours ago","record.leaveComment":"Leave a comment","record.commentPlaceholder":"Leave a comment, @ to mention","record.peopleToMention":"People to mention","record.empty":"Empty","record.emptyValue":"empty","record.fieldValue":"{label}: {value}","record.fieldValueEdit":"{label}: {value}, edit","record.formProblems.one":"{count} field needs attention","record.formProblems.other":"{count} fields need attention","record.formTitle":"New record","record.formSubmit":"Submit","record.formChoose":"Choose","record.formPickDate":"Pick a date","record.formAddFiles":"Add files","record.formLinkRecords":"Link records","record.formTypeHere":"Type here","record.formRequired":"required","record.formInvalidEmail":"Not a valid email address","record.formInvalidUrl":"Not a valid web address","record.formInvalidPhone":"Not a valid phone number","record.formFieldRequired":"{field} is required","record.formFieldInvalid":"{field} is not valid","record.formSendFailed":"The record could not be sent. Try again.","record.formEmpty":"Fill in at least one field before you send this.","record.formThanks":"Thank you","record.formAdded":"The record was added.","record.formSubmitAnother":"Submit another","record.formNext":"Next","record.formBack":"Back","record.formStepOf":"Question {n} of {count}","record.formPressEnter":"or press Enter","record.unnamed":"Untitled","record.linkedGone":"This record is not in its table any more.","record.openIn":"Open in {table}","record.linkTo":"Link to {table}","record.linkToRecords":"Link to records","record.linkTableMissing":"The table this field links to is not available.","record.searchTable":"Search {table}","record.pickingFromView":'Records of the view "{view}"',"record.noRecordsMatch":"No records match.","record.createRecord":"Create “{name}”","record.showingOf":"Showing {shown} of {total}. Type to narrow.","record.linkedCount":"{count} linked","record.cancel":"Cancel","record.done":"Done","record.attachments":"Attachments","record.fileBadge":"FILE","record.uploadFailed":"Upload failed","record.uploadsFailed.one":"Upload failed","record.uploadsFailed.other":"{count} uploads failed","record.noUrlFound":"No http(s) URL found","record.noFilesYet":"No files yet. Drop files here, paste them, or use Add files.","record.files":"Files","record.fileTile":"{file}. Enter to preview, Delete to remove, Alt+Arrow to move.","record.removeFile":"Remove {name}","record.uploadingFile":"Uploading {name}","record.cancelUpload":"Cancel {name}","record.retry":"Retry","record.remove":"Remove","record.addFiles":"Add files","record.takePhoto":"Take a photo","record.scanCode":"Scan a code","record.scanHint":"Point the camera at a barcode or a QR code.","record.scanUnsupported":"This browser cannot read codes from the camera.","record.scanNoCamera":"The camera is not available: allow it for this site, or close another app using it.","record.pasteUrl":"or paste a URL","record.addByUrl":"Add a file by URL","record.uploadingCount":"Uploading {count}...","record.download":"Download","record.previous":"Previous","record.next":"Next","record.previousFile":"Previous file","record.nextFile":"Next file","record.filePosition":"{index} of {total}","record.noAttachments":"No attachments","record.attachmentList.one":"{count} attachment: {names}","record.attachmentList.other":"{count} attachments: {names}","record.notAdded":"Not added","record.uploading":"Uploading","record.keyMove":"move","record.keySave":"save","record.keyCancel":"cancel","record.checklist":"Checklist","record.checklistDone":"{done} of {total} done","record.noItemsYet":"No items yet","record.noItems":"No items","record.items":"Items","record.item":"item","record.itemNumber":"Item {n}","record.itemDone":"Done: {item}","record.moveItem":"Move {item}","record.deleteItem":"Delete {item}","record.addItem":"Add an item","record.color":"Color","record.hexCode":"Hex code","record.clear":"Clear","record.notAColor":"Not a color: use #rrggbb, #rgb, rgb() or a color name","record.colors":"Colors","record.notATime":"Not a time (9:30 am, 14:05, 2pm)","record.notADate":"Not a date (12/24/2026, 2026-12-24, Dec 24, 2026)","record.dateLabel":"Date","record.dateAndTimeLabel":"Date and time","record.calendarTab":"Date","record.timeTab":"Time","record.openCalendar":"Open the calendar","record.timeOfDay":"Time of day","record.longText":"Long text","record.markupHint":"**bold** *italic* `code` [link](https://...) - list","record.richText":"Rich text","record.removeValue":"Remove {name}","record.findPerson":"Find a person","record.findOption":"Find an option","record.addPerson":"Add a person","record.choosePerson":"Choose a person","record.addOption":"Add an option","record.chooseOption":"Choose an option","record.addNewOption":"Add option","record.everyoneChosen":"Everyone is chosen","record.nobodyMatches":"Nobody matches","record.noPeople":"No people (setFieldUsers)","record.everyOptionChosen":"Every option is chosen","record.noOptionMatches":"No option matches","record.noOptions":"No options","record.notADuration":"Not a duration (1:30, 1h 30m)","record.notANumber":"Not a number","record.formulaInNumber":"This field holds numbers. Press Enter to see how a formula field works this out.","record.noNegative":"Negative numbers are not allowed","record.durationLabel":"Duration ({format})","record.amountIn":"Amount in {symbol}","record.money":"money","record.percent":"Percent","record.number":"Number","record.increaseBy":"Increase by {step}","record.decreaseBy":"Decrease by {step}","record.ratingLabel":"Rating, {value} of {max}","record.aiNeedsPrompt":"Write a prompt for this field first (Edit field).","record.aiGenerating":"Generating...","record.aiWaiting":"Waiting...","record.aiGenerate":"Generate","record.aiGenerateAgain":"Generate again","record.aiNoProvider":"No AI provider","record.aiNoPrompt":"No prompt","record.voted":"{names} voted","record.noVotes":"No votes yet","record.votes.one":"{count} vote","record.votes.other":"{count} votes","record.timerStart":"Start the timer","record.timerStop":"Stop the timer","record.votesMine.one":"{count} vote, including yours","record.votesMine.other":"{count} votes, including yours","record.buttonOpen":"Open","record.nobody":"Nobody"};
|
|
1
|
+
export const RECORD_MESSAGES={"record.untitled":"Untitled","record.record":"Record","record.protected":"protected","record.readOnly":"read-only","record.hiddenInGrid":"hidden in the grid","record.notInGridView":"This row is not in the grid's view any more.","record.showHiddenFields.one":"Show {count} hidden field","record.showHiddenFields.other":"Show {count} hidden fields","record.hideHiddenFields.one":"Hide {count} hidden field","record.hideHiddenFields.other":"Hide {count} hidden fields","record.activity":"Activity","record.someone":"Someone","record.someoneElse":"Someone else","record.you":"You","record.byAutomation":"Automation: {name}","record.acceptedBy":"{source} (accepted by {person})","record.through":"{person} via {source}","record.changedField":"changed {field}","record.undidField":"undid a change to {field}","record.redidField":"redid a change to {field}","record.addedRecord":"added this record","record.changedTo":"to","record.cleared":"(cleared)","record.noActivity":"No changes or comments yet.","record.loadingHistory":"Loading the history...","record.historyError":"The history could not be read: {error}","record.comment":"Comment","record.attachFiles":"Attach files","record.commentFiles":"Files","record.commentUploadFailed":"{name} was not uploaded: {error}","record.internalNote":"Internal note","record.internalNoteHint":"Only your team sees it, never a client.","record.internalTag":"Internal","record.savedReplies":"Saved replies","record.formSuggestTitle":"These may already answer it","record.formSolved":"This solved it","record.formSolvedTitle":"Glad it helped","record.formSolvedNote":"Nothing was sent.","record.formAskAnother":"Ask something else","record.searchReplies":"Search the saved replies","record.noReplies":"No saved replies yet.","record.noRepliesFound":"No saved reply matches.","record.loadingReplies":"Loading the saved replies...","record.repliesFailed":"The saved replies could not be read: {error}","record.saveAsReply":"Save this text as a reply","record.replyName":"Name of the reply","record.replySaved":"Saved as a reply.","record.replyNotSaved":"The reply was not saved: {error}","record.editComment":"Edit","record.deleteComment":"Delete","record.deleteCommentAsk":"Delete this comment?","record.commentNotSent":"This comment is not sent. Send it, or clear the box, and Esc closes the record.","record.commentNotSaved":"This change is not saved. Save or cancel it, and Esc closes the record.","record.commentHoldsStep":"This change is not saved. Save or cancel it, then move to another record.","record.fileRemoved":"{file} removed.","record.commentAddedSay":"Comment added.","record.commentKept":"Your comment was not sent. It is still in this record, ready to send.","record.commentSavedSay":"Comment saved.","record.commentDeletedSay":"Comment deleted.","record.commentEdited":"(edited)","record.saveComment":"Save","record.cancelComment":"Cancel","record.previousRecord":"Previous record","record.nextRecord":"Next record","record.position":"{index} of {total}","record.newRecord":"New record","record.linkedOf":"{table} of {owner} ({count})","record.filteredOut":"This record is filtered out of this view.","record.notInView.one":"Not in view ({count} record)","record.notInView.other":"Not in view ({count} records)","record.close":"Close","record.justNow":"just now","record.minutesAgo.one":"{count} minute ago","record.minutesAgo.other":"{count} minutes ago","record.hoursAgo.one":"{count} hour ago","record.hoursAgo.other":"{count} hours ago","record.leaveComment":"Leave a comment","record.commentPlaceholder":"Leave a comment, @ to mention","record.peopleToMention":"People to mention","record.empty":"Empty","record.emptyValue":"empty","record.fieldValue":"{label}: {value}","record.fieldValueEdit":"{label}: {value}, edit","record.formProblems.one":"{count} field needs attention","record.formProblems.other":"{count} fields need attention","record.formTitle":"New record","record.formSubmit":"Submit","record.formChoose":"Choose","record.formPickDate":"Pick a date","record.formAddFiles":"Add files","record.formLinkRecords":"Link records","record.formTypeHere":"Type here","record.formRequired":"required","record.formInvalidEmail":"Not a valid email address","record.formInvalidUrl":"Not a valid web address","record.formInvalidPhone":"Not a valid phone number","record.formFieldRequired":"{field} is required","record.formFieldInvalid":"{field} is not valid","record.formSendFailed":"The record could not be sent. Try again.","record.formEmpty":"Fill in at least one field before you send this.","record.formThanks":"Thank you","record.formAdded":"The record was added.","record.formSubmitAnother":"Submit another","record.formNext":"Next","record.formBack":"Back","record.formStepOf":"Question {n} of {count}","record.formPressEnter":"or press Enter","record.unnamed":"Untitled","record.linkedGone":"This record is not in its table any more.","record.openIn":"Open in {table}","record.linkTo":"Link to {table}","record.linkToRecords":"Link to records","record.linkTableMissing":"The table this field links to is not available.","record.searchTable":"Search {table}","record.pickingFromView":'Records of the view "{view}"',"record.noRecordsMatch":"No records match.","record.createRecord":"Create “{name}”","record.showingOf":"Showing {shown} of {total}. Type to narrow.","record.linkedCount":"{count} linked","record.cancel":"Cancel","record.done":"Done","record.attachments":"Attachments","record.fileBadge":"FILE","record.uploadFailed":"Upload failed","record.uploadsFailed.one":"Upload failed","record.uploadsFailed.other":"{count} uploads failed","record.noUrlFound":"No http(s) URL found","record.noFilesYet":"No files yet. Drop files here, paste them, or use Add files.","record.files":"Files","record.fileTile":"{file}. Enter to preview, Delete to remove, Alt+Arrow to move.","record.removeFile":"Remove {name}","record.uploadingFile":"Uploading {name}","record.cancelUpload":"Cancel {name}","record.retry":"Retry","record.remove":"Remove","record.addFiles":"Add files","record.takePhoto":"Take a photo","record.scanCode":"Scan a code","record.dictateField":"Speak into {field}","record.dictateComment":"Speak a comment","record.listening":"Listening...","record.scanHint":"Point the camera at a barcode or a QR code.","record.scanUnsupported":"This browser cannot read codes from the camera.","record.scanNoCamera":"The camera is not available: allow it for this site, or close another app using it.","record.pasteUrl":"or paste a URL","record.addByUrl":"Add a file by URL","record.uploadingCount":"Uploading {count}...","record.download":"Download","record.previous":"Previous","record.next":"Next","record.previousFile":"Previous file","record.nextFile":"Next file","record.filePosition":"{index} of {total}","record.noAttachments":"No attachments","record.attachmentList.one":"{count} attachment: {names}","record.attachmentList.other":"{count} attachments: {names}","record.notAdded":"Not added","record.uploading":"Uploading","record.keyMove":"move","record.keySave":"save","record.keyCancel":"cancel","record.checklist":"Checklist","record.checklistDone":"{done} of {total} done","record.noItemsYet":"No items yet","record.noItems":"No items","record.items":"Items","record.item":"item","record.itemNumber":"Item {n}","record.itemDone":"Done: {item}","record.moveItem":"Move {item}","record.deleteItem":"Delete {item}","record.addItem":"Add an item","record.color":"Color","record.hexCode":"Hex code","record.clear":"Clear","record.notAColor":"Not a color: use #rrggbb, #rgb, rgb() or a color name","record.colors":"Colors","record.notATime":"Not a time (9:30 am, 14:05, 2pm)","record.notADate":"Not a date (12/24/2026, 2026-12-24, Dec 24, 2026)","record.dateLabel":"Date","record.dateAndTimeLabel":"Date and time","record.calendarTab":"Date","record.timeTab":"Time","record.openCalendar":"Open the calendar","record.timeOfDay":"Time of day","record.longText":"Long text","record.markupHint":"**bold** *italic* `code` [link](https://...) - list","record.richText":"Rich text","record.removeValue":"Remove {name}","record.findPerson":"Find a person","record.findOption":"Find an option","record.addPerson":"Add a person","record.choosePerson":"Choose a person","record.addOption":"Add an option","record.chooseOption":"Choose an option","record.addNewOption":"Add option","record.everyoneChosen":"Everyone is chosen","record.nobodyMatches":"Nobody matches","record.noPeople":"No people (setFieldUsers)","record.everyOptionChosen":"Every option is chosen","record.noOptionMatches":"No option matches","record.noOptions":"No options","record.notADuration":"Not a duration (1:30, 1h 30m)","record.notANumber":"Not a number","record.formulaInNumber":"This field holds numbers. Press Enter to see how a formula field works this out.","record.noNegative":"Negative numbers are not allowed","record.durationLabel":"Duration ({format})","record.amountIn":"Amount in {symbol}","record.money":"money","record.percent":"Percent","record.number":"Number","record.increaseBy":"Increase by {step}","record.decreaseBy":"Decrease by {step}","record.ratingLabel":"Rating, {value} of {max}","record.aiNeedsPrompt":"Write a prompt for this field first (Edit field).","record.aiGenerating":"Generating...","record.aiWaiting":"Waiting...","record.aiGenerate":"Generate","record.aiGenerateAgain":"Generate again","record.aiNoProvider":"No AI provider","record.aiNoPrompt":"No prompt","record.voted":"{names} voted","record.noVotes":"No votes yet","record.votes.one":"{count} vote","record.votes.other":"{count} votes","record.timerStart":"Start the timer","record.timerStop":"Stop the timer","record.votesMine.one":"{count} vote, including yours","record.votesMine.other":"{count} votes, including yours","record.buttonOpen":"Open","record.nobody":"Nobody"};
|
|
@@ -870,6 +870,9 @@ export declare const BASE_MESSAGES: {
|
|
|
870
870
|
readonly 'record.addFiles': "Add files";
|
|
871
871
|
readonly 'record.takePhoto': "Take a photo";
|
|
872
872
|
readonly 'record.scanCode': "Scan a code";
|
|
873
|
+
readonly 'record.dictateField': "Speak into {field}";
|
|
874
|
+
readonly 'record.dictateComment': "Speak a comment";
|
|
875
|
+
readonly 'record.listening': "Listening...";
|
|
873
876
|
readonly 'record.scanHint': "Point the camera at a barcode or a QR code.";
|
|
874
877
|
readonly 'record.scanUnsupported': "This browser cannot read codes from the camera.";
|
|
875
878
|
readonly 'record.scanNoCamera': "The camera is not available: allow it for this site, or close another app using it.";
|
package/dist/node/studio.js
CHANGED
|
@@ -913,7 +913,7 @@ ${E}
|
|
|
913
913
|
@keyframes st-home-spin { to { transform: rotate(360deg); } }
|
|
914
914
|
</style>
|
|
915
915
|
`}}function Ka(e){for(const r of e)je(r);const t=new Map(e.map(r=>[r.name,r])),a=e.map(r=>{const o=Eu(r,t);return{schema:Fu(r,o),infos:o}});return{entries:a,seed:Du(a)}}function fo(e,t={}){const{entries:a,seed:r}=Ka(e),{file:o,needs:n}=em(a,r,t.sources,t.supabaseConn,t.serverMemory),i=[Lu(a),o];(n.supabase||t.supabaseAuth)&&!n.supabaseUrl&&(t.supabaseConn?.url||t.supabaseConn?.key)&&(n.supabaseUrl=t.supabaseConn.url,n.supabaseKey=t.supabaseConn.key),(n.supabase||t.supabaseAuth)&&i.push(tm(n));for(const s of n.sqlRoutes)i.push(Hu(s.schema,s.table,s.dialect,{access:t.accessEnabled,audit:t.auditEnabled,screenIds:t.screensByEntity?.get(s.schema.name)??[],triggers:t.triggers?.[s.schema.name],dbSchema:s.dbSchema,tenantField:t.tenantField&&t.tenantScoped?.(s.schema.name)!==!1?t.tenantField:void 0}));if(n.memoryRoutes.length){i.push(Gu(n.memoryRoutes));for(const s of n.memoryRoutes)i.push(Vu(s.schema,{access:t.accessEnabled,audit:t.auditEnabled,screenIds:t.screensByEntity?.get(s.schema.name)??[],triggers:t.triggers?.[s.schema.name],tenantField:t.tenantField&&t.tenantScoped?.(s.schema.name)!==!1?t.tenantField:void 0}))}return{files:i,prepared:a.map(s=>s.schema)}}function am(e){if(e.length===0)throw new Error("emitStudioApp: no schemas to emit");const{files:t,prepared:a}=fo(e),r=a.map(n=>{const i=z(n);return{href:`/${i.route}`,label:i.label}}),o={path:"src/custom.css",description:"Your custom styles (imported after app.css so it overrides).",userOwned:!0,contents:`/* Your custom styles. Imported after app.css, so these rules override the defaults. */
|
|
916
|
-
`};return[...t,...a.map(n=>Ni(n)),Mi(r),ji(r),o]}function rm(e){return e.fields.some(t=>!!t.when&&(!!t.when.visible||!!t.when.disabled||!!t.when.required))}var om="3.1.
|
|
916
|
+
`};return[...t,...a.map(n=>Ni(n)),Mi(r),ji(r),o]}function rm(e){return e.fields.some(t=>!!t.when&&(!!t.when.visible||!!t.when.disabled||!!t.when.required))}var om="3.1.48",nm="3.0.37",V=(e,t)=>e.some(a=>a.config.kind===t),qi=e=>`activeTab_${e.replace(/[^a-zA-Z0-9_$]/g,"_")}`,aa=(e,t)=>`${e}-${t}`,zi=e=>`accOpen_${e.replace(/[^a-zA-Z0-9_$]/g,"_")}`,ra=(e,t)=>`${e}-s${t}`,oa=e=>`md_${e.replace(/[^a-zA-Z0-9]/g,"_")}_rows`;function im(e){switch(e.type){case"number":{const t=e.decimals;return t!=null?`{ type: 'number', options: { minimumFractionDigits: ${t}, maximumFractionDigits: ${t} } }`:"{ type: 'number' }"}case"currency":return`{ type: 'currency', currency: ${S(e.currency||"USD")} }`;case"percent":{const t=["type: 'percent'"];return e.valueIsPercentPoints&&t.push("valueIsPercentPoints: true"),e.decimals!=null&&t.push(`options: { minimumFractionDigits: ${e.decimals}, maximumFractionDigits: ${e.decimals} }`),`{ ${t.join(", ")} }`}case"date":case"datetime":return e.pattern?`{ type: '${e.type}', pattern: ${S(e.pattern)} }`:`{ type: '${e.type}' }`}}function sm(e,t,a,r){if(t.config.kind!=="grid")return`schemaToColumns(${e})`;const o=t.config,n=t.id.replace(/-/g,"_"),i=o.columns.filter(b=>b.show),s=new Set(i.map(b=>b.field)),d=new Set,l=i.map(b=>{const y=r?.get(b.field);return{c:b,col:y&&!s.has(y)?y:b.field}}).filter(b=>!d.has(b.col)&&!!d.add(b.col)),c=o.editing==="inline"?"":", editable: false";if(l.length===0)return c?`schemaToColumns(${e}).map((c) => ({ ...c${c} }))`:`schemaToColumns(${e})`;const p=l.map(b=>`'${b.col}'`),u=l.map(({c:b,col:y})=>{const w=[];return b.header&&w.push(`header: ${JSON.stringify(b.header)}`),b.width!=null&&w.push(`width: ${b.width}`),b.align&&w.push(`align: '${b.align}'`),b.aggregate&&w.push(`aggregate: '${b.aggregate}'`),o.treeData&&b.field===o.treeData.labelField&&a?w.push(`cell: (ctx: CellContext<${a}>) => renderSnippet(treeCell_${n}, { value: ctx.getValue(), row: ctx.row.original })`):b.cellType&&a?w.push(`cell: (ctx: CellContext<${a}>) => renderSnippet(${Gi(n,b.field)}, { value: ctx.getValue() })`):b.format&&w.push(`format: ${im(b.format)}`),w.length?`'${y}': { ${w.join(", ")} }`:null}).filter(b=>!!b),m=u.length?` const ov: Record<string, Partial<(typeof all)[number]>> = { ${u.join(", ")} };`:"",g=u.length?", ...(ov[String(c.field)] ?? {})":"",h=`[${p.join(", ")}].map((f) => all.find((c) => c.field === f)).filter((c): c is (typeof all)[number] => !!c)`;return`(() => { const all = schemaToColumns(${e});${m} return ${c||g?`${h}.map((c) => ({ ...c${c}${g} }))`:h} })()`}function Ae(e,t){const a=[`grid-column: span ${ei(e)}`,"min-width: 0"];t&&a.push(t);const r=ti(e.style);return r&&a.push(r),`style="${a.join("; ")}"`}var lm=e=>e&&e.replace(/[^#a-zA-Z0-9(),.%\s_-]/g,"").slice(0,40)||"var(--sg-accent)";function Ue(e,t){const a=[t,Xn(e)].filter(Boolean).join(" ");return a?` class="${a}"`:""}function Ha(e){const t=Ta(e.className);return t?` ${t}`:""}function dm(e){const t=Fe(e);if(t==="grid"){const a=ui(e),r=a.maxWidth?` max-width: ${a.maxWidth}px; margin-inline: auto;`:"";return` .st-screen { grid-template-columns: repeat(12, 1fr); gap: ${a.rowGap}px ${a.colGap}px; align-items: ${a.align};${r} }
|
|
917
917
|
@media (max-width: ${a.mobileBreakpoint}px) { .st-screen { grid-template-columns: 1fr; gap: 12px; } }
|
|
918
918
|
`}if(t==="stack"){const a=mi(e),r=a.maxWidth?` max-width: ${a.maxWidth}px;${a.align==="center"?" margin-inline: auto;":""}`:"",o=a.minHeight?`
|
|
919
919
|
.st-stack > * { min-height: ${a.minHeight}px; }`:"",n=a.dividers?`
|
|
@@ -505,6 +505,16 @@ export type ServerRowModel<TData> = GridRowModel<ServerRowModelGridRow<TData>> &
|
|
|
505
505
|
updateRowData(id: string, patch: Partial<TData>, options?: {
|
|
506
506
|
replace?: boolean;
|
|
507
507
|
}): boolean;
|
|
508
|
+
/**
|
|
509
|
+
* `updateRowData` for many rows at once: one pass over the loaded blocks
|
|
510
|
+
* finds them all, and the grid is told once. A job that wrote thousands of
|
|
511
|
+
* records shows them without a search of the cache per record. Patches for
|
|
512
|
+
* the same id merge in order. Returns how many of the ids were found.
|
|
513
|
+
*/
|
|
514
|
+
updateRowsData(changes: ReadonlyArray<{
|
|
515
|
+
id: string;
|
|
516
|
+
patch: Partial<TData>;
|
|
517
|
+
}>): number;
|
|
508
518
|
/**
|
|
509
519
|
* Show a row above the list though no block holds it: a record being
|
|
510
520
|
* filled in, or one opened from a search. It outlives a refresh, is not in
|