@svgrid/enterprise 3.1.73 → 3.1.75

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 (42) hide show
  1. package/dist/cdn/svgrid-enterprise.svelte-external.js +1 -1
  2. package/dist/designer/assets/PinSplitter-PRGGE5GP.js +1 -0
  3. package/dist/designer/assets/{index-BN-wGfOs.js → index-BOF2h-Nd.js} +3 -3
  4. package/dist/designer/index.html +1 -1
  5. package/dist/fields/AutomationAction.svelte +2 -1
  6. package/dist/fields/FieldInput.svelte +1 -1
  7. package/dist/fields/LongTextEditor.svelte +22 -15
  8. package/dist/fields/LongTextEditor.svelte.d.ts +1 -0
  9. package/dist/fields/MentionInput.svelte +13 -7
  10. package/dist/fields/MentionInput.svelte.d.ts +4 -1
  11. package/dist/fields/RecordView.svelte +4 -3
  12. package/dist/fields/RichTextEditor.svelte +25 -17
  13. package/dist/fields/RichTextEditor.svelte.d.ts +1 -0
  14. package/dist/fields/automations.svelte.d.ts +9 -1
  15. package/dist/fields/automations.svelte.js +6 -1
  16. package/dist/fields/builtin-types.js +1 -1
  17. package/dist/fields/index.d.ts +1 -1
  18. package/dist/fields/index.js +1 -1
  19. package/dist/fields/mentions.d.ts +31 -3
  20. package/dist/fields/mentions.js +1 -1
  21. package/dist/fields/messages/extras.d.ts +2 -0
  22. package/dist/fields/messages/extras.js +1 -1
  23. package/dist/fields/messages.svelte.d.ts +2 -0
  24. package/dist/fields/page/PageEditor.svelte +2 -2
  25. package/dist/fields/page/PageEditor.svelte.d.ts +3 -0
  26. package/dist/fields/page/page-editor.d.ts +9 -0
  27. package/dist/fields/page/page-editor.js +4 -4
  28. package/dist/fields/rollups.d.ts +2 -0
  29. package/dist/fields/rollups.js +1 -1
  30. package/dist/node/studio.js +1 -1
  31. package/dist/version.d.ts +2 -2
  32. package/dist/version.js +1 -1
  33. package/dist/wc/PageEditor-D9pEmMvk.js +12 -0
  34. package/dist/wc/{PinSplitter-D7UYjmiP.js → PinSplitter-C6SuBrBi.js} +2 -2
  35. package/dist/wc/PinSplitter-CZx_nlrw.js +11 -0
  36. package/dist/wc/{embed-url-CGl6lpsT.js → embed-url-CdvhipnX.js} +1 -1
  37. package/dist/wc/sv-base-element.js +101 -90
  38. package/dist/wc/sv-sheet-element.js +1 -1
  39. package/package.json +3 -3
  40. package/dist/designer/assets/PinSplitter-DFIcNVPE.js +0 -1
  41. package/dist/wc/PageEditor-0bKgt5ID.js +0 -12
  42. package/dist/wc/PinSplitter-BmwDy-Ow.js +0 -11
@@ -1 +1,6 @@
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 viewFilterOf(t,viewId){const v=(t.views??[]).find(x=>x.id===viewId);const f=v?.state?.advancedFilter;return f&&typeof f==="object"&&f.kind==="fieldFilter"?f:null}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"deleteRecord":{if(!rec||recordId==null)return{action:bm("extras.actionDeleteRecord"),detail:bm("extras.noRecordToDelete")};const name=String(rec[primaryOf(t)]??"")||bm("extras.aRecord");if(t.source?.server){if(!options.server?.remove)throw new Error(bm("extras.cannotDeleteHere"));await options.server.remove(t.id,recordId,rec)}else{let next=(options.getTables()??[]).map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==recordId)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}return{action:bm("extras.actionDeleteRecord"),detail:bm("extras.deletedRecord",{name})}}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"recordEntersView":{const f=viewFilterOf(t,tr.view);if(!f)return false;if(e.type==="created")return matches(t,f,e.record)&&matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,f,e.record)&&!matches(t,f,e.before)&&matches(t,a.condition,e.record);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"deleteRecord":return bm("extras.actionDeleteRecord");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"recordEntersView":{const view=(t?.views??[]).find(v=>v.id===tr.view)?.name??bm("extras.aView");return where?bm("extras.whenEntersViewWhere",{view,condition:cond}):bm("extras.whenEntersView",{view})}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 baseText(tables,most=6e4){const SKIP=new Set(["attachment","button","richText","createdBy","lastModifiedBy"]);const parts=tables.slice(0,20).map(t=>{const fields=[...tableFields(t).values()].filter(c=>!SKIP.has(String(c.fieldType??"text")));const lines=[];for(const r of t.data??[]){const cells=[];for(const c of fields){let v=fieldText(c,r);if(!v||c.fieldType==="checkbox"&&v==="false")continue;v=(v.length>300?v.slice(0,297)+"...":v).replace(/\s+/g," ");cells.push(c.field===t.primaryField?v:`${c.header}: ${v}`)}if(cells.length)lines.push("- "+cells.join(" | "))}return{name:t.name,lines}});const sizes=parts.map((p,i)=>({i,size:p.lines.reduce((n,line)=>n+line.length+1,0)})).sort((a,b)=>a.size-b.size);const budget=[];let left=most;sizes.forEach(({i,size},k)=>{budget[i]=Math.min(size,Math.floor(left/Math.max(1,sizes.length-k)));left-=budget[i]});return parts.map((p,i)=>{const kept=[];let size=0;for(const line of p.lines){if(size+line.length+1>budget[i])break;kept.push(line);size+=line.length+1}const left2=p.lines.length-kept.length;return`## ${p.name} (${p.lines.length} records${left2>0?`, the first ${kept.length} shown`:""})
2
+ ${kept.join("\n")}`}).join("\n\n")}export function viewFilterOf(t,viewId){const v=(t.views??[]).find(x=>x.id===viewId);const f=v?.state?.advancedFilter;return f&&typeof f==="object"&&f.kind==="fieldFilter"?f:null}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"deleteRecord":{if(!rec||recordId==null)return{action:bm("extras.actionDeleteRecord"),detail:bm("extras.noRecordToDelete")};const name=String(rec[primaryOf(t)]??"")||bm("extras.aRecord");if(t.source?.server){if(!options.server?.remove)throw new Error(bm("extras.cannotDeleteHere"));await options.server.remove(t.id,recordId,rec)}else{let next=(options.getTables()??[]).map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==recordId)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}return{action:bm("extras.actionDeleteRecord"),detail:bm("extras.deletedRecord",{name})}}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"));let prompt=fillTokens(t,rec,action.prompt,values).trim();if(!prompt)throw new Error(bm("extras.aiNoPrompt"));if(action.base)prompt+=`
3
+
4
+ Today is ${ctx.now.toDateString()}. The base now:
5
+
6
+ ${baseText(options.getTables()??[])}`;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"recordEntersView":{const f=viewFilterOf(t,tr.view);if(!f)return false;if(e.type==="created")return matches(t,f,e.record)&&matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,f,e.record)&&!matches(t,f,e.before)&&matches(t,a.condition,e.record);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"deleteRecord":return bm("extras.actionDeleteRecord");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"recordEntersView":{const view=(t?.views??[]).find(v=>v.id===tr.view)?.name??bm("extras.aView");return where?bm("extras.whenEntersViewWhere",{view,condition:cond}):bm("extras.whenEntersView",{view})}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 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 We,formatCurrency as ie,formatDate as E,formatDuration as ne,formatNumber as H,formatPercent as oe,numberFieldShape as ae,numberFromText as Ge,numberKind as je,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 W,getLinkedTable as T,idOf as it,linkedRows as G,listLinkedTables as nt,liveLink as ot,recordsNaming as at,resolveLinkId as st,resolveLinkIds as ut}from"./sources.svelte.js";import{splitNames as j}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(G(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=Ge(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=We(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?j(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=W(),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?j(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=j(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,Wt=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},Gt=e=>{const t=typeof e.rawInput=="string"?e.rawInput:e.newValue;return t==null||String(t).trim()===""?null:$(t)??e.oldValue},jt=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??"")):G(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??W().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:"who",get label(){return l("fields.propButtonWho")},kind:"people",get everyone(){return l("fields.buttonWhoEveryone")},get only(){return l("fields.whoOnly")},get hint(){return l("fields.propButtonWhoHint")}},{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??Gt,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,je("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??jt(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??Wt(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??W().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 G(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];
1
+ import{fillFieldColumn as O}from"./registry.svelte.js";import Ve from"./RatingCell.svelte";import N from"./LinkCell.svelte";import Fe from"./AttachmentCell.svelte";import Ie from"./CheckboxCell.svelte";import le from"./PercentCell.svelte";import B from"./UserCell.svelte";import Le from"./ButtonCell.svelte";import Oe from"./BarcodeCell.svelte";import Ne from"./LinkedRecordsCell.svelte";import Be from"./RichTextCell.svelte";import Re from"./RichHtmlCell.svelte";import{richPlain as A}from"./rich-html.js";import{toRichHtml as Ee}from"./rich-html-write.js";import ie from"./SelectCell.svelte";import He from"./ChecklistCell.svelte";import Ue from"./ColorCell.svelte";import{attachmentsText as _e,parseAttachments as ze}from"./attachments.js";import{dateEditTokens as We,dateFromParts as R,exactNumber as Ge,formatCurrency as ne,formatDate as E,formatDuration as oe,formatNumber as H,formatPercent as ae,numberFieldShape as se,numberFromText as je,numberKind as $e,parseDateText as xe,parseDuration as V,toNumber as U}from"./format.js";import{BRIGHT as ue,CHECKBOX_ICONS as Ke,RATING_ICONS as Xe}from"./palette.js";import{COMPUTED_TYPES as ce,ROLLUPS as _,fieldNameMap as Ye}from"./rollups.js";import{sparklineValues as z,voteCount as de,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 pe,getCurrentUser as fe,getFieldUsers as W,getLinkedTable as T,idOf as it,linkedRows as G,listLinkedTables as nt,liveLink as ot,recordsNaming as at,resolveLinkId as st,resolveLinkIds as ut}from"./sources.svelte.js";import{splitNames as j}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 me,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 ge,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 vt,isLinkTemplate as wt}from"./button.js";import{recordActionsFor as he}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=>pe(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 d=x(a,a.primaryField),g=new Map(G(a,n).map(m=>[it(a,m),d(m)]));return r((Array.isArray(n)?n:[n]).map(m=>g.get(String(m))??m))}}const be=new WeakMap;let w=0;function x(e,t){const r=n=>n?.[t];if(!e?.fields?.length)return r;let i=be.get(e.fields);if(i||be.set(e.fields,i=new Map),!i.has(t)){const n=ct(e).find(d=>d.def.field===t),a=n?.def.fieldType==="timer"?d=>F(d?.[t]):null;i.set(t,a??n?.def.fieldFn??null)}const o=i.get(t);return o?n=>{if(w>3)return r(n);w+=1;try{return o(n)}finally{w-=1}}:r}const u={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"},c=(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 Dt(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"?he(e.ctrl?.props?.baseTableId).length>0:!0:!1;return Tt.filter(i).map(o=>c(o,Ct[o]))}const ye=e=>e?{visible:e}:{},Pt={key:"separators",get label(){return l("fields.propSeparators")},kind:"choice",choices:[c("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:[c("none","fields.choiceNone"),c("thousand","fields.choiceThousand"),c("million","fields.choiceMillion"),c("billion","fields.choiceBillion")],...ye(e)}),Ft={key:"allowNegative",get label(){return l("fields.propAllowNegative")},kind:"checkbox"},v={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)}`}}),X=(e,t)=>({key:"precision",get label(){return l("fields.propPrecision")},kind:"choice",choices:e,visible:t}),It=[c("local","fields.choiceLocal"),c("friendly","fields.choiceFriendly"),c("us","fields.choiceUs"),c("european","fields.choiceEuropean"),c("iso","fields.choiceIso")],I=e=>({key:"dateFormat",get label(){return l("fields.propDateFormat")},kind:"choice",choices:It,...ye(e)}),ke=[c("12hour","fields.choice12Hour"),c("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:ke,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})):[]},Te={key:"field",get label(){return l("fields.propLinkedField")},kind:"choice",choices:Ot,visible:e=>!!e.linkField},M={key:"color",get label(){return l("fields.propColor")},kind:"color",palette:ue},ve={key:"options",get label(){return l("fields.propOptions")},kind:"options"},we=(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:we(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:se(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"?ne(o,{...r,symbol:t.symbol,symbolPosition:t.symbolPosition}):e==="percent"?ae(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}),C=e=>Array.isArray(e.options)?e.options.map(t=>({value:t.value,label:t.label??String(t.value),...t.color?{color:t.color}:{}})):[],Se=(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?j(n.rawInput):n.rawInput.split(/\n/).map(g=>g.trim()).filter(Boolean);if(o)return t?[...new Set(a)]:a[0]??null;const d=a.map(i).filter(g=>g!==void 0);return a.length&&!d.length?n.oldValue:t?[...new Set(d)]:a.length?i(a[0])===void 0?n.oldValue:i(a[0]):null}},Me=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(", ")},Ht=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},Ce=Ye,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=xe(i,e);return o?R(o,e,t.oldValue):t.oldValue},Q=e=>(Array.isArray(e)?e:e==null||e===""?[]:[e]).map(t=>pe(t)?.name??String(t)).join(", "),De=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=W(),i=a=>{const d=a.toLowerCase();return r.find(m=>m.id.toLowerCase()===d||m.name.toLowerCase()===d||m.email?.toLowerCase()===d)?.id??(r.length?void 0:a)},o=e?j(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=j(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,Wt=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},Gt=e=>{const t=typeof e.rawInput=="string"?e.rawInput:e.newValue;return t==null||String(t).trim()===""?null:$(t)??e.oldValue},jt=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;return r==null||typeof r=="string"&&r.trim()===""?null:ge(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:se(r,{precision:t.precision}).places};return r==="currency"?ne(e,{...i,symbol:t.symbol}):r==="percent"?ae(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),d=String(r.field??r.id);return a&&o&&!a.records&&n?.[d]===void 0?at(a,o,String(n?.id??"")):G(a,n?.[d])},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"},Pe=new WeakMap;function re(e,t,r){const i=e?.table?.fields;if(!i)return;let o=Pe.get(i);o||Pe.set(i,o=new Map);const n=`${String(t)}|${r??""}`;if(o.has(n))return o.get(n);const a=i.find(g=>g.field===String(t)),d=a?.fieldType?O({field:a.field,fieldType:a.fieldType,fieldProps:{...a.fieldProps,...r==null?{}:{precision:r}}}).formatter:void 0;return o.set(n,d),d}const L=()=>new Date().toISOString(),xt=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0}),Kt=(e,t)=>{const r=i=>i?me.indexOf(i):me.length;return r(e)-r(t)},Ae=[{key:"watch",get label(){return l("fields.propWatch")},kind:"segmented",choices:[c("all","fields.choiceAllFields"),c("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:u.text,group:"basic",properties:[v],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:u.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:Be,hasCell:e=>!!e.richText},{id:"richText",get label(){return l("fields.typeRichText")},get description(){return l("fields.typeRichTextDescription")},icon:u.richText,group:"basic",width:280,defaults:{toolbar:"standard"},properties:[{key:"toolbar",get label(){return l("fields.propToolbar")},kind:"segmented",choices:[c("standard","fields.choiceStandard"),c("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=>Ee(t.newValue))}),cell:Re},{id:"attachment",get label(){return l("fields.typeAttachment")},get description(){return l("fields.typeAttachmentDescription")},icon:u.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=>_e(r.value)),valueParser:e.valueParser??(r=>ze(r.newValue,t))}),cell:Fe},{id:"checkbox",get label(){return l("fields.typeCheckbox")},get description(){return l("fields.typeCheckboxDescription")},icon:u.checkbox,group:"basic",width:90,defaults:{icon:"check",color:"#20c933"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:Ke},M,v],fill:e=>({...e,editorType:e.editorType??"checkbox",align:e.align??"center",toggleOnSecondClick:e.toggleOnSecondClick??!0}),cell:Ie},{id:"singleSelect",get label(){return l("fields.typeSingleSelect")},get description(){return l("fields.typeSingleSelectDescription")},icon:u.singleSelect,group:"basic",width:140,defaults:{options:[]},properties:[ve,v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorOptions:e.editorOptions??C(t),formatter:e.formatter??Me(t),valueParser:e.valueParser??Se(t,!1),sortValue:e.sortValue??Ht(t)}),cell:ie},{id:"multiSelect",get label(){return l("fields.typeMultiSelect")},get description(){return l("fields.typeMultiSelectDescription")},icon:u.multiSelect,group:"basic",width:200,defaults:{options:[]},properties:[ve,v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorMultiple:e.editorMultiple??!0,editorOptions:e.editorOptions??C(t),formatter:e.formatter??Me(t),valueParser:e.valueParser??Se(t,!0)}),cell:ie},{id:"user",get label(){return l("fields.typeUser")},get description(){return l("fields.typeUserDescription")},icon:u.user,group:"basic",width:170,properties:[{key:"multiple",get label(){return l("fields.propMultipleUsers")},kind:"checkbox"},v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",valueParser:e.valueParser??De(!!t.multiple),editorMultiple:e.editorMultiple??!!t.multiple,editorOptions:e.editorOptions??W().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:u.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??We(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:u.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:u.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:u.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:u.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:Oe},{id:"button",get label(){return l("fields.typeButton")},get description(){return l("fields.typeButtonDescription")},icon:u.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:ue},{key:"action",get label(){return l("fields.propButtonAction")},kind:"choice",choices:Dt},{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=>he(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:"who",get label(){return l("fields.propButtonWho")},kind:"people",get everyone(){return l("fields.buttonWhoEveryone")},get only(){return l("fields.whoOnly")},get hint(){return l("fields.propButtonWhoHint")}},{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=Ce(r.columns),o=(g,m,S)=>{if(!g.trim())return null;if(!m)return p=>p?vt(g,p,i,S):"";const s=O({id:`${String(e.id??e.field)}__button`,field:`__button_${String(e.field??e.id)}`,fieldType:"formula",fieldProps:{formula:g}},r.columns).fieldFn;return p=>{if(!s||!p)return"";const f=s(p);return f==="#ERROR"?"":ee(f,{})}},n=String(t.url??""),a=String(t.copy??""),d=a.trim().startsWith("=");return{...e,...y(e),sortable:e.sortable??!1,__fieldNames:i,__buttonLink:o(n,!!n.trim()&&!wt(n),!0),__buttonCopy:o(d?a.trim().slice(1):a,d,!1)}},cell:Le},{id:"checklist",get label(){return l("fields.typeChecklist")},get description(){return l("fields.typeChecklistDescription")},icon:u.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:He},{id:"color",get label(){return l("fields.typeColor")},get description(){return l("fields.typeColorDescription")},icon:u.color,group:"basic",width:130,properties:[v],fill:e=>({...e,editorType:e.editorType??"fieldColor",formatter:e.formatter??(t=>$(t.value)??String(t.value??"")),valueParser:e.valueParser??Gt,sortValue:e.sortValue??bt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:$(e.default),cell:Ue},{id:"number",get label(){return l("fields.typeNumber")},get description(){return l("fields.typeNumberDescription")},icon:u.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:[c("integer","fields.choiceInteger"),c("decimal","fields.choiceDecimal"),c("currency","fields.choiceCurrency"),c("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:[c("before","fields.choiceBefore"),c("after","fields.choiceAfter")]},X(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")}},Pt,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"},v],fill:(e,t)=>q(e,t,$e("number",t)),cell:le,hasCell:e=>e.format==="percent"&&!!e.showBar},{id:"currency",get label(){return l("fields.typeCurrency")},get description(){return l("fields.typeCurrencyDescription")},icon:u.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:u.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:le,hasCell:e=>!!e.showBar},{id:"duration",get label(){return l("fields.typeDuration")},get description(){return l("fields.typeDurationDescription")},icon:u.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?"":oe(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:u.timeOfDay,group:"number",width:120,defaults:{timeFormat:"12hour",showSeconds:!1},properties:[{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:ke},{key:"showSeconds",get label(){return l("fields.propShowSeconds")},kind:"checkbox"},v],fill:(e,t)=>({...e,editorType:e.editorType??"fieldTime",formatter:e.formatter??(r=>yt(r.value,t)),valueParser:e.valueParser??jt(t),sortValue:e.sortValue??kt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:ge(e.default,{seconds:!!e.showSeconds})},{id:"rating",get label(){return l("fields.typeRating")},get description(){return l("fields.typeRatingDescription")},icon:u.rating,group:"number",width:130,defaults:{max:5,icon:"star",color:"#fcb400"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:Xe},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??Wt(t)}),cell:Ve},{id:"timer",get label(){return l("fields.typeTimer")},get description(){return l("fields.typeTimerDescription")},icon:u.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?"":oe(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:u.vote,group:"basic",width:100,defaults:{icon:"up"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"segmented",choices:[c("up","fields.choiceArrow"),c("thumb","fields.choiceThumb"),c("heart","fields.choiceHeart")]},M],fill:e=>({...e,editorType:e.editorType??"fieldVote",editorOptions:e.editorOptions??W().map(t=>({value:t.id,label:t.name})),align:e.align??"left",sortValue:e.sortValue??(t=>de(t)),formatter:e.formatter??(t=>String(de(t.value))),valueParser:e.valueParser??(t=>Ze(De(!0)(t)))}),newRowValue:()=>[],cell:qe},{id:"sparkline",get label(){return l("fields.typeSparkline")},get description(){return l("fields.typeSparklineDescription")},icon:u.sparkline,group:"number",width:160,defaults:{chart:"line"},properties:[{key:"chart",get label(){return l("fields.propChart")},kind:"segmented",choices:[c("line","fields.choiceLine"),c("area","fields.choiceArea"),c("bar","fields.choiceColumns")]},M,{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:u.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:[c("auto","fields.choiceAsComputed"),c("number","fields.choiceNumber"),c("currency","fields.choiceCurrency"),c("percent","fields.choicePercent"),c("date","fields.choiceDate")]},X(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=Ce(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)),d=s=>{const p=s.trim().toLowerCase(),f=i[p]??null;if(f===n||f==null&&a.has(p))throw lt(s);return f};let g=null;try{g=o.trim()?tt(o,d).fn:()=>null}catch{g=null}let m=null;const S=()=>{if(m)return m;m=new Map;for(const s of r.columns){if(s.fieldType==="richText"){const h=String(s.field??s.id);m.set(h,k=>A(k?.[h]));continue}if(s.fieldType==="timer"){const h=String(s.field??s.id);m.set(h,k=>F(k?.[h]));continue}const p=Mt(s);if(p){m.set(String(s.field??s.id),p);continue}if(!ce.has(String(s.fieldType))||String(s.field??s.id)===n)continue;const f=O(s,r.columns);typeof f.fieldFn=="function"&&m.set(String(s.field??s.id),f.fieldFn)}return m},P=s=>{const p=S();return!p.size||!s?s:new Proxy(s,{get:(f,h)=>{const k=typeof h=="string"?p.get(h):void 0;if(!k||w>3)return f[h];w+=1;try{return k(f)}finally{w-=1}}})};return{...e,...y(e),fieldFn:s=>g?g(P(s)):"#ERROR",align:e.align??(["number","currency","percent"].includes(t.result)?"right":void 0),formatter:e.formatter??(s=>ee(s.value,t))}}},{id:"createdTime",get label(){return l("fields.typeCreatedTime")},get description(){return l("fields.typeCreatedTimeDescription")},icon:u.createdTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour"},properties:[I(),...Y],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:u.modifiedTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour",watch:"all"},properties:[...Ae,I(),...Y],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:u.createdBy,group:"computed",width:160,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>fe()?.id??null,cell:B},{id:"lastModifiedBy",get label(){return l("fields.typeLastModifiedBy")},get description(){return l("fields.typeLastModifiedByDescription")},icon:u.modifiedBy,group:"computed",width:160,defaults:{watch:"all"},properties:Ae,fill:e=>({...e,...y(e),formatter:e.formatter??(t=>Q(t.value))}),newRowValue:()=>fe()?.id??null,cell:B},{id:"autoNumber",get label(){return l("fields.typeAutoNumber")},get description(){return l("fields.typeAutoNumberDescription")},icon:u.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:u.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 G(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:Ne},{id:"lookup",get label(){return l("fields.typeLookup")},get description(){return l("fields.typeLookupDescription")},icon:u.lookup,group:"relation",width:180,properties:[Z,Te],fill:(e,t,r)=>{const i=te(t,r),o=n=>{const a=re(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)),d=i.stored;return d?d.records.allLinkedTo(d.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:u.rollup,group:"relation",width:140,defaults:{aggregation:"SUM"},properties:[Z,Te,{key:"aggregation",get label(){return l("fields.propAggregation")},kind:"choice",choices:Object.keys(_).map(e=>({value:e,label:e}))},X(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=String(i?.table?.fields?.find(s=>s.field===String(t.field))?.fieldType??""),a=["MIN","MAX"].includes(String(t.aggregation))&&["date","createdTime","lastModifiedTime"].includes(n),d=!a&&!ce.has(n),g=!a&&["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL"].includes(String(t.aggregation)),m=["SUM","AVERAGE","MIN","MAX"].includes(String(t.aggregation)),S=s=>{const p=m?re(i,t.field,t.precision):void 0;return p?String(p({value:s})??""):H(s,{precision:we(t,0)})},P=s=>{const p=re(i,t.field),f=s instanceof Date?s.toISOString():s;return String(p?p({value:f})??"":f??"")};return{...e,...y(e),...g?{cellDataType:e.cellDataType??"number"}:{},...a?{cellDataType:e.cellDataType??"dateString"}:{},align:e.align??(g?"right":void 0),fieldSource:()=>i?.table?.fields?.find(s=>s.field===String(t.field)),fieldFn:s=>{if(!i)return null;const p=x(i.table,String(t.field)),f=i.stored;if(f&&!d)return o(f.records.allLinkedTo(f.field,String(s?.id??"")).map(p));if(f){const h=String(s?.id??""),k=$t[String(t.aggregation)];return k?f.records.total(f.field,h,String(t.field),k)??null:t.aggregation==="COUNTA"||t.aggregation==="COUNTALL"?f.records.total(f.field,h)??null:o(f.records.allLinkedTo(f.field,h).map(p))}return o(i.rowsOf(s).map(p))},formatter:e.formatter??(s=>{if(a)return s.value==null||s.value===""?"":P(s.value);const p=g?U(s.value):typeof s.value=="number"?s.value:null;return p==null?String(s.value??""):S(p)})}}},{id:"count",get label(){return l("fields.typeCount")},get description(){return l("fields.typeCountDescription")},icon:u.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];
@@ -47,7 +47,7 @@ export { setBaseMessages, baseMessages, BASE_MESSAGES, type BaseMessages, type B
47
47
  export { setDateLocale, dateLocale } from '../date-locale.js';
48
48
  export { setRecordHistory, historyOf, loadHistory, type RecordChange, type RecordHistoryStore, type RecordHistoryContext } from './activity.svelte.js';
49
49
  export { setMentionHandler, type MentionEvent, type MentionHandler } from './activity.svelte.js';
50
- export { mentionToken, mentionIds, mentionText, parseMentions, encodeMentions, type MentionPart } from './mentions.js';
50
+ export { mentionToken, mentionIds, mentionText, parseMentions, encodeMentions, setMentionLinks, findMentionLinks, linkToken, safeHref, type MentionPart, type MentionLink } from './mentions.js';
51
51
  export { baseCondition, baseFilterOf } from './base-alerts.js';
52
52
  export { compileFieldFilter, describeFieldFilter, filterKindOf, operatorsFor, ME, type FieldFilter, type FieldCondition, type FieldConditionGroup, type FilterKind, type FilterOp, } from './filter-model.js';
53
53
  export type { FieldView, FieldViewType, ColorSetting } from './view-model.js';
@@ -1 +1 @@
1
- import{registerCellEditor as f,registerGridExtension as O,registerGridShortcuts as g}from"@svgrid/grid";import{nudgeEnterpriseFor as P}from"../license.js";import B from"./FieldCell.svelte";import L from"./RowAdder.svelte";import V from"./FootRowAdder.svelte";import H from"./AttachmentEditor.svelte";import K from"./FieldsHeaderEnd.svelte";import{askDeleteField as N,openFieldEditor as C,openRecord as U}from"./editor-request.svelte.js";import{enableAdvancedFilter as _,registerFilterKind as G}from"../advanced-filter-enable.js";import{compileFieldFilter as z,newCondition as F,resolveMeWith as W}from"./filter-model.js";import{hasBar as $,openBarPanel as T}from"./bar-request.svelte.js";import{groupRules as q,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 w}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 x,fillFieldColumn as ge,getFieldType as A,isServerGroupRow as Ce,originalColumn as b,registerFieldType as be,ruleFieldNames as ye,typeDrawsCell as he}from"./registry.svelte.js";import Fe from"./RatingEditor.svelte";import Te from"./LinkPickerEditor.svelte";import we from"./DateEditor.svelte";import ve from"./SelectEditor.svelte";import Me from"./NumberEditor.svelte";import xe from"./LongTextEditor.svelte";import Ae from"./RichTextEditor.svelte";import Ee from"./VoteEditor.svelte";import ke from"./TimerEditor.svelte";import Se from"./ChecklistEditor.svelte";import Re from"./ColorEditor.svelte";import De from"./TimeOfDayEditor.svelte";import Ie from"./RowHeader.svelte";import Oe from"./GroupHeader.svelte";import Pe from"./SummaryCell.svelte";import{getCurrentUser as E}from"./sources.svelte.js";import{fieldColumns as Be,gridOf as y,primaryIdOf as h,rememberGrid as Le}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,canPickChoice,defaultCanEditField,fieldEditorChoices,fieldEditors,setCanEditField,setFieldProtection}from"./field-access.svelte.js";export{FIELD_PREFIX,fieldToken,isFieldToken,personIds,recordOf,ruleFields,ruleNames,ruleUsers,tokenField}from"./people-rule.js";import{protectionText as Ve}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{default as SvPageEditor}from"./page/SvPageEditor.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,mergeByKey}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,commentThreads,resolveComment}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 He(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&&$(o)?[...F(r,e)?[{key:"field-filter",label:p("fields.menuFilter"),icon:m.filter,separatorBefore:!0,run:()=>Ke(o,r,e)}]:[],...o.groupingControlsEnabled?[]:[{key:"field-group",label:p("fields.menuGroup"),icon:m.group,run:()=>Ne(o,r)}]]:[];return[...i?[i]:[],{key:"field-edit",label:p("fields.menuEdit"),icon:m.edit,run:()=>C({ctrl:o,mode:"edit",columnId:r})},...t?[]:[{key:"field-left",label:p("fields.menuInsertLeft"),icon:m.left,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"left")})}],{key:"field-right",label:p("fields.menuInsertRight"),icon:m.right,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"right")})},{key:"field-duplicate",label:p("fields.menuDuplicate"),icon:m.duplicate,run:()=>{o.props.baseRefuseDuplicate?.(r)||re(o,r)}},...t?[]:[{key:"field-move-left",label:p("fields.menuMoveLeft"),icon:m.left,disabled:!S(o,r,-1),run:()=>R(o,r,-1)},{key:"field-move-right",label:p("fields.menuMoveRight"),icon:m.right,disabled:!S(o,r,1),run:()=>R(o,r,1)}],...l,...Je(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?N({ctrl:o,columnId:r}):te(o,r)}]]}function k(o,r,e){const i=(o.allColumns??[]).map(l=>l.id),t=i[i.indexOf(r)+e];if(!(!t||t===h(o)||o.isColumnPinned?.(t)!==o.isColumnPinned?.(r)))return t}const S=(o,r,e)=>!!k(o,r,e);function R(o,r,e){const i=k(o,r,e);if(!i)return;const t=o.allColumns.map(n=>n.id),l=t.indexOf(r),d=t.indexOf(i);t[l]=i,t[d]=r;const a=o.grid.getAllColumns().map(n=>n.id),s=o.userColumnOrder??[];o.moveColumnsByUser(je(s.length?[...s,...a.filter(n=>!s.includes(n))]:a,t))}function Ke(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]}),T(o,"filter")}function Ne(o,r){const e=q(o);e.some(i=>i.id===r)||j(o.buildApi(),[...e,{id:r,desc:!1}],X(o)),T(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=x(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),w(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;w(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(),U({ctrl:e,rowId:t.id}),!0)}function Ge(o,r){if(o.key!=="Enter"&&o.key!==" "||o.ctrlKey||o.metaKey||o.altKey||o.shiftKey||r.editing||!r.activeCell)return!1;const e=y(r.api);if(!e?.props?.baseDeleteSelection)return!1;const{rowIndex:i,colIndex:t}=r.activeCell,l=e.allColumns?.[t]?.columnDef.editorType,d=l==="checkbox";if(o.key===" "&&!d&&l!=="fieldVote")return!1;const 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 ze}from"./base-keys.svelte.js";import{treeGridKey as We}from"./tree-edit.js";import{fillDownKey as $e}from"./base-fill.js";import{autoSumKey as qe,formatKey as Xe}from"./excel-habits.svelte.js";import{orderKeepingScreen as je}from"./column-order.js";let I=!1;export function enableFields(){if(I)return;I=!0;for(const e of ae)A(e.id)||be(e);O({column:(e,i)=>ge(e,i),cell:B,hasCell:e=>he(e??{}),cellEdited:(e,i)=>{D(e,i.row,i.columnId,i.rowId,i.offGrid),Ue(e,i.row,i.columnId,i.rowId),Ye(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?A(e.fieldType)?.icon:null,headerNote:e=>{if(!e?.fieldType)return null;const i=typeof e.description=="string"?e.description:"",t=Ve(b(e),x(b(e)),ye(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?"right":!1,rowHeader:e=>e?.props?.expandRows?Ie:null,groupRow:e=>!e?.props?.rowModel&&Be(e).some(i=>i.fieldType)?Oe:null,summaryCell:e=>e?.props?.rowModel?null:Pe,rootClass:e=>{Le(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,He(e,i),!se(e)):[]});const o=e=>({value:e.value,typed:e.typed,columnDef:e.columnDef,columnId:e.columnId,row:e.row,onCommit:e.onCommit,onCancel:e.onCancel});f("fieldRating",{component:Fe,props:o,typeToEdit:e=>/^[0-9]$/.test(e)}),f("fieldLink",{component:Te,props:o,typeToEdit:e=>e!==" "}),f("fieldNumber",{component:Me,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9.,:+\-(=]/.test(e)}),f("fieldLongText",{component:xe,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove})}),f("fieldSelect",{component:ve,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:Ee,props:r,typeToEdit:e=>e===" "}),f("fieldTimer",{component:ke,props:e=>({...r(e),rowId:e.rowId,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>e===" "||/[0-9:]/.test(e)}),f("fieldColor",{component:Re,props:r}),f("fieldTime",{component:De,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)),W(()=>E()?.id),oe(),_(),g(_e,{id:"svgrid-fields-space"}),g(ze,{id:"svgrid-fields-keys"}),g(Ge,{id:"svgrid-base-keys"}),g($e,{id:"svgrid-base-fill-down"}),g(qe,{id:"svgrid-base-autosum",priority:200}),g(Xe,{id:"svgrid-base-format-keys",priority:200}),g(We,{id:"svgrid-base-tree"}),P("base","SvGrid Base")}export{inboxRecords,listColumns,listGroups,viewRecords}from"./list-view.js";import{aiFieldEdited as Ye,aiFieldMenuItems as Je}from"./ai-field.svelte.js";export{generateAIField,regenerateAIFields,cancelAIField,pendingAIField,setAIFieldConcurrency}from"./ai-field.svelte.js";export{aiPromptError,readAIAnswer}from"./ai-prompt.js";export{moveTile,newTile,putTile,removeTile,tileResult,tileRows,tileTitle}from"./dashboard.js";export{sharedTables,sharedViews,shareOf}from"./base-share.js";export{recordsAsShown,downloadAsShown,filesFolders,safeFolder}from"./base-export.js";export{permittedTables,permittedRecords,permittedViews,tablePermissions,gridPermissions,canDeleteRecord}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";export{recordDock,setRecordDock,recordDockWidth,setRecordDockWidth}from"./record-dock.svelte.js";
1
+ import{registerCellEditor as f,registerGridExtension as O,registerGridShortcuts as g}from"@svgrid/grid";import{nudgeEnterpriseFor as P}from"../license.js";import B from"./FieldCell.svelte";import L from"./RowAdder.svelte";import H from"./FootRowAdder.svelte";import V from"./AttachmentEditor.svelte";import K from"./FieldsHeaderEnd.svelte";import{askDeleteField as N,openFieldEditor as C,openRecord as U}from"./editor-request.svelte.js";import{enableAdvancedFilter as _,registerFilterKind as G}from"../advanced-filter-enable.js";import{compileFieldFilter as z,newCondition as F,resolveMeWith as W}from"./filter-model.js";import{hasBar as $,openBarPanel as T}from"./bar-request.svelte.js";import{groupRules as q,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 w}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 k,fillFieldColumn as ge,getFieldType as x,isServerGroupRow as Ce,originalColumn as b,registerFieldType as be,ruleFieldNames as ye,typeDrawsCell as he}from"./registry.svelte.js";import Fe from"./RatingEditor.svelte";import Te from"./LinkPickerEditor.svelte";import we from"./DateEditor.svelte";import ve from"./SelectEditor.svelte";import Me from"./NumberEditor.svelte";import ke from"./LongTextEditor.svelte";import xe from"./RichTextEditor.svelte";import Ae from"./VoteEditor.svelte";import Ee from"./TimerEditor.svelte";import Se from"./ChecklistEditor.svelte";import Re from"./ColorEditor.svelte";import De from"./TimeOfDayEditor.svelte";import Ie from"./RowHeader.svelte";import Oe from"./GroupHeader.svelte";import Pe from"./SummaryCell.svelte";import{getCurrentUser as A}from"./sources.svelte.js";import{fieldColumns as Be,gridOf as y,primaryIdOf as h,rememberGrid as Le}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,canPickChoice,defaultCanEditField,fieldEditorChoices,fieldEditors,setCanEditField,setFieldProtection}from"./field-access.svelte.js";export{FIELD_PREFIX,fieldToken,isFieldToken,personIds,recordOf,ruleFields,ruleNames,ruleUsers,tokenField}from"./people-rule.js";import{protectionText as He}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{default as SvPageEditor}from"./page/SvPageEditor.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,mergeByKey}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,commentThreads,resolveComment}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,setMentionLinks,findMentionLinks,linkToken,safeHref}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&&$(o)?[...F(r,e)?[{key:"field-filter",label:p("fields.menuFilter"),icon:m.filter,separatorBefore:!0,run:()=>Ke(o,r,e)}]:[],...o.groupingControlsEnabled?[]:[{key:"field-group",label:p("fields.menuGroup"),icon:m.group,run:()=>Ne(o,r)}]]:[];return[...i?[i]:[],{key:"field-edit",label:p("fields.menuEdit"),icon:m.edit,run:()=>C({ctrl:o,mode:"edit",columnId:r})},...t?[]:[{key:"field-left",label:p("fields.menuInsertLeft"),icon:m.left,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"left")})}],{key:"field-right",label:p("fields.menuInsertRight"),icon:m.right,run:()=>C({ctrl:o,mode:"add",index:v(o,r,"right")})},{key:"field-duplicate",label:p("fields.menuDuplicate"),icon:m.duplicate,run:()=>{o.props.baseRefuseDuplicate?.(r)||re(o,r)}},...t?[]:[{key:"field-move-left",label:p("fields.menuMoveLeft"),icon:m.left,disabled:!S(o,r,-1),run:()=>R(o,r,-1)},{key:"field-move-right",label:p("fields.menuMoveRight"),icon:m.right,disabled:!S(o,r,1),run:()=>R(o,r,1)}],...l,...Je(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?N({ctrl:o,columnId:r}):te(o,r)}]]}function E(o,r,e){const i=(o.allColumns??[]).map(l=>l.id),t=i[i.indexOf(r)+e];if(!(!t||t===h(o)||o.isColumnPinned?.(t)!==o.isColumnPinned?.(r)))return t}const S=(o,r,e)=>!!E(o,r,e);function R(o,r,e){const i=E(o,r,e);if(!i)return;const t=o.allColumns.map(n=>n.id),l=t.indexOf(r),d=t.indexOf(i);t[l]=i,t[d]=r;const a=o.grid.getAllColumns().map(n=>n.id),s=o.userColumnOrder??[];o.moveColumnsByUser(je(s.length?[...s,...a.filter(n=>!s.includes(n))]:a,t))}function Ke(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]}),T(o,"filter")}function Ne(o,r){const e=q(o);e.some(i=>i.id===r)||j(o.buildApi(),[...e,{id:r,desc:!1}],X(o)),T(o,"group")}function D(o,r,e,i,t){if(!r)return;const l=A()?.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=k(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),w(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;w(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(),U({ctrl:e,rowId:t.id}),!0)}function Ge(o,r){if(o.key!=="Enter"&&o.key!==" "||o.ctrlKey||o.metaKey||o.altKey||o.shiftKey||r.editing||!r.activeCell)return!1;const e=y(r.api);if(!e?.props?.baseDeleteSelection)return!1;const{rowIndex:i,colIndex:t}=r.activeCell,l=e.allColumns?.[t]?.columnDef.editorType,d=l==="checkbox";if(o.key===" "&&!d&&l!=="fieldVote")return!1;const 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 ze}from"./base-keys.svelte.js";import{treeGridKey as We}from"./tree-edit.js";import{fillDownKey as $e}from"./base-fill.js";import{autoSumKey as qe,formatKey as Xe}from"./excel-habits.svelte.js";import{orderKeepingScreen as je}from"./column-order.js";let I=!1;export function enableFields(){if(I)return;I=!0;for(const e of ae)x(e.id)||be(e);O({column:(e,i)=>ge(e,i),cell:B,hasCell:e=>he(e??{}),cellEdited:(e,i)=>{D(e,i.row,i.columnId,i.rowId,i.offGrid),Ue(e,i.row,i.columnId,i.rowId),Ye(e,i.row,i.columnId,i.rowId)},rangeAction:(e,i)=>e.props?.baseRangeAction?.(i)===!0,bodyEnd:L,footEnd:H,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=He(b(e),k(b(e)),ye(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?"right":!1,rowHeader:e=>e?.props?.expandRows?Ie:null,groupRow:e=>!e?.props?.rowModel&&Be(e).some(i=>i.fieldType)?Oe:null,summaryCell:e=>e?.props?.rowModel?null:Pe,rootClass:e=>{Le(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,inCell:e.inCell!==!1,onCommit:e.onCommit,onCancel:e.onCancel});f("fieldRating",{component:Fe,props:o,typeToEdit:e=>/^[0-9]$/.test(e)}),f("fieldLink",{component:Te,props:o,typeToEdit:e=>e!==" "}),f("fieldNumber",{component:Me,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove,onCommitAndMoveDown:e.onCommitAndMoveDown}),typeToEdit:e=>/[0-9.,:+\-(=]/.test(e)}),f("fieldLongText",{component:ke,props:e=>({...o(e),onCommitAndMove:e.onCommitAndMove})}),f("fieldSelect",{component:ve,props:e=>({...o(e),grid:e.grid,onChange:e.onChange,onCommitAndMove:e.onCommitAndMove})}),f("attachment",{component:V,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:xe,props:r}),f("fieldVote",{component:Ae,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:Re,props:r}),f("fieldTime",{component:De,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)),W(()=>A()?.id),oe(),_(),g(_e,{id:"svgrid-fields-space"}),g(ze,{id:"svgrid-fields-keys"}),g(Ge,{id:"svgrid-base-keys"}),g($e,{id:"svgrid-base-fill-down"}),g(qe,{id:"svgrid-base-autosum",priority:200}),g(Xe,{id:"svgrid-base-format-keys",priority:200}),g(We,{id:"svgrid-base-tree"}),P("base","SvGrid Base")}export{inboxRecords,listColumns,listGroups,viewRecords}from"./list-view.js";import{aiFieldEdited as Ye,aiFieldMenuItems as Je}from"./ai-field.svelte.js";export{generateAIField,regenerateAIFields,cancelAIField,pendingAIField,setAIFieldConcurrency}from"./ai-field.svelte.js";export{aiPromptError,readAIAnswer}from"./ai-prompt.js";export{moveTile,newTile,putTile,removeTile,tileResult,tileRows,tileTitle}from"./dashboard.js";export{sharedTables,sharedViews,shareOf}from"./base-share.js";export{recordsAsShown,downloadAsShown,filesFolders,safeFolder}from"./base-export.js";export{permittedTables,permittedRecords,permittedViews,tablePermissions,gridPermissions,canDeleteRecord}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";export{recordDock,setRecordDock,recordDockWidth,setRecordDockWidth}from"./record-dock.svelte.js";
@@ -9,16 +9,42 @@
9
9
  * people picked from the list into tokens when the comment is sent.
10
10
  */
11
11
  import type { FieldUser } from './sources.svelte.js';
12
- /** A run of a comment's text, or a mention in it. */
12
+ /**
13
+ * A run of a comment's text, a mention in it, or a link: `[name](href)` picked from
14
+ * the "@" list (a note of the host's), or a web address typed as it is (`bare`).
15
+ */
13
16
  export type MentionPart = {
14
17
  text: string;
15
18
  } | {
16
19
  mention: string;
17
20
  name: string;
21
+ } | {
22
+ link: string;
23
+ text: string;
24
+ bare?: boolean;
25
+ };
26
+ /** A page of the host's own that "@" can link to, such as a note: its name, its address, its icon. */
27
+ export type MentionLink = {
28
+ id: string;
29
+ name: string;
30
+ href: string;
31
+ icon?: string;
32
+ kind?: string;
18
33
  };
34
+ /** True for an address a link may go to: a web address, or a path of the same site. */
35
+ export declare function safeHref(href: string): boolean;
36
+ /**
37
+ * What else "@" can link to besides people and the table's records: the host's own
38
+ * pages, such as notes. Called with the words typed after "@"; null stops it.
39
+ */
40
+ export declare function setMentionLinks(source: ((query: string) => MentionLink[]) | null): void;
41
+ /** The host's pages for the words typed after "@" (a few, safe addresses only). */
42
+ export declare function findMentionLinks(query: string, limit?: number): MentionLink[];
43
+ /** The inline form of a link to one of the host's pages. */
44
+ export declare function linkToken(link: Pick<MentionLink, 'name' | 'href'>): string;
19
45
  /** The inline form of a mention of `user`. */
20
46
  export declare function mentionToken(user: Pick<FieldUser, 'id' | 'name'>): string;
21
- /** A comment's text cut into plain runs and mentions, in order. */
47
+ /** A comment's text cut into plain runs, mentions and links, in order. */
22
48
  export declare function parseMentions(text: string): MentionPart[];
23
49
  /** The ids a comment mentions, each once, in the order they first appear. */
24
50
  export declare function mentionIds(text: string): string[];
@@ -31,7 +57,9 @@ export declare function mentionText(text: string, nameOf?: (id: string) => strin
31
57
  * Turn each `@Name` of the people picked while typing into a token. A name
32
58
  * the user has since edited is no longer a mention and stays as typed.
33
59
  */
34
- export declare function encodeMentions(text: string, picked: ReadonlyArray<Pick<FieldUser, 'id' | 'name'>>): string;
60
+ export declare function encodeMentions(text: string, picked: ReadonlyArray<Pick<FieldUser, 'id' | 'name'> & {
61
+ href?: string;
62
+ }>): string;
35
63
  /**
36
64
  * The mention being typed at `caret`: where its `@` is and what follows it.
37
65
  * Null when the caret is not in one (the `@` must start the text or follow a
@@ -1 +1 @@
1
- const a=/@\[([^\]\n]*)\]\(([^)\s]+)\)/g,f=e=>{try{return decodeURIComponent(e)}catch{return e}};export function mentionToken(e){return`@[${e.name.replace(/[[\]\r\n]/g,"").trim()}](${encodeURIComponent(e.id).replace(/\)/g,"%29")})`}export function parseMentions(e){const r=[];let o=0;for(const t of e.matchAll(a)){const s=t.index??0;s>o&&r.push({text:e.slice(o,s)}),r.push({mention:f(t[2]),name:t[1]}),o=s+t[0].length}return o<e.length&&r.push({text:e.slice(o)}),r}export function mentionIds(e){const r=[];for(const o of e.matchAll(a)){const t=f(o[2]);r.includes(t)||r.push(t)}return r}export function mentionText(e,r){return parseMentions(e).map(o=>"mention"in o?`@${r?.(o.mention)??o.name}`:o.text).join("")}export function encodeMentions(e,r){const o=[...r].sort((s,n)=>n.name.length-s.name.length);let t=e;for(const s of o){const n=`@${s.name}`;let i=0;for(let c=t.indexOf(n,i);c>=0;c=t.indexOf(n,i)){const l=t[c+n.length];if(l!==void 0&&/[\p{L}\p{N}_]/u.test(l)){i=c+n.length;continue}const u=mentionToken(s);t=t.slice(0,c)+u+t.slice(c+n.length),i=c+u.length}}return t}export function mentionQuery(e,r){const o=e.slice(0,r),t=o.lastIndexOf("@");if(t<0)return null;const s=t>0?o[t-1]:" ";if(!/[\s([{"']/.test(s))return null;const n=o.slice(t+1);return n.length>30||/^\s|\s$|[\n@]/.test(n)?null:{start:t,query:n}}export function matchMentionUsers(e,r,o=8){const t=r.trim().toLowerCase();if(!t)return e.slice(0,o);const s=n=>{const i=n.name.toLowerCase();return i.startsWith(t)?0:i.split(/\s+/).some(c=>c.startsWith(t))?1:n.email?.toLowerCase().startsWith(t)?2:-1};return e.map(n=>({u:n,r:s(n)})).filter(n=>n.r>=0).sort((n,i)=>n.r-i.r).slice(0,o).map(n=>n.u)}export function insertMention(e,r,o,t){const s=`@${t.name} `,n=e.slice(o).replace(/^ /,"");return{text:e.slice(0,r)+s+n,caret:r+s.length}}
1
+ const m=/@\[([^\]\n]*)\]\(([^)\s]+)\)|\[([^\]\n]+)\]\(((?:https?:\/\/|\/(?!\/))[^)\s]+)\)/g,p=/\bhttps?:\/\/[^\s<>"']*[^\s<>"'.,;:!?)\]]/gi;export function safeHref(n){return/^https?:\/\//i.test(n)||/^\/(?!\/)/.test(n)}let l=null;export function setMentionLinks(n){l=n}export function findMentionLinks(n,r=5){if(!l)return[];try{return l(n).filter(e=>e&&e.name&&safeHref(e.href)).slice(0,r)}catch{return[]}}export function linkToken(n){return`[${n.name.replace(/[[\]\r\n]/g,"").trim()}](${n.href.replace(/[)\s]/g,r=>encodeURIComponent(r))})`}function h(n,r){let e=0;for(const t of n.matchAll(p)){const i=t.index??0;i>e&&r.push({text:n.slice(e,i)}),r.push({link:t[0],text:t[0],bare:!0}),e=i+t[0].length}e<n.length&&r.push({text:n.slice(e)})}const f=n=>{try{return decodeURIComponent(n)}catch{return n}};export function mentionToken(n){return`@[${n.name.replace(/[[\]\r\n]/g,"").trim()}](${encodeURIComponent(n.id).replace(/\)/g,"%29")})`}export function parseMentions(n){const r=[];let e=0;for(const t of n.matchAll(m)){const i=t.index??0;i>e&&h(n.slice(e,i),r),t[2]!==void 0?r.push({mention:f(t[2]),name:t[1]}):r.push({link:f(t[4]),text:t[3]}),e=i+t[0].length}return e<n.length&&h(n.slice(e),r),r}export function mentionIds(n){const r=[];for(const e of n.matchAll(m)){if(e[2]===void 0)continue;const t=f(e[2]);r.includes(t)||r.push(t)}return r}export function mentionText(n,r){return parseMentions(n).map(e=>"mention"in e?`@${r?.(e.mention)??e.name}`:"link"in e&&!e.bare?`@${e.text}`:e.text).join("")}export function encodeMentions(n,r){const e=[...r].sort((i,o)=>o.name.length-i.name.length);let t=n;for(const i of e){const o=`@${i.name}`;let s=0;for(let c=t.indexOf(o,s);c>=0;c=t.indexOf(o,s)){const u=t[c+o.length];if(u!==void 0&&/[\p{L}\p{N}_]/u.test(u)){s=c+o.length;continue}const a=i.href?linkToken({name:i.name,href:i.href}):mentionToken(i);t=t.slice(0,c)+a+t.slice(c+o.length),s=c+a.length}}return t}export function mentionQuery(n,r){const e=n.slice(0,r),t=e.lastIndexOf("@");if(t<0)return null;const i=t>0?e[t-1]:" ";if(!/[\s([{"']/.test(i))return null;const o=e.slice(t+1);return o.length>30||/^\s|\s$|[\n@]/.test(o)?null:{start:t,query:o}}export function matchMentionUsers(n,r,e=8){const t=r.trim().toLowerCase();if(!t)return n.slice(0,e);const i=o=>{const s=o.name.toLowerCase();return s.startsWith(t)?0:s.split(/\s+/).some(c=>c.startsWith(t))?1:o.email?.toLowerCase().startsWith(t)?2:-1};return n.map(o=>({u:o,r:i(o)})).filter(o=>o.r>=0).sort((o,s)=>o.r-s.r).slice(0,e).map(o=>o.u)}export function insertMention(n,r,e,t){const i=`@${t.name} `,o=n.slice(e).replace(/^ /,"");return{text:n.slice(0,r)+i+o,caret:r+i.length}}
@@ -303,6 +303,8 @@ export declare const EXTRAS_MESSAGES: {
303
303
  readonly 'extras.aiInto': "Put the answer in";
304
304
  readonly 'extras.aiNowhere': "No field (use {ai} in the next steps)";
305
305
  readonly 'extras.aiHint': "Name fields in braces. The answer is {ai} in the next steps.";
306
+ readonly 'extras.aiBase': "Send it the whole base";
307
+ readonly 'extras.aiBaseHint': "The records of every table go with the prompt, for a letter about all of it (\"What should I do this week?\").";
306
308
  readonly 'extras.scriptCode': "Script";
307
309
  readonly 'extras.scriptNeedsBrowser': "A script runs in the browser: set Runs in to The browser.";
308
310
  readonly 'extras.scriptHint': "JavaScript, as in Airtable: input.config() has the record's fields by name; base.getTable('Name') reads and changes a table (selectRecordsAsync, updateRecordAsync, createRecordAsync, deleteRecordAsync); output.set('name', value) is {script.name} in the next steps; fetch() calls https addresses that allow it. It runs in a sandbox for up to 30 seconds.";