@svgrid/enterprise 3.1.57 → 3.1.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/SvGridBoard.svelte +1 -1
  2. package/dist/SvGridScheduler.svelte +1 -1
  3. package/dist/SvRecordDetail.svelte +1 -1
  4. package/dist/SvSchedule.svelte +1 -1
  5. package/dist/cdn/svgrid-enterprise.svelte-external.js +295 -295
  6. package/dist/date-locale.d.ts +8 -0
  7. package/dist/date-locale.js +1 -0
  8. package/dist/designer/assets/{index-DfYT4Bxh.js → index-DoEhPIfX.js} +310 -310
  9. package/dist/designer/index.html +1 -1
  10. package/dist/fields/BaseInboxView.svelte +1 -1
  11. package/dist/fields/BaseTableView.svelte +1 -1
  12. package/dist/fields/ButtonCell.svelte +6 -5
  13. package/dist/fields/ButtonCell.svelte.d.ts +6 -5
  14. package/dist/fields/PropertyInput.svelte +25 -2
  15. package/dist/fields/SvBase.svelte +1 -1
  16. package/dist/fields/automations.svelte.d.ts +6 -0
  17. package/dist/fields/automations.svelte.js +1 -1
  18. package/dist/fields/builtin-types.js +1 -1
  19. package/dist/fields/button-host.d.ts +61 -0
  20. package/dist/fields/button-host.js +1 -0
  21. package/dist/fields/button.d.ts +36 -1
  22. package/dist/fields/button.js +1 -1
  23. package/dist/fields/index.d.ts +1 -0
  24. package/dist/fields/index.js +1 -1
  25. package/dist/fields/messages/fields.d.ts +41 -2
  26. package/dist/fields/messages/fields.js +1 -1
  27. package/dist/fields/messages.svelte.d.ts +45 -3
  28. package/dist/fields/messages.svelte.js +1 -1
  29. package/dist/fields/registry.svelte.d.ts +11 -0
  30. package/dist/gantt/SvGridGantt.svelte +1 -1
  31. package/dist/gantt/gantt-model.js +1 -1
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.js +1 -1
  34. package/dist/node/studio.js +1 -1
  35. package/dist/version.d.ts +1 -1
  36. package/dist/version.js +1 -1
  37. package/dist/wc/board-CEIIZoaC.js +26 -0
  38. package/dist/wc/{palette-DkaM8TCP.js → date-locale-CKE0m3Dc.js} +9 -9
  39. package/dist/wc/gantt-_heLybcH.js +115 -0
  40. package/dist/wc/scheduler-CGoM4ahy.js +160 -0
  41. package/dist/wc/sv-base-element.js +197 -195
  42. package/package.json +1 -1
  43. package/dist/wc/board-C2hPY2IP.js +0 -26
  44. package/dist/wc/gantt-DBRJiYsr.js +0 -115
  45. package/dist/wc/scheduler-DJZRC1fj.js +0 -160
@@ -265,6 +265,12 @@ export type AutomationRunnerOptions = {
265
265
  /** "Ask AI": a prompt in, the model's answer out. Without it the step fails and says so. */
266
266
  ai?: (prompt: string) => Promise<string>;
267
267
  };
268
+ /**
269
+ * Who pressed a button, for the steps of the automation it starts:
270
+ * `{pressed.name}`, `{pressed.email}`, `{pressed.id}` (Airtable's "User who took
271
+ * action"). In the browser it is the person on the page.
272
+ */
273
+ export declare function pressedValues(): RunValues;
268
274
  /** The most records "Find records" runs its steps for. */
269
275
  export declare const REPEAT_MOST = 1000;
270
276
  /** A record as a script sees it: each field's value and text, by field name. */
@@ -1 +1 @@
1
- import{toast}from"@svgrid/grid";import{createScheduler}from"../scheduling.js";import{colId,primaryOf,rowIdOf,syncAllInverses}from"./base-tables.js";import{compileFieldFilter,describeFieldFilter}from"./filter-model.js";import{fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";import{noteChange}from"./activity.svelte.js";import{getFieldUsers}from"./sources.svelte.js";import{newRecordId}from"./field-ops.js";import{fieldText,fieldValue,linkNames}from"./base-alerts.js";import{callWebhook,sendChat,sendEmailAction,sendTextAction}from"./automation-outbound.js";import{runScript}from"./automation-script.js";import{bm}from"./messages.svelte.js";import{cronWords}from"./cron-words.js";const appActions=new Map;export function registerAutomationAction(id,action){appActions.set(id,action)}export function listAutomationActions(){return[...appActions].map(([id,a])=>({id,label:a.label}))}const readers=new WeakMap;export function tableFields(t){const hit=readers.get(t.columns);if(hit)return hit;const all=t.columns.map(d=>({...d,id:colId(d)}));const map=new Map;for(const d of t.columns){if(d.field==null)continue;const def=fillFieldColumn(d,all);map.set(colId(d),{id:colId(d),field:String(d.field),header:String(d.header??d.field),fieldType:d.fieldType,def,visible:true})}readers.set(t.columns,map);return map}const byName=(t,name)=>{const lower=name.trim().toLowerCase();for(const c of tableFields(t).values()){if(c.header.trim().toLowerCase()===lower||c.field.toLowerCase()===lower||c.id.toLowerCase()===lower)return c}return void 0};export function fillTokens(t,record,template,values){return template.replace(/\{([^{}\n]+)\}/g,(m,name)=>{const given=values?.get(name.trim().toLowerCase());if(given!==void 0)return given;const c=byName(t,name);return!c?m:record?fieldText(c,record):bm("extras.noRecordValue")})}export function matches(t,condition,record){if(!condition)return true;const fields=tableFields(t);const test=compileFieldFilter(condition,(row,id)=>{const c=fields.get(id);return c?fieldValue(c,row):row[id]},linkNames);return test?test(record):true}function stampModifiedTime(t,row,changedIds,at){for(const d of t.columns){if(d.fieldType!=="lastModifiedTime"||d.field==null||changedIds.includes(colId(d)))continue;const p=fieldPropsOf(d);if(p.watch==="specific"&&!changedIds.some(id=>(p.watchFields??[]).includes(id)))continue;row[String(d.field)]=at.toISOString()}}const DAY=864e5;const isoDay=d=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;export function fieldValueFrom(t,def,spec,ctx){const type=def.fieldType;if(typeof spec!=="string")return spec;const raw=spec.includes("{record}")?spec:fillTokens(ctx.from,ctx.record,spec,ctx.values);const text=raw.trim();if(text==="")return type==="checkbox"?false:type==="multiSelect"||type==="link"||type==="attachment"?[]:null;switch(type){case"checkbox":return/^(true|yes|1|checked|on)$/i.test(text);case"number":case"rating":case"duration":case"currency":case"percent":{const n=Number(text.replace(/[^0-9.+-eE]/g,""));return Number.isFinite(n)?text.endsWith("%")?n/100:n:null}case"multiSelect":return text.split(/\s*,\s*/).filter(Boolean);case"user":{const found=getFieldUsers().find(u=>u.id===text||u.name.toLocaleLowerCase()===text.toLocaleLowerCase());return found?found.id:text}case"date":{const m=/^(today|now)\s*(?:([+-])\s*(\d+))?$/i.exec(text);if(!m)return text;const shift=m[2]?(m[2]==="-"?-1:1)*Number(m[3])*DAY:0;const at=new Date(ctx.now.getTime()+shift);return m[1].toLowerCase()==="now"||def.fieldProps?.time?at.toISOString():isoDay(at)}case"link":{const target=ctx.tables.find(x=>x.id===def.fieldProps?.table);const out=[];for(const part of text.split(/\s*,\s*/)){if(part==="{record}"){if(ctx.record&&ctx.from.id===target?.id)out.push(rowIdOf(ctx.from,ctx.record));continue}const name=fillTokens(ctx.from,ctx.record,part,ctx.values).toLocaleLowerCase();const named=ctx.named?.get(name);if(named){out.push(named);continue}const hit=target?.data.find(r=>String(r?.[primaryOf(target)]??"").toLocaleLowerCase()===name);if(hit&&target)out.push(rowIdOf(target,hit))}return def.fieldProps?.multiple===false?out.slice(0,1):out}default:return raw}}export const MAX_DEPTH=4;export const REPEAT_MOST=1e3;const SCRIPT_ROWS=5e3;const READ_AS_TEXT=new Set(["checkbox","number","rating","duration","currency","percent","multiSelect","user","date","link"]);export function scriptRecord(t,r){const values={};const texts={};let name="";for(const c of tableFields(t).values()){let v=r[c.field]??null;try{v=JSON.parse(JSON.stringify(v))}catch{v=null}values[c.header]=v;texts[c.header]=fieldText(c,r);if(c.field===primaryOf(t))name=texts[c.header]}return{id:rowIdOf(t,r),name,values,texts}}export function scriptInput(t,rec,values){const out={};if(rec){out.recordId=rowIdOf(t,rec);for(const c of tableFields(t).values())out[c.header]=fieldText(c,rec)}for(const[k,v]of values)out[k]=v;return out}export function webhookValues(body){const out=new Map;const walk=(v,path,depth)=>{if(out.size>=200)return;if(v!==null&&typeof v==="object"&&depth<5){for(const[k,x]of Object.entries(v).slice(0,100))walk(x,`${path}.${k.toLowerCase()}`,depth+1);if(path!=="webhook")out.set(path,JSON.stringify(v));return}out.set(path,v==null?"":typeof v==="string"?v:JSON.stringify(v))};walk(body,"webhook",0);out.set("webhook",typeof body==="string"?body:JSON.stringify(body??null));return out}export function triggerValues(t,rec,values){const out=new Map(values);if(rec)for(const c of tableFields(t).values())out.set(`trigger.${c.header.trim().toLowerCase()}`,fieldText(c,rec));return out}export function allActions(list){const out=[];for(const x of list){out.push(x);if(x.type==="if")out.push(...allActions(x.then??[]),...allActions(x.else??[]));if(x.type==="repeat")out.push(...allActions(x.actions??[]))}return out}const SHOW_BACKLOG=20;const CARRY_MOST=5e3;const FREE_EVERY=4096;let runSeq=0;export function createAutomationRunner(options){const now=options.now??(()=>new Date);let runs=$state.raw([]);let scheduler=null;let chain=Promise.resolve();let waiting=[];let head=0;let draining=false;let burst={done:0,total:0,at:0,told:0};let backlog=$state.raw(null);let measured=null;const record=run=>runs=[run,...runs].slice(0,100);const automationsOf=t=>(t.automations??[]).filter(a=>a.enabled&&a.runOn!=="server");const tableOf=id=>options.getTables()?.find(t=>t.id===id);const carried=new Map;const carriedFor=new Map;const carry=(key,row)=>{carried.set(key,row);carriedFor.set(key,(carriedFor.get(key)??0)+1)};const letGo=key=>{const left=(carriedFor.get(key)??1)-1;if(left>0)return void carriedFor.set(key,left);carriedFor.delete(key);carried.delete(key)};const recordNow=async(t,id)=>{const own=tableOf(t.id)??t;if(!own.source?.server)return own.data.find(r=>r&&rowIdOf(own,r)===id)??null;return carried.get(`${t.id}:${id}`)??await options.server?.read(t.id,id)??null};async function namesIn(target,values,ctx){const named=new Map;const fields=tableFields(target);for(const[id,spec]of Object.entries(values)){const def=fields.get(id)?.def;if(def?.fieldType!=="link"||typeof spec!=="string")continue;const to=(options.getTables()??[]).find(x=>x.id===def.fieldProps?.table);if(!to?.source?.server)continue;for(const part of spec.split(/\s*,\s*/)){const name=fillTokens(ctx.from,ctx.record,part);const hit=part==="{record}"?null:await options.server?.byName(to.id,name);if(hit)named.set(name.toLocaleLowerCase(),hit)}}return named}const setOff=(t,e)=>automationsFor(t,e,"browser");function handle(e){const t=tableOf(e.table);if(!t)return chain;const list=setOff(t,e);const depth="depth"in e?e.depth??0:0;const recordId=rowIdOf(t,e.record);for(const a of list){if(t.source?.server&&waiting.length-head<CARRY_MOST)carry(`${t.id}:${recordId}`,e.record);if(!draining&&head===waiting.length)burst={done:0,total:0,at:Date.now(),told:0};burst.total+=1;waiting.push({a,tableId:t.id,recordId,depth})}return list.length?drain():chain}function tell(){const clock=Date.now();if(burst.total<SHOW_BACKLOG||clock-burst.told<250)return;burst.told=clock;const seconds=(clock-burst.at)/1e3;if(burst.done>=SHOW_BACKLOG&&seconds>0)measured=burst.done/seconds;backlog={done:burst.done,total:burst.total,perSecond:burst.done>=SHOW_BACKLOG?measured:null}}function endBurst(left){const shown=backlog!=null||burst.total>=SHOW_BACKLOG;backlog=null;if(shown)options.onBurstEnd?.({done:burst.total-left,total:burst.total,left})}function drain(){if(draining)return chain;draining=true;tell();chain=chain.then(async()=>{let breath=Date.now();for(;;){if(head>=waiting.length){if(burst.total<SHOW_BACKLOG)break;await new Promise(r=>setTimeout(r,200));if(head>=waiting.length)break;continue}if(Date.now()-breath>40){await new Promise(r=>setTimeout(r));breath=Date.now();continue}const w=waiting[head];head+=1;if(head>=FREE_EVERY){waiting=waiting.slice(head);head=0}try{await runOne(w.a,w.tableId,w.recordId,w.depth)}catch(e){record({id:++runSeq,automationId:w.a.id,name:w.a.name,table:tableOf(w.tableId)?.name??w.tableId,record:w.recordId,at:now().getTime(),status:"error",steps:[{action:w.a.name,detail:"",error:e instanceof Error?e.message:String(e)}]})}if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`);burst.done+=1;tell()}waiting=[];head=0;draining=false;endBurst(0)});return chain}function stopRuns(){const left=waiting.length-head;if(!left)return 0;for(let i=head;i<waiting.length;i++){const w=waiting[i];if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`)}waiting=[];head=0;endBurst(left);burst={done:0,total:0,at:Date.now(),told:0};return left}async function runOne(a,tableId,recordId,depth){const t=tableOf(tableId);if(!t)return;const rec=recordId==null?null:await recordNow(t,recordId);const run={id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:rec?String(rec[primaryOf(t)]??recordId):null,at:now().getTime(),status:"ok",steps:[]};if(depth>=MAX_DEPTH){run.status="stopped";run.steps.push({action:bm("extras.stepStopped"),detail:bm("extras.stepLoop",{max:MAX_DEPTH})});record(run);return}await runList(a,a.actions,tableId,recordId,depth,run,new Map);record(run)}async function runList(a,list,tableId,recordId,depth,run,values){for(const action of list){try{if(action.type==="if"){const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const yes=!!t&&(rec?matches(t,action.condition,rec):!action.condition?.conditions?.length);run.steps.push({action:bm("extras.stepIf"),detail:bm(yes?"extras.stepIfThen":"extras.stepIfElse")});if(!await runList(a,(yes?action.then:action.else)??[],tableId,recordId,depth,run,values))return false;continue}if(action.type==="repeat"){if(!await runRepeat(a,action,tableId,recordId,depth,run,values))return false;continue}const step=await act(a,action,tableId,recordId,depth,values);if(step)run.steps.push(step)}catch(e){run.status="error";run.steps.push({action:actionLabel(action),detail:"",error:e instanceof Error?e.message:String(e)});return false}}return true}async function runRepeat(a,action,tableId,recordId,depth,run,values){const target=tableOf(action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const most=Math.max(1,Math.min(REPEAT_MOST,action.limit??100));const ids=[];if(target.source?.server){await options.server?.each(target.id,action.condition,async r=>{if(ids.length>=most)return;const id=rowIdOf(target,r);carry(`${target.id}:${id}`,r);ids.push(id)})}else{for(const r of target.data){if(ids.length>=most)break;if(r&&matches(target,action.condition,r))ids.push(rowIdOf(target,r))}}run.steps.push({action:bm("extras.stepFound"),detail:bm("extras.foundIn",{count:ids.length,table:target.name})});const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const inner=t?triggerValues(t,rec,values):new Map(values);inner.set("found",String(ids.length));try{for(const id of ids)if(!await runList(a,action.actions??[],target.id,id,depth,run,inner))return false}finally{if(target.source?.server)for(const id of ids)letGo(`${target.id}:${id}`)}return true}async function writeRecord(a,t,recordId,rec,patch,depth,at){const fields=tableFields(t);const before={...rec};const after={...rec,...patch};const changed=Object.keys(patch).filter(f=>JSON.stringify(before[f]??null)!==JSON.stringify(after[f]??null));if(!changed.length)return{changed,after};const changedIds=changed.map(f=>[...fields.values()].find(c=>c.field===f)?.id??f);stampModifiedTime(t,after,changedIds,at);if(t.source?.server){carried.set(`${t.id}:${recordId}`,after);await options.server?.update(t.id,recordId,Object.fromEntries(Object.keys(after).filter(k=>after[k]!==before[k]).map(k=>[k,after[k]])),before)}else{const tables=options.getTables()??[];let next=tables.map(x=>x.id===t.id?{...x,data:x.data.map(r=>r&&rowIdOf(t,r)===recordId?after:r)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}changed.forEach((f,i)=>noteChange({base:options.scope,tableId:t.id},recordId,changedIds[i],after[f],a.name));void handle({type:"updated",table:t.id,record:after,before,fields:changedIds,depth:depth+1});return{changed,after}}function addRecord(target,row,depth){const tables=options.getTables()??[];let next=tables.map(x=>x.id===target.id?{...x,data:[...x.data,row]}:x);next=syncAllInverses(next,target.id);options.apply(next,depth+1,target.id);void handle({type:"created",table:target.id,record:row,depth:depth+1})}function pageBridge(a,depth){const named=name=>{const t=(options.getTables()??[]).find(x=>x.name.trim().toLowerCase()===name.trim().toLowerCase());if(!t)throw new Error(bm("extras.noTable",{table:name}));return t};const rowsOf=async t=>{if(!t.source?.server)return t.data.filter(Boolean);const out=[];await options.server?.each(t.id,void 0,async r=>{if(out.length<SCRIPT_ROWS)out.push(r)});return out};const patchOf=(t,given)=>{const patch={};for(const[name,v]of Object.entries(given??{})){const c=byName(t,name);if(!c)throw new Error(bm("extras.noField",{field:name}));const type=String(c.fieldType??"");const text=typeof v==="string"?v:v&&typeof v==="object"&&!Array.isArray(v)&&"name"in v?String(v.name):null;patch[c.field]=text!==null&&READ_AS_TEXT.has(type)?fieldValueFrom(t,c.def,text.replace(/[{}]/g,""),{tables:options.getTables()??[],from:t,record:null,now:now()}):v}return patch};return{tables:()=>(options.getTables()??[]).map(t=>t.name),select:async name=>{const t=named(name);return(await rowsOf(t)).map(r=>scriptRecord(t,r))},update:async(name,id,given)=>{const t=named(name);const rec=await recordNow(t,id);if(!rec)throw new Error(bm("extras.noRecordId",{id}));await writeRecord(a,t,id,rec,patchOf(t,given),depth,now())},create:async(name,given)=>{const t=named(name);const row={id:newRecordId(),...patchOf(t,given)};addRecord(t,row,depth);return String(row.id)},remove:async(name,id)=>{const t=named(name);const tables=options.getTables()??[];options.apply(tables.map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==id)}:x),depth+1,t.id)}}}async function act(a,action,tableId,recordId,depth,values){const tables=options.getTables()??[];const t=tables.find(x=>x.id===tableId);const rec=recordId==null?null:await recordNow(t,recordId);const ctx={tables,from:t,record:rec,now:now(),values};switch(action.type){case"notify":{const message=fillTokens(t,rec,action.message,values);const sev=action.severity??"info";toast[sev](message);return{action:bm("extras.stepNotice"),detail:message}}case"highlight":return null;case"updateRecord":{if(!rec||recordId==null)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.noRecordToUpdate")};const fields=tableFields(t);const patch={};ctx.named=await namesIn(t,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)patch[c.field]=fieldValueFrom(t,c.def,spec,ctx)}const{changed,after}=await writeRecord(a,t,recordId,rec,patch,depth,ctx.now);if(!changed.length)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.alreadySet")};return{action:bm("extras.actionUpdateRecord"),detail:changed.map(f=>said([...fields.values()].find(c=>c.field===f),f,after)).join(", ")}}case"createRecord":{const target=tables.find(x=>x.id===action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const fields=tableFields(target);const row={id:newRecordId()};ctx.named=await namesIn(target,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)row[c.field]=fieldValueFrom(target,c.def,spec,ctx)}if(action.linkField&&rec){const c=fields.get(action.linkField);if(c)row[c.field]=[rowIdOf(t,rec)]}addRecord(target,row,depth);const name=String(row[primaryOf(target)]??"")||bm("extras.aRecord");return{action:bm("extras.actionCreateRecord"),detail:bm("extras.createdIn",{name,table:target.name})}}case"run":return runAppAction(a,action,t,rec);case"webhook":return{action:bm("extras.stepWebhook"),detail:await callWebhook(action,outbound(a,t,rec,{},values))};case"email":return{action:bm("extras.stepEmail"),detail:await sendEmailAction(action,outbound(a,t,rec,{},values),void 0)};case"chat":return{action:bm("extras.stepChat"),detail:await sendChat(action,outbound(a,t,rec,{},values))};case"textMessage":return{action:bm("extras.stepText"),detail:await sendTextAction(action,outbound(a,t,rec,{},values),void 0)};case"ai":{if(!options.ai)throw new Error(bm("extras.noAi"));const prompt=fillTokens(t,rec,action.prompt,values).trim();if(!prompt)throw new Error(bm("extras.aiNoPrompt"));const answer=String(await options.ai(prompt)).trim();values.set("ai",answer);const c=action.field?tableFields(t).get(action.field):void 0;if(c&&rec&&recordId!=null)await writeRecord(a,t,recordId,rec,{[c.field]:answer},depth,ctx.now);return{action:bm("extras.stepAi"),detail:answer.length>160?answer.slice(0,157)+"...":answer}}case"script":{const result=await runScript(action.code,{input:scriptInput(t,rec,values),bridge:pageBridge(a,depth)});for(const[k,v]of Object.entries(result.output))values.set(`script.${k.toLowerCase()}`,typeof v==="string"?v:JSON.stringify(v));if(!result.ok)throw new Error(result.error??bm("extras.scriptFailed"));return{action:bm("extras.stepScript"),detail:result.logs.slice(-3).join(" | ")||bm("extras.stepDone")}}default:return null}}function schedule(){scheduler?.stop();scheduler=null;const list=options.getTables()??[];const due=[];for(const t of list)for(const a of automationsOf(t))if(a.trigger.type==="scheduled")due.push({id:`${t.id}:${a.id}`,cron:a.trigger.cron,table:t.id,automation:a});if(!due.length)return;scheduler=createScheduler({schedules:due,now,onFire:s=>void runScheduled(s.id)});scheduler.start()}function runScheduled(key){const[tableId,automationId]=key.split(":");const t=tableOf(tableId);const a=t?.automations?.find(x=>x.id===automationId);if(!t||!a)return chain;if(!a.condition)chain=chain.then(()=>runOne(a,t.id,null,0));else if(t.source?.server){chain=chain.then(()=>options.server?.each(t.id,a.condition,async r=>{const key2=`${t.id}:${rowIdOf(t,r)}`;carry(key2,r);await runOne(a,t.id,rowIdOf(t,r),0);letGo(key2)}))}else for(const r of t.data)if(r&&matches(t,a.condition,r))chain=chain.then(()=>runOne(a,t.id,rowIdOf(t,r),0));return chain}return{handle,stopRuns,get backlog(){return backlog},get waiting(){return waiting.length-head},get perSecond(){return measured},schedule,runScheduled,firstRecords:async(tableId,count)=>await options.server?.first(tableId,count)??[],runNow:(a,tableId,recordId)=>chain=chain.then(async()=>{const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;if(t&&rec&&a.condition&&!matches(t,a.condition,rec)){record({id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:String(rec[primaryOf(t)]??recordId),at:now().getTime(),status:"stopped",steps:[{action:bm("extras.stepNotRun"),detail:bm("extras.stepNoMatch")}]});return}return runOne(a,tableId,recordId,0)}),get runs(){return runs},clearRuns:()=>runs=[],settled:()=>chain,stop:()=>scheduler?.stop()}}function said(c,field,record){if(!c)return bm("extras.saidValue",{field,value:String(record[field]??"")});if(c.fieldType==="checkbox")return bm(record[c.field]?"extras.saidChecked":"extras.saidUnchecked",{field:c.header});return bm("extras.saidValue",{field:c.header,value:fieldText(c,record)||bm("extras.saidEmpty")})}export function automationsFor(t,e,side){return(t.automations??[]).filter(a=>{if(!a.enabled||a.runOn==="server"!==(side==="server"))return false;const tr=a.trigger;switch(tr.type){case"recordCreated":return e.type==="created"&&matches(t,a.condition,e.record);case"recordUpdated":return e.type==="updated"&&(!tr.fields?.length||tr.fields.some(f=>e.fields.includes(f)))&&matches(t,a.condition,e.record);case"recordMatches":if(!a.condition)return false;if(e.type==="created")return matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,a.condition,e.record)&&!matches(t,a.condition,e.before);return false;case"formSubmitted":return e.type==="form"&&(!tr.view||tr.view===e.view)&&matches(t,a.condition,e.record);case"button":return e.type==="button"&&e.field===tr.field&&matches(t,a.condition,e.record);default:return false}})}export function outbound(a,t,rec,extra={},values){return{automation:a.name,table:t.name,record:rec,fill:template=>fillTokens(t,rec,template,values),fields:()=>{const out={};if(rec)for(const c of tableFields(t).values())out[c.header]=c.fieldType==="checkbox"?String(!!rec[c.field]):fieldText(c,rec);return out},...extra}}export async function runAppAction(a,action,t,rec){const app=appActions.get(action.action);if(!app)throw new Error(bm("extras.noAction",{action:action.action}));const out=await app.run({automation:a,table:t,record:rec,text:name=>fillTokens(t,rec,`{${name}}`),options:action.options??{}});return{action:app.label,detail:typeof out==="string"?out:bm("extras.stepDone")}}export function actionLabel(a){switch(a.type){case"updateRecord":return bm("extras.actionUpdateRecord");case"createRecord":return bm("extras.actionCreateRecord");case"notify":return bm("extras.actionNotify");case"highlight":return bm("extras.actionHighlight");case"run":return appActions.get(a.action)?.label??a.action;case"webhook":return bm("extras.actionWebhook");case"email":return bm("extras.actionEmail");case"chat":return bm("extras.actionChat");case"textMessage":return bm("extras.actionText");case"repeat":return bm("extras.actionRepeat");case"if":return bm("extras.actionIf");case"ai":return bm("extras.actionAi");case"script":return bm("extras.actionScript")}}export function triggerText(t,a){const name=id=>t?tableFields(t).get(id)?.header??id:id;const cond=a.condition?describeFieldFilter(a.condition,name):"";const where=cond&&cond!=="every record";const tr=a.trigger;switch(tr.type){case"recordCreated":return where?bm("extras.whenCreatedWhere",{condition:cond}):bm("extras.whenCreated");case"recordUpdated":{if(!tr.fields?.length)return where?bm("extras.whenRecordChangesWhere",{condition:cond}):bm("extras.whenRecordChanges");const fields=tr.fields.map(name).join(bm("extras.fieldsOr"));return where?bm("extras.whenFieldsChangeWhere",{fields,condition:cond}):bm("extras.whenFieldsChange",{fields})}case"recordMatches":return bm("extras.whenMatches",{condition:cond||bm("extras.noConditionYet")});case"formSubmitted":return where?bm("extras.whenFormWhere",{condition:cond}):bm("extras.whenForm");case"button":return bm("extras.whenPressed",{field:name(tr.field)});case"scheduled":return where?bm("extras.onScheduleWhere",{cron:cronWords(tr.cron),condition:cond}):bm("extras.onSchedule",{cron:cronWords(tr.cron)});case"webhookReceived":return bm("extras.whenWebhook")}}
1
+ import{toast}from"@svgrid/grid";import{createScheduler}from"../scheduling.js";import{colId,primaryOf,rowIdOf,syncAllInverses}from"./base-tables.js";import{compileFieldFilter,describeFieldFilter}from"./filter-model.js";import{fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";import{noteChange}from"./activity.svelte.js";import{getCurrentUser,getFieldUsers}from"./sources.svelte.js";import{newRecordId}from"./field-ops.js";import{fieldText,fieldValue,linkNames}from"./base-alerts.js";import{callWebhook,sendChat,sendEmailAction,sendTextAction}from"./automation-outbound.js";import{runScript}from"./automation-script.js";import{bm}from"./messages.svelte.js";import{cronWords}from"./cron-words.js";const appActions=new Map;export function registerAutomationAction(id,action){appActions.set(id,action)}export function listAutomationActions(){return[...appActions].map(([id,a])=>({id,label:a.label}))}const readers=new WeakMap;export function tableFields(t){const hit=readers.get(t.columns);if(hit)return hit;const all=t.columns.map(d=>({...d,id:colId(d)}));const map=new Map;for(const d of t.columns){if(d.field==null)continue;const def=fillFieldColumn(d,all);map.set(colId(d),{id:colId(d),field:String(d.field),header:String(d.header??d.field),fieldType:d.fieldType,def,visible:true})}readers.set(t.columns,map);return map}const byName=(t,name)=>{const lower=name.trim().toLowerCase();for(const c of tableFields(t).values()){if(c.header.trim().toLowerCase()===lower||c.field.toLowerCase()===lower||c.id.toLowerCase()===lower)return c}return void 0};export function fillTokens(t,record,template,values){return template.replace(/\{([^{}\n]+)\}/g,(m,name)=>{const given=values?.get(name.trim().toLowerCase());if(given!==void 0)return given;const c=byName(t,name);return!c?m:record?fieldText(c,record):bm("extras.noRecordValue")})}export function matches(t,condition,record){if(!condition)return true;const fields=tableFields(t);const test=compileFieldFilter(condition,(row,id)=>{const c=fields.get(id);return c?fieldValue(c,row):row[id]},linkNames);return test?test(record):true}function stampModifiedTime(t,row,changedIds,at){for(const d of t.columns){if(d.fieldType!=="lastModifiedTime"||d.field==null||changedIds.includes(colId(d)))continue;const p=fieldPropsOf(d);if(p.watch==="specific"&&!changedIds.some(id=>(p.watchFields??[]).includes(id)))continue;row[String(d.field)]=at.toISOString()}}const DAY=864e5;const isoDay=d=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;export function fieldValueFrom(t,def,spec,ctx){const type=def.fieldType;if(typeof spec!=="string")return spec;const raw=spec.includes("{record}")?spec:fillTokens(ctx.from,ctx.record,spec,ctx.values);const text=raw.trim();if(text==="")return type==="checkbox"?false:type==="multiSelect"||type==="link"||type==="attachment"?[]:null;switch(type){case"checkbox":return/^(true|yes|1|checked|on)$/i.test(text);case"number":case"rating":case"duration":case"currency":case"percent":{const n=Number(text.replace(/[^0-9.+-eE]/g,""));return Number.isFinite(n)?text.endsWith("%")?n/100:n:null}case"multiSelect":return text.split(/\s*,\s*/).filter(Boolean);case"user":{const found=getFieldUsers().find(u=>u.id===text||u.name.toLocaleLowerCase()===text.toLocaleLowerCase());return found?found.id:text}case"date":{const m=/^(today|now)\s*(?:([+-])\s*(\d+))?$/i.exec(text);if(!m)return text;const shift=m[2]?(m[2]==="-"?-1:1)*Number(m[3])*DAY:0;const at=new Date(ctx.now.getTime()+shift);return m[1].toLowerCase()==="now"||def.fieldProps?.time?at.toISOString():isoDay(at)}case"link":{const target=ctx.tables.find(x=>x.id===def.fieldProps?.table);const out=[];for(const part of text.split(/\s*,\s*/)){if(part==="{record}"){if(ctx.record&&ctx.from.id===target?.id)out.push(rowIdOf(ctx.from,ctx.record));continue}const name=fillTokens(ctx.from,ctx.record,part,ctx.values).toLocaleLowerCase();const named=ctx.named?.get(name);if(named){out.push(named);continue}const hit=target?.data.find(r=>String(r?.[primaryOf(target)]??"").toLocaleLowerCase()===name);if(hit&&target)out.push(rowIdOf(target,hit))}return def.fieldProps?.multiple===false?out.slice(0,1):out}default:return raw}}export const MAX_DEPTH=4;export function pressedValues(){const me=getCurrentUser();const out=new Map;out.set("pressed.name",me?.name??"");out.set("pressed.email",me?.email??"");out.set("pressed.id",me?.id??"");return out}export const REPEAT_MOST=1e3;const SCRIPT_ROWS=5e3;const READ_AS_TEXT=new Set(["checkbox","number","rating","duration","currency","percent","multiSelect","user","date","link"]);export function scriptRecord(t,r){const values={};const texts={};let name="";for(const c of tableFields(t).values()){let v=r[c.field]??null;try{v=JSON.parse(JSON.stringify(v))}catch{v=null}values[c.header]=v;texts[c.header]=fieldText(c,r);if(c.field===primaryOf(t))name=texts[c.header]}return{id:rowIdOf(t,r),name,values,texts}}export function scriptInput(t,rec,values){const out={};if(rec){out.recordId=rowIdOf(t,rec);for(const c of tableFields(t).values())out[c.header]=fieldText(c,rec)}for(const[k,v]of values)out[k]=v;return out}export function webhookValues(body){const out=new Map;const walk=(v,path,depth)=>{if(out.size>=200)return;if(v!==null&&typeof v==="object"&&depth<5){for(const[k,x]of Object.entries(v).slice(0,100))walk(x,`${path}.${k.toLowerCase()}`,depth+1);if(path!=="webhook")out.set(path,JSON.stringify(v));return}out.set(path,v==null?"":typeof v==="string"?v:JSON.stringify(v))};walk(body,"webhook",0);out.set("webhook",typeof body==="string"?body:JSON.stringify(body??null));return out}export function triggerValues(t,rec,values){const out=new Map(values);if(rec)for(const c of tableFields(t).values())out.set(`trigger.${c.header.trim().toLowerCase()}`,fieldText(c,rec));return out}export function allActions(list){const out=[];for(const x of list){out.push(x);if(x.type==="if")out.push(...allActions(x.then??[]),...allActions(x.else??[]));if(x.type==="repeat")out.push(...allActions(x.actions??[]))}return out}const SHOW_BACKLOG=20;const CARRY_MOST=5e3;const FREE_EVERY=4096;let runSeq=0;export function createAutomationRunner(options){const now=options.now??(()=>new Date);let runs=$state.raw([]);let scheduler=null;let chain=Promise.resolve();let waiting=[];let head=0;let draining=false;let burst={done:0,total:0,at:0,told:0};let backlog=$state.raw(null);let measured=null;const record=run=>runs=[run,...runs].slice(0,100);const automationsOf=t=>(t.automations??[]).filter(a=>a.enabled&&a.runOn!=="server");const tableOf=id=>options.getTables()?.find(t=>t.id===id);const carried=new Map;const carriedFor=new Map;const carry=(key,row)=>{carried.set(key,row);carriedFor.set(key,(carriedFor.get(key)??0)+1)};const letGo=key=>{const left=(carriedFor.get(key)??1)-1;if(left>0)return void carriedFor.set(key,left);carriedFor.delete(key);carried.delete(key)};const recordNow=async(t,id)=>{const own=tableOf(t.id)??t;if(!own.source?.server)return own.data.find(r=>r&&rowIdOf(own,r)===id)??null;return carried.get(`${t.id}:${id}`)??await options.server?.read(t.id,id)??null};async function namesIn(target,values,ctx){const named=new Map;const fields=tableFields(target);for(const[id,spec]of Object.entries(values)){const def=fields.get(id)?.def;if(def?.fieldType!=="link"||typeof spec!=="string")continue;const to=(options.getTables()??[]).find(x=>x.id===def.fieldProps?.table);if(!to?.source?.server)continue;for(const part of spec.split(/\s*,\s*/)){const name=fillTokens(ctx.from,ctx.record,part);const hit=part==="{record}"?null:await options.server?.byName(to.id,name);if(hit)named.set(name.toLocaleLowerCase(),hit)}}return named}const setOff=(t,e)=>automationsFor(t,e,"browser");function handle(e){const t=tableOf(e.table);if(!t)return chain;const list=setOff(t,e);const depth="depth"in e?e.depth??0:0;const recordId=rowIdOf(t,e.record);for(const a of list){if(t.source?.server&&waiting.length-head<CARRY_MOST)carry(`${t.id}:${recordId}`,e.record);if(!draining&&head===waiting.length)burst={done:0,total:0,at:Date.now(),told:0};burst.total+=1;waiting.push({a,tableId:t.id,recordId,depth})}return list.length?drain():chain}function tell(){const clock=Date.now();if(burst.total<SHOW_BACKLOG||clock-burst.told<250)return;burst.told=clock;const seconds=(clock-burst.at)/1e3;if(burst.done>=SHOW_BACKLOG&&seconds>0)measured=burst.done/seconds;backlog={done:burst.done,total:burst.total,perSecond:burst.done>=SHOW_BACKLOG?measured:null}}function endBurst(left){const shown=backlog!=null||burst.total>=SHOW_BACKLOG;backlog=null;if(shown)options.onBurstEnd?.({done:burst.total-left,total:burst.total,left})}function drain(){if(draining)return chain;draining=true;tell();chain=chain.then(async()=>{let breath=Date.now();for(;;){if(head>=waiting.length){if(burst.total<SHOW_BACKLOG)break;await new Promise(r=>setTimeout(r,200));if(head>=waiting.length)break;continue}if(Date.now()-breath>40){await new Promise(r=>setTimeout(r));breath=Date.now();continue}const w=waiting[head];head+=1;if(head>=FREE_EVERY){waiting=waiting.slice(head);head=0}try{await runOne(w.a,w.tableId,w.recordId,w.depth)}catch(e){record({id:++runSeq,automationId:w.a.id,name:w.a.name,table:tableOf(w.tableId)?.name??w.tableId,record:w.recordId,at:now().getTime(),status:"error",steps:[{action:w.a.name,detail:"",error:e instanceof Error?e.message:String(e)}]})}if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`);burst.done+=1;tell()}waiting=[];head=0;draining=false;endBurst(0)});return chain}function stopRuns(){const left=waiting.length-head;if(!left)return 0;for(let i=head;i<waiting.length;i++){const w=waiting[i];if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`)}waiting=[];head=0;endBurst(left);burst={done:0,total:0,at:Date.now(),told:0};return left}async function runOne(a,tableId,recordId,depth){const t=tableOf(tableId);if(!t)return;const rec=recordId==null?null:await recordNow(t,recordId);const run={id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:rec?String(rec[primaryOf(t)]??recordId):null,at:now().getTime(),status:"ok",steps:[]};if(depth>=MAX_DEPTH){run.status="stopped";run.steps.push({action:bm("extras.stepStopped"),detail:bm("extras.stepLoop",{max:MAX_DEPTH})});record(run);return}await runList(a,a.actions,tableId,recordId,depth,run,a.trigger.type==="button"?pressedValues():new Map);record(run)}async function runList(a,list,tableId,recordId,depth,run,values){for(const action of list){try{if(action.type==="if"){const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const yes=!!t&&(rec?matches(t,action.condition,rec):!action.condition?.conditions?.length);run.steps.push({action:bm("extras.stepIf"),detail:bm(yes?"extras.stepIfThen":"extras.stepIfElse")});if(!await runList(a,(yes?action.then:action.else)??[],tableId,recordId,depth,run,values))return false;continue}if(action.type==="repeat"){if(!await runRepeat(a,action,tableId,recordId,depth,run,values))return false;continue}const step=await act(a,action,tableId,recordId,depth,values);if(step)run.steps.push(step)}catch(e){run.status="error";run.steps.push({action:actionLabel(action),detail:"",error:e instanceof Error?e.message:String(e)});return false}}return true}async function runRepeat(a,action,tableId,recordId,depth,run,values){const target=tableOf(action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const most=Math.max(1,Math.min(REPEAT_MOST,action.limit??100));const ids=[];if(target.source?.server){await options.server?.each(target.id,action.condition,async r=>{if(ids.length>=most)return;const id=rowIdOf(target,r);carry(`${target.id}:${id}`,r);ids.push(id)})}else{for(const r of target.data){if(ids.length>=most)break;if(r&&matches(target,action.condition,r))ids.push(rowIdOf(target,r))}}run.steps.push({action:bm("extras.stepFound"),detail:bm("extras.foundIn",{count:ids.length,table:target.name})});const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const inner=t?triggerValues(t,rec,values):new Map(values);inner.set("found",String(ids.length));try{for(const id of ids)if(!await runList(a,action.actions??[],target.id,id,depth,run,inner))return false}finally{if(target.source?.server)for(const id of ids)letGo(`${target.id}:${id}`)}return true}async function writeRecord(a,t,recordId,rec,patch,depth,at){const fields=tableFields(t);const before={...rec};const after={...rec,...patch};const changed=Object.keys(patch).filter(f=>JSON.stringify(before[f]??null)!==JSON.stringify(after[f]??null));if(!changed.length)return{changed,after};const changedIds=changed.map(f=>[...fields.values()].find(c=>c.field===f)?.id??f);stampModifiedTime(t,after,changedIds,at);if(t.source?.server){carried.set(`${t.id}:${recordId}`,after);await options.server?.update(t.id,recordId,Object.fromEntries(Object.keys(after).filter(k=>after[k]!==before[k]).map(k=>[k,after[k]])),before)}else{const tables=options.getTables()??[];let next=tables.map(x=>x.id===t.id?{...x,data:x.data.map(r=>r&&rowIdOf(t,r)===recordId?after:r)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}changed.forEach((f,i)=>noteChange({base:options.scope,tableId:t.id},recordId,changedIds[i],after[f],a.name));void handle({type:"updated",table:t.id,record:after,before,fields:changedIds,depth:depth+1});return{changed,after}}function addRecord(target,row,depth){const tables=options.getTables()??[];let next=tables.map(x=>x.id===target.id?{...x,data:[...x.data,row]}:x);next=syncAllInverses(next,target.id);options.apply(next,depth+1,target.id);void handle({type:"created",table:target.id,record:row,depth:depth+1})}function pageBridge(a,depth){const named=name=>{const t=(options.getTables()??[]).find(x=>x.name.trim().toLowerCase()===name.trim().toLowerCase());if(!t)throw new Error(bm("extras.noTable",{table:name}));return t};const rowsOf=async t=>{if(!t.source?.server)return t.data.filter(Boolean);const out=[];await options.server?.each(t.id,void 0,async r=>{if(out.length<SCRIPT_ROWS)out.push(r)});return out};const patchOf=(t,given)=>{const patch={};for(const[name,v]of Object.entries(given??{})){const c=byName(t,name);if(!c)throw new Error(bm("extras.noField",{field:name}));const type=String(c.fieldType??"");const text=typeof v==="string"?v:v&&typeof v==="object"&&!Array.isArray(v)&&"name"in v?String(v.name):null;patch[c.field]=text!==null&&READ_AS_TEXT.has(type)?fieldValueFrom(t,c.def,text.replace(/[{}]/g,""),{tables:options.getTables()??[],from:t,record:null,now:now()}):v}return patch};return{tables:()=>(options.getTables()??[]).map(t=>t.name),select:async name=>{const t=named(name);return(await rowsOf(t)).map(r=>scriptRecord(t,r))},update:async(name,id,given)=>{const t=named(name);const rec=await recordNow(t,id);if(!rec)throw new Error(bm("extras.noRecordId",{id}));await writeRecord(a,t,id,rec,patchOf(t,given),depth,now())},create:async(name,given)=>{const t=named(name);const row={id:newRecordId(),...patchOf(t,given)};addRecord(t,row,depth);return String(row.id)},remove:async(name,id)=>{const t=named(name);const tables=options.getTables()??[];options.apply(tables.map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==id)}:x),depth+1,t.id)}}}async function act(a,action,tableId,recordId,depth,values){const tables=options.getTables()??[];const t=tables.find(x=>x.id===tableId);const rec=recordId==null?null:await recordNow(t,recordId);const ctx={tables,from:t,record:rec,now:now(),values};switch(action.type){case"notify":{const message=fillTokens(t,rec,action.message,values);const sev=action.severity??"info";toast[sev](message);return{action:bm("extras.stepNotice"),detail:message}}case"highlight":return null;case"updateRecord":{if(!rec||recordId==null)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.noRecordToUpdate")};const fields=tableFields(t);const patch={};ctx.named=await namesIn(t,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)patch[c.field]=fieldValueFrom(t,c.def,spec,ctx)}const{changed,after}=await writeRecord(a,t,recordId,rec,patch,depth,ctx.now);if(!changed.length)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.alreadySet")};return{action:bm("extras.actionUpdateRecord"),detail:changed.map(f=>said([...fields.values()].find(c=>c.field===f),f,after)).join(", ")}}case"createRecord":{const target=tables.find(x=>x.id===action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const fields=tableFields(target);const row={id:newRecordId()};ctx.named=await namesIn(target,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)row[c.field]=fieldValueFrom(target,c.def,spec,ctx)}if(action.linkField&&rec){const c=fields.get(action.linkField);if(c)row[c.field]=[rowIdOf(t,rec)]}addRecord(target,row,depth);const name=String(row[primaryOf(target)]??"")||bm("extras.aRecord");return{action:bm("extras.actionCreateRecord"),detail:bm("extras.createdIn",{name,table:target.name})}}case"run":return runAppAction(a,action,t,rec);case"webhook":return{action:bm("extras.stepWebhook"),detail:await callWebhook(action,outbound(a,t,rec,{},values))};case"email":return{action:bm("extras.stepEmail"),detail:await sendEmailAction(action,outbound(a,t,rec,{},values),void 0)};case"chat":return{action:bm("extras.stepChat"),detail:await sendChat(action,outbound(a,t,rec,{},values))};case"textMessage":return{action:bm("extras.stepText"),detail:await sendTextAction(action,outbound(a,t,rec,{},values),void 0)};case"ai":{if(!options.ai)throw new Error(bm("extras.noAi"));const prompt=fillTokens(t,rec,action.prompt,values).trim();if(!prompt)throw new Error(bm("extras.aiNoPrompt"));const answer=String(await options.ai(prompt)).trim();values.set("ai",answer);const c=action.field?tableFields(t).get(action.field):void 0;if(c&&rec&&recordId!=null)await writeRecord(a,t,recordId,rec,{[c.field]:answer},depth,ctx.now);return{action:bm("extras.stepAi"),detail:answer.length>160?answer.slice(0,157)+"...":answer}}case"script":{const result=await runScript(action.code,{input:scriptInput(t,rec,values),bridge:pageBridge(a,depth)});for(const[k,v]of Object.entries(result.output))values.set(`script.${k.toLowerCase()}`,typeof v==="string"?v:JSON.stringify(v));if(!result.ok)throw new Error(result.error??bm("extras.scriptFailed"));return{action:bm("extras.stepScript"),detail:result.logs.slice(-3).join(" | ")||bm("extras.stepDone")}}default:return null}}function schedule(){scheduler?.stop();scheduler=null;const list=options.getTables()??[];const due=[];for(const t of list)for(const a of automationsOf(t))if(a.trigger.type==="scheduled")due.push({id:`${t.id}:${a.id}`,cron:a.trigger.cron,table:t.id,automation:a});if(!due.length)return;scheduler=createScheduler({schedules:due,now,onFire:s=>void runScheduled(s.id)});scheduler.start()}function runScheduled(key){const[tableId,automationId]=key.split(":");const t=tableOf(tableId);const a=t?.automations?.find(x=>x.id===automationId);if(!t||!a)return chain;if(!a.condition)chain=chain.then(()=>runOne(a,t.id,null,0));else if(t.source?.server){chain=chain.then(()=>options.server?.each(t.id,a.condition,async r=>{const key2=`${t.id}:${rowIdOf(t,r)}`;carry(key2,r);await runOne(a,t.id,rowIdOf(t,r),0);letGo(key2)}))}else for(const r of t.data)if(r&&matches(t,a.condition,r))chain=chain.then(()=>runOne(a,t.id,rowIdOf(t,r),0));return chain}return{handle,stopRuns,get backlog(){return backlog},get waiting(){return waiting.length-head},get perSecond(){return measured},schedule,runScheduled,firstRecords:async(tableId,count)=>await options.server?.first(tableId,count)??[],runNow:(a,tableId,recordId)=>chain=chain.then(async()=>{const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;if(t&&rec&&a.condition&&!matches(t,a.condition,rec)){record({id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:String(rec[primaryOf(t)]??recordId),at:now().getTime(),status:"stopped",steps:[{action:bm("extras.stepNotRun"),detail:bm("extras.stepNoMatch")}]});return}return runOne(a,tableId,recordId,0)}),get runs(){return runs},clearRuns:()=>runs=[],settled:()=>chain,stop:()=>scheduler?.stop()}}function said(c,field,record){if(!c)return bm("extras.saidValue",{field,value:String(record[field]??"")});if(c.fieldType==="checkbox")return bm(record[c.field]?"extras.saidChecked":"extras.saidUnchecked",{field:c.header});return bm("extras.saidValue",{field:c.header,value:fieldText(c,record)||bm("extras.saidEmpty")})}export function automationsFor(t,e,side){return(t.automations??[]).filter(a=>{if(!a.enabled||a.runOn==="server"!==(side==="server"))return false;const tr=a.trigger;switch(tr.type){case"recordCreated":return e.type==="created"&&matches(t,a.condition,e.record);case"recordUpdated":return e.type==="updated"&&(!tr.fields?.length||tr.fields.some(f=>e.fields.includes(f)))&&matches(t,a.condition,e.record);case"recordMatches":if(!a.condition)return false;if(e.type==="created")return matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,a.condition,e.record)&&!matches(t,a.condition,e.before);return false;case"formSubmitted":return e.type==="form"&&(!tr.view||tr.view===e.view)&&matches(t,a.condition,e.record);case"button":return e.type==="button"&&e.field===tr.field&&matches(t,a.condition,e.record);default:return false}})}export function outbound(a,t,rec,extra={},values){return{automation:a.name,table:t.name,record:rec,fill:template=>fillTokens(t,rec,template,values),fields:()=>{const out={};if(rec)for(const c of tableFields(t).values())out[c.header]=c.fieldType==="checkbox"?String(!!rec[c.field]):fieldText(c,rec);return out},...extra}}export async function runAppAction(a,action,t,rec){const app=appActions.get(action.action);if(!app)throw new Error(bm("extras.noAction",{action:action.action}));const out=await app.run({automation:a,table:t,record:rec,text:name=>fillTokens(t,rec,`{${name}}`),options:action.options??{}});return{action:app.label,detail:typeof out==="string"?out:bm("extras.stepDone")}}export function actionLabel(a){switch(a.type){case"updateRecord":return bm("extras.actionUpdateRecord");case"createRecord":return bm("extras.actionCreateRecord");case"notify":return bm("extras.actionNotify");case"highlight":return bm("extras.actionHighlight");case"run":return appActions.get(a.action)?.label??a.action;case"webhook":return bm("extras.actionWebhook");case"email":return bm("extras.actionEmail");case"chat":return bm("extras.actionChat");case"textMessage":return bm("extras.actionText");case"repeat":return bm("extras.actionRepeat");case"if":return bm("extras.actionIf");case"ai":return bm("extras.actionAi");case"script":return bm("extras.actionScript")}}export function triggerText(t,a){const name=id=>t?tableFields(t).get(id)?.header??id:id;const cond=a.condition?describeFieldFilter(a.condition,name):"";const where=cond&&cond!=="every record";const tr=a.trigger;switch(tr.type){case"recordCreated":return where?bm("extras.whenCreatedWhere",{condition:cond}):bm("extras.whenCreated");case"recordUpdated":{if(!tr.fields?.length)return where?bm("extras.whenRecordChangesWhere",{condition:cond}):bm("extras.whenRecordChanges");const fields=tr.fields.map(name).join(bm("extras.fieldsOr"));return where?bm("extras.whenFieldsChangeWhere",{fields,condition:cond}):bm("extras.whenFieldsChange",{fields})}case"recordMatches":return bm("extras.whenMatches",{condition:cond||bm("extras.noConditionYet")});case"formSubmitted":return where?bm("extras.whenFormWhere",{condition:cond}):bm("extras.whenForm");case"button":return bm("extras.whenPressed",{field:name(tr.field)});case"scheduled":return where?bm("extras.onScheduleWhere",{cron:cronWords(tr.cron),condition:cond}):bm("extras.onSchedule",{cron:cronWords(tr.cron)});case"webhookReceived":return bm("extras.whenWebhook")}}
@@ -1 +1 @@
1
- import{fillFieldColumn as Q}from"./registry.svelte.js";import Pe from"./RatingCell.svelte";import A from"./LinkCell.svelte";import De from"./AttachmentCell.svelte";import Ve from"./CheckboxCell.svelte";import ee from"./PercentCell.svelte";import O from"./UserCell.svelte";import Fe from"./ButtonCell.svelte";import Ie from"./BarcodeCell.svelte";import Le from"./LinkedRecordsCell.svelte";import Ae from"./RichTextCell.svelte";import Oe from"./RichHtmlCell.svelte";import{richPlain as D}from"./rich-html.js";import{toRichHtml as Ne}from"./rich-html-write.js";import te from"./SelectCell.svelte";import Re from"./ChecklistCell.svelte";import Be from"./ColorCell.svelte";import{attachmentsText as Ee,parseAttachments as Ue}from"./attachments.js";import{dateEditTokens as He,dateFromParts as N,exactNumber as _e,formatCurrency as re,formatDate as R,formatDuration as le,formatNumber as B,formatPercent as ie,numberFieldShape as ne,numberFromText as ze,numberKind as Ge,parseDateText as je,parseDuration as V,toNumber as E}from"./format.js";import{BRIGHT as oe,CHECKBOX_ICONS as $e,RATING_ICONS as Ke}from"./palette.js";import{COMPUTED_TYPES as We,ROLLUPS as U,fieldNameMap as Ye}from"./rollups.js";import{sparklineValues as H,voteCount as ae,voteIds as Xe}from"./vote.js";import xe from"./VoteCell.svelte";import Ze from"./TimerCell.svelte";import{timerSeconds as F,timerTotal as qe}from"./timer.js";import Je from"./SparklineCell.svelte";import{compileFormula as Qe,isoDate as et,selfReferenceError as tt}from"./formula.js";import{findFieldUser as se,getCurrentUser as ue,getFieldUsers as _,getLinkedTable as k,idOf as rt,linkedRows as z,listLinkedTables as lt,liveLink as it,recordsNaming as nt,resolveLinkId as ot,resolveLinkIds as at}from"./sources.svelte.js";import{splitNames as G}from"./name-list.js";import{linkedFields as st}from"./linked-fields.js";import{AI_FIELD_TYPE as ut}from"./ai-field.svelte.js";import{CHECKLIST_GROUPS as ce,checklistGroup as ct,checklistSortValue as dt,checklistText as pt,parseChecklist as ft,toChecklist as mt}from"./checklist.js";import{colorSortValue as gt,parseColor as j}from"./color-value.js";import{formatTimeOfDay as ht,parseTimeOfDay as de,timeSeconds as yt}from"./time-of-day.js";import{bm as l}from"./messages.svelte.js";const bt=new Set(["user","createdBy","lastModifiedBy"]);function kt(e){const t=String(e.field??e.id),r=o=>o.length===1?o[0]:o;if(bt.has(String(e.fieldType)))return o=>{const n=o?.[t];return n==null||n===""?n:r((Array.isArray(n)?n:[n]).map(a=>se(a)?.name??a))};if(e.fieldType!=="link")return null;const i=e.fieldProps?.table;return o=>{const n=o?.[t],a=k(i);if(!a||n==null||n==="")return n;const p=$(a,a.primaryField),f=new Map(z(a,n).map(d=>[rt(a,d),p(d)]));return r((Array.isArray(n)?n:[n]).map(d=>f.get(String(d))??d))}}const pe=new WeakMap;let v=0;function $(e,t){const r=n=>n?.[t];if(!e?.fields?.length)return r;let i=pe.get(e.fields);if(i||pe.set(e.fields,i=new Map),!i.has(t)){const n=st(e).find(p=>p.def.field===t),a=n?.def.fieldType==="timer"?p=>F(p?.[t]):null;i.set(t,a??n?.def.fieldFn??null)}const o=i.get(t);return o?n=>{if(v>3)return r(n);v+=1;try{return o(n)}finally{v-=1}}:r}const s={text:"M4 6h16M4 12h10M4 18h7",longText:"M4 6h16M4 10h16M4 14h16M4 18h10",richText:"M6 4h7a4 4 0 0 1 0 8H6zM6 12h8a4 4 0 0 1 0 8H6zM6 4v16",vote:"M12 19V5M5 12l7-7 7 7",sparkline:"M3 17l5-6 4 4 8-9",number:"M9 4 7 20M17 4l-2 16M4 9h16M3 15h16",currency:"M12 3v18M16 7.5C16 5.6 14.2 4.5 12 4.5S8 5.6 8 7.5s1.8 2.7 4 3.5 4 1.6 4 3.5-1.8 3-4 3-4-1.1-4-3",percent:"M19 5 5 19M7 7h.01M17 17h.01",date:"M4 6h16v14H4zM4 10h16M8 3v4M16 3v4",duration:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4l3 2",timer:"M12 7a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM12 10v4l2.5 1.5M9.5 2.5h5M12 2.5V5",checkbox:"M4 4h16v16H4zM8 12l3 3 5-6",singleSelect:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM8 11l4 4 4-4",multiSelect:"M3 7h11M3 12h11M3 17h11M17 6l2 2 3-3M17 16l2 2 3-3",rating:"M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3 6.5 20.2l1-6.2L3 9.6l6.2-.9z",url:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1",email:"M3 6h18v12H3zM3 7l9 6 9-6",phone:"M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2",attachment:"M20 11.5 12.3 19a5 5 0 0 1-7.1-7.1l7.8-7.8a3.3 3.3 0 0 1 4.7 4.7L9.9 16.6a1.7 1.7 0 0 1-2.4-2.4l7.1-7",user:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0",createdTime:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4h4",modifiedTime:"M4 12a8 8 0 1 0 2.3-5.7M4 4v4h4M12 8v4l3 2",createdBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M19 15v6M16 18h6",modifiedBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M16 21l5-5-2-2-5 5v2z",autoNumber:"M5 7h3v10M11 9a2 2 0 1 1 4 0c0 2-4 3-4 6h4M18 7h2v10",barcode:"M4 5v14M7 5v14M10 5v14M13 5v14M15 5v14M18 5v14M20 5v14",button:"M4 7h16v10H4zM9 12h6",formula:"M7 20c2 0 2.5-2 3-5l2-10c.5-2 1.5-2 3-2M8 9h7",link:"M9 7H6a5 5 0 0 0 0 10h3M15 7h3a5 5 0 0 1 0 10h-3M8 12h8",lookup:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4M8 11h6",rollup:"M6 4h12L12 12l6 8H6",count:"M5 5h14v14H5zM9 9v6M12 9v6M15 9v6",checklist:"M3.5 6l1.5 1.5L7.5 5M3.5 12l1.5 1.5 2.5-2.5M3.5 18l1.5 1.5 2.5-2.5M11 6h9M11 12h9M11 18h9",color:"M12 3a9 9 0 1 0 0 18c1 0 1.6-.7 1.6-1.6 0-1-.8-1.4-.8-2.3 0-1 .8-1.7 1.8-1.7H17a4 4 0 0 0 4-4C21 6.6 17 3 12 3zM7.5 12h.01M9.5 7.5h.01M14.5 7.5h.01",timeOfDay:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7v5l-3 2M12 3v2M21 12h-2M12 21v-2M3 12h2"},u=(e,t)=>({value:e,get label(){return l(t)}}),fe=e=>e?{visible:e}:{},wt={key:"separators",get label(){return l("fields.propSeparators")},kind:"choice",choices:[u("local","fields.choiceLocal"),{value:"comma-period",label:"1,000,000.00"},{value:"period-comma",label:"1.000.000,00"},{value:"space-comma",label:"1 000 000,00"},{value:"space-period",label:"1 000 000.00"}]},Tt={key:"showThousands",get label(){return l("fields.propShowThousands")},kind:"checkbox"},vt=e=>({key:"abbreviation",get label(){return l("fields.propAbbreviation")},kind:"choice",choices:[u("none","fields.choiceNone"),u("thousand","fields.choiceThousand"),u("million","fields.choiceMillion"),u("billion","fields.choiceBillion")],...fe(e)}),St={key:"allowNegative",get label(){return l("fields.propAllowNegative")},kind:"checkbox"},w={key:"default",get label(){return l("fields.propDefault")},kind:"default",get hint(){return l("fields.propDefaultHint")}},K=(e,t)=>Array.from({length:t-e+1},(r,i)=>{const o=e+i;return{value:String(o),label:o===0?"1":`1.${"0".repeat(o)}`}}),W=(e,t)=>({key:"precision",get label(){return l("fields.propPrecision")},kind:"choice",choices:e,visible:t}),Mt=[u("local","fields.choiceLocal"),u("friendly","fields.choiceFriendly"),u("us","fields.choiceUs"),u("european","fields.choiceEuropean"),u("iso","fields.choiceIso")],I=e=>({key:"dateFormat",get label(){return l("fields.propDateFormat")},kind:"choice",choices:Mt,...fe(e)}),me=[u("12hour","fields.choice12Hour"),u("24hour","fields.choice24Hour")],Y=[{key:"time",get label(){return l("fields.propIncludeTime")},kind:"checkbox"},{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:me,visible:e=>!!e.time},{key:"gmt",get label(){return l("fields.propGmt")},kind:"checkbox",visible:e=>!!e.time},{key:"showTimeZone",get label(){return l("fields.propShowTimeZone")},kind:"checkbox",visible:e=>!!e.time}],Ct=e=>e.columns.filter(t=>t.fieldType==="link").map(t=>({value:String(t.id??t.field),label:String(t.header??t.field)})),X={key:"linkField",get label(){return l("fields.propLinkField")},kind:"choice",choices:Ct,get hint(){return l("fields.propLinkFieldHint")}},Pt=e=>{const t=e.columns.find(o=>String(o.id??o.field)===e.props.linkField),r=k(t?.fieldProps?.table);return r?(r.fields??[{field:r.primaryField,header:r.primaryField}]).map(o=>({value:o.field,label:o.header})):[]},ge={key:"field",get label(){return l("fields.propLinkedField")},kind:"choice",choices:Pt,visible:e=>!!e.linkField},M={key:"color",get label(){return l("fields.propColor")},kind:"color",palette:oe},he={key:"options",get label(){return l("fields.propOptions")},kind:"options"},ye=(e,t=0)=>{const r=Number(e.precision);return Number.isInteger(r)&&r>=0&&r<=8?r:t},Dt=e=>({precision:e.format==="integer"?0:ye(e,e.format==="decimal"?1:0),separators:e.separators,showThousands:e.showThousands!==!1,abbreviation:e.abbreviation}),Vt=(e,t)=>r=>{const i=typeof r.rawInput=="string"?r.rawInput:r.newValue;if(typeof i=="number"||i==null)return i;if(String(i).trim()==="")return null;const o=ze(String(i),e,t);return o??r.oldValue},Ft=(e,t)=>t.allowNegative===!1&&!e.validate?{rejectInvalid:!0,validate:r=>Number(r.value)<0?l("fields.negativeNotAllowed"):null}:{},It=(e,t)=>{const r={precision:ne(e,t).places,separators:t.separators,showThousands:t.showThousands!==!1,abbreviation:e==="percent"?void 0:t.abbreviation};return i=>{const o=_e(i.value);return o==null?"":e==="currency"?re(o,{...r,symbol:t.symbol,symbolPosition:t.symbolPosition}):e==="percent"?ie(o,{...r,points:t.points}):B(o,r)}},x=(e,t,r)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",align:e.align??(r==="percent"&&t.showBar?"left":"right"),...Ft(e,t),valueParser:e.valueParser??Vt(r,t),formatter:e.formatter??It(r,t),sortValue:e.sortValue??E}),C=e=>Array.isArray(e.options)?e.options.map(t=>({value:t.value,label:t.label??String(t.value),...t.color?{color:t.color}:{}})):[],be=(e,t)=>{const r=new Map;for(const n of C(e))r.set(String(n.value).toLowerCase(),n.value),r.set(String(n.label).toLowerCase(),n.value);const i=n=>r.get(n.toLowerCase()),o=r.size===0;return n=>{if(typeof n.rawInput!="string")return n.newValue;const a=t?G(n.rawInput):n.rawInput.split(/\n/).map(f=>f.trim()).filter(Boolean);if(o)return t?[...new Set(a)]:a[0]??null;const p=a.map(i).filter(f=>f!==void 0);return a.length&&!p.length?n.oldValue:t?[...new Set(p)]:a.length?i(a[0])===void 0?n.oldValue:i(a[0]):null}},ke=e=>{const t=new Map(C(e).map(r=>[String(r.value),r.label]));return r=>(Array.isArray(r.value)?r.value:r.value==null||r.value===""?[]:[r.value]).map(i=>t.get(String(i))??String(i)).join(", ")},Lt=e=>{const t=new Map(C(e).map((r,i)=>[String(r.value),i]));return r=>r==null||r===""?null:t.get(String(r))??t.size},we=Ye,m=e=>({editable:e.editable??!1}),Z=e=>t=>R(t.value,e),P=e=>e.oldValue!=null&&typeof e.oldValue!="string"&&String(e.oldValue)===e.newValue?e.oldValue:e.newValue,At=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;if(r==null||typeof r=="string"&&r.trim()==="")return null;if(r instanceof Date)return e.time?r.toISOString():N({y:r.getFullYear(),mo:r.getMonth()+1,d:r.getDate(),time:null},e);const i=String(r).trim();if(/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?/.test(i)){if(!e.time)return i.slice(0,10);if(i.length>10&&i[10]==="T")return i}const o=je(i,e);return o?N(o,e,t.oldValue):t.oldValue},q=e=>(Array.isArray(e)?e:e==null||e===""?[]:[e]).map(t=>se(t)?.name??String(t)).join(", "),Te=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=_(),i=a=>{const p=a.toLowerCase();return r.find(d=>d.id.toLowerCase()===p||d.name.toLowerCase()===p||d.email?.toLowerCase()===p)?.id??(r.length?void 0:a)},o=e?G(t.rawInput):t.rawInput.split(/\n/).map(a=>a.trim()).filter(Boolean),n=o.map(i).filter(a=>a!==void 0);return o.length&&!n.length?t.oldValue:e?[...new Set(n)]:o.length?n[0]:null},Ot=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=k(e.table);if(!r)return t.newValue;const i=G(t.rawInput),o=at(r,i);if(r.records&&r.resolveNames&&t.data&&t.columnId){const n=i.filter(a=>ot(r,a)==null);n.length&&r.resolveNames({row:t.data,columnId:t.columnId,multiple:e.multiple!==!1},n,o)}return i.length&&!o.length?t.oldValue:e.multiple===!1?o.slice(0,1):o},Nt=e=>typeof e.rawInput=="string"?e.rawInput.trim()?ft(e.rawInput):null:Array.isArray(e.newValue)?mt(e.newValue):e.newValue??null,Rt=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=t.rawInput.trim();if(!r)return null;const i=Number(r);return Number.isInteger(i)&&i>=0&&i<=Number(e.max??5)?i:t.oldValue},Bt=e=>{const t=typeof e.rawInput=="string"?e.rawInput:e.newValue;return t==null||String(t).trim()===""?null:j(t)??e.oldValue},Et=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;return r==null||typeof r=="string"&&r.trim()===""?null:de(r,{seconds:!!e.showSeconds})??t.oldValue};function ve(e,t){if(e==null)return"";if(Array.isArray(e))return e.map(r=>ve(r,t)).join(", ");if(e instanceof Date)return R(e,t);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(t.result==="currency"||t.result==="percent"||t.result==="number"){const r=t.result,i={...Dt(t),precision:ne(r,{precision:t.precision}).places};return r==="currency"?re(e,{...i,symbol:t.symbol}):r==="percent"?ie(e,i):B(e,i)}return String(Math.round(e*1e10)/1e10)}if(t.result==="date"){const r=et(String(e));if(r)return R(r,t)}return String(e)}const J=(e,t)=>{const r=t.columns.find(n=>String(n.id??n.field)===e.linkField);if(!r)return null;const i=r.fieldProps?.table,o=r.fieldProps?.inverse;return{key:String(r.field??r.id),get table(){return k(i)},rowsOf(n){const a=k(i),p=String(r.field??r.id);return a&&o&&!a.records&&n?.[p]===void 0?nt(a,o,String(n?.id??"")):z(a,n?.[p])},get stored(){const n=k(i)?.records;return n&&o&&n.stores(o)?{records:n,field:o}:null}}},Ut={SUM:"sum",AVERAGE:"avg",MIN:"min",MAX:"max",COUNT:"count"},Se=new WeakMap;function Me(e,t,r){const i=e?.table?.fields;if(!i)return;let o=Se.get(i);o||Se.set(i,o=new Map);const n=`${String(t)}|${r??""}`;if(o.has(n))return o.get(n);const a=i.find(f=>f.field===String(t)),p=a?.fieldType?Q({field:a.field,fieldType:a.fieldType,fieldProps:{...a.fieldProps,...r==null?{}:{precision:r}}}).formatter:void 0;return o.set(n,p),p}const L=()=>new Date().toISOString(),Ht=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0}),_t=(e,t)=>{const r=i=>i?ce.indexOf(i):ce.length;return r(e)-r(t)},Ce=[{key:"watch",get label(){return l("fields.propWatch")},kind:"segmented",choices:[u("all","fields.choiceAllFields"),u("specific","fields.choiceSpecificFields")]},{key:"watchFields",get label(){return l("fields.propWatchFields")},kind:"columns",visible:e=>e.watch==="specific"}];export const BUILTIN_FIELD_TYPES=[{id:"text",get label(){return l("fields.typeText")},get description(){return l("fields.typeTextDescription")},icon:s.text,group:"basic",properties:[w],fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??P})},{id:"longText",get label(){return l("fields.typeLongText")},get description(){return l("fields.typeLongTextDescription")},icon:s.longText,group:"basic",width:260,properties:[{key:"richText",get label(){return l("fields.propMarkdown")},kind:"checkbox",get hint(){return l("fields.propMarkdownHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldLongText",valueParser:e.valueParser??P}),cell:Ae,hasCell:e=>!!e.richText},{id:"richText",get label(){return l("fields.typeRichText")},get description(){return l("fields.typeRichTextDescription")},icon:s.richText,group:"basic",width:280,defaults:{toolbar:"standard"},properties:[{key:"toolbar",get label(){return l("fields.propToolbar")},kind:"segmented",choices:[u("standard","fields.choiceStandard"),u("full","fields.choiceFull")],get hint(){return l("fields.propToolbarHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldRichText",formatter:e.formatter??(t=>D(t.value)),sortComparator:e.sortComparator??((t,r)=>Ht.compare(D(t),D(r))),valueParser:e.valueParser??(t=>Ne(t.newValue))}),cell:Oe},{id:"attachment",get label(){return l("fields.typeAttachment")},get description(){return l("fields.typeAttachmentDescription")},icon:s.attachment,group:"basic",width:180,defaults:{maxFiles:20},properties:[{key:"accept",get label(){return l("fields.propAccept")},kind:"text",get placeholder(){return l("fields.propAcceptPlaceholder")}},{key:"maxFiles",get label(){return l("fields.propMaxFiles")},kind:"number",min:1,max:100}],fill:(e,t)=>({...e,editorType:e.editorType??"attachment",formatter:e.formatter??(r=>Ee(r.value)),valueParser:e.valueParser??(r=>Ue(r.newValue,t))}),cell:De},{id:"checkbox",get label(){return l("fields.typeCheckbox")},get description(){return l("fields.typeCheckboxDescription")},icon:s.checkbox,group:"basic",width:90,defaults:{icon:"check",color:"#20c933"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:$e},M,w],fill:e=>({...e,editorType:e.editorType??"checkbox",align:e.align??"center",toggleOnSecondClick:e.toggleOnSecondClick??!0}),cell:Ve},{id:"singleSelect",get label(){return l("fields.typeSingleSelect")},get description(){return l("fields.typeSingleSelectDescription")},icon:s.singleSelect,group:"basic",width:140,defaults:{options:[]},properties:[he,w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorOptions:e.editorOptions??C(t),formatter:e.formatter??ke(t),valueParser:e.valueParser??be(t,!1),sortValue:e.sortValue??Lt(t)}),cell:te},{id:"multiSelect",get label(){return l("fields.typeMultiSelect")},get description(){return l("fields.typeMultiSelectDescription")},icon:s.multiSelect,group:"basic",width:200,defaults:{options:[]},properties:[he,w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorMultiple:e.editorMultiple??!0,editorOptions:e.editorOptions??C(t),formatter:e.formatter??ke(t),valueParser:e.valueParser??be(t,!0)}),cell:te},{id:"user",get label(){return l("fields.typeUser")},get description(){return l("fields.typeUserDescription")},icon:s.user,group:"basic",width:170,properties:[{key:"multiple",get label(){return l("fields.propMultipleUsers")},kind:"checkbox"},w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",valueParser:e.valueParser??Te(!!t.multiple),editorMultiple:e.editorMultiple??!!t.multiple,editorOptions:e.editorOptions??_().map(r=>({value:r.id,label:r.name})),formatter:e.formatter??(r=>q(r.value))}),cell:O},{id:"date",get label(){return l("fields.typeDate")},get description(){return l("fields.typeDateDescription")},icon:s.date,group:"basic",width:150,defaults:{dateFormat:"local",timeFormat:"12hour"},properties:[I(),...Y,{key:"defaultToday",get label(){return l("fields.propDefaultToday")},kind:"checkbox"}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??(t.time?"date":"dateString"),editorType:e.editorType??"fieldDate",editorFormatString:e.editorFormatString??He(t),formatter:e.formatter??Z(t),valueParser:e.valueParser??At(t)}),newRowValue:({props:e})=>{if(!e.defaultToday)return;if(e.time)return L();const t=new Date;return N({y:t.getFullYear(),mo:t.getMonth()+1,d:t.getDate(),time:null},{})}},{id:"phone",get label(){return l("fields.typePhone")},get description(){return l("fields.typePhoneDescription")},icon:s.phone,group:"basic",fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??P}),cell:A},{id:"email",get label(){return l("fields.typeEmail")},get description(){return l("fields.typeEmailDescription")},icon:s.email,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??P}),cell:A},{id:"url",get label(){return l("fields.typeUrl")},get description(){return l("fields.typeUrlDescription")},icon:s.url,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??P}),cell:A},{id:"barcode",get label(){return l("fields.typeBarcode")},get description(){return l("fields.typeBarcodeDescription")},icon:s.barcode,group:"basic",width:160,fill:e=>({...e,editorType:e.editorType??"text",formatter:e.formatter??(t=>t.value&&typeof t.value=="object"?String(t.value.text??""):String(t.value??""))}),cell:Ie},{id:"button",get label(){return l("fields.typeButton")},get description(){return l("fields.typeButtonDescription")},icon:s.button,group:"basic",width:120,defaults:{label:"Open",color:"#2d7ff9"},properties:[{key:"label",get label(){return l("fields.propButtonLabel")},kind:"text",get placeholder(){return l("fields.propButtonLabelPlaceholder")}},{key:"color",get label(){return l("fields.propButtonStyle")},kind:"color",palette:oe},{key:"url",get label(){return l("fields.propButtonUrl")},kind:"text",get placeholder(){return l("fields.propButtonUrlPlaceholder")},get hint(){return l("fields.propButtonUrlHint")}}],fill:(e,t,r)=>({...e,...m(e),sortable:e.sortable??!1,__fieldNames:we(r.columns)}),cell:Fe},{id:"checklist",get label(){return l("fields.typeChecklist")},get description(){return l("fields.typeChecklistDescription")},icon:s.checklist,group:"basic",width:150,fill:e=>({...e,editorType:e.editorType??"fieldChecklist",formatter:e.formatter??(t=>pt(t.value)),valueParser:e.valueParser??Nt,sortValue:e.sortValue??dt,groupValue:e.groupValue??ct,groupOrder:e.groupOrder??_t}),cell:Re},{id:"color",get label(){return l("fields.typeColor")},get description(){return l("fields.typeColorDescription")},icon:s.color,group:"basic",width:130,properties:[w],fill:e=>({...e,editorType:e.editorType??"fieldColor",formatter:e.formatter??(t=>j(t.value)??String(t.value??"")),valueParser:e.valueParser??Bt,sortValue:e.sortValue??gt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:j(e.default),cell:Be},{id:"number",get label(){return l("fields.typeNumber")},get description(){return l("fields.typeNumberDescription")},icon:s.number,group:"number",width:120,defaults:{format:"decimal",precision:1,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0,symbol:"$",symbolPosition:"before",showBar:!1,points:!1,step:1},properties:[{key:"format",get label(){return l("fields.propFormat")},kind:"segmented",choices:[u("integer","fields.choiceInteger"),u("decimal","fields.choiceDecimal"),u("currency","fields.choiceCurrency"),u("percent","fields.choicePercent")],alsoSets:e=>({precision:e==="decimal"?1:e==="currency"?2:0})},{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$, €, £, ¥, CHF, kr",visible:e=>e.format==="currency"},{key:"symbolPosition",get label(){return l("fields.propSymbolPosition")},kind:"segmented",visible:e=>e.format==="currency",choices:[u("before","fields.choiceBefore"),u("after","fields.choiceAfter")]},W(K(0,8),e=>e.format!=="integer"),{key:"step",get label(){return l("fields.propStep")},kind:"number",min:0,get hint(){return l("fields.propStepHint")}},wt,Tt,vt(e=>e.format!=="percent"),St,{key:"showBar",get label(){return l("fields.propShowBar")},kind:"checkbox",visible:e=>e.format==="percent"},{key:"points",get label(){return l("fields.propPoints")},kind:"checkbox",visible:e=>e.format==="percent"},w],fill:(e,t)=>x(e,t,Ge("number",t)),cell:ee,hasCell:e=>e.format==="percent"&&!!e.showBar},{id:"currency",get label(){return l("fields.typeCurrency")},get description(){return l("fields.typeCurrencyDescription")},icon:s.currency,group:"number",width:120,defaults:{symbol:"$",symbolPosition:"before",precision:2,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0},editAs:{type:"number",props:{format:"currency"}},fill:(e,t)=>x(e,t,"currency")},{id:"percent",get label(){return l("fields.typePercent")},get description(){return l("fields.typePercentDescription")},icon:s.percent,group:"number",width:110,defaults:{precision:0,separators:"local",showThousands:!0,allowNegative:!0,points:!1},editAs:{type:"number",props:{format:"percent"}},fill:(e,t)=>x(e,t,"percent"),cell:ee,hasCell:e=>!!e.showBar},{id:"duration",get label(){return l("fields.typeDuration")},get description(){return l("fields.typeDurationDescription")},icon:s.duration,group:"number",width:110,defaults:{durationFormat:"h:mm"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"},{value:"h:mm:ss.S",label:"h:mm:ss.S"},{value:"h:mm:ss.SS",label:"h:mm:ss.SS"},{value:"h:mm:ss.SSS",label:"h:mm:ss.SSS"}]}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",formatter:e.formatter??(r=>{const i=E(r.value);return i==null?"":le(i,t.durationFormat)}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:typeof r.newValue=="number"?r.newValue:V(r.newValue))})},{id:"timeOfDay",get label(){return l("fields.typeTimeOfDay")},get description(){return l("fields.typeTimeOfDayDescription")},icon:s.timeOfDay,group:"number",width:120,defaults:{timeFormat:"12hour",showSeconds:!1},properties:[{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:me},{key:"showSeconds",get label(){return l("fields.propShowSeconds")},kind:"checkbox"},w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldTime",formatter:e.formatter??(r=>ht(r.value,t)),valueParser:e.valueParser??Et(t),sortValue:e.sortValue??yt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:de(e.default,{seconds:!!e.showSeconds})},{id:"rating",get label(){return l("fields.typeRating")},get description(){return l("fields.typeRatingDescription")},icon:s.rating,group:"number",width:130,defaults:{max:5,icon:"star",color:"#fcb400"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:Ke},M,{key:"max",get label(){return l("fields.propMaximum")},kind:"choice",choices:Array.from({length:10},(e,t)=>({value:String(t+1),label:String(t+1)}))}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",align:e.align??"left",editorType:e.editorType??"fieldRating",valueParser:e.valueParser??Rt(t)}),cell:Pe},{id:"timer",get label(){return l("fields.typeTimer")},get description(){return l("fields.typeTimerDescription")},icon:s.timer,group:"number",width:130,defaults:{durationFormat:"h:mm:ss"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"}]},M],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldTimer",align:e.align??"left",sortValue:e.sortValue??(r=>F(r)),formatter:e.formatter??(r=>{const i=F(r.value);return i==null?"":le(i,t.durationFormat??"h:mm:ss")}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:r.newValue==null||r.newValue===""?null:typeof r.newValue=="number"||typeof r.newValue=="object"&&qe(r.newValue)!=null?r.newValue:V(r.newValue))}),cell:Ze},{id:"vote",get label(){return l("fields.typeVote")},get description(){return l("fields.typeVoteDescription")},icon:s.vote,group:"basic",width:100,defaults:{icon:"up"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"segmented",choices:[u("up","fields.choiceArrow"),u("thumb","fields.choiceThumb"),u("heart","fields.choiceHeart")]},M],fill:e=>({...e,editorType:e.editorType??"fieldVote",editorOptions:e.editorOptions??_().map(t=>({value:t.id,label:t.name})),align:e.align??"left",sortValue:e.sortValue??(t=>ae(t)),formatter:e.formatter??(t=>String(ae(t.value))),valueParser:e.valueParser??(t=>Xe(Te(!0)(t)))}),newRowValue:()=>[],cell:xe},{id:"sparkline",get label(){return l("fields.typeSparkline")},get description(){return l("fields.typeSparklineDescription")},icon:s.sparkline,group:"number",width:160,defaults:{chart:"line"},properties:[{key:"chart",get label(){return l("fields.propChart")},kind:"segmented",choices:[u("line","fields.choiceLine"),u("area","fields.choiceArea"),u("bar","fields.choiceColumns")]},M,{key:"showLast",get label(){return l("fields.propShowLast")},kind:"checkbox"}],fill:e=>({...e,formatter:e.formatter??(t=>H(t.value).join(", ")),valueParser:e.valueParser??(t=>{const r=H(t.newValue);return r.length?r:null}),sortValue:e.sortValue??(t=>H(t).at(-1)??null)}),cell:Je},{id:"formula",get label(){return l("fields.typeFormula")},get description(){return l("fields.typeFormulaDescription")},icon:s.formula,group:"computed",width:160,defaults:{formula:"",result:"auto"},properties:[{key:"formula",get label(){return l("fields.propFormula")},kind:"formula"},{key:"result",get label(){return l("fields.propResult")},kind:"choice",choices:[u("auto","fields.choiceAsComputed"),u("number","fields.choiceNumber"),u("currency","fields.choiceCurrency"),u("percent","fields.choicePercent"),u("date","fields.choiceDate")]},W(K(0,8),e=>["number","currency","percent"].includes(e.result)),{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$",visible:e=>e.result==="currency"},I(e=>e.result==="date")],fill:(e,t,r)=>{const i=we(r.columns),o=String(t.formula??""),n=String(e.field??e.id),a=new Set([n.toLowerCase(),typeof e.header=="string"?e.header.trim().toLowerCase():""].filter(Boolean)),p=c=>{const b=c.trim().toLowerCase(),h=i[b]??null;if(h===n||h==null&&a.has(b))throw tt(c);return h};let f=null;try{f=o.trim()?Qe(o,p).fn:()=>null}catch{f=null}let d=null;const g=()=>{if(d)return d;d=new Map;for(const c of r.columns){if(c.fieldType==="richText"){const y=String(c.field??c.id);d.set(y,T=>D(T?.[y]));continue}if(c.fieldType==="timer"){const y=String(c.field??c.id);d.set(y,T=>F(T?.[y]));continue}const b=kt(c);if(b){d.set(String(c.field??c.id),b);continue}if(!We.has(String(c.fieldType))||String(c.field??c.id)===n)continue;const h=Q(c,r.columns);typeof h.fieldFn=="function"&&d.set(String(c.field??c.id),h.fieldFn)}return d},S=c=>{const b=g();return!b.size||!c?c:new Proxy(c,{get:(h,y)=>{const T=typeof y=="string"?b.get(y):void 0;if(!T||v>3)return h[y];v+=1;try{return T(h)}finally{v-=1}}})};return{...e,...m(e),fieldFn:c=>f?f(S(c)):"#ERROR",align:e.align??(["number","currency","percent"].includes(t.result)?"right":void 0),formatter:e.formatter??(c=>ve(c.value,t))}}},{id:"createdTime",get label(){return l("fields.typeCreatedTime")},get description(){return l("fields.typeCreatedTimeDescription")},icon:s.createdTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour"},properties:[I(),...Y],fill:(e,t)=>({...e,...m(e),formatter:e.formatter??Z(t)}),newRowValue:()=>L(),onCreate:({rows:e})=>e.map(()=>L())},{id:"lastModifiedTime",get label(){return l("fields.typeLastModifiedTime")},get description(){return l("fields.typeLastModifiedTimeDescription")},icon:s.modifiedTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour",watch:"all"},properties:[...Ce,I(),...Y],fill:(e,t)=>({...e,...m(e),formatter:e.formatter??Z(t)}),newRowValue:()=>L()},{id:"createdBy",get label(){return l("fields.typeCreatedBy")},get description(){return l("fields.typeCreatedByDescription")},icon:s.createdBy,group:"computed",width:160,fill:e=>({...e,...m(e),formatter:e.formatter??(t=>q(t.value))}),newRowValue:()=>ue()?.id??null,cell:O},{id:"lastModifiedBy",get label(){return l("fields.typeLastModifiedBy")},get description(){return l("fields.typeLastModifiedByDescription")},icon:s.modifiedBy,group:"computed",width:160,defaults:{watch:"all"},properties:Ce,fill:e=>({...e,...m(e),formatter:e.formatter??(t=>q(t.value))}),newRowValue:()=>ue()?.id??null,cell:O},{id:"autoNumber",get label(){return l("fields.typeAutoNumber")},get description(){return l("fields.typeAutoNumberDescription")},icon:s.autoNumber,group:"computed",width:100,fill:e=>({...e,...m(e),cellDataType:e.cellDataType??"number"}),newRowValue:({rows:e,field:t})=>e.reduce((r,i)=>Math.max(r,Number(i?.[t])||0),0)+1,onCreate:({rows:e})=>e.map((t,r)=>r+1)},{id:"link",get label(){return l("fields.typeLink")},get description(){return l("fields.typeLinkDescription")},icon:s.link,group:"relation",width:200,defaults:{multiple:!0},properties:[{key:"table",get label(){return l("fields.propTable")},kind:"choice",choices:()=>lt().map(e=>({value:e.id,label:e.name})),get hint(){return l("fields.propTableHint")},alsoSets:()=>({pickFrom:""})},{key:"multiple",get label(){return l("fields.propMultipleRecords")},kind:"checkbox"},{key:"pickFrom",get label(){return l("fields.propPickFrom")},kind:"choice",choices:e=>[{value:"",label:l("fields.pickFromAll")},...(k(e.props.table)?.views?.()??[]).filter(t=>!t.personal&&t.type!=="form").map(t=>({value:t.id,label:t.name}))],visible:e=>!!e.table,get hint(){return l("fields.propPickFromHint")}}],fill:(e,t)=>({...e,editorType:e.editorType??"fieldLink",formatter:e.formatter??(r=>{const i=k(t.table);return z(i,r.value).map(o=>String(o[i.primaryField]??"")).join(", ")}),valueParser:e.valueParser??Ot(t),groupValue:e.groupValue??(r=>it(t.table,r)),groupCopies:!0}),cell:Le},{id:"lookup",get label(){return l("fields.typeLookup")},get description(){return l("fields.typeLookupDescription")},icon:s.lookup,group:"relation",width:180,properties:[X,ge],fill:(e,t,r)=>{const i=J(t,r),o=n=>{const a=Me(i,t.field);return String(a?a({value:n})??"":n)};return{...e,...m(e),fieldSource:()=>i?.table?.fields?.find(n=>n.field===String(t.field)),fieldFn:n=>{if(!i)return[];const a=$(i.table,String(t.field)),p=i.stored;return p?p.records.allLinkedTo(p.field,String(n?.id??"")).map(a):i.rowsOf(n).map(a)},formatter:e.formatter??(n=>Array.isArray(n.value)?n.value.filter(a=>a!=null&&a!=="").map(o).join(", "):n.value==null?"":o(n.value))}}},{id:"rollup",get label(){return l("fields.typeRollup")},get description(){return l("fields.typeRollupDescription")},icon:s.rollup,group:"relation",width:140,defaults:{aggregation:"SUM"},properties:[X,ge,{key:"aggregation",get label(){return l("fields.propAggregation")},kind:"choice",choices:Object.keys(U).map(e=>({value:e,label:e}))},W(K(0,8),e=>["SUM","AVERAGE","MIN","MAX"].includes(e.aggregation))],fill:(e,t,r)=>{const i=J(t,r),o=U[String(t.aggregation)]??U.SUM,n=["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL"].includes(String(t.aggregation)),a=["SUM","AVERAGE","MIN","MAX"].includes(String(t.aggregation)),p=f=>{const d=a?Me(i,t.field,t.precision):void 0;return d?String(d({value:f})??""):B(f,{precision:ye(t,0)})};return{...e,...m(e),...n?{cellDataType:e.cellDataType??"number"}:{},align:e.align??(n?"right":void 0),fieldSource:()=>i?.table?.fields?.find(f=>f.field===String(t.field)),fieldFn:f=>{if(!i)return null;const d=$(i.table,String(t.field)),g=i.stored;if(g){const S=String(f?.id??""),c=Ut[String(t.aggregation)];return c?g.records.total(g.field,S,String(t.field),c)??null:t.aggregation==="COUNTA"||t.aggregation==="COUNTALL"?g.records.total(g.field,S)??null:o(g.records.allLinkedTo(g.field,S).map(d))}return o(i.rowsOf(f).map(d))},formatter:e.formatter??(f=>{const d=n?E(f.value):typeof f.value=="number"?f.value:null;return d==null?String(f.value??""):p(d)})}}},{id:"count",get label(){return l("fields.typeCount")},get description(){return l("fields.typeCountDescription")},icon:s.count,group:"relation",width:90,properties:[X],fill:(e,t,r)=>{const i=J(t,r);return{...e,...m(e),cellDataType:e.cellDataType??"number",formatter:o=>o.value==null?"":Number(o.value).toLocaleString(),fieldFn:o=>{if(!i)return 0;const n=i.stored;return n?n.records.total(n.field,String(o?.id??""))??null:i.rowsOf(o).length}}}},ut];
1
+ import{fillFieldColumn as O}from"./registry.svelte.js";import Ae from"./RatingCell.svelte";import N from"./LinkCell.svelte";import Ve from"./AttachmentCell.svelte";import Fe from"./CheckboxCell.svelte";import re from"./PercentCell.svelte";import B from"./UserCell.svelte";import Ie from"./ButtonCell.svelte";import Le from"./BarcodeCell.svelte";import Oe from"./LinkedRecordsCell.svelte";import Ne from"./RichTextCell.svelte";import Be from"./RichHtmlCell.svelte";import{richPlain as A}from"./rich-html.js";import{toRichHtml as Re}from"./rich-html-write.js";import le from"./SelectCell.svelte";import Ee from"./ChecklistCell.svelte";import He from"./ColorCell.svelte";import{attachmentsText as Ue,parseAttachments as _e}from"./attachments.js";import{dateEditTokens as ze,dateFromParts as R,exactNumber as Ge,formatCurrency as ie,formatDate as E,formatDuration as ne,formatNumber as H,formatPercent as oe,numberFieldShape as ae,numberFromText as je,numberKind as We,parseDateText as $e,parseDuration as V,toNumber as U}from"./format.js";import{BRIGHT as se,CHECKBOX_ICONS as xe,RATING_ICONS as Ke}from"./palette.js";import{COMPUTED_TYPES as Ye,ROLLUPS as _,fieldNameMap as Xe}from"./rollups.js";import{sparklineValues as z,voteCount as ue,voteIds as Ze}from"./vote.js";import qe from"./VoteCell.svelte";import Je from"./TimerCell.svelte";import{timerSeconds as F,timerTotal as Qe}from"./timer.js";import et from"./SparklineCell.svelte";import{compileFormula as tt,isoDate as rt,selfReferenceError as lt}from"./formula.js";import{findFieldUser as ce,getCurrentUser as de,getFieldUsers as G,getLinkedTable as T,idOf as it,linkedRows as j,listLinkedTables as nt,liveLink as ot,recordsNaming as at,resolveLinkId as st,resolveLinkIds as ut}from"./sources.svelte.js";import{splitNames as W}from"./name-list.js";import{linkedFields as ct}from"./linked-fields.js";import{AI_FIELD_TYPE as dt}from"./ai-field.svelte.js";import{CHECKLIST_GROUPS as pe,checklistGroup as pt,checklistSortValue as ft,checklistText as mt,parseChecklist as gt,toChecklist as ht}from"./checklist.js";import{colorSortValue as bt,parseColor as $}from"./color-value.js";import{formatTimeOfDay as yt,parseTimeOfDay as fe,timeSeconds as kt}from"./time-of-day.js";import{bm as l}from"./messages.svelte.js";import{BUTTON_ACTIONS as Tt,buttonAction as b,fillButtonTokens as wt,isLinkTemplate as vt}from"./button.js";import{recordActionsFor as me}from"./record-actions.js";const St=new Set(["user","createdBy","lastModifiedBy"]);function Mt(e){const t=String(e.field??e.id),r=o=>o.length===1?o[0]:o;if(St.has(String(e.fieldType)))return o=>{const n=o?.[t];return n==null||n===""?n:r((Array.isArray(n)?n:[n]).map(a=>ce(a)?.name??a))};if(e.fieldType!=="link")return null;const i=e.fieldProps?.table;return o=>{const n=o?.[t],a=T(i);if(!a||n==null||n==="")return n;const p=x(a,a.primaryField),d=new Map(j(a,n).map(f=>[it(a,f),p(f)]));return r((Array.isArray(n)?n:[n]).map(f=>d.get(String(f))??f))}}const ge=new WeakMap;let M=0;function x(e,t){const r=n=>n?.[t];if(!e?.fields?.length)return r;let i=ge.get(e.fields);if(i||ge.set(e.fields,i=new Map),!i.has(t)){const n=ct(e).find(p=>p.def.field===t),a=n?.def.fieldType==="timer"?p=>F(p?.[t]):null;i.set(t,a??n?.def.fieldFn??null)}const o=i.get(t);return o?n=>{if(M>3)return r(n);M+=1;try{return o(n)}finally{M-=1}}:r}const s={text:"M4 6h16M4 12h10M4 18h7",longText:"M4 6h16M4 10h16M4 14h16M4 18h10",richText:"M6 4h7a4 4 0 0 1 0 8H6zM6 12h8a4 4 0 0 1 0 8H6zM6 4v16",vote:"M12 19V5M5 12l7-7 7 7",sparkline:"M3 17l5-6 4 4 8-9",number:"M9 4 7 20M17 4l-2 16M4 9h16M3 15h16",currency:"M12 3v18M16 7.5C16 5.6 14.2 4.5 12 4.5S8 5.6 8 7.5s1.8 2.7 4 3.5 4 1.6 4 3.5-1.8 3-4 3-4-1.1-4-3",percent:"M19 5 5 19M7 7h.01M17 17h.01",date:"M4 6h16v14H4zM4 10h16M8 3v4M16 3v4",duration:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4l3 2",timer:"M12 7a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM12 10v4l2.5 1.5M9.5 2.5h5M12 2.5V5",checkbox:"M4 4h16v16H4zM8 12l3 3 5-6",singleSelect:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM8 11l4 4 4-4",multiSelect:"M3 7h11M3 12h11M3 17h11M17 6l2 2 3-3M17 16l2 2 3-3",rating:"M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3 6.5 20.2l1-6.2L3 9.6l6.2-.9z",url:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1",email:"M3 6h18v12H3zM3 7l9 6 9-6",phone:"M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2",attachment:"M20 11.5 12.3 19a5 5 0 0 1-7.1-7.1l7.8-7.8a3.3 3.3 0 0 1 4.7 4.7L9.9 16.6a1.7 1.7 0 0 1-2.4-2.4l7.1-7",user:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0",createdTime:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4h4",modifiedTime:"M4 12a8 8 0 1 0 2.3-5.7M4 4v4h4M12 8v4l3 2",createdBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M19 15v6M16 18h6",modifiedBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M16 21l5-5-2-2-5 5v2z",autoNumber:"M5 7h3v10M11 9a2 2 0 1 1 4 0c0 2-4 3-4 6h4M18 7h2v10",barcode:"M4 5v14M7 5v14M10 5v14M13 5v14M15 5v14M18 5v14M20 5v14",button:"M4 7h16v10H4zM9 12h6",formula:"M7 20c2 0 2.5-2 3-5l2-10c.5-2 1.5-2 3-2M8 9h7",link:"M9 7H6a5 5 0 0 0 0 10h3M15 7h3a5 5 0 0 1 0 10h-3M8 12h8",lookup:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4M8 11h6",rollup:"M6 4h12L12 12l6 8H6",count:"M5 5h14v14H5zM9 9v6M12 9v6M15 9v6",checklist:"M3.5 6l1.5 1.5L7.5 5M3.5 12l1.5 1.5 2.5-2.5M3.5 18l1.5 1.5 2.5-2.5M11 6h9M11 12h9M11 18h9",color:"M12 3a9 9 0 1 0 0 18c1 0 1.6-.7 1.6-1.6 0-1-.8-1.4-.8-2.3 0-1 .8-1.7 1.8-1.7H17a4 4 0 0 0 4-4C21 6.6 17 3 12 3zM7.5 12h.01M9.5 7.5h.01M14.5 7.5h.01",timeOfDay:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7v5l-3 2M12 3v2M21 12h-2M12 21v-2M3 12h2"},u=(e,t)=>({value:e,get label(){return l(t)}}),Ct={link:"fields.buttonActionLink",automation:"fields.buttonActionAutomation",update:"fields.buttonActionUpdate",template:"fields.buttonActionTemplate",recordAction:"fields.buttonActionRecordAction",copy:"fields.buttonActionCopy",duplicate:"fields.buttonActionDuplicate",delete:"fields.buttonActionDelete",open:"fields.buttonActionOpen"};function Pt(e){const t=!!e.ctrl?.props?.baseButton,r=b(e.props),i=o=>o===r||o==="link"||o==="copy"?!0:t?o==="template"?(e.ctrl?.props?.baseRecordTemplates?.()??[]).length>0:o==="recordAction"?me(e.ctrl?.props?.baseTableId).length>0:!0:!1;return Tt.filter(i).map(o=>u(o,Ct[o]))}const he=e=>e?{visible:e}:{},Dt={key:"separators",get label(){return l("fields.propSeparators")},kind:"choice",choices:[u("local","fields.choiceLocal"),{value:"comma-period",label:"1,000,000.00"},{value:"period-comma",label:"1.000.000,00"},{value:"space-comma",label:"1 000 000,00"},{value:"space-period",label:"1 000 000.00"}]},At={key:"showThousands",get label(){return l("fields.propShowThousands")},kind:"checkbox"},Vt=e=>({key:"abbreviation",get label(){return l("fields.propAbbreviation")},kind:"choice",choices:[u("none","fields.choiceNone"),u("thousand","fields.choiceThousand"),u("million","fields.choiceMillion"),u("billion","fields.choiceBillion")],...he(e)}),Ft={key:"allowNegative",get label(){return l("fields.propAllowNegative")},kind:"checkbox"},w={key:"default",get label(){return l("fields.propDefault")},kind:"default",get hint(){return l("fields.propDefaultHint")}},K=(e,t)=>Array.from({length:t-e+1},(r,i)=>{const o=e+i;return{value:String(o),label:o===0?"1":`1.${"0".repeat(o)}`}}),Y=(e,t)=>({key:"precision",get label(){return l("fields.propPrecision")},kind:"choice",choices:e,visible:t}),It=[u("local","fields.choiceLocal"),u("friendly","fields.choiceFriendly"),u("us","fields.choiceUs"),u("european","fields.choiceEuropean"),u("iso","fields.choiceIso")],I=e=>({key:"dateFormat",get label(){return l("fields.propDateFormat")},kind:"choice",choices:It,...he(e)}),be=[u("12hour","fields.choice12Hour"),u("24hour","fields.choice24Hour")],X=[{key:"time",get label(){return l("fields.propIncludeTime")},kind:"checkbox"},{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:be,visible:e=>!!e.time},{key:"gmt",get label(){return l("fields.propGmt")},kind:"checkbox",visible:e=>!!e.time},{key:"showTimeZone",get label(){return l("fields.propShowTimeZone")},kind:"checkbox",visible:e=>!!e.time}],Lt=e=>e.columns.filter(t=>t.fieldType==="link").map(t=>({value:String(t.id??t.field),label:String(t.header??t.field)})),Z={key:"linkField",get label(){return l("fields.propLinkField")},kind:"choice",choices:Lt,get hint(){return l("fields.propLinkFieldHint")}},Ot=e=>{const t=e.columns.find(o=>String(o.id??o.field)===e.props.linkField),r=T(t?.fieldProps?.table);return r?(r.fields??[{field:r.primaryField,header:r.primaryField}]).map(o=>({value:o.field,label:o.header})):[]},ye={key:"field",get label(){return l("fields.propLinkedField")},kind:"choice",choices:Ot,visible:e=>!!e.linkField},C={key:"color",get label(){return l("fields.propColor")},kind:"color",palette:se},ke={key:"options",get label(){return l("fields.propOptions")},kind:"options"},Te=(e,t=0)=>{const r=Number(e.precision);return Number.isInteger(r)&&r>=0&&r<=8?r:t},Nt=e=>({precision:e.format==="integer"?0:Te(e,e.format==="decimal"?1:0),separators:e.separators,showThousands:e.showThousands!==!1,abbreviation:e.abbreviation}),Bt=(e,t)=>r=>{const i=typeof r.rawInput=="string"?r.rawInput:r.newValue;if(typeof i=="number"||i==null)return i;if(String(i).trim()==="")return null;const o=je(String(i),e,t);return o??r.oldValue},Rt=(e,t)=>t.allowNegative===!1&&!e.validate?{rejectInvalid:!0,validate:r=>Number(r.value)<0?l("fields.negativeNotAllowed"):null}:{},Et=(e,t)=>{const r={precision:ae(e,t).places,separators:t.separators,showThousands:t.showThousands!==!1,abbreviation:e==="percent"?void 0:t.abbreviation};return i=>{const o=Ge(i.value);return o==null?"":e==="currency"?ie(o,{...r,symbol:t.symbol,symbolPosition:t.symbolPosition}):e==="percent"?oe(o,{...r,points:t.points}):H(o,r)}},q=(e,t,r)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",align:e.align??(r==="percent"&&t.showBar?"left":"right"),...Rt(e,t),valueParser:e.valueParser??Bt(r,t),formatter:e.formatter??Et(r,t),sortValue:e.sortValue??U}),P=e=>Array.isArray(e.options)?e.options.map(t=>({value:t.value,label:t.label??String(t.value),...t.color?{color:t.color}:{}})):[],we=(e,t)=>{const r=new Map;for(const n of P(e))r.set(String(n.value).toLowerCase(),n.value),r.set(String(n.label).toLowerCase(),n.value);const i=n=>r.get(n.toLowerCase()),o=r.size===0;return n=>{if(typeof n.rawInput!="string")return n.newValue;const a=t?W(n.rawInput):n.rawInput.split(/\n/).map(d=>d.trim()).filter(Boolean);if(o)return t?[...new Set(a)]:a[0]??null;const p=a.map(i).filter(d=>d!==void 0);return a.length&&!p.length?n.oldValue:t?[...new Set(p)]:a.length?i(a[0])===void 0?n.oldValue:i(a[0]):null}},ve=e=>{const t=new Map(P(e).map(r=>[String(r.value),r.label]));return r=>(Array.isArray(r.value)?r.value:r.value==null||r.value===""?[]:[r.value]).map(i=>t.get(String(i))??String(i)).join(", ")},Ht=e=>{const t=new Map(P(e).map((r,i)=>[String(r.value),i]));return r=>r==null||r===""?null:t.get(String(r))??t.size},Se=Xe,y=e=>({editable:e.editable??!1}),J=e=>t=>E(t.value,e),D=e=>e.oldValue!=null&&typeof e.oldValue!="string"&&String(e.oldValue)===e.newValue?e.oldValue:e.newValue,Ut=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;if(r==null||typeof r=="string"&&r.trim()==="")return null;if(r instanceof Date)return e.time?r.toISOString():R({y:r.getFullYear(),mo:r.getMonth()+1,d:r.getDate(),time:null},e);const i=String(r).trim();if(/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?/.test(i)){if(!e.time)return i.slice(0,10);if(i.length>10&&i[10]==="T")return i}const o=$e(i,e);return o?R(o,e,t.oldValue):t.oldValue},Q=e=>(Array.isArray(e)?e:e==null||e===""?[]:[e]).map(t=>ce(t)?.name??String(t)).join(", "),Me=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=G(),i=a=>{const p=a.toLowerCase();return r.find(f=>f.id.toLowerCase()===p||f.name.toLowerCase()===p||f.email?.toLowerCase()===p)?.id??(r.length?void 0:a)},o=e?W(t.rawInput):t.rawInput.split(/\n/).map(a=>a.trim()).filter(Boolean),n=o.map(i).filter(a=>a!==void 0);return o.length&&!n.length?t.oldValue:e?[...new Set(n)]:o.length?n[0]:null},_t=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=T(e.table);if(!r)return t.newValue;const i=W(t.rawInput),o=ut(r,i);if(r.records&&r.resolveNames&&t.data&&t.columnId){const n=i.filter(a=>st(r,a)==null);n.length&&r.resolveNames({row:t.data,columnId:t.columnId,multiple:e.multiple!==!1},n,o)}return i.length&&!o.length?t.oldValue:e.multiple===!1?o.slice(0,1):o},zt=e=>typeof e.rawInput=="string"?e.rawInput.trim()?gt(e.rawInput):null:Array.isArray(e.newValue)?ht(e.newValue):e.newValue??null,Gt=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=t.rawInput.trim();if(!r)return null;const i=Number(r);return Number.isInteger(i)&&i>=0&&i<=Number(e.max??5)?i:t.oldValue},jt=e=>{const t=typeof e.rawInput=="string"?e.rawInput:e.newValue;return t==null||String(t).trim()===""?null:$(t)??e.oldValue},Wt=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;return r==null||typeof r=="string"&&r.trim()===""?null:fe(r,{seconds:!!e.showSeconds})??t.oldValue};function ee(e,t){if(e==null)return"";if(Array.isArray(e))return e.map(r=>ee(r,t)).join(", ");if(e instanceof Date)return E(e,t);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(t.result==="currency"||t.result==="percent"||t.result==="number"){const r=t.result,i={...Nt(t),precision:ae(r,{precision:t.precision}).places};return r==="currency"?ie(e,{...i,symbol:t.symbol}):r==="percent"?oe(e,i):H(e,i)}return String(Math.round(e*1e10)/1e10)}if(t.result==="date"){const r=rt(String(e));if(r)return E(r,t)}return String(e)}const te=(e,t)=>{const r=t.columns.find(n=>String(n.id??n.field)===e.linkField);if(!r)return null;const i=r.fieldProps?.table,o=r.fieldProps?.inverse;return{key:String(r.field??r.id),get table(){return T(i)},rowsOf(n){const a=T(i),p=String(r.field??r.id);return a&&o&&!a.records&&n?.[p]===void 0?at(a,o,String(n?.id??"")):j(a,n?.[p])},get stored(){const n=T(i)?.records;return n&&o&&n.stores(o)?{records:n,field:o}:null}}},$t={SUM:"sum",AVERAGE:"avg",MIN:"min",MAX:"max",COUNT:"count"},Ce=new WeakMap;function Pe(e,t,r){const i=e?.table?.fields;if(!i)return;let o=Ce.get(i);o||Ce.set(i,o=new Map);const n=`${String(t)}|${r??""}`;if(o.has(n))return o.get(n);const a=i.find(d=>d.field===String(t)),p=a?.fieldType?O({field:a.field,fieldType:a.fieldType,fieldProps:{...a.fieldProps,...r==null?{}:{precision:r}}}).formatter:void 0;return o.set(n,p),p}const L=()=>new Date().toISOString(),xt=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0}),Kt=(e,t)=>{const r=i=>i?pe.indexOf(i):pe.length;return r(e)-r(t)},De=[{key:"watch",get label(){return l("fields.propWatch")},kind:"segmented",choices:[u("all","fields.choiceAllFields"),u("specific","fields.choiceSpecificFields")]},{key:"watchFields",get label(){return l("fields.propWatchFields")},kind:"columns",visible:e=>e.watch==="specific"}];export const BUILTIN_FIELD_TYPES=[{id:"text",get label(){return l("fields.typeText")},get description(){return l("fields.typeTextDescription")},icon:s.text,group:"basic",properties:[w],fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D})},{id:"longText",get label(){return l("fields.typeLongText")},get description(){return l("fields.typeLongTextDescription")},icon:s.longText,group:"basic",width:260,properties:[{key:"richText",get label(){return l("fields.propMarkdown")},kind:"checkbox",get hint(){return l("fields.propMarkdownHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldLongText",valueParser:e.valueParser??D}),cell:Ne,hasCell:e=>!!e.richText},{id:"richText",get label(){return l("fields.typeRichText")},get description(){return l("fields.typeRichTextDescription")},icon:s.richText,group:"basic",width:280,defaults:{toolbar:"standard"},properties:[{key:"toolbar",get label(){return l("fields.propToolbar")},kind:"segmented",choices:[u("standard","fields.choiceStandard"),u("full","fields.choiceFull")],get hint(){return l("fields.propToolbarHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldRichText",formatter:e.formatter??(t=>A(t.value)),sortComparator:e.sortComparator??((t,r)=>xt.compare(A(t),A(r))),valueParser:e.valueParser??(t=>Re(t.newValue))}),cell:Be},{id:"attachment",get label(){return l("fields.typeAttachment")},get description(){return l("fields.typeAttachmentDescription")},icon:s.attachment,group:"basic",width:180,defaults:{maxFiles:20},properties:[{key:"accept",get label(){return l("fields.propAccept")},kind:"text",get placeholder(){return l("fields.propAcceptPlaceholder")}},{key:"maxFiles",get label(){return l("fields.propMaxFiles")},kind:"number",min:1,max:100}],fill:(e,t)=>({...e,editorType:e.editorType??"attachment",formatter:e.formatter??(r=>Ue(r.value)),valueParser:e.valueParser??(r=>_e(r.newValue,t))}),cell:Ve},{id:"checkbox",get label(){return l("fields.typeCheckbox")},get description(){return l("fields.typeCheckboxDescription")},icon:s.checkbox,group:"basic",width:90,defaults:{icon:"check",color:"#20c933"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:xe},C,w],fill:e=>({...e,editorType:e.editorType??"checkbox",align:e.align??"center",toggleOnSecondClick:e.toggleOnSecondClick??!0}),cell:Fe},{id:"singleSelect",get label(){return l("fields.typeSingleSelect")},get description(){return l("fields.typeSingleSelectDescription")},icon:s.singleSelect,group:"basic",width:140,defaults:{options:[]},properties:[ke,w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorOptions:e.editorOptions??P(t),formatter:e.formatter??ve(t),valueParser:e.valueParser??we(t,!1),sortValue:e.sortValue??Ht(t)}),cell:le},{id:"multiSelect",get label(){return l("fields.typeMultiSelect")},get description(){return l("fields.typeMultiSelectDescription")},icon:s.multiSelect,group:"basic",width:200,defaults:{options:[]},properties:[ke,w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorMultiple:e.editorMultiple??!0,editorOptions:e.editorOptions??P(t),formatter:e.formatter??ve(t),valueParser:e.valueParser??we(t,!0)}),cell:le},{id:"user",get label(){return l("fields.typeUser")},get description(){return l("fields.typeUserDescription")},icon:s.user,group:"basic",width:170,properties:[{key:"multiple",get label(){return l("fields.propMultipleUsers")},kind:"checkbox"},w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",valueParser:e.valueParser??Me(!!t.multiple),editorMultiple:e.editorMultiple??!!t.multiple,editorOptions:e.editorOptions??G().map(r=>({value:r.id,label:r.name})),formatter:e.formatter??(r=>Q(r.value))}),cell:B},{id:"date",get label(){return l("fields.typeDate")},get description(){return l("fields.typeDateDescription")},icon:s.date,group:"basic",width:150,defaults:{dateFormat:"local",timeFormat:"12hour"},properties:[I(),...X,{key:"defaultToday",get label(){return l("fields.propDefaultToday")},kind:"checkbox"}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??(t.time?"date":"dateString"),editorType:e.editorType??"fieldDate",editorFormatString:e.editorFormatString??ze(t),formatter:e.formatter??J(t),valueParser:e.valueParser??Ut(t)}),newRowValue:({props:e})=>{if(!e.defaultToday)return;if(e.time)return L();const t=new Date;return R({y:t.getFullYear(),mo:t.getMonth()+1,d:t.getDate(),time:null},{})}},{id:"phone",get label(){return l("fields.typePhone")},get description(){return l("fields.typePhoneDescription")},icon:s.phone,group:"basic",fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"email",get label(){return l("fields.typeEmail")},get description(){return l("fields.typeEmailDescription")},icon:s.email,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"url",get label(){return l("fields.typeUrl")},get description(){return l("fields.typeUrlDescription")},icon:s.url,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??D}),cell:N},{id:"barcode",get label(){return l("fields.typeBarcode")},get description(){return l("fields.typeBarcodeDescription")},icon:s.barcode,group:"basic",width:160,fill:e=>({...e,editorType:e.editorType??"text",formatter:e.formatter??(t=>t.value&&typeof t.value=="object"?String(t.value.text??""):String(t.value??""))}),cell:Le},{id:"button",get label(){return l("fields.typeButton")},get description(){return l("fields.typeButtonDescription")},icon:s.button,group:"basic",width:120,defaults:{label:"Open",color:"#2d7ff9",action:"link"},properties:[{key:"label",get label(){return l("fields.propButtonLabel")},kind:"text",get placeholder(){return l("fields.propButtonLabelPlaceholder")}},{key:"color",get label(){return l("fields.propButtonStyle")},kind:"color",palette:se},{key:"action",get label(){return l("fields.propButtonAction")},kind:"choice",choices:Pt},{key:"url",get label(){return l("fields.propButtonUrl")},kind:"text",get placeholder(){return l("fields.propButtonUrlPlaceholder")},get hint(){return l("fields.propButtonUrlHint")},visible:e=>b(e)==="link"},{key:"values",get label(){return l("fields.propButtonValues")},kind:"recordValues",get hint(){return l("fields.propButtonValuesHint")},visible:e=>b(e)==="update"},{key:"template",get label(){return l("fields.propButtonTemplate")},kind:"choice",get hint(){return l("fields.propButtonTemplateHint")},visible:e=>b(e)==="template",choices:e=>(e.ctrl?.props?.baseRecordTemplates?.()??[]).map(t=>({value:t.id,label:t.name}))},{key:"recordAction",get label(){return l("fields.propButtonRecordAction")},kind:"choice",visible:e=>b(e)==="recordAction",choices:e=>me(e.ctrl?.props?.baseTableId).map(t=>({value:t.id,label:t.label}))},{key:"copy",get label(){return l("fields.propButtonCopy")},kind:"text",get placeholder(){return l("fields.propButtonCopyPlaceholder")},get hint(){return l("fields.propButtonCopyHint")},visible:e=>b(e)==="copy"},{key:"doneLabel",get label(){return l("fields.propButtonDoneLabel")},kind:"text",get placeholder(){return l("fields.propButtonDoneLabelPlaceholder")},get hint(){return l("fields.propButtonDoneLabelHint")},visible:e=>b(e)==="update"||b(e)==="template"},{key:"when",get label(){return l("fields.propButtonWhen")},kind:"filter",get hint(){return l("fields.propButtonWhenHint")}},{key:"ask",get label(){return l("fields.propButtonAsk")},kind:"checkbox",visible:e=>b(e)!=="delete"},{key:"askText",get label(){return l("fields.propButtonAskText")},kind:"text",get placeholder(){return l("fields.buttonAskDefault")},visible:e=>!!e.ask&&b(e)!=="delete"}],fill:(e,t,r)=>{const i=Se(r.columns),o=(d,f,h)=>{if(!d.trim())return null;if(!f)return m=>m?wt(d,m,i,h):"";const c=O({id:`${String(e.id??e.field)}__button`,field:`__button_${String(e.field??e.id)}`,fieldType:"formula",fieldProps:{formula:d}},r.columns).fieldFn;return m=>{if(!c||!m)return"";const g=c(m);return g==="#ERROR"?"":ee(g,{})}},n=String(t.url??""),a=String(t.copy??""),p=a.trim().startsWith("=");return{...e,...y(e),sortable:e.sortable??!1,__fieldNames:i,__buttonLink:o(n,!!n.trim()&&!vt(n),!0),__buttonCopy:o(p?a.trim().slice(1):a,p,!1)}},cell:Ie},{id:"checklist",get label(){return l("fields.typeChecklist")},get description(){return l("fields.typeChecklistDescription")},icon:s.checklist,group:"basic",width:150,fill:e=>({...e,editorType:e.editorType??"fieldChecklist",formatter:e.formatter??(t=>mt(t.value)),valueParser:e.valueParser??zt,sortValue:e.sortValue??ft,groupValue:e.groupValue??pt,groupOrder:e.groupOrder??Kt}),cell:Ee},{id:"color",get label(){return l("fields.typeColor")},get description(){return l("fields.typeColorDescription")},icon:s.color,group:"basic",width:130,properties:[w],fill:e=>({...e,editorType:e.editorType??"fieldColor",formatter:e.formatter??(t=>$(t.value)??String(t.value??"")),valueParser:e.valueParser??jt,sortValue:e.sortValue??bt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:$(e.default),cell:He},{id:"number",get label(){return l("fields.typeNumber")},get description(){return l("fields.typeNumberDescription")},icon:s.number,group:"number",width:120,defaults:{format:"decimal",precision:1,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0,symbol:"$",symbolPosition:"before",showBar:!1,points:!1,step:1},properties:[{key:"format",get label(){return l("fields.propFormat")},kind:"segmented",choices:[u("integer","fields.choiceInteger"),u("decimal","fields.choiceDecimal"),u("currency","fields.choiceCurrency"),u("percent","fields.choicePercent")],alsoSets:e=>({precision:e==="decimal"?1:e==="currency"?2:0})},{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$, €, £, ¥, CHF, kr",visible:e=>e.format==="currency"},{key:"symbolPosition",get label(){return l("fields.propSymbolPosition")},kind:"segmented",visible:e=>e.format==="currency",choices:[u("before","fields.choiceBefore"),u("after","fields.choiceAfter")]},Y(K(0,8),e=>e.format!=="integer"),{key:"step",get label(){return l("fields.propStep")},kind:"number",min:0,get hint(){return l("fields.propStepHint")}},Dt,At,Vt(e=>e.format!=="percent"),Ft,{key:"showBar",get label(){return l("fields.propShowBar")},kind:"checkbox",visible:e=>e.format==="percent"},{key:"points",get label(){return l("fields.propPoints")},kind:"checkbox",visible:e=>e.format==="percent"},w],fill:(e,t)=>q(e,t,We("number",t)),cell:re,hasCell:e=>e.format==="percent"&&!!e.showBar},{id:"currency",get label(){return l("fields.typeCurrency")},get description(){return l("fields.typeCurrencyDescription")},icon:s.currency,group:"number",width:120,defaults:{symbol:"$",symbolPosition:"before",precision:2,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0},editAs:{type:"number",props:{format:"currency"}},fill:(e,t)=>q(e,t,"currency")},{id:"percent",get label(){return l("fields.typePercent")},get description(){return l("fields.typePercentDescription")},icon:s.percent,group:"number",width:110,defaults:{precision:0,separators:"local",showThousands:!0,allowNegative:!0,points:!1},editAs:{type:"number",props:{format:"percent"}},fill:(e,t)=>q(e,t,"percent"),cell:re,hasCell:e=>!!e.showBar},{id:"duration",get label(){return l("fields.typeDuration")},get description(){return l("fields.typeDurationDescription")},icon:s.duration,group:"number",width:110,defaults:{durationFormat:"h:mm"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"},{value:"h:mm:ss.S",label:"h:mm:ss.S"},{value:"h:mm:ss.SS",label:"h:mm:ss.SS"},{value:"h:mm:ss.SSS",label:"h:mm:ss.SSS"}]}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",formatter:e.formatter??(r=>{const i=U(r.value);return i==null?"":ne(i,t.durationFormat)}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:typeof r.newValue=="number"?r.newValue:V(r.newValue))})},{id:"timeOfDay",get label(){return l("fields.typeTimeOfDay")},get description(){return l("fields.typeTimeOfDayDescription")},icon:s.timeOfDay,group:"number",width:120,defaults:{timeFormat:"12hour",showSeconds:!1},properties:[{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:be},{key:"showSeconds",get label(){return l("fields.propShowSeconds")},kind:"checkbox"},w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldTime",formatter:e.formatter??(r=>yt(r.value,t)),valueParser:e.valueParser??Wt(t),sortValue:e.sortValue??kt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:fe(e.default,{seconds:!!e.showSeconds})},{id:"rating",get label(){return l("fields.typeRating")},get description(){return l("fields.typeRatingDescription")},icon:s.rating,group:"number",width:130,defaults:{max:5,icon:"star",color:"#fcb400"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:Ke},C,{key:"max",get label(){return l("fields.propMaximum")},kind:"choice",choices:Array.from({length:10},(e,t)=>({value:String(t+1),label:String(t+1)}))}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",align:e.align??"left",editorType:e.editorType??"fieldRating",valueParser:e.valueParser??Gt(t)}),cell:Ae},{id:"timer",get label(){return l("fields.typeTimer")},get description(){return l("fields.typeTimerDescription")},icon:s.timer,group:"number",width:130,defaults:{durationFormat:"h:mm:ss"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"}]},C],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldTimer",align:e.align??"left",sortValue:e.sortValue??(r=>F(r)),formatter:e.formatter??(r=>{const i=F(r.value);return i==null?"":ne(i,t.durationFormat??"h:mm:ss")}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:r.newValue==null||r.newValue===""?null:typeof r.newValue=="number"||typeof r.newValue=="object"&&Qe(r.newValue)!=null?r.newValue:V(r.newValue))}),cell:Je},{id:"vote",get label(){return l("fields.typeVote")},get description(){return l("fields.typeVoteDescription")},icon:s.vote,group:"basic",width:100,defaults:{icon:"up"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"segmented",choices:[u("up","fields.choiceArrow"),u("thumb","fields.choiceThumb"),u("heart","fields.choiceHeart")]},C],fill:e=>({...e,editorType:e.editorType??"fieldVote",editorOptions:e.editorOptions??G().map(t=>({value:t.id,label:t.name})),align:e.align??"left",sortValue:e.sortValue??(t=>ue(t)),formatter:e.formatter??(t=>String(ue(t.value))),valueParser:e.valueParser??(t=>Ze(Me(!0)(t)))}),newRowValue:()=>[],cell:qe},{id:"sparkline",get label(){return l("fields.typeSparkline")},get description(){return l("fields.typeSparklineDescription")},icon:s.sparkline,group:"number",width:160,defaults:{chart:"line"},properties:[{key:"chart",get label(){return l("fields.propChart")},kind:"segmented",choices:[u("line","fields.choiceLine"),u("area","fields.choiceArea"),u("bar","fields.choiceColumns")]},C,{key:"showLast",get label(){return l("fields.propShowLast")},kind:"checkbox"}],fill:e=>({...e,formatter:e.formatter??(t=>z(t.value).join(", ")),valueParser:e.valueParser??(t=>{const r=z(t.newValue);return r.length?r:null}),sortValue:e.sortValue??(t=>z(t).at(-1)??null)}),cell:et},{id:"formula",get label(){return l("fields.typeFormula")},get description(){return l("fields.typeFormulaDescription")},icon:s.formula,group:"computed",width:160,defaults:{formula:"",result:"auto"},properties:[{key:"formula",get label(){return l("fields.propFormula")},kind:"formula"},{key:"result",get label(){return l("fields.propResult")},kind:"choice",choices:[u("auto","fields.choiceAsComputed"),u("number","fields.choiceNumber"),u("currency","fields.choiceCurrency"),u("percent","fields.choicePercent"),u("date","fields.choiceDate")]},Y(K(0,8),e=>["number","currency","percent"].includes(e.result)),{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$",visible:e=>e.result==="currency"},I(e=>e.result==="date")],fill:(e,t,r)=>{const i=Se(r.columns),o=String(t.formula??""),n=String(e.field??e.id),a=new Set([n.toLowerCase(),typeof e.header=="string"?e.header.trim().toLowerCase():""].filter(Boolean)),p=c=>{const m=c.trim().toLowerCase(),g=i[m]??null;if(g===n||g==null&&a.has(m))throw lt(c);return g};let d=null;try{d=o.trim()?tt(o,p).fn:()=>null}catch{d=null}let f=null;const h=()=>{if(f)return f;f=new Map;for(const c of r.columns){if(c.fieldType==="richText"){const k=String(c.field??c.id);f.set(k,S=>A(S?.[k]));continue}if(c.fieldType==="timer"){const k=String(c.field??c.id);f.set(k,S=>F(S?.[k]));continue}const m=Mt(c);if(m){f.set(String(c.field??c.id),m);continue}if(!Ye.has(String(c.fieldType))||String(c.field??c.id)===n)continue;const g=O(c,r.columns);typeof g.fieldFn=="function"&&f.set(String(c.field??c.id),g.fieldFn)}return f},v=c=>{const m=h();return!m.size||!c?c:new Proxy(c,{get:(g,k)=>{const S=typeof k=="string"?m.get(k):void 0;if(!S||M>3)return g[k];M+=1;try{return S(g)}finally{M-=1}}})};return{...e,...y(e),fieldFn:c=>d?d(v(c)):"#ERROR",align:e.align??(["number","currency","percent"].includes(t.result)?"right":void 0),formatter:e.formatter??(c=>ee(c.value,t))}}},{id:"createdTime",get label(){return l("fields.typeCreatedTime")},get description(){return l("fields.typeCreatedTimeDescription")},icon:s.createdTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour"},properties:[I(),...X],fill:(e,t)=>({...e,...y(e),formatter:e.formatter??J(t)}),newRowValue:()=>L(),onCreate:({rows:e})=>e.map(()=>L())},{id:"lastModifiedTime",get label(){return l("fields.typeLastModifiedTime")},get description(){return l("fields.typeLastModifiedTimeDescription")},icon:s.modifiedTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour",watch:"all"},properties:[...De,I(),...X],fill:(e,t)=>({...e,...y(e),formatter:e.formatter??J(t)}),newRowValue:()=>L()},{id:"createdBy",get label(){return l("fields.typeCreatedBy")},get description(){return l("fields.typeCreatedByDescription")},icon:s.createdBy,group:"computed",width:160,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>de()?.id??null,cell:B},{id:"lastModifiedBy",get label(){return l("fields.typeLastModifiedBy")},get description(){return l("fields.typeLastModifiedByDescription")},icon:s.modifiedBy,group:"computed",width:160,defaults:{watch:"all"},properties:De,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>de()?.id??null,cell:B},{id:"autoNumber",get label(){return l("fields.typeAutoNumber")},get description(){return l("fields.typeAutoNumberDescription")},icon:s.autoNumber,group:"computed",width:100,fill:e=>({...e,...y(e),cellDataType:e.cellDataType??"number"}),newRowValue:({rows:e,field:t})=>e.reduce((r,i)=>Math.max(r,Number(i?.[t])||0),0)+1,onCreate:({rows:e})=>e.map((t,r)=>r+1)},{id:"link",get label(){return l("fields.typeLink")},get description(){return l("fields.typeLinkDescription")},icon:s.link,group:"relation",width:200,defaults:{multiple:!0},properties:[{key:"table",get label(){return l("fields.propTable")},kind:"choice",choices:()=>nt().map(e=>({value:e.id,label:e.name})),get hint(){return l("fields.propTableHint")},alsoSets:()=>({pickFrom:""})},{key:"multiple",get label(){return l("fields.propMultipleRecords")},kind:"checkbox"},{key:"pickFrom",get label(){return l("fields.propPickFrom")},kind:"choice",choices:e=>[{value:"",label:l("fields.pickFromAll")},...(T(e.props.table)?.views?.()??[]).filter(t=>!t.personal&&t.type!=="form").map(t=>({value:t.id,label:t.name}))],visible:e=>!!e.table,get hint(){return l("fields.propPickFromHint")}}],fill:(e,t)=>({...e,editorType:e.editorType??"fieldLink",formatter:e.formatter??(r=>{const i=T(t.table);return j(i,r.value).map(o=>String(o[i.primaryField]??"")).join(", ")}),valueParser:e.valueParser??_t(t),groupValue:e.groupValue??(r=>ot(t.table,r)),groupCopies:!0}),cell:Oe},{id:"lookup",get label(){return l("fields.typeLookup")},get description(){return l("fields.typeLookupDescription")},icon:s.lookup,group:"relation",width:180,properties:[Z,ye],fill:(e,t,r)=>{const i=te(t,r),o=n=>{const a=Pe(i,t.field);return String(a?a({value:n})??"":n)};return{...e,...y(e),fieldSource:()=>i?.table?.fields?.find(n=>n.field===String(t.field)),fieldFn:n=>{if(!i)return[];const a=x(i.table,String(t.field)),p=i.stored;return p?p.records.allLinkedTo(p.field,String(n?.id??"")).map(a):i.rowsOf(n).map(a)},formatter:e.formatter??(n=>Array.isArray(n.value)?n.value.filter(a=>a!=null&&a!=="").map(o).join(", "):n.value==null?"":o(n.value))}}},{id:"rollup",get label(){return l("fields.typeRollup")},get description(){return l("fields.typeRollupDescription")},icon:s.rollup,group:"relation",width:140,defaults:{aggregation:"SUM"},properties:[Z,ye,{key:"aggregation",get label(){return l("fields.propAggregation")},kind:"choice",choices:Object.keys(_).map(e=>({value:e,label:e}))},Y(K(0,8),e=>["SUM","AVERAGE","MIN","MAX"].includes(e.aggregation))],fill:(e,t,r)=>{const i=te(t,r),o=_[String(t.aggregation)]??_.SUM,n=["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL"].includes(String(t.aggregation)),a=["SUM","AVERAGE","MIN","MAX"].includes(String(t.aggregation)),p=d=>{const f=a?Pe(i,t.field,t.precision):void 0;return f?String(f({value:d})??""):H(d,{precision:Te(t,0)})};return{...e,...y(e),...n?{cellDataType:e.cellDataType??"number"}:{},align:e.align??(n?"right":void 0),fieldSource:()=>i?.table?.fields?.find(d=>d.field===String(t.field)),fieldFn:d=>{if(!i)return null;const f=x(i.table,String(t.field)),h=i.stored;if(h){const v=String(d?.id??""),c=$t[String(t.aggregation)];return c?h.records.total(h.field,v,String(t.field),c)??null:t.aggregation==="COUNTA"||t.aggregation==="COUNTALL"?h.records.total(h.field,v)??null:o(h.records.allLinkedTo(h.field,v).map(f))}return o(i.rowsOf(d).map(f))},formatter:e.formatter??(d=>{const f=n?U(d.value):typeof d.value=="number"?d.value:null;return f==null?String(d.value??""):p(f)})}}},{id:"count",get label(){return l("fields.typeCount")},get description(){return l("fields.typeCountDescription")},icon:s.count,group:"relation",width:90,properties:[Z],fill:(e,t,r)=>{const i=te(t,r);return{...e,...y(e),cellDataType:e.cellDataType??"number",formatter:o=>o.value==null?"":Number(o.value).toLocaleString(),fieldFn:o=>{if(!i)return 0;const n=i.stored;return n?n.records.total(n.field,String(o?.id??""))??null:i.rowsOf(o).length}}}},dt];
@@ -0,0 +1,61 @@
1
+ import type { BaseTable } from './base-tables.js';
2
+ import { type BaseAutomation } from './automations.svelte.js';
3
+ import { type ButtonAction } from './button.js';
4
+ import type { FieldFilter } from './filter-model.js';
5
+ type Row = Record<string, unknown>;
6
+ /** A Button field's own settings (`fieldProps`). */
7
+ export type ButtonProps = {
8
+ label?: string;
9
+ color?: string;
10
+ action?: ButtonAction;
11
+ url?: string;
12
+ /** `update`: field id -> value, written as an automation's "Update the record" writes them (`me` is the person pressing). */
13
+ values?: Record<string, unknown>;
14
+ /** `update`: the label once the record holds the values (the button is then done). */
15
+ doneLabel?: string;
16
+ /** `template`: the record template whose values fill the empty fields. */
17
+ template?: string;
18
+ /** `recordAction`: the app's record action, by id. */
19
+ recordAction?: string;
20
+ /** `copy`: the text, `{Field name}` tokens filled in; starting with `=` it is a formula. */
21
+ copy?: string;
22
+ /** Only records that match can press it. */
23
+ when?: FieldFilter;
24
+ /** Ask before it runs, with this question. */
25
+ ask?: boolean;
26
+ askText?: string;
27
+ };
28
+ export type ButtonState = {
29
+ /** It cannot be pressed on this record. */
30
+ disabled: boolean;
31
+ /** A change the record already holds: shown with a check and `label`. */
32
+ done: boolean;
33
+ /** The label to show (the done label once it is done). */
34
+ label?: string;
35
+ /** Why it cannot be pressed, for its tooltip. */
36
+ reason?: string;
37
+ };
38
+ export type ButtonHost = {
39
+ state(tableId: string | undefined, columnId: string, row: Row, ctrl: any): ButtonState;
40
+ press(tableId: string | undefined, columnId: string, row: Row, rowId: string, ctrl: any, api: any): Promise<void>;
41
+ };
42
+ export type ButtonHostDeps = {
43
+ tableOf: (id: string) => BaseTable | undefined;
44
+ tables: () => BaseTable[];
45
+ /** A shared base: nobody changes records from it. */
46
+ locked: () => boolean;
47
+ /** The automations "When a button is pressed" on this one, as a handler; null for none. */
48
+ automations: (tableId: string, columnId: string) => ((row: Row) => void) | null;
49
+ /** Run an automation now on a record (the runner's `runNow`). */
50
+ runNow: (a: BaseAutomation, tableId: string, recordId: string) => Promise<void>;
51
+ confirm: (q: {
52
+ title: string;
53
+ body: string;
54
+ yes: string;
55
+ }) => Promise<boolean>;
56
+ /** The writes under way have landed: an automation run on the server reads the record as the button left it. */
57
+ settled?: () => Promise<unknown>;
58
+ now?: () => Date;
59
+ };
60
+ export declare function createButtonHost(deps: ButtonHostDeps): ButtonHost;
61
+ export {};
@@ -0,0 +1 @@
1
+ import{nextGroupId as w,pushHistory as B,toast as v}from"@svgrid/grid";import{fieldValueFrom as F,matches as P,tableFields as E}from"./automations.svelte.js";import{buttonAction as T,CHANGING_ACTIONS as $,copyButtonText as G,openButtonLink as H,safeButtonLink as M}from"./button.js";import{gridPermissions as V}from"./base-permissions.js";import{fieldPropsOf as z}from"./registry.svelte.js";import{openRecord as J}from"./editor-request.svelte.js";import{askDeleteRecord as U}from"./record-delete.svelte.js";import{recordMenu as q}from"./record-menu.js";import{recordActionsFor as x}from"./record-actions.js";import{getCurrentUser as K}from"./sources.svelte.js";import{bm as u}from"./messages.svelte.js";function Q(t){const m=t?.props;return m?.baseReadOnly===!0?{canEdit:!1,canCreate:!1,canDelete:!1,canEditSchema:!1,canEditViews:!1,canComment:!1}:m?.basePermissions??V(t)}const S=(t,m)=>JSON.stringify(t??null)===JSON.stringify(m??null),j=t=>t==null||t===""||t===!1||Array.isArray(t)&&t.length===0,W=t=>typeof t=="string"&&/^\s*(today|now)\s*([+-]\s*\d+)?\s*$|^\s*me\s*$/i.test(t);function X(t,m){return m.link?!1:m.moving?!j(t[m.field]):S(t[m.field],m.value)}function Y(t,m){const A=K(),R=E(t),O={};for(const[h,k]of Object.entries(m)){const C=R.get(h);O[h]=C?.fieldType==="user"&&typeof k=="string"&&/^\s*me\s*$/i.test(k)?A?.id??"":k}return O}export function createButtonHost(t){const m=t.now??(()=>new Date),A=(f,o)=>{const e=f.columns.find(d=>String(d.id??d.field)===o);return e&&e.fieldType==="button"?z(e):null},R=(f,o)=>E(f).get(o)?.def,O=(f,o,e)=>M(String(R(f,o)?.__buttonLink?.(e)??"")),h=(f,o,e)=>String(R(f,o)?.__buttonCopy?.(e)??"");function k(f,o,e,d){const n=new Map,l=E(f),s=e==="update"?o.values??{}:e==="template"?f.recordTemplates?.find(a=>a.id===o.template)?.values??{}:{},c=Y(f,s),g={tables:t.tables(),from:f,record:d,now:m()};for(const[a,y]of Object.entries(c)){const r=l.get(a);!r||r.def.editable===!1||e==="template"&&!j(d[r.field])||n.set(a,{field:r.field,value:F(f,r.def,y,g),spec:y,link:r.fieldType==="link",moving:W(s[a])})}return n}function C(f,o,e,d){const n=f?t.tableOf(f):void 0,l=n?A(n,o):null;if(!n||!l)return{disabled:!0,done:!1};const s=T(l),c=Q(d),g=!t.locked()&&!!t.automations(n.id,o),a=r=>({disabled:!0,done:!1,reason:r}),y={disabled:!0,done:!0,label:l.doneLabel?.trim()||void 0};if(s==="update"){const r=k(n,l,s,e);if(!r.size)return a(u("fields.buttonNoValues"));if([...r.values()].every(i=>X(e,i)))return y}if(s==="template"){if(!n.recordTemplates?.some(r=>r.id===l.template))return a(u("fields.buttonNoTemplate"));if(!k(n,l,s,e).size)return y}if(l.when?.conditions?.length&&!P(n,l.when,e))return a(u("fields.buttonNotNow"));if($.has(s)&&(t.locked()||!c.canEdit))return a(u("fields.buttonReadOnly"));switch(s){case"link":return O(n,o,e)||g?{disabled:!1,done:!1}:a(u("fields.buttonNoLink"));case"copy":return h(n,o,e)?{disabled:!1,done:!1}:a(u("fields.buttonNoText"));case"automation":return g?{disabled:!1,done:!1}:a(u("fields.buttonNoAutomation"));case"recordAction":return x(n.id,{rowId:"",row:e}).some(r=>r.id===l.recordAction)||x(n.id).some(r=>r.id===l.recordAction)?{disabled:!1,done:!1}:a(u("fields.buttonNoRecordAction"));case"duplicate":return c.canCreate?{disabled:!1,done:!1}:a(u("fields.buttonReadOnly"));case"delete":return c.canDelete?{disabled:!1,done:!1}:a(u("fields.buttonReadOnly"));default:return{disabled:!1,done:!1}}}async function D(f,o,e,d,n,l){const s=l?.allRows?.findIndex(i=>i.id===n)??-1,c=[...e.values()].some(i=>i.link);if(s<0||c||!l?.editingEnabled||typeof l?.writeCellsRaw!="function"){const i=Object.fromEntries([...e.entries()].map(([b,N])=>[b,N.spec])),p={id:`button-${n}`,name:o,enabled:!0,trigger:{type:"recordCreated"},actions:[{type:"updateRecord",values:i}]};return await t.runNow(p,f.id,n),{...d,...Object.fromEntries([...e.values()].filter(b=>!b.link).map(b=>[b.field,b.value]))}}const g=l.allColumns,a=[],y=[];let r=0;for(const[i,p]of e){const b=g.findIndex(_=>_.id===i),N=d[p.field];if(!S(N,p.value)){if(b<0||l.isCellEditableAt?.(s,b)===!1){r+=1;continue}a.push({rowIndex:s,columnId:i,value:p.value}),y.push({rowId:n,columnId:i,field:p.field,before:N,after:p.value})}}return r&&v.warning(u("fields.buttonSomeRefused")),a.length?(l.writeCellsRaw(a),B(l,y,w()),{...d,...Object.fromEntries(y.map(i=>[i.field,i.after]))}):d}async function L(f,o,e,d,n,l){const s=f?t.tableOf(f):void 0,c=s?A(s,o):null;if(!s||!c||C(f,o,e,n).disabled)return;const g=T(c),a=c.label?.trim()||u("record.buttonOpen");if(c.ask&&g!=="delete"&&!await t.confirm({title:a,body:c.askText?.trim()||u("fields.buttonAskDefault"),yes:a}))return;const y=t.locked()?null:t.automations(s.id,o);let r=e;try{switch(g){case"link":{const i=O(s,o,e);i&&H(i);break}case"copy":{await G(h(s,o,e))?v.success(u("fields.buttonCopied")):v.error(u("fields.buttonCopyFailed"));break}case"update":case"template":r=await D(s,a,k(s,c,g,e),e,d,n);break;case"recordAction":{[...x(s.id,{rowId:d,row:e}),...x(s.id)].find(p=>p.id===c.recordAction)?.run({tableId:s.id,rowId:d,row:e});break}case"open":J({ctrl:n,rowId:d});break;case"duplicate":{const i=q(()=>l,()=>n).find(b=>typeof b=="object"&&b.key==="duplicate"),p=n?.allRows?.findIndex(b=>b.id===d)??-1;i?.action?.({rowIndex:p,colIndex:-1,columnId:o,rowId:d,row:n?.allRows?.[p]?.original??e,card:p<0});break}case"delete":U({ctrl:n,api:l,row:n?.allRows?.find?.(i=>i.id===d)?.original??e});return;case"automation":break}}catch(i){v.error(i instanceof Error?i.message:String(i));return}y&&(r!==e&&await t.settled?.().catch(()=>{}),y(r))}return{state:C,press:L}}
@@ -1,2 +1,37 @@
1
- /** The URL a button field opens: `{Field name}` tokens filled from the row, http(s) only. */
1
+ /**
2
+ * What a Button field does when it is pressed (`fieldProps.action`):
3
+ *
4
+ * - `link`: open a link. The URL is either text with `{Field name}` tokens
5
+ * (`https://maps.google.com/?q={Address}`, each value URL-encoded) or, as in
6
+ * Airtable, a formula (`"mailto:" & {Email} & "?subject=" & ENCODE_URL_COMPONENT({Name})`,
7
+ * or `{Website}` for the link a field holds). Web links open in a new tab, a link
8
+ * to this site in the same tab, and mailto:, tel: and sms: in the app that takes them.
9
+ * - `automation`: only the automations that start "When a button is pressed".
10
+ * - `update`: change fields of the record (values as an automation's "Update the record").
11
+ * - `template`: fill the record's empty fields from one of the table's record templates.
12
+ * - `recordAction`: one of the app's record actions (Print, Make a document).
13
+ * - `copy`: copy text made from the record.
14
+ * - `duplicate`, `delete`, `open`: the record menu's own.
15
+ *
16
+ * Whatever the action, the automations listening on the button run after it.
17
+ */
18
+ export type ButtonAction = 'link' | 'automation' | 'update' | 'template' | 'recordAction' | 'copy' | 'duplicate' | 'delete' | 'open';
19
+ export declare const BUTTON_ACTIONS: ReadonlyArray<ButtonAction>;
20
+ /** The actions that change records: a person who may only read cannot press them. */
21
+ export declare const CHANGING_ACTIONS: ReadonlySet<ButtonAction>;
22
+ /** A field's action; a field saved before there were actions opens its link. */
23
+ export declare function buttonAction(props: {
24
+ action?: unknown;
25
+ } | null | undefined): ButtonAction;
26
+ /** URL text is a template when it starts as a link does (`https:`, `mailto:`, `/orders`); anything else is a formula. */
27
+ export declare function isLinkTemplate(text: string): boolean;
28
+ /** `{Field name}` tokens filled from the row; `encode` URL-encodes each value. */
29
+ export declare function fillButtonTokens(template: string, row: Record<string, unknown>, names: Record<string, string> | undefined, encode: boolean): string;
30
+ /** Where a link may go: the web, e-mail, a phone call or a text, and this site. Never script or data. */
31
+ export declare function safeButtonLink(text: string, origin?: string): string | null;
32
+ /** The URL a template-style button opens: `{Field name}` tokens filled from the row. */
2
33
  export declare function buttonUrl(template: string, row: Record<string, unknown> | null | undefined, names?: Record<string, string>): string | null;
34
+ /** Open a button's link: this site in the same tab, other web links in a new one, mailto:/tel:/sms: in their app. */
35
+ export declare function openButtonLink(href: string, origin?: string): void;
36
+ /** Copy text to the clipboard; on a page without the Clipboard API, through a hidden text box. */
37
+ export declare function copyButtonText(text: string): Promise<boolean>;
@@ -1 +1 @@
1
- export function buttonUrl(n,o,e){if(!n.trim()||!o)return null;const c=n.replace(/\{([^}]+)\}/g,(r,l)=>{const u=e?.[l.trim().toLowerCase()]??l.trim(),t=o[u];return encodeURIComponent(t==null?"":Array.isArray(t)?t.join(","):String(t))});try{const r=new URL(c);return r.protocol==="http:"||r.protocol==="https:"?r.href:null}catch{return null}}
1
+ export const BUTTON_ACTIONS=["link","automation","update","template","recordAction","copy","duplicate","delete","open"],CHANGING_ACTIONS=new Set(["automation","update","template","duplicate","delete"]);export function buttonAction(o){const e=o?.action;return typeof e=="string"&&BUTTON_ACTIONS.includes(e)?e:"link"}export function isLinkTemplate(o){return/^\s*([a-z][a-z0-9+.-]*:|\/)/i.test(o)}export function fillButtonTokens(o,e,t,r){return o.replace(/\{([^}]+)\}/g,(n,c)=>{const a=t?.[c.trim().toLowerCase()]??c.trim(),i=e[a],l=i==null?"":Array.isArray(i)?i.join(","):String(i);return r?encodeURIComponent(l):l})}export function safeButtonLink(o,e=typeof location>"u"?"http://localhost":location.origin){const t=o.trim();if(!t)return null;if(t.startsWith("/")&&!t.startsWith("//"))try{return new URL(t,e).href}catch{return null}const r=/^[a-z0-9-]+(\.[a-z0-9-]+)+(:\d+)?([/?#]|$)/i.test(t)?`https://${t}`:t;try{const n=new URL(r);return n.protocol==="http:"||n.protocol==="https:"?n.href:n.protocol==="mailto:"||n.protocol==="tel:"||n.protocol==="sms:"?r:null}catch{return null}}export function buttonUrl(o,e,t){return!o.trim()||!e?null:safeButtonLink(fillButtonTokens(o,e,t,!0))}export function openButtonLink(o,e=location.origin){let t=null;try{t=new URL(o,e)}catch{return}if(t.protocol!=="http:"&&t.protocol!=="https:"){location.href=o;return}t.origin===e?location.assign(t.href):window.open(t.href,"_blank","noopener,noreferrer")}export async function copyButtonText(o){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(o),!0}catch{}const e=document.createElement("textarea");e.value=o,e.setAttribute("readonly",""),e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select();let t=!1;try{t=document.execCommand("copy")}catch{t=!1}return e.remove(),t}
@@ -41,6 +41,7 @@ export { setRecordComments, type RecordComment, type RecordCommentContext, type
41
41
  export { setCommentSnippets, type CommentSnippet, type CommentSnippets } from './comment-snippets.svelte.js';
42
42
  export { setFormSuggestions, type FormSuggestion, type FormSuggestions } from './form-suggestions.svelte.js';
43
43
  export { setBaseMessages, baseMessages, BASE_MESSAGES, type BaseMessages, type BaseMessageKey } from './messages.svelte.js';
44
+ export { setDateLocale, dateLocale } from '../date-locale.js';
44
45
  export { setRecordHistory, historyOf, loadHistory, type RecordChange, type RecordHistoryStore, type RecordHistoryContext } from './activity.svelte.js';
45
46
  export { setMentionHandler, type MentionEvent, type MentionHandler } from './activity.svelte.js';
46
47
  export { mentionToken, mentionIds, mentionText, parseMentions, encodeMentions, type MentionPart } from './mentions.js';
@@ -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 W,userSorts as X,writeSortState as j}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 x,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 xe from"./VoteEditor.svelte";import Ee from"./TimerEditor.svelte";import Se from"./ChecklistEditor.svelte";import ke 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 E}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{setAutomationDrafter}from"./automation-drafter.js";export{setRecordSeries,refreshRecordSeries}from"./record-series.svelte.js";export{cronWords}from"./cron-words.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,setAttachmentSources,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:!k(o,r,-1),run:()=>R(o,r,-1)},{key:"field-move-right",label:p("fields.menuMoveRight"),icon:m.right,disabled:!k(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 S(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 k=(o,r,e)=>!!S(o,r,e);function R(o,r,e){const i=S(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(Xe(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=W(o);e.some(i=>i.id===r)||j(o.buildApi(),[...e,{id:r,desc:!1}],X(o)),w(o,"group")}function D(o,r,e,i,t){if(!r)return;const l=E()?.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 We}from"./excel-habits.svelte.js";import{orderKeepingScreen as Xe}from"./column-order.js";let O=!1;export function enableFields(){if(O)return;O=!0;for(const e of ae)x(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),je(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?x(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:Se,props:r}),f("fieldRichText",{component:Ae,props:r}),f("fieldVote",{component:xe,props:r,typeToEdit:e=>e===" "}),f("fieldTimer",{component:Ee,props:e=>({...r(e),rowId:e.rowId,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>e===" "||/[0-9:]/.test(e)}),f("fieldColor",{component:ke,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)),$(()=>E()?.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(We,{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 je,aiFieldMenuItems as Ye}from"./ai-field.svelte.js";export{generateAIField,regenerateAIFields,cancelAIField,pendingAIField,setAIFieldConcurrency}from"./ai-field.svelte.js";export{aiPromptError,readAIAnswer}from"./ai-prompt.js";export{moveTile,newTile,putTile,removeTile,tileResult,tileRows,tileTitle}from"./dashboard.js";export{sharedTables,sharedViews,shareOf}from"./base-share.js";export{recordsAsShown,downloadAsShown,filesFolders,safeFolder}from"./base-export.js";export{permittedTables,permittedRecords,permittedViews,tablePermissions,gridPermissions}from"./base-permissions.js";export{computeRecords,computeRecord,computedValues,computedFields,evaluateFilter,filterRecords}from"./base-compute.js";export{queryRecords,fieldFilterToSql,fieldFilterToPostgrest,supabaseFieldFilter,viewFilterOf}from"./base-query.js";export{searchBase}from"./base-search.js";export{toChecklist,parseChecklist,checklistText,checklistProgress}from"./checklist.js";export{parseColor}from"./color-value.js";export{parseTimeOfDay,formatTimeOfDay,timeSeconds}from"./time-of-day.js";
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 W,userSorts as X,writeSortState as j}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 x,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 xe from"./VoteEditor.svelte";import Ee from"./TimerEditor.svelte";import Se from"./ChecklistEditor.svelte";import ke 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 E}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{setAutomationDrafter}from"./automation-drafter.js";export{setRecordSeries,refreshRecordSeries}from"./record-series.svelte.js";export{cronWords}from"./cron-words.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{setDateLocale,dateLocale}from"../date-locale.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,setAttachmentSources,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:!k(o,r,-1),run:()=>R(o,r,-1)},{key:"field-move-right",label:p("fields.menuMoveRight"),icon:m.right,disabled:!k(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 S(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 k=(o,r,e)=>!!S(o,r,e);function R(o,r,e){const i=S(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(Xe(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=W(o);e.some(i=>i.id===r)||j(o.buildApi(),[...e,{id:r,desc:!1}],X(o)),w(o,"group")}function D(o,r,e,i,t){if(!r)return;const l=E()?.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 We}from"./excel-habits.svelte.js";import{orderKeepingScreen as Xe}from"./column-order.js";let O=!1;export function enableFields(){if(O)return;O=!0;for(const e of ae)x(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),je(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?x(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:Se,props:r}),f("fieldRichText",{component:Ae,props:r}),f("fieldVote",{component:xe,props:r,typeToEdit:e=>e===" "}),f("fieldTimer",{component:Ee,props:e=>({...r(e),rowId:e.rowId,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>e===" "||/[0-9:]/.test(e)}),f("fieldColor",{component:ke,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)),$(()=>E()?.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(We,{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 je,aiFieldMenuItems as Ye}from"./ai-field.svelte.js";export{generateAIField,regenerateAIFields,cancelAIField,pendingAIField,setAIFieldConcurrency}from"./ai-field.svelte.js";export{aiPromptError,readAIAnswer}from"./ai-prompt.js";export{moveTile,newTile,putTile,removeTile,tileResult,tileRows,tileTitle}from"./dashboard.js";export{sharedTables,sharedViews,shareOf}from"./base-share.js";export{recordsAsShown,downloadAsShown,filesFolders,safeFolder}from"./base-export.js";export{permittedTables,permittedRecords,permittedViews,tablePermissions,gridPermissions}from"./base-permissions.js";export{computeRecords,computeRecord,computedValues,computedFields,evaluateFilter,filterRecords}from"./base-compute.js";export{queryRecords,fieldFilterToSql,fieldFilterToPostgrest,supabaseFieldFilter,viewFilterOf}from"./base-query.js";export{searchBase}from"./base-search.js";export{toChecklist,parseChecklist,checklistText,checklistProgress}from"./checklist.js";export{parseColor}from"./color-value.js";export{parseTimeOfDay,formatTimeOfDay,timeSeconds}from"./time-of-day.js";