@svgrid/enterprise 3.1.57 → 3.1.59

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 (64) hide show
  1. package/dist/SvGridBoard.svelte +1 -1
  2. package/dist/SvGridScheduler.svelte +1 -1
  3. package/dist/SvRecordDetail.svelte +1 -1
  4. package/dist/SvSchedule.svelte +1 -1
  5. package/dist/cdn/svgrid-enterprise.svelte-external.js +295 -295
  6. package/dist/date-locale.d.ts +8 -0
  7. package/dist/date-locale.js +1 -0
  8. package/dist/designer/assets/{index-DfYT4Bxh.js → index-BAAiipJp.js} +310 -310
  9. package/dist/designer/index.html +1 -1
  10. package/dist/fields/BaseInboxView.svelte +1 -1
  11. package/dist/fields/BaseTableView.svelte +1 -1
  12. package/dist/fields/ButtonCell.svelte +6 -5
  13. package/dist/fields/ButtonCell.svelte.d.ts +6 -5
  14. package/dist/fields/FieldEditor.svelte +30 -6
  15. package/dist/fields/PeopleRulePicker.svelte +34 -0
  16. package/dist/fields/PeopleRulePicker.svelte.d.ts +16 -0
  17. package/dist/fields/PropertyInput.svelte +36 -2
  18. package/dist/fields/RecordView.svelte +26 -8
  19. package/dist/fields/SelectEditor.svelte +1 -1
  20. package/dist/fields/SvBase.svelte +1 -1
  21. package/dist/fields/activity.svelte.d.ts +34 -0
  22. package/dist/fields/activity.svelte.js +1 -1
  23. package/dist/fields/automations.svelte.d.ts +6 -0
  24. package/dist/fields/automations.svelte.js +1 -1
  25. package/dist/fields/base-permissions.d.ts +13 -0
  26. package/dist/fields/base-permissions.js +1 -1
  27. package/dist/fields/builtin-types.js +1 -1
  28. package/dist/fields/button-host.d.ts +63 -0
  29. package/dist/fields/button-host.js +1 -0
  30. package/dist/fields/button.d.ts +36 -1
  31. package/dist/fields/button.js +1 -1
  32. package/dist/fields/field-access.svelte.d.ts +38 -8
  33. package/dist/fields/field-access.svelte.js +1 -1
  34. package/dist/fields/index.d.ts +5 -3
  35. package/dist/fields/index.js +1 -1
  36. package/dist/fields/messages/fields.d.ts +62 -2
  37. package/dist/fields/messages/fields.js +1 -1
  38. package/dist/fields/messages/record.d.ts +7 -0
  39. package/dist/fields/messages/record.js +1 -1
  40. package/dist/fields/messages.svelte.d.ts +73 -3
  41. package/dist/fields/messages.svelte.js +1 -1
  42. package/dist/fields/people-rule.d.ts +35 -0
  43. package/dist/fields/people-rule.js +1 -0
  44. package/dist/fields/record-delete.svelte.js +1 -1
  45. package/dist/fields/record-menu.js +1 -1
  46. package/dist/fields/registry.svelte.d.ts +22 -0
  47. package/dist/fields/registry.svelte.js +1 -1
  48. package/dist/fields/view-model.js +1 -1
  49. package/dist/gantt/SvGridGantt.svelte +1 -1
  50. package/dist/gantt/gantt-model.js +1 -1
  51. package/dist/index.d.ts +1 -0
  52. package/dist/index.js +1 -1
  53. package/dist/node/studio.js +1 -1
  54. package/dist/version.d.ts +2 -2
  55. package/dist/version.js +1 -1
  56. package/dist/wc/board-CEIIZoaC.js +26 -0
  57. package/dist/wc/{palette-DkaM8TCP.js → date-locale-CKE0m3Dc.js} +9 -9
  58. package/dist/wc/gantt-_heLybcH.js +115 -0
  59. package/dist/wc/scheduler-CGoM4ahy.js +160 -0
  60. package/dist/wc/sv-base-element.js +198 -196
  61. package/package.json +3 -3
  62. package/dist/wc/board-C2hPY2IP.js +0 -26
  63. package/dist/wc/gantt-DBRJiYsr.js +0 -115
  64. package/dist/wc/scheduler-DJZRC1fj.js +0 -160
@@ -24,7 +24,19 @@ export type RecordComment = {
24
24
  * it, and the store keeps it from people outside the team (a client portal).
25
25
  */
26
26
  internal?: boolean;
27
+ /**
28
+ * Who voted it up and who down, by user id (a store with `vote`, or no
29
+ * store). A person has one vote on a comment, and none on their own.
30
+ */
31
+ votes?: CommentVotes;
27
32
  };
33
+ /** A comment's votes: the ids of the people who voted it up, and down. */
34
+ export type CommentVotes = {
35
+ up?: string[];
36
+ down?: string[];
37
+ };
38
+ /** A person's vote on a comment; null takes it back. */
39
+ export type CommentVote = 'up' | 'down' | null;
28
40
  /** Which record a comment store is asked about, beyond its row id. */
29
41
  export type RecordCommentContext = {
30
42
  /** The table of `<SvBase tables>` the record is in; undefined for a single table or a plain grid. */
@@ -60,6 +72,12 @@ export type RecordCommentStore = {
60
72
  files?: boolean;
61
73
  /** It keeps internal notes: the comment box offers to mark one for the team only. */
62
74
  internal?: boolean;
75
+ /**
76
+ * Someone voted a comment up or down, or took their vote back (null). With
77
+ * it the record view shows Up and Down under each comment; without it a
78
+ * store's comments take no votes. `comment` is the comment with the vote.
79
+ */
80
+ vote?: (rowId: string, comment: RecordComment, vote: CommentVote, api: unknown, context: RecordCommentContext) => void;
63
81
  };
64
82
  export type RecordChange = {
65
83
  at: number;
@@ -223,6 +241,22 @@ export declare function addComment(ctrl: any, rowId: string, text: string, extra
223
241
  export declare function ownsComment(comment: RecordComment, what: 'update' | 'remove'): boolean;
224
242
  /** Change a comment's text. Only its author can; someone newly named in it hears of it. */
225
243
  export declare function editComment(ctrl: any, rowId: string, id: string, text: string): void;
244
+ /** Whether comments take votes here: no store (they are kept in the page), or a store with `vote`. */
245
+ export declare const commentsTakeVotes: () => boolean;
246
+ /** The people who voted a comment up and down, each list without repeats. */
247
+ export declare function commentVotes(comment: RecordComment): {
248
+ up: string[];
249
+ down: string[];
250
+ };
251
+ /** The signed-in person's vote on a comment, or null. */
252
+ export declare function myCommentVote(comment: RecordComment): CommentVote;
253
+ /** Whether the signed-in person may vote a comment: someone signed in, not its author, where votes are kept. */
254
+ export declare function mayVoteComment(comment: RecordComment): boolean;
255
+ /**
256
+ * Vote a comment up or down. Pressing the vote a person already gave takes
257
+ * it back; the other vote replaces it. Nobody votes their own comment.
258
+ */
259
+ export declare function voteComment(ctrl: any, rowId: string, id: string, vote: 'up' | 'down'): void;
226
260
  /** Delete a comment. Only its author can. */
227
261
  export declare function deleteComment(ctrl: any, rowId: string, id: string): void;
228
262
  /** "just now", "5 minutes ago", "3 hours ago", else the date. */
@@ -1 +1 @@
1
- import{untrack}from"svelte";import{findFieldUser,getCurrentUser}from"./sources.svelte.js";import{mentionIds,parseMentions}from"./mentions.js";import{bm,bmCount}from"./messages.svelte.js";export const RECORDS_KEPT=2e4;let version=$state(0);const changes={bases:new WeakMap,grids:new WeakMap};const memory={bases:new WeakMap,grids:new WeakMap};const unseen={bases:new WeakMap,grids:new WeakMap};const ANY_BASE={};let store=null;let mentionHandler=null;let historyStore=null;const loaded={bases:new WeakMap,grids:new WeakMap};export function tableIdOf(ctrl){const id=ctrl?.props?.baseTableId;return typeof id==="string"&&id?id:void 0}function rowsOf(kept,scope,create){const named=typeof scope==="string"?{tableId:scope}:"tableId"in scope&&typeof scope.tableId==="string"?scope:null;const tableId=named?named.tableId:tableIdOf(scope);if(!tableId){let byRow2=kept.grids.get(scope);if(!byRow2&&create)kept.grids.set(scope,byRow2=new Map);return byRow2}const base=(named?named.base:scope?.props?.baseScope)??ANY_BASE;let byTable=kept.bases.get(base);if(!byTable&&create)kept.bases.set(base,byTable=new Map);let byRow=byTable?.get(tableId);if(!byRow&&byTable&&create)byTable.set(tableId,byRow=new Map);return byRow}export function setRecordComments(next){store=next;untrack(()=>version+=1)}export function setRecordHistory(next){historyStore=next;loaded.bases=new WeakMap;loaded.grids=new WeakMap;untrack(()=>version+=1)}const historyScope=scope=>{if(typeof scope==="string")return{tableId:scope};if("tableId"in scope&&typeof scope.tableId==="string")return{tableId:scope.tableId};const tableId=tableIdOf(scope);return tableId?{tableId}:scope};const historyContext=scope=>{const tableId=typeof scope==="string"?scope:"tableId"in scope&&typeof scope.tableId==="string"?scope.tableId:tableIdOf(scope);const api=typeof scope==="object"&&!("tableId"in scope)?scope?.buildApi?.():void 0;return{...tableId?{tableId}:{},...api?{api}:{}}};function keep(scope,rowId,change){if(!historyStore?.add)return;try{historyStore.add(rowId,change,historyContext(scope))}catch(err){console.error(err)}}export function loadHistory(scope,rowId){const kept=historyStore;if(!kept)return;const byRow=rowsOf(loaded,historyScope(scope),true);const was=byRow.get(rowId)?.[0];const ask=(was?.ask??0)+1;byRow.set(rowId,[{entries:was?.entries??[],loading:true,ask}]);untrack(()=>version+=1);const done=(entries,error)=>{if(historyStore!==kept||byRow.get(rowId)?.[0]?.ask!==ask)return;byRow.set(rowId,[{entries:Array.isArray(entries)?entries:[],loading:false,ask,...error?{error}:{}}]);version+=1};try{const out=kept.list(rowId,historyContext(scope));if(out&&typeof out.then==="function"){;out.then(entries=>done(entries),err=>done(was?.entries??[],err instanceof Error?err.message:String(err)))}else done(out)}catch(err){done(was?.entries??[],err instanceof Error?err.message:String(err))}}export function historyState(scope,rowId){void version;const l=rowsOf(loaded,historyScope(scope),false)?.get(rowId)?.[0];return{loading:!!l?.loading,...l?.error?{error:l.error}:{}}}const changeKey=c=>`${c.at}|${c.columnId}|${c.by??""}|${c.added?1:0}`;export function historyOf(scope,rowId){const session=changesOf(scope,rowId);const stored=rowsOf(loaded,historyScope(scope),false)?.get(rowId)?.[0]?.entries;if(!stored?.length)return session;const seen=new Set(stored.map(changeKey));return[...stored,...session.filter(c=>!seen.has(changeKey(c)))].sort((a,b)=>a.at-b.at)}export function setMentionHandler(next){mentionHandler=next}export function releaseMentionHandler(fn){if(mentionHandler===fn)mentionHandler=null}export function noteChange(scope,rowId,columnId,value,automation,via,how){const change={at:Date.now(),...automation?{automation}:{by:getCurrentUser()?.id},...via?{via}:{},columnId,value:Array.isArray(value)?[...value]:value,...how&&"from"in how?{from:copy(how.from)}:{},...how?.undone?{undone:true}:{},...how?.redone?{redone:true}:{}};const held=unstored.get(rowId);if(held)return void held.push(()=>addChange(scope,rowId,change));addChange(scope,rowId,change)}const unstored=new Map;export function holdChanges(rowId){if(!unstored.has(rowId))unstored.set(rowId,[])}export function releaseChanges(rowId,stored){const held=unstored.get(rowId);unstored.delete(rowId);if(stored&&held?.length)noteAtOnce(()=>held.forEach(note=>note()))}function addChange(scope,rowId,change){const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];list.push(change);if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);if(byRow.size>RECORDS_KEPT)byRow.delete(byRow.keys().next().value);if(noting)changedWhileNoting=true;else version+=1;keep(scope,rowId,change)}let noting=false;let changedWhileNoting=false;export function noteAtOnce(notes){const outer=noting;noting=true;try{return notes()}finally{noting=outer;if(!outer&&changedWhileNoting){changedWhileNoting=false;version+=1}}}export function changesOf(scope,rowId){void version;return rowsOf(changes,scope,false)?.get(rowId)??[]}export function noteRemoteChange(scope,rowId,change){const at=Date.now();const fields=change.fields??[];if(!change.added&&!fields.length)return;const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];const by=change.by?{by:change.by}:{};if(change.added)list.push({at,...by,remote:true,added:true,columnId:"",value:void 0});for(const f of fields)list.push({at,...by,remote:true,columnId:f.columnId,value:copy(f.to),from:copy(f.from)});if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);if(byRow.size>RECORDS_KEPT)byRow.delete(byRow.keys().next().value);const marks=rowsOf(unseen,scope,true);const was=marks.get(rowId)?.[0];const columns=new Set([...was?.columns??[],...fields.map(f=>f.columnId)]);marks.set(rowId,[{at,...by,columns,...change.added||was?.added?{added:true}:{}}]);version+=1}const copy=v=>Array.isArray(v)?[...v]:v;export function unseenOf(scope,rowId){void version;return rowsOf(unseen,scope,false)?.get(rowId)?.[0]}export function unseenIn(scope){void version;const out=new Map;for(const[id,list]of rowsOf(unseen,scope,false)??[])if(list[0])out.set(id,list[0]);return out}export function markSeen(scope,rowId){const marks=rowsOf(unseen,scope,false);if(marks?.delete(rowId))version+=1}export function markAllSeen(scope){const marks=rowsOf(unseen,scope,false);if(marks?.size){marks.clear();version+=1}}const contextOf=ctrl=>({tableId:tableIdOf(ctrl),api:ctrl?.buildApi?.()});const commentScope=ctrl=>{const tableId=tableIdOf(ctrl);return tableId?{tableId}:ctrl};export function commentsOf(ctrl,rowId){void version;if(store){const context=contextOf(ctrl);return store.list(rowId,context.api,context)}return rowsOf(memory,commentScope(ctrl),false)?.get(rowId)??[]}let seq=0;export function commentStoreTakes(what){return!!store?.[what]}export function addComment(ctrl,rowId,text,extra={}){const body=text.trim();const files=store?.files&&extra.files?.length?extra.files:[];if(!body&&!files.length)return;const context=contextOf(ctrl);const mentions=mentionIds(body);const comment={id:`c${Date.now().toString(36)}${seq+=1}`,rowId,...context.tableId?{tableId:context.tableId}:{},text:body,at:Date.now(),by:getCurrentUser()?.id,...mentions.length?{mentions}:{},...files.length?{files}:{},...store?.internal&&extra.internal?{internal:true}:{}};const kept=store;if(kept)kept.add(rowId,comment,context.api,context);else{const byRow=rowsOf(memory,commentScope(ctrl),true);byRow.set(rowId,[...byRow.get(rowId)??[],comment])}version+=1;announceMentions(ctrl,rowId,comment,mentions)}function announceMentions(ctrl,rowId,comment,mentions){const kept=store;const context=contextOf(ctrl);if(!mentions.length||!kept?.onMention&&!mentionHandler)return;const written=new Map(parseMentions(comment.text).flatMap(p=>"mention"in p?[[p.mention,p.name]]:[]));const event={comment,mentioned:mentions.map(id=>findFieldUser(id)??{id,name:written.get(id)||id}),rowId,...context.tableId?{tableId:context.tableId}:{},record:(ctrl?.allRows??[]).find(r=>r.id===rowId)?.original,api:context.api};for(const hook of[kept?.onMention,mentionHandler]){try{hook?.(event)}catch(err){console.error(err)}}}export function ownsComment(comment,what){if(store&&!store[what])return false;return comment.by===getCurrentUser()?.id}export function editComment(ctrl,rowId,id,text){const body=text.trim();const was=commentsOf(ctrl,rowId).find(c=>c.id===id);if(!was||!body&&!was.files?.length||!ownsComment(was,"update")||body===was.text)return;const mentions=mentionIds(body);const{mentions:_old,...rest}=was;const comment={...rest,text:body,editedAt:Date.now(),...mentions.length?{mentions}:{}};const kept=store;const context=contextOf(ctrl);if(kept)kept.update(rowId,comment,context.api,context);else{const byRow=rowsOf(memory,commentScope(ctrl),true);byRow.set(rowId,(byRow.get(rowId)??[]).map(c=>c.id===id?comment:c))}version+=1;announceMentions(ctrl,rowId,comment,mentions.filter(m=>!was.mentions?.includes(m)))}export function deleteComment(ctrl,rowId,id){const was=commentsOf(ctrl,rowId).find(c=>c.id===id);if(!was||!ownsComment(was,"remove"))return;const kept=store;const context=contextOf(ctrl);if(kept)kept.remove(rowId,id,context.api,context);else{const byRow=rowsOf(memory,commentScope(ctrl),true);byRow.set(rowId,(byRow.get(rowId)??[]).filter(c=>c.id!==id))}version+=1}export function timeAgo(at,now=Date.now()){const s=Math.max(0,Math.round((now-at)/1e3));if(s<45)return bm("record.justNow");const m=Math.round(s/60);if(m<60)return bmCount("record.minutesAgo",m);const h=Math.round(m/60);if(h<24)return bmCount("record.hoursAgo",h);return new Date(at).toLocaleDateString()}
1
+ import{untrack}from"svelte";import{findFieldUser,getCurrentUser}from"./sources.svelte.js";import{mentionIds,parseMentions}from"./mentions.js";import{bm,bmCount}from"./messages.svelte.js";export const RECORDS_KEPT=2e4;let version=$state(0);const changes={bases:new WeakMap,grids:new WeakMap};const memory={bases:new WeakMap,grids:new WeakMap};const unseen={bases:new WeakMap,grids:new WeakMap};const ANY_BASE={};let store=null;let mentionHandler=null;let historyStore=null;const loaded={bases:new WeakMap,grids:new WeakMap};export function tableIdOf(ctrl){const id=ctrl?.props?.baseTableId;return typeof id==="string"&&id?id:void 0}function rowsOf(kept,scope,create){const named=typeof scope==="string"?{tableId:scope}:"tableId"in scope&&typeof scope.tableId==="string"?scope:null;const tableId=named?named.tableId:tableIdOf(scope);if(!tableId){let byRow2=kept.grids.get(scope);if(!byRow2&&create)kept.grids.set(scope,byRow2=new Map);return byRow2}const base=(named?named.base:scope?.props?.baseScope)??ANY_BASE;let byTable=kept.bases.get(base);if(!byTable&&create)kept.bases.set(base,byTable=new Map);let byRow=byTable?.get(tableId);if(!byRow&&byTable&&create)byTable.set(tableId,byRow=new Map);return byRow}export function setRecordComments(next){store=next;untrack(()=>version+=1)}export function setRecordHistory(next){historyStore=next;loaded.bases=new WeakMap;loaded.grids=new WeakMap;untrack(()=>version+=1)}const historyScope=scope=>{if(typeof scope==="string")return{tableId:scope};if("tableId"in scope&&typeof scope.tableId==="string")return{tableId:scope.tableId};const tableId=tableIdOf(scope);return tableId?{tableId}:scope};const historyContext=scope=>{const tableId=typeof scope==="string"?scope:"tableId"in scope&&typeof scope.tableId==="string"?scope.tableId:tableIdOf(scope);const api=typeof scope==="object"&&!("tableId"in scope)?scope?.buildApi?.():void 0;return{...tableId?{tableId}:{},...api?{api}:{}}};function keep(scope,rowId,change){if(!historyStore?.add)return;try{historyStore.add(rowId,change,historyContext(scope))}catch(err){console.error(err)}}export function loadHistory(scope,rowId){const kept=historyStore;if(!kept)return;const byRow=rowsOf(loaded,historyScope(scope),true);const was=byRow.get(rowId)?.[0];const ask=(was?.ask??0)+1;byRow.set(rowId,[{entries:was?.entries??[],loading:true,ask}]);untrack(()=>version+=1);const done=(entries,error)=>{if(historyStore!==kept||byRow.get(rowId)?.[0]?.ask!==ask)return;byRow.set(rowId,[{entries:Array.isArray(entries)?entries:[],loading:false,ask,...error?{error}:{}}]);version+=1};try{const out=kept.list(rowId,historyContext(scope));if(out&&typeof out.then==="function"){;out.then(entries=>done(entries),err=>done(was?.entries??[],err instanceof Error?err.message:String(err)))}else done(out)}catch(err){done(was?.entries??[],err instanceof Error?err.message:String(err))}}export function historyState(scope,rowId){void version;const l=rowsOf(loaded,historyScope(scope),false)?.get(rowId)?.[0];return{loading:!!l?.loading,...l?.error?{error:l.error}:{}}}const changeKey=c=>`${c.at}|${c.columnId}|${c.by??""}|${c.added?1:0}`;export function historyOf(scope,rowId){const session=changesOf(scope,rowId);const stored=rowsOf(loaded,historyScope(scope),false)?.get(rowId)?.[0]?.entries;if(!stored?.length)return session;const seen=new Set(stored.map(changeKey));return[...stored,...session.filter(c=>!seen.has(changeKey(c)))].sort((a,b)=>a.at-b.at)}export function setMentionHandler(next){mentionHandler=next}export function releaseMentionHandler(fn){if(mentionHandler===fn)mentionHandler=null}export function noteChange(scope,rowId,columnId,value,automation,via,how){const change={at:Date.now(),...automation?{automation}:{by:getCurrentUser()?.id},...via?{via}:{},columnId,value:Array.isArray(value)?[...value]:value,...how&&"from"in how?{from:copy(how.from)}:{},...how?.undone?{undone:true}:{},...how?.redone?{redone:true}:{}};const held=unstored.get(rowId);if(held)return void held.push(()=>addChange(scope,rowId,change));addChange(scope,rowId,change)}const unstored=new Map;export function holdChanges(rowId){if(!unstored.has(rowId))unstored.set(rowId,[])}export function releaseChanges(rowId,stored){const held=unstored.get(rowId);unstored.delete(rowId);if(stored&&held?.length)noteAtOnce(()=>held.forEach(note=>note()))}function addChange(scope,rowId,change){const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];list.push(change);if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);if(byRow.size>RECORDS_KEPT)byRow.delete(byRow.keys().next().value);if(noting)changedWhileNoting=true;else version+=1;keep(scope,rowId,change)}let noting=false;let changedWhileNoting=false;export function noteAtOnce(notes){const outer=noting;noting=true;try{return notes()}finally{noting=outer;if(!outer&&changedWhileNoting){changedWhileNoting=false;version+=1}}}export function changesOf(scope,rowId){void version;return rowsOf(changes,scope,false)?.get(rowId)??[]}export function noteRemoteChange(scope,rowId,change){const at=Date.now();const fields=change.fields??[];if(!change.added&&!fields.length)return;const byRow=rowsOf(changes,scope,true);const list=byRow.get(rowId)??[];const by=change.by?{by:change.by}:{};if(change.added)list.push({at,...by,remote:true,added:true,columnId:"",value:void 0});for(const f of fields)list.push({at,...by,remote:true,columnId:f.columnId,value:copy(f.to),from:copy(f.from)});if(list.length>50)list.splice(0,list.length-50);byRow.set(rowId,list);if(byRow.size>RECORDS_KEPT)byRow.delete(byRow.keys().next().value);const marks=rowsOf(unseen,scope,true);const was=marks.get(rowId)?.[0];const columns=new Set([...was?.columns??[],...fields.map(f=>f.columnId)]);marks.set(rowId,[{at,...by,columns,...change.added||was?.added?{added:true}:{}}]);version+=1}const copy=v=>Array.isArray(v)?[...v]:v;export function unseenOf(scope,rowId){void version;return rowsOf(unseen,scope,false)?.get(rowId)?.[0]}export function unseenIn(scope){void version;const out=new Map;for(const[id,list]of rowsOf(unseen,scope,false)??[])if(list[0])out.set(id,list[0]);return out}export function markSeen(scope,rowId){const marks=rowsOf(unseen,scope,false);if(marks?.delete(rowId))version+=1}export function markAllSeen(scope){const marks=rowsOf(unseen,scope,false);if(marks?.size){marks.clear();version+=1}}const contextOf=ctrl=>({tableId:tableIdOf(ctrl),api:ctrl?.buildApi?.()});const commentScope=ctrl=>{const tableId=tableIdOf(ctrl);return tableId?{tableId}:ctrl};export function commentsOf(ctrl,rowId){void version;if(store){const context=contextOf(ctrl);return store.list(rowId,context.api,context)}return rowsOf(memory,commentScope(ctrl),false)?.get(rowId)??[]}let seq=0;export function commentStoreTakes(what){return!!store?.[what]}export function addComment(ctrl,rowId,text,extra={}){const body=text.trim();const files=store?.files&&extra.files?.length?extra.files:[];if(!body&&!files.length)return;const context=contextOf(ctrl);const mentions=mentionIds(body);const comment={id:`c${Date.now().toString(36)}${seq+=1}`,rowId,...context.tableId?{tableId:context.tableId}:{},text:body,at:Date.now(),by:getCurrentUser()?.id,...mentions.length?{mentions}:{},...files.length?{files}:{},...store?.internal&&extra.internal?{internal:true}:{}};const kept=store;if(kept)kept.add(rowId,comment,context.api,context);else{const byRow=rowsOf(memory,commentScope(ctrl),true);byRow.set(rowId,[...byRow.get(rowId)??[],comment])}version+=1;announceMentions(ctrl,rowId,comment,mentions)}function announceMentions(ctrl,rowId,comment,mentions){const kept=store;const context=contextOf(ctrl);if(!mentions.length||!kept?.onMention&&!mentionHandler)return;const written=new Map(parseMentions(comment.text).flatMap(p=>"mention"in p?[[p.mention,p.name]]:[]));const event={comment,mentioned:mentions.map(id=>findFieldUser(id)??{id,name:written.get(id)||id}),rowId,...context.tableId?{tableId:context.tableId}:{},record:(ctrl?.allRows??[]).find(r=>r.id===rowId)?.original,api:context.api};for(const hook of[kept?.onMention,mentionHandler]){try{hook?.(event)}catch(err){console.error(err)}}}export function ownsComment(comment,what){if(store&&!store[what])return false;return comment.by===getCurrentUser()?.id}export function editComment(ctrl,rowId,id,text){const body=text.trim();const was=commentsOf(ctrl,rowId).find(c=>c.id===id);if(!was||!body&&!was.files?.length||!ownsComment(was,"update")||body===was.text)return;const mentions=mentionIds(body);const{mentions:_old,...rest}=was;const comment={...rest,text:body,editedAt:Date.now(),...mentions.length?{mentions}:{}};const kept=store;const context=contextOf(ctrl);if(kept)kept.update(rowId,comment,context.api,context);else{const byRow=rowsOf(memory,commentScope(ctrl),true);byRow.set(rowId,(byRow.get(rowId)??[]).map(c=>c.id===id?comment:c))}version+=1;announceMentions(ctrl,rowId,comment,mentions.filter(m=>!was.mentions?.includes(m)))}export const commentsTakeVotes=()=>!store||!!store.vote;export function commentVotes(comment){const ids=list=>Array.isArray(list)?[...new Set(list.map(String))]:[];return{up:ids(comment.votes?.up),down:ids(comment.votes?.down)}}export function myCommentVote(comment){const me=getCurrentUser()?.id;if(!me)return null;const v=commentVotes(comment);return v.up.includes(me)?"up":v.down.includes(me)?"down":null}export function mayVoteComment(comment){const me=getCurrentUser()?.id;return!!me&&commentsTakeVotes()&&comment.by!==me}export function voteComment(ctrl,rowId,id,vote){const was=commentsOf(ctrl,rowId).find(c=>c.id===id);const me=getCurrentUser()?.id;if(!was||!me||!mayVoteComment(was))return;const now=myCommentVote(was)===vote?null:vote;const v=commentVotes(was);const up=v.up.filter(x=>x!==me);const down=v.down.filter(x=>x!==me);if(now==="up")up.push(me);if(now==="down")down.push(me);const{votes:_old,...rest}=was;const comment={...rest,...up.length||down.length?{votes:{...up.length?{up}:{},...down.length?{down}:{}}}:{}};const kept=store;const context=contextOf(ctrl);if(kept)kept.vote(rowId,comment,now,context.api,context);else{const byRow=rowsOf(memory,commentScope(ctrl),true);byRow.set(rowId,(byRow.get(rowId)??[]).map(c=>c.id===id?comment:c))}version+=1}export function deleteComment(ctrl,rowId,id){const was=commentsOf(ctrl,rowId).find(c=>c.id===id);if(!was||!ownsComment(was,"remove"))return;const kept=store;const context=contextOf(ctrl);if(kept)kept.remove(rowId,id,context.api,context);else{const byRow=rowsOf(memory,commentScope(ctrl),true);byRow.set(rowId,(byRow.get(rowId)??[]).filter(c=>c.id!==id))}version+=1}export function timeAgo(at,now=Date.now()){const s=Math.max(0,Math.round((now-at)/1e3));if(s<45)return bm("record.justNow");const m=Math.round(s/60);if(m<60)return bmCount("record.minutesAgo",m);const h=Math.round(m/60);if(h<24)return bmCount("record.hoursAgo",h);return new Date(at).toLocaleDateString()}
@@ -265,6 +265,12 @@ export type AutomationRunnerOptions = {
265
265
  /** "Ask AI": a prompt in, the model's answer out. Without it the step fails and says so. */
266
266
  ai?: (prompt: string) => Promise<string>;
267
267
  };
268
+ /**
269
+ * Who pressed a button, for the steps of the automation it starts:
270
+ * `{pressed.name}`, `{pressed.email}`, `{pressed.id}` (Airtable's "User who took
271
+ * action"). In the browser it is the person on the page.
272
+ */
273
+ export declare function pressedValues(): RunValues;
268
274
  /** The most records "Find records" runs its steps for. */
269
275
  export declare const REPEAT_MOST = 1000;
270
276
  /** A record as a script sees it: each field's value and text, by field name. */
@@ -1 +1 @@
1
- import{toast}from"@svgrid/grid";import{createScheduler}from"../scheduling.js";import{colId,primaryOf,rowIdOf,syncAllInverses}from"./base-tables.js";import{compileFieldFilter,describeFieldFilter}from"./filter-model.js";import{fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";import{noteChange}from"./activity.svelte.js";import{getFieldUsers}from"./sources.svelte.js";import{newRecordId}from"./field-ops.js";import{fieldText,fieldValue,linkNames}from"./base-alerts.js";import{callWebhook,sendChat,sendEmailAction,sendTextAction}from"./automation-outbound.js";import{runScript}from"./automation-script.js";import{bm}from"./messages.svelte.js";import{cronWords}from"./cron-words.js";const appActions=new Map;export function registerAutomationAction(id,action){appActions.set(id,action)}export function listAutomationActions(){return[...appActions].map(([id,a])=>({id,label:a.label}))}const readers=new WeakMap;export function tableFields(t){const hit=readers.get(t.columns);if(hit)return hit;const all=t.columns.map(d=>({...d,id:colId(d)}));const map=new Map;for(const d of t.columns){if(d.field==null)continue;const def=fillFieldColumn(d,all);map.set(colId(d),{id:colId(d),field:String(d.field),header:String(d.header??d.field),fieldType:d.fieldType,def,visible:true})}readers.set(t.columns,map);return map}const byName=(t,name)=>{const lower=name.trim().toLowerCase();for(const c of tableFields(t).values()){if(c.header.trim().toLowerCase()===lower||c.field.toLowerCase()===lower||c.id.toLowerCase()===lower)return c}return void 0};export function fillTokens(t,record,template,values){return template.replace(/\{([^{}\n]+)\}/g,(m,name)=>{const given=values?.get(name.trim().toLowerCase());if(given!==void 0)return given;const c=byName(t,name);return!c?m:record?fieldText(c,record):bm("extras.noRecordValue")})}export function matches(t,condition,record){if(!condition)return true;const fields=tableFields(t);const test=compileFieldFilter(condition,(row,id)=>{const c=fields.get(id);return c?fieldValue(c,row):row[id]},linkNames);return test?test(record):true}function stampModifiedTime(t,row,changedIds,at){for(const d of t.columns){if(d.fieldType!=="lastModifiedTime"||d.field==null||changedIds.includes(colId(d)))continue;const p=fieldPropsOf(d);if(p.watch==="specific"&&!changedIds.some(id=>(p.watchFields??[]).includes(id)))continue;row[String(d.field)]=at.toISOString()}}const DAY=864e5;const isoDay=d=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;export function fieldValueFrom(t,def,spec,ctx){const type=def.fieldType;if(typeof spec!=="string")return spec;const raw=spec.includes("{record}")?spec:fillTokens(ctx.from,ctx.record,spec,ctx.values);const text=raw.trim();if(text==="")return type==="checkbox"?false:type==="multiSelect"||type==="link"||type==="attachment"?[]:null;switch(type){case"checkbox":return/^(true|yes|1|checked|on)$/i.test(text);case"number":case"rating":case"duration":case"currency":case"percent":{const n=Number(text.replace(/[^0-9.+-eE]/g,""));return Number.isFinite(n)?text.endsWith("%")?n/100:n:null}case"multiSelect":return text.split(/\s*,\s*/).filter(Boolean);case"user":{const found=getFieldUsers().find(u=>u.id===text||u.name.toLocaleLowerCase()===text.toLocaleLowerCase());return found?found.id:text}case"date":{const m=/^(today|now)\s*(?:([+-])\s*(\d+))?$/i.exec(text);if(!m)return text;const shift=m[2]?(m[2]==="-"?-1:1)*Number(m[3])*DAY:0;const at=new Date(ctx.now.getTime()+shift);return m[1].toLowerCase()==="now"||def.fieldProps?.time?at.toISOString():isoDay(at)}case"link":{const target=ctx.tables.find(x=>x.id===def.fieldProps?.table);const out=[];for(const part of text.split(/\s*,\s*/)){if(part==="{record}"){if(ctx.record&&ctx.from.id===target?.id)out.push(rowIdOf(ctx.from,ctx.record));continue}const name=fillTokens(ctx.from,ctx.record,part,ctx.values).toLocaleLowerCase();const named=ctx.named?.get(name);if(named){out.push(named);continue}const hit=target?.data.find(r=>String(r?.[primaryOf(target)]??"").toLocaleLowerCase()===name);if(hit&&target)out.push(rowIdOf(target,hit))}return def.fieldProps?.multiple===false?out.slice(0,1):out}default:return raw}}export const MAX_DEPTH=4;export const REPEAT_MOST=1e3;const SCRIPT_ROWS=5e3;const READ_AS_TEXT=new Set(["checkbox","number","rating","duration","currency","percent","multiSelect","user","date","link"]);export function scriptRecord(t,r){const values={};const texts={};let name="";for(const c of tableFields(t).values()){let v=r[c.field]??null;try{v=JSON.parse(JSON.stringify(v))}catch{v=null}values[c.header]=v;texts[c.header]=fieldText(c,r);if(c.field===primaryOf(t))name=texts[c.header]}return{id:rowIdOf(t,r),name,values,texts}}export function scriptInput(t,rec,values){const out={};if(rec){out.recordId=rowIdOf(t,rec);for(const c of tableFields(t).values())out[c.header]=fieldText(c,rec)}for(const[k,v]of values)out[k]=v;return out}export function webhookValues(body){const out=new Map;const walk=(v,path,depth)=>{if(out.size>=200)return;if(v!==null&&typeof v==="object"&&depth<5){for(const[k,x]of Object.entries(v).slice(0,100))walk(x,`${path}.${k.toLowerCase()}`,depth+1);if(path!=="webhook")out.set(path,JSON.stringify(v));return}out.set(path,v==null?"":typeof v==="string"?v:JSON.stringify(v))};walk(body,"webhook",0);out.set("webhook",typeof body==="string"?body:JSON.stringify(body??null));return out}export function triggerValues(t,rec,values){const out=new Map(values);if(rec)for(const c of tableFields(t).values())out.set(`trigger.${c.header.trim().toLowerCase()}`,fieldText(c,rec));return out}export function allActions(list){const out=[];for(const x of list){out.push(x);if(x.type==="if")out.push(...allActions(x.then??[]),...allActions(x.else??[]));if(x.type==="repeat")out.push(...allActions(x.actions??[]))}return out}const SHOW_BACKLOG=20;const CARRY_MOST=5e3;const FREE_EVERY=4096;let runSeq=0;export function createAutomationRunner(options){const now=options.now??(()=>new Date);let runs=$state.raw([]);let scheduler=null;let chain=Promise.resolve();let waiting=[];let head=0;let draining=false;let burst={done:0,total:0,at:0,told:0};let backlog=$state.raw(null);let measured=null;const record=run=>runs=[run,...runs].slice(0,100);const automationsOf=t=>(t.automations??[]).filter(a=>a.enabled&&a.runOn!=="server");const tableOf=id=>options.getTables()?.find(t=>t.id===id);const carried=new Map;const carriedFor=new Map;const carry=(key,row)=>{carried.set(key,row);carriedFor.set(key,(carriedFor.get(key)??0)+1)};const letGo=key=>{const left=(carriedFor.get(key)??1)-1;if(left>0)return void carriedFor.set(key,left);carriedFor.delete(key);carried.delete(key)};const recordNow=async(t,id)=>{const own=tableOf(t.id)??t;if(!own.source?.server)return own.data.find(r=>r&&rowIdOf(own,r)===id)??null;return carried.get(`${t.id}:${id}`)??await options.server?.read(t.id,id)??null};async function namesIn(target,values,ctx){const named=new Map;const fields=tableFields(target);for(const[id,spec]of Object.entries(values)){const def=fields.get(id)?.def;if(def?.fieldType!=="link"||typeof spec!=="string")continue;const to=(options.getTables()??[]).find(x=>x.id===def.fieldProps?.table);if(!to?.source?.server)continue;for(const part of spec.split(/\s*,\s*/)){const name=fillTokens(ctx.from,ctx.record,part);const hit=part==="{record}"?null:await options.server?.byName(to.id,name);if(hit)named.set(name.toLocaleLowerCase(),hit)}}return named}const setOff=(t,e)=>automationsFor(t,e,"browser");function handle(e){const t=tableOf(e.table);if(!t)return chain;const list=setOff(t,e);const depth="depth"in e?e.depth??0:0;const recordId=rowIdOf(t,e.record);for(const a of list){if(t.source?.server&&waiting.length-head<CARRY_MOST)carry(`${t.id}:${recordId}`,e.record);if(!draining&&head===waiting.length)burst={done:0,total:0,at:Date.now(),told:0};burst.total+=1;waiting.push({a,tableId:t.id,recordId,depth})}return list.length?drain():chain}function tell(){const clock=Date.now();if(burst.total<SHOW_BACKLOG||clock-burst.told<250)return;burst.told=clock;const seconds=(clock-burst.at)/1e3;if(burst.done>=SHOW_BACKLOG&&seconds>0)measured=burst.done/seconds;backlog={done:burst.done,total:burst.total,perSecond:burst.done>=SHOW_BACKLOG?measured:null}}function endBurst(left){const shown=backlog!=null||burst.total>=SHOW_BACKLOG;backlog=null;if(shown)options.onBurstEnd?.({done:burst.total-left,total:burst.total,left})}function drain(){if(draining)return chain;draining=true;tell();chain=chain.then(async()=>{let breath=Date.now();for(;;){if(head>=waiting.length){if(burst.total<SHOW_BACKLOG)break;await new Promise(r=>setTimeout(r,200));if(head>=waiting.length)break;continue}if(Date.now()-breath>40){await new Promise(r=>setTimeout(r));breath=Date.now();continue}const w=waiting[head];head+=1;if(head>=FREE_EVERY){waiting=waiting.slice(head);head=0}try{await runOne(w.a,w.tableId,w.recordId,w.depth)}catch(e){record({id:++runSeq,automationId:w.a.id,name:w.a.name,table:tableOf(w.tableId)?.name??w.tableId,record:w.recordId,at:now().getTime(),status:"error",steps:[{action:w.a.name,detail:"",error:e instanceof Error?e.message:String(e)}]})}if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`);burst.done+=1;tell()}waiting=[];head=0;draining=false;endBurst(0)});return chain}function stopRuns(){const left=waiting.length-head;if(!left)return 0;for(let i=head;i<waiting.length;i++){const w=waiting[i];if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`)}waiting=[];head=0;endBurst(left);burst={done:0,total:0,at:Date.now(),told:0};return left}async function runOne(a,tableId,recordId,depth){const t=tableOf(tableId);if(!t)return;const rec=recordId==null?null:await recordNow(t,recordId);const run={id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:rec?String(rec[primaryOf(t)]??recordId):null,at:now().getTime(),status:"ok",steps:[]};if(depth>=MAX_DEPTH){run.status="stopped";run.steps.push({action:bm("extras.stepStopped"),detail:bm("extras.stepLoop",{max:MAX_DEPTH})});record(run);return}await runList(a,a.actions,tableId,recordId,depth,run,new Map);record(run)}async function runList(a,list,tableId,recordId,depth,run,values){for(const action of list){try{if(action.type==="if"){const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const yes=!!t&&(rec?matches(t,action.condition,rec):!action.condition?.conditions?.length);run.steps.push({action:bm("extras.stepIf"),detail:bm(yes?"extras.stepIfThen":"extras.stepIfElse")});if(!await runList(a,(yes?action.then:action.else)??[],tableId,recordId,depth,run,values))return false;continue}if(action.type==="repeat"){if(!await runRepeat(a,action,tableId,recordId,depth,run,values))return false;continue}const step=await act(a,action,tableId,recordId,depth,values);if(step)run.steps.push(step)}catch(e){run.status="error";run.steps.push({action:actionLabel(action),detail:"",error:e instanceof Error?e.message:String(e)});return false}}return true}async function runRepeat(a,action,tableId,recordId,depth,run,values){const target=tableOf(action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const most=Math.max(1,Math.min(REPEAT_MOST,action.limit??100));const ids=[];if(target.source?.server){await options.server?.each(target.id,action.condition,async r=>{if(ids.length>=most)return;const id=rowIdOf(target,r);carry(`${target.id}:${id}`,r);ids.push(id)})}else{for(const r of target.data){if(ids.length>=most)break;if(r&&matches(target,action.condition,r))ids.push(rowIdOf(target,r))}}run.steps.push({action:bm("extras.stepFound"),detail:bm("extras.foundIn",{count:ids.length,table:target.name})});const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const inner=t?triggerValues(t,rec,values):new Map(values);inner.set("found",String(ids.length));try{for(const id of ids)if(!await runList(a,action.actions??[],target.id,id,depth,run,inner))return false}finally{if(target.source?.server)for(const id of ids)letGo(`${target.id}:${id}`)}return true}async function writeRecord(a,t,recordId,rec,patch,depth,at){const fields=tableFields(t);const before={...rec};const after={...rec,...patch};const changed=Object.keys(patch).filter(f=>JSON.stringify(before[f]??null)!==JSON.stringify(after[f]??null));if(!changed.length)return{changed,after};const changedIds=changed.map(f=>[...fields.values()].find(c=>c.field===f)?.id??f);stampModifiedTime(t,after,changedIds,at);if(t.source?.server){carried.set(`${t.id}:${recordId}`,after);await options.server?.update(t.id,recordId,Object.fromEntries(Object.keys(after).filter(k=>after[k]!==before[k]).map(k=>[k,after[k]])),before)}else{const tables=options.getTables()??[];let next=tables.map(x=>x.id===t.id?{...x,data:x.data.map(r=>r&&rowIdOf(t,r)===recordId?after:r)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}changed.forEach((f,i)=>noteChange({base:options.scope,tableId:t.id},recordId,changedIds[i],after[f],a.name));void handle({type:"updated",table:t.id,record:after,before,fields:changedIds,depth:depth+1});return{changed,after}}function addRecord(target,row,depth){const tables=options.getTables()??[];let next=tables.map(x=>x.id===target.id?{...x,data:[...x.data,row]}:x);next=syncAllInverses(next,target.id);options.apply(next,depth+1,target.id);void handle({type:"created",table:target.id,record:row,depth:depth+1})}function pageBridge(a,depth){const named=name=>{const t=(options.getTables()??[]).find(x=>x.name.trim().toLowerCase()===name.trim().toLowerCase());if(!t)throw new Error(bm("extras.noTable",{table:name}));return t};const rowsOf=async t=>{if(!t.source?.server)return t.data.filter(Boolean);const out=[];await options.server?.each(t.id,void 0,async r=>{if(out.length<SCRIPT_ROWS)out.push(r)});return out};const patchOf=(t,given)=>{const patch={};for(const[name,v]of Object.entries(given??{})){const c=byName(t,name);if(!c)throw new Error(bm("extras.noField",{field:name}));const type=String(c.fieldType??"");const text=typeof v==="string"?v:v&&typeof v==="object"&&!Array.isArray(v)&&"name"in v?String(v.name):null;patch[c.field]=text!==null&&READ_AS_TEXT.has(type)?fieldValueFrom(t,c.def,text.replace(/[{}]/g,""),{tables:options.getTables()??[],from:t,record:null,now:now()}):v}return patch};return{tables:()=>(options.getTables()??[]).map(t=>t.name),select:async name=>{const t=named(name);return(await rowsOf(t)).map(r=>scriptRecord(t,r))},update:async(name,id,given)=>{const t=named(name);const rec=await recordNow(t,id);if(!rec)throw new Error(bm("extras.noRecordId",{id}));await writeRecord(a,t,id,rec,patchOf(t,given),depth,now())},create:async(name,given)=>{const t=named(name);const row={id:newRecordId(),...patchOf(t,given)};addRecord(t,row,depth);return String(row.id)},remove:async(name,id)=>{const t=named(name);const tables=options.getTables()??[];options.apply(tables.map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==id)}:x),depth+1,t.id)}}}async function act(a,action,tableId,recordId,depth,values){const tables=options.getTables()??[];const t=tables.find(x=>x.id===tableId);const rec=recordId==null?null:await recordNow(t,recordId);const ctx={tables,from:t,record:rec,now:now(),values};switch(action.type){case"notify":{const message=fillTokens(t,rec,action.message,values);const sev=action.severity??"info";toast[sev](message);return{action:bm("extras.stepNotice"),detail:message}}case"highlight":return null;case"updateRecord":{if(!rec||recordId==null)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.noRecordToUpdate")};const fields=tableFields(t);const patch={};ctx.named=await namesIn(t,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)patch[c.field]=fieldValueFrom(t,c.def,spec,ctx)}const{changed,after}=await writeRecord(a,t,recordId,rec,patch,depth,ctx.now);if(!changed.length)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.alreadySet")};return{action:bm("extras.actionUpdateRecord"),detail:changed.map(f=>said([...fields.values()].find(c=>c.field===f),f,after)).join(", ")}}case"createRecord":{const target=tables.find(x=>x.id===action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const fields=tableFields(target);const row={id:newRecordId()};ctx.named=await namesIn(target,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)row[c.field]=fieldValueFrom(target,c.def,spec,ctx)}if(action.linkField&&rec){const c=fields.get(action.linkField);if(c)row[c.field]=[rowIdOf(t,rec)]}addRecord(target,row,depth);const name=String(row[primaryOf(target)]??"")||bm("extras.aRecord");return{action:bm("extras.actionCreateRecord"),detail:bm("extras.createdIn",{name,table:target.name})}}case"run":return runAppAction(a,action,t,rec);case"webhook":return{action:bm("extras.stepWebhook"),detail:await callWebhook(action,outbound(a,t,rec,{},values))};case"email":return{action:bm("extras.stepEmail"),detail:await sendEmailAction(action,outbound(a,t,rec,{},values),void 0)};case"chat":return{action:bm("extras.stepChat"),detail:await sendChat(action,outbound(a,t,rec,{},values))};case"textMessage":return{action:bm("extras.stepText"),detail:await sendTextAction(action,outbound(a,t,rec,{},values),void 0)};case"ai":{if(!options.ai)throw new Error(bm("extras.noAi"));const prompt=fillTokens(t,rec,action.prompt,values).trim();if(!prompt)throw new Error(bm("extras.aiNoPrompt"));const answer=String(await options.ai(prompt)).trim();values.set("ai",answer);const c=action.field?tableFields(t).get(action.field):void 0;if(c&&rec&&recordId!=null)await writeRecord(a,t,recordId,rec,{[c.field]:answer},depth,ctx.now);return{action:bm("extras.stepAi"),detail:answer.length>160?answer.slice(0,157)+"...":answer}}case"script":{const result=await runScript(action.code,{input:scriptInput(t,rec,values),bridge:pageBridge(a,depth)});for(const[k,v]of Object.entries(result.output))values.set(`script.${k.toLowerCase()}`,typeof v==="string"?v:JSON.stringify(v));if(!result.ok)throw new Error(result.error??bm("extras.scriptFailed"));return{action:bm("extras.stepScript"),detail:result.logs.slice(-3).join(" | ")||bm("extras.stepDone")}}default:return null}}function schedule(){scheduler?.stop();scheduler=null;const list=options.getTables()??[];const due=[];for(const t of list)for(const a of automationsOf(t))if(a.trigger.type==="scheduled")due.push({id:`${t.id}:${a.id}`,cron:a.trigger.cron,table:t.id,automation:a});if(!due.length)return;scheduler=createScheduler({schedules:due,now,onFire:s=>void runScheduled(s.id)});scheduler.start()}function runScheduled(key){const[tableId,automationId]=key.split(":");const t=tableOf(tableId);const a=t?.automations?.find(x=>x.id===automationId);if(!t||!a)return chain;if(!a.condition)chain=chain.then(()=>runOne(a,t.id,null,0));else if(t.source?.server){chain=chain.then(()=>options.server?.each(t.id,a.condition,async r=>{const key2=`${t.id}:${rowIdOf(t,r)}`;carry(key2,r);await runOne(a,t.id,rowIdOf(t,r),0);letGo(key2)}))}else for(const r of t.data)if(r&&matches(t,a.condition,r))chain=chain.then(()=>runOne(a,t.id,rowIdOf(t,r),0));return chain}return{handle,stopRuns,get backlog(){return backlog},get waiting(){return waiting.length-head},get perSecond(){return measured},schedule,runScheduled,firstRecords:async(tableId,count)=>await options.server?.first(tableId,count)??[],runNow:(a,tableId,recordId)=>chain=chain.then(async()=>{const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;if(t&&rec&&a.condition&&!matches(t,a.condition,rec)){record({id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:String(rec[primaryOf(t)]??recordId),at:now().getTime(),status:"stopped",steps:[{action:bm("extras.stepNotRun"),detail:bm("extras.stepNoMatch")}]});return}return runOne(a,tableId,recordId,0)}),get runs(){return runs},clearRuns:()=>runs=[],settled:()=>chain,stop:()=>scheduler?.stop()}}function said(c,field,record){if(!c)return bm("extras.saidValue",{field,value:String(record[field]??"")});if(c.fieldType==="checkbox")return bm(record[c.field]?"extras.saidChecked":"extras.saidUnchecked",{field:c.header});return bm("extras.saidValue",{field:c.header,value:fieldText(c,record)||bm("extras.saidEmpty")})}export function automationsFor(t,e,side){return(t.automations??[]).filter(a=>{if(!a.enabled||a.runOn==="server"!==(side==="server"))return false;const tr=a.trigger;switch(tr.type){case"recordCreated":return e.type==="created"&&matches(t,a.condition,e.record);case"recordUpdated":return e.type==="updated"&&(!tr.fields?.length||tr.fields.some(f=>e.fields.includes(f)))&&matches(t,a.condition,e.record);case"recordMatches":if(!a.condition)return false;if(e.type==="created")return matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,a.condition,e.record)&&!matches(t,a.condition,e.before);return false;case"formSubmitted":return e.type==="form"&&(!tr.view||tr.view===e.view)&&matches(t,a.condition,e.record);case"button":return e.type==="button"&&e.field===tr.field&&matches(t,a.condition,e.record);default:return false}})}export function outbound(a,t,rec,extra={},values){return{automation:a.name,table:t.name,record:rec,fill:template=>fillTokens(t,rec,template,values),fields:()=>{const out={};if(rec)for(const c of tableFields(t).values())out[c.header]=c.fieldType==="checkbox"?String(!!rec[c.field]):fieldText(c,rec);return out},...extra}}export async function runAppAction(a,action,t,rec){const app=appActions.get(action.action);if(!app)throw new Error(bm("extras.noAction",{action:action.action}));const out=await app.run({automation:a,table:t,record:rec,text:name=>fillTokens(t,rec,`{${name}}`),options:action.options??{}});return{action:app.label,detail:typeof out==="string"?out:bm("extras.stepDone")}}export function actionLabel(a){switch(a.type){case"updateRecord":return bm("extras.actionUpdateRecord");case"createRecord":return bm("extras.actionCreateRecord");case"notify":return bm("extras.actionNotify");case"highlight":return bm("extras.actionHighlight");case"run":return appActions.get(a.action)?.label??a.action;case"webhook":return bm("extras.actionWebhook");case"email":return bm("extras.actionEmail");case"chat":return bm("extras.actionChat");case"textMessage":return bm("extras.actionText");case"repeat":return bm("extras.actionRepeat");case"if":return bm("extras.actionIf");case"ai":return bm("extras.actionAi");case"script":return bm("extras.actionScript")}}export function triggerText(t,a){const name=id=>t?tableFields(t).get(id)?.header??id:id;const cond=a.condition?describeFieldFilter(a.condition,name):"";const where=cond&&cond!=="every record";const tr=a.trigger;switch(tr.type){case"recordCreated":return where?bm("extras.whenCreatedWhere",{condition:cond}):bm("extras.whenCreated");case"recordUpdated":{if(!tr.fields?.length)return where?bm("extras.whenRecordChangesWhere",{condition:cond}):bm("extras.whenRecordChanges");const fields=tr.fields.map(name).join(bm("extras.fieldsOr"));return where?bm("extras.whenFieldsChangeWhere",{fields,condition:cond}):bm("extras.whenFieldsChange",{fields})}case"recordMatches":return bm("extras.whenMatches",{condition:cond||bm("extras.noConditionYet")});case"formSubmitted":return where?bm("extras.whenFormWhere",{condition:cond}):bm("extras.whenForm");case"button":return bm("extras.whenPressed",{field:name(tr.field)});case"scheduled":return where?bm("extras.onScheduleWhere",{cron:cronWords(tr.cron),condition:cond}):bm("extras.onSchedule",{cron:cronWords(tr.cron)});case"webhookReceived":return bm("extras.whenWebhook")}}
1
+ import{toast}from"@svgrid/grid";import{createScheduler}from"../scheduling.js";import{colId,primaryOf,rowIdOf,syncAllInverses}from"./base-tables.js";import{compileFieldFilter,describeFieldFilter}from"./filter-model.js";import{fieldPropsOf,fillFieldColumn}from"./registry.svelte.js";import{noteChange}from"./activity.svelte.js";import{getCurrentUser,getFieldUsers}from"./sources.svelte.js";import{newRecordId}from"./field-ops.js";import{fieldText,fieldValue,linkNames}from"./base-alerts.js";import{callWebhook,sendChat,sendEmailAction,sendTextAction}from"./automation-outbound.js";import{runScript}from"./automation-script.js";import{bm}from"./messages.svelte.js";import{cronWords}from"./cron-words.js";const appActions=new Map;export function registerAutomationAction(id,action){appActions.set(id,action)}export function listAutomationActions(){return[...appActions].map(([id,a])=>({id,label:a.label}))}const readers=new WeakMap;export function tableFields(t){const hit=readers.get(t.columns);if(hit)return hit;const all=t.columns.map(d=>({...d,id:colId(d)}));const map=new Map;for(const d of t.columns){if(d.field==null)continue;const def=fillFieldColumn(d,all);map.set(colId(d),{id:colId(d),field:String(d.field),header:String(d.header??d.field),fieldType:d.fieldType,def,visible:true})}readers.set(t.columns,map);return map}const byName=(t,name)=>{const lower=name.trim().toLowerCase();for(const c of tableFields(t).values()){if(c.header.trim().toLowerCase()===lower||c.field.toLowerCase()===lower||c.id.toLowerCase()===lower)return c}return void 0};export function fillTokens(t,record,template,values){return template.replace(/\{([^{}\n]+)\}/g,(m,name)=>{const given=values?.get(name.trim().toLowerCase());if(given!==void 0)return given;const c=byName(t,name);return!c?m:record?fieldText(c,record):bm("extras.noRecordValue")})}export function matches(t,condition,record){if(!condition)return true;const fields=tableFields(t);const test=compileFieldFilter(condition,(row,id)=>{const c=fields.get(id);return c?fieldValue(c,row):row[id]},linkNames);return test?test(record):true}function stampModifiedTime(t,row,changedIds,at){for(const d of t.columns){if(d.fieldType!=="lastModifiedTime"||d.field==null||changedIds.includes(colId(d)))continue;const p=fieldPropsOf(d);if(p.watch==="specific"&&!changedIds.some(id=>(p.watchFields??[]).includes(id)))continue;row[String(d.field)]=at.toISOString()}}const DAY=864e5;const isoDay=d=>`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;export function fieldValueFrom(t,def,spec,ctx){const type=def.fieldType;if(typeof spec!=="string")return spec;const raw=spec.includes("{record}")?spec:fillTokens(ctx.from,ctx.record,spec,ctx.values);const text=raw.trim();if(text==="")return type==="checkbox"?false:type==="multiSelect"||type==="link"||type==="attachment"?[]:null;switch(type){case"checkbox":return/^(true|yes|1|checked|on)$/i.test(text);case"number":case"rating":case"duration":case"currency":case"percent":{const n=Number(text.replace(/[^0-9.+-eE]/g,""));return Number.isFinite(n)?text.endsWith("%")?n/100:n:null}case"multiSelect":return text.split(/\s*,\s*/).filter(Boolean);case"user":{const found=getFieldUsers().find(u=>u.id===text||u.name.toLocaleLowerCase()===text.toLocaleLowerCase());return found?found.id:text}case"date":{const m=/^(today|now)\s*(?:([+-])\s*(\d+))?$/i.exec(text);if(!m)return text;const shift=m[2]?(m[2]==="-"?-1:1)*Number(m[3])*DAY:0;const at=new Date(ctx.now.getTime()+shift);return m[1].toLowerCase()==="now"||def.fieldProps?.time?at.toISOString():isoDay(at)}case"link":{const target=ctx.tables.find(x=>x.id===def.fieldProps?.table);const out=[];for(const part of text.split(/\s*,\s*/)){if(part==="{record}"){if(ctx.record&&ctx.from.id===target?.id)out.push(rowIdOf(ctx.from,ctx.record));continue}const name=fillTokens(ctx.from,ctx.record,part,ctx.values).toLocaleLowerCase();const named=ctx.named?.get(name);if(named){out.push(named);continue}const hit=target?.data.find(r=>String(r?.[primaryOf(target)]??"").toLocaleLowerCase()===name);if(hit&&target)out.push(rowIdOf(target,hit))}return def.fieldProps?.multiple===false?out.slice(0,1):out}default:return raw}}export const MAX_DEPTH=4;export function pressedValues(){const me=getCurrentUser();const out=new Map;out.set("pressed.name",me?.name??"");out.set("pressed.email",me?.email??"");out.set("pressed.id",me?.id??"");return out}export const REPEAT_MOST=1e3;const SCRIPT_ROWS=5e3;const READ_AS_TEXT=new Set(["checkbox","number","rating","duration","currency","percent","multiSelect","user","date","link"]);export function scriptRecord(t,r){const values={};const texts={};let name="";for(const c of tableFields(t).values()){let v=r[c.field]??null;try{v=JSON.parse(JSON.stringify(v))}catch{v=null}values[c.header]=v;texts[c.header]=fieldText(c,r);if(c.field===primaryOf(t))name=texts[c.header]}return{id:rowIdOf(t,r),name,values,texts}}export function scriptInput(t,rec,values){const out={};if(rec){out.recordId=rowIdOf(t,rec);for(const c of tableFields(t).values())out[c.header]=fieldText(c,rec)}for(const[k,v]of values)out[k]=v;return out}export function webhookValues(body){const out=new Map;const walk=(v,path,depth)=>{if(out.size>=200)return;if(v!==null&&typeof v==="object"&&depth<5){for(const[k,x]of Object.entries(v).slice(0,100))walk(x,`${path}.${k.toLowerCase()}`,depth+1);if(path!=="webhook")out.set(path,JSON.stringify(v));return}out.set(path,v==null?"":typeof v==="string"?v:JSON.stringify(v))};walk(body,"webhook",0);out.set("webhook",typeof body==="string"?body:JSON.stringify(body??null));return out}export function triggerValues(t,rec,values){const out=new Map(values);if(rec)for(const c of tableFields(t).values())out.set(`trigger.${c.header.trim().toLowerCase()}`,fieldText(c,rec));return out}export function allActions(list){const out=[];for(const x of list){out.push(x);if(x.type==="if")out.push(...allActions(x.then??[]),...allActions(x.else??[]));if(x.type==="repeat")out.push(...allActions(x.actions??[]))}return out}const SHOW_BACKLOG=20;const CARRY_MOST=5e3;const FREE_EVERY=4096;let runSeq=0;export function createAutomationRunner(options){const now=options.now??(()=>new Date);let runs=$state.raw([]);let scheduler=null;let chain=Promise.resolve();let waiting=[];let head=0;let draining=false;let burst={done:0,total:0,at:0,told:0};let backlog=$state.raw(null);let measured=null;const record=run=>runs=[run,...runs].slice(0,100);const automationsOf=t=>(t.automations??[]).filter(a=>a.enabled&&a.runOn!=="server");const tableOf=id=>options.getTables()?.find(t=>t.id===id);const carried=new Map;const carriedFor=new Map;const carry=(key,row)=>{carried.set(key,row);carriedFor.set(key,(carriedFor.get(key)??0)+1)};const letGo=key=>{const left=(carriedFor.get(key)??1)-1;if(left>0)return void carriedFor.set(key,left);carriedFor.delete(key);carried.delete(key)};const recordNow=async(t,id)=>{const own=tableOf(t.id)??t;if(!own.source?.server)return own.data.find(r=>r&&rowIdOf(own,r)===id)??null;return carried.get(`${t.id}:${id}`)??await options.server?.read(t.id,id)??null};async function namesIn(target,values,ctx){const named=new Map;const fields=tableFields(target);for(const[id,spec]of Object.entries(values)){const def=fields.get(id)?.def;if(def?.fieldType!=="link"||typeof spec!=="string")continue;const to=(options.getTables()??[]).find(x=>x.id===def.fieldProps?.table);if(!to?.source?.server)continue;for(const part of spec.split(/\s*,\s*/)){const name=fillTokens(ctx.from,ctx.record,part);const hit=part==="{record}"?null:await options.server?.byName(to.id,name);if(hit)named.set(name.toLocaleLowerCase(),hit)}}return named}const setOff=(t,e)=>automationsFor(t,e,"browser");function handle(e){const t=tableOf(e.table);if(!t)return chain;const list=setOff(t,e);const depth="depth"in e?e.depth??0:0;const recordId=rowIdOf(t,e.record);for(const a of list){if(t.source?.server&&waiting.length-head<CARRY_MOST)carry(`${t.id}:${recordId}`,e.record);if(!draining&&head===waiting.length)burst={done:0,total:0,at:Date.now(),told:0};burst.total+=1;waiting.push({a,tableId:t.id,recordId,depth})}return list.length?drain():chain}function tell(){const clock=Date.now();if(burst.total<SHOW_BACKLOG||clock-burst.told<250)return;burst.told=clock;const seconds=(clock-burst.at)/1e3;if(burst.done>=SHOW_BACKLOG&&seconds>0)measured=burst.done/seconds;backlog={done:burst.done,total:burst.total,perSecond:burst.done>=SHOW_BACKLOG?measured:null}}function endBurst(left){const shown=backlog!=null||burst.total>=SHOW_BACKLOG;backlog=null;if(shown)options.onBurstEnd?.({done:burst.total-left,total:burst.total,left})}function drain(){if(draining)return chain;draining=true;tell();chain=chain.then(async()=>{let breath=Date.now();for(;;){if(head>=waiting.length){if(burst.total<SHOW_BACKLOG)break;await new Promise(r=>setTimeout(r,200));if(head>=waiting.length)break;continue}if(Date.now()-breath>40){await new Promise(r=>setTimeout(r));breath=Date.now();continue}const w=waiting[head];head+=1;if(head>=FREE_EVERY){waiting=waiting.slice(head);head=0}try{await runOne(w.a,w.tableId,w.recordId,w.depth)}catch(e){record({id:++runSeq,automationId:w.a.id,name:w.a.name,table:tableOf(w.tableId)?.name??w.tableId,record:w.recordId,at:now().getTime(),status:"error",steps:[{action:w.a.name,detail:"",error:e instanceof Error?e.message:String(e)}]})}if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`);burst.done+=1;tell()}waiting=[];head=0;draining=false;endBurst(0)});return chain}function stopRuns(){const left=waiting.length-head;if(!left)return 0;for(let i=head;i<waiting.length;i++){const w=waiting[i];if(w.recordId!=null)letGo(`${w.tableId}:${w.recordId}`)}waiting=[];head=0;endBurst(left);burst={done:0,total:0,at:Date.now(),told:0};return left}async function runOne(a,tableId,recordId,depth){const t=tableOf(tableId);if(!t)return;const rec=recordId==null?null:await recordNow(t,recordId);const run={id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:rec?String(rec[primaryOf(t)]??recordId):null,at:now().getTime(),status:"ok",steps:[]};if(depth>=MAX_DEPTH){run.status="stopped";run.steps.push({action:bm("extras.stepStopped"),detail:bm("extras.stepLoop",{max:MAX_DEPTH})});record(run);return}await runList(a,a.actions,tableId,recordId,depth,run,a.trigger.type==="button"?pressedValues():new Map);record(run)}async function runList(a,list,tableId,recordId,depth,run,values){for(const action of list){try{if(action.type==="if"){const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const yes=!!t&&(rec?matches(t,action.condition,rec):!action.condition?.conditions?.length);run.steps.push({action:bm("extras.stepIf"),detail:bm(yes?"extras.stepIfThen":"extras.stepIfElse")});if(!await runList(a,(yes?action.then:action.else)??[],tableId,recordId,depth,run,values))return false;continue}if(action.type==="repeat"){if(!await runRepeat(a,action,tableId,recordId,depth,run,values))return false;continue}const step=await act(a,action,tableId,recordId,depth,values);if(step)run.steps.push(step)}catch(e){run.status="error";run.steps.push({action:actionLabel(action),detail:"",error:e instanceof Error?e.message:String(e)});return false}}return true}async function runRepeat(a,action,tableId,recordId,depth,run,values){const target=tableOf(action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const most=Math.max(1,Math.min(REPEAT_MOST,action.limit??100));const ids=[];if(target.source?.server){await options.server?.each(target.id,action.condition,async r=>{if(ids.length>=most)return;const id=rowIdOf(target,r);carry(`${target.id}:${id}`,r);ids.push(id)})}else{for(const r of target.data){if(ids.length>=most)break;if(r&&matches(target,action.condition,r))ids.push(rowIdOf(target,r))}}run.steps.push({action:bm("extras.stepFound"),detail:bm("extras.foundIn",{count:ids.length,table:target.name})});const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;const inner=t?triggerValues(t,rec,values):new Map(values);inner.set("found",String(ids.length));try{for(const id of ids)if(!await runList(a,action.actions??[],target.id,id,depth,run,inner))return false}finally{if(target.source?.server)for(const id of ids)letGo(`${target.id}:${id}`)}return true}async function writeRecord(a,t,recordId,rec,patch,depth,at){const fields=tableFields(t);const before={...rec};const after={...rec,...patch};const changed=Object.keys(patch).filter(f=>JSON.stringify(before[f]??null)!==JSON.stringify(after[f]??null));if(!changed.length)return{changed,after};const changedIds=changed.map(f=>[...fields.values()].find(c=>c.field===f)?.id??f);stampModifiedTime(t,after,changedIds,at);if(t.source?.server){carried.set(`${t.id}:${recordId}`,after);await options.server?.update(t.id,recordId,Object.fromEntries(Object.keys(after).filter(k=>after[k]!==before[k]).map(k=>[k,after[k]])),before)}else{const tables=options.getTables()??[];let next=tables.map(x=>x.id===t.id?{...x,data:x.data.map(r=>r&&rowIdOf(t,r)===recordId?after:r)}:x);next=syncAllInverses(next,t.id);options.apply(next,depth+1,t.id)}changed.forEach((f,i)=>noteChange({base:options.scope,tableId:t.id},recordId,changedIds[i],after[f],a.name));void handle({type:"updated",table:t.id,record:after,before,fields:changedIds,depth:depth+1});return{changed,after}}function addRecord(target,row,depth){const tables=options.getTables()??[];let next=tables.map(x=>x.id===target.id?{...x,data:[...x.data,row]}:x);next=syncAllInverses(next,target.id);options.apply(next,depth+1,target.id);void handle({type:"created",table:target.id,record:row,depth:depth+1})}function pageBridge(a,depth){const named=name=>{const t=(options.getTables()??[]).find(x=>x.name.trim().toLowerCase()===name.trim().toLowerCase());if(!t)throw new Error(bm("extras.noTable",{table:name}));return t};const rowsOf=async t=>{if(!t.source?.server)return t.data.filter(Boolean);const out=[];await options.server?.each(t.id,void 0,async r=>{if(out.length<SCRIPT_ROWS)out.push(r)});return out};const patchOf=(t,given)=>{const patch={};for(const[name,v]of Object.entries(given??{})){const c=byName(t,name);if(!c)throw new Error(bm("extras.noField",{field:name}));const type=String(c.fieldType??"");const text=typeof v==="string"?v:v&&typeof v==="object"&&!Array.isArray(v)&&"name"in v?String(v.name):null;patch[c.field]=text!==null&&READ_AS_TEXT.has(type)?fieldValueFrom(t,c.def,text.replace(/[{}]/g,""),{tables:options.getTables()??[],from:t,record:null,now:now()}):v}return patch};return{tables:()=>(options.getTables()??[]).map(t=>t.name),select:async name=>{const t=named(name);return(await rowsOf(t)).map(r=>scriptRecord(t,r))},update:async(name,id,given)=>{const t=named(name);const rec=await recordNow(t,id);if(!rec)throw new Error(bm("extras.noRecordId",{id}));await writeRecord(a,t,id,rec,patchOf(t,given),depth,now())},create:async(name,given)=>{const t=named(name);const row={id:newRecordId(),...patchOf(t,given)};addRecord(t,row,depth);return String(row.id)},remove:async(name,id)=>{const t=named(name);const tables=options.getTables()??[];options.apply(tables.map(x=>x.id===t.id?{...x,data:x.data.filter(r=>!r||rowIdOf(t,r)!==id)}:x),depth+1,t.id)}}}async function act(a,action,tableId,recordId,depth,values){const tables=options.getTables()??[];const t=tables.find(x=>x.id===tableId);const rec=recordId==null?null:await recordNow(t,recordId);const ctx={tables,from:t,record:rec,now:now(),values};switch(action.type){case"notify":{const message=fillTokens(t,rec,action.message,values);const sev=action.severity??"info";toast[sev](message);return{action:bm("extras.stepNotice"),detail:message}}case"highlight":return null;case"updateRecord":{if(!rec||recordId==null)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.noRecordToUpdate")};const fields=tableFields(t);const patch={};ctx.named=await namesIn(t,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)patch[c.field]=fieldValueFrom(t,c.def,spec,ctx)}const{changed,after}=await writeRecord(a,t,recordId,rec,patch,depth,ctx.now);if(!changed.length)return{action:bm("extras.actionUpdateRecord"),detail:bm("extras.alreadySet")};return{action:bm("extras.actionUpdateRecord"),detail:changed.map(f=>said([...fields.values()].find(c=>c.field===f),f,after)).join(", ")}}case"createRecord":{const target=tables.find(x=>x.id===action.table);if(!target)throw new Error(bm("extras.noTable",{table:action.table}));const fields=tableFields(target);const row={id:newRecordId()};ctx.named=await namesIn(target,action.values,ctx);for(const[id,spec]of Object.entries(action.values)){const c=fields.get(id);if(c)row[c.field]=fieldValueFrom(target,c.def,spec,ctx)}if(action.linkField&&rec){const c=fields.get(action.linkField);if(c)row[c.field]=[rowIdOf(t,rec)]}addRecord(target,row,depth);const name=String(row[primaryOf(target)]??"")||bm("extras.aRecord");return{action:bm("extras.actionCreateRecord"),detail:bm("extras.createdIn",{name,table:target.name})}}case"run":return runAppAction(a,action,t,rec);case"webhook":return{action:bm("extras.stepWebhook"),detail:await callWebhook(action,outbound(a,t,rec,{},values))};case"email":return{action:bm("extras.stepEmail"),detail:await sendEmailAction(action,outbound(a,t,rec,{},values),void 0)};case"chat":return{action:bm("extras.stepChat"),detail:await sendChat(action,outbound(a,t,rec,{},values))};case"textMessage":return{action:bm("extras.stepText"),detail:await sendTextAction(action,outbound(a,t,rec,{},values),void 0)};case"ai":{if(!options.ai)throw new Error(bm("extras.noAi"));const prompt=fillTokens(t,rec,action.prompt,values).trim();if(!prompt)throw new Error(bm("extras.aiNoPrompt"));const answer=String(await options.ai(prompt)).trim();values.set("ai",answer);const c=action.field?tableFields(t).get(action.field):void 0;if(c&&rec&&recordId!=null)await writeRecord(a,t,recordId,rec,{[c.field]:answer},depth,ctx.now);return{action:bm("extras.stepAi"),detail:answer.length>160?answer.slice(0,157)+"...":answer}}case"script":{const result=await runScript(action.code,{input:scriptInput(t,rec,values),bridge:pageBridge(a,depth)});for(const[k,v]of Object.entries(result.output))values.set(`script.${k.toLowerCase()}`,typeof v==="string"?v:JSON.stringify(v));if(!result.ok)throw new Error(result.error??bm("extras.scriptFailed"));return{action:bm("extras.stepScript"),detail:result.logs.slice(-3).join(" | ")||bm("extras.stepDone")}}default:return null}}function schedule(){scheduler?.stop();scheduler=null;const list=options.getTables()??[];const due=[];for(const t of list)for(const a of automationsOf(t))if(a.trigger.type==="scheduled")due.push({id:`${t.id}:${a.id}`,cron:a.trigger.cron,table:t.id,automation:a});if(!due.length)return;scheduler=createScheduler({schedules:due,now,onFire:s=>void runScheduled(s.id)});scheduler.start()}function runScheduled(key){const[tableId,automationId]=key.split(":");const t=tableOf(tableId);const a=t?.automations?.find(x=>x.id===automationId);if(!t||!a)return chain;if(!a.condition)chain=chain.then(()=>runOne(a,t.id,null,0));else if(t.source?.server){chain=chain.then(()=>options.server?.each(t.id,a.condition,async r=>{const key2=`${t.id}:${rowIdOf(t,r)}`;carry(key2,r);await runOne(a,t.id,rowIdOf(t,r),0);letGo(key2)}))}else for(const r of t.data)if(r&&matches(t,a.condition,r))chain=chain.then(()=>runOne(a,t.id,rowIdOf(t,r),0));return chain}return{handle,stopRuns,get backlog(){return backlog},get waiting(){return waiting.length-head},get perSecond(){return measured},schedule,runScheduled,firstRecords:async(tableId,count)=>await options.server?.first(tableId,count)??[],runNow:(a,tableId,recordId)=>chain=chain.then(async()=>{const t=tableOf(tableId);const rec=t&&recordId!=null?await recordNow(t,recordId):null;if(t&&rec&&a.condition&&!matches(t,a.condition,rec)){record({id:++runSeq,automationId:a.id,name:a.name,table:t.name,record:String(rec[primaryOf(t)]??recordId),at:now().getTime(),status:"stopped",steps:[{action:bm("extras.stepNotRun"),detail:bm("extras.stepNoMatch")}]});return}return runOne(a,tableId,recordId,0)}),get runs(){return runs},clearRuns:()=>runs=[],settled:()=>chain,stop:()=>scheduler?.stop()}}function said(c,field,record){if(!c)return bm("extras.saidValue",{field,value:String(record[field]??"")});if(c.fieldType==="checkbox")return bm(record[c.field]?"extras.saidChecked":"extras.saidUnchecked",{field:c.header});return bm("extras.saidValue",{field:c.header,value:fieldText(c,record)||bm("extras.saidEmpty")})}export function automationsFor(t,e,side){return(t.automations??[]).filter(a=>{if(!a.enabled||a.runOn==="server"!==(side==="server"))return false;const tr=a.trigger;switch(tr.type){case"recordCreated":return e.type==="created"&&matches(t,a.condition,e.record);case"recordUpdated":return e.type==="updated"&&(!tr.fields?.length||tr.fields.some(f=>e.fields.includes(f)))&&matches(t,a.condition,e.record);case"recordMatches":if(!a.condition)return false;if(e.type==="created")return matches(t,a.condition,e.record);if(e.type==="updated")return matches(t,a.condition,e.record)&&!matches(t,a.condition,e.before);return false;case"formSubmitted":return e.type==="form"&&(!tr.view||tr.view===e.view)&&matches(t,a.condition,e.record);case"button":return e.type==="button"&&e.field===tr.field&&matches(t,a.condition,e.record);default:return false}})}export function outbound(a,t,rec,extra={},values){return{automation:a.name,table:t.name,record:rec,fill:template=>fillTokens(t,rec,template,values),fields:()=>{const out={};if(rec)for(const c of tableFields(t).values())out[c.header]=c.fieldType==="checkbox"?String(!!rec[c.field]):fieldText(c,rec);return out},...extra}}export async function runAppAction(a,action,t,rec){const app=appActions.get(action.action);if(!app)throw new Error(bm("extras.noAction",{action:action.action}));const out=await app.run({automation:a,table:t,record:rec,text:name=>fillTokens(t,rec,`{${name}}`),options:action.options??{}});return{action:app.label,detail:typeof out==="string"?out:bm("extras.stepDone")}}export function actionLabel(a){switch(a.type){case"updateRecord":return bm("extras.actionUpdateRecord");case"createRecord":return bm("extras.actionCreateRecord");case"notify":return bm("extras.actionNotify");case"highlight":return bm("extras.actionHighlight");case"run":return appActions.get(a.action)?.label??a.action;case"webhook":return bm("extras.actionWebhook");case"email":return bm("extras.actionEmail");case"chat":return bm("extras.actionChat");case"textMessage":return bm("extras.actionText");case"repeat":return bm("extras.actionRepeat");case"if":return bm("extras.actionIf");case"ai":return bm("extras.actionAi");case"script":return bm("extras.actionScript")}}export function triggerText(t,a){const name=id=>t?tableFields(t).get(id)?.header??id:id;const cond=a.condition?describeFieldFilter(a.condition,name):"";const where=cond&&cond!=="every record";const tr=a.trigger;switch(tr.type){case"recordCreated":return where?bm("extras.whenCreatedWhere",{condition:cond}):bm("extras.whenCreated");case"recordUpdated":{if(!tr.fields?.length)return where?bm("extras.whenRecordChangesWhere",{condition:cond}):bm("extras.whenRecordChanges");const fields=tr.fields.map(name).join(bm("extras.fieldsOr"));return where?bm("extras.whenFieldsChangeWhere",{fields,condition:cond}):bm("extras.whenFieldsChange",{fields})}case"recordMatches":return bm("extras.whenMatches",{condition:cond||bm("extras.noConditionYet")});case"formSubmitted":return where?bm("extras.whenFormWhere",{condition:cond}):bm("extras.whenForm");case"button":return bm("extras.whenPressed",{field:name(tr.field)});case"scheduled":return where?bm("extras.onScheduleWhere",{cron:cronWords(tr.cron),condition:cond}):bm("extras.onSchedule",{cron:cronWords(tr.cron)});case"webhookReceived":return bm("extras.whenWebhook")}}
@@ -34,6 +34,12 @@ export type BasePermissions = {
34
34
  canEditViews?: boolean;
35
35
  /** Write comments (default true). Comments are read either way. */
36
36
  canComment?: boolean;
37
+ /**
38
+ * Who of those who may delete records may delete a given one: user ids, and
39
+ * `field:<field>` for whoever a person field of the record names ("only the
40
+ * record's approver"). Without it, everyone with `canDelete`.
41
+ */
42
+ deleters?: ReadonlyArray<string>;
37
43
  /**
38
44
  * Per field: `'hidden'` leaves it out (and every field that would show what
39
45
  * it holds), `'readOnly'` shows it without taking edits. A key is a column
@@ -55,6 +61,8 @@ export type TablePermissions = {
55
61
  canEditSchema: boolean;
56
62
  canEditViews: boolean;
57
63
  canComment: boolean;
64
+ /** Who may delete a given record (`deleters`); absent: everyone with `canDelete`. */
65
+ deleters?: ReadonlyArray<string>;
58
66
  };
59
67
  /** The base's permissions with a table's own over them. */
60
68
  export declare function mergePermissions(base: BasePermissions | null | undefined, own: BasePermissions | null | undefined): BasePermissions | null;
@@ -66,6 +74,11 @@ export declare function gridPermissions(ctrl: any): TablePermissions;
66
74
  export declare const canCreateIn: (ctrl: any) => boolean;
67
75
  /** Whether the person may delete records in this grid. */
68
76
  export declare const canDeleteIn: (ctrl: any) => boolean;
77
+ /**
78
+ * Whether the person may delete this record in this grid: `canDelete`, and
79
+ * named by the table's `deleters` (by id, or in a person field of the record).
80
+ */
81
+ export declare function canDeleteRecord(ctrl: any, row: unknown): boolean;
69
82
  /** Whether the person may write comments in this grid. */
70
83
  export declare const canCommentIn: (ctrl: any) => boolean;
71
84
  /** Whether the person may change this grid's fields. */
@@ -1 +1 @@
1
- import{colId as f}from"./base-tables.js";import{droppedFields as w}from"./base-share.js";const p={canEdit:!0,canCreate:!0,canDelete:!0,canEditSchema:!0,canEditViews:!0,canComment:!0};export function mergePermissions(e,n){if(!e&&!n)return null;const s=n?.viewsOnly??e?.viewsOnly;return{...e,...n,fields:{...e?.fields,...n?.fields},...s?{viewsOnly:s}:{}}}export function tablePermissions(e){if(!e)return p;const n=e.canEdit!==!1,s=!!e.viewsOnly;return{canEdit:n,canCreate:n&&e.canCreate!==!1,canDelete:n&&e.canDelete!==!1,canEditSchema:!s&&e.canEditSchema!==!1,canEditViews:!s&&e.canEditViews!==!1,canComment:e.canComment!==!1}}export function gridPermissions(e){const n=e?.props;if(n?.baseReadOnly===!0)return{canEdit:!1,canCreate:!1,canDelete:!1,canEditSchema:!1,canEditViews:!1,canComment:!1};const s=n?.basePermissions,r=!e||!!(e.editingEnabled??n?.editable??n?.enableInlineEditing),c=s??p;return{...c,canEdit:c.canEdit&&r,canCreate:c.canCreate&&r,canDelete:c.canDelete&&r}}export const canCreateIn=e=>gridPermissions(e).canCreate,canDeleteIn=e=>gridPermissions(e).canDelete,canCommentIn=e=>gridPermissions(e).canComment,canEditSchemaIn=e=>gridPermissions(e).canEditSchema;const y=(e,n)=>[n.id,`${e.id}.${n.id}`];export function permittedViews(e,n){const s=e.views;if(!s||!n)return s;const r=tablePermissions(n),c=n.viewsOnly?new Set(n.viewsOnly):null;return s.filter(l=>(!c||y(e,l).some(a=>c.has(a)))&&(r.canCreate||l.type!=="form"))}const m=Symbol("svgrid.permissionColumn");export function permittedTables(e,n){const s=new Map(e.map(t=>[t.id,mergePermissions(n,t.permissions)])),r=e.filter(t=>{const o=s.get(t.id);return!o?.viewsOnly||!!permittedViews(t,o)?.length});if(![...s.values()].some(Boolean))return[...e];const c=new Set(r.map(t=>t.id)),l=(t,o)=>{const i=s.get(t.id)?.fields;return i?.[`${t.id}.${f(o)}`]??i?.[f(o)]},a=w(r,(t,o)=>l(t,o)==="hidden"||o.fieldType==="link"&&!c.has(String(o.fieldProps?.table??"")));return r.map(t=>{const o=s.get(t.id);if(!o)return t;const i=a.get(t.id),d=tablePermissions(o),h=t.columns.filter(u=>!i.has(f(u))).map(u=>!d.canEdit||l(t,u)==="readOnly"?E(u):u);return{...t,columns:h,views:permittedViews(t,o)}})}export function permittedRecords(e,n){const s=new Map(e.map(r=>[r.id,r]));return permittedTables(e,n).map(r=>{const c=new Set(r.columns.map(a=>a.field)),l=s.get(r.id).columns.filter(a=>a.field!=null&&!c.has(a.field)).map(a=>String(a.field));return l.length?{...r,data:r.data.map(a=>{const t={...a};for(const o of l)delete t[o];return t})}:r})}function E(e){return e.editable===!1?e:{...e,editable:!1,[m]:{had:"editable"in e,editable:e.editable}}}export function restoreColumns(e,n,s=[]){const r=n.map(a=>{const t=a[m];if(!t)return a;const{[m]:o,...i}=a;return t.had?i.editable=t.editable:delete i.editable,i}),c=new Set([...r.map(f),...s]),l=[...r];return e.forEach((a,t)=>{if(c.has(f(a)))return;const o=e.slice(0,t).reverse().find(d=>c.has(f(d))),i=o?l.findIndex(d=>f(d)===f(o))+1:0;l.splice(i,0,a),c.add(f(a))}),l}export function restoreViews(e,n,s,r,c){const l=i=>r||!!c&&i.personal===c,a=new Set((n??[]).map(i=>i.id)),t=new Map(s.map(i=>[i.id,i])),o=[];for(const i of e??[]){const d=t.get(i.id);a.has(i.id)?d?o.push(l(i)?d:i):l(i)||o.push(i):o.push(i)}for(const i of s)!(e??[]).some(d=>d.id===i.id)&&l(i)&&o.push(i);return o}export function noDeleteSelectionBar(e){const n=s=>s.filter(r=>r!=="deleteRows");return Array.isArray(e)?n(e):e&&typeof e=="object"&&Array.isArray(e.actions)?{...e,actions:n(e.actions)}:e}
1
+ import{colId as f}from"./base-tables.js";import{recordOf as w,ruleNames as y}from"./people-rule.js";import{getCurrentUser as g}from"./sources.svelte.js";import{droppedFields as E}from"./base-share.js";const p={canEdit:!0,canCreate:!0,canDelete:!0,canEditSchema:!0,canEditViews:!0,canComment:!0};export function mergePermissions(e,n){if(!e&&!n)return null;const r=n?.viewsOnly??e?.viewsOnly;return{...e,...n,fields:{...e?.fields,...n?.fields},...r?{viewsOnly:r}:{}}}export function tablePermissions(e){if(!e)return p;const n=e.canEdit!==!1,r=!!e.viewsOnly;return{canEdit:n,canCreate:n&&e.canCreate!==!1,canDelete:n&&e.canDelete!==!1,canEditSchema:!r&&e.canEditSchema!==!1,canEditViews:!r&&e.canEditViews!==!1,canComment:e.canComment!==!1,...Array.isArray(e.deleters)?{deleters:e.deleters.map(String)}:{}}}export function gridPermissions(e){const n=e?.props;if(n?.baseReadOnly===!0)return{canEdit:!1,canCreate:!1,canDelete:!1,canEditSchema:!1,canEditViews:!1,canComment:!1};const r=n?.basePermissions,s=!e||!!(e.editingEnabled??n?.editable??n?.enableInlineEditing),c=r??p;return{...c,canEdit:c.canEdit&&s,canCreate:c.canCreate&&s,canDelete:c.canDelete&&s}}export const canCreateIn=e=>gridPermissions(e).canCreate,canDeleteIn=e=>gridPermissions(e).canDelete;export function canDeleteRecord(e,n){const r=gridPermissions(e);return r.canDelete?!r.deleters||y(r.deleters,g()?.id,w(n)):!1}export const canCommentIn=e=>gridPermissions(e).canComment,canEditSchemaIn=e=>gridPermissions(e).canEditSchema;const C=(e,n)=>[n.id,`${e.id}.${n.id}`];export function permittedViews(e,n){const r=e.views;if(!r||!n)return r;const s=tablePermissions(n),c=n.viewsOnly?new Set(n.viewsOnly):null;return r.filter(l=>(!c||C(e,l).some(a=>c.has(a)))&&(s.canCreate||l.type!=="form"))}const m=Symbol("svgrid.permissionColumn");export function permittedTables(e,n){const r=new Map(e.map(t=>[t.id,mergePermissions(n,t.permissions)])),s=e.filter(t=>{const o=r.get(t.id);return!o?.viewsOnly||!!permittedViews(t,o)?.length});if(![...r.values()].some(Boolean))return[...e];const c=new Set(s.map(t=>t.id)),l=(t,o)=>{const i=r.get(t.id)?.fields;return i?.[`${t.id}.${f(o)}`]??i?.[f(o)]},a=E(s,(t,o)=>l(t,o)==="hidden"||o.fieldType==="link"&&!c.has(String(o.fieldProps?.table??"")));return s.map(t=>{const o=r.get(t.id);if(!o)return t;const i=a.get(t.id),d=tablePermissions(o),h=t.columns.filter(u=>!i.has(f(u))).map(u=>!d.canEdit||l(t,u)==="readOnly"?S(u):u);return{...t,columns:h,views:permittedViews(t,o)}})}export function permittedRecords(e,n){const r=new Map(e.map(s=>[s.id,s]));return permittedTables(e,n).map(s=>{const c=new Set(s.columns.map(a=>a.field)),l=r.get(s.id).columns.filter(a=>a.field!=null&&!c.has(a.field)).map(a=>String(a.field));return l.length?{...s,data:s.data.map(a=>{const t={...a};for(const o of l)delete t[o];return t})}:s})}function S(e){return e.editable===!1?e:{...e,editable:!1,[m]:{had:"editable"in e,editable:e.editable}}}export function restoreColumns(e,n,r=[]){const s=n.map(a=>{const t=a[m];if(!t)return a;const{[m]:o,...i}=a;return t.had?i.editable=t.editable:delete i.editable,i}),c=new Set([...s.map(f),...r]),l=[...s];return e.forEach((a,t)=>{if(c.has(f(a)))return;const o=e.slice(0,t).reverse().find(d=>c.has(f(d))),i=o?l.findIndex(d=>f(d)===f(o))+1:0;l.splice(i,0,a),c.add(f(a))}),l}export function restoreViews(e,n,r,s,c){const l=i=>s||!!c&&i.personal===c,a=new Set((n??[]).map(i=>i.id)),t=new Map(r.map(i=>[i.id,i])),o=[];for(const i of e??[]){const d=t.get(i.id);a.has(i.id)?d?o.push(l(i)?d:i):l(i)||o.push(i):o.push(i)}for(const i of r)!(e??[]).some(d=>d.id===i.id)&&l(i)&&o.push(i);return o}export function noDeleteSelectionBar(e){const n=r=>r.filter(s=>s!=="deleteRows");return Array.isArray(e)?n(e):e&&typeof e=="object"&&Array.isArray(e.actions)?{...e,actions:n(e.actions)}:e}
@@ -1 +1 @@
1
- import{fillFieldColumn as Q}from"./registry.svelte.js";import Pe from"./RatingCell.svelte";import A from"./LinkCell.svelte";import De from"./AttachmentCell.svelte";import Ve from"./CheckboxCell.svelte";import ee from"./PercentCell.svelte";import O from"./UserCell.svelte";import Fe from"./ButtonCell.svelte";import Ie from"./BarcodeCell.svelte";import Le from"./LinkedRecordsCell.svelte";import Ae from"./RichTextCell.svelte";import Oe from"./RichHtmlCell.svelte";import{richPlain as D}from"./rich-html.js";import{toRichHtml as Ne}from"./rich-html-write.js";import te from"./SelectCell.svelte";import Re from"./ChecklistCell.svelte";import Be from"./ColorCell.svelte";import{attachmentsText as Ee,parseAttachments as Ue}from"./attachments.js";import{dateEditTokens as He,dateFromParts as N,exactNumber as _e,formatCurrency as re,formatDate as R,formatDuration as le,formatNumber as B,formatPercent as ie,numberFieldShape as ne,numberFromText as ze,numberKind as Ge,parseDateText as je,parseDuration as V,toNumber as E}from"./format.js";import{BRIGHT as oe,CHECKBOX_ICONS as $e,RATING_ICONS as Ke}from"./palette.js";import{COMPUTED_TYPES as We,ROLLUPS as U,fieldNameMap as Ye}from"./rollups.js";import{sparklineValues as H,voteCount as ae,voteIds as Xe}from"./vote.js";import xe from"./VoteCell.svelte";import Ze from"./TimerCell.svelte";import{timerSeconds as F,timerTotal as qe}from"./timer.js";import Je from"./SparklineCell.svelte";import{compileFormula as Qe,isoDate as et,selfReferenceError as tt}from"./formula.js";import{findFieldUser as se,getCurrentUser as ue,getFieldUsers as _,getLinkedTable as k,idOf as rt,linkedRows as z,listLinkedTables as lt,liveLink as it,recordsNaming as nt,resolveLinkId as ot,resolveLinkIds as at}from"./sources.svelte.js";import{splitNames as G}from"./name-list.js";import{linkedFields as st}from"./linked-fields.js";import{AI_FIELD_TYPE as ut}from"./ai-field.svelte.js";import{CHECKLIST_GROUPS as ce,checklistGroup as ct,checklistSortValue as dt,checklistText as pt,parseChecklist as ft,toChecklist as mt}from"./checklist.js";import{colorSortValue as gt,parseColor as j}from"./color-value.js";import{formatTimeOfDay as ht,parseTimeOfDay as de,timeSeconds as yt}from"./time-of-day.js";import{bm as l}from"./messages.svelte.js";const bt=new Set(["user","createdBy","lastModifiedBy"]);function kt(e){const t=String(e.field??e.id),r=o=>o.length===1?o[0]:o;if(bt.has(String(e.fieldType)))return o=>{const n=o?.[t];return n==null||n===""?n:r((Array.isArray(n)?n:[n]).map(a=>se(a)?.name??a))};if(e.fieldType!=="link")return null;const i=e.fieldProps?.table;return o=>{const n=o?.[t],a=k(i);if(!a||n==null||n==="")return n;const p=$(a,a.primaryField),f=new Map(z(a,n).map(d=>[rt(a,d),p(d)]));return r((Array.isArray(n)?n:[n]).map(d=>f.get(String(d))??d))}}const pe=new WeakMap;let v=0;function $(e,t){const r=n=>n?.[t];if(!e?.fields?.length)return r;let i=pe.get(e.fields);if(i||pe.set(e.fields,i=new Map),!i.has(t)){const n=st(e).find(p=>p.def.field===t),a=n?.def.fieldType==="timer"?p=>F(p?.[t]):null;i.set(t,a??n?.def.fieldFn??null)}const o=i.get(t);return o?n=>{if(v>3)return r(n);v+=1;try{return o(n)}finally{v-=1}}:r}const s={text:"M4 6h16M4 12h10M4 18h7",longText:"M4 6h16M4 10h16M4 14h16M4 18h10",richText:"M6 4h7a4 4 0 0 1 0 8H6zM6 12h8a4 4 0 0 1 0 8H6zM6 4v16",vote:"M12 19V5M5 12l7-7 7 7",sparkline:"M3 17l5-6 4 4 8-9",number:"M9 4 7 20M17 4l-2 16M4 9h16M3 15h16",currency:"M12 3v18M16 7.5C16 5.6 14.2 4.5 12 4.5S8 5.6 8 7.5s1.8 2.7 4 3.5 4 1.6 4 3.5-1.8 3-4 3-4-1.1-4-3",percent:"M19 5 5 19M7 7h.01M17 17h.01",date:"M4 6h16v14H4zM4 10h16M8 3v4M16 3v4",duration:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4l3 2",timer:"M12 7a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM12 10v4l2.5 1.5M9.5 2.5h5M12 2.5V5",checkbox:"M4 4h16v16H4zM8 12l3 3 5-6",singleSelect:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM8 11l4 4 4-4",multiSelect:"M3 7h11M3 12h11M3 17h11M17 6l2 2 3-3M17 16l2 2 3-3",rating:"M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3 6.5 20.2l1-6.2L3 9.6l6.2-.9z",url:"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1",email:"M3 6h18v12H3zM3 7l9 6 9-6",phone:"M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2",attachment:"M20 11.5 12.3 19a5 5 0 0 1-7.1-7.1l7.8-7.8a3.3 3.3 0 0 1 4.7 4.7L9.9 16.6a1.7 1.7 0 0 1-2.4-2.4l7.1-7",user:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0",createdTime:"M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zM12 8v4h4",modifiedTime:"M4 12a8 8 0 1 0 2.3-5.7M4 4v4h4M12 8v4l3 2",createdBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M19 15v6M16 18h6",modifiedBy:"M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 11-7.5M16 21l5-5-2-2-5 5v2z",autoNumber:"M5 7h3v10M11 9a2 2 0 1 1 4 0c0 2-4 3-4 6h4M18 7h2v10",barcode:"M4 5v14M7 5v14M10 5v14M13 5v14M15 5v14M18 5v14M20 5v14",button:"M4 7h16v10H4zM9 12h6",formula:"M7 20c2 0 2.5-2 3-5l2-10c.5-2 1.5-2 3-2M8 9h7",link:"M9 7H6a5 5 0 0 0 0 10h3M15 7h3a5 5 0 0 1 0 10h-3M8 12h8",lookup:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4M8 11h6",rollup:"M6 4h12L12 12l6 8H6",count:"M5 5h14v14H5zM9 9v6M12 9v6M15 9v6",checklist:"M3.5 6l1.5 1.5L7.5 5M3.5 12l1.5 1.5 2.5-2.5M3.5 18l1.5 1.5 2.5-2.5M11 6h9M11 12h9M11 18h9",color:"M12 3a9 9 0 1 0 0 18c1 0 1.6-.7 1.6-1.6 0-1-.8-1.4-.8-2.3 0-1 .8-1.7 1.8-1.7H17a4 4 0 0 0 4-4C21 6.6 17 3 12 3zM7.5 12h.01M9.5 7.5h.01M14.5 7.5h.01",timeOfDay:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 7v5l-3 2M12 3v2M21 12h-2M12 21v-2M3 12h2"},u=(e,t)=>({value:e,get label(){return l(t)}}),fe=e=>e?{visible:e}:{},wt={key:"separators",get label(){return l("fields.propSeparators")},kind:"choice",choices:[u("local","fields.choiceLocal"),{value:"comma-period",label:"1,000,000.00"},{value:"period-comma",label:"1.000.000,00"},{value:"space-comma",label:"1 000 000,00"},{value:"space-period",label:"1 000 000.00"}]},Tt={key:"showThousands",get label(){return l("fields.propShowThousands")},kind:"checkbox"},vt=e=>({key:"abbreviation",get label(){return l("fields.propAbbreviation")},kind:"choice",choices:[u("none","fields.choiceNone"),u("thousand","fields.choiceThousand"),u("million","fields.choiceMillion"),u("billion","fields.choiceBillion")],...fe(e)}),St={key:"allowNegative",get label(){return l("fields.propAllowNegative")},kind:"checkbox"},w={key:"default",get label(){return l("fields.propDefault")},kind:"default",get hint(){return l("fields.propDefaultHint")}},K=(e,t)=>Array.from({length:t-e+1},(r,i)=>{const o=e+i;return{value:String(o),label:o===0?"1":`1.${"0".repeat(o)}`}}),W=(e,t)=>({key:"precision",get label(){return l("fields.propPrecision")},kind:"choice",choices:e,visible:t}),Mt=[u("local","fields.choiceLocal"),u("friendly","fields.choiceFriendly"),u("us","fields.choiceUs"),u("european","fields.choiceEuropean"),u("iso","fields.choiceIso")],I=e=>({key:"dateFormat",get label(){return l("fields.propDateFormat")},kind:"choice",choices:Mt,...fe(e)}),me=[u("12hour","fields.choice12Hour"),u("24hour","fields.choice24Hour")],Y=[{key:"time",get label(){return l("fields.propIncludeTime")},kind:"checkbox"},{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:me,visible:e=>!!e.time},{key:"gmt",get label(){return l("fields.propGmt")},kind:"checkbox",visible:e=>!!e.time},{key:"showTimeZone",get label(){return l("fields.propShowTimeZone")},kind:"checkbox",visible:e=>!!e.time}],Ct=e=>e.columns.filter(t=>t.fieldType==="link").map(t=>({value:String(t.id??t.field),label:String(t.header??t.field)})),X={key:"linkField",get label(){return l("fields.propLinkField")},kind:"choice",choices:Ct,get hint(){return l("fields.propLinkFieldHint")}},Pt=e=>{const t=e.columns.find(o=>String(o.id??o.field)===e.props.linkField),r=k(t?.fieldProps?.table);return r?(r.fields??[{field:r.primaryField,header:r.primaryField}]).map(o=>({value:o.field,label:o.header})):[]},ge={key:"field",get label(){return l("fields.propLinkedField")},kind:"choice",choices:Pt,visible:e=>!!e.linkField},M={key:"color",get label(){return l("fields.propColor")},kind:"color",palette:oe},he={key:"options",get label(){return l("fields.propOptions")},kind:"options"},ye=(e,t=0)=>{const r=Number(e.precision);return Number.isInteger(r)&&r>=0&&r<=8?r:t},Dt=e=>({precision:e.format==="integer"?0:ye(e,e.format==="decimal"?1:0),separators:e.separators,showThousands:e.showThousands!==!1,abbreviation:e.abbreviation}),Vt=(e,t)=>r=>{const i=typeof r.rawInput=="string"?r.rawInput:r.newValue;if(typeof i=="number"||i==null)return i;if(String(i).trim()==="")return null;const o=ze(String(i),e,t);return o??r.oldValue},Ft=(e,t)=>t.allowNegative===!1&&!e.validate?{rejectInvalid:!0,validate:r=>Number(r.value)<0?l("fields.negativeNotAllowed"):null}:{},It=(e,t)=>{const r={precision:ne(e,t).places,separators:t.separators,showThousands:t.showThousands!==!1,abbreviation:e==="percent"?void 0:t.abbreviation};return i=>{const o=_e(i.value);return o==null?"":e==="currency"?re(o,{...r,symbol:t.symbol,symbolPosition:t.symbolPosition}):e==="percent"?ie(o,{...r,points:t.points}):B(o,r)}},x=(e,t,r)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",align:e.align??(r==="percent"&&t.showBar?"left":"right"),...Ft(e,t),valueParser:e.valueParser??Vt(r,t),formatter:e.formatter??It(r,t),sortValue:e.sortValue??E}),C=e=>Array.isArray(e.options)?e.options.map(t=>({value:t.value,label:t.label??String(t.value),...t.color?{color:t.color}:{}})):[],be=(e,t)=>{const r=new Map;for(const n of C(e))r.set(String(n.value).toLowerCase(),n.value),r.set(String(n.label).toLowerCase(),n.value);const i=n=>r.get(n.toLowerCase()),o=r.size===0;return n=>{if(typeof n.rawInput!="string")return n.newValue;const a=t?G(n.rawInput):n.rawInput.split(/\n/).map(f=>f.trim()).filter(Boolean);if(o)return t?[...new Set(a)]:a[0]??null;const p=a.map(i).filter(f=>f!==void 0);return a.length&&!p.length?n.oldValue:t?[...new Set(p)]:a.length?i(a[0])===void 0?n.oldValue:i(a[0]):null}},ke=e=>{const t=new Map(C(e).map(r=>[String(r.value),r.label]));return r=>(Array.isArray(r.value)?r.value:r.value==null||r.value===""?[]:[r.value]).map(i=>t.get(String(i))??String(i)).join(", ")},Lt=e=>{const t=new Map(C(e).map((r,i)=>[String(r.value),i]));return r=>r==null||r===""?null:t.get(String(r))??t.size},we=Ye,m=e=>({editable:e.editable??!1}),Z=e=>t=>R(t.value,e),P=e=>e.oldValue!=null&&typeof e.oldValue!="string"&&String(e.oldValue)===e.newValue?e.oldValue:e.newValue,At=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;if(r==null||typeof r=="string"&&r.trim()==="")return null;if(r instanceof Date)return e.time?r.toISOString():N({y:r.getFullYear(),mo:r.getMonth()+1,d:r.getDate(),time:null},e);const i=String(r).trim();if(/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?/.test(i)){if(!e.time)return i.slice(0,10);if(i.length>10&&i[10]==="T")return i}const o=je(i,e);return o?N(o,e,t.oldValue):t.oldValue},q=e=>(Array.isArray(e)?e:e==null||e===""?[]:[e]).map(t=>se(t)?.name??String(t)).join(", "),Te=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=_(),i=a=>{const p=a.toLowerCase();return r.find(d=>d.id.toLowerCase()===p||d.name.toLowerCase()===p||d.email?.toLowerCase()===p)?.id??(r.length?void 0:a)},o=e?G(t.rawInput):t.rawInput.split(/\n/).map(a=>a.trim()).filter(Boolean),n=o.map(i).filter(a=>a!==void 0);return o.length&&!n.length?t.oldValue:e?[...new Set(n)]:o.length?n[0]:null},Ot=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=k(e.table);if(!r)return t.newValue;const i=G(t.rawInput),o=at(r,i);if(r.records&&r.resolveNames&&t.data&&t.columnId){const n=i.filter(a=>ot(r,a)==null);n.length&&r.resolveNames({row:t.data,columnId:t.columnId,multiple:e.multiple!==!1},n,o)}return i.length&&!o.length?t.oldValue:e.multiple===!1?o.slice(0,1):o},Nt=e=>typeof e.rawInput=="string"?e.rawInput.trim()?ft(e.rawInput):null:Array.isArray(e.newValue)?mt(e.newValue):e.newValue??null,Rt=e=>t=>{if(typeof t.rawInput!="string")return t.newValue;const r=t.rawInput.trim();if(!r)return null;const i=Number(r);return Number.isInteger(i)&&i>=0&&i<=Number(e.max??5)?i:t.oldValue},Bt=e=>{const t=typeof e.rawInput=="string"?e.rawInput:e.newValue;return t==null||String(t).trim()===""?null:j(t)??e.oldValue},Et=e=>t=>{const r=typeof t.rawInput=="string"?t.rawInput:t.newValue;return r==null||typeof r=="string"&&r.trim()===""?null:de(r,{seconds:!!e.showSeconds})??t.oldValue};function ve(e,t){if(e==null)return"";if(Array.isArray(e))return e.map(r=>ve(r,t)).join(", ");if(e instanceof Date)return R(e,t);if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(t.result==="currency"||t.result==="percent"||t.result==="number"){const r=t.result,i={...Dt(t),precision:ne(r,{precision:t.precision}).places};return r==="currency"?re(e,{...i,symbol:t.symbol}):r==="percent"?ie(e,i):B(e,i)}return String(Math.round(e*1e10)/1e10)}if(t.result==="date"){const r=et(String(e));if(r)return R(r,t)}return String(e)}const J=(e,t)=>{const r=t.columns.find(n=>String(n.id??n.field)===e.linkField);if(!r)return null;const i=r.fieldProps?.table,o=r.fieldProps?.inverse;return{key:String(r.field??r.id),get table(){return k(i)},rowsOf(n){const a=k(i),p=String(r.field??r.id);return a&&o&&!a.records&&n?.[p]===void 0?nt(a,o,String(n?.id??"")):z(a,n?.[p])},get stored(){const n=k(i)?.records;return n&&o&&n.stores(o)?{records:n,field:o}:null}}},Ut={SUM:"sum",AVERAGE:"avg",MIN:"min",MAX:"max",COUNT:"count"},Se=new WeakMap;function Me(e,t,r){const i=e?.table?.fields;if(!i)return;let o=Se.get(i);o||Se.set(i,o=new Map);const n=`${String(t)}|${r??""}`;if(o.has(n))return o.get(n);const a=i.find(f=>f.field===String(t)),p=a?.fieldType?Q({field:a.field,fieldType:a.fieldType,fieldProps:{...a.fieldProps,...r==null?{}:{precision:r}}}).formatter:void 0;return o.set(n,p),p}const L=()=>new Date().toISOString(),Ht=new Intl.Collator(void 0,{sensitivity:"base",numeric:!0}),_t=(e,t)=>{const r=i=>i?ce.indexOf(i):ce.length;return r(e)-r(t)},Ce=[{key:"watch",get label(){return l("fields.propWatch")},kind:"segmented",choices:[u("all","fields.choiceAllFields"),u("specific","fields.choiceSpecificFields")]},{key:"watchFields",get label(){return l("fields.propWatchFields")},kind:"columns",visible:e=>e.watch==="specific"}];export const BUILTIN_FIELD_TYPES=[{id:"text",get label(){return l("fields.typeText")},get description(){return l("fields.typeTextDescription")},icon:s.text,group:"basic",properties:[w],fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??P})},{id:"longText",get label(){return l("fields.typeLongText")},get description(){return l("fields.typeLongTextDescription")},icon:s.longText,group:"basic",width:260,properties:[{key:"richText",get label(){return l("fields.propMarkdown")},kind:"checkbox",get hint(){return l("fields.propMarkdownHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldLongText",valueParser:e.valueParser??P}),cell:Ae,hasCell:e=>!!e.richText},{id:"richText",get label(){return l("fields.typeRichText")},get description(){return l("fields.typeRichTextDescription")},icon:s.richText,group:"basic",width:280,defaults:{toolbar:"standard"},properties:[{key:"toolbar",get label(){return l("fields.propToolbar")},kind:"segmented",choices:[u("standard","fields.choiceStandard"),u("full","fields.choiceFull")],get hint(){return l("fields.propToolbarHint")}}],fill:e=>({...e,editorType:e.editorType??"fieldRichText",formatter:e.formatter??(t=>D(t.value)),sortComparator:e.sortComparator??((t,r)=>Ht.compare(D(t),D(r))),valueParser:e.valueParser??(t=>Ne(t.newValue))}),cell:Oe},{id:"attachment",get label(){return l("fields.typeAttachment")},get description(){return l("fields.typeAttachmentDescription")},icon:s.attachment,group:"basic",width:180,defaults:{maxFiles:20},properties:[{key:"accept",get label(){return l("fields.propAccept")},kind:"text",get placeholder(){return l("fields.propAcceptPlaceholder")}},{key:"maxFiles",get label(){return l("fields.propMaxFiles")},kind:"number",min:1,max:100}],fill:(e,t)=>({...e,editorType:e.editorType??"attachment",formatter:e.formatter??(r=>Ee(r.value)),valueParser:e.valueParser??(r=>Ue(r.newValue,t))}),cell:De},{id:"checkbox",get label(){return l("fields.typeCheckbox")},get description(){return l("fields.typeCheckboxDescription")},icon:s.checkbox,group:"basic",width:90,defaults:{icon:"check",color:"#20c933"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:$e},M,w],fill:e=>({...e,editorType:e.editorType??"checkbox",align:e.align??"center",toggleOnSecondClick:e.toggleOnSecondClick??!0}),cell:Ve},{id:"singleSelect",get label(){return l("fields.typeSingleSelect")},get description(){return l("fields.typeSingleSelectDescription")},icon:s.singleSelect,group:"basic",width:140,defaults:{options:[]},properties:[he,w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorOptions:e.editorOptions??C(t),formatter:e.formatter??ke(t),valueParser:e.valueParser??be(t,!1),sortValue:e.sortValue??Lt(t)}),cell:te},{id:"multiSelect",get label(){return l("fields.typeMultiSelect")},get description(){return l("fields.typeMultiSelectDescription")},icon:s.multiSelect,group:"basic",width:200,defaults:{options:[]},properties:[he,w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",editorMultiple:e.editorMultiple??!0,editorOptions:e.editorOptions??C(t),formatter:e.formatter??ke(t),valueParser:e.valueParser??be(t,!0)}),cell:te},{id:"user",get label(){return l("fields.typeUser")},get description(){return l("fields.typeUserDescription")},icon:s.user,group:"basic",width:170,properties:[{key:"multiple",get label(){return l("fields.propMultipleUsers")},kind:"checkbox"},w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldSelect",valueParser:e.valueParser??Te(!!t.multiple),editorMultiple:e.editorMultiple??!!t.multiple,editorOptions:e.editorOptions??_().map(r=>({value:r.id,label:r.name})),formatter:e.formatter??(r=>q(r.value))}),cell:O},{id:"date",get label(){return l("fields.typeDate")},get description(){return l("fields.typeDateDescription")},icon:s.date,group:"basic",width:150,defaults:{dateFormat:"local",timeFormat:"12hour"},properties:[I(),...Y,{key:"defaultToday",get label(){return l("fields.propDefaultToday")},kind:"checkbox"}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??(t.time?"date":"dateString"),editorType:e.editorType??"fieldDate",editorFormatString:e.editorFormatString??He(t),formatter:e.formatter??Z(t),valueParser:e.valueParser??At(t)}),newRowValue:({props:e})=>{if(!e.defaultToday)return;if(e.time)return L();const t=new Date;return N({y:t.getFullYear(),mo:t.getMonth()+1,d:t.getDate(),time:null},{})}},{id:"phone",get label(){return l("fields.typePhone")},get description(){return l("fields.typePhoneDescription")},icon:s.phone,group:"basic",fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??P}),cell:A},{id:"email",get label(){return l("fields.typeEmail")},get description(){return l("fields.typeEmailDescription")},icon:s.email,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??P}),cell:A},{id:"url",get label(){return l("fields.typeUrl")},get description(){return l("fields.typeUrlDescription")},icon:s.url,group:"basic",width:200,fill:e=>({...e,editorType:e.editorType??"text",valueParser:e.valueParser??P}),cell:A},{id:"barcode",get label(){return l("fields.typeBarcode")},get description(){return l("fields.typeBarcodeDescription")},icon:s.barcode,group:"basic",width:160,fill:e=>({...e,editorType:e.editorType??"text",formatter:e.formatter??(t=>t.value&&typeof t.value=="object"?String(t.value.text??""):String(t.value??""))}),cell:Ie},{id:"button",get label(){return l("fields.typeButton")},get description(){return l("fields.typeButtonDescription")},icon:s.button,group:"basic",width:120,defaults:{label:"Open",color:"#2d7ff9"},properties:[{key:"label",get label(){return l("fields.propButtonLabel")},kind:"text",get placeholder(){return l("fields.propButtonLabelPlaceholder")}},{key:"color",get label(){return l("fields.propButtonStyle")},kind:"color",palette:oe},{key:"url",get label(){return l("fields.propButtonUrl")},kind:"text",get placeholder(){return l("fields.propButtonUrlPlaceholder")},get hint(){return l("fields.propButtonUrlHint")}}],fill:(e,t,r)=>({...e,...m(e),sortable:e.sortable??!1,__fieldNames:we(r.columns)}),cell:Fe},{id:"checklist",get label(){return l("fields.typeChecklist")},get description(){return l("fields.typeChecklistDescription")},icon:s.checklist,group:"basic",width:150,fill:e=>({...e,editorType:e.editorType??"fieldChecklist",formatter:e.formatter??(t=>pt(t.value)),valueParser:e.valueParser??Nt,sortValue:e.sortValue??dt,groupValue:e.groupValue??ct,groupOrder:e.groupOrder??_t}),cell:Re},{id:"color",get label(){return l("fields.typeColor")},get description(){return l("fields.typeColorDescription")},icon:s.color,group:"basic",width:130,properties:[w],fill:e=>({...e,editorType:e.editorType??"fieldColor",formatter:e.formatter??(t=>j(t.value)??String(t.value??"")),valueParser:e.valueParser??Bt,sortValue:e.sortValue??gt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:j(e.default),cell:Be},{id:"number",get label(){return l("fields.typeNumber")},get description(){return l("fields.typeNumberDescription")},icon:s.number,group:"number",width:120,defaults:{format:"decimal",precision:1,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0,symbol:"$",symbolPosition:"before",showBar:!1,points:!1,step:1},properties:[{key:"format",get label(){return l("fields.propFormat")},kind:"segmented",choices:[u("integer","fields.choiceInteger"),u("decimal","fields.choiceDecimal"),u("currency","fields.choiceCurrency"),u("percent","fields.choicePercent")],alsoSets:e=>({precision:e==="decimal"?1:e==="currency"?2:0})},{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$, €, £, ¥, CHF, kr",visible:e=>e.format==="currency"},{key:"symbolPosition",get label(){return l("fields.propSymbolPosition")},kind:"segmented",visible:e=>e.format==="currency",choices:[u("before","fields.choiceBefore"),u("after","fields.choiceAfter")]},W(K(0,8),e=>e.format!=="integer"),{key:"step",get label(){return l("fields.propStep")},kind:"number",min:0,get hint(){return l("fields.propStepHint")}},wt,Tt,vt(e=>e.format!=="percent"),St,{key:"showBar",get label(){return l("fields.propShowBar")},kind:"checkbox",visible:e=>e.format==="percent"},{key:"points",get label(){return l("fields.propPoints")},kind:"checkbox",visible:e=>e.format==="percent"},w],fill:(e,t)=>x(e,t,Ge("number",t)),cell:ee,hasCell:e=>e.format==="percent"&&!!e.showBar},{id:"currency",get label(){return l("fields.typeCurrency")},get description(){return l("fields.typeCurrencyDescription")},icon:s.currency,group:"number",width:120,defaults:{symbol:"$",symbolPosition:"before",precision:2,separators:"local",showThousands:!0,abbreviation:"none",allowNegative:!0},editAs:{type:"number",props:{format:"currency"}},fill:(e,t)=>x(e,t,"currency")},{id:"percent",get label(){return l("fields.typePercent")},get description(){return l("fields.typePercentDescription")},icon:s.percent,group:"number",width:110,defaults:{precision:0,separators:"local",showThousands:!0,allowNegative:!0,points:!1},editAs:{type:"number",props:{format:"percent"}},fill:(e,t)=>x(e,t,"percent"),cell:ee,hasCell:e=>!!e.showBar},{id:"duration",get label(){return l("fields.typeDuration")},get description(){return l("fields.typeDurationDescription")},icon:s.duration,group:"number",width:110,defaults:{durationFormat:"h:mm"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"},{value:"h:mm:ss.S",label:"h:mm:ss.S"},{value:"h:mm:ss.SS",label:"h:mm:ss.SS"},{value:"h:mm:ss.SSS",label:"h:mm:ss.SSS"}]}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldNumber",formatter:e.formatter??(r=>{const i=E(r.value);return i==null?"":le(i,t.durationFormat)}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:typeof r.newValue=="number"?r.newValue:V(r.newValue))})},{id:"timeOfDay",get label(){return l("fields.typeTimeOfDay")},get description(){return l("fields.typeTimeOfDayDescription")},icon:s.timeOfDay,group:"number",width:120,defaults:{timeFormat:"12hour",showSeconds:!1},properties:[{key:"timeFormat",get label(){return l("fields.propTimeFormat")},kind:"segmented",choices:me},{key:"showSeconds",get label(){return l("fields.propShowSeconds")},kind:"checkbox"},w],fill:(e,t)=>({...e,editorType:e.editorType??"fieldTime",formatter:e.formatter??(r=>ht(r.value,t)),valueParser:e.valueParser??Et(t),sortValue:e.sortValue??yt}),newRowValue:({props:e})=>e.default==null||e.default===""?void 0:de(e.default,{seconds:!!e.showSeconds})},{id:"rating",get label(){return l("fields.typeRating")},get description(){return l("fields.typeRatingDescription")},icon:s.rating,group:"number",width:130,defaults:{max:5,icon:"star",color:"#fcb400"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"icon",icons:Ke},M,{key:"max",get label(){return l("fields.propMaximum")},kind:"choice",choices:Array.from({length:10},(e,t)=>({value:String(t+1),label:String(t+1)}))}],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",align:e.align??"left",editorType:e.editorType??"fieldRating",valueParser:e.valueParser??Rt(t)}),cell:Pe},{id:"timer",get label(){return l("fields.typeTimer")},get description(){return l("fields.typeTimerDescription")},icon:s.timer,group:"number",width:130,defaults:{durationFormat:"h:mm:ss"},properties:[{key:"durationFormat",get label(){return l("fields.propDurationFormat")},kind:"choice",choices:[{value:"h:mm",label:"h:mm"},{value:"h:mm:ss",label:"h:mm:ss"}]},M],fill:(e,t)=>({...e,cellDataType:e.cellDataType??"number",editorType:e.editorType??"fieldTimer",align:e.align??"left",sortValue:e.sortValue??(r=>F(r)),formatter:e.formatter??(r=>{const i=F(r.value);return i==null?"":le(i,t.durationFormat??"h:mm:ss")}),valueParser:e.valueParser??(r=>typeof r.rawInput=="string"?r.rawInput.trim()?V(r.rawInput)??r.oldValue:null:r.newValue==null||r.newValue===""?null:typeof r.newValue=="number"||typeof r.newValue=="object"&&qe(r.newValue)!=null?r.newValue:V(r.newValue))}),cell:Ze},{id:"vote",get label(){return l("fields.typeVote")},get description(){return l("fields.typeVoteDescription")},icon:s.vote,group:"basic",width:100,defaults:{icon:"up"},properties:[{key:"icon",get label(){return l("fields.propIcon")},kind:"segmented",choices:[u("up","fields.choiceArrow"),u("thumb","fields.choiceThumb"),u("heart","fields.choiceHeart")]},M],fill:e=>({...e,editorType:e.editorType??"fieldVote",editorOptions:e.editorOptions??_().map(t=>({value:t.id,label:t.name})),align:e.align??"left",sortValue:e.sortValue??(t=>ae(t)),formatter:e.formatter??(t=>String(ae(t.value))),valueParser:e.valueParser??(t=>Xe(Te(!0)(t)))}),newRowValue:()=>[],cell:xe},{id:"sparkline",get label(){return l("fields.typeSparkline")},get description(){return l("fields.typeSparklineDescription")},icon:s.sparkline,group:"number",width:160,defaults:{chart:"line"},properties:[{key:"chart",get label(){return l("fields.propChart")},kind:"segmented",choices:[u("line","fields.choiceLine"),u("area","fields.choiceArea"),u("bar","fields.choiceColumns")]},M,{key:"showLast",get label(){return l("fields.propShowLast")},kind:"checkbox"}],fill:e=>({...e,formatter:e.formatter??(t=>H(t.value).join(", ")),valueParser:e.valueParser??(t=>{const r=H(t.newValue);return r.length?r:null}),sortValue:e.sortValue??(t=>H(t).at(-1)??null)}),cell:Je},{id:"formula",get label(){return l("fields.typeFormula")},get description(){return l("fields.typeFormulaDescription")},icon:s.formula,group:"computed",width:160,defaults:{formula:"",result:"auto"},properties:[{key:"formula",get label(){return l("fields.propFormula")},kind:"formula"},{key:"result",get label(){return l("fields.propResult")},kind:"choice",choices:[u("auto","fields.choiceAsComputed"),u("number","fields.choiceNumber"),u("currency","fields.choiceCurrency"),u("percent","fields.choicePercent"),u("date","fields.choiceDate")]},W(K(0,8),e=>["number","currency","percent"].includes(e.result)),{key:"symbol",get label(){return l("fields.propCurrencySymbol")},kind:"text",placeholder:"$",visible:e=>e.result==="currency"},I(e=>e.result==="date")],fill:(e,t,r)=>{const i=we(r.columns),o=String(t.formula??""),n=String(e.field??e.id),a=new Set([n.toLowerCase(),typeof e.header=="string"?e.header.trim().toLowerCase():""].filter(Boolean)),p=c=>{const b=c.trim().toLowerCase(),h=i[b]??null;if(h===n||h==null&&a.has(b))throw tt(c);return h};let f=null;try{f=o.trim()?Qe(o,p).fn:()=>null}catch{f=null}let d=null;const g=()=>{if(d)return d;d=new Map;for(const c of r.columns){if(c.fieldType==="richText"){const y=String(c.field??c.id);d.set(y,T=>D(T?.[y]));continue}if(c.fieldType==="timer"){const y=String(c.field??c.id);d.set(y,T=>F(T?.[y]));continue}const b=kt(c);if(b){d.set(String(c.field??c.id),b);continue}if(!We.has(String(c.fieldType))||String(c.field??c.id)===n)continue;const h=Q(c,r.columns);typeof h.fieldFn=="function"&&d.set(String(c.field??c.id),h.fieldFn)}return d},S=c=>{const b=g();return!b.size||!c?c:new Proxy(c,{get:(h,y)=>{const T=typeof y=="string"?b.get(y):void 0;if(!T||v>3)return h[y];v+=1;try{return T(h)}finally{v-=1}}})};return{...e,...m(e),fieldFn:c=>f?f(S(c)):"#ERROR",align:e.align??(["number","currency","percent"].includes(t.result)?"right":void 0),formatter:e.formatter??(c=>ve(c.value,t))}}},{id:"createdTime",get label(){return l("fields.typeCreatedTime")},get description(){return l("fields.typeCreatedTimeDescription")},icon:s.createdTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour"},properties:[I(),...Y],fill:(e,t)=>({...e,...m(e),formatter:e.formatter??Z(t)}),newRowValue:()=>L(),onCreate:({rows:e})=>e.map(()=>L())},{id:"lastModifiedTime",get label(){return l("fields.typeLastModifiedTime")},get description(){return l("fields.typeLastModifiedTimeDescription")},icon:s.modifiedTime,group:"computed",width:170,defaults:{dateFormat:"local",time:!0,timeFormat:"12hour",watch:"all"},properties:[...Ce,I(),...Y],fill:(e,t)=>({...e,...m(e),formatter:e.formatter??Z(t)}),newRowValue:()=>L()},{id:"createdBy",get label(){return l("fields.typeCreatedBy")},get description(){return l("fields.typeCreatedByDescription")},icon:s.createdBy,group:"computed",width:160,fill:e=>({...e,...m(e),formatter:e.formatter??(t=>q(t.value))}),newRowValue:()=>ue()?.id??null,cell:O},{id:"lastModifiedBy",get label(){return l("fields.typeLastModifiedBy")},get description(){return l("fields.typeLastModifiedByDescription")},icon:s.modifiedBy,group:"computed",width:160,defaults:{watch:"all"},properties:Ce,fill:e=>({...e,...m(e),formatter:e.formatter??(t=>q(t.value))}),newRowValue:()=>ue()?.id??null,cell:O},{id:"autoNumber",get label(){return l("fields.typeAutoNumber")},get description(){return l("fields.typeAutoNumberDescription")},icon:s.autoNumber,group:"computed",width:100,fill:e=>({...e,...m(e),cellDataType:e.cellDataType??"number"}),newRowValue:({rows:e,field:t})=>e.reduce((r,i)=>Math.max(r,Number(i?.[t])||0),0)+1,onCreate:({rows:e})=>e.map((t,r)=>r+1)},{id:"link",get label(){return l("fields.typeLink")},get description(){return l("fields.typeLinkDescription")},icon:s.link,group:"relation",width:200,defaults:{multiple:!0},properties:[{key:"table",get label(){return l("fields.propTable")},kind:"choice",choices:()=>lt().map(e=>({value:e.id,label:e.name})),get hint(){return l("fields.propTableHint")},alsoSets:()=>({pickFrom:""})},{key:"multiple",get label(){return l("fields.propMultipleRecords")},kind:"checkbox"},{key:"pickFrom",get label(){return l("fields.propPickFrom")},kind:"choice",choices:e=>[{value:"",label:l("fields.pickFromAll")},...(k(e.props.table)?.views?.()??[]).filter(t=>!t.personal&&t.type!=="form").map(t=>({value:t.id,label:t.name}))],visible:e=>!!e.table,get hint(){return l("fields.propPickFromHint")}}],fill:(e,t)=>({...e,editorType:e.editorType??"fieldLink",formatter:e.formatter??(r=>{const i=k(t.table);return z(i,r.value).map(o=>String(o[i.primaryField]??"")).join(", ")}),valueParser:e.valueParser??Ot(t),groupValue:e.groupValue??(r=>it(t.table,r)),groupCopies:!0}),cell:Le},{id:"lookup",get label(){return l("fields.typeLookup")},get description(){return l("fields.typeLookupDescription")},icon:s.lookup,group:"relation",width:180,properties:[X,ge],fill:(e,t,r)=>{const i=J(t,r),o=n=>{const a=Me(i,t.field);return String(a?a({value:n})??"":n)};return{...e,...m(e),fieldSource:()=>i?.table?.fields?.find(n=>n.field===String(t.field)),fieldFn:n=>{if(!i)return[];const a=$(i.table,String(t.field)),p=i.stored;return p?p.records.allLinkedTo(p.field,String(n?.id??"")).map(a):i.rowsOf(n).map(a)},formatter:e.formatter??(n=>Array.isArray(n.value)?n.value.filter(a=>a!=null&&a!=="").map(o).join(", "):n.value==null?"":o(n.value))}}},{id:"rollup",get label(){return l("fields.typeRollup")},get description(){return l("fields.typeRollupDescription")},icon:s.rollup,group:"relation",width:140,defaults:{aggregation:"SUM"},properties:[X,ge,{key:"aggregation",get label(){return l("fields.propAggregation")},kind:"choice",choices:Object.keys(U).map(e=>({value:e,label:e}))},W(K(0,8),e=>["SUM","AVERAGE","MIN","MAX"].includes(e.aggregation))],fill:(e,t,r)=>{const i=J(t,r),o=U[String(t.aggregation)]??U.SUM,n=["SUM","AVERAGE","MIN","MAX","COUNT","COUNTA","COUNTALL"].includes(String(t.aggregation)),a=["SUM","AVERAGE","MIN","MAX"].includes(String(t.aggregation)),p=f=>{const d=a?Me(i,t.field,t.precision):void 0;return d?String(d({value:f})??""):B(f,{precision:ye(t,0)})};return{...e,...m(e),...n?{cellDataType:e.cellDataType??"number"}:{},align:e.align??(n?"right":void 0),fieldSource:()=>i?.table?.fields?.find(f=>f.field===String(t.field)),fieldFn:f=>{if(!i)return null;const d=$(i.table,String(t.field)),g=i.stored;if(g){const S=String(f?.id??""),c=Ut[String(t.aggregation)];return c?g.records.total(g.field,S,String(t.field),c)??null:t.aggregation==="COUNTA"||t.aggregation==="COUNTALL"?g.records.total(g.field,S)??null:o(g.records.allLinkedTo(g.field,S).map(d))}return o(i.rowsOf(f).map(d))},formatter:e.formatter??(f=>{const d=n?E(f.value):typeof f.value=="number"?f.value:null;return d==null?String(f.value??""):p(d)})}}},{id:"count",get label(){return l("fields.typeCount")},get description(){return l("fields.typeCountDescription")},icon:s.count,group:"relation",width:90,properties:[X],fill:(e,t,r)=>{const i=J(t,r);return{...e,...m(e),cellDataType:e.cellDataType??"number",formatter:o=>o.value==null?"":Number(o.value).toLocaleString(),fieldFn:o=>{if(!i)return 0;const n=i.stored;return n?n.records.total(n.field,String(o?.id??""))??null:i.rowsOf(o).length}}}},ut];
1
+ import{fillFieldColumn as O}from"./registry.svelte.js";import Ae from"./RatingCell.svelte";import N from"./LinkCell.svelte";import Ve from"./AttachmentCell.svelte";import Fe from"./CheckboxCell.svelte";import re from"./PercentCell.svelte";import B from"./UserCell.svelte";import Ie from"./ButtonCell.svelte";import Le from"./BarcodeCell.svelte";import Oe from"./LinkedRecordsCell.svelte";import Ne from"./RichTextCell.svelte";import Be from"./RichHtmlCell.svelte";import{richPlain as A}from"./rich-html.js";import{toRichHtml as Re}from"./rich-html-write.js";import le from"./SelectCell.svelte";import Ee from"./ChecklistCell.svelte";import He from"./ColorCell.svelte";import{attachmentsText as Ue,parseAttachments as _e}from"./attachments.js";import{dateEditTokens as ze,dateFromParts as R,exactNumber as 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];
@@ -0,0 +1,63 @@
1
+ import type { BaseTable } from './base-tables.js';
2
+ import { type BaseAutomation } from './automations.svelte.js';
3
+ import { type ButtonAction } from './button.js';
4
+ import type { FieldFilter } from './filter-model.js';
5
+ type Row = Record<string, unknown>;
6
+ /** A Button field's own settings (`fieldProps`). */
7
+ export type ButtonProps = {
8
+ label?: string;
9
+ color?: string;
10
+ action?: ButtonAction;
11
+ url?: string;
12
+ /** `update`: field id -> value, written as an automation's "Update the record" writes them (`me` is the person pressing). */
13
+ values?: Record<string, unknown>;
14
+ /** `update`: the label once the record holds the values (the button is then done). */
15
+ doneLabel?: string;
16
+ /** `template`: the record template whose values fill the empty fields. */
17
+ template?: string;
18
+ /** `recordAction`: the app's record action, by id. */
19
+ recordAction?: string;
20
+ /** `copy`: the text, `{Field name}` tokens filled in; starting with `=` it is a formula. */
21
+ copy?: string;
22
+ /** Only records that match can press it. */
23
+ when?: FieldFilter;
24
+ /** Only these can press it: user ids, and `field:<field>` for whoever a person field of the record names. */
25
+ who?: string[];
26
+ /** Ask before it runs, with this question. */
27
+ ask?: boolean;
28
+ askText?: string;
29
+ };
30
+ export type ButtonState = {
31
+ /** It cannot be pressed on this record. */
32
+ disabled: boolean;
33
+ /** A change the record already holds: shown with a check and `label`. */
34
+ done: boolean;
35
+ /** The label to show (the done label once it is done). */
36
+ label?: string;
37
+ /** Why it cannot be pressed, for its tooltip. */
38
+ reason?: string;
39
+ };
40
+ export type ButtonHost = {
41
+ state(tableId: string | undefined, columnId: string, row: Row, ctrl: any): ButtonState;
42
+ press(tableId: string | undefined, columnId: string, row: Row, rowId: string, ctrl: any, api: any): Promise<void>;
43
+ };
44
+ export type ButtonHostDeps = {
45
+ tableOf: (id: string) => BaseTable | undefined;
46
+ tables: () => BaseTable[];
47
+ /** A shared base: nobody changes records from it. */
48
+ locked: () => boolean;
49
+ /** The automations "When a button is pressed" on this one, as a handler; null for none. */
50
+ automations: (tableId: string, columnId: string) => ((row: Row) => void) | null;
51
+ /** Run an automation now on a record (the runner's `runNow`). */
52
+ runNow: (a: BaseAutomation, tableId: string, recordId: string) => Promise<void>;
53
+ confirm: (q: {
54
+ title: string;
55
+ body: string;
56
+ yes: string;
57
+ }) => Promise<boolean>;
58
+ /** The writes under way have landed: an automation run on the server reads the record as the button left it. */
59
+ settled?: () => Promise<unknown>;
60
+ now?: () => Date;
61
+ };
62
+ export declare function createButtonHost(deps: ButtonHostDeps): ButtonHost;
63
+ export {};
@@ -0,0 +1 @@
1
+ import{nextGroupId as G,pushHistory as H,toast as T}from"@svgrid/grid";import{fieldValueFrom as M,matches as V,tableFields as R}from"./automations.svelte.js";import{buttonAction as j,CHANGING_ACTIONS as z,copyButtonText as J,openButtonLink as U,safeButtonLink as W}from"./button.js";import{gridPermissions as Y}from"./base-permissions.js";import{fieldPropsOf as D,originalColumn as q,ruleFieldNames as K}from"./registry.svelte.js";import{openRecord as Q}from"./editor-request.svelte.js";import{askDeleteRecord as X}from"./record-delete.svelte.js";import{recordMenu as Z}from"./record-menu.js";import{recordActionsFor as E}from"./record-actions.js";import{findFieldUser as I,getCurrentUser as S}from"./sources.svelte.js";import{canEditField as ee,canPickChoice as te,protectionText as ne}from"./field-access.svelte.js";import{isFieldToken as ie,ruleNames as L,tokenField as P}from"./people-rule.js";import{bm as c}from"./messages.svelte.js";function oe(t){const b=t?.props;return b?.baseReadOnly===!0?{canEdit:!1,canCreate:!1,canDelete:!1,canEditSchema:!1,canEditViews:!1,canComment:!1}:b?.basePermissions??Y(t)}const _=(t,b)=>JSON.stringify(t??null)===JSON.stringify(b??null),B=t=>t==null||t===""||t===!1||Array.isArray(t)&&t.length===0,se=t=>typeof t=="string"&&/^\s*(today|now)\s*([+-]\s*\d+)?\s*$|^\s*me\s*$/i.test(t);function ae(t,b){return b.link?!1:b.moving?!B(t[b.field]):_(t[b.field],b.value)}function re(t,b){const v=S(),A=R(t),g={};for(const[N,k]of Object.entries(b)){const x=A.get(N);g[N]=x?.fieldType==="user"&&typeof k=="string"&&/^\s*me\s*$/i.test(k)?v?.id??"":k}return g}function le(t,b){const v=[...R(t).values()],A=b.map(g=>{if(!ie(g))return I(g)?.name??g;const N=v.find(k=>k.field===P(g));return c("fields.protectedWhoeverIn",{field:N?.header??P(g)})});return A.length?A.join(", "):c("record.nobody")}export function createButtonHost(t){const b=t.now??(()=>new Date),v=(f,l)=>{const e=f.columns.find(d=>String(d.id??d.field)===l);return e&&e.fieldType==="button"?D(e):null},A=(f,l)=>R(f).get(l)?.def,g=(f,l,e)=>W(String(A(f,l)?.__buttonLink?.(e)??"")),N=(f,l,e)=>String(A(f,l)?.__buttonCopy?.(e)??"");function k(f,l,e,d){const n=new Map,s=R(f),o=e==="update"?l.values??{}:e==="template"?f.recordTemplates?.find(a=>a.id===l.template)?.values??{}:{},m=re(f,o),h={tables:t.tables(),from:f,record:d,now:b()};for(const[a,y]of Object.entries(m)){const r=s.get(a);!r||r.def.editable===!1||e==="template"&&!B(d[r.field])||n.set(a,{field:r.field,value:M(f,r.def,y,h),spec:y,link:r.fieldType==="link",moving:se(o[a])})}return n}function x(f,l,e,d){const n=f?t.tableOf(f):void 0,s=n?v(n,l):null;if(!n||!s)return{disabled:!0,done:!1};const o=j(s),m=oe(d),h=!t.locked()&&!!t.automations(n.id,l),a=r=>({disabled:!0,done:!1,reason:r}),y={disabled:!0,done:!0,label:s.doneLabel?.trim()||void 0};if(o==="update"){const r=k(n,s,o,e);if(!r.size)return a(c("fields.buttonNoValues"));if([...r.values()].every(i=>ae(e,i)))return y}if(o==="template"){if(!n.recordTemplates?.some(r=>r.id===s.template))return a(c("fields.buttonNoTemplate"));if(!k(n,s,o,e).size)return y}if(s.when?.conditions?.length&&!V(n,s.when,e))return a(c("fields.buttonNotNow"));if(Array.isArray(s.who)&&!L(s.who,S()?.id,e))return a(c("fields.buttonOnlyWho",{names:le(n,s.who)}));if(z.has(o)&&(t.locked()||!m.canEdit))return a(c("fields.buttonReadOnly"));if(o==="update"||o==="template"){const r=R(n);for(const[i,p]of k(n,s,o,e)){const u=r.get(i);if(!u)continue;const O=q(u.def),C=D(O);if(!ee(O,C,e)||!(Array.isArray(p.value)?p.value:[p.value]).every(F=>F==null||F===""||te(O,F,e,C)))return a(ne(O,C,K(u.def))??c("fields.protectedNotYou"))}}switch(o){case"link":return g(n,l,e)||h?{disabled:!1,done:!1}:a(c("fields.buttonNoLink"));case"copy":return N(n,l,e)?{disabled:!1,done:!1}:a(c("fields.buttonNoText"));case"automation":return h?{disabled:!1,done:!1}:a(c("fields.buttonNoAutomation"));case"recordAction":return E(n.id,{rowId:"",row:e}).some(r=>r.id===s.recordAction)||E(n.id).some(r=>r.id===s.recordAction)?{disabled:!1,done:!1}:a(c("fields.buttonNoRecordAction"));case"duplicate":return m.canCreate?{disabled:!1,done:!1}:a(c("fields.buttonReadOnly"));case"delete":return m.canDelete&&(!m.deleters||L(m.deleters,S()?.id,e))?{disabled:!1,done:!1}:a(c("fields.buttonReadOnly"));default:return{disabled:!1,done:!1}}}async function $(f,l,e,d,n,s){const o=s?.allRows?.findIndex(i=>i.id===n)??-1,m=[...e.values()].some(i=>i.link);if(o<0||m||!s?.editingEnabled||typeof s?.writeCellsRaw!="function"){const i=Object.fromEntries([...e.entries()].map(([u,O])=>[u,O.spec])),p={id:`button-${n}`,name:l,enabled:!0,trigger:{type:"recordCreated"},actions:[{type:"updateRecord",values:i}]};return await t.runNow(p,f.id,n),{...d,...Object.fromEntries([...e.values()].filter(u=>!u.link).map(u=>[u.field,u.value]))}}const h=s.allColumns,a=[],y=[];let r=0;for(const[i,p]of e){const u=h.findIndex(C=>C.id===i),O=d[p.field];if(!_(O,p.value)){if(u<0||s.isCellEditableAt?.(o,u)===!1){r+=1;continue}a.push({rowIndex:o,columnId:i,value:p.value}),y.push({rowId:n,columnId:i,field:p.field,before:O,after:p.value})}}return r&&T.warning(c("fields.buttonSomeRefused")),a.length?(s.writeCellsRaw(a),H(s,y,G()),{...d,...Object.fromEntries(y.map(i=>[i.field,i.after]))}):d}async function w(f,l,e,d,n,s){const o=f?t.tableOf(f):void 0,m=o?v(o,l):null;if(!o||!m||x(f,l,e,n).disabled)return;const h=j(m),a=m.label?.trim()||c("record.buttonOpen");if(m.ask&&h!=="delete"&&!await t.confirm({title:a,body:m.askText?.trim()||c("fields.buttonAskDefault"),yes:a}))return;const y=t.locked()?null:t.automations(o.id,l);let r=e;try{switch(h){case"link":{const i=g(o,l,e);i&&U(i);break}case"copy":{await J(N(o,l,e))?T.success(c("fields.buttonCopied")):T.error(c("fields.buttonCopyFailed"));break}case"update":case"template":r=await $(o,a,k(o,m,h,e),e,d,n);break;case"recordAction":{[...E(o.id,{rowId:d,row:e}),...E(o.id)].find(p=>p.id===m.recordAction)?.run({tableId:o.id,rowId:d,row:e});break}case"open":Q({ctrl:n,rowId:d});break;case"duplicate":{const i=Z(()=>s,()=>n).find(u=>typeof u=="object"&&u.key==="duplicate"),p=n?.allRows?.findIndex(u=>u.id===d)??-1;i?.action?.({rowIndex:p,colIndex:-1,columnId:l,rowId:d,row:n?.allRows?.[p]?.original??e,card:p<0});break}case"delete":X({ctrl:n,api:s,row:n?.allRows?.find?.(i=>i.id===d)?.original??e});return;case"automation":break}}catch(i){T.error(i instanceof Error?i.message:String(i));return}y&&(r!==e&&await t.settled?.().catch(()=>{}),y(r))}return{state:x,press:w}}