@uibot/renderer-react 0.0.0-stage → 0.2.0

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 (81) hide show
  1. package/dist/HtmlSourceEditor.d.ts +60 -0
  2. package/dist/collection-activity.d.ts +12 -0
  3. package/dist/collection-ai.d.ts +17 -0
  4. package/dist/collection-application.d.ts +5 -0
  5. package/dist/collection-application.js +25 -0
  6. package/dist/collection-approval.d.ts +7 -0
  7. package/dist/collection-attachments.d.ts +10 -0
  8. package/dist/collection-automation.d.ts +10 -0
  9. package/dist/collection-calendar-view.d.ts +2 -0
  10. package/dist/collection-computed.d.ts +4 -0
  11. package/dist/collection-conversion.d.ts +6 -0
  12. package/dist/collection-editors.d.ts +40 -0
  13. package/dist/collection-editors.js +10 -0
  14. package/dist/collection-form-view.d.ts +2 -0
  15. package/dist/collection-formula/evaluate.d.ts +18 -0
  16. package/dist/collection-formula/index.d.ts +1 -0
  17. package/dist/collection-gallery-view.d.ts +2 -0
  18. package/dist/collection-grid/cell-display.d.ts +24 -0
  19. package/dist/collection-grid/cells.d.ts +29 -0
  20. package/dist/collection-grid/column-color.d.ts +5 -0
  21. package/dist/collection-grid/date-value.d.ts +13 -0
  22. package/dist/collection-grid/features.d.ts +76 -0
  23. package/dist/collection-grid/field-format.d.ts +17 -0
  24. package/dist/collection-grid/fill.d.ts +10 -0
  25. package/dist/collection-grid/filter-labels.d.ts +6 -0
  26. package/dist/collection-grid/footer-aggregate.d.ts +6 -0
  27. package/dist/collection-grid/footer-stats.d.ts +5 -0
  28. package/dist/collection-grid/grouping.d.ts +51 -0
  29. package/dist/collection-grid/index.d.ts +9 -0
  30. package/dist/collection-grid/paged-field-input.d.ts +22 -0
  31. package/dist/collection-grid/paged-locale.d.ts +3 -0
  32. package/dist/collection-grid/paged-model.d.ts +25 -0
  33. package/dist/collection-grid/relation-editor.d.ts +14 -0
  34. package/dist/collection-grid/relation-options.d.ts +4 -0
  35. package/dist/collection-grid/selection.d.ts +4 -0
  36. package/dist/collection-interaction-state.d.ts +26 -0
  37. package/dist/collection-kanban-view.d.ts +2 -0
  38. package/dist/collection-live-changes.d.ts +8 -0
  39. package/dist/collection-relations.d.ts +20 -0
  40. package/dist/collection-sharing.d.ts +10 -0
  41. package/dist/collection-table-view.d.ts +2 -0
  42. package/dist/collection-transfer.d.ts +12 -0
  43. package/dist/collection-ui.d.ts +152 -0
  44. package/dist/collection-views/aggregate.d.ts +39 -0
  45. package/dist/collection-views/ai-fill-drawer.d.ts +28 -0
  46. package/dist/collection-views/ai-fill-model.d.ts +35 -0
  47. package/dist/collection-views/board.d.ts +2 -0
  48. package/dist/collection-views/calendar.d.ts +4 -0
  49. package/dist/collection-views/field-config.d.ts +16 -0
  50. package/dist/collection-views/filter-builder.d.ts +23 -0
  51. package/dist/collection-views/gallery.d.ts +2 -0
  52. package/dist/collection-views/icons.d.ts +43 -0
  53. package/dist/collection-views/menu.d.ts +16 -0
  54. package/dist/collection-views/model.d.ts +22 -0
  55. package/dist/collection-views/record-creator.d.ts +31 -0
  56. package/dist/collection-views/schema-editor.d.ts +38 -0
  57. package/dist/collection-views/schema-field-settings.d.ts +22 -0
  58. package/dist/collection-views/schema-styles.d.ts +4 -0
  59. package/dist/collection-views/shared.d.ts +110 -0
  60. package/dist/collection-views/table-nav.d.ts +52 -0
  61. package/dist/collection-views/toolbar-popover.d.ts +24 -0
  62. package/dist/collection-views/ui.d.ts +45 -0
  63. package/dist/collection-views/view-settings-sections.d.ts +39 -0
  64. package/dist/collection-views/view-tabs.d.ts +35 -0
  65. package/dist/collection-views.d.ts +35 -0
  66. package/dist/collection-views.js +10 -0
  67. package/dist/collection-workspace.d.ts +128 -0
  68. package/dist/collection-workspace.js +26 -0
  69. package/dist/define-component.d.ts +35 -0
  70. package/dist/document-collection.d.ts +30 -0
  71. package/dist/document-view.d.ts +1 -0
  72. package/dist/html-source-editor.css +84 -0
  73. package/dist/index.d.ts +121 -0
  74. package/dist/index.js +25 -0
  75. package/dist/live-renderer.d.ts +60 -0
  76. package/dist/paged-collection-grid.d.ts +95 -0
  77. package/dist/paged-collection-grid.js +25 -0
  78. package/dist/paged-collection-views.d.ts +15 -0
  79. package/dist/renderer.d.ts +20 -0
  80. package/package.json +69 -4
  81. package/README.md +0 -3
@@ -0,0 +1,25 @@
1
+ import{createContext as Ei,useCallback as Di,useContext as Ti,useLayoutEffect as Yn,useMemo as Fi,useRef as tr,useState as Ni}from"react";var Mi=Ei(void 0);function $t(e,t={}){let n=Ti(Mi),o=tr({}),{dirty:i,busy:r}=e,{onDirtyChange:a,onBusyChange:d}=t;Yn(()=>{n?.(o.current,{dirty:i,busy:r}),a?.(i),d?.(r)},[n,i,r,a,d]),Yn(()=>()=>{n?.(o.current),a?.(!1),d?.(!1)},[n,a,d])}function kl(){let e=tr(new Map),[t,n]=Ni({dirty:!1,busy:!1}),o=Di((i,r)=>{if(r)e.current.set(i,r);else e.current.delete(i);let a=[...e.current.values()],d=a.some((p)=>p.dirty),s=a.some((p)=>p.busy);n((p)=>p.dirty===d&&p.busy===s?p:{dirty:d,busy:s})},[]);return{...t,report:o}}function nr(e,t){let n=Fi(()=>({active:!0,client:e,id:t}),[e,t]);return Yn(()=>(n.active=!0,()=>{n.active=!1}),[n]),n}import{useEffect as rt,useLayoutEffect as il,useMemo as nt,useRef as ot,useState as Me}from"react";import{DndContext as al,PointerSensor as ll,useDraggable as sl,useSensor as dl,useSensors as cl}from"@dnd-kit/core";import{defaultRangeExtractor as ul,useVirtualizer as yi}from"@tanstack/react-virtual";function Pl(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var yn=["blue","green","red","orange","gray","teal","purple"];function Oi(e){if(typeof e==="number"&&Number.isFinite(e))return e;if(typeof e==="string"&&e.trim()!==""){let t=Number(e);return Number.isFinite(t)?t:null}return null}function or(e,t,n){if(!t?.length)return[];return t.map((o)=>{if(o.fn==="count")return{fieldId:o.fieldId,fn:"count",value:e.length};let i=n.find((d)=>d.id===o.fieldId),a=i?.type==="number"||i?.type==="rating"||i?.type==="autoNumber"?e.reduce((d,s)=>d+(Oi(s.values[o.fieldId])??0),0):0;return{fieldId:o.fieldId,fn:"sum",value:a}})}function rr(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function Li(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function Vi(e,t){let n=e.values[t.fieldId];if(t.operator==="isEmpty")return n==null||n==="";if(["gt","gte","lt","lte"].includes(t.operator)){if(typeof n!=="number"||!Number.isFinite(n)||typeof t.value!=="number"||!Number.isFinite(t.value))return!1;if(t.operator==="gt")return n>t.value;if(t.operator==="gte")return n>=t.value;if(t.operator==="lt")return n<t.value;return n<=t.value}if(t.operator==="contains")return String(n??"").toLowerCase().includes(String(t.value??"").toLowerCase());if(t.operator==="isNot")return n!==t.value;return n===t.value}function ir(e,t){if(!t)return!0;if(rr(t)){let n=t.filterSet.map((o)=>rr(o)?ir(e,o):Li(o)?Vi(e,o):!1);return t.conjunction==="or"?n.some(Boolean):n.every(Boolean)}return Object.entries(t).every(([n,o])=>{if(n==="conjunction"||n==="filterSet")return!0;return e.values[n]===o})}function ar(e,t,n,o){let i=e.views.find((x)=>x.id===n)??e.views[0];if(!i)return{view:{id:n,name:n,kind:"table"},columns:e.fields,rows:[...t]};let r=[...t];if(i.filter)r=r.filter((x)=>ir(x,i.filter));if(i.sort?.length)r.sort((x,C)=>{for(let v of i.sort??[]){let P=x.values[v.fieldId],m=C.values[v.fieldId];if(P===m)continue;if(P==null)return 1;if(m==null)return-1;let w=e.fields.find((U)=>U.id===v.fieldId)?.type,y=(U)=>{if(["number","rating","autoNumber"].includes(w??"")&&typeof U==="number")return U;if(["date","createdTime","lastModifiedTime"].includes(w??"")){let E=Date.parse(String(U));if(Number.isFinite(E))return E}return String(U)},S=y(P),N=y(m);if(S===N)continue;let A=S<N?-1:1;return v.direction==="desc"?-A:A}return x.id<C.id?-1:x.id===C.id?0:1});let a=i.projection?.length?e.fields.filter((x)=>i.projection?.includes(x.id)):e.fields,d=o?.search?.trim().toLowerCase();if(d)r=r.filter((x)=>a.some((C)=>String(x.values[C.id]??"").toLowerCase().includes(d)));let s=or(r,i.aggregates,e.fields),p=i.group?.fieldId;if(!p)return{view:i,columns:a,rows:r,...s.length?{aggregates:s}:{}};let c=[],u=new Map;for(let x of r){let C=String(x.values[p]??"");if(!u.has(C))u.set(C,[]),c.push(C);u.get(C)?.push(x)}let g=c.map((x)=>{let C=u.get(x)??[];return{key:x,fieldId:p,rows:C,aggregates:or(C,i.aggregates,e.fields)}});return{view:i,columns:a,rows:r,groups:g,...s.length?{aggregates:s}:{}}}var Bi=500;function Ne(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function Dt(e){if(e.type==="lookup"||e.type==="json"||e.type==="blob"||e.type==="relation"||e.type==="linkedRecord")return!1;if(e.type==="formula"||e.type==="rollup")return e.resultType==="text"||e.resultType==="number"||e.resultType==="date";return!0}var Ml=["short","medium","tall","extra"];function Ol(e,t){return t.map((n)=>{let o={},i={};for(let r of e.groupBy){let a=n[r];if(!(r in n)||a!==null&&typeof a!=="string"&&typeof a!=="number"&&typeof a!=="boolean")throw Error(`Invalid aggregate group ${r}.`);o[r]=a}for(let{as:r,fn:a}of e.aggregates){let d=n[r];if(!(r in n)||d!==null&&!(typeof d==="number"&&Number.isFinite(d))&&!((a==="min"||a==="max")&&typeof d==="string"&&Number.isFinite(Date.parse(d))))throw Error(`Invalid aggregate value ${r}.`);i[r]=d}return{groups:o,values:i}})}var Ui=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,_i=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function bn(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function je(e,t){return{code:e,...t}}function qi(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function Jn(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function Cn(e,t){if(t.aggregates.length===0)return je("empty");if(t.aggregates.length>8||t.groupBy.length>3)return je("too_many");let n=new Set;for(let i of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(i.fn))return je("function");if(!Ui.test(i.as)||n.has(i.as)||t.groupBy.includes(i.as))return je("alias",{alias:i.as,...i.fieldId!==void 0?{fieldId:i.fieldId}:{}});if(n.add(i.as),i.fn==="count"&&i.fieldId===void 0)continue;let r=e.fields.find((a)=>a.id===i.fieldId);if(!r)return je(i.fn==="sum"?"sum_field":"unknown_field",{alias:i.as,...i.fieldId!==void 0?{fieldId:i.fieldId}:{}});if(i.fn==="sum"&&!Jn(r))return je("sum_field",{fieldId:r.id,alias:i.as});if(i.fn==="avg"&&!Jn(r))return je("numeric_field",{fieldId:r.id,alias:i.as});if((i.fn==="min"||i.fn==="max")&&!Jn(r)&&r.type!=="date"&&!((r.type==="formula"||r.type==="rollup")&&r.resultType==="date"))return je("extrema_field",{fieldId:r.id,alias:i.as});if((i.fn==="filled"||i.fn==="empty")&&!Dt(r))return je("queryable_field",{fieldId:r.id,alias:i.as});if(i.fn==="count"&&!Dt(r))return je("count_field",{fieldId:r.id,alias:i.as})}let o=new Set;for(let i of t.groupBy){if(o.has(i))return je("duplicate_group",{fieldId:i});o.add(i);let r=e.fields.find((a)=>a.id===i);if(!r)return je("unknown_field",{fieldId:i});if(!_i.has(r.type)&&!qi(r))return je("not_groupable",{fieldId:i})}return null}var lr=(e)=>String(e).padStart(2,"0");function lt(e,t){let n=new Intl.DateTimeFormat("en-CA",{...t?{timeZone:t}:{},year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(e),o=(i)=>Number(n.find((r)=>r.type===i)?.value??0);return{year:o("year"),month:o("month"),day:o("day"),hour:o("hour"),minute:o("minute"),second:o("second")}}function kt(e,t){let n=Date.UTC(e.year,e.month-1,e.day,e.hour??0,e.minute??0,e.second??0);if(!t)return new Date(e.year,e.month-1,e.day,e.hour??0,e.minute??0,e.second??0);let o=n;for(let i=0;i<2;i++){let r=lt(new Date(o),t),a=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second);o+=n-a}return new Date(o)}function hn(e,t){let n=lt(e,t??"UTC");return`${n.year}-${lr(n.month)}-${lr(n.day)}`}function sr(e,t=new Date,n){let o={};for(let i of e){let r=i.defaultValue;if(!r)continue;if(r.kind==="value")o[i.id]=Array.isArray(r.value)?[...r.value]:r.value;else if(i.type==="date"){let a=i.formatting;if(a&&"time"in a&&a.time==="none"){let d=lt(t,n);o[i.id]=`${d.year}-${String(d.month).padStart(2,"0")}-${String(d.day).padStart(2,"0")}`}else o[i.id]=t.toISOString()}}return o}var $i=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],zi=new Set(["pastDays","nextDays","daysAgo","daysFromNow"]),dr={text:["is","isNot","contains","notContains","isEmpty","isNotEmpty"],number:["is","isNot","gt","gte","lt","lte","isEmpty","isNotEmpty"],checkbox:["is","isNot","isEmpty","isNotEmpty"],date:["is","isNot","before","after","onOrBefore","onOrAfter","isEmpty","isNotEmpty"],singleSelect:["is","isNot","isEmpty","isNotEmpty"],multipleSelect:["is","isNot","contains","notContains","isEmpty","isNotEmpty"],relation:["is","isNot","isEmpty","isNotEmpty"]},ji=new Set(["isEmpty","isNotEmpty"]);function cr(e){switch(e.type){case"singleLineText":case"longText":return"text";case"number":return"number";case"checkbox":return"checkbox";case"date":return"date";case"singleSelect":return"singleSelect";case"multipleSelect":return"multipleSelect";case"relation":return"relation";case"formula":case"rollup":return e.resultType==="text"?"text":e.resultType==="number"?"number":e.resultType==="date"?"date":null;default:return null}}function $l(e){let t=cr(e);return t?dr[t]:[]}var Qn=/^\d{4}-\d{2}-\d{2}$/,Hi=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function Ki(e){if(!Hi(e))return!1;let t=e.mode;if(!$i.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&&Qn.test(e.date);if(t==="dateRange")return typeof e.date==="string"&&Qn.test(e.date)&&typeof e.to==="string"&&Qn.test(e.to)&&e.date<=e.to;if(zi.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function zl(e,t){if(!e)return"unknown field";let n=cr(e),o=t.operator==="contains"&&(n==="number"||n==="checkbox"||n==="date"||n==="singleSelect");if(!n||!(dr[n].includes(t.operator)||o))return"operator not allowed";if(ji.has(t.operator))return null;let i=t.value;if(o)return n==="number"?typeof i==="number"&&Number.isFinite(i)?null:"number required":n==="checkbox"?typeof i==="boolean"?null:"boolean required":typeof i==="string"?null:"text required";switch(n){case"text":return typeof i==="string"?null:"text value required";case"number":return typeof i==="number"&&Number.isFinite(i)?null:"number required";case"checkbox":return typeof i==="boolean"?null:"boolean required";case"singleSelect":return typeof i==="string"?null:"option required";case"relation":return typeof i==="string"&&i!==""?null:"record required";case"multipleSelect":return typeof i==="string"||Array.isArray(i)&&i.every((r)=>typeof r==="string")?null:"options required";case"date":return Ki(i)||typeof i==="string"&&Number.isFinite(Date.parse(i))?null:"date required"}}var Gi={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},ps=Array.from(new Set(Object.values(Gi).flat()));var fs=Object.freeze([Object.freeze({name:"manifest",summary:"Describe query operations and list the derived resource index.",positionals:Object.freeze([]),options:Object.freeze([])}),Object.freeze({name:"search",summary:"Search resources with deterministic bilingual ranking and reasons.",positionals:Object.freeze([Object.freeze({name:"text",property:"text",type:"string",required:!1})]),options:Object.freeze([Object.freeze({name:"kind",property:"kinds",type:"resource-kind",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"tag",property:"tags",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"category",property:"categories",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"capability",property:"capabilities",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"maturity",property:"maturities",type:"resource-maturity",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"limit",property:"limit",type:"positive-integer"})])}),Object.freeze({name:"get",summary:"Resolve one canonical resource id or unambiguous alias.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([])}),Object.freeze({name:"build",summary:"Plan dependency closure and gaps without writing or installing.",positionals:Object.freeze([Object.freeze({name:"root",property:"roots",type:"string",required:!0,variadic:!0})]),options:Object.freeze([])})]);function Wi(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function vs(e,t){if(t===e.draft)return e;return{...e,draft:t}}function Yi(e){return e.draft!==e.savedContent}function xs(e,t){let n=t.replaceDraft===!0||e.draft===t.submittedContent;return{expectedRevisionId:t.savedRevisionId,savedContent:t.savedContent,draft:n?t.savedContent:e.draft,format:t.format??e.format,schemaVersion:t.schemaVersion??e.schemaVersion}}function ks(e,t){if(Yi(e))return e;let n=Wi(t);if(e.expectedRevisionId===n.expectedRevisionId&&e.savedContent===n.savedContent&&e.draft===n.draft&&e.format===n.format&&e.schemaVersion===n.schemaVersion)return e;return n}var mt=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),Tt=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),Ft=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,ur=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,vn=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),pr=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every(vn)&&new Set(e).size===e.length;function Ji(e){if(!mt(e)||!Tt(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!vn(e.id)||!Ft(e.name,200)||!["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect","linkedRecord","lookup","formula","rollup"].includes(String(e.type))||e.required!==void 0&&typeof e.required!=="boolean")return!1;if(e.options!==void 0&&(!Array.isArray(e.options)||e.options.length>100||e.options.some((t)=>!mt(t)||!Tt(t,["id","name"])||!vn(t.id)||!Ft(t.name,200))||new Set(e.options.map((t)=>t.id)).size!==e.options.length))return!1;if(e.options!==void 0&&!["singleSelect","multipleSelect"].includes(String(e.type)))return!1;for(let[t,n,o]of[["linkedRecord","link",["collectionId","displayFieldId"]],["lookup","lookup",["linkFieldId","targetFieldId"]],["formula","formula",["expression"]],["rollup","rollup",["linkFieldId","targetFieldId","function"]]]){let i=e[n];if(e.type===t!==(i!==void 0))return!1;if(i!==void 0&&(!mt(i)||!Tt(i,[...o])||o.some((r)=>!Ft(i[r],r==="expression"?2048:512))))return!1}return!0}function Ps(e){if(!mt(e)||!Tt(e,["id","collectionId","descriptor","view","uibotCommit","authorId","createdAt","digest"])||!/^[a-f0-9]{64}$/.test(String(e.id))||!/^[a-f0-9]{64}$/.test(String(e.digest))||!/^[a-f0-9]{40}$/.test(String(e.uibotCommit))||!Ft(e.collectionId,512)||!Ft(e.authorId,512)||typeof e.createdAt!=="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.createdAt)||!Number.isFinite(Date.parse(e.createdAt)))return!1;try{if(new TextEncoder().encode(JSON.stringify(e)).length>131072)return!1}catch{return!1}let{descriptor:t,view:n}=e;if(!mt(t)||!Tt(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!Ft(t.name,200)||!ur(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(Ji)||new Set(t.fields.map((r)=>r.id)).size!==t.fields.length)return!1;if(!mt(n)||!Tt(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!vn(n.id)||!Ft(n.name,200)||!ur(n.version)||!pr(n.columnOrder)||!pr(n.hiddenColumns)||!mt(n.columnWidths)||Object.values(n.columnWidths).some((r)=>typeof r!=="number"||!Number.isInteger(r)||r<72||r>800))return!1;let o=t.fields,i=(r)=>o.some((a)=>mt(a)&&a.id===r);if([...n.columnOrder,...n.hiddenColumns,...Object.keys(n.columnWidths)].some((r)=>!i(r)))return!1;if(n.type!==void 0&&!["grid","kanban","gallery","calendar","form"].includes(String(n.type)))return!1;if(n.type==="kanban"&&!t.fields.some((r)=>r.id===n.groupByFieldId&&["singleSelect","checkbox"].includes(r.type)))return!1;if(n.type==="calendar"&&!t.fields.some((r)=>r.id===n.dateFieldId&&r.type==="date"))return!1;if(n.search!==void 0&&(typeof n.search!=="string"||n.search.length>200))return!1;if(n.sort!==void 0&&(!Array.isArray(n.sort)||n.sort.length>4||n.sort.some((r)=>!mt(r)||!Tt(r,["fieldId","direction"])||!i(r.fieldId)||!["asc","desc"].includes(String(r.direction)))))return!1;return!0}var Xe=(e)=>String(e).padStart(2,"0"),Qi=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function st(e){let t=e.formatting;return Qi(e)&&t&&"date"in t?t:void 0}function tn(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function Xn(e){let t=st(e);return!t?"auto":t.time==="none"?"date":"datetime"}function Zn(e,t,n,o){switch(o){case"YYYY/MM/DD":return`${e}/${Xe(t)}/${Xe(n)}`;case"MM/DD/YYYY":return`${Xe(t)}/${Xe(n)}/${e}`;case"DD/MM/YYYY":return`${Xe(n)}/${Xe(t)}/${e}`;case"YYYY年M月D日":return`${e}年${t}月${n}日`;default:return`${e}-${Xe(t)}-${Xe(n)}`}}function nn(e,t){let n=e==null?"":String(e);if(!n)return"";let o=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n);if(t.time==="none"){if(o)return Zn(Number(o[1]),Number(o[2]),Number(o[3]),t.date);let d=new Date(n);if(!Number.isFinite(d.getTime()))return n;let s=lt(d,t.timeZone??"UTC");return Zn(s.year,s.month,s.day,t.date)}let i=o?kt({year:Number(o[1]),month:Number(o[2]),day:Number(o[3])},t.timeZone):new Date(n);if(!Number.isFinite(i.getTime()))return n;let r=lt(i,t.timeZone),a=Zn(r.year,r.month,r.day,t.date);if(t.time==="12h"){let d=r.hour%12||12;return`${a} ${d}:${Xe(r.minute)} ${r.hour<12?"AM":"PM"}`}return`${a} ${Xe(r.hour)}:${Xe(r.minute)}`}function on(e,t){if(e==null||e==="")return"";let n=typeof e==="number"?e:Number(e);if(!Number.isFinite(n))return String(e);let o=Math.min(8,Math.max(0,Math.trunc(t.precision)));return new Intl.NumberFormat(void 0,{style:t.kind==="decimal"?"decimal":t.kind,...t.kind==="currency"?{currency:t.currency||"CNY"}:{},minimumFractionDigits:o,maximumFractionDigits:o,useGrouping:t.grouping!==!1}).format(n)}function rn(e,t){let n=e?.findIndex((r)=>r.id===t)??-1,o=n>=0?e?.[n]?.color:void 0,i=yn.findIndex((r)=>r===o);return i>=0?i:n}var Zi={"AI fill":"AI 填充","All records in this view ({count})":"当前视图全部记录({count})","Generating batch {done} of {total}…":"正在生成第 {done}/{total} 批…","{count} records could not be processed: {reason}":"{count} 条记录处理失败:{reason}","Retry failed":"重试失败批次",Close:"关闭","Records in scope":"记录范围","Selected records ({count})":"已选记录({count})","Loaded records ({count})":"已载入记录({count})","Fields to fill":"要填充的字段",Instruction:"指令","Describe what to fill or change":"描述要填写或修改的内容","Fill empty cells":"补全空白","Fill the empty target cells using the other fields of the same record.":"根据同一条记录的其他字段,补全目标字段中的空白单元格。","Translate to English":"翻译成英文","Translate the target fields into English and keep proper nouns.":"把目标字段翻译成英文,专有名词保持原样。",Summarize:"生成摘要","Write a one-sentence summary of each record for the target fields.":"为每条记录在目标字段中写一句话摘要。",Classify:"自动归类","Pick the best matching option for each record from the allowed options.":"为每条记录从可选项中选择最匹配的一项。",Model:"模型",Suggestions:"建议","{count} suggested changes":"{count} 处建议修改","Select all":"全选","Select none":"全不选","No changes were suggested.":"没有需要修改的内容。","(empty)":"(空)","Generating suggestions…":"正在生成建议…",Stop:"停止","Apply {count} changes":"应用 {count} 处修改",Regenerate:"重新生成","Generate preview":"生成预览","Applied {count} AI changes":"已应用 {count} 处 AI 修改","AI changes undone":"已撤销 AI 修改",Undo:"撤销","Some records changed since the preview. Generate again to review the latest values.":"部分记录在预览后已被修改,请重新生成以查看最新内容。","Loaded records fallback: {value}":"已载入记录兜底:{value}","That summary function is not supported.":"不支持该汇总函数。","Average only a number field.":"只能对数字字段求平均值。","Minimum and maximum need a number or date field.":"最大值和最小值需要数字或日期字段。","Summarize a queryable field.":"请选择可查询字段汇总。","Select row":"选择行","Select all loaded records":"全选已载入记录","{count} selected":"已选择 {count} 条","Column color":"整列填色","Column color for {name}":"{name}整列填色","Column color {number}":"列色 {number}","No color":"无色","Fill selection":"拖拽填充","Fill at most 100 rows at once.":"一次最多 100 行","Filled {count} cells":"已填充 {count} 个单元格","Skipped {count} cells":"已跳过 {count} 个不可填充单元格","Table not found":"数据表不存在或不可访问","View not found":"视图不存在或不可访问","{count} records total":"共 {count} 条","Row height":"行高","Row height short":"紧凑","Row height medium":"中等","Row height tall":"较高","Row height extra":"超高","Sort {index}":"排序 {index}","Move sort {index} up":"上移排序 {index}","Move sort {index} down":"下移排序 {index}","Remove sort {index}":"删除排序 {index}","Add sort":"添加排序","Clear sort":"清除排序","Default order":"默认顺序",Match:"满足","all conditions":"全部条件","any condition":"任一条件","Filter conjunction":"条件关系","Condition {index}":"条件 {index}","Remove condition {index}":"删除条件 {index}","{count} grouped conditions are kept.":"另有 {count} 组嵌套条件保持不变。",Remove:"移除","Finish the highlighted condition to apply it.":"补全未完成的条件后才会生效。","Add condition":"添加条件","Add group":"添加条件组","Condition group {index}":"条件组 {index}","Remove group {index}":"删除条件组 {index}","Clear filter":"清除筛选","Filter value":"筛选值","Filter field":"筛选字段","Filter operator":"筛选条件","Date mode":"日期方式","From date":"起始日期","To date":"结束日期","Number of days":"天数","Choose option":"选择选项",Format:"格式","Format of field {name}":"字段{name}的格式","Defaults of field {name}":"字段{name}的默认值","Date format":"日期格式","Time format":"时间格式","Time zone":"时区","Viewer's time zone":"跟随查看者","No time (date only)":"不含时间(仅日期)","24-hour":"24 小时制","12-hour":"12 小时制",Preview:"预览","Default value":"默认值",Empty:"空","Current date and time":"当前日期和时间","Number style":"数字样式",Percent:"百分比",Currency:"货币","Decimal places":"小数位数","Thousands separator":"千分位分隔","Checked by default":"默认勾选","Default option {name}":"默认选中{name}","Colour of option {index}":"选项 {index} 的颜色","Colour blue":"蓝","Colour green":"绿","Colour red":"红","Colour orange":"橙","Colour gray":"灰","Colour teal":"青","Colour purple":"紫","Unsaved changes":"修改未保存","Your edit":"我的修改","Server value":"服务端当前值","Record ID":"记录 ID","Record ID {id}":"记录 ID {id}",Row:"序号","Generated automatically":"自动生成","{name} is auto-generated and cannot be edited.":"{name}由系统自动生成,不能手动修改。","Saving failed. Your edit has been kept.":"保存失败,修改已保留。",Saved:"已保存","Invalid value":"输入值无效","{name} is read-only; its original bytes are preserved.":"{name}为只读字段,原始文件内容保持不变。","{name} needs a server-provided option.":"{name}需要由服务端提供可选项。","{name} is read only.":"{name}为只读字段。","Use the {name} record picker.":"请使用{name}记录选择器。","{name} needs a number.":"{name}需要有效数字。","{name} needs valid JSON.":"{name}必须是有效 JSON。","{name} needs an integer.":"{name}必须是整数。","{name} needs true or false.":"{name}请选择是或否。","{name} needs a date.":"{name}需要有效日期。","{name} needs a valid calendar date.":"{name}需要有效日期。","{name} has no option '{option}'.":"{name}没有名为“{option}”的选项。","Paste is too large.":"粘贴内容过大。","Paste must fit within the loaded page and contain at most 100 rows.":"粘贴内容必须位于当前已加载页内,且最多包含 100 行。","Paste extends beyond the visible columns.":"粘贴内容超出可见列范围。","Row is not loaded.":"目标行尚未加载。","Unclosed quoted cell.":"粘贴内容中的引号没有闭合。","Invalid paste.":"粘贴内容无效。","Edit {name}":"编辑 {name}","{name} editor":"{name}编辑器","Sorting is unavailable for this field":"此字段暂不支持排序","Clear selection":"清空选择","{id} (unavailable)":"{id}(选项已移除)","Select at most 100 rows per delete.":"每次最多删除 100 条记录。","{total} records · {loaded} loaded":"共 {total} 条 · 已载入 {loaded} 条","Arrows · Shift select · Enter edit · Copy / paste":"方向键移动 · Shift 多选 · Enter 编辑 · 复制 / 粘贴","Arrows · Shift select · Copy":"方向键移动 · Shift 多选 · 复制","Delete selected rows":"删除所选记录","{name} records":"{name} 数据表","Resize {name}":"调整 {name} 列宽","Saving…":"保存中…","Save edit":"保存修改","Cancel edit":"取消修改","Confirm bulk change":"确认批量修改","Apply {count} row changes in one transaction?":"确认一次性提交 {count} 条记录的修改?","If any record changed or any value is invalid, all changes are rejected.":"如有记录版本冲突或输入值无效,整批修改将不提交。","Confirm changes":"确认修改","Cancel changes":"取消修改","Current server version {version}":"服务端当前版本 {version}","Retry against current version":"按当前版本重试","Saving failed. Your draft has been kept.":"保存失败,草稿已保留。","Choose a text, checkbox or single select grouping field.":"请选择文本、复选框或单选字段作为看板分组。",Ungrouped:"未分组","Invalid grouping value":"分组值无效","Move {name}":"移动 {name}","Retry change":"重试修改","{name} is required.":"请填写 {name}。","No changes":"没有修改","{name} record":"{name} 记录","No value":"未选择",Yes:"是",No:"否","Save record":"保存记录","Create record":"新建记录","Search {name}":"搜索 {name}","No relation":"未关联","More {name} options":"加载更多 {name} 选项","Relation options unavailable.":"关联选项加载失败,请重试。","Relation option provider unavailable.":"暂时无法选择关联记录。","Collection query failed. Retry to load records.":"记录加载失败,请重试。","Previous page":"上一页","Next page":"下一页","Page {page}":"第 {page} 页","Loading records…":"正在加载记录…","Retry query":"重新加载","Saving failed. Your change has been kept.":"保存失败,已保留当前修改。","{name} needs unique linked records.":"{name}需要不重复的关联记录。","Change a field before saving.":"请先修改字段再保存。","Close record":"关闭记录","Delete record":"删除记录","Confirm record deletion":"确认删除记录","Delete this record? Your unsaved changes will be discarded after deletion.":"确定删除此记录?删除后将丢弃尚未保存的修改。","Confirm deletion":"确认删除","Cancel deletion":"取消删除","Record creation requires editor permission.":"新建记录需要编辑权限。","Creating…":"正在创建…","Record created.":"记录已创建。","Record created. Add another below.":"记录已创建,可继续新增。","Show records":"查看记录","Pending record move":"待处理的记录移动","Moving record…":"正在移动记录…","The move has been kept for retry.":"已保留移动请求,可重试。","Retry move":"重试移动","Cancel move":"取消移动","Choose a single-select or boolean grouping field.":"请选择单选或复选框分组字段。","Lane {name}":"分组{name}","Open {name}":"打开{name}","Move to":"移动至","No records in this lane.":"此分组暂无记录。","No records match this view.":"此视图暂无匹配记录。",Unassigned:"未分组","Choose a valid month.":"请选择有效月份。","Invalid initial month. Showing the current UTC month.":"初始月份无效,已显示当前月份。","Choose a valid month between years 1 and 9998.":"请选择 1 至 9998 年之间的有效月份。","Invalid date":"日期无效","Choose a date field for this calendar.":"请为日历选择日期字段。","Previous month":"上个月","Next month":"下个月",Today:"今天","Calendar month":"日历月份",Month:"月份","{year}-{month}":"{year} 年 {month} 月",Sun:"周日",Mon:"周一",Tue:"周二",Wed:"周三",Thu:"周四",Fri:"周五",Sat:"周六","Day {day}":"日期 {day}","No dated records match this month.":"本月暂无匹配的日期记录。","Move {name} to date":"将 {name} 移动至日期",Move:"移动",Grid:"表格",Kanban:"看板",Gallery:"画廊",Calendar:"日历",Form:"表单","View type":"视图类型","Group by":"分组依据","Grid grouping field":"表格分组字段","No grouping":"不分组","Hide fields":"隐藏字段","Field menu {name}":"{name} 字段菜单","Edit field":"修改字段","Duplicate field":"复制字段","Hide field":"隐藏字段","Undo/redo recovery":"撤销/重做恢复","Retry undo/redo":"重试撤销/重做","Clear undo/redo history":"清除撤销/重做历史",Undone:"已撤销",Redone:"已重做","Duplicate {count} selected records":"复制所选 {count} 条记录","Add record below the table":"在表格末尾新增记录","Move to {name}":"移至 {name}","Delete this record?":"删除这条记录?","Filter by {name}":"按 {name} 筛选","Record details":"记录详情","Expand record":"展开记录","Select all rows":"全选记录",Summary:"统计","Auto summary":"自动计算","Footer record count":"{count} 条记录","No summary":"不统计","Footer count":"记录数","Footer filled":"已填写","Footer empty":"未填写","Footer sum":"求和","Footer avg":"平均值","Footer min":"最小值","Footer max":"最大值","Summaries cover the {count} loaded records.":"统计范围为已载入的 {count} 条记录。","Freeze up to this field":"冻结至此字段","Unfreeze columns":"取消冻结","Insert field left":"向左插入字段","Insert field right":"向右插入字段","Sort {name} ascending":"按 {name} 升序","Sort {name} descending":"按 {name} 降序","Group by {name}":"按 {name} 分组","Ungroup by {name}":"取消按 {name} 分组","Create kanban by {name}":"按 {name} 创建看板","Delete field “{name}”?":"删除字段“{name}”?","The field and its values in every record are removed. This cannot be undone.":"该字段及其在所有记录中的值都会被删除,且无法恢复。","Field duplicated":"已复制字段","Field deleted":"已删除字段","Deleted {count} records":"已删除 {count} 条记录","Delete {count} records?":"删除 {count} 条记录?","The selected records will be deleted. If any of them changed meanwhile, nothing is deleted.":"所选记录将被删除。若其中任一条记录已被他人修改,则整体取消、不会删除任何记录。","Search fields":"搜索字段","Reorder {name}":"拖动或按上下方向键调整 {name} 的顺序","No matching fields":"没有匹配的字段","Edit field {name}":"编辑字段 {name}","Field config":"字段配置","View config":"视图配置","{count} hidden fields":"已隐藏 {count} 个字段",Filter:"筛选",Group:"分组",Sort:"排序","{count} sorts":"{count} 项排序","Add grouping":"添加分组","Remove grouping":"移除分组","Hide {name}":"隐藏{name}","Show {name}":"显示{name}","Kanban grouping field":"看板分组字段","Date field":"日期字段","Calendar date field":"日历日期字段","Linked records are unavailable. Ask the host to connect this collection.":"关联记录不可用,请确认表格已连接。","Linked records could not be loaded. Retry to keep editing.":"关联记录加载失败,请重试后继续编辑。","{name} linked records":"{name}关联记录","Remove {name}":"移除 {name}","Search {name} records":"搜索 {name} 记录","Search linked records":"搜索关联记录","Loading linked records…":"加载关联记录…","Retry linked records":"重试加载关联记录","Link {name}":"关联 {name}","No matching records.":"没有匹配记录。","Previous linked records":"上一页关联记录","Next linked records":"下一页关联记录","{count} selected · up to 100 per record across all link fields":"已选择 {count} 项 · 每条记录的所有关联字段合计最多 100 项","{name} (read only)":"{name}(只读)","Choose…":"请选择…","Division by zero":"除数不能为零","Invalid computed value":"计算值无效","Computed value overflow":"计算值超出范围","Dependency failed":"依赖字段计算失败",Views:"视图","Add view":"添加视图","Rename view":"重命名视图","Duplicate view":"复制视图","Delete view":"删除视图","View name":"视图名称","View actions":"视图操作","Double click to rename":"双击重命名","Record actions":"记录操作","Copy cells":"复制所选单元格","Delete {count} selected records":"删除所选 {count} 条记录","Not set":"未设置",Checked:"已勾选",Unchecked:"未勾选","Expand group {name}":"展开分组 {name}","Collapse group {name}":"折叠分组 {name}","{count} records":"{count} 条","Collection fields":"表格字段","Field {name}":"字段 {name}","Field name":"字段名","Field description":"字段说明","Field type":"字段类型",Required:"必填","Delete field":"删除字段","Delete field {name}":"删除字段「{name}」","Options of field {name}":"字段 {name} 的选项",Options:"选项","Option name {index}":"选项名称 {index}","Delete option {index}":"删除选项 {index}",Delete:"删除","Add option":"新增选项","Add field":"新增字段","New field":"新字段","New option":"新选项","Single line text":"单行文本","Long text":"长文本",Number:"数字",Checkbox:"复选框",Date:"日期","Single select":"单选","Multiple select":"多选","Filter applied":"已应用筛选","Sort field":"排序字段","Sort direction":"排序方向",Default:"默认",Ascending:"升序",Descending:"降序",Columns:"列设置","Show row numbers":"显示行号","Show record IDs":"显示记录 ID","Move {name} left":"移动{name}到左侧","Move {name} right":"移动{name}到右侧",Tables:"数据表","New table":"新建数据表","Change table icon":"修改数据表图标","Table icon":"数据表图标","Double click to change the icon":"双击修改图标","Schema permission required":"需要数据结构管理权限","Table name":"数据表名称","Rename table {name}":"重命名数据表 {name}","Start with a table":"从一张数据表开始","{count} fields · {mode}":"{count} 个字段 · {mode}",Editable:"可编辑","Read only":"只读",Table:"表格",People:"人员",Business:"业务",List:"清单",Schedule:"日程",Inventory:"库存","Choose a table first.":"请先选择数据表。","Save view":"保存视图",Done:"完成","View settings":"视图设置","Save fields":"保存字段",Cancel:"取消",Refresh:"刷新","Search records":"搜索记录",Search:"搜索",Fields:"字段","Add record":"新增记录","Unsaved view changes":"视图设置未保存","Delete view “{name}”?":"删除视图「{name}」?","Reload records":"重新加载记录","Loading…":"加载中…","{name} copy":"{name} 副本",Name:"名称","New grid view":"新网格视图","New kanban view":"新看板视图","New gallery view":"新画廊视图","New calendar view":"新日历视图","New form view":"新表单视图","Create table":"创建数据表","Sum field":"求和字段","No sum":"不求和","Linked record":"关联记录","Related table":"关联数据表","Choose a related table":"选择关联表",Relations:"关联","{name} · inverse records":"{name} · 反向记录","No tables yet":"还没有数据表","All records":"全部记录","Loading summary…":"正在汇总…","No summary rows.":"没有汇总数据","The collection service is unavailable.":"数据服务暂不可用",none:"无","Choose a count or sum.":"请选择计数或求和。","Use at most three groups and eight summaries.":"最多使用三个分组和八项汇总。","That field is not in this collection.":"该字段不在此数据表中。","Group by a text, number, date, checkbox, or single select field.":"请按文本、数字、日期、复选框或单选字段分组。","Sum only a number field.":"只能对数字字段求和。","Count a queryable field, or omit the field to count records.":"请统计可查询字段,或不选字段以统计记录数。","Each summary needs its own name, different from the group fields.":"每项汇总需要独立名称,且不能与分组字段重名。","Each group field can be used once.":"每个分组字段只能使用一次。",Records:"记录数","Sum of {name}":"{name}合计","Discard unsaved changes?":"放弃未保存的更改?",Discard:"放弃更改","Keep editing":"继续编辑","View deleted":"视图已删除","View saved":"视图已保存","Fields saved":"字段已保存","Record saved":"记录已保存","Record saved, keep adding":"记录已保存,可继续新增","New record form":"新增记录表单",Save:"保存","Save new record":"保存新记录","Save and continue":"保存并继续","Cancel adding":"取消新增","Clear current filter":"清除当前筛选","Configure fields":"配置字段","Table title":"表格标题","{count} filters":"{count} 项筛选","Cancel field settings":"取消字段设置","Only this view's filters, sort and layout are removed; no records are deleted.":"只删除这个视图的筛选、排序和布局设置,不会删除任何记录。","Expand all groups before pasting.":"请先展开所有分组再粘贴。"};function ke(e="en"){return(t,n={})=>(e==="zh-CN"?Zi[t]??t:t).replace(/\{(\w+)\}/g,(o,i)=>String(n[i]??o))}function xn(e,t,n,o,i=!1){let{row:r,column:a}=e;if(t==="ArrowUp")r--;if(t==="ArrowDown")r++;if(t==="ArrowLeft")a--;if(t==="ArrowRight")a++;if(t==="Home")a=0;if(t==="End")a=o-1;if(t==="Tab"){let d=Math.max(0,Math.min(n*o-1,r*o+a+(i?-1:1)));r=Math.floor(d/o),a=d%o}return{row:Math.max(0,Math.min(n-1,r)),column:Math.max(0,Math.min(o-1,a))}}function eo(e,t){return{firstRow:Math.min(e.row,t.row),lastRow:Math.max(e.row,t.row),firstColumn:Math.min(e.column,t.column),lastColumn:Math.max(e.column,t.column)}}function Re(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function gr(e,t,n,o){let i=eo(n,o),r=[];for(let a=i.firstRow;a<=i.lastRow;a++){let d=[];for(let s=i.firstColumn;s<=i.lastColumn;s++){let p=t[s],c=e[a]?.values[p?.id??""],u=p?.type==="json"&&c!=null?JSON.stringify(c):Re(c);d.push(/[\t\r\n"]/.test(u)?`"${u.replaceAll('"','""')}"`:u)}r.push(d.join("\t"))}return r.join(`
2
+ `)}function Xi(e,t="en"){let n=ke(t),o=[],i=[],r="",a=!1;for(let d=0;d<e.length;d++){let s=e[d];if(s==='"'&&(a||r===""))if(a&&e[d+1]==='"')r+='"',d++;else a=!a;else if(!a&&(s==="\t"||s===`
3
+ `||s==="\r")){if(i.push(r),r="",s!=="\t"){if(o.push(i),i=[],s==="\r"&&e[d+1]===`
4
+ `)d++}}else r+=s}if(a)throw Error(n("Unclosed quoted cell."));if(r||i.length||o.length===0)i.push(r),o.push(i);return o}function et(e,t,n="en"){let o=ke(n);if(t.type==="blob")throw Error(o("{name} is read-only; its original bytes are preserved.",{name:t.name}));if(t.type==="relation")throw Error(o("{name} needs a server-provided option.",{name:t.name}));if(t.type==="lookup"||t.type==="formula"||t.type==="rollup")throw Error(o("{name} is read only.",{name:t.name}));if(t.type==="linkedRecord")throw Error(o("Use the {name} record picker.",{name:t.name}));if(e===""){if(t.required)throw Error(o("{name} is required.",{name:t.name}));return null}if(t.type==="number"){let r=Number(e);if(!e.trim()||!Number.isFinite(r))throw Error(o("{name} needs a number.",{name:t.name}));return r}if(t.type==="json")try{return JSON.parse(e)}catch{throw Error(o("{name} needs valid JSON.",{name:t.name}))}if(t.type==="bigint"){if(!/^-?\d+$/.test(e))throw Error(o("{name} needs an integer.",{name:t.name}));return e}if(t.type==="checkbox"){if(["true","1","yes"].includes(e.toLowerCase()))return!0;if(["false","0","no"].includes(e.toLowerCase()))return!1;throw Error(o("{name} needs true or false.",{name:t.name}))}if(t.type==="date"){let r=st(t);if(r){let N=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!N)throw Error(o("{name} needs a date.",{name:t.name}));let[,A,U,E]=N,_=new Date(Date.UTC(Number(A),Number(U)-1,Number(E)));if(_.getUTCMonth()!==Number(U)-1||_.getUTCDate()!==Number(E))throw Error(o("{name} needs a valid calendar date.",{name:t.name}));if(r.time==="none"){if(/T.*(?:Z|[+-]\d{2}:\d{2})$/i.test(e)&&Number.isFinite(Date.parse(e)))return hn(new Date(e),r.timeZone);return`${A}-${U}-${E}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return kt({year:Number(A),month:Number(U),day:Number(E)},r.timeZone).toISOString()}let a=/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-](\d{2}):(\d{2})))?$/i.exec(e);if(!a)throw Error(o("{name} needs a date.",{name:t.name}));let[,d,s,p,c,u,g,x,C]=a,v=Number(d),P=Number(s),m=Number(p),y=[31,v%4===0&&(v%100!==0||v%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(P<1||P>12||m<1||m>(y[P-1]??0)||Number(c??0)>23||Number(u??0)>59||Number(g??0)>59||Number(x??0)>23||Number(C??0)>59)throw Error(o("{name} needs a valid calendar date.",{name:t.name}));let S=new Date(e);if(!Number.isFinite(S.getTime()))throw Error(o("{name} needs a date.",{name:t.name}));return S.toISOString()}let i=(r)=>{let a=t.options?.find((d)=>d.id===r||d.name===r);if(!a)throw Error(o("{name} has no option '{option}'.",{name:t.name,option:r}));return a.id};if(t.type==="singleSelect")return i(e);if(t.type==="multipleSelect")return[...new Set(e.split(",").map((r)=>i(r.trim())))];return e}function mr(e,t,n,o,i="en"){let r=ke(i);try{if(e.length>1048576)throw Error(r("Paste is too large."));let a=Xi(e,i);if(a.length>100||o.row+a.length>t.length)throw Error(r("Paste must fit within the loaded page and contain at most 100 rows."));return{ok:!0,items:a.map((s,p)=>{if(o.column+s.length>n.length)throw Error(r("Paste extends beyond the visible columns."));let c=t[o.row+p];if(!c)throw Error(r("Row is not loaded."));let u={};return s.forEach((g,x)=>{let C=n[o.column+x];if(C?.generation==="autoIncrement")throw Error(r("{name} is auto-generated and cannot be edited.",{name:C.name}));if(C)u[C.id]=et(g,C,i)}),{op:"update",id:c.id,expectedVersion:c.version,values:u}})}}catch(a){return{ok:!1,message:a instanceof Error?a.message:r("Invalid paste.")}}}function kn(e,t){let n=Re(e);if(!/^\d{4}-\d{2}-\d{2}T/.test(n))return n;let o=new Date(n);if(!Number.isFinite(o.getTime()))return n;let i=new Intl.DateTimeFormat("en-CA",{...t?{timeZone:t}:{},year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(o),r=(p)=>i.find((c)=>c.type===p)?.value??"",a=o.getUTCMilliseconds(),d=r("second"),s=d!=="00"||a?`:${d}${a?`.${String(a).padStart(3,"0")}`:""}`:"";return`${r("year")}-${r("month")}-${r("day")} ${r("hour")}:${r("minute")}${s}`}function fr(e,t,n,o=new Set){let i=new Set([...e.map((r)=>r.id),...t]);return n.filter((r)=>i.has(r.id)&&!o.has(r.id))}function to(e,t){let n=new Set(e);if(n.has(t))n.delete(t);else n.add(t);return n}import{jsx as zt}from"react/jsx-runtime";var yr=[["#e8f0fe","#1a56c4"],["#e6f4ea","#1e7a3c"],["#fdecea","#b3261e"],["#fff1e0","#a05a00"],["#e8eaed","#3c4043"],["#e0f2f1","#00695c"],["#f3e8fd","#6a1b9a"]];function no(e){let t=Math.max(e,0)%yr.length,[n,o]=yr[t]??["#e8eaed","#3c4043"];return{background:`var(--uibot-chip-${t}-bg, ${n})`,color:`var(--uibot-chip-${t}-fg, ${o})`}}function oo({index:e,children:t}){return zt("span",{"data-uibot-chip":"",style:{display:"inline-flex",alignItems:"center",maxWidth:"100%",padding:"1px 8px",borderRadius:999,fontSize:12,lineHeight:"18px",fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",...no(e)},children:t})}function ro({ids:e,field:t,wrap:n}){let o=t.options??[];return zt("span",{style:{display:"inline-flex",gap:4,alignItems:"center",maxWidth:"100%",overflow:"hidden",...n?{flexWrap:"wrap"}:{}},children:e.map((i)=>{let r=o.findIndex((a)=>a.id===i);return zt(oo,{index:rn(o,i),children:o[r]?.name??String(i)},String(i))})})}function Cr({checked:e,label:t,onToggle:n}){return zt("input",{type:"checkbox","aria-label":t,checked:e,disabled:!n,style:{width:16,height:16,margin:0,accentColor:"var(--primary, #1a56c4)"},onMouseDown:(o)=>o.stopPropagation(),onKeyDown:(o)=>o.stopPropagation(),onChange:()=>n?.()})}var br={singleLineText:"M3 4.5h10M8 4.5v8",longText:"M3 4h10M3 8h10M3 12h6",number:"M6.5 3 5.5 13M10.5 3l-1 10M3 6h10.5M2.5 10h10.5",bigint:"M6.5 3 5.5 13M10.5 3l-1 10M3 6h10.5M2.5 10h10.5",checkbox:"M3.5 3.5h9v9h-9zM5.6 8.1l1.8 1.8 3-3.6",date:"M3 4.5h10V13H3zM3 7.5h10M6 3v3M10 3v3",singleSelect:"M8 14a6 6 0 1 0 0-12 6 6 0 0 0 0 12zM5.8 7l2.2 2.2L10.2 7",multipleSelect:"M6 4h7M6 8h7M6 12h7M3 4h.01M3 8h.01M3 12h.01",relation:"M7 9a2.5 2.5 0 0 0 3.5 0l2-2A2.5 2.5 0 0 0 9 3.5l-.7.7M9 7a2.5 2.5 0 0 0-3.5 0l-2 2A2.5 2.5 0 0 0 7 12.5l.7-.7",linkedRecord:"M7 9a2.5 2.5 0 0 0 3.5 0l2-2A2.5 2.5 0 0 0 9 3.5l-.7.7M9 7a2.5 2.5 0 0 0-3.5 0l-2 2A2.5 2.5 0 0 0 7 12.5l.7-.7",lookup:"M7 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM10 10l3.5 3.5",formula:"M10.5 3.5c-2 0-2.2 1-2.5 3L7.2 12c-.3 1.6-1 2-2.5 2M5 7.5h5",rollup:"M12 3.5H4.5L8.5 8l-4 4.5H12",json:"M6 3.5C4.5 3.5 4.5 5 4.5 6.5S4 8 3 8c1 0 1.5.5 1.5 1.5S4.5 12.5 6 12.5M10 3.5c1.5 0 1.5 1.5 1.5 3S12 8 13 8c-1 0-1.5.5-1.5 1.5s0 3-1.5 3",blob:"M4 3.5h5l3 3V12.5H4z"};function hr({type:e}){return zt("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",width:13,height:13,fill:"none",stroke:"currentColor",strokeWidth:1.4,strokeLinecap:"round",strokeLinejoin:"round",style:{flex:"none",opacity:0.62},children:zt("path",{d:br[e]??br.singleLineText})})}function wn(e){let t=yn.findIndex((o)=>o===e);if(t<0)return;let n=no(t);return{background:`color-mix(in srgb, ${n.background} 55%, var(--background, white))`,marker:String(n.color)}}var vr=(e,t)=>(e%t+t)%t;function xr(e,t,n,o){let i=[],r=0,a=0,d=e.lastRow-e.firstRow+1,s=e.lastColumn-e.firstColumn+1;if(d<1||s<1||t.lastRow-t.firstRow+1>100)return{mutations:i,skipped:r,count:a,limitExceeded:!0};for(let p=t.firstRow;p<=t.lastRow;p++){let c=n[p];if(!c)continue;let u={};for(let g=t.firstColumn;g<=t.lastColumn;g++){if(p>=e.firstRow&&p<=e.lastRow&&g>=e.firstColumn&&g<=e.lastColumn)continue;let x=o[g];if(!x)continue;if(Ne(x)||x.generation==="autoIncrement"||["blob","linkedRecord","relation"].includes(x.type)){r++;continue}let C=e.firstColumn+vr(g-e.firstColumn,s),v=o[C];if(!v||v.type!==x.type){r++;continue}let P=n[e.firstRow+vr(p-e.firstRow,d)]?.values[v.id]??null;if(s===1&&d>=2&&(x.type==="number"||x.type==="date")&&g===e.firstColumn){let m=n.slice(e.firstRow,e.lastRow+1).map((N)=>N.values[v.id]),w=m.map((N)=>x.type==="date"?typeof N==="string"&&N!==""?Date.parse(N)/86400000:Number.NaN:typeof N==="number"?N:Number.NaN),y=w[0]??Number.NaN,S=(w[1]??Number.NaN)-y;if(w.every((N,A)=>Number.isFinite(N)&&Math.abs(N-(y+S*A))<0.00000001)){let N=y+S*(p-e.firstRow);if(Number.isFinite(N))P=x.type==="date"?String(m[0]).length===10?new Date(N*86400000).toISOString().slice(0,10):new Date(N*86400000).toISOString():N}}u[x.id]=structuredClone(P),a++}if(Object.keys(u).length)i.push({op:"update",id:c.id,expectedVersion:c.version,values:u})}return{mutations:i,skipped:r,count:a,limitExceeded:!1}}import{useEffect as wr,useId as ta,useMemo as na,useRef as oa,useState as Pr}from"react";var ea=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function wt(e){return ea.test(e)}var ft=(e)=>String(e).padStart(2,"0");function kr(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${ft(t.getMonth()+1)}-${ft(t.getDate())}T${ft(t.getHours())}:${ft(t.getMinutes())}:${ft(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var io=(e,t)=>{let n=lt(e,t);return`${n.year}-${ft(n.month)}-${ft(n.day)}T${ft(n.hour)}:${ft(n.minute)}`};function ao(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!wt(e))return e.slice(0,10);return io(new Date(e),t.timeZone??"UTC").slice(0,10)}if(wt(e))return io(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function lo(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||wt(t)))return e;let i=e.length>10?e.slice(11,16):t&&wt(t)?io(new Date(t),n.timeZone).slice(11,16):"00:00",[r,a,d]=e.slice(0,10).split("-").map(Number),[s,p]=i.split(":").map(Number),c=kt({year:r??0,month:a??1,day:d??1,hour:s??0,minute:p??0},n.timeZone);return Number.isFinite(c.getTime())?c.toISOString():e}import{jsx as Nt,jsxs as Rr}from"react/jsx-runtime";function jt(e,t,n){if(e.type==="blob")return"";try{return et(t,e),""}catch{if(t===""&&e.required)return n==="zh-CN"?`请填写${e.name}。`:`${e.name} is required.`;if(e.type==="number")return n==="zh-CN"?`${e.name}需要有效数字。`:`${e.name} needs a number.`;if(e.type==="bigint")return n==="zh-CN"?`${e.name}必须是整数。`:`${e.name} needs an integer.`;if(e.type==="date")return n==="zh-CN"?`${e.name}需要有效日期。`:`${e.name} needs a valid date.`;if(e.type==="checkbox")return n==="zh-CN"?`${e.name}请选择是或否。`:`${e.name} needs true or false.`;if(e.type==="json")return n==="zh-CN"?`${e.name}必须是有效 JSON。`:`${e.name} needs valid JSON.`;return n==="zh-CN"?"输入值无效":"Invalid value"}}function so({field:e,text:t,disabled:n,id:o,label:i,ariaLabel:r,onChange:a,onSave:d,onCancel:s,locale:p="en",submitted:c=!1,describedBy:u}){let g=na(()=>ke(p),[p]),x=ta(),C=oa(null),v=Boolean(d);wr(()=>{if(v)C.current?.querySelector("input,textarea,select")?.focus()},[v]);let P=o??x,m=`${P}-error`,[w,y]=Pr(t),[S,N]=Pr(!1);wr(()=>y(t),[t]);let A=jt(e,w,p),E=Boolean(e.required&&w===""&&A)&&!S&&!c?"":A,_=r??i??e.name,G=e.type==="date"&&wt(w),M=G&&!A?kr(w):w,T=[u,E?m:void 0].filter(Boolean).join(" "),Y={id:P,"aria-label":_,"aria-invalid":Boolean(E),...T?{"aria-describedby":T}:{},disabled:n,onBlur:()=>N(!0),onKeyDown:(R)=>{if(d||s)R.stopPropagation();let J=e.type==="longText"||e.type==="json";if(R.key==="Tab"&&d)R.preventDefault(),d(R.shiftKey?"previous":"next");else if(R.key==="Enter"&&!R.shiftKey&&d&&(!J||R.ctrlKey||R.metaKey))R.preventDefault(),d();else if(R.key==="Escape"&&s)R.preventDefault(),s()},style:{width:"100%",...v?{height:"100%",border:0,borderRadius:0,outline:"none",boxShadow:"none",padding:"0 7px",boxSizing:"border-box",font:"inherit"}:{},background:"var(--background, white)",color:"inherit"},className:"min-w-0 rounded-md border border-[var(--uibot-border,#d4d4d8)] bg-[var(--uibot-surface,#fff)] px-2 py-1 text-sm text-[var(--uibot-text,#18181b)] disabled:cursor-not-allowed disabled:opacity-60"},D=(R)=>{N(!0),y(R),a(R)},k=(R)=>{if(e.type==="date"&&G&&R){let J=new Date(R);D(Number.isFinite(J.getTime())?J.toISOString():R)}else D(R)},Q;if(e.type==="checkbox")Q=Rr("select",{...Y,value:w,onChange:(R)=>D(R.currentTarget.value),children:[!e.required&&Nt("option",{value:"",children:g("No value")}),Nt("option",{value:"true",children:g("Yes")}),Nt("option",{value:"false",children:g("No")})]});else if(e.type==="longText"||e.type==="json")Q=Nt("textarea",{...Y,value:w,rows:e.type==="json"?4:3,onChange:(R)=>D(R.currentTarget.value)});else{let R=e.type==="date"&&!(A&&w)?G?"datetime-local":"date":"text",J=e.type==="blob";Q=Nt("input",{...Y,type:R,inputMode:e.type==="number"?"decimal":void 0,step:G?"0.001":void 0,value:M,readOnly:J,onInput:e.type==="date"?(O)=>k(O.currentTarget.value):void 0,onChange:(O)=>k(O.currentTarget.value)})}return Rr("div",{ref:C,className:"grid min-w-0 gap-1",style:v?{height:"100%"}:void 0,children:[i&&Nt("label",{className:"text-xs font-medium",htmlFor:P,children:i}),Q,E&&Nt("span",{id:m,role:"alert",className:"text-xs text-red-600",children:E})]})}import{useEffect as co,useMemo as ra,useState as Mt}from"react";import{jsx as Ht,jsxs as Sr}from"react/jsx-runtime";function Pn(e,t){if(!t?.length)return e;let n=!1,o={...e};for(let i of t){let r=i.label.trim();if(!r||o[i.id]===r)continue;o[i.id]=r,n=!0}return n?o:e}function uo(e){let t=ra(()=>ke(e.locale),[e.locale]),[n,o]=Mt(""),[i,r]=Mt(),[a,d]=Mt(null),[s,p]=Mt([]),[c,u]=Mt(()=>Pn({},e.labels)),[g,x]=Mt(""),[C,v]=Mt(!1),P=e.field.relation?.collectionId,m=e.field.relation?.labelFieldId,{getOptions:w,value:y}=e;co(()=>{u((A)=>Pn(A,e.labels))},[e.labels]),co(()=>{let A=!1;if(!P||!w)return;return v(!0),x(""),w({collectionId:P,...m?{labelFieldId:m}:{},search:n,...i?{cursor:i}:{},limit:50}).then((U)=>{if(A)return;if(!U.ok){x(U.error.message),d(null);return}let E=U.data.items.slice(0,50);u((_)=>Pn(_,E)),p((_)=>{let G=i?[..._,...E]:E;return[...new Map(G.map((M)=>[M.id,M])).values()]}),d(U.data.nextCursor)}).catch(()=>{if(!A)x(t("Relation options unavailable."))}).finally(()=>{if(!A)v(!1)}),()=>{A=!0}},[P,m,n,i,w,t]),co(()=>{if(!y||!P||!w)return;if(e.labels?.some((U)=>U.id===y&&U.label.trim()))return;let A=!1;return w({collectionId:P,...m?{labelFieldId:m}:{},ids:[y],limit:50}).then((U)=>{if(A||!U.ok)return;let E=U.data.items.find((_)=>_.id===y);if(E)u((_)=>Pn(_,[E]))}).catch(()=>{}),()=>{A=!0}},[y,P,m,w,e.labels]);let S=!P||!w,N=y?c[y]??s.find((A)=>A.id===y)?.label??y:"";return Sr("div",{children:[Ht("input",{"aria-label":t("Search {name}",{name:e.field.name}),value:n,disabled:e.disabled||S,onChange:(A)=>{o(A.currentTarget.value),r(void 0),p([]),d(null)}}),Sr("select",{"aria-label":e.label??e.field.name,value:e.value,disabled:e.disabled||S||C,onChange:(A)=>{let U=A.currentTarget.value;if(!U||s.some((E)=>E.id===U))e.onChange(U)},children:[Ht("option",{value:"",children:t("No relation")}),y&&!s.some((A)=>A.id===y)&&Ht("option",{value:y,children:N}),s.map((A)=>Ht("option",{value:A.id,children:A.label},A.id))]}),a&&Ht("button",{type:"button",disabled:C||e.disabled,onClick:()=>r(a),children:t("More {name} options",{name:e.field.name})}),(g||S)&&Ht("span",{role:"status",children:g||t("Relation option provider unavailable.")})]})}import{jsx as Ir}from"react/jsx-runtime";var ia={refresh:"M13 3v3.5h-3.5M3 13V9.5h3.5M12.4 6.5A5 5 0 0 0 4 5M3.6 9.5A5 5 0 0 0 12 11",sliders:"M3 4.5h6M12 4.5h1M3 11.5h1M7 11.5h6M9 3v3M5 10v3",save:"M3.5 3.5h7l2 2v7h-9zM5.5 3.5v3h4v-3M5.5 12.5v-3h5v3",fields:"M3 3.5h10v9H3zM6.3 3.5v9M9.7 3.5v9",plus:"M8 3.5v9M3.5 8h9",chevronLeft:"M9.5 3.5 5 8l4.5 4.5",chevronRight:"M6.5 3.5 11 8l-4.5 4.5",chevronUp:"M3.5 9.5 8 5l4.5 4.5",chevronDown:"M3.5 6.5 8 11l4.5-4.5",trash:"M3.5 4.5h9M6.5 4.5v-1.5h3v1.5M5 4.5l.5 8h5l.5-8",x:"M4 4l8 8M12 4l-8 8",eye:"M1.5 8S4 3.5 8 3.5 14.5 8 14.5 8 12 12.5 8 12.5 1.5 8 1.5 8zM8 9.8a1.8 1.8 0 1 0 0-3.6 1.8 1.8 0 0 0 0 3.6z",eyeOff:"M2 2l12 12M6.4 3.8A6.3 6.3 0 0 1 8 3.5C12 3.5 14.5 8 14.5 8a11 11 0 0 1-2 2.6M9.7 12.2a6.3 6.3 0 0 1-1.7.3C4 12.5 1.5 8 1.5 8a11 11 0 0 1 2.3-2.8M6.6 6.6a1.8 1.8 0 0 0 2.4 2.4",group:"M3 4h10M3 8h7M3 12h4",filter:"M2.5 3.5h11l-4.2 5v4l-2.6 1v-5z",arrowLeft:"M13 8H3M7 4 3 8l4 4",arrowRight:"M3 8h10M9 4l4 4-4 4",sortAsc:"M4.5 13V3M4.5 3 2.5 5M4.5 3l2 2M9 4h4M9 8h3M9 12h2",sortDesc:"M4.5 3v10M4.5 13l-2-2M4.5 13l2-2M9 4h2M9 8h3M9 12h4",kanban:"M3 3h3.5v10H3zM9.5 3H13v6H9.5z",palette:"M8 2a6 6 0 1 0 0 12h1a1.5 1.5 0 0 0 0-3h-.5a1 1 0 0 1 0-2H11a3 3 0 0 0 3-3c0-2-3-4-6-4zM5 5h.01M8 4h.01M11 5h.01M4 8h.01",freeze:"M3 3.5h10v9H3zM6.5 3.5v9M3 6.5h3.5M3 9.5h3.5",sigma:"M12 3.5H4.5L8.5 8l-4 4.5H12",expand:"M9.5 3H13v3.5M6.5 13H3V9.5M13 3 9 7M3 13l4-4",pencil:"M3 13l.7-3L10.5 3.2a1.4 1.4 0 0 1 2 2L5.7 12 3 13z",copy:"M5.5 5.5h7v7h-7zM3.5 10.5v-7h7",calendar:"M3 4.5h10V13H3zM3 7.5h10M6 3v3M10 3v3",sort:"M4.5 3v10M4.5 13l-2-2M4.5 13l2-2M11.5 13V3M11.5 3l-2 2M11.5 3l2 2",rows:"M3 4h10M3 8h10M3 12h10",more:"M4 8h.01M8 8h.01M12 8h.01",sparkles:"M7 2.5l1.2 3.3L11.5 7 8.2 8.2 7 11.5 5.8 8.2 2.5 7l3.3-1.2zM12 9.5l.6 1.4 1.4.6-1.4.6-.6 1.4-.6-1.4-1.4-.6 1.4-.6z",grip:"M6 4h.01M10 4h.01M6 8h.01M10 8h.01M6 12h.01M10 12h.01"};function Le({name:e,size:t=15,style:n}){return Ir("svg",{"aria-hidden":"true",focusable:"false",viewBox:"0 0 16 16",width:t,height:t,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",style:{flex:"none",...n},children:Ir("path",{d:ia[e]})})}import{createContext as aa,useContext as la,useCallback as sa,useEffect as Ar,useId as da,useLayoutEffect as Er,useRef as Dr,useState as Tr}from"react";import{createPortal as ca}from"react-dom";import{jsx as yt,jsxs as Mr,Fragment as Nr}from"react/jsx-runtime";var ua=aa(!1),po="uibot:collection-popover-open";function go({label:e,trigger:t,defaultOpen:n=!1,disabled:o,menu:i,children:r}){let[a,d]=Tr(n),[s,p]=Tr({left:8,top:8}),c=Dr(null),u=Dr(null),g=da();Ar(()=>{let v=(P)=>{let m=P.detail,w=c.current;if(!m||!w||m===w)return;let y=w.closest("[data-uibot-workspace]")??w.parentElement,S=m.closest("[data-uibot-workspace]")??m.parentElement;if(y===S)d(!1)};return document.addEventListener(po,v),()=>document.removeEventListener(po,v)},[]);let x=()=>{d(!1),c.current?.focus({preventScroll:!0})},C=sa(()=>{if(!a)return;let v=c.current?.getBoundingClientRect(),P=u.current?.getBoundingClientRect();if(v&&P){let m={left:Math.max(8,Math.min(v.left,window.innerWidth-P.width-8)),top:Math.max(8,v.bottom+P.height+8<=window.innerHeight?v.bottom+4:v.top-P.height-4)};p((w)=>w.left===m.left&&w.top===m.top?w:m)}},[a]);return Er(C),Er(()=>{if(!a)return;if(c.current)document.dispatchEvent(new CustomEvent(po,{detail:c.current}));(u.current?.querySelector("button:not(:disabled), input, select, textarea")??u.current)?.focus({preventScroll:!0})},[a]),Ar(()=>{if(!a)return;let v=(m)=>{if(m.target instanceof Node&&!u.current?.contains(m.target)&&!c.current?.contains(m.target))d(!1)},P=(m)=>{if(m.key!=="Escape")return;m.preventDefault(),m.stopPropagation(),d(!1),c.current?.focus({preventScroll:!0})};return window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),document.addEventListener("pointerdown",v),document.addEventListener("keydown",P),()=>{window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0),document.removeEventListener("pointerdown",v),document.removeEventListener("keydown",P)}},[a,C]),Mr(Nr,{children:[yt("button",{ref:c,type:"button","aria-label":e,"aria-haspopup":i?"menu":"dialog","aria-expanded":a,"aria-controls":a?g:void 0,disabled:o,style:{display:"inline-flex",alignItems:"center",gap:6,border:0,background:"transparent",color:"inherit",font:"inherit",padding:"4px 6px",cursor:"pointer"},onPointerDown:(v)=>v.stopPropagation(),onClick:()=>a?x():d(!0),children:t}),a&&ca(yt("div",{ref:u,id:g,role:i?"menu":"dialog","aria-label":e,tabIndex:-1,style:{position:"fixed",...s,zIndex:80,padding:i?4:12,minWidth:160,maxWidth:"calc(100vw - 16px)",maxHeight:"min(70vh, 600px)",overflow:"auto",boxSizing:"border-box",border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"var(--foreground, inherit)",fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},onKeyDown:(v)=>{if(!i||!["ArrowDown","ArrowUp","Home","End"].includes(v.key))return;v.preventDefault();let P=[...v.currentTarget.querySelectorAll('button[role="menuitem"]:not(:disabled)')],m=P.indexOf(document.activeElement),w=v.key==="Home"?0:v.key==="End"?P.length-1:(m+(v.key==="ArrowUp"?-1:1)+P.length)%P.length;P[w]?.focus()},children:r(x)}),document.body)]})}function Fr({ui:e,label:t,defaultOpen:n,icon:o,chevron:i,quiet:r,active:a,children:d}){let s=la(ua),p=(c)=>yt("div",{style:{fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},children:yt("fieldset",{disabled:s,style:{border:0,padding:0,margin:0,minWidth:0},children:c})});if(e?.Popover)return e.Popover({label:t,defaultOpen:n,...o?{icon:yt(Le,{name:o})}:{},...i?{iconEnd:yt(Le,{name:"chevronDown",size:13})}:{},...r?{quiet:r}:{},active:a,children:typeof d==="function"?(c)=>p(d(c)):p(d)});return yt(go,{label:t,defaultOpen:n,trigger:Mr(Nr,{children:[o?yt(Le,{name:o}):null,t,i?yt(Le,{name:"chevronDown",size:13}):null]}),children:(c)=>p(typeof d==="function"?d(c):d)})}import{useEffect as pa,useMemo as ga,useState as ma}from"react";function Or(e,t,n,o,i,r){let a=ga(()=>{let p=n.flatMap((c,u)=>{let g=t.footerStats?.[c.id];return g&&g!=="none"&&g!=="count"?[{fn:g,fieldId:c.id,as:`footer${u}`}]:[]});return JSON.stringify([e,bn(t,{aggregates:p}),o.map((c)=>[c.id,c.version]),r])},[e,n,t,o,r]),[d,s]=ma({key:"",status:"ready",values:{}});return pa(()=>{if(!i)return;let p=!0,[c,u]=JSON.parse(a);return(async()=>{let g={};for(let x=0;x<u.aggregates.length;x+=8){let C={...u,aggregates:u.aggregates.slice(x,x+8)};if(Cn(c,C))throw Error("Invalid summary");let v=await i.aggregate(c.id,C);if(!p)return;if(!v.ok||v.data.length!==1)throw Error("Summary unavailable");for(let P of C.aggregates){let m=v.data[0]?.values[P.as],w=c.fields.find((S)=>S.id===P.fieldId),y=w?.type==="date"||w?.resultType==="date";if(m!==null&&!(typeof m==="number"&&Number.isFinite(m))&&!(y&&(P.fn==="min"||P.fn==="max")&&typeof m==="string"&&Number.isFinite(Date.parse(m))))throw Error("Invalid summary result");g[P.as]=m}}if(p)s({key:a,client:i,status:"ready",values:g})})().catch(()=>{if(p)s({key:a,client:i,status:"error",values:{}})}),()=>{p=!1}},[i,a]),{status:!i?"local":d.key!==a||d.client!==i?"loading":d.status,values:d.key===a&&d.client===i?d.values:{}}}function Vr(e){if(e.type==="number")return["count","filled","empty","sum","avg","min","max"];if(e.type==="date")return["count","filled","empty","min","max"];return["count","filled","empty"]}var Lr=(e)=>e!==null&&e!==void 0&&e!==""&&!(Array.isArray(e)&&e.length===0)&&e!==!1;function Br(e,t,n){let o=e.map((r)=>r.values[t.id]);if(n==="none")return null;if(n==="count")return e.length;if(n==="filled")return o.filter(Lr).length;if(n==="empty")return o.filter((r)=>!Lr(r)).length;if(t.type==="date"){let r=o.filter((a)=>typeof a==="string"&&a!=="").sort();if(!r.length)return null;return n==="min"?r[0]??null:r[r.length-1]??null}let i=o.filter((r)=>typeof r==="number"&&Number.isFinite(r));if(!i.length)return null;if(n==="sum")return i.reduce((r,a)=>r+a,0);if(n==="avg")return i.reduce((r,a)=>r+a,0)/i.length;if(n==="min")return Math.min(...i);return Math.max(...i)}import{useEffect as fa,useRef as ya,useState as Kt}from"react";import{jsx as tt,jsxs as an}from"react/jsx-runtime";function Pt(e){if(e==null)return"—";if(Array.isArray(e))return e.map(Pt).join(", ");return String(e)}function Ur(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((o)=>o.label||o.id).join(", "):void 0)??Pt(e.values[t.id])}function _r(e,t){return Re(e.values[t.id])}function Rn({field:e,value:t,labels:n=[],client:o,onChange:i,disabled:r=!1,locale:a,"aria-describedby":d,"aria-invalid":s}){let p=ke(a),c=Array.isArray(t)?t.filter((M)=>typeof M==="string"):[],u=ya(new Set(c));u.current=new Set(c);let[g,x]=Kt(""),[C,v]=Kt(),[P,m]=Kt([]),[w,y]=Kt(0),[S,N]=Kt({}),[A,U]=Kt({rows:[],next:null,error:"",loading:!0}),E=e.link?.collectionId,_=e.link?.displayFieldId;fa(()=>{let M=!0;if(U({rows:[],next:null,error:"",loading:!0}),!o||!E||!_){U({rows:[],next:null,error:p("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return o.query(E,{limit:50,search:g,...C?{cursor:C}:{}}).then((T)=>{if(!M)return;if(!T.ok){U({rows:[],next:null,error:T.error.message,loading:!1});return}N((Y)=>({...Object.fromEntries(Object.entries(Y).filter(([D])=>u.current.has(D))),...Object.fromEntries(T.data.items.map((D)=>{let k=String(D.values[_]??"");return[D.id,k.trim()?k.slice(0,256):D.id]}))})),U({rows:T.data.items,next:T.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(M)U({rows:[],next:null,error:p("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{M=!1}},[o,E,_,g,C,w]);let G=(M)=>S[M]??n.find((T)=>T.id===M)?.label??M;return an("fieldset",{disabled:r,"aria-label":p("{name} linked records",{name:e.name}),...d?{"aria-describedby":d}:{},...s?{"aria-invalid":!0}:{},className:"flex min-w-0 flex-col gap-2 rounded-md border p-2",children:[tt("div",{className:"flex flex-wrap gap-1",children:c.map((M)=>an("span",{className:"rounded border px-2 py-1 text-sm",children:[G(M)," ",tt("button",{type:"button","aria-label":p("Remove {name}",{name:G(M)}),onClick:()=>i(c.filter((T)=>T!==M)),children:"×"})]},M))}),tt("input",{"aria-label":p("Search {name} records",{name:e.name}),type:"search",placeholder:p("Search linked records"),value:g,onChange:(M)=>{x(M.target.value),v(void 0),m([])}}),A.loading&&tt("p",{role:"status",children:p("Loading linked records…")}),A.error&&an("div",{role:"alert",children:[A.error," ",tt("button",{type:"button",onClick:()=>y((M)=>M+1),children:p("Retry linked records")})]}),tt("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:A.rows.map((M)=>an("label",{className:"flex items-center gap-2 text-sm",children:[tt("input",{type:"checkbox","aria-label":p("Link {name}",{name:G(M.id)}),checked:c.includes(M.id),disabled:!c.includes(M.id)&&c.length>=100,onChange:(T)=>i(T.target.checked?[...c,M.id]:c.filter((Y)=>Y!==M.id))}),G(M.id)]},M.id))}),!A.loading&&!A.error&&!A.rows.length&&tt("p",{children:p("No matching records.")}),an("div",{className:"flex gap-2",children:[tt("button",{type:"button",disabled:!P.length||A.loading,onClick:()=>{v(P.at(-1)),m((M)=>M.slice(0,-1))},children:p("Previous linked records")}),tt("button",{type:"button",disabled:!A.next||A.loading,onClick:()=>{m((M)=>[...M,C]),v(A.next??void 0)},children:p("Next linked records")})]}),tt("small",{children:p("{count} selected · up to 100 per record across all link fields",{count:c.length})})]})}var ba={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function Gt(e,t,n){return t?ke(n)(ba[t]):e==null?"—":String(e)}function yc(e,t=(n)=>n){return[...e.type==="checkbox"?[{id:"boolean:false",name:t("Unchecked"),value:!1},{id:"boolean:true",name:t("Checked"),value:!0}]:e.type==="singleSelect"?(e.options??[]).map((o)=>({id:`option:${o.id}`,name:o.name,value:o.id})):[],{id:"null",name:t("Unassigned"),value:null}]}function qr(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function $r(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function bc(e,t,n){let o=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...$r(e),filter:qr(e.filter,o)}}function Ca(e,t=(n)=>n){if(!/^\d{4}-\d{2}$/.test(e))throw Error(t("Choose a valid month."));let[n,o]=e.split("-").map(Number);if(!n||n>9998||!o||o>12)throw Error(t("Choose a valid month."));let i=new Date(`${e}-01T00:00:00.000Z`),r=new Date(i);return r.setUTCMonth(r.getUTCMonth()+1),{start:i.toISOString(),end:r.toISOString(),days:Math.round((r.getTime()-i.getTime())/86400000),weekday:i.getUTCDay()}}function Cc(e,t,n){let{start:o,end:i}=Ca(n);return{...$r(e),filter:qr(e.filter,{fieldId:t,operator:"onOrAfter",value:o},{fieldId:t,operator:"before",value:i})}}function zr(e,t){let n={id:"date",name:"Date",type:"date"},o=String(et(t,n)),i=String(et(String(e),n));return`${o.slice(0,10)}${i.slice(10)}`}function mo(e,t){return[...t.columnOrder,...e.map((o)=>o.id).filter((o)=>!t.columnOrder.includes(o))].filter((o)=>!t.hiddenColumns.includes(o)).flatMap((o)=>e.filter((i)=>i.id===o))}function fo(e,t){let n=t.find((o)=>o.type==="singleLineText"||o.type==="longText");return(n?Re(e.values[n.id]):"")||e.id}function yo(e,t,n){if(t.type==="lookup")return Pt(e);if(t.type==="date"){let o=st(t);return o?nn(e,o):kn(e)}if(t.type==="number"){let o=tn(t);return o?on(e,o):Re(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return Gt(e,n);if(t.type==="singleSelect"||t.type==="multipleSelect")return(Array.isArray(e)?e:e==null?[]:[e]).map((i)=>t.options?.find((r)=>r.id===i)?.name??String(i)).join(", ");return Re(e)}import{useEffect as ha,useRef as va}from"react";import{jsx as Rt,jsxs as jr,Fragment as xa}from"react/jsx-runtime";var Sn={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function Ae({ui:e,style:t,variant:n,size:o,children:i,disabled:r,onClick:a,title:d,ariaLabel:s,icon:p,iconOnly:c,badge:u}){let g=e?.Button,x=p?jr("span",{style:{position:"relative",display:"inline-flex"},children:[Rt(Le,{name:p}),u?Rt("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,C=c?x:jr(xa,{children:[x,i]}),v=s,P=d??(c?v:void 0),m=c?"icon":o;if(g)return Rt(g,{...n?{variant:n}:{},...m?{size:m}:{},disabled:r,onClick:a,title:P,"aria-label":v,children:C});return Rt("button",{type:"button",style:{...p?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?Sn:{},...c?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:r,onClick:a,title:P,"aria-label":v,children:C})}function Hr({ui:e,value:t,options:n,onChange:o,disabled:i,label:r,style:a,"aria-describedby":d,"aria-invalid":s}){let p=e?.Select,c={...d?{"aria-describedby":d}:{},...s?{"aria-invalid":!0}:{}};if(p)return Rt(p,{value:t,options:n,onChange:o,disabled:i,"aria-label":r,...c});return Rt("select",{"aria-label":r,...c,style:a,disabled:i,value:t,onChange:(u)=>o(u.target.value),children:n.map((u)=>Rt("option",{value:u.value,disabled:u.disabled,children:u.label},u.value))})}function In({label:e,busy:t,onCancel:n,children:o,alert:i=!1}){let r=va(null);return ha(()=>{let a=r.current,d=document.activeElement;if(a?.showModal)a.showModal();else a?.setAttribute("open","");return()=>{if(a?.close?.(),d instanceof HTMLElement&&d.isConnected)d.focus({preventScroll:!0})}},[]),Rt("dialog",{ref:r,role:i?"alertdialog":"dialog","aria-modal":"true","aria-label":e,style:{position:"fixed",inset:0,margin:"auto",maxWidth:"min(440px, calc(100vw - 32px))",maxHeight:"80vh",overflow:"auto",boxSizing:"border-box",padding:20,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"inherit",font:"inherit"},onKeyDown:(a)=>{if(a.key!=="Tab")return;let d=a.currentTarget,s=[...d.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter((u)=>!u.hidden),p=s[0],c=s.at(-1);if(!p||(a.shiftKey?document.activeElement===p:document.activeElement===c)||!d.contains(document.activeElement)){if(a.preventDefault(),(a.shiftKey?c:p)?.focus(),!p)d.focus()}},tabIndex:-1,onCancel:(a)=>{if(a.preventDefault(),!t)n()},children:o})}import{useEffect as On,useRef as cn,useState as We}from"react";import{useId as $a,useState as ko}from"react";import{useEffect as Kr,useRef as ln,useState as dt}from"react";import{jsx as le,jsxs as be,Fragment as Ra}from"react/jsx-runtime";function ka(e){let t=URL.createObjectURL(new Blob([e.csv],{type:"text/csv;charset=utf-8"})),n=document.createElement("a");n.href=t,n.download=e.fileName,n.click(),setTimeout(()=>URL.revokeObjectURL(t),1000)}var wa=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function Pa({descriptor:e,fieldIds:t,query:n,client:o,readOnly:i=!1,reloadKey:r=0,onImported:a,onRefreshSchema:d}){let[s,p]=dt(null),[c,u]=dt(null),[g,x]=dt(null),[C,v]=dt([]),[P,m]=dt(""),[w,y]=dt(!1),[S,N]=dt(!1),[A,U]=dt(!0),[E,_]=dt(null),[G,M]=dt(!1),T=ln(!1),Y=ln(!1),D=ln(!1),k=ln(null),Q=ln({client:o,onImported:a,descriptor:e});Q.current={client:o,onImported:a,descriptor:e},Kr(()=>(T.current=!0,()=>{T.current=!1,Y.current=!1}),[]),Kr(()=>{let F=!0;if(!i)o.imports(e.id).then((K)=>{if(!F||!T.current||!K.ok)return;if(v((ee)=>K.data.map((de)=>{let me=ee.find((X)=>X.id===de.id);return me&&me.version>de.version?me:de})),!D.current)x((ee)=>{let de=K.data.find((me)=>me.id===ee?.id);return ee&&de&&de.version>ee.version?de:ee})});return()=>{F=!1}},[o,e.id,i,r]);let R=(F)=>{x(F),v((K)=>[F,...K.filter((ee)=>ee.id!==F.id)].slice(0,50)),_(null)};async function J(F){if(D.current||i)return;D.current=!0,Y.current=!0,y(!0),N(!0),m("");let K=F;try{while(T.current&&Y.current&&K.status==="ready"){let ee=await Q.current.client.advanceImport(e.id,K.id,K.version);if(!T.current)break;if(!ee.ok){m(ee.error.message);break}let de=ee.data;if(R(de),de.importedRows>K.importedRows)Q.current.onImported();if(de.version===K.version&&de.status==="ready"){m("Import paused. Refresh the saved progress before retrying.");break}K=de}}finally{if(D.current=!1,Y.current=!1,T.current)y(!1),N(!1)}}async function O(){if(!s||D.current)return;D.current=!0,y(!0),m("");let F=await o.previewImport(e.id,{...s,expectedSchemaVersion:e.schemaVersion});if(D.current=!1,!T.current)return;if(y(!1),F.ok)u(F.data),p({...s,expectedSchemaVersion:F.data.schemaVersion,mapping:F.data.mapping});else m(F.error.message)}async function ie(){if(!s||!c||c.missingRequiredFieldIds.length||!c.totalRows||D.current||i)return;D.current=!0,y(!0),m(""),k.current??=crypto.randomUUID();let F=await o.createImport(e.id,{...s,idempotencyKey:k.current});if(D.current=!1,!T.current)return;if(y(!1),F.ok)R(F.data),p(null),u(null),k.current=null,J(F.data);else m(F.error.message)}async function z(){if(!g||D.current||i)return;if(g.status==="ready"){J(g);return}D.current=!0,y(!0),m("");let F=d?await d():Q.current.descriptor;if(!F){D.current=!1,y(!1),m("Refresh the collection schema and try again.");return}let K=await o.resumeImport(e.id,g.id,g.version,F.schemaVersion);if(D.current=!1,!T.current)return;if(y(!1),K.ok)R(K.data),J(K.data);else m(K.error.message)}async function re(F){if(!g)return;let K=await o.importErrors(e.id,g.id,{limit:100,...F===void 0?{}:{cursor:F},expectedVersion:g.version});if(!T.current)return;if(K.ok)_(K.data);else m(K.error.message)}async function j(F=!1){if(w||D.current)return;D.current=!0,y(!0),m("");let K=F&&g?await o.exportImportErrors(e.id,g.id):await o.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:A});if(D.current=!1,!T.current)return;if(y(!1),K.ok)ka(K.data),m(`${K.data.rowCount} rows downloaded${K.data.protectedCells?`; ${K.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else m(K.error.message)}return be("details",{className:"min-w-0 rounded-lg border p-4",children:[le("summary",{className:"cursor-pointer text-sm font-medium",children:"CSV import and export"}),be("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[be("div",{className:"flex flex-wrap items-center gap-3",children:[le("button",{type:"button",disabled:w||!t.length,onClick:()=>void j(),children:"Export CSV"}),be("label",{className:"flex items-center gap-2 text-sm",children:[le("input",{type:"checkbox",checked:A,onChange:(F)=>U(F.target.checked)}),"Spreadsheet view"]})]}),le("p",{className:"text-xs text-muted-foreground",children:"Export all matching records and visible columns from the active query. Spreadsheet view prefixes potentially active text with a tab and changes those values; application support varies. Turn it off for exact text. Limit: 100,000 rows or 20 MiB."}),!i&&be(Ra,{children:[be("label",{className:"flex min-w-0 flex-col gap-2 text-sm",children:["CSV file",le("input",{"aria-label":"CSV file",className:"max-w-full",type:"file",accept:".csv,text/csv",disabled:w,onChange:async(F)=>{let K=F.target.files?.[0];if(!K)return;if(m(""),u(null),p(null),k.current=null,K.size>20971520){m("Choose a UTF-8 CSV file no larger than 20 MiB.");return}y(!0),D.current=!0;try{let ee=new TextDecoder("utf-8",{fatal:!0}).decode(await K.arrayBuffer());if(T.current)p({fileName:K.name,csv:ee,expectedSchemaVersion:e.schemaVersion})}catch{if(T.current)m("The file must be valid UTF-8 text.")}finally{if(D.current=!1,T.current)y(!1)}}})]}),s&&be("div",{className:"flex flex-wrap gap-3",children:[le("span",{className:"break-all text-sm",children:s.fileName}),le("button",{type:"button",disabled:w,onClick:()=>void O(),children:"Preview CSV"})]}),le("p",{className:"text-xs text-muted-foreground",children:"Insert into this collection. Existing records and options stay unchanged. Dates: ISO or YYYY-MM-DD; selections: IDs or names; multi-select: JSON array or semicolon list; linked records: JSON IDs. Blank non-text cells become null. Computed columns are skipped. Invalid rows are skipped with downloadable errors."}),c&&s&&be("div",{className:"flex min-w-0 flex-col gap-3",children:[be("p",{className:"text-sm",children:[c.totalRows," rows · ",c.validRows," valid · ",c.invalidRows," ","invalid · ",c.ignoredColumns.length," skipped columns"]}),c.headers.map((F,K)=>be("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[be("span",{className:"max-w-64 break-all",children:["Column ",K+1,": ",F||"(empty)"]}),be("select",{"aria-label":`Column ${K+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:s.mapping?.[K]??"",disabled:w,onChange:(ee)=>{let de=[...s.mapping??c.mapping];de[K]=ee.target.value||null,p({...s,mapping:de}),u(null),k.current=null},children:[le("option",{value:"",children:"Skip column"}),e.fields.filter((ee)=>!Ne(ee)).map((ee)=>be("option",{value:ee.id,children:[ee.name," (",ee.id,")",ee.required?" · required":""]},ee.id))]})]},`${K}:${F}`)),c.missingRequiredFieldIds.length>0&&be("p",{role:"alert",children:["Map required fields: ",c.missingRequiredFieldIds.join(", ")]}),le("div",{className:"max-w-full overflow-x-auto",children:be("table",{className:"w-full text-xs",children:[be("caption",{children:["First ",c.sample.length," normalized rows; row numbers include the header."]}),le("thead",{children:be("tr",{children:[le("th",{children:"Row"}),le("th",{children:"Normalized values"}),le("th",{children:"Error"})]})}),le("tbody",{children:c.sample.map((F)=>be("tr",{children:[le("td",{children:F.rowNumber}),le("td",{className:"max-w-96 break-all",children:wa(F.values)}),le("td",{children:F.error?.code??""})]},F.rowNumber))})]})}),le("button",{type:"button",className:"self-start",disabled:w||!c.totalRows||c.missingRequiredFieldIds.length>0,onClick:()=>void ie(),children:"Confirm import"})]}),be("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",be("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:g?.id??"",disabled:w,onChange:async(F)=>{if(!F.target.value){x(null);return}let K=await o.importJob(e.id,F.target.value);if(T.current)if(K.ok)R(K.data),M(!1);else m(K.error.message)},children:[le("option",{value:"",children:"Choose saved progress…"}),C.map((F)=>be("option",{value:F.id,children:[F.fileName," · ",F.processedRows,"/",F.totalRows," · ",F.status]},F.id))]})]}),le("button",{type:"button",className:"self-start",disabled:w,onClick:async()=>{let F=await o.imports(e.id);if(T.current)if(F.ok)v(F.data);else m(F.error.message)},children:"Refresh saved imports"}),g&&be("div",{className:"flex flex-col gap-3",children:[be("p",{role:"status",children:[S?"Importing":g.status==="ready"?"Paused":g.status==="schemaChanged"?"Schema changed — confirm before continuing":g.status==="completed"?"Completed":"Cancelled"," ","· ",g.processedRows," of ",g.totalRows," processed · ",g.importedRows," imported ·"," ",g.failedRows," failed"]}),le("progress",{"aria-label":"Import progress",max:g.totalRows,value:g.processedRows,className:"max-w-full"}),le("p",{className:"text-xs text-muted-foreground",children:"Closing this page pauses new batches. An in-flight batch may finish. Resume saved progress after signing in with the same credential. Imported records remain if you cancel."}),be("div",{className:"flex flex-wrap gap-3",children:[S&&le("button",{type:"button",onClick:()=>{Y.current=!1,N(!1)},children:"Pause import"}),!S&&(g.status==="ready"||g.status==="schemaChanged")&&le("button",{type:"button",disabled:w,onClick:()=>void z(),children:g.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(g.status==="ready"||g.status==="schemaChanged")&&le("button",{type:"button",disabled:w,onClick:()=>M(!0),children:"Cancel import"}),le("button",{type:"button",disabled:w||!g.failedRows,onClick:()=>void re(),children:"Show import errors"}),le("button",{type:"button",disabled:w||!g.failedRows,onClick:()=>void j(!0),children:"Download all import errors"})]}),G&&be("div",{children:[be("p",{children:["Stop remaining rows? The ",g.importedRows," imported records will remain."]}),le("button",{type:"button",disabled:w,onClick:async()=>{D.current=!0,y(!0);let F=await o.cancelImport(e.id,g.id);if(D.current=!1,!T.current)return;if(y(!1),F.ok)R(F.data),M(!1);else m(F.error.message)},children:"Confirm cancellation"}),le("button",{type:"button",onClick:()=>M(!1),children:"Keep import"})]}),E&&be("div",{className:"max-w-full overflow-x-auto",children:[be("table",{className:"w-full text-xs",children:[be("caption",{children:[E.total," failed rows"]}),le("thead",{children:be("tr",{children:[le("th",{children:"Row"}),le("th",{children:"Field"}),le("th",{children:"Error"})]})}),le("tbody",{children:E.items.map((F)=>be("tr",{children:[le("td",{children:F.rowNumber}),le("td",{children:F.fieldId??""}),le("td",{children:F.code})]},F.rowNumber))})]}),E.nextCursor!==null&&le("button",{type:"button",onClick:()=>void re(E.nextCursor??void 0),children:"Next errors"})]})]})]}),P&&le("p",{role:"alert",className:"break-words text-sm",children:P})]})]})}import{useEffect as Gr,useRef as Ot,useState as Lt}from"react";import{jsx as Pe,jsxs as qe,Fragment as Ia}from"react/jsx-runtime";var An=[{type:"singleLineText",label:"Text"},{type:"longText",label:"Long text"},{type:"number",label:"Number"},{type:"checkbox",label:"Boolean"},{type:"date",label:"Date"},{type:"singleSelect",label:"Single select"},{type:"multipleSelect",label:"Multiple select"}];function Sa({descriptor:e,client:t,onConverted:n}){let o=e.fields.filter((R)=>An.some((J)=>J.type===R.type)),[i,r]=Lt(o[0]?.id??""),a=o.find((R)=>R.id===i)??o[0],[d,s]=Lt(a?.type??"singleLineText"),[p,c]=Lt(a?.required??!1),[u,g]=Lt(a?.options?.map((R)=>`${R.id}=${R.name}`).join(`
5
+ `)??""),[x,C]=Lt(null),[v,P]=Lt(""),[m,w]=Lt(!1),y=Ot(null),S=Ot(null),N=Ot(0),A=Ot(e);A.current=e;let U=y.current?.field??a,E=m||y.current!==null,_=`${e.id}:${e.schemaVersion}:${JSON.stringify(e.fields)}`,G=Ot(e.fields);G.current=e.fields;let M=Ot(_);M.current=_;let T=Ot(!0);Gr(()=>(T.current=!0,()=>{T.current=!1,N.current++}),[]),Gr(()=>{if(M.current!==_)return;if(y.current&&S.current===e.id)return;N.current++;let R=G.current.find((J)=>J.id===i&&An.some((O)=>O.type===J.type))??G.current.find((J)=>An.some((O)=>O.type===J.type));if(R)r(R.id),s(R.type),c(R.required??!1),g(R.options?.map((J)=>`${J.id}=${J.name}`).join(`
6
+ `)??"");C(null),y.current=null,S.current=null,P(""),w(!1)},[_,i,e.id]);let Y=()=>{C(null),y.current=null,S.current=null,N.current++,P("")},D=(R)=>{r(R.id),s(R.type),c(R.required??!1),g(R.options?.map((J)=>`${J.id}=${J.name}`).join(`
7
+ `)??""),Y()};if(!U)return null;let k=()=>{let R={id:U.id,name:U.name,type:d,required:p};if(d==="singleSelect"||d==="multipleSelect")R.options=u.split(`
8
+ `).filter((J)=>J.trim()).map((J)=>{let O=J.indexOf("=");if(O<1)throw Error("Each option must use stable_id=Display name.");return{id:J.slice(0,O).trim(),name:J.slice(O+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:R}},Q=()=>T.current&&M.current===_;return qe("details",{className:"rounded-lg border p-4",children:[Pe("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),qe("div",{className:"mt-4 flex flex-col gap-3",children:[Pe("p",{className:"text-sm",children:"Preview every existing record before changing the field. Invalid values or a changed preview block confirmation. All record versions advance together."}),qe("label",{children:["Field"," ",qe("select",{"aria-label":"Conversion field",value:U.id,disabled:E,onChange:(R)=>{let J=o.find((O)=>O.id===R.target.value);if(J)D(J)},children:[y.current&&!o.some((R)=>R.id===U.id)&&Pe("option",{value:U.id,children:U.name}),o.map((R)=>Pe("option",{value:R.id,children:R.name},R.id))]})]}),qe("label",{children:["Target type"," ",Pe("select",{"aria-label":"Conversion target type",value:d,disabled:E,onChange:(R)=>{s(R.target.value),Y()},children:An.map((R)=>Pe("option",{value:R.type,children:R.label},R.type))})]}),qe("label",{children:[Pe("input",{type:"checkbox",checked:p,disabled:E,onChange:(R)=>{c(R.target.checked),Y()}})," ","Required after conversion"]}),(d==="singleSelect"||d==="multipleSelect")&&qe("label",{children:["Stable option IDs and display names",Pe("textarea",{"aria-label":"Conversion options",className:"block w-full rounded border p-2",disabled:E,value:u,onChange:(R)=>{g(R.target.value),Y()},placeholder:`open=Open
9
+ done=Done`})]}),v&&Pe("p",{role:"alert",className:"text-sm text-destructive",children:v}),Pe("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:E,onClick:async()=>{let R;try{R=k()}catch(J){P(J instanceof Error?J.message:"Invalid conversion options.");return}w(!0),P(""),C(null),y.current=null;try{let J=await t.previewConversion(e.id,R);if(!Q())return;if(J.ok)C(J.data);else P(J.error.message)}catch{if(Q())P("Preview unavailable. Your draft is kept.")}finally{if(Q())w(!1)}},children:m?"Working…":"Preview conversion"}),x&&qe(Ia,{children:[qe("p",{role:"status",children:[x.validRows," valid · ",x.invalidRows," invalid"]}),qe("p",{className:"text-xs",children:["Preview covers ",x.totalRows," records. Samples and errors show at most 20 records."]}),Pe("div",{className:"overflow-x-auto",children:qe("table",{className:"w-full text-sm",children:[Pe("thead",{children:qe("tr",{children:[Pe("th",{children:"Record"}),Pe("th",{children:"Before"}),Pe("th",{children:"After"}),Pe("th",{children:"Error"})]})}),Pe("tbody",{children:x.sample.map((R)=>qe("tr",{children:[Pe("td",{className:"max-w-32 break-all",children:R.id}),Pe("td",{className:"max-w-48 break-words",children:JSON.stringify(R.before)}),Pe("td",{className:"max-w-48 break-words",children:JSON.stringify(R.after)}),Pe("td",{children:R.error})]},R.id))})]})}),x.errors.length>0&&Pe("ul",{children:x.errors.map((R)=>qe("li",{children:[Pe("span",{className:"break-all",children:R.id}),": ",Pe("span",{children:R.code})]},R.id))}),Pe("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:m||x.invalidRows>0,onClick:async()=>{if(!y.current)S.current=e.id,N.current++;y.current??={expectedSchemaVersion:x.schemaVersion,field:x.field,previewToken:x.previewToken,idempotencyKey:crypto.randomUUID()};let R=y.current,J=N.current,O=()=>T.current&&A.current.id===e.id&&J===N.current;w(!0),P("");try{let ie=await t.convertField(e.id,R);if(!O())return;if(ie.ok){if(C(null),y.current=null,S.current=null,ie.data.descriptor.schemaVersion>=A.current.schemaVersion)n(ie.data.descriptor)}else if(P(ie.error.message),ie.error.status===409)C(null),y.current=null,S.current=null}catch{if(O())P("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(O())w(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as Aa,useRef as bo,useState as Wr}from"react";import{jsx as Yr,jsxs as Da}from"react/jsx-runtime";function Ea({collectionIds:e,client:t,onChanges:n,pollIntervalMs:o=2000}){let i=JSON.stringify([...new Set(e)].sort()),r=bo(i);r.current=i;let a=bo(n);a.current=n;let d=bo(()=>{}),[s,p]=Wr("connecting"),[c,u]=Wr(!1);return Aa(()=>{let g=JSON.parse(i),x=new Map,C=!1,v=!1,P=0,m,w=()=>!C&&r.current===i,y=Math.max(50,Math.min(60000,o)),S=async()=>{if(!w()||v)return;v=!0,u(!0);let U=!1;try{let E=P>0;for(let _ of g){let G=x.get(_),M=await t.changes(_,{...G!==void 0?{cursor:G}:{},limit:100});if(!w())return;if(!M.ok)throw p(M.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let T=G===void 0;if(T||E||M.data.items.length>0)await a.current(_,M.data,T);if(!w())return;x.set(_,M.data.cursor),U||=M.data.hasMore}P=0,p("live")}catch{if(P++,w())p((E)=>E==="expired"?"expired":"offline")}finally{if(v=!1,w())u(!1),m=setTimeout(()=>{S()},U&&P===0?0:Math.min(30000,y*2**Math.min(P,8)))}},N=()=>{if(m!==void 0)clearTimeout(m);S()};d.current=N,p("connecting"),S();let A=()=>{if(document.visibilityState==="visible")N()};return window.addEventListener("online",N),document.addEventListener("visibilitychange",A),()=>{if(C=!0,m!==void 0)clearTimeout(m);window.removeEventListener("online",N),document.removeEventListener("visibilitychange",A)}},[i,t,o]),Da("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[Yr("p",{role:"status",children:s==="live"?"Live updates":s==="connecting"?"Connecting live updates…":s==="expired"?"Session expired. Renew your session; drafts are kept.":"Connection interrupted. Drafts are kept."}),(s==="offline"||s==="expired")&&Yr("button",{type:"button",className:"rounded border px-2 py-1",disabled:c,onClick:()=>d.current(),children:"Reconnect now"})]})}import{useEffect as En,useRef as St,useState as He}from"react";import{jsx as ce,jsxs as Ce,Fragment as vo}from"react/jsx-runtime";var ho={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function sn(e){try{return await e()}catch{return{ok:!1,error:ho}}}function Co({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return Ce("div",{className:"min-w-0",children:[ce("strong",{children:t}),ce("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-words rounded border p-2 text-xs",children:n.slice(0,16000)}),n.length>16000&&Ce(vo,{children:[ce("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),ce("button",{type:"button",onClick:()=>{let o=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),i=document.createElement("a");i.href=o,i.download=`record-${e?.id}-${e?.version}.json`,i.click(),setTimeout(()=>URL.revokeObjectURL(o),1000)},children:"Download snapshot"})]})]})}function Ta({descriptor:e,recordId:t,client:n,readOnly:o=!1,onCommitted:i,registerRefresh:r}){let[a,d]=He(null),[s,p]=He(null),[c,u]=He(null),[g,x]=He(),[C,v]=He(),[P,m]=He([]),[w,y]=He([]),[S,N]=He(""),[A,U]=He(null),[E,_]=He(null),[G,M]=He(null),[T,Y]=He(!1),[D,k]=He(""),Q=St(null),R=St(null),J=St(n);J.current=n;let O=St(!1),ie=St(0),z=`${e.id}:${t}`,re=St(z);re.current=z;let j=St({historyBefore:g,commentBefore:C});j.current={historyBefore:g,commentBefore:C};let F=St(async()=>{}),K=(b=z)=>O.current&&re.current===b&&J.current===n,ee=async()=>{let b=z,q=++ie.current,Z=j.current,[Oe,Ye]=await Promise.all([sn(()=>n.history(e.id,t,{...Z.historyBefore===void 0?{}:{before:Z.historyBefore},limit:20})),sn(()=>n.comments(e.id,t,{...Z.commentBefore===void 0?{}:{before:Z.commentBefore},limit:50}))]);if(!K(b)||q!==ie.current)throw Error("Refresh superseded");if(!Oe.ok||!Ye.ok)throw k(!Oe.ok?Oe.error.message:!Ye.ok?Ye.error.message:ho.message),Error("Activity refresh failed");p(Oe.data),u(Ye.data),d(b)};F.current=ee,En(()=>(O.current=!0,()=>{O.current=!1,ie.current++}),[]),En(()=>(r?.(()=>F.current()),()=>r?.(null)),[r]),En(()=>{if(re.current!==z)return;p(null),u(null),d(null),x(void 0),v(void 0),m([]),y([]),j.current={historyBefore:void 0,commentBefore:void 0},N(""),U(null),_(null),M(null),Q.current=null,R.current=null,Y(!1),k("")},[z]),En(()=>{if(re.current!==z||J.current!==n||j.current.historyBefore!==g||j.current.commentBefore!==C)return;F.current().catch(()=>{})},[z,n,g,C]);let de=(b)=>{let q=Q.current;if(q?.signature===b)return q.key;let Z={signature:b,key:crypto.randomUUID()};return Q.current=Z,Z.key},me=async(b)=>{if(T||o||!c||a!==z)return;let q=b==="delete"?E:A;if(b!=="create"&&(!q||q.authorId!==c.actorId))return;let Z=b==="create"?S:A?.draft??"";if(b!=="delete"&&(!Z.trim()||Z.length>4000||Z.includes("\x00"))){k("Comments require 1–4,000 characters.");return}let Oe=de(JSON.stringify([b,q?.id,q?.version,Z]));Y(!0),k("");let Ye=await sn(async()=>{if(b==="create")return n.createComment(e.id,t,{text:Z,idempotencyKey:Oe});if(!q)return{ok:!1,error:ho};if(b==="edit")return n.editComment(e.id,t,q.id,{text:Z,expectedVersion:q.version,idempotencyKey:Oe});return n.deleteComment(e.id,t,q.id,{expectedVersion:q.version,idempotencyKey:Oe})});if(!K())return;if(Y(!1),!Ye.ok){k(Ye.error.message);return}if(Q.current=null,b==="create")N("");else if(b==="edit")U(null);else _(null);if(b==="create"&&C!==void 0)v(void 0),y([]);else await F.current().catch(()=>{})},X=async(b)=>{if(T||o||!s||a!==z)return;Y(!0),k(""),R.current=null;let q={targetVersion:b,expectedCurrentVersion:s.currentVersion,expectedSchemaVersion:e.schemaVersion},Z=await sn(()=>n.previewUndo(e.id,t,q));if(!K())return;if(Y(!1),Z.ok)M(Z.data);else M(null),k(Z.error.message)},we=async()=>{if(T||o||a!==z||!G&&!R.current)return;let b=R.current;if(!b){if(!G)return;b={targetVersion:G.targetVersion,expectedCurrentVersion:G.currentVersion,expectedSchemaVersion:G.schemaVersion,idempotencyKey:crypto.randomUUID()},R.current=b}let q=b;Y(!0),k("");let Z=await sn(()=>n.undo(e.id,t,q));if(!K())return;if(Y(!1),!Z.ok){if(Z.error.code==="version_conflict"||Z.error.code==="reference_conflict"||Z.error.code==="validation")R.current=null,M(null);k(Z.error.message),await F.current().catch(()=>{});return}R.current=null,M(null),i(Z.data),x(void 0),m([]),await F.current().catch(()=>{})},ae=c?.items.find((b)=>b.id===A?.id),Se=A&&ae&&ae.version!==A.version,L=G&&(G.currentVersion!==s?.currentVersion||G.schemaVersion!==e.schemaVersion);return Ce("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[Ce("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ce("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),ce("button",{type:"button",disabled:T,onClick:()=>{k(""),F.current().catch(()=>{})},children:"Refresh activity"})]}),D&&ce("p",{role:"alert",className:"text-sm text-destructive",children:D}),!s||!c||a!==z?ce("p",{role:"status",children:"Loading record activity…"}):Ce(vo,{children:[Ce("p",{role:"status",children:["Current version ",s.currentVersion,s.currentDeleted?" · Deleted record":""]}),ce("h3",{className:"font-medium",children:"Comments"}),c.items.length===0&&ce("p",{className:"text-sm",children:"No comments yet."}),ce("ol",{className:"flex flex-col gap-3",children:c.items.map((b)=>Ce("li",{className:"min-w-0 rounded border p-3",children:[Ce("p",{className:"break-all text-xs",children:[b.authorId," · ",b.updatedAt," · version ",b.version]}),ce("p",{className:"whitespace-pre-wrap break-words text-sm",children:b.text??"Comment deleted"}),!o&&b.text!==null&&b.authorId===c.actorId&&Ce("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:T,onClick:()=>{U({...b,draft:b.text??""}),_(null),Q.current=null},children:"Edit comment"}),ce("button",{type:"button",disabled:T,onClick:()=>{_(b),U(null),Q.current=null},children:"Delete comment"})]})]},b.id))}),Ce("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:T||!w.length,onClick:()=>{v(w.at(-1)),y((b)=>b.slice(0,-1))},children:"Newer comments"}),ce("button",{type:"button",disabled:T||c.nextCursor===null,onClick:()=>{y((b)=>[...b,C]),v(c.nextCursor??void 0)},children:"Older comments"})]}),!o&&Ce(vo,{children:[A&&Ce("div",{className:"flex flex-col gap-2",children:[Ce("label",{children:["Edit comment text",ce("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:T,maxLength:4000,value:A.draft,onChange:(b)=>{U({...A,draft:b.target.value}),Q.current=null}})]}),Se&&Ce("div",{role:"status",children:[ce("p",{children:"This comment changed. Your draft and original version are kept."}),Ce("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",ae.text??"Comment deleted"]}),ae.text!==null&&ae.authorId===c.actorId&&ce("button",{type:"button",disabled:T,onClick:()=>{U({...ae,draft:A.draft}),Q.current=null},children:"Use current comment version"})]}),Ce("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:T||A.authorId!==c.actorId,onClick:()=>void me("edit"),children:"Save comment"}),ce("button",{type:"button",disabled:T,onClick:()=>{U(null),Q.current=null},children:"Cancel comment edit"})]})]}),E&&Ce("div",{children:[ce("p",{children:"Delete this comment? A deletion marker will remain."}),ce("p",{className:"whitespace-pre-wrap break-words",children:E.text}),ce("button",{type:"button",disabled:T||E.authorId!==c.actorId,onClick:()=>void me("delete"),children:"Confirm delete comment"}),ce("button",{type:"button",disabled:T,onClick:()=>_(null),children:"Cancel delete comment"})]}),Ce("label",{children:["New comment",ce("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:T,maxLength:4000,value:S,onChange:(b)=>{N(b.target.value),Q.current=null}})]}),ce("button",{type:"button",className:"self-start",disabled:T||!S.trim(),onClick:()=>void me("create"),children:"Add comment"})]}),ce("h3",{className:"font-medium",children:"Record history"}),ce("p",{className:"text-xs",children:"Stored writable values at each version. Live computed values are excluded. A legacy baseline has an unknown author; earlier versions cannot be recovered."}),ce("ol",{className:"flex flex-col gap-3",children:s.items.map((b)=>Ce("li",{className:"min-w-0 rounded border p-3",children:[Ce("p",{className:"break-all text-xs",children:["Version ",b.version," · ",b.operation," · schema ",b.schemaVersion," · ",b.actorId," ·"," ",b.createdAt]}),Ce("details",{children:[Ce("summary",{children:["Stored values at version ",b.version]}),ce(Co,{record:b.snapshot,label:`Version ${b.version}`})]}),!o&&b.version<s.currentVersion&&Ce("button",{type:"button",disabled:T,onClick:()=>void X(b.version),children:["Preview restore version ",b.version]})]},b.id))}),Ce("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:T||!P.length,onClick:()=>{x(P.at(-1)),m((b)=>b.slice(0,-1))},children:"Newer history"}),ce("button",{type:"button",disabled:T||s.nextCursor===null,onClick:()=>{m((b)=>[...b,g]),x(s.nextCursor??void 0)},children:"Older history"})]}),!o&&G&&Ce("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[Ce("h3",{children:["Restore version ",G.targetVersion," as a new version"]}),Ce("p",{children:["Current version ",G.currentVersion," · schema ",G.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),Ce("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[ce(Co,{record:G.before,label:"Current stored values"}),ce(Co,{record:G.target,label:"Values to restore"})]}),L&&!R.current&&ce("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),Ce("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:T||!!L&&!R.current,onClick:()=>void we(),children:R.current?"Retry undo":"Confirm restore"}),ce("button",{type:"button",disabled:T,onClick:()=>{M(null),R.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as Dn,useRef as It,useState as bt}from"react";import{jsx as Ve,jsxs as Ke,Fragment as Jr}from"react/jsx-runtime";async function Tn(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Attachments are unavailable. Your selected file has been kept."}}}}async function Fa(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let o of t)n+=String.fromCharCode(o);return btoa(n)}function Na({collectionId:e,recordId:t,client:n,readOnly:o=!1,registerRefresh:i}){let r=`${e}:${t}`,a=It({identity:r,client:n});a.current={identity:r,client:n};let d=It(!1),s=It(0),p=It(0),[c,u]=bt(null),[g,x]=bt(null),[C,v]=bt(),[P,m]=bt([]),w=It(C);w.current=C;let[y,S]=bt(null),[N,A]=bt(null),U=It(null),E=It(null),[_,G]=bt(!1),[M,T]=bt(!1),[Y,D]=bt(""),k=()=>d.current&&a.current.identity===r&&a.current.client===n,Q=async()=>{let z=++s.current,re=await Tn(()=>n.list(e,t,{limit:20,...w.current===void 0?{}:{before:w.current}}));if(!k()||z!==s.current)throw Error("Refresh superseded");if(!re.ok)throw D(re.error.message),Error("Attachment refresh failed");x(re.data),u(r)},R=It(Q);R.current=Q,Dn(()=>(d.current=!0,()=>{d.current=!1,++s.current,++p.current}),[]),Dn(()=>{if(a.current.identity!==r||a.current.client!==n)return;u(null),x(null),S(null),A(null),U.current=null,G(!1),T(!1),D(""),v(void 0),m([]),w.current=void 0,++p.current,R.current().catch(()=>{})},[r,n]),Dn(()=>{if(w.current===C&&c===r)R.current().catch(()=>{})},[C,r,c]),Dn(()=>(i?.(()=>R.current()),()=>i?.(null)),[i]);let J=async()=>{if(_||o||!y||c!==r)return;let z=y;G(!0),D("");let re=await Tn(()=>n.upload(e,t,z));if(!k())return;if(G(!1),!re.ok){D(re.error.message);return}if(S(null),E.current)E.current.value="";v(void 0),m([]),w.current=void 0,await R.current().catch(()=>{})},O=async()=>{if(_||o||!N||N.authorId!==g?.actorId||c!==r)return;U.current??=crypto.randomUUID();let z=N,re=U.current;G(!0),D("");let j=await Tn(()=>n.delete(e,t,z.id,{expectedVersion:z.version,idempotencyKey:re}));if(!k())return;if(G(!1),!j.ok){D(j.error.message),await R.current().catch(()=>{});return}A(null),U.current=null,await R.current().catch(()=>{})},ie=async(z)=>{if(_||c!==r)return;G(!0),D("");let re=await Tn(()=>n.content(e,t,z.id));if(!k())return;if(G(!1),!re.ok){D(re.error.message);return}let j=Uint8Array.from(atob(re.data.base64),(ee)=>ee.charCodeAt(0)),F=URL.createObjectURL(new Blob([j],{type:"application/octet-stream"})),K=document.createElement("a");K.href=F,K.download=re.data.attachment.name,K.click(),setTimeout(()=>URL.revokeObjectURL(F),1000)};return Ke("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Ke("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ve("h3",{className:"font-medium",children:"Attachments"}),Ve("button",{type:"button",disabled:_,onClick:()=>{D(""),R.current().catch(()=>{})},children:"Refresh attachments"})]}),Y&&Ve("p",{role:"alert",children:Y}),!g||c!==r?Ve("p",{role:"status",children:"Loading attachments…"}):Ke(Jr,{children:[g.items.length===0&&Ve("p",{children:"No attachments yet."}),Ve("ol",{className:"flex min-w-0 flex-col gap-2",children:g.items.map((z)=>Ke("li",{className:"min-w-0 rounded border p-2",children:[Ve("p",{className:"break-all",children:z.name}),Ke("p",{className:"break-all text-xs",children:[z.size," bytes · version ",z.version," · ",z.authorId]}),z.deletedAt?Ve("p",{children:"Attachment deleted"}):Ke("div",{className:"flex flex-wrap gap-3",children:[Ve("button",{type:"button",disabled:_,"aria-label":`Download attachment ${z.name}`,onClick:()=>void ie(z),children:"Download"}),!o&&z.authorId===g.actorId&&Ve("button",{type:"button",disabled:_,"aria-label":`Delete attachment ${z.name}`,onClick:()=>{A(z),U.current=null},children:"Delete"})]})]},z.id))}),Ke("div",{className:"flex flex-wrap gap-3",children:[Ve("button",{type:"button",disabled:_||!P.length,onClick:()=>{v(P.at(-1)),m((z)=>z.slice(0,-1))},children:"Newer attachments"}),Ve("button",{type:"button",disabled:_||g.nextCursor===null,onClick:()=>{m((z)=>[...z,C]),v(g.nextCursor??void 0)},children:"Older attachments"})]}),!o&&Ke(Jr,{children:[Ve("p",{className:"text-xs",children:"Up to 1 MiB per file, 20 active files and 5 MiB per record. Files have independent versions; restoring record values does not restore deleted files."}),Ke("label",{children:["Attachment file",Ve("input",{ref:E,"aria-label":"Attachment file",type:"file",disabled:_||M,onChange:async(z)=>{let re=z.target.files?.[0];if(!re)return;let j=++p.current;if(S(null),D(""),!re.size||re.size>1048576){D("Choose a nonempty file up to 1 MiB.");return}T(!0);try{let F=await Fa(re);if(!k()||j!==p.current)return;let K=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(re.type)?re.type:"application/octet-stream";S({name:re.name,contentType:K,base64:F,idempotencyKey:crypto.randomUUID()})}catch{if(k()&&j===p.current)D("The selected file could not be read.")}finally{if(k()&&j===p.current)T(!1)}}},r)]}),y&&Ke("p",{className:"break-all",children:["Selected file: ",y.name]}),Ve("button",{type:"button",className:"self-start",disabled:_||M||!y,onClick:()=>void J(),children:"Upload attachment"}),N&&Ke("div",{children:[Ke("p",{className:"break-all",children:["Delete ",N.name,"? This permanently removes its bytes and keeps a deletion marker."]}),Ke("div",{className:"flex flex-wrap gap-3",children:[Ve("button",{type:"button",disabled:_,onClick:()=>void O(),children:"Confirm delete attachment"}),Ve("button",{type:"button",disabled:_,onClick:()=>{A(null),U.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as Fn,useRef as Wt,useState as Ge}from"react";import{jsx as ve,jsxs as Ee,Fragment as Qr}from"react/jsx-runtime";async function xo(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function Ma(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function Oa({descriptor:e,recordIds:t,client:n,linkForGrant:o,registerRefresh:i}){let r=e.id,a=Wt({identity:r,client:n});a.current={identity:r,client:n};let d=Wt(!1),s=Wt(0),[p,c]=Ge(null),[u,g]=Ge(null),[x,C]=Ge(),v=Wt(x);v.current=x;let[P,m]=Ge([]),[w,y]=Ge([]),[S,N]=Ge([]),[A,U]=Ge(3600),[E,_]=Ge(null),[G,M]=Ge(!1),[T,Y]=Ge(""),[D,k]=Ge(null),Q=Wt(null),[R,J]=Ge(!1),[O,ie]=Ge(""),z=()=>d.current&&a.current.identity===r&&a.current.client===n,re=async()=>{let X=++s.current,we=await xo(()=>n.list(r,{limit:20,...v.current===void 0?{}:{before:v.current}}));if(!z()||X!==s.current)throw Error("Refresh superseded");if(!we.ok)throw ie(we.error.message),Error("Share refresh failed");g(we.data),c(r)},j=Wt(re);j.current=re,Fn(()=>(d.current=!0,()=>{d.current=!1,++s.current}),[]),Fn(()=>{if(a.current.identity!==r||a.current.client!==n)return;c(null),g(null),y([]),N([]),_(null),M(!1),Y(""),k(null),Q.current=null,J(!1),ie(""),C(void 0),m([]),v.current=void 0,j.current().catch(()=>{})},[r,n]),Fn(()=>{if(v.current===x&&p===r)j.current().catch(()=>{})},[x,p,r]),Fn(()=>(i?.(()=>j.current()),()=>i?.(null)),[i]);let F=()=>{if(!G)_(null)},K=async()=>{if(R||!E||p!==r)return;let X=E;J(!0),M(!0),ie("");let we=await xo(()=>n.create(r,X));if(!z())return;if(J(!1),!we.ok){ie(we.error.message);return}Y(o(we.data,X.key)),_(null),M(!1),C(void 0),m([]),v.current=void 0,await j.current().catch(()=>{})},ee=async()=>{if(R||!D||p!==r)return;let X=D;Q.current??=crypto.randomUUID();let we=Q.current;J(!0),ie("");let ae=await xo(()=>n.revoke(r,X.id,{expectedVersion:X.version,idempotencyKey:we}));if(!z())return;if(J(!1),!ae.ok){ie(ae.error.message),await j.current().catch(()=>{});return}k(null),Q.current=null,Y(""),await j.current().catch(()=>{})},de=e.fields.filter((X)=>!["linkedRecord","lookup","formula","rollup"].includes(X.type)),me=R||G;return Ee("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Ee("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[ve("h3",{className:"font-medium",children:"Read-only sharing"}),ve("button",{type:"button",disabled:R,onClick:()=>{ie(""),j.current().catch(()=>{})},children:"Refresh share grants"})]}),ve("p",{className:"text-sm",children:"Select the exact basic fields and stable record IDs. Links expose current selected values until expiry or revocation. Schema changes close access."}),ve("p",{className:"text-xs",children:"Relations, computed fields, attachments, discussions, history and writes are excluded. Up to 100 records, 20 active grants and 24 hours per grant. Keys are shown only when created."}),O&&ve("p",{role:"alert",children:O}),Ee("fieldset",{disabled:me,className:"flex min-w-0 flex-col gap-2",children:[ve("legend",{children:"Fields to share"}),de.map((X)=>Ee("label",{className:"break-all",children:[ve("input",{type:"checkbox","aria-label":`Share field ${X.name}`,checked:w.includes(X.id),onChange:(we)=>{F(),y((ae)=>we.target.checked?[...ae,X.id]:ae.filter((Se)=>Se!==X.id))}})," ",X.name]},X.id))]}),Ee("fieldset",{disabled:me,className:"flex min-w-0 flex-col gap-2",children:[ve("legend",{children:"Records on the current page"}),t.slice(0,100).map((X)=>Ee("label",{className:"break-all",children:[ve("input",{type:"checkbox","aria-label":`Share record ${X}`,checked:S.includes(X),onChange:(we)=>{F(),N((ae)=>we.target.checked?[...ae,X]:ae.filter((Se)=>Se!==X))}})," ",X]},X)),t.length===0&&ve("p",{children:"Load records in Grid to choose a share scope."})]}),Ee("p",{className:"break-all text-xs",children:["Selected record IDs: ",S.join(", ")||"none"]}),Ee("label",{children:["Link lifetime"," ",Ee("select",{"aria-label":"Share link lifetime",disabled:me,value:A,onChange:(X)=>{F(),U(Number(X.target.value))},children:[ve("option",{value:60,children:"1 minute"}),ve("option",{value:3600,children:"1 hour"}),ve("option",{value:86400,children:"24 hours"})]})]}),ve("button",{type:"button",className:"self-start",disabled:me||p!==r||!w.length||!S.length||S.length>100||w.some((X)=>!de.some((we)=>we.id===X)),onClick:()=>{ie("");try{_({expectedSchemaVersion:e.schemaVersion,fieldIds:[...w],recordIds:[...S],expiresInSeconds:A,key:Ma(),idempotencyKey:crypto.randomUUID()})}catch{ie("A secure share key could not be generated.")}},children:"Review read-only share"}),E&&Ee("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[Ee("p",{className:"break-all",children:["Confirm schema ",E.expectedSchemaVersion,", fields ",E.fieldIds.join(", "),", records ",E.recordIds.join(", ")," for ",E.expiresInSeconds," seconds."]}),E.expectedSchemaVersion!==e.schemaVersion&&ve("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),Ee("div",{className:"flex flex-wrap gap-3",children:[ve("button",{type:"button",disabled:R,onClick:()=>void K(),children:G?"Retry create read link":"Create read link"}),ve("button",{type:"button",disabled:R,onClick:()=>{_(null),M(!1),ie("")},children:"Discard share confirmation"})]}),G&&ve("p",{className:"text-xs",children:"If the response was lost, retry returns the same grant. A discarded committed grant remains in the directory and can be revoked."})]}),T&&Ee("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",ve("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:T,onFocus:(X)=>X.target.select()})]}),!u||p!==r?ve("p",{role:"status",children:"Loading share grants…"}):Ee(Qr,{children:[u.items.length===0&&ve("p",{children:"No share grants yet."}),ve("ol",{className:"flex min-w-0 flex-col gap-2",children:u.items.map((X)=>Ee("li",{className:"min-w-0 rounded border p-2",children:[Ee("p",{className:"break-all",children:["Grant ",X.id," · version ",X.version," · schema ",X.schemaVersion]}),Ee("p",{className:"break-all text-xs",children:["Fields: ",X.fieldIds.join(", ")," · Records: ",X.recordIds.join(", ")," · Expires:"," ",X.expiresAt]}),X.revokedAt?ve("p",{children:"Share revoked"}):Ee(Qr,{children:[ve("p",{children:X.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(X.expiresAt)<=Date.now()?"Share expired":"Share active"}),ve("button",{type:"button",disabled:R,"aria-label":`Revoke share ${X.id}`,onClick:()=>{k(X),Q.current=null},children:"Revoke"})]})]},X.id))}),Ee("div",{className:"flex flex-wrap gap-3",children:[ve("button",{type:"button",disabled:R||!P.length,onClick:()=>{C(P.at(-1)),m((X)=>X.slice(0,-1))},children:"Newer share grants"}),ve("button",{type:"button",disabled:R||u.nextCursor===null,onClick:()=>{m((X)=>[...X,x]),C(u.nextCursor??void 0)},children:"Older share grants"})]})]}),D&&Ee("div",{children:[Ee("p",{className:"break-all",children:["Revoke grant ",D.id," at version ",D.version,"? Every existing share session will lose access."]}),Ee("div",{className:"flex flex-wrap gap-3",children:[ve("button",{type:"button",disabled:R,onClick:()=>void ee(),children:"Confirm revoke share"}),ve("button",{type:"button",disabled:R,onClick:()=>{k(null),Q.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as Zr,useRef as Yt,useState as _e}from"react";import{jsx as pe,jsxs as De}from"react/jsx-runtime";var Xr=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],La=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function Va({descriptor:e,recordIds:t,client:n,webhookRequest:o}){let i=e.id,r=Yt({id:i,client:n});r.current={id:i,client:n};let a=Yt(!0),d=Yt(0),[s,p]=_e([]),[c,u]=_e(""),g=Yt(c);g.current=c;let[x,C]=_e(null),[v,P]=_e(),m=Yt(v);m.current=v;let[w,y]=_e(""),[S,N]=_e("record"),[A,U]=_e(60),[E,_]=_e([]),[G,M]=_e([]),[T,Y]=_e({}),[D,k]=_e(null),[Q,R]=_e(!1),[J,O]=_e(!1),[ie,z]=_e(""),[re,j]=_e(""),F=()=>a.current&&r.current.id===i&&r.current.client===n,K=async(L)=>{try{return await L()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},ee=async()=>{let L=++d.current,b=await K(()=>n.list(i));if(!F()||L!==d.current)return;if(!b.ok){z(b.error.message);return}p(b.data);let q=b.data.find((Oe)=>Oe.id===g.current)?.id??b.data[0]?.id??"";if(g.current=q,u(q),!q){C(null);return}let Z=await K(()=>n.runs(i,q,{limit:20,...m.current?{before:m.current}:{}}));if(!F()||L!==d.current||g.current!==q)return;if(Z.ok)C(Z.data);else z(Z.error.message)},de=Yt(ee);de.current=ee,Zr(()=>{if(r.current.id!==i||r.current.client!==n)return;a.current=!0,de.current();let L=setInterval(()=>void de.current(),5000);return()=>{a.current=!1,++d.current,clearInterval(L)}},[i,n]),Zr(()=>{if(g.current!==c||m.current!==v)return;de.current()},[c,v]);let me=()=>{if(z(""),!w.trim()||!E.length||S!=="record"&&!G.length){z("Choose a name, writable fields, and target records for time or webhook triggers.");return}let L=Object.fromEntries(E.map((q)=>[q,T[q]??null])),b={expectedSchemaVersion:e.schemaVersion,name:w.trim(),trigger:S==="time"?{kind:S,intervalSeconds:A}:{kind:S},targetRecordIds:G,values:L,idempotencyKey:crypto.randomUUID(),...S==="webhook"?{webhookKey:La()}:{}};k({kind:"create",input:b}),R(!1)},X=(L)=>{k(L),R(!1),z("")},we=async()=>{if(!D||J)return;let L=D,b=Q;R(!0),O(!0),z("");let q=await K(()=>L.kind==="create"?n.create(i,L.input):L.kind==="toggle"?n.toggle(i,L.a.id,L.input):L.kind==="run"?n.runNow(i,L.a.id,L.input):n.retry(i,L.a.id,L.run.id,L.input));if(!F())return;if(O(!1),!q.ok){if(!b&&q.error.status>=400&&q.error.status<500)R(!1);z(`${q.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(L.kind==="create"){let Z=q.data;if(g.current=Z.id,u(Z.id),L.input.webhookKey&&o)j(JSON.stringify(o(Z,L.input.webhookKey),null,2));y(""),_([]),M([]),Y({})}k(null),R(!1),m.current=void 0,P(void 0),await de.current()},ae=s.find((L)=>L.id===c),Se=!!D||J;return De("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[pe("p",{children:"Update chosen fields through record changes, a timed interval or a private webhook. Runs keep their original schema and record versions. Automatic changes do not trigger another automation."}),pe("button",{type:"button",onClick:()=>void de.current(),children:"Refresh automation"}),ie&&pe("p",{role:"alert",children:ie}),pe("form",{onSubmit:(L)=>{L.preventDefault(),me()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:De("fieldset",{disabled:Se,style:{minWidth:0},children:[pe("legend",{children:"New automation"}),De("label",{children:["Name"," ",pe("input",{"aria-label":"Automation name",value:w,maxLength:200,onChange:(L)=>y(L.target.value)})]}),De("label",{children:["Trigger"," ",De("select",{"aria-label":"Automation trigger",value:S,onChange:(L)=>N(L.target.value),children:[pe("option",{value:"record",children:"Record changes"}),pe("option",{value:"time",children:"Timed interval"}),pe("option",{value:"webhook",children:"Private webhook"})]})]}),S==="time"&&De("label",{children:["Interval in seconds"," ",pe("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:A,onChange:(L)=>U(Number(L.target.value))})]}),De("fieldset",{children:[pe("legend",{children:"Fields to update"}),e.fields.filter((L)=>Xr.includes(L.type)).map((L)=>De("label",{style:{display:"block"},children:[pe("input",{type:"checkbox",checked:E.includes(L.id),onChange:(b)=>{_(b.target.checked?[...E,L.id]:E.filter((q)=>q!==L.id))}}),L.name]},L.id))]}),pe(dn,{fields:e.fields.filter((L)=>E.includes(L.id)&&Xr.includes(L.type)),values:T,onChange:Y}),De("fieldset",{children:[pe("legend",{children:"Target records from this page"}),S==="record"&&pe("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&pe("p",{children:"Open a grid page to choose fixed records."}),t.map((L)=>De("label",{style:{display:"block",overflowWrap:"anywhere"},children:[pe("input",{type:"checkbox","aria-label":`Automation target ${L}`,checked:G.includes(L),onChange:(b)=>M(b.target.checked?[...G,L]:G.filter((q)=>q!==L))}),L]},L))]}),pe("button",{type:"submit",children:"Review automation"})]})}),D&&De("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[pe("p",{children:D.kind==="create"?`Create ${D.input.name} using schema ${D.input.expectedSchemaVersion}; ${D.input.targetRecordIds.length||"event"} targets.`:D.kind==="toggle"?`${D.input.enabled?"Enable":"Disable"} ${D.a.name}. Disabling fences queued and running work.`:D.kind==="run"?`Run ${D.a.name} for ${D.input.recordIds.length} explicitly selected records.`:`Retry ${D.a.name}, run ${D.run.sequence}, using its original record versions.`}),D.kind==="create"&&pe("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(D.input.values,null,2)}),pe("button",{type:"button",disabled:J,onClick:()=>void we(),children:J?"Confirming…":Q?"Retry automation confirmation":"Confirm automation"}),pe("button",{type:"button",disabled:Q||J,onClick:()=>k(null),children:"Cancel automation review"}),Q&&pe("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),re&&De("div",{children:[pe("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),pe("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:re}),pe("button",{type:"button",onClick:()=>j(""),children:"Hide webhook key"})]}),s.length>0&&De("label",{children:["Automation"," ",pe("select",{"aria-label":"Selected automation",disabled:Se,value:c,onChange:(L)=>{g.current=L.target.value,m.current=void 0,P(void 0),u(L.target.value),C(null)},children:s.map((L)=>pe("option",{value:L.id,children:L.name},L.id))})]}),ae&&De("div",{children:[De("p",{children:[ae.enabled?"Enabled":"Disabled"," · ",ae.trigger.kind," · schema ",ae.schemaVersion," · configuration ",ae.version]}),pe("button",{type:"button",disabled:Se,onClick:()=>X({kind:"toggle",a:ae,input:{expectedVersion:ae.version,enabled:!ae.enabled,idempotencyKey:crypto.randomUUID()}}),children:ae.enabled?"Review disable automation":"Review enable automation"}),pe("button",{type:"button",disabled:Se||!ae.enabled||!(ae.targetRecordIds.length||t.length),onClick:()=>X({kind:"run",a:ae,input:{recordIds:ae.targetRecordIds.length?ae.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),x&&De("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!x.items.length&&pe("p",{children:"No runs yet."}),x.items.map((L)=>De("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[De("p",{children:["Run ",L.sequence," · ",L.triggerKind," · ",L.status," · step ",L.step]}),De("p",{children:["Attempts: evaluate ",L.stepAttempts.evaluate,", apply ",L.stepAttempts.apply," · original versions: ",L.expectedRows.map((b)=>`${b.id}: ${b.version}`).join(", ")]}),L.errorCode&&pe("p",{role:"status",children:L.errorCode}),L.leaseUntil&&De("p",{children:["Lease expires ",L.leaseUntil]}),ae&&L.status==="failed"&&De("button",{type:"button",disabled:Se||!ae.enabled,onClick:()=>X({kind:"retry",a:ae,run:L,input:{expectedVersion:L.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",L.sequence]})]},L.id)),pe("button",{type:"button",disabled:Se||v===void 0,onClick:()=>{m.current=void 0,P(void 0)},children:"Newest runs"}),pe("button",{type:"button",disabled:Se||x.nextCursor===null,onClick:()=>{m.current=x.nextCursor??void 0,P(m.current)},children:"Older runs"})]})]})}import{useEffect as Ba,useId as Ua,useRef as ei,useState as Be}from"react";import{jsx as he,jsxs as Te}from"react/jsx-runtime";var ti=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function _a(e,t,n){if(!n.resourceId||!n.model.trim()||n.model.length>200||!n.instruction.trim()||new TextEncoder().encode(n.instruction).length>2000||n.recordIds.length<1||n.recordIds.length>10||new Set(n.recordIds).size!==n.recordIds.length)throw Error("Choose an AI resource, model, instruction and up to ten records.");for(let i of[n.sourceFieldIds,n.targetFieldIds])if(i.length<1||i.length>10||new Set(i).size!==i.length||i.some((r)=>!e.fields.some((a)=>a.id===r&&ti.includes(a.type))))throw Error("Choose up to ten basic source and target fields.");let o=n.recordIds.map((i)=>{let r=t.find((a)=>a.id===i);if(!r)throw Error("A selected record is no longer on this page.");return{id:i,expectedVersion:r.version}});return structuredClone({expectedSchemaVersion:e.schemaVersion,resourceId:n.resourceId,model:n.model.trim(),instruction:n.instruction,records:o,sourceFieldIds:n.sourceFieldIds,targetFieldIds:n.targetFieldIds,idempotencyKey:crypto.randomUUID()})}function qa({descriptor:e,records:t,client:n,onApplied:o}){let i=Ua(),r=e.id,a=ei({id:r,client:n}),d=ei(!0);a.current={id:r,client:n};let[s,p]=Be([]),[c,u]=Be(!1),[g,x]=Be(""),[C,v]=Be(""),[P,m]=Be(""),[w,y]=Be([]),[S,N]=Be([]),[A,U]=Be([]),[E,_]=Be(null),[G,M]=Be(null),[T,Y]=Be(null),[D,k]=Be(!1),[Q,R]=Be(!1),[J,O]=Be(""),[ie,z]=Be(""),[re,j]=Be(""),F=()=>d.current&&a.current.id===r&&a.current.client===n,K=async(b)=>{try{return await b()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};Ba(()=>{d.current=!0,_(null),M(null),Y(null),k(!1),O(""),z(""),j(""),y([]),N([]),U([]),m("");let b=!0;return u(!1),R(!1),p([]),x(""),v(""),n.providers(r).then((q)=>{if(!b||a.current.id!==r||a.current.client!==n)return;if(u(!0),q.ok)p(q.data),x(q.data[0]?.resourceId??""),v(q.data[0]?.allowedModels[0]??"");else O(q.error.message)}).catch(()=>{if(b)u(!0),O("AI configuration is unavailable.")}),()=>{b=!1,d.current=!1}},[r,n]);let ee=()=>{try{let b=_a(e,t,{resourceId:g,model:C,instruction:P,recordIds:w,sourceFieldIds:S,targetFieldIds:A});M(structuredClone(b.records.map((q)=>({id:q.id,version:q.expectedVersion,values:Object.fromEntries(b.sourceFieldIds.map((Z)=>[Z,t.find((Oe)=>Oe.id===q.id)?.values[Z]??null]))})))),_(b),k(!1),O(""),z("")}catch(b){O(b instanceof Error?b.message:"Invalid selection.")}},de=async()=>{if(!E||Q)return;let b=E,q=D;R(!0),k(!0),O("");let Z=await K(()=>n.propose(r,b));if(!F())return;if(R(!1),!Z.ok){if(!q&&Z.error.status>=400&&Z.error.status<500)k(!1);O(`${Z.error.message} Retry keeps the original selection and versions.`);return}Y(Z.data),j(Z.data.id),k(!1)},me=async()=>{if(!T||Q)return;let b=T,q=D;R(!0),k(!0),O("");let Z=await K(()=>n.confirm(r,b));if(!F())return;if(R(!1),!Z.ok){if(!q&&Z.error.status>=400&&Z.error.status<500)k(!1);O(`${Z.error.message} The reviewed proposal keeps its original versions.`);return}z(`${Z.data.items.length} records filled${Z.data.replayed?"; original receipt recovered":""}.`),Y(null),_(null),M(null),k(!1);try{await o?.()}catch{if(F())O("The fill committed. Refresh the Collection to see its records.")}},X=async()=>{if(Q||E||T)return;R(!0),O("");let b=await K(()=>n.get(r,re));if(!F())return;if(R(!1),b.ok)Y(b.data),k(!1),z("");else O(b.error.message)},we=(b,q,Z)=>Z(b.includes(q)?b.filter((Oe)=>Oe!==q):[...b,q]),ae=Q||!!E||!!T,Se=e.fields.filter((b)=>ti.includes(b.type)),L=s.find((b)=>b.resourceId===g);return Te("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[he("p",{children:"Choose the records and fields to send to your configured AI service. Review suggested values before writing. Conflicts keep the original record versions."}),J&&he("p",{role:"alert",children:J}),ie&&he("p",{role:"status",children:ie}),c&&s.length===0&&he("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),he("form",{onSubmit:(b)=>{b.preventDefault(),ee()},children:Te("fieldset",{disabled:ae,style:{minWidth:0},children:[he("legend",{children:"AI fill request"}),Te("label",{children:["AI resource"," ",Te("select",{"aria-label":"AI resource",value:g,onChange:(b)=>{x(b.target.value),v(s.find((q)=>q.resourceId===b.target.value)?.allowedModels[0]??"")},children:[he("option",{value:"",children:"Choose resource"}),s.map((b)=>he("option",{value:b.resourceId,children:b.name},b.resourceId))]})]}),Te("label",{htmlFor:i,children:["Model"," ",L?.allowedModels.length?he("select",{id:i,"aria-label":"AI model",value:C,onChange:(b)=>v(b.target.value),children:L.allowedModels.map((b)=>he("option",{value:b,children:b},b))}):he("input",{id:i,"aria-label":"AI model",maxLength:200,value:C,onChange:(b)=>v(b.target.value)})]}),Te("label",{children:["Instructions"," ",he("textarea",{"aria-label":"AI instructions",maxLength:2000,value:P,onChange:(b)=>m(b.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),Te("fieldset",{children:[he("legend",{children:"Source fields to send"}),Se.map((b)=>Te("label",{style:{display:"block"},children:[he("input",{type:"checkbox","aria-label":`Send ${b.name}`,checked:S.includes(b.id),onChange:()=>we(S,b.id,N)}),b.name]},b.id))]}),Te("fieldset",{children:[he("legend",{children:"Fields to fill"}),Se.map((b)=>Te("label",{style:{display:"block"},children:[he("input",{type:"checkbox","aria-label":`Fill ${b.name}`,checked:A.includes(b.id),onChange:()=>we(A,b.id,U)}),b.name]},b.id))]}),Te("fieldset",{children:[he("legend",{children:"Target records from this page"}),t.map((b)=>Te("label",{style:{display:"block",overflowWrap:"anywhere"},children:[he("input",{type:"checkbox","aria-label":`AI record ${b.id}`,checked:w.includes(b.id),onChange:()=>we(w,b.id,y)}),b.id," · version ",b.version]},b.id))]}),he("button",{type:"submit",disabled:!g,children:"Review AI request"})]})}),E&&!T&&Te("section",{"aria-label":"AI data disclosure",children:[Te("p",{children:["Selected service: ",E.resourceId," · model ",E.model," · schema"," ",E.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),he("p",{children:E.instruction}),he("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(G,null,2)}),he("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),he("button",{type:"button",disabled:Q,onClick:()=>void de(),children:D?"Retry original AI request":"Generate proposal"}),he("button",{type:"button",disabled:Q||D,onClick:()=>{_(null),M(null),O("")},children:"Cancel AI request"})]}),T&&Te("section",{"aria-label":"AI fill confirmation",children:[Te("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",T.id," · ",T.provider," · schema ",T.schemaVersion]}),T.schemaVersion!==e.schemaVersion&&he("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),T.rows.map((b)=>Te("div",{style:{overflowWrap:"anywhere"},children:[Te("p",{children:[b.id," · original version ",b.expectedVersion]}),Object.keys(b.values).map((q)=>Te("div",{children:[he("strong",{children:e.fields.find((Z)=>Z.id===q)?.name??q}),Te("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(b.before[q]),`
10
+ `,"Suggested: ",JSON.stringify(b.values[q])]})]},q))]},b.id)),he("button",{type:"button",disabled:Q,onClick:()=>void me(),children:D?"Retry original AI fill":"Confirm fill"}),he("button",{type:"button",disabled:Q||D,onClick:()=>{Y(null),_(null),M(null),O("")},children:"Dismiss proposal"})]}),Te("label",{children:["Recover a saved proposal"," ",he("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:re,onChange:(b)=>j(b.target.value),disabled:ae,style:{width:"100%",boxSizing:"border-box"}})]}),he("button",{type:"button",disabled:ae||!/^[a-f0-9]{64}$/.test(re),onClick:()=>void X(),children:"Load saved proposal"})]})}import{jsx as te,jsxs as ge}from"react/jsx-runtime";var za=[{value:"singleLineText",name:"Text"},{value:"longText",name:"Long text"},{value:"number",name:"Number"},{value:"checkbox",name:"Boolean"},{value:"date",name:"Date"},{value:"singleSelect",name:"Single select"},{value:"multipleSelect",name:"Multiple select"},{value:"linkedRecord",name:"Linked records"},{value:"lookup",name:"Lookup (read only)"},{value:"formula",name:"Formula (read only)"},{value:"rollup",name:"Rollup (read only)"}];function lu({fields:e,onChange:t,lockedIds:n=[],collections:o=[]}){let i=(r,a)=>t(e.map((d,s)=>s===r?{...d,...a}:d));return ge("div",{className:"flex flex-col gap-3",children:[e.map((r,a)=>{let d=n.includes(r.id);return ge("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)] gap-2 rounded-md border p-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_150px_auto]",children:[te("input",{"aria-label":`Field ${a+1} name`,placeholder:"Display name",value:r.name,onChange:(s)=>i(a,{name:s.target.value})}),te("input",{"aria-label":`Field ${a+1} ID`,placeholder:"field_id",value:r.id,disabled:d,onChange:(s)=>i(a,{id:s.target.value})}),te("select",{"aria-label":`Field ${a+1} type`,className:"rounded-md border bg-background px-2 text-sm",value:r.type,disabled:d,onChange:(s)=>{let p=s.target.value,c={id:r.id,name:r.name,type:p,required:Ne({type:p})?!1:r.required??!1};if(p==="formula")c.formula={expression:""};if(p==="rollup")c.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(p==="singleSelect"||p==="multipleSelect")c.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((u,g)=>g===a?c:u))},children:za.map((s)=>te("option",{value:s.value,children:s.name},s.value))}),ge("div",{className:"flex items-center gap-2",children:[ge("label",{className:"flex items-center gap-1 text-xs",children:[te("input",{type:"checkbox",checked:r.required??!1,disabled:d||n.length>0||Ne(r),onChange:(s)=>i(a,{required:s.target.checked})}),"Required"]}),!d&&te("button",{type:"button",onClick:()=>t(e.filter((s,p)=>p!==a)),children:"Remove"})]}),(r.type==="singleSelect"||r.type==="multipleSelect")&&te("input",{className:"md:col-span-4","aria-label":`Field ${a+1} options`,placeholder:"Open, Done",value:r.options?.map((s)=>s.name).join(", ")??"",disabled:d,onChange:(s)=>i(a,{options:s.target.value.split(",").map((p,c)=>({id:p.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${c}`,name:p.trim()})).filter((p)=>p.name)})}),r.type==="linkedRecord"&&ge("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ge("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",ge("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} linked collection`,value:r.link?.collectionId??"",disabled:d,onChange:(s)=>{let p=o.find((c)=>c.id===s.target.value);i(a,{link:{collectionId:s.target.value,displayFieldId:p?.fields.find((c)=>c.type==="singleLineText"||c.type==="longText")?.id??""}})},children:[te("option",{value:"",children:"Choose collection…"}),o.map((s)=>te("option",{value:s.id,children:s.name},s.id))]})]}),ge("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",ge("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} record label`,value:r.link?.displayFieldId??"",disabled:d||!r.link?.collectionId,onChange:(s)=>i(a,{link:{collectionId:r.link?.collectionId??"",displayFieldId:s.target.value}}),children:[te("option",{value:"",children:"Choose text field…"}),o.find((s)=>s.id===r.link?.collectionId)?.fields.filter((s)=>s.type==="singleLineText"||s.type==="longText").map((s)=>te("option",{value:s.id,children:s.name},s.id))]})]})]}),r.type==="lookup"&&ge("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ge("label",{children:["Through linked field"," ",ge("select",{"aria-label":`Field ${a+1} lookup link`,value:r.lookup?.linkFieldId??"",disabled:d,onChange:(s)=>i(a,{lookup:{linkFieldId:s.target.value,targetFieldId:""}}),children:[te("option",{value:"",children:"Choose linked field…"}),e.filter((s)=>s.type==="linkedRecord"&&s.link).map((s)=>te("option",{value:s.id,children:s.name},s.id))]})]}),ge("label",{children:["Read target field"," ",ge("select",{"aria-label":`Field ${a+1} lookup target`,value:r.lookup?.targetFieldId??"",disabled:d||!r.lookup?.linkFieldId,onChange:(s)=>i(a,{lookup:{linkFieldId:r.lookup?.linkFieldId??"",targetFieldId:s.target.value}}),children:[te("option",{value:"",children:"Choose target field…"}),o.find((s)=>s.id===e.find((p)=>p.id===r.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((s)=>!Ne(s)&&s.type!=="linkedRecord").map((s)=>te("option",{value:s.id,children:s.name},s.id))]})]}),te("small",{children:"Computed from linked records. Values cannot be edited."})]}),r.type==="formula"&&ge("div",{className:"flex flex-col gap-1 md:col-span-4",children:[ge("label",{children:["Formula",te("textarea",{"aria-label":`Field ${a+1} formula`,maxLength:2048,className:"min-h-16 w-full rounded-md border bg-background p-2",placeholder:"{quantity} * {price}",value:r.formula?.expression??"",onChange:(s)=>i(a,{formula:{expression:s.target.value}})})]}),te("small",{children:"Use numbers, stable field references, + - * / and parentheses. Text and date functions: CONCAT, UPPER, LOWER, TRIM, DATE_ADD_DAYS, DATE_DIFF_DAYS. Empty inputs produce an empty result."}),ge("small",{children:["References:"," ",e.filter((s)=>s.id!==r.id&&(s.type==="singleLineText"||s.type==="longText"||s.type==="date"||s.type==="number"||s.type==="formula"||s.type==="rollup")).map((s)=>`{${s.id}}`).join(", ")||"None yet"]})]}),r.type==="rollup"&&ge("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ge("label",{children:["Through linked field"," ",ge("select",{"aria-label":`Field ${a+1} rollup link`,value:r.rollup?.linkFieldId??"",onChange:(s)=>i(a,{rollup:{linkFieldId:s.target.value,targetFieldId:"",function:r.rollup?.function??"sum"}}),children:[te("option",{value:"",children:"Choose linked field…"}),e.filter((s)=>s.type==="linkedRecord"&&s.link).map((s)=>te("option",{value:s.id,children:s.name},s.id))]})]}),ge("label",{children:["Aggregate"," ",ge("select",{"aria-label":`Field ${a+1} rollup function`,value:r.rollup?.function??"sum",onChange:(s)=>{let p=s.target.value,c=o.find((u)=>u.id===e.find((g)=>g.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((u)=>u.id===r.rollup?.targetFieldId);i(a,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:p==="count"||c?.type==="number"?r.rollup?.targetFieldId??"":"",function:p}})},children:[te("option",{value:"sum",children:"Sum"}),te("option",{value:"average",children:"Average"}),te("option",{value:"min",children:"Minimum"}),te("option",{value:"max",children:"Maximum"}),te("option",{value:"count",children:"Count values"})]})]}),ge("label",{children:["Target field"," ",ge("select",{"aria-label":`Field ${a+1} rollup target`,value:r.rollup?.targetFieldId??"",disabled:!r.rollup?.linkFieldId,onChange:(s)=>i(a,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:s.target.value,function:r.rollup?.function??"sum"}}),children:[te("option",{value:"",children:"Choose target field…"}),o.find((s)=>s.id===e.find((p)=>p.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((s)=>!Ne(s)&&s.type!=="linkedRecord"&&(r.rollup?.function==="count"||s.type==="number")).map((s)=>te("option",{value:s.id,children:s.name},s.id))]})]}),te("small",{className:"w-full",children:"Null targets are skipped. Count counts values; empty sum/count are zero. Other empty aggregates have no result."})]})]},a)}),te("button",{type:"button",className:"self-start",onClick:()=>t([...e,{id:`field_${crypto.randomUUID().replaceAll("-","").slice(0,8)}`,name:"New field",type:"singleLineText",required:!1}]),children:"Add field"})]})}function ja(e,t,n){if(Ne(e)||e.type==="blob")return"";if(e.type==="linkedRecord"||e.type==="relation"){let o=t==null||t===""||Array.isArray(t)&&t.length===0;if(e.required&&o)return n==="zh-CN"?`请填写${e.name}。`:`${e.name} is required.`;return""}return jt(e,Re(t),n)}function wo(e,t,n,o){let i=Object.create(null);for(let r of e){if(r.type==="lookup"||r.type==="formula"||r.type==="rollup"||r.type==="blob"||r.generation==="autoIncrement")continue;if(!Object.hasOwn(t,r.id)){if(r.required)throw Error(n("{name} is required.",{name:r.name}));continue}let a=t[r.id];if(r.type==="linkedRecord"){if(!Array.isArray(a)||a.some((d)=>typeof d!=="string")||a.length>100||new Set(a).size!==a.length)throw Error(n("{name} needs unique linked records.",{name:r.name}));if(r.required&&!a.length)throw Error(n("{name} is required.",{name:r.name}));i[r.id]=a;continue}if(r.type==="relation"){if(a==null||a===""){if(r.required)throw Error(n("{name} is required.",{name:r.name}));i[r.id]=null;continue}if(typeof a!=="string")throw Error(n("{name} needs a server-provided option.",{name:r.name}));i[r.id]=a;continue}if(r.required&&typeof a==="string"&&!a.trim())throw Error(n("{name} is required.",{name:r.name}));i[r.id]=et(Array.isArray(a)?a.join(","):String(a??""),r,o)}return i}function dn({fields:e,values:t,onChange:n,relationClient:o,linkedRecords:i,computedErrors:r,locale:a,ui:d,submitted:s=!1}){let p=ke(a),c=$a();return te("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((u)=>{let g=u.description?.trim()??"",x=g?`${c}-${u.id}-hint`:void 0,C=ja(u,t[u.id],a??"en"),P=Boolean(u.required&&Re(t[u.id])===""&&C)&&!s?"":C,m=P?`${c}-${u.id}-error`:void 0,w=[x,m].filter(Boolean).join(" "),y={...w?{"aria-describedby":w}:{},...P?{"aria-invalid":!0}:{}};return ge("div",{className:"flex flex-col gap-1 text-sm",children:[ge("label",{htmlFor:`${c}-${u.id}`,children:[u.name,u.required?" *":""]}),g?te("p",{id:x,className:"m-0 text-xs opacity-70",children:g}):null,Ne(u)?te("output",{id:`${c}-${u.id}`,"aria-label":p("{name} (read only)",{name:u.name}),...y,children:u.type==="lookup"?Pt(t[u.id]):Gt(t[u.id],r?.[u.id],a)}):u.type==="linkedRecord"?te(Rn,{...a?{locale:a}:{},field:u,value:t[u.id],labels:i?.[u.id],client:o,onChange:(S)=>n({...t,[u.id]:S}),...y}):u.type==="checkbox"?te("input",{id:`${c}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,type:"checkbox",checked:t[u.id]===!0,onChange:(S)=>n({...t,[u.id]:S.target.checked}),...y}):u.type==="singleSelect"&&d?.Select?te(Hr,{ui:d,label:`${u.name}${u.required?" *":""}`,...y,value:String(t[u.id]??""),options:[{value:"",label:p("Choose…")},...(u.options??[]).map((S)=>({value:S.id,label:S.name}))],onChange:(S)=>n({...t,[u.id]:S||null})}):u.type==="multipleSelect"&&d?.MultiSelect?te(d.MultiSelect,{"aria-label":`${u.name}${u.required?" *":""}`,...y,options:(u.options??[]).map((S)=>({value:S.id,label:S.name,slot:rn(u.options,S.id)})),values:Array.isArray(t[u.id])?t[u.id]:[],placeholder:p("Choose…"),onChange:(S)=>n({...t,[u.id]:S})}):u.type==="singleSelect"||u.type==="multipleSelect"?ge("select",{id:`${c}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...y,className:"min-h-9 rounded-md border bg-background p-2",multiple:u.type==="multipleSelect",value:u.type==="multipleSelect"?Array.isArray(t[u.id])?t[u.id]:[]:String(t[u.id]??""),onChange:(S)=>n({...t,[u.id]:u.type==="multipleSelect"?Array.from(S.target.selectedOptions,(N)=>N.value):S.target.value||null}),children:[u.type==="singleSelect"&&te("option",{value:"",children:p("Choose…")}),u.options?.map((S)=>te("option",{value:S.id,children:S.name},S.id))]}):u.type==="date"&&d?.DatePicker?(()=>{let S={kind:Xn(u),timeZone:st(u)?.timeZone},N=String(t[u.id]??"");return te(d.DatePicker,{id:`${c}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...y,value:ao(N,S),withTime:S.kind==="auto"?wt(N):S.kind==="datetime",fixedKind:S.kind!=="auto",clearable:!u.required,onChange:(A)=>n({...t,[u.id]:A?lo(A,N,S):null})})})():u.type==="longText"?te("textarea",{id:`${c}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...y,className:"rounded-md border bg-background p-2",value:String(t[u.id]??""),onChange:(S)=>n({...t,[u.id]:S.target.value||null})}):te("input",{id:`${c}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...y,className:"min-h-9 min-w-0 rounded-md border bg-background p-2",type:u.type==="number"?"number":u.type==="date"?"date":"text",step:u.type==="number"?"any":void 0,value:u.type==="date"?String(t[u.id]??"").slice(0,10):String(t[u.id]??""),onChange:(S)=>n({...t,[u.id]:S.target.value===""?null:u.type==="number"?Number(S.target.value):u.type==="date"&&t[u.id]?zr(t[u.id],S.target.value):S.target.value})}),P?te("span",{id:m,className:"text-xs text-red-600",children:P}):null]},u.id)})})}function Ha(e,t,n){if(t==="isEmpty")return;let o=Ne(e)?e.resultType:e.type;if(o==="number"){if(t!=="is"&&t!=="isNot")throw Error("Number filters support is, is not, or is empty.");let i=Number(n);if(!n.trim()||!Number.isFinite(i))throw Error("Filter needs a number.");return i}if(o==="date"){if(!["is","isNot","onOrAfter","before"].includes(t))throw Error("Date filters support is, is not, on or after, before, or is empty.");return n}if(o==="checkbox"){if(!["true","false"].includes(n))throw Error("Filter needs true or false.");return n==="true"}if(Ne(e)&&!Dt(e))throw Error("Computed filters are not available for this field.");if((e.type==="multipleSelect"||e.type==="linkedRecord")&&t!=="contains")return n.split(",").map((i)=>i.trim());return n}function su({fields:e,view:t,onChange:n,onError:o}){let i=e.filter(Dt),[r,a]=ko(i[0]?.id??""),d=i.some((m)=>m.id===r)?r:i[0]?.id??"",[s,p]=ko("contains"),c=d?(()=>{let m=e.find((w)=>w.id===d);return m&&Ne(m)?m.resultType:m?.type})():void 0,u=c==="number"?["is","isNot","isEmpty"]:c==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],g=u.includes(s)?s:c==="number"||c==="date"?"is":"contains",[x,C]=ko(""),P=[...t.columnOrder.flatMap((m)=>{let w=e.find((y)=>y.id===m);return w?[w]:[]}),...e.filter((m)=>!t.columnOrder.includes(m.id))];return ge("div",{className:"flex flex-wrap items-end gap-3",children:[ge("label",{className:"flex min-w-52 flex-col gap-1 text-sm",children:["Search",te("input",{type:"search",className:"min-h-9 min-w-0 rounded-md border bg-background p-2",value:t.search??"",onChange:(m)=>n({...t,search:m.target.value})})]}),ge("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(m)=>{m.preventDefault();let w=e.find((S)=>S.id===d);if(!w)return;let y;try{y=Ha(w,g,x)}catch(S){o(S instanceof Error?S.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:d,operator:g,...g==="isEmpty"?{}:{value:y}}]}})},children:[ge("label",{className:"flex flex-col gap-1 text-sm",children:["Filter field",te("select",{className:"h-9 rounded-md border bg-background px-2",value:d,onChange:(m)=>a(m.target.value),children:i.map((m)=>te("option",{value:m.id,children:m.name},m.id))})]}),te("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:g,onChange:(m)=>p(m.target.value),children:u.map((m)=>te("option",{value:m,children:m==="isNot"?"is not":m==="isEmpty"?"is empty":m==="onOrAfter"?"on or after":m},m))}),g!=="isEmpty"&&te("input",{type:c==="number"?"number":c==="date"?"date":"text",step:c==="number"?"any":void 0,className:"min-h-9 max-w-40 rounded-md border bg-background p-2","aria-label":"Filter value",value:x,onChange:(m)=>C(m.target.value)}),te("button",{type:"submit",disabled:!d,children:"Apply filter"}),te("button",{type:"button",onClick:()=>{let m={...t};delete m.filter,n(m)},children:"Clear filter"})]}),ge("details",{className:"relative",children:[te("summary",{className:"cursor-pointer rounded-md border px-3 py-2 text-sm",children:"Columns"}),te("div",{className:"absolute right-0 top-full z-10 mt-1 flex max-h-96 min-w-64 flex-col gap-2 overflow-auto rounded-md border bg-background p-3 shadow-md",children:P.map((m,w)=>ge("div",{className:"flex items-center gap-2 text-sm",children:[ge("label",{className:"flex flex-1 items-center gap-2",children:[te("input",{type:"checkbox",checked:!t.hiddenColumns.includes(m.id),disabled:t.type==="form"&&m.required===!0,onChange:(y)=>n({...t,hiddenColumns:y.target.checked?t.hiddenColumns.filter((S)=>S!==m.id):[...t.hiddenColumns,m.id]})}),m.name]}),te("button",{type:"button","aria-label":`Move ${m.name} left`,disabled:w===0,onClick:()=>{let y=P.map((N)=>N.id),S=y[w-1];if(S!==void 0)[y[w-1],y[w]]=[m.id,S];n({...t,columnOrder:y})},children:"←"}),te("button",{type:"button","aria-label":`Move ${m.name} right`,disabled:w===P.length-1,onClick:()=>{let y=P.map((N)=>N.id),S=y[w+1];if(S!==void 0)[y[w],y[w+1]]=[S,m.id];n({...t,columnOrder:y})},children:"→"})]},m.id))})]})]})}import{useEffect as Ka,useMemo as ni,useState as oi}from"react";import{jsx as Po}from"react/jsx-runtime";function Ga(e){switch(e.code){case"empty":return"Choose a count or sum.";case"too_many":return"Use at most three groups and eight summaries.";case"unknown_field":return"That field is not in this collection.";case"not_groupable":return"Group by a text, number, date, checkbox, or single select field.";case"function":return"That summary function is not supported.";case"numeric_field":return"Average only a number field.";case"extrema_field":return"Minimum and maximum need a number or date field.";case"queryable_field":return"Summarize a queryable field.";case"sum_field":return"Sum only a number field.";case"count_field":return"Count a queryable field, or omit the field to count records.";case"alias":return"Each summary needs its own name, different from the group fields.";case"duplicate_group":return"Each group field can be used once."}}function Wa(e,t,n){let o=n.unassigned??"Unassigned";if(t===null||t===void 0)return o;if(e?.type==="singleSelect")return e.options?.find((i)=>i.id===t)?.name??String(t);if(e?.type==="checkbox")return t===!0?n.checked??"Checked":n.unchecked??"Unchecked";return typeof t==="string"||typeof t==="number"||typeof t==="boolean"?String(t):o}function ri(e,t,n,o={},i={}){return n.map((r)=>{let a=t.groupBy.map((s)=>{let p=e.fields.find((c)=>c.id===s);return`${p?.name??s} ${Wa(p,r.groups[s],i)}`}),d=t.aggregates.map((s)=>{let p=r.values[s.as];return`${o[s.as]??s.as}: ${typeof p==="number"||typeof p==="string"?String(p):i.none??"none"}`});return[...a,...d].join(" · ")})}function ku({descriptor:e,query:t,rows:n}){return Po("ul",{"data-uibot":"collection-aggregate",children:ri(e,t,n).map((o)=>Po("li",{children:o},o))})}function Nn({collectionId:e,descriptor:t,view:n,groupBy:o,aggregates:i,client:r,locale:a,labels:d,reloadKey:s=0}){let p=ni(()=>bn(n,{aggregates:i,...o?{groupBy:o}:{}}),[n,o,i]),c=ni(()=>ke(a),[a]),[u,g]=oi(c("Loading summary…")),[x,C]=oi(!1);return Ka(()=>{let v=Cn(t,p);if(v){g(c(Ga(v))),C(!0);return}let P=!0;return g(c("Loading summary…")),C(!1),r.aggregate(e,p).then((m)=>{if(!P)return;if(!m.ok){g(m.error.message),C(!0);return}let w=ri(t,p,m.data,d??{},{unassigned:c("Unassigned"),checked:c("Checked"),unchecked:c("Unchecked"),none:c("none")});g(w.length?w.join(" · "):c("No summary rows.")),C(!1)}).catch(()=>{if(!P)return;g(c("The collection service is unavailable.")),C(!0)}),()=>{P=!1}},[r,e,t,p,d,c,s]),Po("p",{role:x?"alert":"status","data-uibot":"collection-aggregate",children:u})}var ai=["grid","kanban","gallery","calendar","form"],Ya=["grid","form"],Ro={search:!0,filter:!0,columns:!0,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!0,tableList:!0,viewManagement:!0,export:!0},Ja={search:!0,filter:!1,columns:!1,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!1,tableList:!1,viewManagement:!1,export:!1},Qa={search:!0,filter:!0,columns:!0,rowCreate:!1,rowUpdate:!1,rowDelete:!1,schemaEditor:!1,tableList:!0,viewManagement:!1,export:!0},ii={fieldTypeIcons:!1,optionChips:!1,groupBy:!1,groupCollapse:!1,autoHeight:!1,sorting:!0,columnResize:!0,columnReorder:!1,columnFreezing:!1,columnColors:!1,footerStats:!1,recordContextMenu:!1,optimisticEdit:!1,viewTypes:ai},So={fieldTypeIcons:!0,optionChips:!0,groupBy:!0,groupCollapse:!0,autoHeight:!0,sorting:!0,columnResize:!0,columnReorder:!0,columnFreezing:!0,columnColors:!0,footerStats:!0,recordContextMenu:!0,optimisticEdit:!0,viewTypes:ai},li={basic:{...ii,...Ro},full:{...So,...Ro},simple:{...ii,...Ja,viewTypes:Ya},workbench:{...So,...Ro},readonly:{...So,...Qa,recordContextMenu:!1,optimisticEdit:!1}};function Vt(e){let{preset:t="basic",...n}=e??{},o={...li[t],...Za(n)};return o.groupBy?o:{...o,groupCollapse:!1}}function Za(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}import{jsx as se,jsxs as ze,Fragment as Do}from"react/jsx-runtime";function Ou(e){if(!e.aggregate)return null;return se(Nn,{collectionId:e.descriptor.id,descriptor:e.descriptor,view:e.view,...e.aggregate.groupBy?{groupBy:e.aggregate.groupBy}:{},aggregates:e.aggregate.aggregates,client:e.aggregate.client,...e.locale?{locale:e.locale}:{},...e.reloadKey!==void 0?{reloadKey:e.reloadKey}:{}})}var $e={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},Ln={padding:12,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)"},Mn={items:[],total:0,nextCursor:null,limit:50};function Lu(e,t,n=!0){let o=ke(e.locale),i=JSON.stringify([e.descriptor.id,e.descriptor.schemaVersion,t]),[r,a]=We({key:i,history:[]}),d=r.key===i?r.cursor:void 0,s=r.key===i?r.history:[],p=JSON.stringify([i,d]),[c,u]=We(0),[g,x]=We({key:p,page:Mn,loading:n,error:""});On(()=>{let v=!0;if(!n){x({key:p,page:Mn,loading:!1,error:""});return}x((w)=>({key:p,page:w.key===p?w.page:Mn,loading:!0,error:""}));let[P,,m]=JSON.parse(i);return e.client.query(P,{...m,...d?{cursor:d}:{}}).then((w)=>{if(!v)return;if(w.ok)x({key:p,page:w.data,loading:!1,error:""});else x((y)=>({...y,loading:!1,error:w.error.message}))}).catch(()=>{if(v)x((w)=>({...w,loading:!1,error:o("Collection query failed. Retry to load records.")}))}),()=>{v=!1}},[p,i,d,e.client,e.reloadKey,n,c]);let C=g.key===p?g.page:Mn;return{page:C,loading:n&&(g.key!==p||g.loading),error:g.key===p?g.error:"",previous:s.length?()=>a({key:i,cursor:s.at(-1),history:s.slice(0,-1)}):void 0,next:C.nextCursor?()=>a({key:i,cursor:C.nextCursor??void 0,history:[...s,d]}):void 0,retry:()=>u((v)=>v+1),pageNumber:s.length+1}}function Io(e,t,n,o){return n>=t?e("{count} records total",{count:t.toLocaleString(o)}):e("{total} records · {loaded} loaded",{total:t.toLocaleString(o),loaded:n})}function Xa({hasPrevious:e,hasNext:t,onPrevious:n,onNext:o,loading:i,page:r,locale:a,ui:d}){let s=ke(a);if(!e&&!t)return null;return ze("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[se(Ae,{ui:d,style:$e,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:s("Previous page"),disabled:!e||i,onClick:n}),r?se("span",{style:{fontSize:12},children:s("Page {page}",{page:r})}):null,se(Ae,{ui:d,style:$e,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:s("Next page"),disabled:!t||i,onClick:o})]})}function Vu({state:e,locale:t,ui:n,hideCount:o}){let i=ke(t);return ze("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[o?null:se("span",{children:Io(i,e.page.total,e.page.items.length,t)}),se(Xa,{hasPrevious:Boolean(e.previous),hasNext:Boolean(e.next),onPrevious:e.previous,onNext:e.next,loading:e.loading,page:e.pageNumber,locale:t,ui:n}),e.loading&&se("span",{role:"status",children:i("Loading records…")}),e.error&&ze(Do,{children:[se("span",{role:"alert",children:e.error}),se(Ae,{ui:n,style:$e,variant:"outline",size:"sm",disabled:e.loading,onClick:e.retry,children:i("Retry query")})]})]})}function Ao(e){let t=nr(e.client,e.descriptor.id),n=ke(e.locale),[o,i]=We(!1),[r,a]=We(""),[d,s]=We(null),p=cn(null);$t({dirty:Boolean(p.current),busy:o});let c=()=>{p.current=null,a(""),s(null)};return{saving:o,error:r,setError:a,remote:d,pending:p,reset:c,commit:async(x)=>{if(o||e.readOnly)return!1;p.current=x,i(!0),a(""),s(null);let C=await e.client.mutate(e.descriptor.id,x).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:n("Saving failed. Your change has been kept.")}}));if(!t.active)return!1;if(i(!1),C.ok)return c(),e.onCommitted(C.data),!0;a(C.error.message);let v=C.error.details?.current;if(v&&typeof v.id==="string"&&Number.isSafeInteger(v.version)&&v.version>0)s(v);return!1},retryRequest:()=>p.current&&d?{idempotencyKey:crypto.randomUUID(),items:p.current.items.map((x)=>x.op!=="insert"&&x.id===d.id?{...x,expectedVersion:d.version}:x)}:p.current}}function Eo({mutation:e,onRetry:t,locale:n,ui:o}){let i=ke(n);return ze(Do,{children:[e.error&&se("p",{role:"alert",children:e.error}),e.remote&&ze("div",{style:Ln,children:[se("strong",{children:i("Current server version {version}",{version:e.remote.version})}),se("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(e.remote.values,null,2)}),se(Ae,{ui:o,style:$e,variant:"outline",size:"sm",disabled:e.saving,onClick:t,children:i("Retry against current version")})]})]})}function Bu({row:e,onClose:t,onCancel:n,onDirtyChange:o,onBusyChange:i,stickyActions:r,...a}){let d=ke(a.locale),s=Vt(a.features),p=!a.readOnly&&s.rowDelete,c=!a.readOnly&&s.rowUpdate,u=cn(e.values),[g,x]=We(()=>({...u.current})),[C,v]=We(!1);$t({dirty:JSON.stringify(g)!==JSON.stringify(u.current),busy:!1});let P=cn(null),[m,w]=We(!1);On(()=>{P.current?.focus()},[]);let y=Ao(a),S=mo(a.descriptor.fields,a.view),N=JSON.stringify(g)!==JSON.stringify(e.values);On(()=>{o?.(N)},[N,o]),On(()=>{i?.(y.saving)},[y.saving,i]);let A=async(E=!1)=>{v(!0);try{let _=E?y.retryRequest():y.pending.current;if(!_){let G=S.filter((T)=>T.type!=="lookup"&&T.type!=="formula"&&T.type!=="rollup"&&JSON.stringify(g[T.id])!==JSON.stringify(e.values[T.id]));if(!G.length){y.setError(d("Change a field before saving."));return}let M=wo(G,g,d,a.locale);_={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:e.id,expectedVersion:e.version,values:M}]}}if(await y.commit(_))t()}catch(_){y.setError(_ instanceof Error?_.message:d("Invalid value"))}},U=async()=>{let E=y.pending.current?.items[0]?.op==="delete"?y.pending.current:{idempotencyKey:crypto.randomUUID(),items:[{op:"delete",id:e.id,expectedVersion:e.version}]};if(await y.commit(E))t()};return ze("div",{ref:P,tabIndex:-1,onKeyDown:(E)=>{if(E.key==="Escape"&&!y.saving)E.stopPropagation(),(n??t)()},role:"dialog","aria-label":d("{name} record",{name:fo(e,a.descriptor.fields)}),style:{...Ln,marginTop:12},children:[se("h3",{children:fo(e,a.descriptor.fields)}),a.onInspectRecord&&se(Ae,{ui:a.ui,style:$e,variant:"outline",size:"sm",disabled:y.saving,onClick:()=>a.onInspectRecord?.(e.id),children:d("Open record activity")}),ze("form",{onSubmit:(E)=>{E.preventDefault(),A()},children:[se("fieldset",{disabled:y.saving||m||!c,style:{border:0,padding:0},children:se(dn,{fields:S,values:g,submitted:C,...a.locale?{locale:a.locale}:{},...a.ui?{ui:a.ui}:{},relationClient:a.client,linkedRecords:e.linkedRecords,computedErrors:e.computedErrors,onChange:(E)=>{x(E),y.reset()}})}),ze("div",{"data-uibot":"record-editor-actions",style:r?{position:"sticky",bottom:0,zIndex:1,display:"flex",gap:8,alignItems:"center",padding:"12px 0",borderTop:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",background:"var(--background, white)"}:void 0,children:[c&&se("button",{type:"submit",style:{...$e,...Sn},disabled:y.saving||m,children:y.saving?d("Saving…"):d("Save record")}),r?null:se("button",{type:"button",style:$e,disabled:y.saving,onClick:n??t,children:d("Close record")}),r&&p?se("span",{style:{marginLeft:"auto"},children:se(Ae,{ui:a.ui,variant:"ghost",size:"sm",icon:"trash",disabled:y.saving,onClick:()=>w(!0),children:d("Delete record")})}):null]})]}),p&&!r&&se("button",{type:"button",style:$e,disabled:y.saving,onClick:()=>w(!0),children:d("Delete record")}),m&&a.ui?.ConfirmDialog?a.ui.ConfirmDialog({open:!0,destructive:!0,title:d("Delete this record?"),description:d("Delete this record? Your unsaved changes will be discarded after deletion."),confirmLabel:d("Delete"),cancelLabel:d("Cancel"),busy:y.saving,onConfirm:()=>void U(),onCancel:()=>{if(w(!1),y.pending.current?.items[0]?.op==="delete")y.reset()}}):null,m&&!a.ui?.ConfirmDialog&&ze(In,{alert:!0,label:d("Confirm record deletion"),busy:y.saving,onCancel:()=>{if(w(!1),y.pending.current?.items[0]?.op==="delete")y.reset()},children:[se("p",{children:d("Delete this record? Your unsaved changes will be discarded after deletion.")}),se("button",{type:"button",style:$e,disabled:y.saving,onClick:()=>void U(),children:d("Confirm deletion")}),se("button",{type:"button",style:$e,disabled:y.saving,onClick:()=>{if(w(!1),y.pending.current?.items[0]?.op==="delete")y.reset()},children:d("Cancel deletion")})]}),se(Eo,{mutation:y,onRetry:()=>void A(!0),locale:a.locale,ui:a.ui})]})}function Uu(e){let t=ke(e.locale),n=!e.readOnly&&Vt(e.features).rowCreate,o=cn(null),i=mo(e.descriptor.fields,{...e.view,hiddenColumns:e.view.hiddenColumns.filter((P)=>!e.descriptor.fields.find((m)=>m.id===P)?.required)}),r=()=>({...Object.fromEntries(i.filter((P)=>P.type==="checkbox").map((P)=>[P.id,!1])),...sr(i)}),a=cn(r()),[d,s]=We(a.current),[p,c]=We(!1),[u,g]=We(!1);$t({dirty:JSON.stringify(d)!==JSON.stringify(a.current),busy:!1});let x=Ao(e),C=()=>o.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")?.focus(),v=async()=>{if(!n)return;g(!0);try{let P=x.pending.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:wo(i,d,t,e.locale)}]};if(await x.commit(P))a.current=r(),s(a.current),c(!0),g(!1),requestAnimationFrame(C)}catch(P){x.setError(P instanceof Error?P.message:t("Invalid value"))}};return ze("section",{"data-uibot":"collection-form",style:Ln,children:[se("h3",{children:e.view.name}),e.readOnly&&se("p",{children:t("Record creation requires editor permission.")}),ze("form",{ref:o,onSubmit:(P)=>{P.preventDefault(),v()},children:[se("fieldset",{disabled:x.saving||!n,style:{border:0,padding:0},children:se(dn,{fields:i,values:d,submitted:u,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},relationClient:e.client,onChange:(P)=>{s(P),c(!1),x.reset()}})}),n&&se("button",{type:"submit",style:{...$e,...Sn},disabled:x.saving,children:x.saving?t("Creating…"):t("Create record")})]}),se(Eo,{mutation:x,onRetry:()=>void v(),locale:e.locale,ui:e.ui}),p?ze("p",{role:"status",children:[t("Record created. Add another below."),e.onShowRecords?ze(Do,{children:[" ",se(Ae,{ui:e.ui,style:$e,variant:"outline",size:"sm",onClick:e.onShowRecords,children:t("Show records")})]}):null]}):null]})}function _u(e){let[t,n]=We(null),o=Ao(e),i=!e.readOnly&&Vt(e.features).rowUpdate;return{intent:t,mutation:o,move:async(d,s)=>{if(!i||o.saving||t)return;n({row:d,values:s});let p={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:d.id,expectedVersion:d.version,values:s}]};if(await o.commit(p))n(null)},retry:async()=>{let d=o.retryRequest();if(d&&await o.commit(d))n(null)},cancel:()=>{n(null),o.reset()},blocked:o.saving||!!t}}function qu({state:e,locale:t,ui:n}){let o=ke(t);if(!e.intent)return null;return ze("div",{role:"dialog","aria-label":o("Pending record move"),style:Ln,children:[se("p",{children:e.mutation.saving?o("Moving record…"):o("The move has been kept for retry.")}),se("pre",{children:JSON.stringify(e.intent.values,null,2)}),se(Eo,{mutation:e.mutation,onRetry:()=>void e.retry(),locale:t,ui:n}),!e.mutation.remote&&se(Ae,{ui:n,style:$e,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:()=>void e.retry(),children:o("Retry move")}),se(Ae,{ui:n,style:$e,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:e.cancel,children:o("Cancel move")})]})}import{useCallback as el,useEffect as si,useLayoutEffect as tl,useRef as To,useState as di}from"react";import{jsx as Vn,jsxs as pi,Fragment as nl}from"react/jsx-runtime";function ci({items:e,label:t,children:n,block:o=!1}){let[i,r]=di(null),a=To(null),d=To(null),[s,p]=di({x:0,y:0}),c=el(()=>{if(!i||!d.current)return;let g=Math.max(12,Math.min(i.x,window.innerWidth-12-d.current.offsetWidth)),x=Math.max(12,Math.min(i.y,window.innerHeight-12-d.current.offsetHeight));p((C)=>C.x===g&&C.y===x?C:{x:g,y:x})},[i]);tl(c),si(()=>{if(!i)return;return window.addEventListener("resize",c),()=>window.removeEventListener("resize",c)},[i,c]);let u=To(null);return si(()=>{if(!i)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null,d.current?.querySelector("button:not(:disabled)")?.focus();let g=()=>r(null),x=(C)=>{if(C.key==="Escape")C.preventDefault(),C.stopPropagation(),r(null),u.current?.focus({preventScroll:!0})};return window.addEventListener("keydown",x),window.addEventListener("pointerdown",g),window.addEventListener("blur",g),()=>{window.removeEventListener("keydown",x),window.removeEventListener("pointerdown",g),window.removeEventListener("blur",g)}},[i]),pi("span",{ref:a,style:{display:o?"block":"inline-flex"},onKeyDown:(g)=>{if(g.shiftKey&&g.key==="F10"||g.key==="ContextMenu"){g.preventDefault(),g.stopPropagation();let x=g.target.getBoundingClientRect();r({x:Math.max(8,Math.min(x.left,window.innerWidth-240)),y:Math.max(8,Math.min(x.bottom,window.innerHeight-280))})}},onContextMenu:(g)=>{g.preventDefault(),g.stopPropagation(),r({x:Math.max(8,Math.min(g.clientX,window.innerWidth-240)),y:Math.max(8,Math.min(g.clientY,window.innerHeight-280))})},children:[n,i&&Vn("div",{ref:d,role:"menu","aria-label":t,style:{position:"fixed",left:s.x,top:s.y,boxSizing:"border-box",maxWidth:"calc(100vw - 24px)",maxHeight:"min(70vh, calc(100vh - 24px))",overflow:"auto",zIndex:60,minWidth:140,font:"inherit",padding:4,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",boxShadow:"0 4px 16px rgb(0 0 0 / 0.12)"},onPointerDown:(g)=>g.stopPropagation(),onKeyDown:(g)=>{if(!["ArrowDown","ArrowUp"].includes(g.key))return;g.preventDefault();let x=[...g.currentTarget.querySelectorAll("button:not(:disabled)")],C=x.indexOf(document.activeElement);x[(C+(g.key==="ArrowUp"?-1:1)+x.length)%x.length]?.focus()},children:e.map((g)=>Vn("button",{type:"button",role:"menuitem",disabled:g.disabled,style:{display:"block",width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderRadius:6,background:"transparent",color:g.destructive?"var(--destructive, #b3261e)":"inherit",cursor:g.disabled?"default":"pointer",opacity:g.disabled?0.5:1},onClick:()=>{r(null),g.onSelect()},children:g.label},g.id))})]})}function ui({label:e,items:t,disabled:n,icon:o}){return Vn(go,{label:e,disabled:n,menu:!0,trigger:o??"+",children:(i)=>Vn(nl,{children:t.map((r)=>pi("button",{type:"button",role:"menuitem",disabled:r.disabled,style:{display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderTop:r.separatorBefore?"1px solid var(--border, #d5d9df)":void 0,background:"transparent",color:r.destructive?"var(--destructive, #b3261e)":"inherit",opacity:r.disabled?0.5:1,font:"inherit"},onClick:()=>{i(),r.onSelect()},children:[r.icon,r.label]},r.id))})})}function No(e){return e?.type==="singleSelect"||e?.type==="checkbox"}var ol="\x00none";function gi(e,t,n=new Set){if(!t)return{items:e.map((a,d)=>({kind:"row",index:d,key:a.id})),rowItem:e.map((a,d)=>d)};let o=[],i=[],r;return e.forEach((a,d)=>{let s=a.values[t.id],p=s==null?ol:String(s);if(!r||r.raw!==p){let c=t.options?.findIndex((u)=>u.id===s)??-1;r={kind:"group",key:`group:${o.length}:${p}`,raw:p,label:s==null?null:t.type==="checkbox"?s===!0?"true":"false":t.options?.[c]?.name??String(s),colorIndex:c,count:0,collapsed:n.has(p)},o.push(r)}if(r.count+=1,r.collapsed)return;i[d]=o.length,o.push({kind:"row",index:d,key:a.id})}),{items:o,rowItem:i}}function Bn(e,t,n,o){for(let i=t;i>=0&&i<o;i+=n)if(e.rowItem[i]!==void 0)return i;return-1}var Mo=34,Fo=38,rl={short:1,medium:2,tall:3,extra:4},Oo=(e)=>rl[e??"short"],mi=(e)=>Fo+(Oo(e)-1)*22;function fi(e,t=Fo){return Fo+e.items.reduce((n,o)=>n+(o.kind==="group"?Mo:t),0)}function Wu(e,t){let n=e?.groupByFieldId;if(!e||!n||(e.type??"grid")!=="grid")return e?.sort;if(!t?.some((o)=>o.id===n&&No(o)))return e.sort;return[{fieldId:n,direction:"asc"},...(e.sort??[]).filter((o)=>o.fieldId!==n)]}import{jsx as B,jsxs as Ie}from"react/jsx-runtime";function pl(e,t){let n=e.find((o)=>o.fieldId===t);if(n?.direction==="desc")return[];return[{fieldId:t,direction:n?"desc":"asc"}]}var Ct={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},gl={padding:5,width:"100%",border:"1px solid #6688bb",background:"var(--background, white)",color:"inherit"};function Pp(e){let{descriptor:t,view:n}=e,o=ke(e.locale),i=nt(()=>Vt(e.features),[e.features]),r=!e.readOnly&&i.rowDelete,a=!e.readOnly&&i.rowCreate,d=!e.readOnly&&i.rowUpdate,[s,p]=Me({}),c=ot(new Set),[u,g]=Me(()=>new Set),x=ot(new Set);rt(()=>{if(!c.current.size)return;let l=c.current;c.current=new Set,p((f)=>Object.fromEntries(Object.entries(f).filter(([h])=>!l.has(h))))},[e.rows]);let C=nt(()=>Object.keys(s).length?e.rows.map((l)=>s[l.id]?{...l,values:{...l.values,...s[l.id]}}:l):e.rows,[e.rows,s]),v=nt(()=>[...n.columnOrder,...t.fields.map((f)=>f.id).filter((f)=>!n.columnOrder.includes(f))].filter((f)=>!n.hiddenColumns.includes(f)).flatMap((f)=>{let h=t.fields.find((W)=>W.id===f);return h?[h]:[]}),[t.fields,n.columnOrder,n.hiddenColumns]),P=nt(()=>JSON.stringify([C.map((l)=>l.id),v.map((l)=>l.id)]),[C,v]),[m,w]=Me(P),y=ot(null),[S,N]=Me({row:0,column:0}),[A,U]=Me(!1),[E,_]=Me(()=>new Set),[G,M]=Me(()=>new Set),T=JSON.stringify([t.id,n.filter,n.search,n.sort,e.rowOffset]);rt(()=>{_(new Set),M(new Set)},[e.rows,T]);let[Y,D]=Me({row:0,column:0}),[k,Q]=Me(null),R=ot(!1),J=ot(!1),[O,ie]=Me(null),[z,re]=Me(!1),[j,F]=Me(!1);$t({dirty:Boolean(O||z||k&&k.text!==k.originalText),busy:j||u.size>0},e);let[K,ee]=Me(""),[de,me]=Me(null),X=ot(null),we=k?.field.type==="linkedRecord"?JSON.stringify([k.rowId,k.field.id]):null;rt(()=>{if(we)X.current?.querySelector('input[type="search"]')?.focus({preventScroll:!0})},[we]),rt(()=>{U(!1),N({row:0,column:0}),D({row:0,column:0}),w(P)},[P]);let ae=nt(()=>{if(!i.groupBy||(n.type??"grid")!=="grid")return;let l=t.fields.find((f)=>f.id===n.groupByFieldId);return No(l)?l:void 0},[i.groupBy,n.type,n.groupByFieldId,t.fields]),[Se,L]=Me(()=>new Set),b=ae?.id;rt(()=>L(new Set),[b]);let q=nt(()=>gi(C,ae,Se),[C,ae,Se]),Z=(l)=>Boolean(ae)&&q.rowItem[l]===void 0,Oe=mi(n.rowHeight),Ye=Oo(n.rowHeight),Jt=yi({count:q.items.length,getScrollElement:()=>y.current,estimateSize:(l)=>q.items[l]?.kind==="group"?Mo:Oe,overscan:5,scrollMargin:38,getItemKey:(l)=>`${Oe}:${q.items[l]?.key??l}`}),Je=n.showRowNumber===!1?0:56,it=n.showRecordId?220:0,Bt=Je+it,[Un,bi]=Me(0);rt(()=>{let l=y.current;if(!l)return;let f=()=>bi(l.clientWidth);if(f(),typeof ResizeObserver>"u")return window.addEventListener("resize",f),()=>window.removeEventListener("resize",f);let h=new ResizeObserver(f);return h.observe(l),()=>h.disconnect()},[]);let Vo=Math.min(Math.max(0,n.frozenColumnCount??0),v.length),Bo=nt(()=>{let l=[Bt];for(let f of v)l.push((l.at(-1)??Bt)+un(n.columnWidths[f.id]??180));return l},[Bt,v,n.columnWidths]),Ci=Bo[Vo]??Bt,Qe=Un>0&&Un<=768&&Ci>Un*0.6?0:Vo,_n=(l)=>Bo[l]??Bt,Uo=ot(null),qn=Boolean(e.onAddRecord)&&a,hi=cl(dl(ll,{activationConstraint:{distance:6}})),vi=({active:l,delta:f})=>{let h=v.findIndex((xe)=>xe.id===l.id),W=ht.getVirtualItems().find((xe)=>xe.index===h);if(h<0||!W)return;let V=W.start+W.size/2+f.x,I=ht.getVirtualItems().find((xe)=>V>=xe.start&&V<xe.start+xe.size)?.index;if(I===void 0||I===h)return;if(h<Qe!==I<Qe)return;let H=[...n.columnOrder.filter((xe)=>t.fields.some((Ai)=>Ai.id===xe)),...t.fields.map((xe)=>xe.id).filter((xe)=>!n.columnOrder.includes(xe))],ue=String(l.id),ne=v[I]?.id;if(!ne)return;let fe=H.filter((xe)=>xe!==ue),oe=fe.indexOf(ne)+(I>h?1:0);fe.splice(oe,0,ue),e.onViewChange({...n,columnOrder:fe})},Ut=(l,f)=>({position:"sticky",float:"left",left:l,zIndex:2,...f?{boxShadow:"2px 0 4px -2px color-mix(in srgb, currentColor 28%, transparent)"}:{}}),ht=yi({paddingStart:Bt,horizontal:!0,count:v.length,rangeExtractor:(l)=>{let f=new Set(ul(l));for(let h=0;h<Qe;h+=1)f.add(h);return[...f].sort((h,W)=>h-W)},getScrollElement:()=>y.current,estimateSize:(l)=>un(n.columnWidths[v[l]?.id??""]??180),overscan:2,getItemKey:(l)=>v[l]?.id??l});rt(()=>{v.forEach((l,f)=>{ht.resizeItem(f,un(n.columnWidths[l.id]??180))})},[ht,n.columnWidths,v]);let _t=Math.max(1,ht.getTotalSize()),$n=ht.getVirtualItems(),Fe=eo(S,Y),zn=nt(()=>A&&m===P?C.slice(Fe.firstRow,Fe.lastRow+1):[],[A,m,P,C,Fe.firstRow,Fe.lastRow]),ye=nt(()=>{let l=new Set(C.filter((f,h)=>!ae||q.rowItem[h]!==void 0).map((f)=>f.id));return fr(zn,E,C,G).filter((f)=>l.has(f.id))},[zn,E,C,G,ae,q]),Qt=nt(()=>ye.map((l)=>l.id),[ye]),ct=nt(()=>new Set(Qt),[Qt]),pn=A?{first:Fe.firstColumn,last:Fe.lastColumn}:{first:0,last:v.length-1},jn=()=>ye.length?gr(ye,v,{row:0,column:pn.first},{row:ye.length-1,column:pn.last}):"",_o=(l)=>{if(k||j||z||O)return;let f=C[l];if(!f)return;if(w(P),zn.some((h)=>h.id===f.id))M((h)=>to(h,f.id));else _((h)=>to(h,f.id));if(!A)N({row:l,column:0}),D({row:l,column:v.length-1})},[Ue,Hn]=Me(null),Zt=ot(null),qo=!E.size&&!G.size&&A&&d&&!j&&!k&&!z&&!O&&!Se.size,$o=(l,f)=>{if(!qo)return;let h=xr(l,f,C,v),W=(I)=>{ee(I),e.onNotify?.(I)};if(h.limitExceeded){W(o("Fill at most 100 rows at once."));return}let V=h.skipped?o("Skipped {count} cells",{count:h.skipped}):"";if(!h.mutations.length){if(V)W(V);return}Ze({idempotencyKey:crypto.randomUUID(),items:h.mutations},()=>{W([o("Filled {count} cells",{count:h.count}),V].filter(Boolean).join("; "))})};rt(()=>{if(!Ue)return;let l=()=>{let h=Zt.current;if(Hn(null),Zt.current=null,h)$o(Ue,h)},f=()=>{Hn(null),Zt.current=null};return window.addEventListener("mouseup",l),window.addEventListener("blur",f),()=>{window.removeEventListener("mouseup",l),window.removeEventListener("blur",f)}});let zo=JSON.stringify({recordIds:m===P?Qt:[],fieldIds:ye.length?v.slice(pn.first,pn.last+1).map((l)=>l.id):[]}),jo=ot(e.onSelectionChange);jo.current=e.onSelectionChange,rt(()=>{jo.current?.(JSON.parse(zo))},[zo]),rt(()=>{if(!ae||!Z(Y.row))return;let l=Bn(q,Y.row,-1,C.length),f=l>=0?l:Bn(q,Y.row,1,C.length);if(f>=0)D({...Y,row:f}),N({...Y,row:f})},[q]);let xi=(l)=>{let f=new Set(Se);if(f.has(l))f.delete(l);else f.add(l);L(f),U(!1),_(new Set),M(new Set),N(Y)},ut=(l,f=!1)=>{if(Se.size)f=!1;if(U(!0),w(P),D(l),!f)N(l),_(new Set),M(new Set);Jt.scrollToIndex(q.rowItem[l.row]??l.row,{align:"auto"}),ht.scrollToIndex(l.column,{align:"auto"})},gn=(l=Y,f)=>{if(!d||j||k||z||O||v[l.column]?.generation==="autoIncrement")return;let h=C[l.row],W=v[l.column];if(!h||!W||W.type==="blob"||Ne(W))return;if(u.has(h.id))return;U(!0),w(P),R.current=!1;let V=W.type==="linkedRecord"?JSON.stringify(h.values[W.id]??[]):W.type==="relation"?_r(h,W):W.type==="json"&&h.values[W.id]!=null?JSON.stringify(h.values[W.id]):Re(h.values[W.id]);Q({rowId:h.id,expectedVersion:h.version,field:W,originalText:V,text:W.type==="linkedRecord"||W.type==="relation"?V:f??V}),ee(i.optimisticEdit?"":o("Unsaved changes")),ie(null),me(null)},at=ot([]),At=ot([]),[Et,mn]=Me(null),Ho=(l,f)=>{for(let h of l.items){if(h.op!=="update")continue;let W=f.items.find((V)=>V.id===h.id);if(!W)continue;for(let V of[at,At])V.current=V.current.map((I)=>({...I,items:I.items.map((H)=>H.op!=="insert"&&H.id===h.id&&H.expectedVersion===h.expectedVersion?{...H,expectedVersion:W.version}:H)}))}},Ko=(l,f,h)=>{let W=l.items;if(!W.length)return null;let V=new Map(h.map((H)=>[H.id,H])),I=[];if(W.every((H)=>H.op==="update")){let H=new Map(f.items.map((ue)=>[ue.id,ue]));for(let ue of W){if(ue.op!=="update")continue;let ne=V.get(ue.id);if(!ne)return null;I.push({op:"update",id:ue.id,expectedVersion:H.get(ue.id)?.version??ue.expectedVersion+1,values:Object.fromEntries(Object.keys(ue.values).map((fe)=>[fe,ne.values[fe]??null]))})}}else if(W.every((H)=>H.op==="insert")){if(f.items.length!==W.length)return null;for(let H of f.items)I.push({op:"delete",id:H.id,expectedVersion:H.version})}else if(W.every((H)=>H.op==="delete"))for(let H of W){if(H.op!=="delete")continue;let ue=V.get(H.id);if(!ue)return null;I.push({op:"insert",values:Object.fromEntries(t.fields.filter((ne)=>ne.type!=="blob"&&ne.type!=="linkedRecord"&&!Ne(ne)&&ne.generation!=="autoIncrement"&&ue.values[ne.id]!==void 0).map((ne)=>[ne.id,ue.values[ne.id]]))})}else return null;return{idempotencyKey:crypto.randomUUID(),items:I}},ki=(l)=>{if(j||e.readOnly||k||z||O)return;let h=(l==="undo"?at:At).current.at(-1);if(!h)return;Ze({...h,idempotencyKey:crypto.randomUUID()},void 0,l)};async function Ze(l,f,h){if(j||J.current||e.readOnly)return;let W=h&&Et?Et.before:C;if(h)mn({direction:h,before:W,rejected:!1});J.current=!0,F(!0),ie(l),ee("");let V=await e.onMutate(l).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:o("Saving failed. Your edit has been kept.")}}));if(J.current=!1,F(!1),V.ok){let I=Ko(l,V.data,W);if(h)(h==="undo"?at:At).current.pop();if(Ho(l,V.data),mn(null),I)if(h==="undo")At.current.push(I);else{if(at.current.push(I),at.current.length>30)at.current.shift();if(!h)At.current=[]}e.onCommitted(V.data),ie(null),Q(null),re(!1),me(null);let H=l.items.filter((ne)=>ne.op==="delete").length,ue=h?o(h==="undo"?"Undone":"Redone"):H>0&&H===l.items.length?o("Deleted {count} records",{count:H}):o("Saved");if(e.onNotify)ee(""),e.onNotify(ue);else ee(ue);y.current?.focus({preventScroll:!0}),f?.()}else{if(h){let H=V.error.status;mn({direction:h,before:W,rejected:H>=400&&H<500&&H!==408})}ee(V.error.message);let I=V.error.details;if(I?.current)me(I.current)}}async function Go(l,f,h,W){if(x.current.has(l.id))return;x.current.add(l.id),F(!0);let V=k??{rowId:l.id,expectedVersion:l.version,field:f,text:Re(h),originalText:Re(l.values[f.id])},I={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:l.id,expectedVersion:l.version,values:{[f.id]:h}}]};p((ne)=>({...ne,[l.id]:{...ne[l.id],[f.id]:h}})),g((ne)=>new Set(ne).add(l.id)),Q(null),ee(""),y.current?.focus({preventScroll:!0});let H=await e.onMutate(I).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:o("Saving failed. Your edit has been kept.")}}));if(x.current.delete(l.id),F(!1),g((ne)=>{let fe=new Set(ne);return fe.delete(l.id),fe}),H.ok){c.current.add(l.id);let ne=Ko(I,H.data,[l]);if(Ho(I,H.data),ne){if(at.current.push(ne),at.current.length>30)at.current.shift();At.current=[]}e.onCommitted(H.data),W?.();return}p((ne)=>{let fe={...ne};return delete fe[l.id],fe}),Q(V),ie(I),ee(H.error.message);let ue=H.error.details;if(ue?.current)me(ue.current)}async function vt(l){if(!k||R.current)return;let{field:f,rowId:h,expectedVersion:W}=k;if(f.generation==="autoIncrement"||t.fields.find((V)=>V.id===f.id)?.generation==="autoIncrement"){ee(o("{name} is auto-generated and cannot be edited.",{name:f.name})),Q(null);return}try{let V=f.type==="linkedRecord"?JSON.parse(k.text):f.type==="relation"?k.text||null:et(k.text,f);if(f.type==="linkedRecord"&&f.required&&Array.isArray(V)&&!V.length)throw Error(`${f.name} is required.`);if(i.optimisticEdit&&f.type==="linkedRecord"&&!O&&k.text===k.originalText){pt();return}if(i.optimisticEdit&&f.type!=="linkedRecord"&&!O){let ue=C.find((ne)=>ne.id===h);if(!ue){Q(null);return}if(JSON.stringify(V??null)===JSON.stringify(ue.values[f.id]??null)){pt();return}await Go(ue,f,V,()=>{if(l)ut(xn(Y,"Tab",C.length,v.length,l==="previous"))});return}let I={[f.id]:V},H=O??{idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:h,expectedVersion:W,values:I}]};await Ze(H,l?()=>ut(xn(Y,"Tab",C.length,v.length,l==="previous")):void 0)}catch(V){ee((e.locale==="zh-CN"?jt(f,k.text,"zh-CN"):null)||(V instanceof Error?V.message:o("Invalid value")))}}let qt=Boolean(e.readOnly||j||k||z||O||Qt.length===0),Wo=()=>{if(qt||!r)return;Wn()},pt=()=>{R.current=!0,ee(""),Q(null),ie(null),me(null),y.current?.focus({preventScroll:!0})},Xt=(l)=>{if(!k||l===k.text)return;ee(i.optimisticEdit?"":o("Unsaved changes")),Q({...k,text:l}),ie(null),me(null)},wi=(l,f,h)=>{if(!d||j||k||z||O)return;if(i.optimisticEdit){Go(l,f,h);return}Q({rowId:l.id,expectedVersion:l.version,field:f,text:String(h),originalText:Re(l.values[f.id])}),Ze({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:l.id,expectedVersion:l.version,values:{[f.id]:h}}]})},xt=i.optionChips,Kn=Boolean(e.renderRecordContextMenu)||i.recordContextMenu,Yo=i.optimisticEdit&&!O?{onBlur:(l)=>{if(!l.currentTarget.contains(l.relatedTarget))vt()}}:{},gt=k?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:k.field,text:k.text,disabled:j||Boolean(e.readOnly),autoOpen:!0,onChange:Xt,onSave:(l)=>void vt(l),onCancel:pt}):void 0,Jo=i.optimisticEdit&&k?.field.type==="linkedRecord"&&(gt===void 0||gt===null)&&!O&&!j?{onBlur:(l)=>{let f=l.relatedTarget;if(!f||X.current?.contains(f)||f.closest('[role="gridcell"]')?.id===`wb-${k.rowId}-${k.field.id}`)return;vt()}}:{},Gn=k&&(k.field.type==="singleSelect"||k.field.type==="multipleSelect")?gt??Ie("select",{"aria-label":o("Edit {name}",{name:k.field.name}),ref:(l)=>l?.focus(),style:gl,multiple:k.field.type==="multipleSelect",value:k.field.type==="multipleSelect"?k.text.split(",").filter(Boolean):k.text,disabled:j,onChange:(l)=>Xt(k.field.type==="multipleSelect"?Array.from(l.currentTarget.selectedOptions,(f)=>f.value).join(","):l.currentTarget.value),onKeyDown:(l)=>{if(l.stopPropagation(),l.key==="Escape")l.preventDefault(),pt();if(l.key==="Tab")l.preventDefault(),vt(l.shiftKey?"previous":"next");if(l.key==="Enter")l.preventDefault(),vt()},children:[k.field.type==="singleSelect"&&B("option",{value:"",disabled:k.field.required,children:o("Clear selection")}),(k.field.options??[]).map((l)=>B("option",{value:l.id,children:l.name},l.id)),k.text.split(",").filter((l)=>l&&!k.field.options?.some((f)=>f.id===l)).map((l)=>B("option",{value:l,disabled:!0,children:o("{id} (unavailable)",{id:l})},l))]}):void 0,Wn=()=>{if(!r||j||k||z||O||ye.length===0)return;if(ye.length>100){ee(o("Select at most 100 rows per delete."));return}ie({idempotencyKey:crypto.randomUUID(),items:ye.map((l)=>({op:"delete",id:l.id,expectedVersion:l.version}))}),re(!0),ee(""),me(null)},Pi=(l,f,h,W,V)=>{V.setPointerCapture(W);let I=(ue)=>e.onViewChange({...n,columnWidths:{...n.columnWidths,[l]:un(h+ue.clientX-f)}}),H=()=>{V.removeEventListener("pointermove",I),V.removeEventListener("pointerup",H),V.removeEventListener("pointercancel",H)};V.addEventListener("pointermove",I),V.addEventListener("pointerup",H),V.addEventListener("pointercancel",H)},[Ri,Si]=Me(480);il(()=>{if(!e.display?.fill)return;let l=()=>{let f=y.current?.getBoundingClientRect().top??0;Si(Math.max(240,Math.round(window.innerHeight-f-64-(i.footerStats?34:0))))};return l(),window.addEventListener("resize",l),()=>window.removeEventListener("resize",l)},[e.display?.fill,i.footerStats]);let en=e.display?.summary===!1&&e.display?.keyboardHints===!1,Qo=!!k&&Jt.getVirtualItems().some((l)=>{let f=q.items[l.index];return f?.kind==="row"&&C[f.index]?.id===k.rowId})&&ht.getVirtualItems().some((l)=>v[l.index]?.id===k.field.id),fn=Ie("section",{"data-uibot":"paged-collection-grid",style:{display:en?"grid":"flex",flexDirection:en?void 0:"column",border:"1px solid var(--border, #d5d9df)",borderRadius:8,overflow:"hidden"},children:[(e.display?.summary!==!1||e.display?.keyboardHints!==!1||e.aggregate&&!i.footerStats||e.onInspectRecord||!e.readOnly&&ye.length>0&&!e.renderRecordContextMenu&&!i.recordContextMenu)&&Ie("div",{"data-uibot":"paged-collection-toolbar",style:{display:"flex",gap:8,padding:8,alignItems:"center",flexWrap:"wrap",...en?{}:{order:1,padding:"4px 10px",fontSize:12,borderTop:"1px solid var(--border, #d5d9df)"},...en?{gridArea:"1 / 1",alignSelf:"end",justifySelf:"end",zIndex:4,margin:8,borderRadius:8,background:"var(--background, white)",boxShadow:"0 2px 12px rgb(0 0 0 / 0.15)"}:{}},children:[e.display?.summary!==!1&&B("span",{children:Io(o,e.total,C.length,e.locale)}),e.aggregate&&!i.footerStats&&B(Nn,{collectionId:t.id,descriptor:t,view:n,...e.aggregate.groupBy?{groupBy:e.aggregate.groupBy}:{},aggregates:e.aggregate.aggregates,client:e.aggregate.client,...e.reloadKey!==void 0?{reloadKey:e.reloadKey}:{}}),B("span",{style:{flex:1}}),e.display?.keyboardHints!==!1&&B("span",{style:{fontSize:12},children:o(d?"Arrows · Shift select · Enter edit · Copy / paste":"Arrows · Shift select · Copy")}),e.onInspectRecord&&B(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:j||ye.length!==1,onClick:()=>{let l=ye[0];if(l)e.onInspectRecord?.(l.id)},children:o("Open record activity")}),r&&ye.length>0&&!e.renderRecordContextMenu&&!i.recordContextMenu&&B(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",icon:"trash",disabled:qt,onClick:Wn,children:o("Delete selected rows")})]}),B("style",{children:`
11
+ [data-uibot="paged-collection-grid"] [role="gridcell"]:hover > [data-uibot-row-actions],
12
+ [data-uibot="paged-collection-grid"] [role="gridcell"]:focus-within > [data-uibot-row-actions] { opacity: 1 !important; }
13
+ [data-uibot="paged-collection-grid"] [role="gridcell"]:hover > [data-uibot-row-number],
14
+ [data-uibot="paged-collection-grid"] [role="gridcell"]:focus-within > [data-uibot-row-number] { opacity: 0 !important; }
15
+ @media (hover: none) {
16
+ [data-uibot="paged-collection-grid"] [data-uibot-row-actions] { opacity: 1 !important; }
17
+ [data-uibot="paged-collection-grid"] [data-uibot-row-number] { opacity: 0 !important; }
18
+ }
19
+ `}),Ie(ml,{ui:e.ui,paneRef:y,role:"grid","aria-label":o("{name} records",{name:t.name}),"aria-rowcount":e.total+1,"aria-colcount":v.length+Number(Boolean(Je))+Number(Boolean(it)),"aria-activedescendant":C[Y.row]&&v[Y.column]?`wb-${C[Y.row]?.id}-${v[Y.column]?.id}`:void 0,tabIndex:0,style:{gridArea:en?"1 / 1":void 0,overflow:"auto",height:e.display?.fill?Ri:i.autoHeight?Math.min(e.display?.maxHeight??560,Math.max(120,fi(q,Oe)+2+(qn?Lo:0))):e.display?.maxHeight??480,position:"relative",outlineOffset:-2},onScroll:(l)=>Uo.current?.style.setProperty("--uibot-sx",`${l.currentTarget.scrollLeft}px`),onCopy:(l)=>{if(k)return;l.preventDefault(),l.clipboardData.setData("text/plain",jn())},onPaste:(l)=>{if(k||z||O||!d||j)return;if(l.preventDefault(),Se.size){ee(o("Expand all groups before pasting."));return}let f=mr(l.clipboardData.getData("text/plain"),C,v,{row:Fe.firstRow,column:Fe.firstColumn},e.locale);if(!f.ok){ee(f.message);return}ie({idempotencyKey:crypto.randomUUID(),items:f.items}),re(!0),ee(""),me(null)},onKeyDown:(l)=>{if(l.target!==l.currentTarget&&l.target.closest("button, input, select, textarea, [contenteditable=true]"))return;if((l.metaKey||l.ctrlKey)&&!l.altKey&&!k){let f=l.key.toLowerCase();if(f==="d"||f==="r"){l.preventDefault();let h=f==="d"?{...Fe,lastRow:Fe.firstRow}:{...Fe,lastColumn:Fe.firstColumn};$o(h,Fe);return}if(f==="z"||f==="y"){l.preventDefault(),ki(f==="y"||l.shiftKey?"redo":"undo");return}}if(!k&&l.key==="Escape"){_(new Set),M(new Set);return}if(k||!C.length||!v.length||j)return;if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End"].includes(l.key)){l.preventDefault();let f=l.key==="Tab"&&l.shiftKey,h=xn(Y,l.key,C.length,v.length,f);if(Z(h.row)){let W=l.key==="ArrowUp"||f||h.row<Y.row,V=Bn(q,h.row,W?-1:1,C.length);if(V<0)return;h={...h,row:V}}ut(h,l.shiftKey&&l.key!=="Tab")}else if(Z(Y.row))l.preventDefault();else if(l.key==="Delete"&&ye.length>0&&r)l.preventDefault(),Wn();else if(d&&["Enter","F2"].includes(l.key))l.preventDefault(),gn();else if(d&&l.key.length===1&&!l.metaKey&&!l.ctrlKey&&!l.altKey)l.preventDefault(),gn(Y,l.key)},children:[B(al,{sensors:hi,modifiers:[Cl],onDragEnd:vi,children:Ie("div",{role:"row",tabIndex:-1,style:{position:"sticky",top:0,height:38,width:_t,zIndex:2,background:"var(--muted, #f4f6f8)"},children:[Je>0&&B("div",{role:"columnheader",tabIndex:-1,"aria-colindex":1,"aria-label":o("Row"),style:{...Ut(0,!it&&Qe===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:Je,padding:4,display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center",height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:Ie("label",{title:o("{count} selected",{count:ye.length}),style:{position:"relative",display:"flex",alignItems:"center"},children:[ye.length===0&&B("span",{"aria-hidden":"true",children:o("Row")}),B("input",{type:"checkbox","aria-label":o("Select all loaded records"),ref:(l)=>{if(l)l.indeterminate=ye.length>0&&ye.length<C.filter((f,h)=>!Z(h)).length},style:ye.length===0?{position:"absolute",inset:0,width:"100%",height:"100%",margin:0,opacity:0,cursor:"pointer"}:{margin:0,width:16,height:16},onKeyDown:(l)=>l.stopPropagation(),checked:ye.length>0&&ye.length===C.filter((l,f)=>!Z(f)).length,disabled:Boolean(k||j||z||O),onChange:(l)=>{U(!1),w(P),M(new Set),_(l.currentTarget.checked?new Set(C.filter((f,h)=>!Z(h)).map((f)=>f.id)):new Set)},onFocus:(l)=>{l.currentTarget.parentElement?.style.setProperty("outline","2px solid var(--ring, currentColor)")},onBlur:(l)=>{l.currentTarget.parentElement?.style.removeProperty("outline")}})]})}),it>0&&B("div",{role:"columnheader",tabIndex:-1,"aria-colindex":Je>0?2:1,style:{...Ut(Je,Qe===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:it,padding:8,height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:o("Record ID")}),$n.map((l)=>{let f=v[l.index];if(!f)return null;let h=wn(n.columnColors?.[f.id]),W=n.sort?.find((ne)=>ne.fieldId===f.id),V=i.sorting&&f.type!=="linkedRecord"&&Dt(f),I=e.fieldMenu?.(f)??[],H=I.length?e.ui?.DropdownMenu?e.ui.DropdownMenu({label:o("Field menu {name}",{name:f.name}),icon:B(Le,{name:"chevronDown"}),items:I}):B(ui,{label:o("Field menu {name}",{name:f.name}),icon:B(Le,{name:"chevronDown"}),items:I},f.id):null,ue=B(hl,{id:f.id,disabled:!i.columnReorder,children:(ne)=>Ie("div",{ref:ne.setNodeRef,...ne.listeners,role:"columnheader",tabIndex:-1,"aria-colindex":l.index+1+Number(Boolean(Je))+Number(Boolean(it)),onKeyDown:(fe)=>{if(fe.shiftKey&&fe.key==="F10"||fe.key==="ContextMenu"){fe.preventDefault(),fe.stopPropagation();let oe=fe.currentTarget.querySelector('button[aria-haspopup="menu"]');oe?.focus({preventScroll:!0}),oe?.click(),oe?.dispatchEvent(new KeyboardEvent("keydown",{key:"ArrowDown",bubbles:!0}))}},"aria-sort":W?W.direction==="asc"?"ascending":"descending":"none",style:{...l.index<Qe?{...Ut(_n(l.index),l.index===Qe-1),background:"var(--muted, #f4f6f8)"}:{position:"absolute",left:l.start},boxSizing:"border-box",background:h?.background??"var(--muted, #f4f6f8)",borderTopWidth:h?3:void 0,borderTopStyle:h?"solid":void 0,borderTopColor:h?.marker,width:l.size,height:38,borderRight:"1px solid var(--border, #d5d9df)",display:"flex",alignItems:"center",...ne.style},children:[Ie("button",{type:"button",disabled:!V,title:V||!i.sorting?void 0:o("Sorting is unavailable for this field"),style:{background:"transparent",border:0,color:"inherit",textAlign:"left",flex:1,minWidth:0,padding:8,overflow:"hidden",textOverflow:"ellipsis",...i.fieldTypeIcons?{display:"flex",alignItems:"center",gap:6,fontSize:12,fontWeight:600,whiteSpace:"nowrap"}:{}},onClick:()=>e.onViewChange({...n,sort:pl(n.sort??[],f.id)}),children:[i.fieldTypeIcons&&B(hr,{type:f.type}),i.fieldTypeIcons?B("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:f.name}):f.name,W?B(Le,{name:W.direction==="asc"?"sortAsc":"sortDesc",size:12,style:{marginLeft:"auto",opacity:0.7}}):null]}),H,i.columnResize&&B("button",{type:"button","aria-label":o("Resize {name}",{name:f.name}),style:{border:0,background:"transparent",position:"absolute",top:0,bottom:0,right:-3,width:7,padding:0,cursor:"col-resize",zIndex:2},onPointerDown:(fe)=>{fe.stopPropagation(),Pi(f.id,fe.clientX,l.size,fe.pointerId,fe.currentTarget)},onKeyDown:(fe)=>{if(fe.key==="ArrowLeft"||fe.key==="ArrowRight")fe.preventDefault(),e.onViewChange({...n,columnWidths:{...n.columnWidths,[f.id]:un(l.size+(fe.key==="ArrowRight"?20:-20))}})}})]})},f.id);return I.length&&e.ui?.ContextMenu?B(e.ui.ContextMenu,{items:I,"aria-label":o("Field menu {name}",{name:f.name}),children:ue},f.id):ue})]})}),Ie("div",{style:{position:"relative",width:_t,height:Jt.getTotalSize()+(qn?Lo:0)},children:[Jt.getVirtualItems().map((l)=>{let f=q.items[l.index];if(f?.kind==="group"){let V=f.label===null?o("Not set"):f.label==="true"?o("Checked"):f.label==="false"?o("Unchecked"):f.label;return B("div",{role:"presentation","data-uibot-group":V,style:{position:"absolute",top:l.start-38,height:l.size,width:_t,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"},children:Ie("button",{type:"button","aria-expanded":!f.collapsed,"aria-label":o(f.collapsed?"Expand group {name}":"Collapse group {name}",{name:V}),disabled:!i.groupCollapse,onClick:()=>xi(f.raw),style:{position:"sticky",left:10,display:"inline-flex",alignItems:"center",gap:8,height:"100%",padding:0,border:0,background:"transparent",color:"inherit",fontSize:12,cursor:i.groupCollapse?"pointer":"default"},children:[i.groupCollapse&&B("span",{"aria-hidden":"true",style:{width:10,fontSize:10,opacity:0.6},children:f.collapsed?"▸":"▾"}),B(oo,{index:f.colorIndex,children:V}),B("span",{style:{opacity:0.6},children:o("{count} records",{count:f.count})})]})},f.key)}let h=f?C[f.index]:void 0;if(f?.kind!=="row"||!h)return null;let W=f.index;return Ie("div",{role:"row",tabIndex:-1,"aria-rowindex":(e.rowOffset??0)+W+2,style:{position:"absolute",top:l.start-38,height:l.size,width:_t},children:[Je>0&&Ie("div",{role:"gridcell",tabIndex:-1,"aria-colindex":1,"aria-label":String((e.rowOffset??0)+W+1),"aria-readonly":"true","aria-selected":ct.has(h.id),style:{...Ut(0,!it&&Qe===0),width:Je,height:l.size,padding:7,boxSizing:"border-box",borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",color:"var(--muted-foreground, #71717a)",textAlign:"center",fontVariantNumeric:"tabular-nums",background:ct.has(h.id)?"var(--accent, #e8f0fe)":"var(--muted, #f4f6f8)"},onMouseDown:(V)=>{if(k||V.button!==0||v.length===0)return;if(V.target.closest("button, input"))return;if(V.preventDefault(),V.ctrlKey||V.metaKey){_o(W),y.current?.focus({preventScroll:!0});return}if(!V.shiftKey)ut({row:W,column:0});ut({row:W,column:v.length-1},!0),y.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!Kn||v.length===0)return;if(!ct.has(h.id))ut({row:W,column:0})},children:[B("span",{"data-uibot-row-number":"",style:{opacity:ct.has(h.id)?0:1},children:(e.rowOffset??0)+W+1}),Ie("span",{"data-uibot-row-actions":"",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",gap:4,opacity:ct.has(h.id)?1:0},children:[B("input",{type:"checkbox","aria-label":o("Select row"),checked:ct.has(h.id),disabled:Boolean(k||j||z||O),onChange:()=>_o(W),onClick:(V)=>V.stopPropagation()}),e.onExpandRecord&&B("button",{type:"button","aria-label":o("Expand record"),title:o("Expand record"),style:{display:"inline-flex",padding:0,border:0,background:"transparent",color:"inherit",cursor:"pointer"},onClick:()=>e.onExpandRecord?.(h),children:B(Le,{name:"expand"})})]})]}),it>0&&B("div",{role:"gridcell",tabIndex:-1,"aria-colindex":Je>0?2:1,"aria-readonly":"true",style:{...Ut(Je,Qe===0),background:"var(--background, white)",boxSizing:"border-box",width:it,height:l.size,padding:7,borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)"},onContextMenu:()=>{if(!Kn)return;if(!ct.has(h.id))ut({row:W,column:0})},children:B("input",{"aria-label":o("Record ID {id}",{id:h.id}),readOnly:!0,value:h.id,style:{width:"100%",border:0,background:"transparent",color:"inherit",fontSize:12},onCopy:(V)=>V.stopPropagation(),onPaste:(V)=>V.stopPropagation(),onKeyDown:(V)=>V.stopPropagation()})}),$n.map((V)=>{let I=v[V.index];if(!I)return null;let H={row:W,column:V.index},ue=ct.has(h.id)&&(E.has(h.id)||A&&H.column>=Fe.firstColumn&&H.column<=Fe.lastColumn),ne=k?.rowId===h.id&&k.field.id===I.id,fe=!ne&&I.type==="checkbox"?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:I,text:Re(h.values[I.id]),disabled:Boolean(!d||j||k||z||O),mode:"inline",autoOpen:!1,onChange:(oe)=>{if(!d||j||k||z||O)return;try{let xe=et(oe,I);Q({rowId:h.id,expectedVersion:h.version,field:I,text:oe,originalText:Re(h.values[I.id])}),Ze({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:h.id,expectedVersion:h.version,values:{[I.id]:xe}}]})}catch(xe){ee(e.locale==="zh-CN"?jt(I,oe,"zh-CN"):xe instanceof Error?xe.message:o("Invalid value"))}},onSave:()=>{},onCancel:pt}):void 0;return Ie("div",{id:`wb-${h.id}-${I.id}`,role:"gridcell",tabIndex:-1,...ne&&I.type==="linkedRecord"?Jo:{},"aria-colindex":V.index+1+Number(Boolean(Je))+Number(Boolean(it)),"aria-selected":ue,"aria-readonly":!d||I.generation==="autoIncrement"||I.type==="blob"||Ne(I),style:{...V.index<Qe?Ut(_n(V.index),V.index===Qe-1):{position:"absolute",left:V.start},width:V.size,height:l.size,padding:ne?0:xt?"0 10px":7,boxSizing:"border-box",borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",overflow:ne?"visible":"hidden",...ne?{zIndex:3}:{},whiteSpace:"nowrap",...xt&&!ne?{display:"flex",alignItems:"center",fontSize:13}:{},...Ye>1&&!ne&&(I.type==="singleLineText"||I.type==="longText")?{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:Ye,whiteSpace:"normal",wordBreak:"break-word",padding:xt?"6px 10px":7}:{},background:ue?"var(--accent, #e8f0fe)":wn(n.columnColors?.[I.id])?.background??"var(--background, white)",outline:Y.row===H.row&&Y.column===H.column?"2px solid #6488bd":"none",outlineOffset:-2},onMouseEnter:()=>{if(!Ue)return;let oe=Math.max(Ue.firstRow-H.row,H.row-Ue.lastRow,0),xe=Math.max(Ue.firstColumn-H.column,H.column-Ue.lastColumn,0);Zt.current=oe>=xe?{...Ue,firstRow:Math.min(H.row,Ue.firstRow),lastRow:Math.max(H.row,Ue.lastRow)}:{...Ue,firstColumn:Math.min(H.column,Ue.firstColumn),lastColumn:Math.max(H.column,Ue.lastColumn)}},onMouseDown:(oe)=>{if(Ue||k)return;if(oe.button!==0)return;oe.preventDefault(),ut(H,oe.shiftKey),y.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!Kn)return;if(!(ct.has(h.id)&&(E.has(h.id)||H.column>=Fe.firstColumn&&H.column<=Fe.lastColumn)))ut(H)},onClick:(oe)=>{if(!k&&!oe.shiftKey&&(I.type==="singleSelect"||I.type==="multipleSelect"))gn(H)},onDoubleClick:()=>gn(H),children:[qo&&H.row===Fe.lastRow&&H.column===Fe.lastColumn&&B("button",{type:"button","aria-label":o("Fill selection"),style:{position:"absolute",right:0,bottom:0,width:8,height:8,padding:0,border:"1px solid var(--background)",background:"var(--primary, #7c2d34)",borderRadius:0,cursor:Ue?"grabbing":"grab",zIndex:4},onMouseDown:(oe)=>{oe.preventDefault(),oe.stopPropagation(),Zt.current=null,Hn(Fe)},onClick:(oe)=>oe.stopPropagation()}),ne&&gt!==void 0&&gt!==null?gt:ne&&I.type==="relation"?B(uo,{locale:e.locale,field:I,value:k.text,label:o("Edit {name}",{name:I.name}),getOptions:e.getRelationOptions,labels:h.linkedRecords?.[I.id],disabled:j,onChange:(oe)=>{ee(i.optimisticEdit?"":o("Unsaved changes")),Q({...k,text:oe}),ie(null),me(null)}}):ne&&Gn!==void 0?B("div",{style:{display:"contents"},...Yo,children:Gn}):ne&&I.type!=="linkedRecord"?B("div",{style:{display:"contents"},...Yo,children:B(so,{field:I,text:k.text,disabled:j||Boolean(e.readOnly),locale:e.locale,ariaLabel:o("Edit {name}",{name:I.name}),onChange:Xt,onSave:(oe)=>void vt(oe),onCancel:pt})}):I.type==="relation"||I.type==="linkedRecord"?Ur(h,I):I.type==="lookup"?Pt(h.values[I.id]):I.type==="formula"||I.type==="rollup"?Gt(h.values[I.id],h.computedErrors?.[I.id]):I.type==="checkbox"&&fe!==void 0&&fe!==null?fe:I.type==="checkbox"&&xt?B(Cr,{checked:h.values[I.id]===!0,label:o("Edit {name}",{name:I.name}),onToggle:!d||j||k||z||O||I.generation==="autoIncrement"?void 0:()=>wi(h,I,h.values[I.id]!==!0)}):I.type==="checkbox"?B("input",{type:"checkbox","aria-label":o("Edit {name}",{name:I.name}),checked:h.values[I.id]===!0,ref:(oe)=>{if(oe)oe.indeterminate=h.values[I.id]==null},disabled:!d||j||Boolean(k)||Boolean(z)||Boolean(O)||I.generation==="autoIncrement",onMouseDown:(oe)=>oe.stopPropagation(),onKeyDown:(oe)=>oe.stopPropagation(),onChange:(oe)=>{if(!d||j||k||z||O)return;let xe=oe.currentTarget.checked;Q({rowId:h.id,expectedVersion:h.version,field:I,text:String(xe),originalText:Re(h.values[I.id])}),Ze({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:h.id,expectedVersion:h.version,values:{[I.id]:xe}}]})}}):I.type==="date"?B("span",{title:Re(h.values[I.id]),style:xt?{opacity:0.75,fontVariantNumeric:"tabular-nums"}:void 0,children:(()=>{let oe=st(I);return oe?nn(h.values[I.id],oe):kn(h.values[I.id])})()}):I.type==="number"&&xt?B("span",{style:{display:"block",width:"100%",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:(()=>{let oe=tn(I);return oe?on(h.values[I.id],oe):Re(h.values[I.id])})()}):xt&&I.type==="singleSelect"&&h.values[I.id]!=null?B(ro,{ids:[h.values[I.id]],field:I,wrap:Ye>1}):xt&&I.type==="multipleSelect"&&Array.isArray(h.values[I.id])?B(ro,{ids:h.values[I.id],field:I,wrap:Ye>1}):I.type==="singleSelect"?I.options?.find((oe)=>oe.id===h.values[I.id])?.name??Re(h.values[I.id]):I.type==="multipleSelect"&&Array.isArray(h.values[I.id])?h.values[I.id].map((oe)=>I.options?.find((xe)=>xe.id===oe)?.name??String(oe)).join(", "):Re(h.values[I.id])]},I.id)})]},h.id)}),qn?B("div",{style:{position:"absolute",top:Jt.getTotalSize(),left:0,width:_t,height:Lo,borderBottom:"1px solid var(--border, #d5d9df)"},children:Ie("button",{type:"button","aria-label":o("Add record below the table"),onClick:e.onAddRecord,style:{position:"sticky",left:0,display:"inline-flex",alignItems:"center",gap:6,height:"100%",padding:"0 12px",border:0,background:"transparent",color:"var(--muted-foreground, #71717a)",cursor:"pointer",font:"inherit"},children:[B(Le,{name:"plus"}),o("Add record")]})}):null]})]}),i.footerStats&&(n.type??"grid")==="grid"&&v.length>0?B(vl,{ui:e.ui,locale:e.locale,t:o,rows:C,total:e.total,descriptor:t,aggregateClient:e.serverFooterStats===!1?void 0:e.aggregate?.client,reloadKey:e.reloadKey,fields:v,columns:$n,width:_t,frozenCount:Qe,frozenLeft:_n,view:n,footerRef:Uo,onChange:e.onViewChange}):null,k&&(O||!(i.optimisticEdit&&k.field.type!=="linkedRecord"))&&!(Qo&&gt!==void 0&&gt!==null)&&Ie("div",{ref:X,...Jo,role:"dialog","aria-label":o("{name} editor",{name:k.field.name}),style:{padding:8,display:"flex",flexWrap:"wrap",gap:8},onKeyDown:(l)=>{if(k.field.type==="linkedRecord"&&l.key==="Escape"&&!j)l.preventDefault(),l.stopPropagation(),pt()},children:[!Qo&&k.field.type!=="linkedRecord"&&(gt??Gn??(k.field.type==="relation"?B(uo,{locale:e.locale,field:k.field,value:k.text,label:o("Edit {name}",{name:k.field.name}),getOptions:e.getRelationOptions,labels:C.find((l)=>l.id===k.rowId)?.linkedRecords?.[k.field.id],disabled:j,onChange:Xt}):B(so,{field:k.field,text:k.text,disabled:j||Boolean(e.readOnly),locale:e.locale,ariaLabel:o("Edit {name}",{name:k.field.name}),onChange:Xt,onSave:(l)=>void vt(l),onCancel:pt}))),k.field.type==="linkedRecord"&&B("div",{style:{width:"100%"},children:B(Rn,{disabled:j,field:k.field,value:JSON.parse(k.text),locale:e.locale,labels:C.find((l)=>l.id===k.rowId)?.linkedRecords?.[k.field.id],client:e.relationClient,onChange:(l)=>{Q({...k,text:JSON.stringify(l)}),ie(null),me(null)}})}),B(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:j,onClick:()=>void vt(),children:j?o("Saving…"):o("Save edit")}),B(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:j,onClick:pt,children:o("Cancel edit")})]}),z&&O&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:O.items.every((l)=>l.op==="delete"),title:O.items.every((l)=>l.op==="delete")?o("Delete {count} records?",{count:O.items.length}):o("Apply {count} row changes in one transaction?",{count:O.items.length}),description:O.items.every((l)=>l.op==="delete")?o("The selected records will be deleted. If any of them changed meanwhile, nothing is deleted."):o("If any record changed or any value is invalid, all changes are rejected."),confirmLabel:j?o("Saving…"):O.items.every((l)=>l.op==="delete")?o("Delete"):o("Confirm changes"),cancelLabel:O.items.every((l)=>l.op==="delete")?o("Cancel"):o("Cancel changes"),busy:j,onConfirm:()=>void Ze(O),onCancel:()=>{re(!1),ie(null),me(null)}}):null,z&&O&&!e.ui?.ConfirmDialog&&Ie(In,{label:o("Confirm bulk change"),busy:j,onCancel:()=>{re(!1),ie(null),me(null)},children:[B("p",{children:o("Apply {count} row changes in one transaction?",{count:O.items.length})}),B("p",{style:{fontSize:12},children:o("If any record changed or any value is invalid, all changes are rejected.")}),B(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:j,onClick:()=>void Ze(O),children:j?o("Saving…"):o("Confirm changes")})," ",B(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:j,onClick:()=>{re(!1),ie(null),me(null)},children:o("Cancel changes")})]}),Et&&O&&Ie("div",{role:"group","aria-label":o("Undo/redo recovery"),style:{padding:8},children:[!j&&K&&B("p",{role:"alert",children:K}),B(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:j||Boolean(e.readOnly),onClick:()=>void Ze(O,void 0,Et.direction),children:o("Retry undo/redo")})," ",Et.rejected&&B(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:j,onClick:()=>{at.current=[],At.current=[],mn(null),ie(null),me(null),ee("")},children:o("Clear undo/redo history")})]}),de&&!Et&&Ie("div",{style:{padding:12},children:[B("strong",{children:o("Current server version {version}",{version:de.version})}),B("div",{style:{display:"grid",gap:8,margin:"8px 0"},children:O?.items.flatMap((l)=>l.op==="update"&&l.id===de.id?Object.entries(l.values).map(([f,h])=>{let W=t.fields.find((I)=>I.id===f),V=(I)=>W?.options?.find((H)=>H.id===I)?.name??Re(I);return Ie("div",{style:{border:"1px solid var(--border,#d5d9df)",borderRadius:6,padding:8},children:[B("strong",{children:W?.name??f}),Ie("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"minmax(90px,auto) 1fr",gap:4},children:[B("dt",{children:o("Your edit")}),B("dd",{style:{margin:0,whiteSpace:"pre-wrap"},children:V(h)}),B("dt",{children:o("Server value")}),B("dd",{style:{margin:0,whiteSpace:"pre-wrap"},children:V(de.values[f])})]})]},f)}):[])}),B(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:j,onClick:()=>{if(!O)return;let l=O.items.map((f)=>f.op!=="insert"&&f.id===de.id?{...f,expectedVersion:de.version}:f);Ze({idempotencyKey:crypto.randomUUID(),items:l})},children:o("Retry against current version")})]}),B("p",{role:"status","aria-live":"polite",style:e.onNotify?fl:{margin:0,padding:K||j?8:0},children:j?o("Saving…"):Et?"":K})]}),Ii=t.fields.filter((l)=>l.type!=="blob"&&l.type!=="linkedRecord"&&!Ne(l)&&l.generation!=="autoIncrement"),Zo=()=>{if(!a||qt||ye.length===0||ye.length>100)return;Ze({idempotencyKey:crypto.randomUUID(),items:ye.map((l)=>({op:"insert",values:Object.fromEntries(Ii.flatMap((f)=>l.values[f.id]===void 0?[]:[[f.id,l.values[f.id]]]))}))})};if(e.renderRecordContextMenu){let l=ye.length===1?ye[0]:void 0;return e.renderRecordContextMenu({children:fn,recordIds:Qt,disabled:qt,onDelete:Wo,...e.onExpandRecord&&l?{onExpand:()=>e.onExpandRecord?.(l)}:{},onCopy:()=>void navigator.clipboard?.writeText(jn()),...a?{onDuplicate:Zo}:{}})}if(!i.recordContextMenu)return fn;let Xo=[...e.onExpandRecord&&ye.length===1?[{id:"expand",icon:B(Le,{name:"expand"}),label:o("Expand record"),onSelect:()=>{let l=ye[0];if(l)e.onExpandRecord?.(l)}}]:[],...a?[{id:"duplicate",icon:B(Le,{name:"copy"}),label:o("Duplicate {count} selected records",{count:ye.length}),disabled:qt||ye.length===0,onSelect:Zo}]:[],{id:"copy",separatorBefore:!0,icon:B(Le,{name:"copy"}),label:o("Copy cells"),disabled:ye.length===0,onSelect:()=>{navigator.clipboard?.writeText(jn())}},...r?[{id:"delete",icon:B(Le,{name:"trash"}),label:o("Delete {count} selected records",{count:ye.length}),separatorBefore:!0,destructive:!0,disabled:qt,onSelect:Wo}]:[]],er=e.ui?.ContextMenu;return er?B(er,{items:Xo,"aria-label":o("Record actions"),children:fn}):B(ci,{block:!0,items:Xo,label:o("Record actions"),children:fn})}function ml({ui:e,paneRef:t,style:n,children:o,...i}){if(e?.ScrollArea)return e.ScrollArea({viewportRef:t,viewportProps:i,style:n,children:o});return B("div",{ref:t,style:n,...i,children:o})}var fl={position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:0},yl=96,bl=560,un=(e)=>Math.max(yl,Math.min(bl,Math.round(e))),Cl=({transform:e})=>({...e,y:0});function hl({id:e,disabled:t,children:n}){let{setNodeRef:o,listeners:i,transform:r,isDragging:a}=sl({id:e,disabled:t});return rt(()=>{if(!a)return;let d=document.body.style.cursor;return document.body.style.cursor="grabbing",()=>{document.body.style.cursor=d}},[a]),n({setNodeRef:o,listeners:t?void 0:i,style:{...r?{transform:`translate3d(${Math.round(r.x)}px, 0, 0)`}:{},...a?{cursor:"grabbing",zIndex:6,opacity:0.9,background:"var(--accent, #e8f0fe)",boxShadow:"0 2px 10px color-mix(in srgb, currentColor 22%, transparent)"}:{}}})}function vl({descriptor:e,aggregateClient:t,reloadKey:n,ui:o,locale:i,t:r,rows:a,total:d,fields:s,columns:p,width:c,frozenCount:u,frozenLeft:g,view:x,footerRef:C,onChange:v}){let P=Or(e,x,s,a,t,n),m=(w,y,S)=>{let N={...x.footerStats??{}};if(y)N[w]=y;else if(S)N[w]="none";else delete N[w];let{footerStats:A,...U}=x;v(Object.keys(N).length?{...U,footerStats:N}:U)};return Ie("div",{ref:C,"data-uibot":"paged-collection-footer",style:{position:"relative",overflow:"hidden",height:34,flex:"none",borderTop:"1px solid var(--border, #d5d9df)",background:"var(--background, white)",fontSize:12,color:"var(--muted-foreground, #71717a)"},children:[B("style",{children:`
20
+ [data-uibot="paged-collection-footer"]:hover [data-uibot-footer-cell],
21
+ [data-uibot="paged-collection-footer"] [data-uibot-footer-cell]:focus-within { opacity: 1 !important; }
22
+ @media (hover: none) {
23
+ [data-uibot="paged-collection-footer"] [data-uibot-footer-cell] { opacity: 1 !important; }
24
+ }
25
+ `}),B("div",{style:{position:"relative",width:c,height:"100%",transform:"translateX(calc(var(--uibot-sx, 0px) * -1))"},children:p.map((w)=>{let y=s[w.index];if(!y)return null;let S=w.index===0,N=x.footerStats?.[y.id],A=N!==void 0?N==="none"?void 0:N:S?"count":void 0,U=A?Br(a,y,A):null,E=(D)=>D===null?"":typeof D==="number"&&A!=="count"&&A!=="filled"&&A!=="empty"?yo(Math.round(D*100)/100,y):typeof D==="number"?D.toLocaleString(i):yo(D,y),_=E(U),G=!t?U:A==="count"?d:P.values[`footer${w.index}`]??null,M=!A?"":!t||A==="count"?E(G):P.status==="loading"?"…":P.status==="error"||G===null?"—":E(G),T=A?A==="count"&&S?r("Footer record count",{count:M}):`${r(`Footer ${A}`)} ${M}`.trim():r("Auto summary"),Y=w.index<u;return B("div",{"data-uibot-footer-cell":"",style:{position:"absolute",left:Y?g(w.index):w.start,width:w.size,height:"100%",boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"flex-end",padding:"0 4px",background:wn(x.columnColors?.[y.id])?.background??"var(--background, white)",zIndex:Y?2:void 0,transform:Y?"translateX(var(--uibot-sx, 0px))":void 0,opacity:A?1:0,transition:"opacity 120ms"},children:B(Fr,{ui:o,chevron:!0,quiet:!0,active:!1,label:T,children:(D)=>Ie("div",{style:{display:"grid",gap:2,minWidth:150},children:[B(Ae,{ui:o,variant:A?"ghost":"outline",size:"sm",onClick:()=>{m(y.id,null,S),D()},children:r("No summary")}),Vr(y).map((k)=>B(Ae,{ui:o,variant:A===k?"outline":"ghost",size:"sm",onClick:()=>{m(y.id,k,S),D()},children:r(`Footer ${k}`)},k)),t&&P.status==="error"&&A&&A!=="count"?B("small",{style:{opacity:0.7,padding:"4px 6px"},children:r("Loaded records fallback: {value}",{value:_||"—"})}):null,(!t||P.status==="error")&&d>a.length?B("small",{style:{opacity:0.7,padding:"4px 6px"},children:r("Summaries cover the {count} loaded records.",{count:a.length})}):null]})})},y.id)})})]})}var Lo=36;export{li as PAGED_COLLECTION_GRID_PRESETS,bl as PAGED_COLUMN_MAX_WIDTH,yl as PAGED_COLUMN_MIN_WIDTH,Pp as PagedCollectionGrid,nn as formatPagedDate,on as formatPagedNumber,kt as instantFromZoned,pl as nextPagedCollectionSort,st as pagedDateFormatting,Xn as pagedDateKind,tn as pagedNumberFormatting,rn as pagedOptionSlot,ao as pickerValue,Vt as resolvePagedCollectionGridFeatures,lo as storedFromPicker};