@uibot/renderer-react 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/HtmlSourceEditor.d.ts +60 -0
- package/dist/collection-activity.d.ts +12 -0
- package/dist/collection-ai.d.ts +17 -0
- package/dist/collection-application.d.ts +5 -0
- package/dist/collection-application.js +25 -0
- package/dist/collection-approval.d.ts +7 -0
- package/dist/collection-attachments.d.ts +10 -0
- package/dist/collection-automation.d.ts +10 -0
- package/dist/collection-calendar-view.d.ts +2 -0
- package/dist/collection-computed.d.ts +4 -0
- package/dist/collection-conversion.d.ts +6 -0
- package/dist/collection-editors.d.ts +40 -0
- package/dist/collection-editors.js +10 -0
- package/dist/collection-form-view.d.ts +2 -0
- package/dist/collection-formula/evaluate.d.ts +18 -0
- package/dist/collection-formula/index.d.ts +1 -0
- package/dist/collection-gallery-view.d.ts +2 -0
- package/dist/collection-grid/cell-display.d.ts +24 -0
- package/dist/collection-grid/cells.d.ts +29 -0
- package/dist/collection-grid/column-color.d.ts +5 -0
- package/dist/collection-grid/date-value.d.ts +13 -0
- package/dist/collection-grid/features.d.ts +76 -0
- package/dist/collection-grid/field-format.d.ts +17 -0
- package/dist/collection-grid/fill.d.ts +10 -0
- package/dist/collection-grid/filter-labels.d.ts +6 -0
- package/dist/collection-grid/footer-aggregate.d.ts +6 -0
- package/dist/collection-grid/footer-stats.d.ts +5 -0
- package/dist/collection-grid/grouping.d.ts +51 -0
- package/dist/collection-grid/index.d.ts +9 -0
- package/dist/collection-grid/paged-field-input.d.ts +22 -0
- package/dist/collection-grid/paged-locale.d.ts +3 -0
- package/dist/collection-grid/paged-model.d.ts +25 -0
- package/dist/collection-grid/relation-editor.d.ts +14 -0
- package/dist/collection-grid/relation-options.d.ts +4 -0
- package/dist/collection-grid/selection.d.ts +4 -0
- package/dist/collection-interaction-state.d.ts +26 -0
- package/dist/collection-kanban-view.d.ts +2 -0
- package/dist/collection-live-changes.d.ts +8 -0
- package/dist/collection-relations.d.ts +20 -0
- package/dist/collection-sharing.d.ts +10 -0
- package/dist/collection-table-view.d.ts +2 -0
- package/dist/collection-transfer.d.ts +12 -0
- package/dist/collection-ui.d.ts +152 -0
- package/dist/collection-views/aggregate.d.ts +39 -0
- package/dist/collection-views/ai-fill-drawer.d.ts +28 -0
- package/dist/collection-views/ai-fill-model.d.ts +35 -0
- package/dist/collection-views/board.d.ts +2 -0
- package/dist/collection-views/calendar.d.ts +4 -0
- package/dist/collection-views/field-config.d.ts +16 -0
- package/dist/collection-views/filter-builder.d.ts +23 -0
- package/dist/collection-views/gallery.d.ts +2 -0
- package/dist/collection-views/icons.d.ts +43 -0
- package/dist/collection-views/menu.d.ts +16 -0
- package/dist/collection-views/model.d.ts +22 -0
- package/dist/collection-views/record-creator.d.ts +31 -0
- package/dist/collection-views/schema-editor.d.ts +38 -0
- package/dist/collection-views/schema-field-settings.d.ts +22 -0
- package/dist/collection-views/schema-styles.d.ts +4 -0
- package/dist/collection-views/shared.d.ts +110 -0
- package/dist/collection-views/table-nav.d.ts +52 -0
- package/dist/collection-views/toolbar-popover.d.ts +24 -0
- package/dist/collection-views/ui.d.ts +45 -0
- package/dist/collection-views/view-settings-sections.d.ts +39 -0
- package/dist/collection-views/view-tabs.d.ts +35 -0
- package/dist/collection-views.d.ts +35 -0
- package/dist/collection-views.js +10 -0
- package/dist/collection-workspace.d.ts +128 -0
- package/dist/collection-workspace.js +26 -0
- package/dist/define-component.d.ts +35 -0
- package/dist/document-collection.d.ts +30 -0
- package/dist/document-view.d.ts +1 -0
- package/dist/html-source-editor.css +84 -0
- package/dist/index.d.ts +121 -0
- package/dist/index.js +25 -0
- package/dist/live-renderer.d.ts +60 -0
- package/dist/paged-collection-grid.d.ts +95 -0
- package/dist/paged-collection-grid.js +25 -0
- package/dist/paged-collection-views.d.ts +15 -0
- package/dist/renderer.d.ts +20 -0
- package/package.json +69 -4
- package/README.md +0 -3
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import{createContext as Xs,useCallback as ed,useContext as td,useLayoutEffect as Ai,useMemo as nd,useRef as ja,useState as od}from"react";var Di=Xs(void 0);function wn(e,t={}){let n=td(Di),o=ja({}),{dirty:i,busy:r}=e,{onDirtyChange:s,onBusyChange:a}=t;Ai(()=>{n?.(o.current,{dirty:i,busy:r}),s?.(i),a?.(r)},[n,i,r,s,a]),Ai(()=>()=>{n?.(o.current),s?.(!1),a?.(!1)},[n,s,a])}function Wa(){let e=ja(new Map),[t,n]=od({dirty:!1,busy:!1}),o=ed((i,r)=>{if(r)e.current.set(i,r);else e.current.delete(i);let s=[...e.current.values()],a=s.some((c)=>c.dirty),l=s.some((c)=>c.busy);n((c)=>c.dirty===a&&c.busy===l?c:{dirty:a,busy:l})},[]);return{...t,report:o}}function Lr(e,t){let n=nd(()=>({active:!0,client:e,id:t}),[e,t]);return Ai(()=>(n.active=!0,()=>{n.active=!1}),[n]),n}import{useCallback as Va,useEffect as Dt,useMemo as jn,useRef as on,useState as Ve}from"react";function Hu(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var Pn=["blue","green","red","orange","gray","teal","purple"];function rd(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 Ga(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((a)=>a.id===o.fieldId),s=i?.type==="number"||i?.type==="rating"||i?.type==="autoNumber"?e.reduce((a,l)=>a+(rd(l.values[o.fieldId])??0),0):0;return{fieldId:o.fieldId,fn:"sum",value:s}})}function Ya(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function id(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function ad(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 Ja(e,t){if(!t)return!0;if(Ya(t)){let n=t.filterSet.map((o)=>Ya(o)?Ja(e,o):id(o)?ad(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 Qa(e,t,n,o){let i=e.views.find((u)=>u.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((u)=>Ja(u,i.filter));if(i.sort?.length)r.sort((u,x)=>{for(let b of i.sort??[]){let v=u.values[b.fieldId],y=x.values[b.fieldId];if(v===y)continue;if(v==null)return 1;if(y==null)return-1;let C=e.fields.find((B)=>B.id===b.fieldId)?.type,p=(B)=>{if(["number","rating","autoNumber"].includes(C??"")&&typeof B==="number")return B;if(["date","createdTime","lastModifiedTime"].includes(C??"")){let R=Date.parse(String(B));if(Number.isFinite(R))return R}return String(B)},k=p(v),P=p(y);if(k===P)continue;let M=k<P?-1:1;return b.direction==="desc"?-M:M}return u.id<x.id?-1:u.id===x.id?0:1});let s=i.projection?.length?e.fields.filter((u)=>i.projection?.includes(u.id)):e.fields,a=o?.search?.trim().toLowerCase();if(a)r=r.filter((u)=>s.some((x)=>String(u.values[x.id]??"").toLowerCase().includes(a)));let l=Ga(r,i.aggregates,e.fields),c=i.group?.fieldId;if(!c)return{view:i,columns:s,rows:r,...l.length?{aggregates:l}:{}};let d=[],g=new Map;for(let u of r){let x=String(u.values[c]??"");if(!g.has(x))g.set(x,[]),d.push(x);g.get(x)?.push(u)}let f=d.map((u)=>{let x=g.get(u)??[];return{key:u,fieldId:c,rows:x,aggregates:Ga(x,i.aggregates,e.fields)}});return{view:i,columns:s,rows:r,groups:f,...l.length?{aggregates:l}:{}}}var Vr=500;function tt(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function tn(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 Br=["short","medium","tall","extra"];function Za(e,t){return t.map((n)=>{let o={},i={};for(let r of e.groupBy){let s=n[r];if(!(r in n)||s!==null&&typeof s!=="string"&&typeof s!=="number"&&typeof s!=="boolean")throw Error(`Invalid aggregate group ${r}.`);o[r]=s}for(let{as:r,fn:s}of e.aggregates){let a=n[r];if(!(r in n)||a!==null&&!(typeof a==="number"&&Number.isFinite(a))&&!((s==="min"||s==="max")&&typeof a==="string"&&Number.isFinite(Date.parse(a))))throw Error(`Invalid aggregate value ${r}.`);i[r]=a}return{groups:o,values:i}})}var ld=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,sd=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function Ur(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function Kt(e,t){return{code:e,...t}}function dd(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function Fi(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function _r(e,t){if(t.aggregates.length===0)return Kt("empty");if(t.aggregates.length>8||t.groupBy.length>3)return Kt("too_many");let n=new Set;for(let i of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(i.fn))return Kt("function");if(!ld.test(i.as)||n.has(i.as)||t.groupBy.includes(i.as))return Kt("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((s)=>s.id===i.fieldId);if(!r)return Kt(i.fn==="sum"?"sum_field":"unknown_field",{alias:i.as,...i.fieldId!==void 0?{fieldId:i.fieldId}:{}});if(i.fn==="sum"&&!Fi(r))return Kt("sum_field",{fieldId:r.id,alias:i.as});if(i.fn==="avg"&&!Fi(r))return Kt("numeric_field",{fieldId:r.id,alias:i.as});if((i.fn==="min"||i.fn==="max")&&!Fi(r)&&r.type!=="date"&&!((r.type==="formula"||r.type==="rollup")&&r.resultType==="date"))return Kt("extrema_field",{fieldId:r.id,alias:i.as});if((i.fn==="filled"||i.fn==="empty")&&!tn(r))return Kt("queryable_field",{fieldId:r.id,alias:i.as});if(i.fn==="count"&&!tn(r))return Kt("count_field",{fieldId:r.id,alias:i.as})}let o=new Set;for(let i of t.groupBy){if(o.has(i))return Kt("duplicate_group",{fieldId:i});o.add(i);let r=e.fields.find((s)=>s.id===i);if(!r)return Kt("unknown_field",{fieldId:i});if(!sd.has(r.type)&&!dd(r))return Kt("not_groupable",{fieldId:i})}return null}var Xa=(e)=>String(e).padStart(2,"0");function kn(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 eo(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=kn(new Date(o),t),s=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second);o+=n-s}return new Date(o)}function qr(e,t){let n=kn(e,t??"UTC");return`${n.year}-${Xa(n.month)}-${Xa(n.day)}`}function gr(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 s=i.formatting;if(s&&"time"in s&&s.time==="none"){let a=kn(t,n);o[i.id]=`${a.year}-${String(a.month).padStart(2,"0")}-${String(a.day).padStart(2,"0")}`}else o[i.id]=t.toISOString()}}return o}var Ei=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],zr=new Set(["pastDays","nextDays","daysAgo","daysFromNow"]),el={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"]},qo=new Set(["isEmpty","isNotEmpty"]);function un(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 tl(e){let t=un(e);return t?el[t]:[]}var Ti=/^\d{4}-\d{2}-\d{2}$/,cd=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function Mi(e){if(!cd(e))return!1;let t=e.mode;if(!Ei.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&&Ti.test(e.date);if(t==="dateRange")return typeof e.date==="string"&&Ti.test(e.date)&&typeof e.to==="string"&&Ti.test(e.to)&&e.date<=e.to;if(zr.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function nl(e,t){if(!e)return"unknown field";let n=un(e),o=t.operator==="contains"&&(n==="number"||n==="checkbox"||n==="date"||n==="singleSelect");if(!n||!(el[n].includes(t.operator)||o))return"operator not allowed";if(qo.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 Mi(i)||typeof i==="string"&&Number.isFinite(Date.parse(i))?null:"date required"}}var ud={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},Ag=Array.from(new Set(Object.values(ud).flat()));var Tg=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 gd(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function Lg(e,t){if(t===e.draft)return e;return{...e,draft:t}}function pd(e){return e.draft!==e.savedContent}function Vg(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 Bg(e,t){if(pd(e))return e;let n=gd(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 Vn=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),ho=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),Co=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,ol=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,$r=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),rl=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every($r)&&new Set(e).size===e.length;function md(e){if(!Vn(e)||!ho(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!$r(e.id)||!Co(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)=>!Vn(t)||!ho(t,["id","name"])||!$r(t.id)||!Co(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&&(!Vn(i)||!ho(i,[...o])||o.some((r)=>!Co(i[r],r==="expression"?2048:512))))return!1}return!0}function _g(e){if(!Vn(e)||!ho(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))||!Co(e.collectionId,512)||!Co(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(!Vn(t)||!ho(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!Co(t.name,200)||!ol(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(md)||new Set(t.fields.map((r)=>r.id)).size!==t.fields.length)return!1;if(!Vn(n)||!ho(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!$r(n.id)||!Co(n.name,200)||!ol(n.version)||!rl(n.columnOrder)||!rl(n.hiddenColumns)||!Vn(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((s)=>Vn(s)&&s.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)=>!Vn(r)||!ho(r,["fieldId","direction"])||!i(r.fieldId)||!["asc","desc"].includes(String(r.direction)))))return!1;return!0}function Oi(e){return e?.type==="singleSelect"||e?.type==="checkbox"}var fd="\x00none";function il(e,t,n=new Set){if(!t)return{items:e.map((s,a)=>({kind:"row",index:a,key:s.id})),rowItem:e.map((s,a)=>a)};let o=[],i=[],r;return e.forEach((s,a)=>{let l=s.values[t.id],c=l==null?fd:String(l);if(!r||r.raw!==c){let d=t.options?.findIndex((g)=>g.id===l)??-1;r={kind:"group",key:`group:${o.length}:${c}`,raw:c,label:l==null?null:t.type==="checkbox"?l===!0?"true":"false":t.options?.[d]?.name??String(l),colorIndex:d,count:0,collapsed:n.has(c)},o.push(r)}if(r.count+=1,r.collapsed)return;i[a]=o.length,o.push({kind:"row",index:a,key:s.id})}),{items:o,rowItem:i}}function Hr(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 Li=34,Ni=38,yd={short:1,medium:2,tall:3,extra:4},Vi=(e)=>yd[e??"short"],al=(e)=>Ni+(Vi(e)-1)*22;function ll(e,t=Ni){return Ni+e.items.reduce((n,o)=>n+(o.kind==="group"?Li:t),0)}function sl(e,t){let n=e?.groupByFieldId;if(!e||!n||(e.type??"grid")!=="grid")return e?.sort;if(!t?.some((o)=>o.id===n&&Oi(o)))return e.sort;return[{fieldId:n,direction:"asc"},...(e.sort??[]).filter((o)=>o.fieldId!==n)]}var cl=["grid","kanban","gallery","calendar","form"],bd=["grid","form"],Bi={search:!0,filter:!0,columns:!0,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!0,tableList:!0,viewManagement:!0,export:!0},hd={search:!0,filter:!1,columns:!1,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!1,tableList:!1,viewManagement:!1,export:!1},Cd={search:!0,filter:!0,columns:!0,rowCreate:!1,rowUpdate:!1,rowDelete:!1,schemaEditor:!1,tableList:!0,viewManagement:!1,export:!0},dl={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:cl},Ui={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:cl},ul={basic:{...dl,...Bi},full:{...Ui,...Bi},simple:{...dl,...hd,viewTypes:bd},workbench:{...Ui,...Bi},readonly:{...Ui,...Cd,recordContextMenu:!1,optimisticEdit:!1}};function vt(e){let{preset:t="basic",...n}=e??{},o={...ul[t],...vd(n)};return o.groupBy?o:{...o,groupCollapse:!1}}function vd(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var xd={"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 le(e="en"){return(t,n={})=>(e==="zh-CN"?xd[t]??t:t).replace(/\{(\w+)\}/g,(o,i)=>String(n[i]??o))}import{useEffect as oi,useRef as Cr,useState as Yt}from"react";import{useId as ec,useState as Xi}from"react";var gn=(e)=>String(e).padStart(2,"0"),wd=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function xt(e){let t=e.formatting;return wd(e)&&t&&"date"in t?t:void 0}function vo(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function qi(e){let t=xt(e);return!t?"auto":t.time==="none"?"date":"datetime"}function _i(e,t,n,o){switch(o){case"YYYY/MM/DD":return`${e}/${gn(t)}/${gn(n)}`;case"MM/DD/YYYY":return`${gn(t)}/${gn(n)}/${e}`;case"DD/MM/YYYY":return`${gn(n)}/${gn(t)}/${e}`;case"YYYY年M月D日":return`${e}年${t}月${n}日`;default:return`${e}-${gn(t)}-${gn(n)}`}}function Bn(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 _i(Number(o[1]),Number(o[2]),Number(o[3]),t.date);let a=new Date(n);if(!Number.isFinite(a.getTime()))return n;let l=kn(a,t.timeZone??"UTC");return _i(l.year,l.month,l.day,t.date)}let i=o?eo({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=kn(i,t.timeZone),s=_i(r.year,r.month,r.day,t.date);if(t.time==="12h"){let a=r.hour%12||12;return`${s} ${a}:${gn(r.minute)} ${r.hour<12?"AM":"PM"}`}return`${s} ${gn(r.hour)}:${gn(r.minute)}`}function xo(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 pr(e,t){let n=e?.findIndex((r)=>r.id===t)??-1,o=n>=0?e?.[n]?.color:void 0,i=Pn.findIndex((r)=>r===o);return i>=0?i:n}function Kr(e,t,n,o,i=!1){let{row:r,column:s}=e;if(t==="ArrowUp")r--;if(t==="ArrowDown")r++;if(t==="ArrowLeft")s--;if(t==="ArrowRight")s++;if(t==="Home")s=0;if(t==="End")s=o-1;if(t==="Tab"){let a=Math.max(0,Math.min(n*o-1,r*o+s+(i?-1:1)));r=Math.floor(a/o),s=a%o}return{row:Math.max(0,Math.min(n-1,r)),column:Math.max(0,Math.min(o-1,s))}}function zi(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 Xe(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function gl(e,t,n,o){let i=zi(n,o),r=[];for(let s=i.firstRow;s<=i.lastRow;s++){let a=[];for(let l=i.firstColumn;l<=i.lastColumn;l++){let c=t[l],d=e[s]?.values[c?.id??""],g=c?.type==="json"&&d!=null?JSON.stringify(d):Xe(d);a.push(/[\t\r\n"]/.test(g)?`"${g.replaceAll('"','""')}"`:g)}r.push(a.join("\t"))}return r.join(`
|
|
2
|
+
`)}function Pd(e,t="en"){let n=le(t),o=[],i=[],r="",s=!1;for(let a=0;a<e.length;a++){let l=e[a];if(l==='"'&&(s||r===""))if(s&&e[a+1]==='"')r+='"',a++;else s=!s;else if(!s&&(l==="\t"||l===`
|
|
3
|
+
`||l==="\r")){if(i.push(r),r="",l!=="\t"){if(o.push(i),i=[],l==="\r"&&e[a+1]===`
|
|
4
|
+
`)a++}}else r+=l}if(s)throw Error(n("Unclosed quoted cell."));if(r||i.length||o.length===0)i.push(r),o.push(i);return o}function pn(e,t,n="en"){let o=le(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=xt(t);if(r){let P=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!P)throw Error(o("{name} needs a date.",{name:t.name}));let[,M,B,R]=P,A=new Date(Date.UTC(Number(M),Number(B)-1,Number(R)));if(A.getUTCMonth()!==Number(B)-1||A.getUTCDate()!==Number(R))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 qr(new Date(e),r.timeZone);return`${M}-${B}-${R}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return eo({year:Number(M),month:Number(B),day:Number(R)},r.timeZone).toISOString()}let s=/^(\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(!s)throw Error(o("{name} needs a date.",{name:t.name}));let[,a,l,c,d,g,f,u,x]=s,b=Number(a),v=Number(l),y=Number(c),p=[31,b%4===0&&(b%100!==0||b%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(v<1||v>12||y<1||y>(p[v-1]??0)||Number(d??0)>23||Number(g??0)>59||Number(f??0)>59||Number(u??0)>23||Number(x??0)>59)throw Error(o("{name} needs a valid calendar date.",{name:t.name}));let k=new Date(e);if(!Number.isFinite(k.getTime()))throw Error(o("{name} needs a date.",{name:t.name}));return k.toISOString()}let i=(r)=>{let s=t.options?.find((a)=>a.id===r||a.name===r);if(!s)throw Error(o("{name} has no option '{option}'.",{name:t.name,option:r}));return s.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 pl(e,t,n,o,i="en"){let r=le(i);try{if(e.length>1048576)throw Error(r("Paste is too large."));let s=Pd(e,i);if(s.length>100||o.row+s.length>t.length)throw Error(r("Paste must fit within the loaded page and contain at most 100 rows."));return{ok:!0,items:s.map((l,c)=>{if(o.column+l.length>n.length)throw Error(r("Paste extends beyond the visible columns."));let d=t[o.row+c];if(!d)throw Error(r("Row is not loaded."));let g={};return l.forEach((f,u)=>{let x=n[o.column+u];if(x?.generation==="autoIncrement")throw Error(r("{name} is auto-generated and cannot be edited.",{name:x.name}));if(x)g[x.id]=pn(f,x,i)}),{op:"update",id:d.id,expectedVersion:d.version,values:g}})}}catch(s){return{ok:!1,message:s instanceof Error?s.message:r("Invalid paste.")}}}function jr(e,t){let n=Xe(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=(c)=>i.find((d)=>d.type===c)?.value??"",s=o.getUTCMilliseconds(),a=r("second"),l=a!=="00"||s?`:${a}${s?`.${String(s).padStart(3,"0")}`:""}`:"";return`${r("year")}-${r("month")}-${r("day")} ${r("hour")}:${r("minute")}${l}`}import{useEffect as kd,useRef as Sd,useState as zo}from"react";import{jsx as mn,jsxs as mr}from"react/jsx-runtime";function to(e){if(e==null)return"—";if(Array.isArray(e))return e.map(to).join(", ");return String(e)}function wo(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((o)=>o.label||o.id).join(", "):void 0)??to(e.values[t.id])}function ml(e,t){return Xe(e.values[t.id])}function Wr({field:e,value:t,labels:n=[],client:o,onChange:i,disabled:r=!1,locale:s,"aria-describedby":a,"aria-invalid":l}){let c=le(s),d=Array.isArray(t)?t.filter((L)=>typeof L==="string"):[],g=Sd(new Set(d));g.current=new Set(d);let[f,u]=zo(""),[x,b]=zo(),[v,y]=zo([]),[C,p]=zo(0),[k,P]=zo({}),[M,B]=zo({rows:[],next:null,error:"",loading:!0}),R=e.link?.collectionId,A=e.link?.displayFieldId;kd(()=>{let L=!0;if(B({rows:[],next:null,error:"",loading:!0}),!o||!R||!A){B({rows:[],next:null,error:c("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return o.query(R,{limit:50,search:f,...x?{cursor:x}:{}}).then((w)=>{if(!L)return;if(!w.ok){B({rows:[],next:null,error:w.error.message,loading:!1});return}P((N)=>({...Object.fromEntries(Object.entries(N).filter(([O])=>g.current.has(O))),...Object.fromEntries(w.data.items.map((O)=>{let D=String(O.values[A]??"");return[O.id,D.trim()?D.slice(0,256):O.id]}))})),B({rows:w.data.items,next:w.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(L)B({rows:[],next:null,error:c("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{L=!1}},[o,R,A,f,x,C]);let _=(L)=>k[L]??n.find((w)=>w.id===L)?.label??L;return mr("fieldset",{disabled:r,"aria-label":c("{name} linked records",{name:e.name}),...a?{"aria-describedby":a}:{},...l?{"aria-invalid":!0}:{},className:"flex min-w-0 flex-col gap-2 rounded-md border p-2",children:[mn("div",{className:"flex flex-wrap gap-1",children:d.map((L)=>mr("span",{className:"rounded border px-2 py-1 text-sm",children:[_(L)," ",mn("button",{type:"button","aria-label":c("Remove {name}",{name:_(L)}),onClick:()=>i(d.filter((w)=>w!==L)),children:"×"})]},L))}),mn("input",{"aria-label":c("Search {name} records",{name:e.name}),type:"search",placeholder:c("Search linked records"),value:f,onChange:(L)=>{u(L.target.value),b(void 0),y([])}}),M.loading&&mn("p",{role:"status",children:c("Loading linked records…")}),M.error&&mr("div",{role:"alert",children:[M.error," ",mn("button",{type:"button",onClick:()=>p((L)=>L+1),children:c("Retry linked records")})]}),mn("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:M.rows.map((L)=>mr("label",{className:"flex items-center gap-2 text-sm",children:[mn("input",{type:"checkbox","aria-label":c("Link {name}",{name:_(L.id)}),checked:d.includes(L.id),disabled:!d.includes(L.id)&&d.length>=100,onChange:(w)=>i(w.target.checked?[...d,L.id]:d.filter((N)=>N!==L.id))}),_(L.id)]},L.id))}),!M.loading&&!M.error&&!M.rows.length&&mn("p",{children:c("No matching records.")}),mr("div",{className:"flex gap-2",children:[mn("button",{type:"button",disabled:!v.length||M.loading,onClick:()=>{b(v.at(-1)),y((L)=>L.slice(0,-1))},children:c("Previous linked records")}),mn("button",{type:"button",disabled:!M.next||M.loading,onClick:()=>{y((L)=>[...L,x]),b(M.next??void 0)},children:c("Next linked records")})]}),mn("small",{children:c("{count} selected · up to 100 per record across all link fields",{count:d.length})})]})}var Rd={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function $o(e,t,n){return t?le(n)(Rd[t]):e==null?"—":String(e)}function fl(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 yl(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function Gr(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function bl(e,t,n){let o=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...Gr(e),filter:yl(e.filter,o)}}function fr(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 hl(e,t,n){let{start:o,end:i}=fr(n);return{...Gr(e),filter:yl(e.filter,{fieldId:t,operator:"onOrAfter",value:o},{fieldId:t,operator:"before",value:i})}}function Yr(e,t){let n={id:"date",name:"Date",type:"date"},o=String(pn(t,n)),i=String(pn(String(e),n));return`${o.slice(0,10)}${i.slice(10)}`}function Po(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 Bt(e,t){let n=t.find((o)=>o.type==="singleLineText"||o.type==="longText");return(n?Xe(e.values[n.id]):"")||e.id}function Sn(e,t,n){if(t.type==="lookup")return to(e);if(t.type==="date"){let o=xt(t);return o?Bn(e,o):jr(e)}if(t.type==="number"){let o=vo(t);return o?xo(e,o):Xe(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return $o(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 Xe(e)}import{useEffect as vl,useId as Ad,useMemo as Dd,useRef as Fd,useState as xl}from"react";var Id=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function no(e){return Id.test(e)}var Un=(e)=>String(e).padStart(2,"0");function Cl(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${Un(t.getMonth()+1)}-${Un(t.getDate())}T${Un(t.getHours())}:${Un(t.getMinutes())}:${Un(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var $i=(e,t)=>{let n=kn(e,t);return`${n.year}-${Un(n.month)}-${Un(n.day)}T${Un(n.hour)}:${Un(n.minute)}`};function Hi(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!no(e))return e.slice(0,10);return $i(new Date(e),t.timeZone??"UTC").slice(0,10)}if(no(e))return $i(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function Ki(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||no(t)))return e;let i=e.length>10?e.slice(11,16):t&&no(t)?$i(new Date(t),n.timeZone).slice(11,16):"00:00",[r,s,a]=e.slice(0,10).split("-").map(Number),[l,c]=i.split(":").map(Number),d=eo({year:r??0,month:s??1,day:a??1,hour:l??0,minute:c??0},n.timeZone);return Number.isFinite(d.getTime())?d.toISOString():e}import{jsx as ko,jsxs as wl}from"react/jsx-runtime";function Ho(e,t,n){if(e.type==="blob")return"";try{return pn(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 ji({field:e,text:t,disabled:n,id:o,label:i,ariaLabel:r,onChange:s,onSave:a,onCancel:l,locale:c="en",submitted:d=!1,describedBy:g}){let f=Dd(()=>le(c),[c]),u=Ad(),x=Fd(null),b=Boolean(a);vl(()=>{if(b)x.current?.querySelector("input,textarea,select")?.focus()},[b]);let v=o??u,y=`${v}-error`,[C,p]=xl(t),[k,P]=xl(!1);vl(()=>p(t),[t]);let M=Ho(e,C,c),R=Boolean(e.required&&C===""&&M)&&!k&&!d?"":M,A=r??i??e.name,_=e.type==="date"&&no(C),L=_&&!M?Cl(C):C,w=[g,R?y:void 0].filter(Boolean).join(" "),N={id:v,"aria-label":A,"aria-invalid":Boolean(R),...w?{"aria-describedby":w}:{},disabled:n,onBlur:()=>P(!0),onKeyDown:(T)=>{if(a||l)T.stopPropagation();let j=e.type==="longText"||e.type==="json";if(T.key==="Tab"&&a)T.preventDefault(),a(T.shiftKey?"previous":"next");else if(T.key==="Enter"&&!T.shiftKey&&a&&(!j||T.ctrlKey||T.metaKey))T.preventDefault(),a();else if(T.key==="Escape"&&l)T.preventDefault(),l()},style:{width:"100%",...b?{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"},O=(T)=>{P(!0),p(T),s(T)},D=(T)=>{if(e.type==="date"&&_&&T){let j=new Date(T);O(Number.isFinite(j.getTime())?j.toISOString():T)}else O(T)},J;if(e.type==="checkbox")J=wl("select",{...N,value:C,onChange:(T)=>O(T.currentTarget.value),children:[!e.required&&ko("option",{value:"",children:f("No value")}),ko("option",{value:"true",children:f("Yes")}),ko("option",{value:"false",children:f("No")})]});else if(e.type==="longText"||e.type==="json")J=ko("textarea",{...N,value:C,rows:e.type==="json"?4:3,onChange:(T)=>O(T.currentTarget.value)});else{let T=e.type==="date"&&!(M&&C)?_?"datetime-local":"date":"text",j=e.type==="blob";J=ko("input",{...N,type:T,inputMode:e.type==="number"?"decimal":void 0,step:_?"0.001":void 0,value:L,readOnly:j,onInput:e.type==="date"?(H)=>D(H.currentTarget.value):void 0,onChange:(H)=>D(H.currentTarget.value)})}return wl("div",{ref:x,className:"grid min-w-0 gap-1",style:b?{height:"100%"}:void 0,children:[i&&ko("label",{className:"text-xs font-medium",htmlFor:v,children:i}),J,R&&ko("span",{id:y,role:"alert",className:"text-xs text-red-600",children:R})]})}import{useEffect as Ed,useRef as Md}from"react";import{jsx as Pl}from"react/jsx-runtime";var Td={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 xe({name:e,size:t=15,style:n}){return Pl("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:Pl("path",{d:Td[e]})})}import{jsx as oo,jsxs as kl,Fragment as Nd}from"react/jsx-runtime";var Ko={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function G({ui:e,style:t,variant:n,size:o,children:i,disabled:r,onClick:s,title:a,ariaLabel:l,icon:c,iconOnly:d,badge:g}){let f=e?.Button,u=c?kl("span",{style:{position:"relative",display:"inline-flex"},children:[oo(xe,{name:c}),g?oo("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,x=d?u:kl(Nd,{children:[u,i]}),b=l,v=a??(d?b:void 0),y=d?"icon":o;if(f)return oo(f,{...n?{variant:n}:{},...y?{size:y}:{},disabled:r,onClick:s,title:v,"aria-label":b,children:x});return oo("button",{type:"button",style:{...c?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?Ko:{},...d?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:r,onClick:s,title:v,"aria-label":b,children:x})}function Ge({ui:e,value:t,options:n,onChange:o,disabled:i,label:r,style:s,"aria-describedby":a,"aria-invalid":l}){let c=e?.Select,d={...a?{"aria-describedby":a}:{},...l?{"aria-invalid":!0}:{}};if(c)return oo(c,{value:t,options:n,onChange:o,disabled:i,"aria-label":r,...d});return oo("select",{"aria-label":r,...d,style:s,disabled:i,value:t,onChange:(g)=>o(g.target.value),children:n.map((g)=>oo("option",{value:g.value,disabled:g.disabled,children:g.label},g.value))})}function Jr({label:e,busy:t,onCancel:n,children:o,alert:i=!1}){let r=Md(null);return Ed(()=>{let s=r.current,a=document.activeElement;if(s?.showModal)s.showModal();else s?.setAttribute("open","");return()=>{if(s?.close?.(),a instanceof HTMLElement&&a.isConnected)a.focus({preventScroll:!0})}},[]),oo("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:(s)=>{if(s.key!=="Tab")return;let a=s.currentTarget,l=[...a.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter((g)=>!g.hidden),c=l[0],d=l.at(-1);if(!c||(s.shiftKey?document.activeElement===c:document.activeElement===d)||!a.contains(document.activeElement)){if(s.preventDefault(),(s.shiftKey?d:c)?.focus(),!c)a.focus()}},tabIndex:-1,onCancel:(s)=>{if(s.preventDefault(),!t)n()},children:o})}import{useEffect as Sl,useRef as yr,useState as Rn}from"react";import{jsx as ke,jsxs as Oe,Fragment as Vd}from"react/jsx-runtime";function Od(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 Ld=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function Wi({descriptor:e,fieldIds:t,query:n,client:o,readOnly:i=!1,reloadKey:r=0,onImported:s,onRefreshSchema:a}){let[l,c]=Rn(null),[d,g]=Rn(null),[f,u]=Rn(null),[x,b]=Rn([]),[v,y]=Rn(""),[C,p]=Rn(!1),[k,P]=Rn(!1),[M,B]=Rn(!0),[R,A]=Rn(null),[_,L]=Rn(!1),w=yr(!1),N=yr(!1),O=yr(!1),D=yr(null),J=yr({client:o,onImported:s,descriptor:e});J.current={client:o,onImported:s,descriptor:e},Sl(()=>(w.current=!0,()=>{w.current=!1,N.current=!1}),[]),Sl(()=>{let K=!0;if(!i)o.imports(e.id).then((ee)=>{if(!K||!w.current||!ee.ok)return;if(b((ae)=>ee.data.map((he)=>{let Ce=ae.find((re)=>re.id===he.id);return Ce&&Ce.version>he.version?Ce:he})),!O.current)u((ae)=>{let he=ee.data.find((Ce)=>Ce.id===ae?.id);return ae&&he&&he.version>ae.version?he:ae})});return()=>{K=!1}},[o,e.id,i,r]);let T=(K)=>{u(K),b((ee)=>[K,...ee.filter((ae)=>ae.id!==K.id)].slice(0,50)),A(null)};async function j(K){if(O.current||i)return;O.current=!0,N.current=!0,p(!0),P(!0),y("");let ee=K;try{while(w.current&&N.current&&ee.status==="ready"){let ae=await J.current.client.advanceImport(e.id,ee.id,ee.version);if(!w.current)break;if(!ae.ok){y(ae.error.message);break}let he=ae.data;if(T(he),he.importedRows>ee.importedRows)J.current.onImported();if(he.version===ee.version&&he.status==="ready"){y("Import paused. Refresh the saved progress before retrying.");break}ee=he}}finally{if(O.current=!1,N.current=!1,w.current)p(!1),P(!1)}}async function H(){if(!l||O.current)return;O.current=!0,p(!0),y("");let K=await o.previewImport(e.id,{...l,expectedSchemaVersion:e.schemaVersion});if(O.current=!1,!w.current)return;if(p(!1),K.ok)g(K.data),c({...l,expectedSchemaVersion:K.data.schemaVersion,mapping:K.data.mapping});else y(K.error.message)}async function me(){if(!l||!d||d.missingRequiredFieldIds.length||!d.totalRows||O.current||i)return;O.current=!0,p(!0),y(""),D.current??=crypto.randomUUID();let K=await o.createImport(e.id,{...l,idempotencyKey:D.current});if(O.current=!1,!w.current)return;if(p(!1),K.ok)T(K.data),c(null),g(null),D.current=null,j(K.data);else y(K.error.message)}async function Z(){if(!f||O.current||i)return;if(f.status==="ready"){j(f);return}O.current=!0,p(!0),y("");let K=a?await a():J.current.descriptor;if(!K){O.current=!1,p(!1),y("Refresh the collection schema and try again.");return}let ee=await o.resumeImport(e.id,f.id,f.version,K.schemaVersion);if(O.current=!1,!w.current)return;if(p(!1),ee.ok)T(ee.data),j(ee.data);else y(ee.error.message)}async function fe(K){if(!f)return;let ee=await o.importErrors(e.id,f.id,{limit:100,...K===void 0?{}:{cursor:K},expectedVersion:f.version});if(!w.current)return;if(ee.ok)A(ee.data);else y(ee.error.message)}async function X(K=!1){if(C||O.current)return;O.current=!0,p(!0),y("");let ee=K&&f?await o.exportImportErrors(e.id,f.id):await o.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:M});if(O.current=!1,!w.current)return;if(p(!1),ee.ok)Od(ee.data),y(`${ee.data.rowCount} rows downloaded${ee.data.protectedCells?`; ${ee.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else y(ee.error.message)}return Oe("details",{className:"min-w-0 rounded-lg border p-4",children:[ke("summary",{className:"cursor-pointer text-sm font-medium",children:"CSV import and export"}),Oe("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[Oe("div",{className:"flex flex-wrap items-center gap-3",children:[ke("button",{type:"button",disabled:C||!t.length,onClick:()=>void X(),children:"Export CSV"}),Oe("label",{className:"flex items-center gap-2 text-sm",children:[ke("input",{type:"checkbox",checked:M,onChange:(K)=>B(K.target.checked)}),"Spreadsheet view"]})]}),ke("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&&Oe(Vd,{children:[Oe("label",{className:"flex min-w-0 flex-col gap-2 text-sm",children:["CSV file",ke("input",{"aria-label":"CSV file",className:"max-w-full",type:"file",accept:".csv,text/csv",disabled:C,onChange:async(K)=>{let ee=K.target.files?.[0];if(!ee)return;if(y(""),g(null),c(null),D.current=null,ee.size>20971520){y("Choose a UTF-8 CSV file no larger than 20 MiB.");return}p(!0),O.current=!0;try{let ae=new TextDecoder("utf-8",{fatal:!0}).decode(await ee.arrayBuffer());if(w.current)c({fileName:ee.name,csv:ae,expectedSchemaVersion:e.schemaVersion})}catch{if(w.current)y("The file must be valid UTF-8 text.")}finally{if(O.current=!1,w.current)p(!1)}}})]}),l&&Oe("div",{className:"flex flex-wrap gap-3",children:[ke("span",{className:"break-all text-sm",children:l.fileName}),ke("button",{type:"button",disabled:C,onClick:()=>void H(),children:"Preview CSV"})]}),ke("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."}),d&&l&&Oe("div",{className:"flex min-w-0 flex-col gap-3",children:[Oe("p",{className:"text-sm",children:[d.totalRows," rows · ",d.validRows," valid · ",d.invalidRows," ","invalid · ",d.ignoredColumns.length," skipped columns"]}),d.headers.map((K,ee)=>Oe("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[Oe("span",{className:"max-w-64 break-all",children:["Column ",ee+1,": ",K||"(empty)"]}),Oe("select",{"aria-label":`Column ${ee+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:l.mapping?.[ee]??"",disabled:C,onChange:(ae)=>{let he=[...l.mapping??d.mapping];he[ee]=ae.target.value||null,c({...l,mapping:he}),g(null),D.current=null},children:[ke("option",{value:"",children:"Skip column"}),e.fields.filter((ae)=>!tt(ae)).map((ae)=>Oe("option",{value:ae.id,children:[ae.name," (",ae.id,")",ae.required?" · required":""]},ae.id))]})]},`${ee}:${K}`)),d.missingRequiredFieldIds.length>0&&Oe("p",{role:"alert",children:["Map required fields: ",d.missingRequiredFieldIds.join(", ")]}),ke("div",{className:"max-w-full overflow-x-auto",children:Oe("table",{className:"w-full text-xs",children:[Oe("caption",{children:["First ",d.sample.length," normalized rows; row numbers include the header."]}),ke("thead",{children:Oe("tr",{children:[ke("th",{children:"Row"}),ke("th",{children:"Normalized values"}),ke("th",{children:"Error"})]})}),ke("tbody",{children:d.sample.map((K)=>Oe("tr",{children:[ke("td",{children:K.rowNumber}),ke("td",{className:"max-w-96 break-all",children:Ld(K.values)}),ke("td",{children:K.error?.code??""})]},K.rowNumber))})]})}),ke("button",{type:"button",className:"self-start",disabled:C||!d.totalRows||d.missingRequiredFieldIds.length>0,onClick:()=>void me(),children:"Confirm import"})]}),Oe("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",Oe("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:f?.id??"",disabled:C,onChange:async(K)=>{if(!K.target.value){u(null);return}let ee=await o.importJob(e.id,K.target.value);if(w.current)if(ee.ok)T(ee.data),L(!1);else y(ee.error.message)},children:[ke("option",{value:"",children:"Choose saved progress…"}),x.map((K)=>Oe("option",{value:K.id,children:[K.fileName," · ",K.processedRows,"/",K.totalRows," · ",K.status]},K.id))]})]}),ke("button",{type:"button",className:"self-start",disabled:C,onClick:async()=>{let K=await o.imports(e.id);if(w.current)if(K.ok)b(K.data);else y(K.error.message)},children:"Refresh saved imports"}),f&&Oe("div",{className:"flex flex-col gap-3",children:[Oe("p",{role:"status",children:[k?"Importing":f.status==="ready"?"Paused":f.status==="schemaChanged"?"Schema changed — confirm before continuing":f.status==="completed"?"Completed":"Cancelled"," ","· ",f.processedRows," of ",f.totalRows," processed · ",f.importedRows," imported ·"," ",f.failedRows," failed"]}),ke("progress",{"aria-label":"Import progress",max:f.totalRows,value:f.processedRows,className:"max-w-full"}),ke("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."}),Oe("div",{className:"flex flex-wrap gap-3",children:[k&&ke("button",{type:"button",onClick:()=>{N.current=!1,P(!1)},children:"Pause import"}),!k&&(f.status==="ready"||f.status==="schemaChanged")&&ke("button",{type:"button",disabled:C,onClick:()=>void Z(),children:f.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(f.status==="ready"||f.status==="schemaChanged")&&ke("button",{type:"button",disabled:C,onClick:()=>L(!0),children:"Cancel import"}),ke("button",{type:"button",disabled:C||!f.failedRows,onClick:()=>void fe(),children:"Show import errors"}),ke("button",{type:"button",disabled:C||!f.failedRows,onClick:()=>void X(!0),children:"Download all import errors"})]}),_&&Oe("div",{children:[Oe("p",{children:["Stop remaining rows? The ",f.importedRows," imported records will remain."]}),ke("button",{type:"button",disabled:C,onClick:async()=>{O.current=!0,p(!0);let K=await o.cancelImport(e.id,f.id);if(O.current=!1,!w.current)return;if(p(!1),K.ok)T(K.data),L(!1);else y(K.error.message)},children:"Confirm cancellation"}),ke("button",{type:"button",onClick:()=>L(!1),children:"Keep import"})]}),R&&Oe("div",{className:"max-w-full overflow-x-auto",children:[Oe("table",{className:"w-full text-xs",children:[Oe("caption",{children:[R.total," failed rows"]}),ke("thead",{children:Oe("tr",{children:[ke("th",{children:"Row"}),ke("th",{children:"Field"}),ke("th",{children:"Error"})]})}),ke("tbody",{children:R.items.map((K)=>Oe("tr",{children:[ke("td",{children:K.rowNumber}),ke("td",{children:K.fieldId??""}),ke("td",{children:K.code})]},K.rowNumber))})]}),R.nextCursor!==null&&ke("button",{type:"button",onClick:()=>void fe(R.nextCursor??void 0),children:"Next errors"})]})]})]}),v&&ke("p",{role:"alert",className:"break-words text-sm",children:v})]})]})}import{useEffect as Rl,useRef as So,useState as Ro}from"react";import{jsx as Ye,jsxs as Ut,Fragment as Ud}from"react/jsx-runtime";var Qr=[{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 Bd({descriptor:e,client:t,onConverted:n}){let o=e.fields.filter((T)=>Qr.some((j)=>j.type===T.type)),[i,r]=Ro(o[0]?.id??""),s=o.find((T)=>T.id===i)??o[0],[a,l]=Ro(s?.type??"singleLineText"),[c,d]=Ro(s?.required??!1),[g,f]=Ro(s?.options?.map((T)=>`${T.id}=${T.name}`).join(`
|
|
5
|
+
`)??""),[u,x]=Ro(null),[b,v]=Ro(""),[y,C]=Ro(!1),p=So(null),k=So(null),P=So(0),M=So(e);M.current=e;let B=p.current?.field??s,R=y||p.current!==null,A=`${e.id}:${e.schemaVersion}:${JSON.stringify(e.fields)}`,_=So(e.fields);_.current=e.fields;let L=So(A);L.current=A;let w=So(!0);Rl(()=>(w.current=!0,()=>{w.current=!1,P.current++}),[]),Rl(()=>{if(L.current!==A)return;if(p.current&&k.current===e.id)return;P.current++;let T=_.current.find((j)=>j.id===i&&Qr.some((H)=>H.type===j.type))??_.current.find((j)=>Qr.some((H)=>H.type===j.type));if(T)r(T.id),l(T.type),d(T.required??!1),f(T.options?.map((j)=>`${j.id}=${j.name}`).join(`
|
|
6
|
+
`)??"");x(null),p.current=null,k.current=null,v(""),C(!1)},[A,i,e.id]);let N=()=>{x(null),p.current=null,k.current=null,P.current++,v("")},O=(T)=>{r(T.id),l(T.type),d(T.required??!1),f(T.options?.map((j)=>`${j.id}=${j.name}`).join(`
|
|
7
|
+
`)??""),N()};if(!B)return null;let D=()=>{let T={id:B.id,name:B.name,type:a,required:c};if(a==="singleSelect"||a==="multipleSelect")T.options=g.split(`
|
|
8
|
+
`).filter((j)=>j.trim()).map((j)=>{let H=j.indexOf("=");if(H<1)throw Error("Each option must use stable_id=Display name.");return{id:j.slice(0,H).trim(),name:j.slice(H+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:T}},J=()=>w.current&&L.current===A;return Ut("details",{className:"rounded-lg border p-4",children:[Ye("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),Ut("div",{className:"mt-4 flex flex-col gap-3",children:[Ye("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."}),Ut("label",{children:["Field"," ",Ut("select",{"aria-label":"Conversion field",value:B.id,disabled:R,onChange:(T)=>{let j=o.find((H)=>H.id===T.target.value);if(j)O(j)},children:[p.current&&!o.some((T)=>T.id===B.id)&&Ye("option",{value:B.id,children:B.name}),o.map((T)=>Ye("option",{value:T.id,children:T.name},T.id))]})]}),Ut("label",{children:["Target type"," ",Ye("select",{"aria-label":"Conversion target type",value:a,disabled:R,onChange:(T)=>{l(T.target.value),N()},children:Qr.map((T)=>Ye("option",{value:T.type,children:T.label},T.type))})]}),Ut("label",{children:[Ye("input",{type:"checkbox",checked:c,disabled:R,onChange:(T)=>{d(T.target.checked),N()}})," ","Required after conversion"]}),(a==="singleSelect"||a==="multipleSelect")&&Ut("label",{children:["Stable option IDs and display names",Ye("textarea",{"aria-label":"Conversion options",className:"block w-full rounded border p-2",disabled:R,value:g,onChange:(T)=>{f(T.target.value),N()},placeholder:`open=Open
|
|
9
|
+
done=Done`})]}),b&&Ye("p",{role:"alert",className:"text-sm text-destructive",children:b}),Ye("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:R,onClick:async()=>{let T;try{T=D()}catch(j){v(j instanceof Error?j.message:"Invalid conversion options.");return}C(!0),v(""),x(null),p.current=null;try{let j=await t.previewConversion(e.id,T);if(!J())return;if(j.ok)x(j.data);else v(j.error.message)}catch{if(J())v("Preview unavailable. Your draft is kept.")}finally{if(J())C(!1)}},children:y?"Working…":"Preview conversion"}),u&&Ut(Ud,{children:[Ut("p",{role:"status",children:[u.validRows," valid · ",u.invalidRows," invalid"]}),Ut("p",{className:"text-xs",children:["Preview covers ",u.totalRows," records. Samples and errors show at most 20 records."]}),Ye("div",{className:"overflow-x-auto",children:Ut("table",{className:"w-full text-sm",children:[Ye("thead",{children:Ut("tr",{children:[Ye("th",{children:"Record"}),Ye("th",{children:"Before"}),Ye("th",{children:"After"}),Ye("th",{children:"Error"})]})}),Ye("tbody",{children:u.sample.map((T)=>Ut("tr",{children:[Ye("td",{className:"max-w-32 break-all",children:T.id}),Ye("td",{className:"max-w-48 break-words",children:JSON.stringify(T.before)}),Ye("td",{className:"max-w-48 break-words",children:JSON.stringify(T.after)}),Ye("td",{children:T.error})]},T.id))})]})}),u.errors.length>0&&Ye("ul",{children:u.errors.map((T)=>Ut("li",{children:[Ye("span",{className:"break-all",children:T.id}),": ",Ye("span",{children:T.code})]},T.id))}),Ye("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:y||u.invalidRows>0,onClick:async()=>{if(!p.current)k.current=e.id,P.current++;p.current??={expectedSchemaVersion:u.schemaVersion,field:u.field,previewToken:u.previewToken,idempotencyKey:crypto.randomUUID()};let T=p.current,j=P.current,H=()=>w.current&&M.current.id===e.id&&j===P.current;C(!0),v("");try{let me=await t.convertField(e.id,T);if(!H())return;if(me.ok){if(x(null),p.current=null,k.current=null,me.data.descriptor.schemaVersion>=M.current.schemaVersion)n(me.data.descriptor)}else if(v(me.error.message),me.error.status===409)x(null),p.current=null,k.current=null}catch{if(H())v("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(H())C(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as _d,useRef as Gi,useState as Il}from"react";import{jsx as Al,jsxs as zd}from"react/jsx-runtime";function qd({collectionIds:e,client:t,onChanges:n,pollIntervalMs:o=2000}){let i=JSON.stringify([...new Set(e)].sort()),r=Gi(i);r.current=i;let s=Gi(n);s.current=n;let a=Gi(()=>{}),[l,c]=Il("connecting"),[d,g]=Il(!1);return _d(()=>{let f=JSON.parse(i),u=new Map,x=!1,b=!1,v=0,y,C=()=>!x&&r.current===i,p=Math.max(50,Math.min(60000,o)),k=async()=>{if(!C()||b)return;b=!0,g(!0);let B=!1;try{let R=v>0;for(let A of f){let _=u.get(A),L=await t.changes(A,{..._!==void 0?{cursor:_}:{},limit:100});if(!C())return;if(!L.ok)throw c(L.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let w=_===void 0;if(w||R||L.data.items.length>0)await s.current(A,L.data,w);if(!C())return;u.set(A,L.data.cursor),B||=L.data.hasMore}v=0,c("live")}catch{if(v++,C())c((R)=>R==="expired"?"expired":"offline")}finally{if(b=!1,C())g(!1),y=setTimeout(()=>{k()},B&&v===0?0:Math.min(30000,p*2**Math.min(v,8)))}},P=()=>{if(y!==void 0)clearTimeout(y);k()};a.current=P,c("connecting"),k();let M=()=>{if(document.visibilityState==="visible")P()};return window.addEventListener("online",P),document.addEventListener("visibilitychange",M),()=>{if(x=!0,y!==void 0)clearTimeout(y);window.removeEventListener("online",P),document.removeEventListener("visibilitychange",M)}},[i,t,o]),zd("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[Al("p",{role:"status",children:l==="live"?"Live updates":l==="connecting"?"Connecting live updates…":l==="expired"?"Session expired. Renew your session; drafts are kept.":"Connection interrupted. Drafts are kept."}),(l==="offline"||l==="expired")&&Al("button",{type:"button",className:"rounded border px-2 py-1",disabled:d,onClick:()=>a.current(),children:"Reconnect now"})]})}import{useEffect as Zr,useRef as ro,useState as jt}from"react";import{jsx as De,jsxs as Ue,Fragment as Qi}from"react/jsx-runtime";var Ji={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function br(e){try{return await e()}catch{return{ok:!1,error:Ji}}}function Yi({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return Ue("div",{className:"min-w-0",children:[De("strong",{children:t}),De("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&&Ue(Qi,{children:[De("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),De("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 $d({descriptor:e,recordId:t,client:n,readOnly:o=!1,onCommitted:i,registerRefresh:r}){let[s,a]=jt(null),[l,c]=jt(null),[d,g]=jt(null),[f,u]=jt(),[x,b]=jt(),[v,y]=jt([]),[C,p]=jt([]),[k,P]=jt(""),[M,B]=jt(null),[R,A]=jt(null),[_,L]=jt(null),[w,N]=jt(!1),[O,D]=jt(""),J=ro(null),T=ro(null),j=ro(n);j.current=n;let H=ro(!1),me=ro(0),Z=`${e.id}:${t}`,fe=ro(Z);fe.current=Z;let X=ro({historyBefore:f,commentBefore:x});X.current={historyBefore:f,commentBefore:x};let K=ro(async()=>{}),ee=(F=Z)=>H.current&&fe.current===F&&j.current===n,ae=async()=>{let F=Z,Y=++me.current,V=X.current,[de,we]=await Promise.all([br(()=>n.history(e.id,t,{...V.historyBefore===void 0?{}:{before:V.historyBefore},limit:20})),br(()=>n.comments(e.id,t,{...V.commentBefore===void 0?{}:{before:V.commentBefore},limit:50}))]);if(!ee(F)||Y!==me.current)throw Error("Refresh superseded");if(!de.ok||!we.ok)throw D(!de.ok?de.error.message:!we.ok?we.error.message:Ji.message),Error("Activity refresh failed");c(de.data),g(we.data),a(F)};K.current=ae,Zr(()=>(H.current=!0,()=>{H.current=!1,me.current++}),[]),Zr(()=>(r?.(()=>K.current()),()=>r?.(null)),[r]),Zr(()=>{if(fe.current!==Z)return;c(null),g(null),a(null),u(void 0),b(void 0),y([]),p([]),X.current={historyBefore:void 0,commentBefore:void 0},P(""),B(null),A(null),L(null),J.current=null,T.current=null,N(!1),D("")},[Z]),Zr(()=>{if(fe.current!==Z||j.current!==n||X.current.historyBefore!==f||X.current.commentBefore!==x)return;K.current().catch(()=>{})},[Z,n,f,x]);let he=(F)=>{let Y=J.current;if(Y?.signature===F)return Y.key;let V={signature:F,key:crypto.randomUUID()};return J.current=V,V.key},Ce=async(F)=>{if(w||o||!d||s!==Z)return;let Y=F==="delete"?R:M;if(F!=="create"&&(!Y||Y.authorId!==d.actorId))return;let V=F==="create"?k:M?.draft??"";if(F!=="delete"&&(!V.trim()||V.length>4000||V.includes("\x00"))){D("Comments require 1–4,000 characters.");return}let de=he(JSON.stringify([F,Y?.id,Y?.version,V]));N(!0),D("");let we=await br(async()=>{if(F==="create")return n.createComment(e.id,t,{text:V,idempotencyKey:de});if(!Y)return{ok:!1,error:Ji};if(F==="edit")return n.editComment(e.id,t,Y.id,{text:V,expectedVersion:Y.version,idempotencyKey:de});return n.deleteComment(e.id,t,Y.id,{expectedVersion:Y.version,idempotencyKey:de})});if(!ee())return;if(N(!1),!we.ok){D(we.error.message);return}if(J.current=null,F==="create")P("");else if(F==="edit")B(null);else A(null);if(F==="create"&&x!==void 0)b(void 0),p([]);else await K.current().catch(()=>{})},re=async(F)=>{if(w||o||!l||s!==Z)return;N(!0),D(""),T.current=null;let Y={targetVersion:F,expectedCurrentVersion:l.currentVersion,expectedSchemaVersion:e.schemaVersion},V=await br(()=>n.previewUndo(e.id,t,Y));if(!ee())return;if(N(!1),V.ok)L(V.data);else L(null),D(V.error.message)},Se=async()=>{if(w||o||s!==Z||!_&&!T.current)return;let F=T.current;if(!F){if(!_)return;F={targetVersion:_.targetVersion,expectedCurrentVersion:_.currentVersion,expectedSchemaVersion:_.schemaVersion,idempotencyKey:crypto.randomUUID()},T.current=F}let Y=F;N(!0),D("");let V=await br(()=>n.undo(e.id,t,Y));if(!ee())return;if(N(!1),!V.ok){if(V.error.code==="version_conflict"||V.error.code==="reference_conflict"||V.error.code==="validation")T.current=null,L(null);D(V.error.message),await K.current().catch(()=>{});return}T.current=null,L(null),i(V.data),u(void 0),y([]),await K.current().catch(()=>{})},pe=d?.items.find((F)=>F.id===M?.id),qe=M&&pe&&pe.version!==M.version,S=_&&(_.currentVersion!==l?.currentVersion||_.schemaVersion!==e.schemaVersion);return Ue("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[Ue("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ue("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),De("button",{type:"button",disabled:w,onClick:()=>{D(""),K.current().catch(()=>{})},children:"Refresh activity"})]}),O&&De("p",{role:"alert",className:"text-sm text-destructive",children:O}),!l||!d||s!==Z?De("p",{role:"status",children:"Loading record activity…"}):Ue(Qi,{children:[Ue("p",{role:"status",children:["Current version ",l.currentVersion,l.currentDeleted?" · Deleted record":""]}),De("h3",{className:"font-medium",children:"Comments"}),d.items.length===0&&De("p",{className:"text-sm",children:"No comments yet."}),De("ol",{className:"flex flex-col gap-3",children:d.items.map((F)=>Ue("li",{className:"min-w-0 rounded border p-3",children:[Ue("p",{className:"break-all text-xs",children:[F.authorId," · ",F.updatedAt," · version ",F.version]}),De("p",{className:"whitespace-pre-wrap break-words text-sm",children:F.text??"Comment deleted"}),!o&&F.text!==null&&F.authorId===d.actorId&&Ue("div",{className:"flex gap-3",children:[De("button",{type:"button",disabled:w,onClick:()=>{B({...F,draft:F.text??""}),A(null),J.current=null},children:"Edit comment"}),De("button",{type:"button",disabled:w,onClick:()=>{A(F),B(null),J.current=null},children:"Delete comment"})]})]},F.id))}),Ue("div",{className:"flex gap-3",children:[De("button",{type:"button",disabled:w||!C.length,onClick:()=>{b(C.at(-1)),p((F)=>F.slice(0,-1))},children:"Newer comments"}),De("button",{type:"button",disabled:w||d.nextCursor===null,onClick:()=>{p((F)=>[...F,x]),b(d.nextCursor??void 0)},children:"Older comments"})]}),!o&&Ue(Qi,{children:[M&&Ue("div",{className:"flex flex-col gap-2",children:[Ue("label",{children:["Edit comment text",De("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:w,maxLength:4000,value:M.draft,onChange:(F)=>{B({...M,draft:F.target.value}),J.current=null}})]}),qe&&Ue("div",{role:"status",children:[De("p",{children:"This comment changed. Your draft and original version are kept."}),Ue("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",pe.text??"Comment deleted"]}),pe.text!==null&&pe.authorId===d.actorId&&De("button",{type:"button",disabled:w,onClick:()=>{B({...pe,draft:M.draft}),J.current=null},children:"Use current comment version"})]}),Ue("div",{className:"flex gap-3",children:[De("button",{type:"button",disabled:w||M.authorId!==d.actorId,onClick:()=>void Ce("edit"),children:"Save comment"}),De("button",{type:"button",disabled:w,onClick:()=>{B(null),J.current=null},children:"Cancel comment edit"})]})]}),R&&Ue("div",{children:[De("p",{children:"Delete this comment? A deletion marker will remain."}),De("p",{className:"whitespace-pre-wrap break-words",children:R.text}),De("button",{type:"button",disabled:w||R.authorId!==d.actorId,onClick:()=>void Ce("delete"),children:"Confirm delete comment"}),De("button",{type:"button",disabled:w,onClick:()=>A(null),children:"Cancel delete comment"})]}),Ue("label",{children:["New comment",De("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:w,maxLength:4000,value:k,onChange:(F)=>{P(F.target.value),J.current=null}})]}),De("button",{type:"button",className:"self-start",disabled:w||!k.trim(),onClick:()=>void Ce("create"),children:"Add comment"})]}),De("h3",{className:"font-medium",children:"Record history"}),De("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."}),De("ol",{className:"flex flex-col gap-3",children:l.items.map((F)=>Ue("li",{className:"min-w-0 rounded border p-3",children:[Ue("p",{className:"break-all text-xs",children:["Version ",F.version," · ",F.operation," · schema ",F.schemaVersion," · ",F.actorId," ·"," ",F.createdAt]}),Ue("details",{children:[Ue("summary",{children:["Stored values at version ",F.version]}),De(Yi,{record:F.snapshot,label:`Version ${F.version}`})]}),!o&&F.version<l.currentVersion&&Ue("button",{type:"button",disabled:w,onClick:()=>void re(F.version),children:["Preview restore version ",F.version]})]},F.id))}),Ue("div",{className:"flex gap-3",children:[De("button",{type:"button",disabled:w||!v.length,onClick:()=>{u(v.at(-1)),y((F)=>F.slice(0,-1))},children:"Newer history"}),De("button",{type:"button",disabled:w||l.nextCursor===null,onClick:()=>{y((F)=>[...F,f]),u(l.nextCursor??void 0)},children:"Older history"})]}),!o&&_&&Ue("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[Ue("h3",{children:["Restore version ",_.targetVersion," as a new version"]}),Ue("p",{children:["Current version ",_.currentVersion," · schema ",_.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),Ue("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[De(Yi,{record:_.before,label:"Current stored values"}),De(Yi,{record:_.target,label:"Values to restore"})]}),S&&!T.current&&De("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),Ue("div",{className:"flex gap-3",children:[De("button",{type:"button",disabled:w||!!S&&!T.current,onClick:()=>void Se(),children:T.current?"Retry undo":"Confirm restore"}),De("button",{type:"button",disabled:w,onClick:()=>{L(null),T.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as Xr,useRef as io,useState as _n}from"react";import{jsx as wt,jsxs as Wt,Fragment as Dl}from"react/jsx-runtime";async function ei(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 Hd(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let o of t)n+=String.fromCharCode(o);return btoa(n)}function Kd({collectionId:e,recordId:t,client:n,readOnly:o=!1,registerRefresh:i}){let r=`${e}:${t}`,s=io({identity:r,client:n});s.current={identity:r,client:n};let a=io(!1),l=io(0),c=io(0),[d,g]=_n(null),[f,u]=_n(null),[x,b]=_n(),[v,y]=_n([]),C=io(x);C.current=x;let[p,k]=_n(null),[P,M]=_n(null),B=io(null),R=io(null),[A,_]=_n(!1),[L,w]=_n(!1),[N,O]=_n(""),D=()=>a.current&&s.current.identity===r&&s.current.client===n,J=async()=>{let Z=++l.current,fe=await ei(()=>n.list(e,t,{limit:20,...C.current===void 0?{}:{before:C.current}}));if(!D()||Z!==l.current)throw Error("Refresh superseded");if(!fe.ok)throw O(fe.error.message),Error("Attachment refresh failed");u(fe.data),g(r)},T=io(J);T.current=J,Xr(()=>(a.current=!0,()=>{a.current=!1,++l.current,++c.current}),[]),Xr(()=>{if(s.current.identity!==r||s.current.client!==n)return;g(null),u(null),k(null),M(null),B.current=null,_(!1),w(!1),O(""),b(void 0),y([]),C.current=void 0,++c.current,T.current().catch(()=>{})},[r,n]),Xr(()=>{if(C.current===x&&d===r)T.current().catch(()=>{})},[x,r,d]),Xr(()=>(i?.(()=>T.current()),()=>i?.(null)),[i]);let j=async()=>{if(A||o||!p||d!==r)return;let Z=p;_(!0),O("");let fe=await ei(()=>n.upload(e,t,Z));if(!D())return;if(_(!1),!fe.ok){O(fe.error.message);return}if(k(null),R.current)R.current.value="";b(void 0),y([]),C.current=void 0,await T.current().catch(()=>{})},H=async()=>{if(A||o||!P||P.authorId!==f?.actorId||d!==r)return;B.current??=crypto.randomUUID();let Z=P,fe=B.current;_(!0),O("");let X=await ei(()=>n.delete(e,t,Z.id,{expectedVersion:Z.version,idempotencyKey:fe}));if(!D())return;if(_(!1),!X.ok){O(X.error.message),await T.current().catch(()=>{});return}M(null),B.current=null,await T.current().catch(()=>{})},me=async(Z)=>{if(A||d!==r)return;_(!0),O("");let fe=await ei(()=>n.content(e,t,Z.id));if(!D())return;if(_(!1),!fe.ok){O(fe.error.message);return}let X=Uint8Array.from(atob(fe.data.base64),(ae)=>ae.charCodeAt(0)),K=URL.createObjectURL(new Blob([X],{type:"application/octet-stream"})),ee=document.createElement("a");ee.href=K,ee.download=fe.data.attachment.name,ee.click(),setTimeout(()=>URL.revokeObjectURL(K),1000)};return Wt("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Wt("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[wt("h3",{className:"font-medium",children:"Attachments"}),wt("button",{type:"button",disabled:A,onClick:()=>{O(""),T.current().catch(()=>{})},children:"Refresh attachments"})]}),N&&wt("p",{role:"alert",children:N}),!f||d!==r?wt("p",{role:"status",children:"Loading attachments…"}):Wt(Dl,{children:[f.items.length===0&&wt("p",{children:"No attachments yet."}),wt("ol",{className:"flex min-w-0 flex-col gap-2",children:f.items.map((Z)=>Wt("li",{className:"min-w-0 rounded border p-2",children:[wt("p",{className:"break-all",children:Z.name}),Wt("p",{className:"break-all text-xs",children:[Z.size," bytes · version ",Z.version," · ",Z.authorId]}),Z.deletedAt?wt("p",{children:"Attachment deleted"}):Wt("div",{className:"flex flex-wrap gap-3",children:[wt("button",{type:"button",disabled:A,"aria-label":`Download attachment ${Z.name}`,onClick:()=>void me(Z),children:"Download"}),!o&&Z.authorId===f.actorId&&wt("button",{type:"button",disabled:A,"aria-label":`Delete attachment ${Z.name}`,onClick:()=>{M(Z),B.current=null},children:"Delete"})]})]},Z.id))}),Wt("div",{className:"flex flex-wrap gap-3",children:[wt("button",{type:"button",disabled:A||!v.length,onClick:()=>{b(v.at(-1)),y((Z)=>Z.slice(0,-1))},children:"Newer attachments"}),wt("button",{type:"button",disabled:A||f.nextCursor===null,onClick:()=>{y((Z)=>[...Z,x]),b(f.nextCursor??void 0)},children:"Older attachments"})]}),!o&&Wt(Dl,{children:[wt("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."}),Wt("label",{children:["Attachment file",wt("input",{ref:R,"aria-label":"Attachment file",type:"file",disabled:A||L,onChange:async(Z)=>{let fe=Z.target.files?.[0];if(!fe)return;let X=++c.current;if(k(null),O(""),!fe.size||fe.size>1048576){O("Choose a nonempty file up to 1 MiB.");return}w(!0);try{let K=await Hd(fe);if(!D()||X!==c.current)return;let ee=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(fe.type)?fe.type:"application/octet-stream";k({name:fe.name,contentType:ee,base64:K,idempotencyKey:crypto.randomUUID()})}catch{if(D()&&X===c.current)O("The selected file could not be read.")}finally{if(D()&&X===c.current)w(!1)}}},r)]}),p&&Wt("p",{className:"break-all",children:["Selected file: ",p.name]}),wt("button",{type:"button",className:"self-start",disabled:A||L||!p,onClick:()=>void j(),children:"Upload attachment"}),P&&Wt("div",{children:[Wt("p",{className:"break-all",children:["Delete ",P.name,"? This permanently removes its bytes and keeps a deletion marker."]}),Wt("div",{className:"flex flex-wrap gap-3",children:[wt("button",{type:"button",disabled:A,onClick:()=>void H(),children:"Confirm delete attachment"}),wt("button",{type:"button",disabled:A,onClick:()=>{M(null),B.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as ti,useRef as jo,useState as Gt}from"react";import{jsx as ze,jsxs as rt,Fragment as Fl}from"react/jsx-runtime";async function Zi(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function jd(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function Wd({descriptor:e,recordIds:t,client:n,linkForGrant:o,registerRefresh:i}){let r=e.id,s=jo({identity:r,client:n});s.current={identity:r,client:n};let a=jo(!1),l=jo(0),[c,d]=Gt(null),[g,f]=Gt(null),[u,x]=Gt(),b=jo(u);b.current=u;let[v,y]=Gt([]),[C,p]=Gt([]),[k,P]=Gt([]),[M,B]=Gt(3600),[R,A]=Gt(null),[_,L]=Gt(!1),[w,N]=Gt(""),[O,D]=Gt(null),J=jo(null),[T,j]=Gt(!1),[H,me]=Gt(""),Z=()=>a.current&&s.current.identity===r&&s.current.client===n,fe=async()=>{let re=++l.current,Se=await Zi(()=>n.list(r,{limit:20,...b.current===void 0?{}:{before:b.current}}));if(!Z()||re!==l.current)throw Error("Refresh superseded");if(!Se.ok)throw me(Se.error.message),Error("Share refresh failed");f(Se.data),d(r)},X=jo(fe);X.current=fe,ti(()=>(a.current=!0,()=>{a.current=!1,++l.current}),[]),ti(()=>{if(s.current.identity!==r||s.current.client!==n)return;d(null),f(null),p([]),P([]),A(null),L(!1),N(""),D(null),J.current=null,j(!1),me(""),x(void 0),y([]),b.current=void 0,X.current().catch(()=>{})},[r,n]),ti(()=>{if(b.current===u&&c===r)X.current().catch(()=>{})},[u,c,r]),ti(()=>(i?.(()=>X.current()),()=>i?.(null)),[i]);let K=()=>{if(!_)A(null)},ee=async()=>{if(T||!R||c!==r)return;let re=R;j(!0),L(!0),me("");let Se=await Zi(()=>n.create(r,re));if(!Z())return;if(j(!1),!Se.ok){me(Se.error.message);return}N(o(Se.data,re.key)),A(null),L(!1),x(void 0),y([]),b.current=void 0,await X.current().catch(()=>{})},ae=async()=>{if(T||!O||c!==r)return;let re=O;J.current??=crypto.randomUUID();let Se=J.current;j(!0),me("");let pe=await Zi(()=>n.revoke(r,re.id,{expectedVersion:re.version,idempotencyKey:Se}));if(!Z())return;if(j(!1),!pe.ok){me(pe.error.message),await X.current().catch(()=>{});return}D(null),J.current=null,N(""),await X.current().catch(()=>{})},he=e.fields.filter((re)=>!["linkedRecord","lookup","formula","rollup"].includes(re.type)),Ce=T||_;return rt("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[rt("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[ze("h3",{className:"font-medium",children:"Read-only sharing"}),ze("button",{type:"button",disabled:T,onClick:()=>{me(""),X.current().catch(()=>{})},children:"Refresh share grants"})]}),ze("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."}),ze("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."}),H&&ze("p",{role:"alert",children:H}),rt("fieldset",{disabled:Ce,className:"flex min-w-0 flex-col gap-2",children:[ze("legend",{children:"Fields to share"}),he.map((re)=>rt("label",{className:"break-all",children:[ze("input",{type:"checkbox","aria-label":`Share field ${re.name}`,checked:C.includes(re.id),onChange:(Se)=>{K(),p((pe)=>Se.target.checked?[...pe,re.id]:pe.filter((qe)=>qe!==re.id))}})," ",re.name]},re.id))]}),rt("fieldset",{disabled:Ce,className:"flex min-w-0 flex-col gap-2",children:[ze("legend",{children:"Records on the current page"}),t.slice(0,100).map((re)=>rt("label",{className:"break-all",children:[ze("input",{type:"checkbox","aria-label":`Share record ${re}`,checked:k.includes(re),onChange:(Se)=>{K(),P((pe)=>Se.target.checked?[...pe,re]:pe.filter((qe)=>qe!==re))}})," ",re]},re)),t.length===0&&ze("p",{children:"Load records in Grid to choose a share scope."})]}),rt("p",{className:"break-all text-xs",children:["Selected record IDs: ",k.join(", ")||"none"]}),rt("label",{children:["Link lifetime"," ",rt("select",{"aria-label":"Share link lifetime",disabled:Ce,value:M,onChange:(re)=>{K(),B(Number(re.target.value))},children:[ze("option",{value:60,children:"1 minute"}),ze("option",{value:3600,children:"1 hour"}),ze("option",{value:86400,children:"24 hours"})]})]}),ze("button",{type:"button",className:"self-start",disabled:Ce||c!==r||!C.length||!k.length||k.length>100||C.some((re)=>!he.some((Se)=>Se.id===re)),onClick:()=>{me("");try{A({expectedSchemaVersion:e.schemaVersion,fieldIds:[...C],recordIds:[...k],expiresInSeconds:M,key:jd(),idempotencyKey:crypto.randomUUID()})}catch{me("A secure share key could not be generated.")}},children:"Review read-only share"}),R&&rt("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[rt("p",{className:"break-all",children:["Confirm schema ",R.expectedSchemaVersion,", fields ",R.fieldIds.join(", "),", records ",R.recordIds.join(", ")," for ",R.expiresInSeconds," seconds."]}),R.expectedSchemaVersion!==e.schemaVersion&&ze("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),rt("div",{className:"flex flex-wrap gap-3",children:[ze("button",{type:"button",disabled:T,onClick:()=>void ee(),children:_?"Retry create read link":"Create read link"}),ze("button",{type:"button",disabled:T,onClick:()=>{A(null),L(!1),me("")},children:"Discard share confirmation"})]}),_&&ze("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."})]}),w&&rt("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",ze("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:w,onFocus:(re)=>re.target.select()})]}),!g||c!==r?ze("p",{role:"status",children:"Loading share grants…"}):rt(Fl,{children:[g.items.length===0&&ze("p",{children:"No share grants yet."}),ze("ol",{className:"flex min-w-0 flex-col gap-2",children:g.items.map((re)=>rt("li",{className:"min-w-0 rounded border p-2",children:[rt("p",{className:"break-all",children:["Grant ",re.id," · version ",re.version," · schema ",re.schemaVersion]}),rt("p",{className:"break-all text-xs",children:["Fields: ",re.fieldIds.join(", ")," · Records: ",re.recordIds.join(", ")," · Expires:"," ",re.expiresAt]}),re.revokedAt?ze("p",{children:"Share revoked"}):rt(Fl,{children:[ze("p",{children:re.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(re.expiresAt)<=Date.now()?"Share expired":"Share active"}),ze("button",{type:"button",disabled:T,"aria-label":`Revoke share ${re.id}`,onClick:()=>{D(re),J.current=null},children:"Revoke"})]})]},re.id))}),rt("div",{className:"flex flex-wrap gap-3",children:[ze("button",{type:"button",disabled:T||!v.length,onClick:()=>{x(v.at(-1)),y((re)=>re.slice(0,-1))},children:"Newer share grants"}),ze("button",{type:"button",disabled:T||g.nextCursor===null,onClick:()=>{y((re)=>[...re,u]),x(g.nextCursor??void 0)},children:"Older share grants"})]})]}),O&&rt("div",{children:[rt("p",{className:"break-all",children:["Revoke grant ",O.id," at version ",O.version,"? Every existing share session will lose access."]}),rt("div",{className:"flex flex-wrap gap-3",children:[ze("button",{type:"button",disabled:T,onClick:()=>void ae(),children:"Confirm revoke share"}),ze("button",{type:"button",disabled:T,onClick:()=>{D(null),J.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as Tl,useRef as Wo,useState as Mt}from"react";import{jsx as Te,jsxs as at}from"react/jsx-runtime";var El=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],Gd=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function Yd({descriptor:e,recordIds:t,client:n,webhookRequest:o}){let i=e.id,r=Wo({id:i,client:n});r.current={id:i,client:n};let s=Wo(!0),a=Wo(0),[l,c]=Mt([]),[d,g]=Mt(""),f=Wo(d);f.current=d;let[u,x]=Mt(null),[b,v]=Mt(),y=Wo(b);y.current=b;let[C,p]=Mt(""),[k,P]=Mt("record"),[M,B]=Mt(60),[R,A]=Mt([]),[_,L]=Mt([]),[w,N]=Mt({}),[O,D]=Mt(null),[J,T]=Mt(!1),[j,H]=Mt(!1),[me,Z]=Mt(""),[fe,X]=Mt(""),K=()=>s.current&&r.current.id===i&&r.current.client===n,ee=async(S)=>{try{return await S()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},ae=async()=>{let S=++a.current,F=await ee(()=>n.list(i));if(!K()||S!==a.current)return;if(!F.ok){Z(F.error.message);return}c(F.data);let Y=F.data.find((de)=>de.id===f.current)?.id??F.data[0]?.id??"";if(f.current=Y,g(Y),!Y){x(null);return}let V=await ee(()=>n.runs(i,Y,{limit:20,...y.current?{before:y.current}:{}}));if(!K()||S!==a.current||f.current!==Y)return;if(V.ok)x(V.data);else Z(V.error.message)},he=Wo(ae);he.current=ae,Tl(()=>{if(r.current.id!==i||r.current.client!==n)return;s.current=!0,he.current();let S=setInterval(()=>void he.current(),5000);return()=>{s.current=!1,++a.current,clearInterval(S)}},[i,n]),Tl(()=>{if(f.current!==d||y.current!==b)return;he.current()},[d,b]);let Ce=()=>{if(Z(""),!C.trim()||!R.length||k!=="record"&&!_.length){Z("Choose a name, writable fields, and target records for time or webhook triggers.");return}let S=Object.fromEntries(R.map((Y)=>[Y,w[Y]??null])),F={expectedSchemaVersion:e.schemaVersion,name:C.trim(),trigger:k==="time"?{kind:k,intervalSeconds:M}:{kind:k},targetRecordIds:_,values:S,idempotencyKey:crypto.randomUUID(),...k==="webhook"?{webhookKey:Gd()}:{}};D({kind:"create",input:F}),T(!1)},re=(S)=>{D(S),T(!1),Z("")},Se=async()=>{if(!O||j)return;let S=O,F=J;T(!0),H(!0),Z("");let Y=await ee(()=>S.kind==="create"?n.create(i,S.input):S.kind==="toggle"?n.toggle(i,S.a.id,S.input):S.kind==="run"?n.runNow(i,S.a.id,S.input):n.retry(i,S.a.id,S.run.id,S.input));if(!K())return;if(H(!1),!Y.ok){if(!F&&Y.error.status>=400&&Y.error.status<500)T(!1);Z(`${Y.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(S.kind==="create"){let V=Y.data;if(f.current=V.id,g(V.id),S.input.webhookKey&&o)X(JSON.stringify(o(V,S.input.webhookKey),null,2));p(""),A([]),L([]),N({})}D(null),T(!1),y.current=void 0,v(void 0),await he.current()},pe=l.find((S)=>S.id===d),qe=!!O||j;return at("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[Te("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."}),Te("button",{type:"button",onClick:()=>void he.current(),children:"Refresh automation"}),me&&Te("p",{role:"alert",children:me}),Te("form",{onSubmit:(S)=>{S.preventDefault(),Ce()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:at("fieldset",{disabled:qe,style:{minWidth:0},children:[Te("legend",{children:"New automation"}),at("label",{children:["Name"," ",Te("input",{"aria-label":"Automation name",value:C,maxLength:200,onChange:(S)=>p(S.target.value)})]}),at("label",{children:["Trigger"," ",at("select",{"aria-label":"Automation trigger",value:k,onChange:(S)=>P(S.target.value),children:[Te("option",{value:"record",children:"Record changes"}),Te("option",{value:"time",children:"Timed interval"}),Te("option",{value:"webhook",children:"Private webhook"})]})]}),k==="time"&&at("label",{children:["Interval in seconds"," ",Te("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:M,onChange:(S)=>B(Number(S.target.value))})]}),at("fieldset",{children:[Te("legend",{children:"Fields to update"}),e.fields.filter((S)=>El.includes(S.type)).map((S)=>at("label",{style:{display:"block"},children:[Te("input",{type:"checkbox",checked:R.includes(S.id),onChange:(F)=>{A(F.target.checked?[...R,S.id]:R.filter((Y)=>Y!==S.id))}}),S.name]},S.id))]}),Te(Io,{fields:e.fields.filter((S)=>R.includes(S.id)&&El.includes(S.type)),values:w,onChange:N}),at("fieldset",{children:[Te("legend",{children:"Target records from this page"}),k==="record"&&Te("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&Te("p",{children:"Open a grid page to choose fixed records."}),t.map((S)=>at("label",{style:{display:"block",overflowWrap:"anywhere"},children:[Te("input",{type:"checkbox","aria-label":`Automation target ${S}`,checked:_.includes(S),onChange:(F)=>L(F.target.checked?[..._,S]:_.filter((Y)=>Y!==S))}),S]},S))]}),Te("button",{type:"submit",children:"Review automation"})]})}),O&&at("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[Te("p",{children:O.kind==="create"?`Create ${O.input.name} using schema ${O.input.expectedSchemaVersion}; ${O.input.targetRecordIds.length||"event"} targets.`:O.kind==="toggle"?`${O.input.enabled?"Enable":"Disable"} ${O.a.name}. Disabling fences queued and running work.`:O.kind==="run"?`Run ${O.a.name} for ${O.input.recordIds.length} explicitly selected records.`:`Retry ${O.a.name}, run ${O.run.sequence}, using its original record versions.`}),O.kind==="create"&&Te("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(O.input.values,null,2)}),Te("button",{type:"button",disabled:j,onClick:()=>void Se(),children:j?"Confirming…":J?"Retry automation confirmation":"Confirm automation"}),Te("button",{type:"button",disabled:J||j,onClick:()=>D(null),children:"Cancel automation review"}),J&&Te("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),fe&&at("div",{children:[Te("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),Te("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:fe}),Te("button",{type:"button",onClick:()=>X(""),children:"Hide webhook key"})]}),l.length>0&&at("label",{children:["Automation"," ",Te("select",{"aria-label":"Selected automation",disabled:qe,value:d,onChange:(S)=>{f.current=S.target.value,y.current=void 0,v(void 0),g(S.target.value),x(null)},children:l.map((S)=>Te("option",{value:S.id,children:S.name},S.id))})]}),pe&&at("div",{children:[at("p",{children:[pe.enabled?"Enabled":"Disabled"," · ",pe.trigger.kind," · schema ",pe.schemaVersion," · configuration ",pe.version]}),Te("button",{type:"button",disabled:qe,onClick:()=>re({kind:"toggle",a:pe,input:{expectedVersion:pe.version,enabled:!pe.enabled,idempotencyKey:crypto.randomUUID()}}),children:pe.enabled?"Review disable automation":"Review enable automation"}),Te("button",{type:"button",disabled:qe||!pe.enabled||!(pe.targetRecordIds.length||t.length),onClick:()=>re({kind:"run",a:pe,input:{recordIds:pe.targetRecordIds.length?pe.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),u&&at("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!u.items.length&&Te("p",{children:"No runs yet."}),u.items.map((S)=>at("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[at("p",{children:["Run ",S.sequence," · ",S.triggerKind," · ",S.status," · step ",S.step]}),at("p",{children:["Attempts: evaluate ",S.stepAttempts.evaluate,", apply ",S.stepAttempts.apply," · original versions: ",S.expectedRows.map((F)=>`${F.id}: ${F.version}`).join(", ")]}),S.errorCode&&Te("p",{role:"status",children:S.errorCode}),S.leaseUntil&&at("p",{children:["Lease expires ",S.leaseUntil]}),pe&&S.status==="failed"&&at("button",{type:"button",disabled:qe||!pe.enabled,onClick:()=>re({kind:"retry",a:pe,run:S,input:{expectedVersion:S.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",S.sequence]})]},S.id)),Te("button",{type:"button",disabled:qe||b===void 0,onClick:()=>{y.current=void 0,v(void 0)},children:"Newest runs"}),Te("button",{type:"button",disabled:qe||u.nextCursor===null,onClick:()=>{y.current=u.nextCursor??void 0,v(y.current)},children:"Older runs"})]})]})}import{useEffect as Jd,useId as Qd,useRef as Ml,useState as It}from"react";import{jsx as _e,jsxs as lt}from"react/jsx-runtime";var Nl=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function Zd(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((s)=>s.id===r&&Nl.includes(s.type))))throw Error("Choose up to ten basic source and target fields.");let o=n.recordIds.map((i)=>{let r=t.find((s)=>s.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 Xd({descriptor:e,records:t,client:n,onApplied:o}){let i=Qd(),r=e.id,s=Ml({id:r,client:n}),a=Ml(!0);s.current={id:r,client:n};let[l,c]=It([]),[d,g]=It(!1),[f,u]=It(""),[x,b]=It(""),[v,y]=It(""),[C,p]=It([]),[k,P]=It([]),[M,B]=It([]),[R,A]=It(null),[_,L]=It(null),[w,N]=It(null),[O,D]=It(!1),[J,T]=It(!1),[j,H]=It(""),[me,Z]=It(""),[fe,X]=It(""),K=()=>a.current&&s.current.id===r&&s.current.client===n,ee=async(F)=>{try{return await F()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};Jd(()=>{a.current=!0,A(null),L(null),N(null),D(!1),H(""),Z(""),X(""),p([]),P([]),B([]),y("");let F=!0;return g(!1),T(!1),c([]),u(""),b(""),n.providers(r).then((Y)=>{if(!F||s.current.id!==r||s.current.client!==n)return;if(g(!0),Y.ok)c(Y.data),u(Y.data[0]?.resourceId??""),b(Y.data[0]?.allowedModels[0]??"");else H(Y.error.message)}).catch(()=>{if(F)g(!0),H("AI configuration is unavailable.")}),()=>{F=!1,a.current=!1}},[r,n]);let ae=()=>{try{let F=Zd(e,t,{resourceId:f,model:x,instruction:v,recordIds:C,sourceFieldIds:k,targetFieldIds:M});L(structuredClone(F.records.map((Y)=>({id:Y.id,version:Y.expectedVersion,values:Object.fromEntries(F.sourceFieldIds.map((V)=>[V,t.find((de)=>de.id===Y.id)?.values[V]??null]))})))),A(F),D(!1),H(""),Z("")}catch(F){H(F instanceof Error?F.message:"Invalid selection.")}},he=async()=>{if(!R||J)return;let F=R,Y=O;T(!0),D(!0),H("");let V=await ee(()=>n.propose(r,F));if(!K())return;if(T(!1),!V.ok){if(!Y&&V.error.status>=400&&V.error.status<500)D(!1);H(`${V.error.message} Retry keeps the original selection and versions.`);return}N(V.data),X(V.data.id),D(!1)},Ce=async()=>{if(!w||J)return;let F=w,Y=O;T(!0),D(!0),H("");let V=await ee(()=>n.confirm(r,F));if(!K())return;if(T(!1),!V.ok){if(!Y&&V.error.status>=400&&V.error.status<500)D(!1);H(`${V.error.message} The reviewed proposal keeps its original versions.`);return}Z(`${V.data.items.length} records filled${V.data.replayed?"; original receipt recovered":""}.`),N(null),A(null),L(null),D(!1);try{await o?.()}catch{if(K())H("The fill committed. Refresh the Collection to see its records.")}},re=async()=>{if(J||R||w)return;T(!0),H("");let F=await ee(()=>n.get(r,fe));if(!K())return;if(T(!1),F.ok)N(F.data),D(!1),Z("");else H(F.error.message)},Se=(F,Y,V)=>V(F.includes(Y)?F.filter((de)=>de!==Y):[...F,Y]),pe=J||!!R||!!w,qe=e.fields.filter((F)=>Nl.includes(F.type)),S=l.find((F)=>F.resourceId===f);return lt("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[_e("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&&_e("p",{role:"alert",children:j}),me&&_e("p",{role:"status",children:me}),d&&l.length===0&&_e("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),_e("form",{onSubmit:(F)=>{F.preventDefault(),ae()},children:lt("fieldset",{disabled:pe,style:{minWidth:0},children:[_e("legend",{children:"AI fill request"}),lt("label",{children:["AI resource"," ",lt("select",{"aria-label":"AI resource",value:f,onChange:(F)=>{u(F.target.value),b(l.find((Y)=>Y.resourceId===F.target.value)?.allowedModels[0]??"")},children:[_e("option",{value:"",children:"Choose resource"}),l.map((F)=>_e("option",{value:F.resourceId,children:F.name},F.resourceId))]})]}),lt("label",{htmlFor:i,children:["Model"," ",S?.allowedModels.length?_e("select",{id:i,"aria-label":"AI model",value:x,onChange:(F)=>b(F.target.value),children:S.allowedModels.map((F)=>_e("option",{value:F,children:F},F))}):_e("input",{id:i,"aria-label":"AI model",maxLength:200,value:x,onChange:(F)=>b(F.target.value)})]}),lt("label",{children:["Instructions"," ",_e("textarea",{"aria-label":"AI instructions",maxLength:2000,value:v,onChange:(F)=>y(F.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),lt("fieldset",{children:[_e("legend",{children:"Source fields to send"}),qe.map((F)=>lt("label",{style:{display:"block"},children:[_e("input",{type:"checkbox","aria-label":`Send ${F.name}`,checked:k.includes(F.id),onChange:()=>Se(k,F.id,P)}),F.name]},F.id))]}),lt("fieldset",{children:[_e("legend",{children:"Fields to fill"}),qe.map((F)=>lt("label",{style:{display:"block"},children:[_e("input",{type:"checkbox","aria-label":`Fill ${F.name}`,checked:M.includes(F.id),onChange:()=>Se(M,F.id,B)}),F.name]},F.id))]}),lt("fieldset",{children:[_e("legend",{children:"Target records from this page"}),t.map((F)=>lt("label",{style:{display:"block",overflowWrap:"anywhere"},children:[_e("input",{type:"checkbox","aria-label":`AI record ${F.id}`,checked:C.includes(F.id),onChange:()=>Se(C,F.id,p)}),F.id," · version ",F.version]},F.id))]}),_e("button",{type:"submit",disabled:!f,children:"Review AI request"})]})}),R&&!w&<("section",{"aria-label":"AI data disclosure",children:[lt("p",{children:["Selected service: ",R.resourceId," · model ",R.model," · schema"," ",R.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),_e("p",{children:R.instruction}),_e("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(_,null,2)}),_e("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),_e("button",{type:"button",disabled:J,onClick:()=>void he(),children:O?"Retry original AI request":"Generate proposal"}),_e("button",{type:"button",disabled:J||O,onClick:()=>{A(null),L(null),H("")},children:"Cancel AI request"})]}),w&<("section",{"aria-label":"AI fill confirmation",children:[lt("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",w.id," · ",w.provider," · schema ",w.schemaVersion]}),w.schemaVersion!==e.schemaVersion&&_e("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),w.rows.map((F)=>lt("div",{style:{overflowWrap:"anywhere"},children:[lt("p",{children:[F.id," · original version ",F.expectedVersion]}),Object.keys(F.values).map((Y)=>lt("div",{children:[_e("strong",{children:e.fields.find((V)=>V.id===Y)?.name??Y}),lt("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(F.before[Y]),`
|
|
10
|
+
`,"Suggested: ",JSON.stringify(F.values[Y])]})]},Y))]},F.id)),_e("button",{type:"button",disabled:J,onClick:()=>void Ce(),children:O?"Retry original AI fill":"Confirm fill"}),_e("button",{type:"button",disabled:J||O,onClick:()=>{N(null),A(null),L(null),H("")},children:"Dismiss proposal"})]}),lt("label",{children:["Recover a saved proposal"," ",_e("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:fe,onChange:(F)=>X(F.target.value),disabled:pe,style:{width:"100%",boxSizing:"border-box"}})]}),_e("button",{type:"button",disabled:pe||!/^[a-f0-9]{64}$/.test(fe),onClick:()=>void re(),children:"Load saved proposal"})]})}import{jsx as ge,jsxs as Ee}from"react/jsx-runtime";var tc=[{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 ef({fields:e,onChange:t,lockedIds:n=[],collections:o=[]}){let i=(r,s)=>t(e.map((a,l)=>l===r?{...a,...s}:a));return Ee("div",{className:"flex flex-col gap-3",children:[e.map((r,s)=>{let a=n.includes(r.id);return Ee("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:[ge("input",{"aria-label":`Field ${s+1} name`,placeholder:"Display name",value:r.name,onChange:(l)=>i(s,{name:l.target.value})}),ge("input",{"aria-label":`Field ${s+1} ID`,placeholder:"field_id",value:r.id,disabled:a,onChange:(l)=>i(s,{id:l.target.value})}),ge("select",{"aria-label":`Field ${s+1} type`,className:"rounded-md border bg-background px-2 text-sm",value:r.type,disabled:a,onChange:(l)=>{let c=l.target.value,d={id:r.id,name:r.name,type:c,required:tt({type:c})?!1:r.required??!1};if(c==="formula")d.formula={expression:""};if(c==="rollup")d.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(c==="singleSelect"||c==="multipleSelect")d.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((g,f)=>f===s?d:g))},children:tc.map((l)=>ge("option",{value:l.value,children:l.name},l.value))}),Ee("div",{className:"flex items-center gap-2",children:[Ee("label",{className:"flex items-center gap-1 text-xs",children:[ge("input",{type:"checkbox",checked:r.required??!1,disabled:a||n.length>0||tt(r),onChange:(l)=>i(s,{required:l.target.checked})}),"Required"]}),!a&&ge("button",{type:"button",onClick:()=>t(e.filter((l,c)=>c!==s)),children:"Remove"})]}),(r.type==="singleSelect"||r.type==="multipleSelect")&&ge("input",{className:"md:col-span-4","aria-label":`Field ${s+1} options`,placeholder:"Open, Done",value:r.options?.map((l)=>l.name).join(", ")??"",disabled:a,onChange:(l)=>i(s,{options:l.target.value.split(",").map((c,d)=>({id:c.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${d}`,name:c.trim()})).filter((c)=>c.name)})}),r.type==="linkedRecord"&&Ee("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Ee("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",Ee("select",{className:"min-w-0 max-w-full","aria-label":`Field ${s+1} linked collection`,value:r.link?.collectionId??"",disabled:a,onChange:(l)=>{let c=o.find((d)=>d.id===l.target.value);i(s,{link:{collectionId:l.target.value,displayFieldId:c?.fields.find((d)=>d.type==="singleLineText"||d.type==="longText")?.id??""}})},children:[ge("option",{value:"",children:"Choose collection…"}),o.map((l)=>ge("option",{value:l.id,children:l.name},l.id))]})]}),Ee("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",Ee("select",{className:"min-w-0 max-w-full","aria-label":`Field ${s+1} record label`,value:r.link?.displayFieldId??"",disabled:a||!r.link?.collectionId,onChange:(l)=>i(s,{link:{collectionId:r.link?.collectionId??"",displayFieldId:l.target.value}}),children:[ge("option",{value:"",children:"Choose text field…"}),o.find((l)=>l.id===r.link?.collectionId)?.fields.filter((l)=>l.type==="singleLineText"||l.type==="longText").map((l)=>ge("option",{value:l.id,children:l.name},l.id))]})]})]}),r.type==="lookup"&&Ee("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Ee("label",{children:["Through linked field"," ",Ee("select",{"aria-label":`Field ${s+1} lookup link`,value:r.lookup?.linkFieldId??"",disabled:a,onChange:(l)=>i(s,{lookup:{linkFieldId:l.target.value,targetFieldId:""}}),children:[ge("option",{value:"",children:"Choose linked field…"}),e.filter((l)=>l.type==="linkedRecord"&&l.link).map((l)=>ge("option",{value:l.id,children:l.name},l.id))]})]}),Ee("label",{children:["Read target field"," ",Ee("select",{"aria-label":`Field ${s+1} lookup target`,value:r.lookup?.targetFieldId??"",disabled:a||!r.lookup?.linkFieldId,onChange:(l)=>i(s,{lookup:{linkFieldId:r.lookup?.linkFieldId??"",targetFieldId:l.target.value}}),children:[ge("option",{value:"",children:"Choose target field…"}),o.find((l)=>l.id===e.find((c)=>c.id===r.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((l)=>!tt(l)&&l.type!=="linkedRecord").map((l)=>ge("option",{value:l.id,children:l.name},l.id))]})]}),ge("small",{children:"Computed from linked records. Values cannot be edited."})]}),r.type==="formula"&&Ee("div",{className:"flex flex-col gap-1 md:col-span-4",children:[Ee("label",{children:["Formula",ge("textarea",{"aria-label":`Field ${s+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:(l)=>i(s,{formula:{expression:l.target.value}})})]}),ge("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."}),Ee("small",{children:["References:"," ",e.filter((l)=>l.id!==r.id&&(l.type==="singleLineText"||l.type==="longText"||l.type==="date"||l.type==="number"||l.type==="formula"||l.type==="rollup")).map((l)=>`{${l.id}}`).join(", ")||"None yet"]})]}),r.type==="rollup"&&Ee("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Ee("label",{children:["Through linked field"," ",Ee("select",{"aria-label":`Field ${s+1} rollup link`,value:r.rollup?.linkFieldId??"",onChange:(l)=>i(s,{rollup:{linkFieldId:l.target.value,targetFieldId:"",function:r.rollup?.function??"sum"}}),children:[ge("option",{value:"",children:"Choose linked field…"}),e.filter((l)=>l.type==="linkedRecord"&&l.link).map((l)=>ge("option",{value:l.id,children:l.name},l.id))]})]}),Ee("label",{children:["Aggregate"," ",Ee("select",{"aria-label":`Field ${s+1} rollup function`,value:r.rollup?.function??"sum",onChange:(l)=>{let c=l.target.value,d=o.find((g)=>g.id===e.find((f)=>f.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((g)=>g.id===r.rollup?.targetFieldId);i(s,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:c==="count"||d?.type==="number"?r.rollup?.targetFieldId??"":"",function:c}})},children:[ge("option",{value:"sum",children:"Sum"}),ge("option",{value:"average",children:"Average"}),ge("option",{value:"min",children:"Minimum"}),ge("option",{value:"max",children:"Maximum"}),ge("option",{value:"count",children:"Count values"})]})]}),Ee("label",{children:["Target field"," ",Ee("select",{"aria-label":`Field ${s+1} rollup target`,value:r.rollup?.targetFieldId??"",disabled:!r.rollup?.linkFieldId,onChange:(l)=>i(s,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:l.target.value,function:r.rollup?.function??"sum"}}),children:[ge("option",{value:"",children:"Choose target field…"}),o.find((l)=>l.id===e.find((c)=>c.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((l)=>!tt(l)&&l.type!=="linkedRecord"&&(r.rollup?.function==="count"||l.type==="number")).map((l)=>ge("option",{value:l.id,children:l.name},l.id))]})]}),ge("small",{className:"w-full",children:"Null targets are skipped. Count counts values; empty sum/count are zero. Other empty aggregates have no result."})]})]},s)}),ge("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 nc(e,t,n){if(tt(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 Ho(e,Xe(t),n)}function hr(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 s=t[r.id];if(r.type==="linkedRecord"){if(!Array.isArray(s)||s.some((a)=>typeof a!=="string")||s.length>100||new Set(s).size!==s.length)throw Error(n("{name} needs unique linked records.",{name:r.name}));if(r.required&&!s.length)throw Error(n("{name} is required.",{name:r.name}));i[r.id]=s;continue}if(r.type==="relation"){if(s==null||s===""){if(r.required)throw Error(n("{name} is required.",{name:r.name}));i[r.id]=null;continue}if(typeof s!=="string")throw Error(n("{name} needs a server-provided option.",{name:r.name}));i[r.id]=s;continue}if(r.required&&typeof s==="string"&&!s.trim())throw Error(n("{name} is required.",{name:r.name}));i[r.id]=pn(Array.isArray(s)?s.join(","):String(s??""),r,o)}return i}function Io({fields:e,values:t,onChange:n,relationClient:o,linkedRecords:i,computedErrors:r,locale:s,ui:a,submitted:l=!1}){let c=le(s),d=ec();return ge("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((g)=>{let f=g.description?.trim()??"",u=f?`${d}-${g.id}-hint`:void 0,x=nc(g,t[g.id],s??"en"),v=Boolean(g.required&&Xe(t[g.id])===""&&x)&&!l?"":x,y=v?`${d}-${g.id}-error`:void 0,C=[u,y].filter(Boolean).join(" "),p={...C?{"aria-describedby":C}:{},...v?{"aria-invalid":!0}:{}};return Ee("div",{className:"flex flex-col gap-1 text-sm",children:[Ee("label",{htmlFor:`${d}-${g.id}`,children:[g.name,g.required?" *":""]}),f?ge("p",{id:u,className:"m-0 text-xs opacity-70",children:f}):null,tt(g)?ge("output",{id:`${d}-${g.id}`,"aria-label":c("{name} (read only)",{name:g.name}),...p,children:g.type==="lookup"?to(t[g.id]):$o(t[g.id],r?.[g.id],s)}):g.type==="linkedRecord"?ge(Wr,{...s?{locale:s}:{},field:g,value:t[g.id],labels:i?.[g.id],client:o,onChange:(k)=>n({...t,[g.id]:k}),...p}):g.type==="checkbox"?ge("input",{id:`${d}-${g.id}`,"aria-label":`${g.name}${g.required?" *":""}`,type:"checkbox",checked:t[g.id]===!0,onChange:(k)=>n({...t,[g.id]:k.target.checked}),...p}):g.type==="singleSelect"&&a?.Select?ge(Ge,{ui:a,label:`${g.name}${g.required?" *":""}`,...p,value:String(t[g.id]??""),options:[{value:"",label:c("Choose…")},...(g.options??[]).map((k)=>({value:k.id,label:k.name}))],onChange:(k)=>n({...t,[g.id]:k||null})}):g.type==="multipleSelect"&&a?.MultiSelect?ge(a.MultiSelect,{"aria-label":`${g.name}${g.required?" *":""}`,...p,options:(g.options??[]).map((k)=>({value:k.id,label:k.name,slot:pr(g.options,k.id)})),values:Array.isArray(t[g.id])?t[g.id]:[],placeholder:c("Choose…"),onChange:(k)=>n({...t,[g.id]:k})}):g.type==="singleSelect"||g.type==="multipleSelect"?Ee("select",{id:`${d}-${g.id}`,"aria-label":`${g.name}${g.required?" *":""}`,...p,className:"min-h-9 rounded-md border bg-background p-2",multiple:g.type==="multipleSelect",value:g.type==="multipleSelect"?Array.isArray(t[g.id])?t[g.id]:[]:String(t[g.id]??""),onChange:(k)=>n({...t,[g.id]:g.type==="multipleSelect"?Array.from(k.target.selectedOptions,(P)=>P.value):k.target.value||null}),children:[g.type==="singleSelect"&&ge("option",{value:"",children:c("Choose…")}),g.options?.map((k)=>ge("option",{value:k.id,children:k.name},k.id))]}):g.type==="date"&&a?.DatePicker?(()=>{let k={kind:qi(g),timeZone:xt(g)?.timeZone},P=String(t[g.id]??"");return ge(a.DatePicker,{id:`${d}-${g.id}`,"aria-label":`${g.name}${g.required?" *":""}`,...p,value:Hi(P,k),withTime:k.kind==="auto"?no(P):k.kind==="datetime",fixedKind:k.kind!=="auto",clearable:!g.required,onChange:(M)=>n({...t,[g.id]:M?Ki(M,P,k):null})})})():g.type==="longText"?ge("textarea",{id:`${d}-${g.id}`,"aria-label":`${g.name}${g.required?" *":""}`,...p,className:"rounded-md border bg-background p-2",value:String(t[g.id]??""),onChange:(k)=>n({...t,[g.id]:k.target.value||null})}):ge("input",{id:`${d}-${g.id}`,"aria-label":`${g.name}${g.required?" *":""}`,...p,className:"min-h-9 min-w-0 rounded-md border bg-background p-2",type:g.type==="number"?"number":g.type==="date"?"date":"text",step:g.type==="number"?"any":void 0,value:g.type==="date"?String(t[g.id]??"").slice(0,10):String(t[g.id]??""),onChange:(k)=>n({...t,[g.id]:k.target.value===""?null:g.type==="number"?Number(k.target.value):g.type==="date"&&t[g.id]?Yr(t[g.id],k.target.value):k.target.value})}),v?ge("span",{id:y,className:"text-xs text-red-600",children:v}):null]},g.id)})})}function oc(e,t,n){if(t==="isEmpty")return;let o=tt(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(tt(e)&&!tn(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 tf({fields:e,view:t,onChange:n,onError:o}){let i=e.filter(tn),[r,s]=Xi(i[0]?.id??""),a=i.some((y)=>y.id===r)?r:i[0]?.id??"",[l,c]=Xi("contains"),d=a?(()=>{let y=e.find((C)=>C.id===a);return y&&tt(y)?y.resultType:y?.type})():void 0,g=d==="number"?["is","isNot","isEmpty"]:d==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],f=g.includes(l)?l:d==="number"||d==="date"?"is":"contains",[u,x]=Xi(""),v=[...t.columnOrder.flatMap((y)=>{let C=e.find((p)=>p.id===y);return C?[C]:[]}),...e.filter((y)=>!t.columnOrder.includes(y.id))];return Ee("div",{className:"flex flex-wrap items-end gap-3",children:[Ee("label",{className:"flex min-w-52 flex-col gap-1 text-sm",children:["Search",ge("input",{type:"search",className:"min-h-9 min-w-0 rounded-md border bg-background p-2",value:t.search??"",onChange:(y)=>n({...t,search:y.target.value})})]}),Ee("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(y)=>{y.preventDefault();let C=e.find((k)=>k.id===a);if(!C)return;let p;try{p=oc(C,f,u)}catch(k){o(k instanceof Error?k.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:a,operator:f,...f==="isEmpty"?{}:{value:p}}]}})},children:[Ee("label",{className:"flex flex-col gap-1 text-sm",children:["Filter field",ge("select",{className:"h-9 rounded-md border bg-background px-2",value:a,onChange:(y)=>s(y.target.value),children:i.map((y)=>ge("option",{value:y.id,children:y.name},y.id))})]}),ge("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:f,onChange:(y)=>c(y.target.value),children:g.map((y)=>ge("option",{value:y,children:y==="isNot"?"is not":y==="isEmpty"?"is empty":y==="onOrAfter"?"on or after":y},y))}),f!=="isEmpty"&&ge("input",{type:d==="number"?"number":d==="date"?"date":"text",step:d==="number"?"any":void 0,className:"min-h-9 max-w-40 rounded-md border bg-background p-2","aria-label":"Filter value",value:u,onChange:(y)=>x(y.target.value)}),ge("button",{type:"submit",disabled:!a,children:"Apply filter"}),ge("button",{type:"button",onClick:()=>{let y={...t};delete y.filter,n(y)},children:"Clear filter"})]}),Ee("details",{className:"relative",children:[ge("summary",{className:"cursor-pointer rounded-md border px-3 py-2 text-sm",children:"Columns"}),ge("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:v.map((y,C)=>Ee("div",{className:"flex items-center gap-2 text-sm",children:[Ee("label",{className:"flex flex-1 items-center gap-2",children:[ge("input",{type:"checkbox",checked:!t.hiddenColumns.includes(y.id),disabled:t.type==="form"&&y.required===!0,onChange:(p)=>n({...t,hiddenColumns:p.target.checked?t.hiddenColumns.filter((k)=>k!==y.id):[...t.hiddenColumns,y.id]})}),y.name]}),ge("button",{type:"button","aria-label":`Move ${y.name} left`,disabled:C===0,onClick:()=>{let p=v.map((P)=>P.id),k=p[C-1];if(k!==void 0)[p[C-1],p[C]]=[y.id,k];n({...t,columnOrder:p})},children:"←"}),ge("button",{type:"button","aria-label":`Move ${y.name} right`,disabled:C===v.length-1,onClick:()=>{let p=v.map((P)=>P.id),k=p[C+1];if(k!==void 0)[p[C],p[C+1]]=[k,y.id];n({...t,columnOrder:p})},children:"→"})]},y.id))})]})]})}import{useEffect as rc,useMemo as Ol,useState as Ll}from"react";import{jsx as ea}from"react/jsx-runtime";function ic(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 ac(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 Vl(e,t,n,o={},i={}){return n.map((r)=>{let s=t.groupBy.map((l)=>{let c=e.fields.find((d)=>d.id===l);return`${c?.name??l} ${ac(c,r.groups[l],i)}`}),a=t.aggregates.map((l)=>{let c=r.values[l.as];return`${o[l.as]??l.as}: ${typeof c==="number"||typeof c==="string"?String(c):i.none??"none"}`});return[...s,...a].join(" · ")})}function lc({descriptor:e,query:t,rows:n}){return ea("ul",{"data-uibot":"collection-aggregate",children:Vl(e,t,n).map((o)=>ea("li",{children:o},o))})}function Ao({collectionId:e,descriptor:t,view:n,groupBy:o,aggregates:i,client:r,locale:s,labels:a,reloadKey:l=0}){let c=Ol(()=>Ur(n,{aggregates:i,...o?{groupBy:o}:{}}),[n,o,i]),d=Ol(()=>le(s),[s]),[g,f]=Ll(d("Loading summary…")),[u,x]=Ll(!1);return rc(()=>{let b=_r(t,c);if(b){f(d(ic(b))),x(!0);return}let v=!0;return f(d("Loading summary…")),x(!1),r.aggregate(e,c).then((y)=>{if(!v)return;if(!y.ok){f(y.error.message),x(!0);return}let C=Vl(t,c,y.data,a??{},{unassigned:d("Unassigned"),checked:d("Checked"),unchecked:d("Unchecked"),none:d("none")});f(C.length?C.join(" · "):d("No summary rows.")),x(!1)}).catch(()=>{if(!v)return;f(d("The collection service is unavailable.")),x(!0)}),()=>{v=!1}},[r,e,t,c,a,d,l]),ea("p",{role:u?"alert":"status","data-uibot":"collection-aggregate",children:g})}import{jsx as Ie,jsxs as _t,Fragment as ia}from"react/jsx-runtime";function Go(e){if(!e.aggregate)return null;return Ie(Ao,{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 Le={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},nn={padding:12,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)"},ni={items:[],total:0,nextCursor:null,limit:50};function Yo(e,t,n=!0){let o=le(e.locale),i=JSON.stringify([e.descriptor.id,e.descriptor.schemaVersion,t]),[r,s]=Yt({key:i,history:[]}),a=r.key===i?r.cursor:void 0,l=r.key===i?r.history:[],c=JSON.stringify([i,a]),[d,g]=Yt(0),[f,u]=Yt({key:c,page:ni,loading:n,error:""});oi(()=>{let b=!0;if(!n){u({key:c,page:ni,loading:!1,error:""});return}u((C)=>({key:c,page:C.key===c?C.page:ni,loading:!0,error:""}));let[v,,y]=JSON.parse(i);return e.client.query(v,{...y,...a?{cursor:a}:{}}).then((C)=>{if(!b)return;if(C.ok)u({key:c,page:C.data,loading:!1,error:""});else u((p)=>({...p,loading:!1,error:C.error.message}))}).catch(()=>{if(b)u((C)=>({...C,loading:!1,error:o("Collection query failed. Retry to load records.")}))}),()=>{b=!1}},[c,i,a,e.client,e.reloadKey,n,d]);let x=f.key===c?f.page:ni;return{page:x,loading:n&&(f.key!==c||f.loading),error:f.key===c?f.error:"",previous:l.length?()=>s({key:i,cursor:l.at(-1),history:l.slice(0,-1)}):void 0,next:x.nextCursor?()=>s({key:i,cursor:x.nextCursor??void 0,history:[...l,a]}):void 0,retry:()=>g((b)=>b+1),pageNumber:l.length+1}}function vr(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 ta({hasPrevious:e,hasNext:t,onPrevious:n,onNext:o,loading:i,page:r,locale:s,ui:a}){let l=le(s);if(!e&&!t)return null;return _t("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[Ie(G,{ui:a,style:Le,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:l("Previous page"),disabled:!e||i,onClick:n}),r?Ie("span",{style:{fontSize:12},children:l("Page {page}",{page:r})}):null,Ie(G,{ui:a,style:Le,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:l("Next page"),disabled:!t||i,onClick:o})]})}function Jo({state:e,locale:t,ui:n,hideCount:o}){let i=le(t);return _t("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[o?null:Ie("span",{children:vr(i,e.page.total,e.page.items.length,t)}),Ie(ta,{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&&Ie("span",{role:"status",children:i("Loading records…")}),e.error&&_t(ia,{children:[Ie("span",{role:"alert",children:e.error}),Ie(G,{ui:n,style:Le,variant:"outline",size:"sm",disabled:e.loading,onClick:e.retry,children:i("Retry query")})]})]})}function na(e){let t=Lr(e.client,e.descriptor.id),n=le(e.locale),[o,i]=Yt(!1),[r,s]=Yt(""),[a,l]=Yt(null),c=Cr(null);wn({dirty:Boolean(c.current),busy:o});let d=()=>{c.current=null,s(""),l(null)};return{saving:o,error:r,setError:s,remote:a,pending:c,reset:d,commit:async(u)=>{if(o||e.readOnly)return!1;c.current=u,i(!0),s(""),l(null);let x=await e.client.mutate(e.descriptor.id,u).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),x.ok)return d(),e.onCommitted(x.data),!0;s(x.error.message);let b=x.error.details?.current;if(b&&typeof b.id==="string"&&Number.isSafeInteger(b.version)&&b.version>0)l(b);return!1},retryRequest:()=>c.current&&a?{idempotencyKey:crypto.randomUUID(),items:c.current.items.map((u)=>u.op!=="insert"&&u.id===a.id?{...u,expectedVersion:a.version}:u)}:c.current}}function oa({mutation:e,onRetry:t,locale:n,ui:o}){let i=le(n);return _t(ia,{children:[e.error&&Ie("p",{role:"alert",children:e.error}),e.remote&&_t("div",{style:nn,children:[Ie("strong",{children:i("Current server version {version}",{version:e.remote.version})}),Ie("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(e.remote.values,null,2)}),Ie(G,{ui:o,style:Le,variant:"outline",size:"sm",disabled:e.saving,onClick:t,children:i("Retry against current version")})]})]})}function qn({row:e,onClose:t,onCancel:n,onDirtyChange:o,onBusyChange:i,stickyActions:r,...s}){let a=le(s.locale),l=vt(s.features),c=!s.readOnly&&l.rowDelete,d=!s.readOnly&&l.rowUpdate,g=Cr(e.values),[f,u]=Yt(()=>({...g.current})),[x,b]=Yt(!1);wn({dirty:JSON.stringify(f)!==JSON.stringify(g.current),busy:!1});let v=Cr(null),[y,C]=Yt(!1);oi(()=>{v.current?.focus()},[]);let p=na(s),k=Po(s.descriptor.fields,s.view),P=JSON.stringify(f)!==JSON.stringify(e.values);oi(()=>{o?.(P)},[P,o]),oi(()=>{i?.(p.saving)},[p.saving,i]);let M=async(R=!1)=>{b(!0);try{let A=R?p.retryRequest():p.pending.current;if(!A){let _=k.filter((w)=>w.type!=="lookup"&&w.type!=="formula"&&w.type!=="rollup"&&JSON.stringify(f[w.id])!==JSON.stringify(e.values[w.id]));if(!_.length){p.setError(a("Change a field before saving."));return}let L=hr(_,f,a,s.locale);A={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:e.id,expectedVersion:e.version,values:L}]}}if(await p.commit(A))t()}catch(A){p.setError(A instanceof Error?A.message:a("Invalid value"))}},B=async()=>{let R=p.pending.current?.items[0]?.op==="delete"?p.pending.current:{idempotencyKey:crypto.randomUUID(),items:[{op:"delete",id:e.id,expectedVersion:e.version}]};if(await p.commit(R))t()};return _t("div",{ref:v,tabIndex:-1,onKeyDown:(R)=>{if(R.key==="Escape"&&!p.saving)R.stopPropagation(),(n??t)()},role:"dialog","aria-label":a("{name} record",{name:Bt(e,s.descriptor.fields)}),style:{...nn,marginTop:12},children:[Ie("h3",{children:Bt(e,s.descriptor.fields)}),s.onInspectRecord&&Ie(G,{ui:s.ui,style:Le,variant:"outline",size:"sm",disabled:p.saving,onClick:()=>s.onInspectRecord?.(e.id),children:a("Open record activity")}),_t("form",{onSubmit:(R)=>{R.preventDefault(),M()},children:[Ie("fieldset",{disabled:p.saving||y||!d,style:{border:0,padding:0},children:Ie(Io,{fields:k,values:f,submitted:x,...s.locale?{locale:s.locale}:{},...s.ui?{ui:s.ui}:{},relationClient:s.client,linkedRecords:e.linkedRecords,computedErrors:e.computedErrors,onChange:(R)=>{u(R),p.reset()}})}),_t("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:[d&&Ie("button",{type:"submit",style:{...Le,...Ko},disabled:p.saving||y,children:p.saving?a("Saving…"):a("Save record")}),r?null:Ie("button",{type:"button",style:Le,disabled:p.saving,onClick:n??t,children:a("Close record")}),r&&c?Ie("span",{style:{marginLeft:"auto"},children:Ie(G,{ui:s.ui,variant:"ghost",size:"sm",icon:"trash",disabled:p.saving,onClick:()=>C(!0),children:a("Delete record")})}):null]})]}),c&&!r&&Ie("button",{type:"button",style:Le,disabled:p.saving,onClick:()=>C(!0),children:a("Delete record")}),y&&s.ui?.ConfirmDialog?s.ui.ConfirmDialog({open:!0,destructive:!0,title:a("Delete this record?"),description:a("Delete this record? Your unsaved changes will be discarded after deletion."),confirmLabel:a("Delete"),cancelLabel:a("Cancel"),busy:p.saving,onConfirm:()=>void B(),onCancel:()=>{if(C(!1),p.pending.current?.items[0]?.op==="delete")p.reset()}}):null,y&&!s.ui?.ConfirmDialog&&_t(Jr,{alert:!0,label:a("Confirm record deletion"),busy:p.saving,onCancel:()=>{if(C(!1),p.pending.current?.items[0]?.op==="delete")p.reset()},children:[Ie("p",{children:a("Delete this record? Your unsaved changes will be discarded after deletion.")}),Ie("button",{type:"button",style:Le,disabled:p.saving,onClick:()=>void B(),children:a("Confirm deletion")}),Ie("button",{type:"button",style:Le,disabled:p.saving,onClick:()=>{if(C(!1),p.pending.current?.items[0]?.op==="delete")p.reset()},children:a("Cancel deletion")})]}),Ie(oa,{mutation:p,onRetry:()=>void M(!0),locale:s.locale,ui:s.ui})]})}function ra(e){let t=le(e.locale),n=!e.readOnly&&vt(e.features).rowCreate,o=Cr(null),i=Po(e.descriptor.fields,{...e.view,hiddenColumns:e.view.hiddenColumns.filter((v)=>!e.descriptor.fields.find((y)=>y.id===v)?.required)}),r=()=>({...Object.fromEntries(i.filter((v)=>v.type==="checkbox").map((v)=>[v.id,!1])),...gr(i)}),s=Cr(r()),[a,l]=Yt(s.current),[c,d]=Yt(!1),[g,f]=Yt(!1);wn({dirty:JSON.stringify(a)!==JSON.stringify(s.current),busy:!1});let u=na(e),x=()=>o.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")?.focus(),b=async()=>{if(!n)return;f(!0);try{let v=u.pending.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:hr(i,a,t,e.locale)}]};if(await u.commit(v))s.current=r(),l(s.current),d(!0),f(!1),requestAnimationFrame(x)}catch(v){u.setError(v instanceof Error?v.message:t("Invalid value"))}};return _t("section",{"data-uibot":"collection-form",style:nn,children:[Ie("h3",{children:e.view.name}),e.readOnly&&Ie("p",{children:t("Record creation requires editor permission.")}),_t("form",{ref:o,onSubmit:(v)=>{v.preventDefault(),b()},children:[Ie("fieldset",{disabled:u.saving||!n,style:{border:0,padding:0},children:Ie(Io,{fields:i,values:a,submitted:g,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},relationClient:e.client,onChange:(v)=>{l(v),d(!1),u.reset()}})}),n&&Ie("button",{type:"submit",style:{...Le,...Ko},disabled:u.saving,children:u.saving?t("Creating…"):t("Create record")})]}),Ie(oa,{mutation:u,onRetry:()=>void b(),locale:e.locale,ui:e.ui}),c?_t("p",{role:"status",children:[t("Record created. Add another below."),e.onShowRecords?_t(ia,{children:[" ",Ie(G,{ui:e.ui,style:Le,variant:"outline",size:"sm",onClick:e.onShowRecords,children:t("Show records")})]}):null]}):null]})}function ri(e){let[t,n]=Yt(null),o=na(e),i=!e.readOnly&&vt(e.features).rowUpdate;return{intent:t,mutation:o,move:async(a,l)=>{if(!i||o.saving||t)return;n({row:a,values:l});let c={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:a.id,expectedVersion:a.version,values:l}]};if(await o.commit(c))n(null)},retry:async()=>{let a=o.retryRequest();if(a&&await o.commit(a))n(null)},cancel:()=>{n(null),o.reset()},blocked:o.saving||!!t}}function ii({state:e,locale:t,ui:n}){let o=le(t);if(!e.intent)return null;return _t("div",{role:"dialog","aria-label":o("Pending record move"),style:nn,children:[Ie("p",{children:e.mutation.saving?o("Moving record…"):o("The move has been kept for retry.")}),Ie("pre",{children:JSON.stringify(e.intent.values,null,2)}),Ie(oa,{mutation:e.mutation,onRetry:()=>void e.retry(),locale:t,ui:n}),!e.mutation.remote&&Ie(G,{ui:n,style:Le,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:()=>void e.retry(),children:o("Retry move")}),Ie(G,{ui:n,style:Le,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:e.cancel,children:o("Cancel move")})]})}import{useEffect as gc,useMemo as _l,useRef as pc,useState as mc}from"react";import{useEffect as aa,useMemo as sc,useState as Do}from"react";import{jsx as Qo,jsxs as Bl}from"react/jsx-runtime";function ai(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 xr(e){let t=sc(()=>le(e.locale),[e.locale]),[n,o]=Do(""),[i,r]=Do(),[s,a]=Do(null),[l,c]=Do([]),[d,g]=Do(()=>ai({},e.labels)),[f,u]=Do(""),[x,b]=Do(!1),v=e.field.relation?.collectionId,y=e.field.relation?.labelFieldId,{getOptions:C,value:p}=e;aa(()=>{g((M)=>ai(M,e.labels))},[e.labels]),aa(()=>{let M=!1;if(!v||!C)return;return b(!0),u(""),C({collectionId:v,...y?{labelFieldId:y}:{},search:n,...i?{cursor:i}:{},limit:50}).then((B)=>{if(M)return;if(!B.ok){u(B.error.message),a(null);return}let R=B.data.items.slice(0,50);g((A)=>ai(A,R)),c((A)=>{let _=i?[...A,...R]:R;return[...new Map(_.map((L)=>[L.id,L])).values()]}),a(B.data.nextCursor)}).catch(()=>{if(!M)u(t("Relation options unavailable."))}).finally(()=>{if(!M)b(!1)}),()=>{M=!0}},[v,y,n,i,C,t]),aa(()=>{if(!p||!v||!C)return;if(e.labels?.some((B)=>B.id===p&&B.label.trim()))return;let M=!1;return C({collectionId:v,...y?{labelFieldId:y}:{},ids:[p],limit:50}).then((B)=>{if(M||!B.ok)return;let R=B.data.items.find((A)=>A.id===p);if(R)g((A)=>ai(A,[R]))}).catch(()=>{}),()=>{M=!0}},[p,v,y,C,e.labels]);let k=!v||!C,P=p?d[p]??l.find((M)=>M.id===p)?.label??p:"";return Bl("div",{children:[Qo("input",{"aria-label":t("Search {name}",{name:e.field.name}),value:n,disabled:e.disabled||k,onChange:(M)=>{o(M.currentTarget.value),r(void 0),c([]),a(null)}}),Bl("select",{"aria-label":e.label??e.field.name,value:e.value,disabled:e.disabled||k||x,onChange:(M)=>{let B=M.currentTarget.value;if(!B||l.some((R)=>R.id===B))e.onChange(B)},children:[Qo("option",{value:"",children:t("No relation")}),p&&!l.some((M)=>M.id===p)&&Qo("option",{value:p,children:P}),l.map((M)=>Qo("option",{value:M.id,children:M.label},M.id))]}),s&&Qo("button",{type:"button",disabled:x||e.disabled,onClick:()=>r(s),children:t("More {name} options",{name:e.field.name})}),(f||k)&&Qo("span",{role:"status",children:f||t("Relation option provider unavailable.")})]})}var dc={"zh-CN":{is:"等于",isNot:"不等于",contains:"包含",notContains:"不包含",isEmpty:"为空",isNotEmpty:"不为空",gt:"大于",gte:"大于等于",lt:"小于",lte:"小于等于",before:"早于",after:"晚于",onOrBefore:"不晚于",onOrAfter:"不早于"},en:{is:"is",isNot:"is not",contains:"contains",notContains:"does not contain",isEmpty:"is empty",isNotEmpty:"is not empty",gt:">",gte:"≥",lt:"<",lte:"≤",before:"is before",after:"is after",onOrBefore:"is on or before",onOrAfter:"is on or after"}},cc={"zh-CN":{is:"恰好是",isNot:"不是恰好",contains:"包含任一",notContains:"不包含任一"},en:{is:"is exactly",isNot:"is not exactly",contains:"has any of",notContains:"has none of"}},uc={"zh-CN":{exactDate:"指定日期",dateRange:"日期区间",today:"今天",yesterday:"昨天",tomorrow:"明天",currentWeek:"本周",lastWeek:"上周",nextWeek:"下周",currentMonth:"本月",lastMonth:"上月",nextMonth:"下月",currentYear:"今年",lastYear:"去年",nextYear:"明年",pastDays:"过去 N 天",nextDays:"未来 N 天",daysAgo:"N 天前",daysFromNow:"N 天后"},en:{exactDate:"exact date",dateRange:"date range",today:"today",yesterday:"yesterday",tomorrow:"tomorrow",currentWeek:"this week",lastWeek:"last week",nextWeek:"next week",currentMonth:"this month",lastMonth:"last month",nextMonth:"next month",currentYear:"this year",lastYear:"last year",nextYear:"next year",pastDays:"past N days",nextDays:"next N days",daysAgo:"N days ago",daysFromNow:"N days from now"}},li=(e,t="en",n)=>{if(n&&un(n)==="multipleSelect"){let o=cc[t][e];if(o)return o}return dc[t][e]??e},si=(e,t="en")=>uc[t][e]??e;function la(e,t){if(!t)return"";let n=e?xt(e):void 0;return n?Bn(t,{...n,time:"none"}):t}function Ul(e,t,n="en"){let o=n==="zh-CN";return e.filterSet.map((i)=>{if("filterSet"in i)return`(${Ul(i,t,n)})`;let r=t.find((c)=>c.id===i.fieldId),s=li(i.operator,n,r);if(i.operator==="isEmpty"||i.operator==="isNotEmpty")return`${r?.name??i.fieldId} ${s}`;let a=(c)=>r?.options?.find((d)=>d.id===c)?.name??String(c??""),l;if(Mi(i.value)){let c=i.value,d=si(c.mode,n);l=c.mode==="exactDate"?la(r,c.date):c.mode==="dateRange"?`${la(r,c.date)} ~ ${la(r,c.to)}`:c.days!==void 0?d.replace("N",String(c.days)):d}else l=Array.isArray(i.value)?i.value.map(a).join(o?"、":", "):a(i.value);return`${r?.name??i.fieldId} ${s} ${l}`}).join(e.conjunction==="or"?o?" 或 ":" OR ":o?" 且 ":" AND ")}import{jsx as Ne,jsxs as In,Fragment as Hl}from"react/jsx-runtime";var fc={text:["is","isNot","contains","isEmpty"],number:["is","isNot","gte","lte","isEmpty"],checkbox:["is"],date:["is","isNot","before","onOrAfter","isEmpty"],singleSelect:["is","isNot","isEmpty"],multipleSelect:["is","contains","isEmpty"]};function Zo(e){return Ne("span",{style:Ke.cell,children:Ne(Ge,{...e})})}var di=()=>`row_${Math.random().toString(36).slice(2,10)}`,yc=(e)=>("filterSet"in e),bc=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}};function sa(e,t){if(t)return tl(e);let n=un(e);return n?fc[n]??[]:[]}function da(e,t,n){if(qo.has(t))return;let o=un(e);if(o==="date"&&n)return{mode:"today",timeZone:xt(e)?.timeZone??bc()};if(o==="checkbox")return!0;if(o==="multipleSelect")return[];return o==="number"?void 0:""}function ql(e){let t=[],n=[];for(let o of e?.filterSet??[])if(yc(o))n.push({key:di(),node:o});else t.push({key:di(),fieldId:o.fieldId,operator:o.operator,value:o.value});return{rows:t,groups:n,conjunction:e?.conjunction??"and"}}function zl(e,t,n,o){let i=[],r=!0;for(let l of t){let c=e.find((f)=>f.id===l.fieldId);if(!c||!l.operator){r=!1;continue}let d=l.value===""||Array.isArray(l.value)&&l.value.length===0;if(!qo.has(l.operator)&&d){r=!1;continue}let g={fieldId:l.fieldId,operator:l.operator,...qo.has(l.operator)?{}:{value:l.value}};if(nl(c,g))r=!1;else i.push(g)}let s=n.map((l)=>l.node).filter((l)=>Boolean(l?.filterSet.length)),a=[...i,...s];return{node:a.length?{conjunction:o,filterSet:a}:void 0,complete:r}}function ci(e){let{ui:t,locale:n}=e,o=e.advanced!==!1,i=e.allowGroups!==!1,r=_l(()=>le(n),[n]),s=_l(()=>e.fields.filter((b)=>!tt(b)&&un(b)!==null),[e.fields]),[a,l]=mc(()=>ql(e.filter)),c=pc(JSON.stringify(e.filter??null));gc(()=>{let b=JSON.stringify(e.filter??null);if(b!==c.current)c.current=b,l(ql(e.filter))},[e.filter]);let d=(b)=>{l(b);let{node:v}=zl(s,b.rows,b.groups,b.conjunction),y=JSON.stringify(v??null);if(y!==c.current)c.current=y,e.onChange(v)},g=(b,v)=>d({...a,rows:a.rows.map((y)=>y.key===b?{...y,...v}:y)}),f=()=>{let b=s[0];if(!b)return;let v=sa(b,o)[0]??"";d({...a,rows:[...a.rows,{key:di(),fieldId:b.id,operator:v,value:v?da(b,v,o):void 0}]})},u=()=>d({...a,groups:[...a.groups,{key:di(),node:void 0}]}),x=zl(s,a.rows,a.groups,a.conjunction).complete===!1||a.groups.some((b)=>b.node===void 0);return In("div",{"data-uibot-filter-builder":"",style:Ke.root,children:[a.rows.length+a.groups.length>1?In("div",{style:Ke.inline,children:[Ne("span",{children:r("Match")}),Ne(Zo,{ui:t,label:r("Filter conjunction"),style:Ke.control,value:a.conjunction,options:[{value:"and",label:r("all conditions")},{value:"or",label:r("any condition")}],onChange:(b)=>d({...a,conjunction:b==="or"?"or":"and"})})]}):null,a.rows.map((b,v)=>{let y=s.find((k)=>k.id===b.fieldId),C=y?un(y):null,p=y?sa(y,o):[];return In("fieldset",{"aria-label":r("Condition {index}",{index:v+1}),style:{...Ke.condition,margin:0,padding:0,border:0,minWidth:0},children:[Ne("span",{style:Ke.slot,children:Ne(Zo,{ui:t,label:r("Filter field"),style:Ke.control,value:b.fieldId,options:s.map((k)=>({value:k.id,label:k.name})),onChange:(k)=>{let P=s.find((A)=>A.id===k);if(!P)return;let M=sa(P,o),B=M.includes(b.operator)?b.operator:M[0]??"",R=un(P)===C;g(b.key,{fieldId:k,operator:B,value:B&&!(R&&B===b.operator)?da(P,B,o):b.value})}})}),Ne("span",{style:Ke.slot,children:Ne(Zo,{ui:t,label:r("Filter operator"),style:Ke.control,value:b.operator,options:p.map((k)=>({value:k,label:li(k,n??"en",y)})),onChange:(k)=>{if(!y)return;let P=k;g(b.key,{operator:P,value:da(y,P,o)})}})}),y&&b.operator&&!qo.has(b.operator)?Ne("span",{style:Ke.slot,children:Ne(hc,{field:y,row:b,advanced:o,t:r,props:e,onValue:(k)=>g(b.key,{value:k})})}):null,Ne(G,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove condition {index}",{index:v+1}),title:r("Remove condition {index}",{index:v+1}),style:{flex:"0 0 auto"},onClick:()=>d({...a,rows:a.rows.filter((k)=>k.key!==b.key)})})]},b.key)}),i?a.groups.map((b,v)=>In("fieldset",{"aria-label":r("Condition group {index}",{index:v+1}),style:Ke.group,children:[In("div",{style:Ke.groupHead,children:[Ne("strong",{style:{fontSize:13},children:r("Condition group {index}",{index:v+1})}),Ne(G,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove group {index}",{index:v+1}),title:r("Remove group {index}",{index:v+1}),onClick:()=>d({...a,groups:a.groups.filter((y)=>y.key!==b.key)})})]}),Ne(ci,{fields:e.fields,filter:b.node,allowGroups:!1,advanced:o,...n?{locale:n}:{},...t?{ui:t}:{},...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},onChange:(y)=>d({...a,groups:y?a.groups.map((C)=>C.key===b.key?{...C,node:y}:C):a.groups.filter((C)=>C.key!==b.key)})})]},b.key)):a.groups.length?In("p",{style:Ke.hint,children:[r("{count} grouped conditions are kept.",{count:a.groups.length})," ",Ne(G,{ui:t,variant:"ghost",size:"sm",onClick:()=>d({...a,groups:[]}),children:r("Remove")})]}):null,x?Ne("p",{role:"status",style:Ke.hint,children:r("Finish the highlighted condition to apply it.")}):null,In("div",{style:Ke.inline,children:[Ne(G,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:s.length===0,onClick:f,children:r("Add condition")}),i?Ne(G,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:s.length===0,onClick:u,children:r("Add group")}):null,a.rows.length||a.groups.length?Ne(G,{ui:t,variant:"ghost",size:"sm",onClick:()=>d({rows:[],groups:[],conjunction:"and"}),children:r("Clear filter")}):null]})]})}function hc({field:e,row:t,advanced:n,t:o,props:i,onValue:r}){let{ui:s}=i,a=un(e),l=o("Filter value"),c=(d,g,f,u)=>i.renderCellEditor?.({...i.getRelationOptions?{getRelationOptions:i.getRelationOptions}:{},field:{...e,...u,required:!1},text:d,disabled:!1,mode:"filter",label:f,autoOpen:!1,onChange:g,onSave:()=>{},onCancel:()=>g("")});if(a==="number")return Ne("input",{"aria-label":l,type:"number",step:"any",style:Ke.control,value:typeof t.value==="number"?String(t.value):"",onChange:(d)=>{let g=d.currentTarget.value;r(g===""||!Number.isFinite(Number(g))?void 0:Number(g))}});if(a==="text")return Ne("input",{"aria-label":l,style:Ke.control,value:typeof t.value==="string"?t.value:"",onChange:(d)=>r(d.currentTarget.value)});if(a==="checkbox")return Ne(Zo,{ui:s,label:l,style:Ke.control,value:t.value===!1?"false":"true",options:[{value:"true",label:o("Yes")},{value:"false",label:o("No")}],onChange:(d)=>r(d==="true")});if(a==="singleSelect"||a==="multipleSelect"){let d=Array.isArray(t.value)?t.value.join(","):typeof t.value==="string"?t.value:"",g=c(d,(u)=>r(a==="multipleSelect"?u.split(",").filter(Boolean):u),l);if(g)return g;if(a==="singleSelect")return Ne(Zo,{ui:s,label:l,style:Ke.control,value:d,options:[{value:"",label:o("Choose option")},...(e.options??[]).map((u)=>({value:u.id,label:u.name}))],onChange:r});let f=new Set(d.split(",").filter(Boolean));return Ne("fieldset",{"aria-label":l,style:{...Ke.inline,margin:0,padding:0,border:0},children:(e.options??[]).map((u)=>In("label",{style:Ke.inline,children:[Ne("input",{type:"checkbox",checked:f.has(u.id),onChange:(x)=>{let b=new Set(f);if(x.currentTarget.checked)b.add(u.id);else b.delete(u.id);r([...b])}}),u.name]},u.id))})}if(a==="relation"){let d=typeof t.value==="string"?t.value:"";return c(d,r,l)??Ne(xr,{field:e,value:d,onChange:r,label:l,getOptions:i.getRelationOptions,locale:i.locale})}if(a==="date"){if(!n||typeof t.value==="string"){let d=typeof t.value==="string"?t.value:"";return c(d,r,l)??Ne("input",{"aria-label":l,type:"date",style:Ke.control,value:d.slice(0,10),onChange:(g)=>r(g.currentTarget.value)})}return Ne(Cc,{field:e,value:t.value,t:o,props:i,custom:c,onValue:r})}return null}function Cc({field:e,value:t,t:n,props:o,custom:i,onValue:r}){let s=t??{mode:"today"},a=(d)=>r({...s,...d}),l=(d,g,f)=>i(g??"",(u)=>f(u.slice(0,10)),d,{formatting:{date:"YYYY-MM-DD",time:"none"}})??Ne("input",{"aria-label":d,type:"date",style:Ke.control,value:g??"",onChange:(u)=>f(u.currentTarget.value)}),c=(d)=>{let{date:g,to:f,days:u,...x}=s;r({...x,mode:d,...zr.has(d)?{days:7}:{}})};return In(Hl,{children:[Ne(Zo,{ui:o.ui,label:n("Date mode"),style:Ke.control,value:s.mode,options:Ei.map((d)=>({value:d,label:si(d,o.locale??"en")})),onChange:(d)=>c(d)}),s.mode==="exactDate"?l(n("Filter value"),s.date,(d)=>a({date:d})):null,s.mode==="dateRange"?In(Hl,{children:[l(n("From date"),s.date,(d)=>a({date:d})),l(n("To date"),s.to,(d)=>a({to:d}))]}):null,zr.has(s.mode)?Ne("input",{"aria-label":n("Number of days"),type:"number",min:0,step:1,style:{...Ke.control,width:84},value:s.days??"",onChange:(d)=>{let g=d.currentTarget.value;if(g===""){let{days:f,...u}=s;r(u)}else a({days:Number(g)})}}):null,Ne("span",{style:Ke.hint,children:xt(e)?.timeZone??s.timeZone??""})]})}var $l="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",Ke={group:{margin:0,minWidth:0,display:"grid",gap:8,padding:10,border:`1px solid ${$l}`,borderRadius:8},groupHead:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},cell:{flex:"1 1 120px",minWidth:0,display:"flex"},condition:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},slot:{display:"flex",minWidth:0,flex:"1 1 120px"},root:{display:"grid",gap:8},row:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},inline:{display:"inline-flex",flexWrap:"wrap",alignItems:"center",gap:6},control:{width:"100%",minWidth:0,minHeight:30,padding:"0 8px",border:`1px solid ${$l}`,borderRadius:6,background:"transparent",color:"inherit",font:"inherit"},hint:{margin:0,fontSize:12,opacity:0.7}};import{jsx as Je,jsxs as zn,Fragment as xc}from"react/jsx-runtime";var ca={display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},ua={minHeight:30,padding:"0 8px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit"};function ui({fields:e,view:t,onChange:n,locale:o,ui:i,editor:r}){return Je("div",{"data-uibot-view-filter":"",children:Je(ci,{fields:e,filter:t.filter,locale:o,ui:i,renderCellEditor:r?.renderCellEditor,getRelationOptions:r?.getRelationOptions,advanced:r?.advanced,onChange:(s)=>{if(s)n({...t,filter:s});else{let{filter:a,...l}=t;n(l)}}})})}var vc=10;function gi({fields:e,view:t,onChange:n,locale:o,ui:i}){let r=le(o),s=t.sort??[],a=e.filter((g)=>tn(g)),l=a.filter((g)=>!s.some((f)=>f.fieldId===g.id)),c=(g)=>{if(g.length)n({...t,sort:g});else{let{sort:f,...u}=t;n(u)}},d=(g,f)=>{let u=[...s],[x]=u.splice(g,1);if(x)u.splice(g+f,0,x);c(u)};return zn("div",{"data-uibot-view-sort":"",style:{display:"grid",gap:8},children:[s.map((g,f)=>zn("fieldset",{"aria-label":r("Sort {index}",{index:f+1}),style:{...ca,margin:0,padding:0,border:0,minWidth:0},children:[Je("span",{style:{flex:"1 1 120px",minWidth:110,display:"flex"},children:Je(Ge,{ui:i,label:r("Sort field"),style:ua,value:g.fieldId,options:a.filter((u)=>u.id===g.fieldId||l.includes(u)).map((u)=>({value:u.id,label:u.name})),onChange:(u)=>c(s.map((x,b)=>b===f?{...x,fieldId:u}:x))})}),Je("span",{style:{flex:"0 1 110px",minWidth:90,display:"flex"},children:Je(Ge,{ui:i,label:r("Sort direction"),style:ua,value:g.direction,options:[{value:"asc",label:r("Ascending")},{value:"desc",label:r("Descending")}],onChange:(u)=>c(s.map((x,b)=>b===f?{...x,direction:u}:x))})}),Je(G,{ui:i,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:f===0,ariaLabel:r("Move sort {index} up",{index:f+1}),title:r("Move sort {index} up",{index:f+1}),onClick:()=>d(f,-1),children:" "}),Je(G,{ui:i,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:f===s.length-1,ariaLabel:r("Move sort {index} down",{index:f+1}),title:r("Move sort {index} down",{index:f+1}),onClick:()=>d(f,1),children:" "}),Je(G,{ui:i,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove sort {index}",{index:f+1}),title:r("Remove sort {index}",{index:f+1}),onClick:()=>c(s.filter((u,x)=>x!==f)),children:" "})]},g.fieldId)),zn("div",{style:ca,children:[Je(G,{ui:i,variant:"outline",size:"sm",icon:"plus",disabled:l.length===0||s.length>=vc,onClick:()=>{let g=l[0];if(g)c([...s,{fieldId:g.id,direction:"asc"}])},children:r("Add sort")}),s.length?Je(G,{ui:i,variant:"ghost",size:"sm",onClick:()=>c([]),children:r("Clear sort")}):Je("span",{style:{fontSize:12,opacity:0.7},children:r("Default order")})]})]})}function Kl({fields:e,view:t,onChange:n,locale:o,ui:i,bare:r}){let s=le(o),l=[...t.columnOrder.flatMap((g)=>{let f=e.find((u)=>u.id===g);return f?[f]:[]}),...e.filter((g)=>!t.columnOrder.includes(g.id))],c=(g,f)=>{let u=l.map((v)=>v.id),x=u[g],b=u[g+f];if(x===void 0||b===void 0)return;u[g]=b,u[g+f]=x,n({...t,columnOrder:u})},d=zn("div",{style:{display:"grid",gap:6,paddingTop:r?0:6,minWidth:0},children:[zn("label",{children:[Je("input",{type:"checkbox",checked:t.showRowNumber!==!1,onChange:(g)=>n({...t,showRowNumber:g.currentTarget.checked})})," ",s("Show row numbers")]}),zn("label",{children:[Je("input",{type:"checkbox",checked:t.showRecordId===!0,onChange:(g)=>n({...t,showRecordId:g.currentTarget.checked})})," ",s("Show record IDs")]}),l.map((g,f)=>{let u=!t.hiddenColumns.includes(g.id),x=`${g.name}${g.required?" *":""}`;return zn("div",{style:{...ca,flexWrap:"nowrap",gap:4},children:[Je(G,{ui:i,variant:"ghost",size:"sm",icon:u?"eye":"eyeOff",iconOnly:!0,disabled:t.type==="form"&&g.required===!0,ariaLabel:x,title:s(u?"Hide {name}":"Show {name}",{name:g.name}),onClick:()=>n({...t,hiddenColumns:u?[...t.hiddenColumns,g.id]:t.hiddenColumns.filter((b)=>b!==g.id)})}),Je("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:u?1:0.5},children:x}),Je(G,{ui:i,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:f===0,ariaLabel:s("Move {name} left",{name:g.name}),onClick:()=>c(f,-1)}),Je(G,{ui:i,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:f===l.length-1,ariaLabel:s("Move {name} right",{name:g.name}),onClick:()=>c(f,1)})]},g.id)})]});if(r)return Je("div",{"data-uibot-view-columns":"",children:d});return zn("details",{"data-uibot-view-columns":"",children:[Je("summary",{children:s("Columns")}),d]})}function pi({fields:e,view:t,onChange:n,locale:o,ui:i}){let r=le(o),s=e.filter((a)=>a.type==="singleSelect"||a.type==="checkbox");return Je("div",{style:{display:"flex",gap:6,alignItems:"center"},children:t.groupByFieldId?zn(xc,{children:[Je(xe,{name:"group"}),Je(Ge,{ui:i,label:r("Grid grouping field"),style:ua,value:t.groupByFieldId,options:s.map((a)=>({value:a.id,label:a.name})),onChange:(a)=>n({...t,groupByFieldId:a})}),Je(G,{ui:i,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove grouping"),onClick:()=>{let a={...t};delete a.groupByFieldId,n(a)}})]}):Je(G,{ui:i,variant:"outline",size:"sm",icon:"plus",onClick:()=>{let a=s[0];if(a)n({...t,groupByFieldId:a.id})},children:r("Add grouping")})})}import{useState as wr}from"react";import{jsx as gt,jsxs as ao}from"react/jsx-runtime";var Pr={table:{label:"Table",path:"M2.5 3.5h11v9h-11zM2.5 7h11M6.5 3.5v9"},users:{label:"People",path:"M6 7.5a2.2 2.2 0 1 0 0-4.4 2.2 2.2 0 0 0 0 4.4zM2 13c0-2.2 1.8-3.6 4-3.6s4 1.4 4 3.6M11 7a1.8 1.8 0 1 0 0-3.6M12 9.6c1.3.3 2.2 1.4 2.2 3"},briefcase:{label:"Business",path:"M2.5 5.5h11v7h-11zM6 5.5v-2h4v2M2.5 9h11"},list:{label:"List",path:"M5.5 4h8M5.5 8h8M5.5 12h8M2.5 4h.01M2.5 8h.01M2.5 12h.01"},calendar:{label:"Schedule",path:"M3 4.5h10V13H3zM3 7.5h10M6 3v3M10 3v3"},package:{label:"Inventory",path:"M8 2.5l5 2.5v6l-5 2.5L3 11V5zM3 5l5 2.5L13 5M8 7.5v6"}},Wl="table";function mi({icon:e,size:t=15,icons:n=Pr}){let o=(e?n[e]:void 0)??n[Wl]??Pr.table;return gt("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",width:t,height:t,fill:"none",stroke:"currentColor",strokeWidth:1.4,strokeLinecap:"round",strokeLinejoin:"round",style:{flex:"none"},children:gt("path",{d:o?.path??""})})}function ga(e){let t=le(e.locale);return ao("aside",{"data-uibot-table-list":"",style:Fo.root,children:[ao("div",{style:Fo.title,children:[gt("span",{children:t("Tables")}),gt("span",{children:e.tables.length})]}),gt("nav",{"aria-label":t("Tables"),style:Fo.nav,children:e.tables.map((n)=>ao("button",{type:"button","aria-current":n.id===e.activeId?"page":void 0,onClick:()=>e.onSelect(n.id),style:{...Fo.item,...n.id===e.activeId?Fo.active:{}},children:[gt(mi,{icon:n.icon,icons:e.icons??Pr}),gt("span",{style:Fo.name,children:n.name})]},n.id))}),e.onCreate?gt(G,{ui:e.ui,variant:"ghost",style:Fo.create,disabled:e.createDisabled,onClick:e.onCreate,children:t("New table")}):null]})}function pa(e){let t=le(e.locale),n=e.icons??Pr,[o,i]=wr(!1),[r,s]=wr(""),[a,l]=wr(!1),[c,d]=wr(!1),[g,f]=wr(""),u=e.table,x=e.canManage&&Boolean(u)&&!c;async function b(p){d(!0),f("");try{return await p(),!0}catch(k){return f(k instanceof Error?k.message:t("Saving failed. Your edit has been kept.")),!1}finally{d(!1)}}let v=()=>{if(!x||!e.onRename)return;s(u?.name??""),f(""),i(!0)};async function y(){let p=r.trim();if(!p||p===u?.name){i(!1);return}if(await b(()=>e.onRename?.(p)))i(!1)}let C=(p)=>{if(p.key==="Enter"||p.key==="F2")p.preventDefault(),v()};return ao("header",{"data-uibot-table-header":"",style:fn.root,children:[ao("div",{style:fn.left,children:[ao("span",{style:{position:"relative"},children:[gt("button",{type:"button","aria-label":t("Change table icon"),"aria-haspopup":"menu","aria-expanded":a,title:e.canManage?t("Double click to change the icon"):t("Schema permission required"),disabled:!x||!e.onIconChange,style:fn.iconButton,onDoubleClick:()=>l(!0),onKeyDown:(p)=>{if(p.key==="Enter"||p.key===" ")p.preventDefault(),l(!0)},children:gt(mi,{icon:u?.icon,size:17,icons:n})}),a?gt("div",{role:"menu","aria-label":t("Table icon"),style:fn.menu,children:Object.entries(n).map(([p,k])=>ao("button",{type:"button",role:"menuitemradio","aria-checked":(u?.icon??Wl)===p,title:k.label,style:fn.menuItem,onClick:()=>{l(!1),b(()=>e.onIconChange?.(p))},children:[gt(mi,{icon:p,icons:n}),gt("span",{children:k.label})]},p))}):null]}),ao("div",{style:{minWidth:0},children:[o?gt("input",{"aria-label":t("Table name"),value:r,disabled:c,style:fn.input,autoFocus:!0,onChange:(p)=>s(p.currentTarget.value),onBlur:()=>{if(!g)y()},onKeyDown:(p)=>{if(p.key==="Enter")p.preventDefault(),y();if(p.key==="Escape")p.preventDefault(),i(!1),f("")}}):gt("h2",{style:fn.title,children:gt("button",{type:"button","aria-label":t("Rename table {name}",{name:u?.name??""}),title:e.canManage?t("Double click to rename"):t("Schema permission required"),disabled:!x||!e.onRename,style:fn.titleButton,onDoubleClick:v,onKeyDown:C,children:u?.name??t("Start with a table")})}),g?gt("p",{role:"alert",style:fn.error,children:g}):null,gt("p",{style:fn.summary,children:u?t("{count} fields · {mode}",{count:u.fields.length,mode:e.canWrite?t("Editable"):t("Read only")}):t("Start with a table")})]})]}),gt("div",{style:fn.actions,children:e.actions})]})}var jl="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",Fo={root:{display:"grid",gap:8,alignContent:"start",minWidth:180},title:{display:"flex",justifyContent:"space-between",padding:"0 12px",fontSize:12,opacity:0.7},nav:{display:"grid",gap:2},item:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",border:0,borderRadius:6,background:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},active:{background:"var(--uibot-active-bg, color-mix(in srgb, currentColor 10%, transparent))",fontWeight:600},name:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},create:{justifyContent:"flex-start",width:"100%"}},fn={root:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,padding:"12px 20px"},left:{display:"flex",alignItems:"center",gap:12,minWidth:0},iconButton:{width:32,height:32,display:"grid",placeItems:"center",border:0,borderRadius:8,background:"var(--uibot-active-bg, color-mix(in srgb, currentColor 10%, transparent))",color:"inherit",cursor:"pointer"},menu:{position:"absolute",top:"100%",left:0,zIndex:60,display:"grid",minWidth:150,padding:4,border:`1px solid ${jl}`,borderRadius:8,background:"var(--background, #fff)"},menuItem:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:0,background:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},input:{height:32,width:240,maxWidth:"100%",padding:"0 8px",border:`1px solid ${jl}`,borderRadius:6,font:"inherit",fontWeight:600},title:{margin:0,fontSize:16,fontWeight:600},titleButton:{maxWidth:"100%",padding:0,border:0,background:"transparent",color:"inherit",font:"inherit",cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},error:{margin:"4px 0 0",fontSize:12,color:"var(--uibot-danger, #b3261e)"},summary:{margin:"2px 0 0",fontSize:12,opacity:0.7},actions:{display:"flex",alignItems:"center",gap:4}};import{useEffect as ma,useMemo as fa,useRef as To,useState as Xo}from"react";import{jsx as lo,jsxs as ya}from"react/jsx-runtime";function ba(e,t){if(!t)return"";let n=e.fields.find((i)=>i.id==="title")??e.fields[0],o=n?t.values[n.id]:void 0;return typeof o==="string"?o.trim():""}function ha(e){let t=fa(()=>le(e.locale),[e.locale]),n=Lr(e.client,e.descriptor.id),o=To(null);if(o.current===null)o.current=gr(e.descriptor.fields);let[i,r]=Xo(o.current),[s,a]=Xo(!1),l=fa(()=>({client:e.client,descriptor:e.descriptor}),[e.client,e.descriptor]),c=To(l);c.current=l;let d=To(!0);ma(()=>(d.current=!0,()=>{d.current=!1}),[]);let[g,f]=Xo(),u=fa(()=>{let N=new Map,O=(D,J)=>{if(!d.current||c.current!==l)return;f((T)=>({scope:l,targets:{...T?.scope===l?T.targets:{},[D]:J}}))};return{query:async(...D)=>{let J=D[0],T=(N.get(J)??0)+1;N.set(J,T),O(J,!1);try{let j=await e.client.query(...D);if(N.get(J)===T)O(J,j.ok);return j}catch(j){if(N.get(J)===T)O(J,!1);throw j}}}},[e.client,l]),x=e.descriptor.fields.some((N)=>N.type==="linkedRecord"&&(!N.link||g?.scope!==l||!g.targets[N.link.collectionId])),[b,v]=Xo(null),y=To(null),C=To(!1),p=To(null),k=To(null),{autoFocus:P}=e;ma(()=>{if(b?.error)k.current?.focus()},[b]);let[M,B]=Xo(!1),[R,A]=Xo(!1),_=JSON.stringify(i)!==JSON.stringify(o.current)||M;wn({dirty:_,busy:s},e);let L=()=>p.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled])")?.focus();ma(()=>{if(P)L()},[P]);async function w(N){if(C.current||e.readOnly||x)return;A(!0);let O;try{O=hr(e.descriptor.fields,i,t,e.locale)}catch(J){v({text:J instanceof Error?J.message:t("Invalid value"),error:!0,clearable:!0});return}C.current=!0,a(!0),v(null);let D=y.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:O}]};y.current=D;try{let J=await e.client.mutate(e.descriptor.id,D);if(!n.active)return;if(!J.ok){let j=J.error.code==="validation";B(!j),v({text:J.error.message,error:!0,clearable:j});return}y.current=null,B(!1),A(!1),o.current=gr(e.descriptor.fields),r(o.current),e.onCommitted(J.data);let T=ba(e.descriptor,J.data.items[0]);if(v({text:`${N?t("Record saved, keep adding"):t("Record saved")}${T?`:${T}`:""}`,error:!1,clearable:!1}),N)requestAnimationFrame(L);else e.onSaved?.(J.data)}catch{if(!n.active)return;B(!0),v({text:t("Saving failed. Your draft has been kept."),error:!0,clearable:!1})}finally{C.current=!1,a(!1)}}return ya("form",{ref:p,noValidate:!0,"aria-label":t("New record form"),"data-uibot":"record-creator",onSubmit:(N)=>{N.preventDefault();let O=N.nativeEvent.submitter;w(O?.getAttribute("data-continue")==="true")},onKeyDown:(N)=>{if(N.key==="Enter"&&(N.ctrlKey||N.metaKey)&&!N.nativeEvent.isComposing&&!s)N.preventDefault(),N.currentTarget.requestSubmit()},children:[lo("fieldset",{disabled:s||e.readOnly,style:An.fields,children:lo(Io,{fields:e.descriptor.fields,values:i,submitted:R,relationClient:u,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},onChange:(N)=>{if(r(N),y.current=null,B(!1),b?.clearable)v(null)}})}),b?lo("p",{ref:k,role:b.error?"alert":"status",tabIndex:-1,style:b.error?An.error:An.status,children:b.text}):null,ya("div",{"data-uibot":"record-creator-actions",style:e.stickyActions?{...An.actions,...An.sticky}:An.actions,children:[ya("span",{style:An.hint,children:[lo("kbd",{children:"Ctrl / ⌘"})," + ",lo("kbd",{children:"Enter"})," ",t("Save")]}),lo("button",{type:"submit","aria-label":t("Save new record"),"aria-busy":s,disabled:s||e.readOnly||x,style:{...An.button,...Ko},children:s?t("Saving…"):t("Save new record")}),lo("button",{type:"submit","data-continue":"true",disabled:s||e.readOnly||x,style:An.button,children:t("Save and continue")}),e.onCancel&&!e.stickyActions?lo(G,{ui:e.ui,style:An.button,disabled:s,onClick:e.onCancel,children:t("Cancel adding")}):null]})]})}var An={sticky:{position:"sticky",bottom:0,zIndex:1,padding:"12px 0",borderTop:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",background:"var(--background, white)"},fields:{margin:0,padding:0,border:0,minWidth:0},actions:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,marginTop:12},button:{padding:"6px 10px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit",cursor:"pointer"},hint:{marginRight:"auto",fontSize:12,opacity:0.7},error:{margin:"8px 0 0",fontSize:13,color:"var(--uibot-danger, #b3261e)"},status:{margin:"8px 0 0",fontSize:12,opacity:0.8}};import{useEffect as Ac,useLayoutEffect as Dc,useRef as kr}from"react";import{jsx as er}from"react/jsx-runtime";var Gl=[["#e8f0fe","#1a56c4"],["#e6f4ea","#1e7a3c"],["#fdecea","#b3261e"],["#fff1e0","#a05a00"],["#e8eaed","#3c4043"],["#e0f2f1","#00695c"],["#f3e8fd","#6a1b9a"]];function yn(e){let t=Math.max(e,0)%Gl.length,[n,o]=Gl[t]??["#e8eaed","#3c4043"];return{background:`var(--uibot-chip-${t}-bg, ${n})`,color:`var(--uibot-chip-${t}-fg, ${o})`}}function Ca({index:e,children:t}){return er("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",...yn(e)},children:t})}function Eo({ids:e,field:t,wrap:n}){let o=t.options??[];return er("span",{style:{display:"inline-flex",gap:4,alignItems:"center",maxWidth:"100%",overflow:"hidden",...n?{flexWrap:"wrap"}:{}},children:e.map((i)=>{let r=o.findIndex((s)=>s.id===i);return er(Ca,{index:pr(o,i),children:o[r]?.name??String(i)},String(i))})})}function Jl({checked:e,label:t,onToggle:n}){return er("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 Yl={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 fi({type:e}){return er("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:er("path",{d:Yl[e]??Yl.singleLineText})})}var be={root:{display:"grid",gap:12,color:"var(--uibot-schema-fg, inherit)",fontFamily:"inherit"},field:{margin:0,minWidth:0,display:"grid",gap:12,padding:16,border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:10,background:"var(--uibot-schema-bg, transparent)"},row:{display:"flex",flexWrap:"wrap",alignItems:"end",gap:12},control:{display:"grid",flex:"1 1 180px",gap:5,minWidth:140,fontSize:13},label:{color:"var(--uibot-schema-muted, color-mix(in srgb, currentColor 65%, transparent))",fontWeight:600},input:{boxSizing:"border-box",width:"100%",minHeight:"var(--uibot-schema-control-height, 36px)",padding:"7px 9px",border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"var(--uibot-schema-bg, transparent)",color:"inherit",font:"inherit"},button:{minHeight:36,padding:"7px 12px",border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"var(--uibot-schema-surface, transparent)",color:"inherit",font:"inherit",fontWeight:600,cursor:"pointer"},danger:{borderColor:"var(--uibot-schema-danger-border, color-mix(in srgb, #e5534b 45%, transparent))",background:"var(--uibot-schema-danger-bg, transparent)",color:"var(--uibot-schema-danger, #e5534b)"},checkbox:{display:"flex",alignItems:"center",gap:8,minHeight:"var(--uibot-schema-control-height, 36px)",fontSize:13},options:{display:"grid",gap:8,margin:0,minWidth:0,padding:"10px 0 0",border:0,borderTop:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))"},optionRow:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},settings:{display:"grid",gap:10,margin:0,minWidth:0,padding:"10px 0 0",border:0,borderTop:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))"},swatch:{width:18,height:18,padding:0,borderRadius:999,cursor:"pointer",flex:"none"}};import{jsx as Nt,jsxs as Ot,Fragment as Ql}from"react/jsx-runtime";var wc=["YYYY-MM-DD","YYYY/MM/DD","MM/DD/YYYY","DD/MM/YYYY","YYYY年M月D日"],Pc=["Asia/Shanghai","Asia/Hong_Kong","Asia/Tokyo","Asia/Singapore","Europe/London","Europe/Paris","America/New_York","America/Los_Angeles","UTC"],kc=["CNY","USD","EUR","JPY","GBP","HKD"],Sc=[0,1,2,3,4,5,6,7,8],Rc={date:"YYYY-MM-DD",time:"none"},Ic={kind:"decimal",precision:0,grouping:!0};function Zl({field:e,onChange:t,disabled:n,locale:o,ui:i,settings:r,dateFormatLocked:s}){let a=r?.formatting!==!1,l=r?.defaults!==!1,c=le(o),d=(u)=>t((x)=>({...x,...u})),g=()=>t((u)=>{let{defaultValue:x,...b}=u;return b}),f=(u,x,b,v,y=!1)=>Ot("div",{style:be.control,children:[Nt("span",{style:be.label,children:u}),Nt(Ge,{ui:i,label:u,style:be.input,disabled:n||y,value:x,options:b,onChange:v})]});if(e.type==="date"){let u=xt(e)??Rc,x=(v)=>{let{timeZone:y,...C}=u,p={...C,...y?{timeZone:y}:{},...v};if(v.timeZone==="")delete p.timeZone;d({formatting:p})},b=u.time!=="none";if(!a&&!l)return null;return Ot("fieldset",{style:be.settings,"aria-label":c("Format of field {name}",{name:e.name}),children:[a?Ot(Ql,{children:[Nt("strong",{style:{fontSize:13},children:c("Format")}),Ot("div",{style:be.row,children:[f(c("Date format"),u.date,wc.map((v)=>({value:v,label:v})),(v)=>x({date:v}),Boolean(s)),f(c("Time format"),u.time,[{value:"none",label:c("No time (date only)")},{value:"24h",label:c("24-hour")},{value:"12h",label:c("12-hour")}],(v)=>x({time:v}),Boolean(s)),b?f(c("Time zone"),u.timeZone??"",[{value:"",label:c("Viewer's time zone")},...Pc.map((v)=>({value:v,label:v}))],(v)=>x({timeZone:v}),Boolean(s)):null]}),Ot("p",{style:{...be.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[c("Preview"),": ",Bn(new Date().toISOString(),u)]})]}):null,l&&f(c("Default value"),e.defaultValue?.kind==="now"?"now":"",[{value:"",label:c("Empty")},{value:"now",label:b?c("Current date and time"):c("Today")}],(v)=>v==="now"?d({defaultValue:{kind:"now"}}):g())]})}if(e.type==="number"){let u=vo(e)??Ic,x=(v)=>d({formatting:{...u,...v}}),b=e.defaultValue?.kind==="value"?String(e.defaultValue.value):"";if(!a&&!l)return null;return Ot("fieldset",{style:be.settings,"aria-label":c("Format of field {name}",{name:e.name}),children:[a?Ot(Ql,{children:[Nt("strong",{style:{fontSize:13},children:c("Format")}),Ot("div",{style:be.row,children:[f(c("Number style"),u.kind,[{value:"decimal",label:c("Number")},{value:"percent",label:c("Percent")},{value:"currency",label:c("Currency")}],(v)=>x({kind:v})),f(c("Decimal places"),String(u.precision),Sc.map((v)=>({value:String(v),label:String(v)})),(v)=>x({precision:Number(v)})),u.kind==="currency"?f(c("Currency"),u.currency??"CNY",kc.map((v)=>({value:v,label:v})),(v)=>x({currency:v})):null]}),Ot("label",{style:be.checkbox,children:[Nt("input",{type:"checkbox","aria-label":c("Thousands separator"),checked:u.grouping!==!1,disabled:n,onChange:(v)=>x({grouping:v.currentTarget.checked})}),c("Thousands separator")]}),Ot("p",{style:{...be.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[c("Preview"),":"," ",xo(u.kind==="percent"?0.1234:1234.5678,u)]})]}):null,l&&Ot("label",{style:be.control,children:[Nt("span",{style:be.label,children:c("Default value")}),Nt("input",{"aria-label":c("Default value"),style:be.input,type:"number",step:"any",disabled:n,value:b,onChange:(v)=>{let y=v.currentTarget.value;if(y===""||!Number.isFinite(Number(y)))g();else d({defaultValue:{kind:"value",value:Number(y)}})}})]})]})}if(!l)return null;if(e.type==="singleLineText"||e.type==="longText")return Nt("fieldset",{style:be.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:Ot("label",{style:be.control,children:[Nt("span",{style:be.label,children:c("Default value")}),Nt("input",{"aria-label":c("Default value"),style:be.input,disabled:n,value:e.defaultValue?.kind==="value"?String(e.defaultValue.value):"",onChange:(u)=>{let x=u.currentTarget.value;if(x==="")g();else d({defaultValue:{kind:"value",value:x}})}})]})});if(e.type==="checkbox")return Nt("fieldset",{style:be.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:Ot("label",{style:be.checkbox,children:[Nt("input",{type:"checkbox","aria-label":c("Checked by default"),checked:e.defaultValue?.kind==="value"&&e.defaultValue.value===!0,disabled:n,onChange:(u)=>u.currentTarget.checked?d({defaultValue:{kind:"value",value:!0}}):g()}),c("Checked by default")]})});if((e.type==="singleSelect"||e.type==="multipleSelect")&&(e.options?.length??0)>0){let u=e.options??[],x=e.defaultValue?.kind==="value"?e.defaultValue.value:void 0;if(e.type==="singleSelect")return Nt("fieldset",{style:be.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:f(c("Default value"),typeof x==="string"?x:"",[{value:"",label:c("Empty")},...u.map((v)=>({value:v.id,label:v.name}))],(v)=>v?d({defaultValue:{kind:"value",value:v}}):g())});let b=Array.isArray(x)?x:[];return Ot("fieldset",{style:be.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:[Nt("span",{style:be.label,children:c("Default value")}),u.map((v)=>Ot("label",{style:be.checkbox,children:[Nt("input",{type:"checkbox","aria-label":c("Default option {name}",{name:v.name}),checked:b.includes(v.id),disabled:n,onChange:(y)=>{let C=y.currentTarget.checked?[...b,v.id]:b.filter((p)=>p!==v.id);if(C.length)d({defaultValue:{kind:"value",value:C}});else g()}}),v.name]},v.id))]})}return null}import{jsx as st,jsxs as Dn}from"react/jsx-runtime";var Fc=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],Xl=(e)=>e==="singleSelect"||e==="multipleSelect";function Tc(e,t){let n=t.slice(0,Vr);if(!n.trim()){let{description:o,...i}=e;return i}return{...e,description:n}}function yi({fields:e,onChange:t,disabled:n=!1,focusFieldId:o,locale:i,ui:r,fieldTypes:s=Fc,relationTargets:a=[],lockedFieldIds:l=[],settings:c}){let d=le(i),g={singleLineText:d("Single line text"),longText:d("Long text"),number:d("Number"),checkbox:d("Checkbox"),date:d("Date"),singleSelect:d("Single select"),multipleSelect:d("Multiple select"),relation:d("Linked record")},f=(R)=>s.includes(R.type),u=kr(new Map),x=kr(new Map),b=kr(null),v=kr(new Map),y=kr(null);function C(R,A){let _={fields:R,target:A};y.current=_,t(R),queueMicrotask(()=>{if(y.current===_)y.current=null})}Dc(()=>{let R=y.current;if(!R||R.fields!==e)return;if(y.current=null,n)return;let{target:A}=R,_=A.type==="field-name"?u.current.get(A.fieldId):A.type==="option-name"?x.current.get(`${A.fieldId}:${A.optionId}`):null;if(_){_.focus(),_.select();return}(A.type==="add-field"?b.current:A.type==="add-option"?v.current.get(A.fieldId):null)?.querySelector("button")?.focus()},[n,e]),Ac(()=>{if(!o)return;let R=window.setTimeout(()=>{let A=u.current.get(o);A?.scrollIntoView({block:"center"}),A?.focus(),A?.select()},200);return()=>window.clearTimeout(R)},[o]);let p=(R,A)=>{if(!n)t(e.map((_)=>_.id===R?A(_):_))};function k(){if(n)return;let R={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:d("New field"),type:"singleLineText"};C([...e,R],{type:"field-name",fieldId:R.id})}function P(R){if(n)return;let A=e.filter(f),_=A.findIndex((N)=>N.id===R),L=A.filter((N)=>N.id!==R),w=L[_]??L[_-1];C(e.filter((N)=>N.id!==R),w?{type:"field-name",fieldId:w.id}:{type:"add-field"})}function M(R){if(n)return;let A={id:crypto.randomUUID(),name:d("New option")};C(e.map((_)=>_.id===R.id?{..._,options:[..._.options??[],A]}:_),{type:"option-name",fieldId:R.id,optionId:A.id})}function B(R,A){if(n)return;let _=R.options??[],L=_.findIndex((O)=>O.id===A),w=_.filter((O)=>O.id!==A),N=w[L]??w[L-1];C(e.map((O)=>{if(O.id!==R.id)return O;let D=O.defaultValue;if(!(D?.kind==="value"&&(Array.isArray(D.value)?D.value.includes(A):D.value===A)))return{...O,options:w};let{defaultValue:T,...j}=O;return{...j,options:w}}),N?{type:"option-name",fieldId:R.id,optionId:N.id}:{type:"add-option",fieldId:R.id})}return Dn("section",{"aria-label":d("Collection fields"),"data-uibot-schema-editor":"",style:be.root,children:[e.filter(f).map((R)=>Dn("fieldset",{"aria-label":d("Field {name}",{name:R.name}),style:be.field,children:[Dn("div",{style:be.row,children:[Dn("label",{style:be.control,children:[st("span",{style:be.label,children:d("Field name")}),st("input",{"aria-label":d("Field name"),ref:(A)=>{if(A)u.current.set(R.id,A);else u.current.delete(R.id)},style:be.input,value:R.name,disabled:n,onChange:(A)=>{let _=A.currentTarget.value;p(R.id,(L)=>({...L,name:_}))}})]}),Dn("div",{style:be.control,children:[st("span",{style:be.label,children:d("Field type")}),st(Ge,{ui:r,label:d("Field type"),style:be.input,disabled:n||l.includes(R.id),value:R.type,options:s.map((A)=>({value:A,label:g[A]})),onChange:(A)=>p(R.id,(_)=>{let{options:L,relation:w,formatting:N,defaultValue:O,...D}=_;return{...D,type:A,...Xl(A)?{options:_.options??[]}:{},...A==="relation"?{relation:{collectionId:""}}:{}}})})]}),Dn("label",{style:be.checkbox,children:[st("input",{type:"checkbox","aria-label":d("Required"),checked:Boolean(R.required),disabled:n,onChange:(A)=>{let _=A.currentTarget.checked;p(R.id,(L)=>({...L,required:_}))}}),d("Required")]}),st(G,{ui:r,style:{...be.button,...be.danger},disabled:n||l.includes(R.id),icon:"trash",iconOnly:!0,ariaLabel:d("Delete field"),title:d("Delete field {name}",{name:R.name}),onClick:()=>P(R.id)})]}),c?.descriptions===!1?null:Dn("label",{style:be.control,children:[st("span",{style:be.label,children:d("Field description")}),st("textarea",{"aria-label":d("Field description"),style:{...be.input,minHeight:64,resize:"vertical"},rows:2,maxLength:Vr,value:R.description??"",disabled:n,onChange:(A)=>{let _=A.currentTarget.value;p(R.id,(L)=>Tc(L,_))}})]}),R.type==="relation"?Dn("div",{style:be.control,children:[st("span",{style:be.label,children:d("Related table")}),st(Ge,{ui:r,label:d("Related table"),style:be.input,disabled:n||l.includes(R.id),value:R.relation?.collectionId??"",options:[{value:"",label:d("Choose a related table")},...a.map((A)=>({value:A.id,label:A.name}))],onChange:(A)=>p(R.id,(_)=>({..._,relation:{collectionId:A}}))})]}):null,Xl(R.type)?Dn("fieldset",{style:be.options,"aria-label":d("Options of field {name}",{name:R.name}),children:[st("strong",{style:{fontSize:13},children:d("Options")}),(R.options??[]).map((A,_)=>Dn("div",{style:be.optionRow,children:[st("input",{"aria-label":d("Option name {index}",{index:_+1}),ref:(L)=>{let w=`${R.id}:${A.id}`;if(L)x.current.set(w,L);else x.current.delete(w)},style:{...be.input,flex:"1 1 120px",minWidth:0,width:"auto"},value:A.name,disabled:n,onChange:(L)=>{let w=L.currentTarget.value;p(R.id,(N)=>({...N,options:(N.options??[]).map((O)=>O.id===A.id?{...O,name:w}:O)}))}}),c?.optionColors===!1?null:st("fieldset",{"aria-label":d("Colour of option {index}",{index:_+1}),style:{display:"inline-flex",flex:"none",gap:4,margin:0,padding:0,border:0,minWidth:0},children:Pn.map((L,w)=>{let N=(A.color??Pn[_%Pn.length])===L;return st("button",{type:"button","aria-label":d(`Colour ${L}`),"aria-pressed":N,disabled:n,style:{...be.swatch,background:yn(w).color,border:N?"2px solid currentColor":"1px solid transparent"},onClick:()=>p(R.id,(O)=>({...O,options:(O.options??[]).map((D)=>D.id===A.id?{...D,color:L}:D)}))},L)})}),st(G,{ui:r,style:{...be.button,...be.danger},disabled:n,icon:"trash",iconOnly:!0,ariaLabel:d("Delete option {index}",{index:_+1}),title:d("Delete option {index}",{index:_+1}),onClick:()=>B(R,A.id)})]},A.id)),st("div",{ref:(A)=>{if(A)v.current.set(R.id,A);else v.current.delete(R.id)},children:st(G,{ui:r,style:be.button,icon:"plus",disabled:n,onClick:()=>M(R),children:d("Add option")})})]}):null,st(Zl,{field:R,...c?{settings:c}:{},dateFormatLocked:l.includes(R.id),disabled:n,locale:i,ui:r,onChange:(A)=>p(R.id,A)})]},R.id)),st("div",{ref:b,children:st(G,{ui:r,style:be.button,icon:"plus",disabled:n,onClick:k,children:d("Add field")})})]})}import{useEffect as ds,useRef as cs,useState as ka}from"react";import{useCallback as Vc,useEffect as as,useLayoutEffect as Bc,useRef as Pa,useState as ls}from"react";import{createContext as Ec,useContext as Mc,useCallback as Nc,useEffect as es,useId as Oc,useLayoutEffect as ts,useRef as ns,useState as os}from"react";import{createPortal as Lc}from"react-dom";import{jsx as $n,jsxs as is,Fragment as rs}from"react/jsx-runtime";var xa=Ec(!1),va="uibot:collection-popover-open";function wa({label:e,trigger:t,defaultOpen:n=!1,disabled:o,menu:i,children:r}){let[s,a]=os(n),[l,c]=os({left:8,top:8}),d=ns(null),g=ns(null),f=Oc();es(()=>{let b=(v)=>{let y=v.detail,C=d.current;if(!y||!C||y===C)return;let p=C.closest("[data-uibot-workspace]")??C.parentElement,k=y.closest("[data-uibot-workspace]")??y.parentElement;if(p===k)a(!1)};return document.addEventListener(va,b),()=>document.removeEventListener(va,b)},[]);let u=()=>{a(!1),d.current?.focus({preventScroll:!0})},x=Nc(()=>{if(!s)return;let b=d.current?.getBoundingClientRect(),v=g.current?.getBoundingClientRect();if(b&&v){let y={left:Math.max(8,Math.min(b.left,window.innerWidth-v.width-8)),top:Math.max(8,b.bottom+v.height+8<=window.innerHeight?b.bottom+4:b.top-v.height-4)};c((C)=>C.left===y.left&&C.top===y.top?C:y)}},[s]);return ts(x),ts(()=>{if(!s)return;if(d.current)document.dispatchEvent(new CustomEvent(va,{detail:d.current}));(g.current?.querySelector("button:not(:disabled), input, select, textarea")??g.current)?.focus({preventScroll:!0})},[s]),es(()=>{if(!s)return;let b=(y)=>{if(y.target instanceof Node&&!g.current?.contains(y.target)&&!d.current?.contains(y.target))a(!1)},v=(y)=>{if(y.key!=="Escape")return;y.preventDefault(),y.stopPropagation(),a(!1),d.current?.focus({preventScroll:!0})};return window.addEventListener("resize",x),window.addEventListener("scroll",x,!0),document.addEventListener("pointerdown",b),document.addEventListener("keydown",v),()=>{window.removeEventListener("resize",x),window.removeEventListener("scroll",x,!0),document.removeEventListener("pointerdown",b),document.removeEventListener("keydown",v)}},[s,x]),is(rs,{children:[$n("button",{ref:d,type:"button","aria-label":e,"aria-haspopup":i?"menu":"dialog","aria-expanded":s,"aria-controls":s?f: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:(b)=>b.stopPropagation(),onClick:()=>s?u():a(!0),children:t}),s&&Lc($n("div",{ref:g,id:f,role:i?"menu":"dialog","aria-label":e,tabIndex:-1,style:{position:"fixed",...l,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:(b)=>{if(!i||!["ArrowDown","ArrowUp","Home","End"].includes(b.key))return;b.preventDefault();let v=[...b.currentTarget.querySelectorAll('button[role="menuitem"]:not(:disabled)')],y=v.indexOf(document.activeElement),C=b.key==="Home"?0:b.key==="End"?v.length-1:(y+(b.key==="ArrowUp"?-1:1)+v.length)%v.length;v[C]?.focus()},children:r(u)}),document.body)]})}function Fn({ui:e,label:t,defaultOpen:n,icon:o,chevron:i,quiet:r,active:s,children:a}){let l=Mc(xa),c=(d)=>$n("div",{style:{fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},children:$n("fieldset",{disabled:l,style:{border:0,padding:0,margin:0,minWidth:0},children:d})});if(e?.Popover)return e.Popover({label:t,defaultOpen:n,...o?{icon:$n(xe,{name:o})}:{},...i?{iconEnd:$n(xe,{name:"chevronDown",size:13})}:{},...r?{quiet:r}:{},active:s,children:typeof a==="function"?(d)=>c(a(d)):c(a)});return $n(wa,{label:t,defaultOpen:n,trigger:is(rs,{children:[o?$n(xe,{name:o}):null,t,i?$n(xe,{name:"chevronDown",size:13}):null]}),children:(d)=>c(typeof a==="function"?a(d):a)})}import{jsx as bi,jsxs as ss,Fragment as Uc}from"react/jsx-runtime";function hi({items:e,label:t,children:n,block:o=!1}){let[i,r]=ls(null),s=Pa(null),a=Pa(null),[l,c]=ls({x:0,y:0}),d=Vc(()=>{if(!i||!a.current)return;let f=Math.max(12,Math.min(i.x,window.innerWidth-12-a.current.offsetWidth)),u=Math.max(12,Math.min(i.y,window.innerHeight-12-a.current.offsetHeight));c((x)=>x.x===f&&x.y===u?x:{x:f,y:u})},[i]);Bc(d),as(()=>{if(!i)return;return window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[i,d]);let g=Pa(null);return as(()=>{if(!i)return;g.current=document.activeElement instanceof HTMLElement?document.activeElement:null,a.current?.querySelector("button:not(:disabled)")?.focus();let f=()=>r(null),u=(x)=>{if(x.key==="Escape")x.preventDefault(),x.stopPropagation(),r(null),g.current?.focus({preventScroll:!0})};return window.addEventListener("keydown",u),window.addEventListener("pointerdown",f),window.addEventListener("blur",f),()=>{window.removeEventListener("keydown",u),window.removeEventListener("pointerdown",f),window.removeEventListener("blur",f)}},[i]),ss("span",{ref:s,style:{display:o?"block":"inline-flex"},onKeyDown:(f)=>{if(f.shiftKey&&f.key==="F10"||f.key==="ContextMenu"){f.preventDefault(),f.stopPropagation();let u=f.target.getBoundingClientRect();r({x:Math.max(8,Math.min(u.left,window.innerWidth-240)),y:Math.max(8,Math.min(u.bottom,window.innerHeight-280))})}},onContextMenu:(f)=>{f.preventDefault(),f.stopPropagation(),r({x:Math.max(8,Math.min(f.clientX,window.innerWidth-240)),y:Math.max(8,Math.min(f.clientY,window.innerHeight-280))})},children:[n,i&&bi("div",{ref:a,role:"menu","aria-label":t,style:{position:"fixed",left:l.x,top:l.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:(f)=>f.stopPropagation(),onKeyDown:(f)=>{if(!["ArrowDown","ArrowUp"].includes(f.key))return;f.preventDefault();let u=[...f.currentTarget.querySelectorAll("button:not(:disabled)")],x=u.indexOf(document.activeElement);u[(x+(f.key==="ArrowUp"?-1:1)+u.length)%u.length]?.focus()},children:e.map((f)=>bi("button",{type:"button",role:"menuitem",disabled:f.disabled,style:{display:"block",width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderRadius:6,background:"transparent",color:f.destructive?"var(--destructive, #b3261e)":"inherit",cursor:f.disabled?"default":"pointer",opacity:f.disabled?0.5:1},onClick:()=>{r(null),f.onSelect()},children:f.label},f.id))})]})}function Ci({label:e,items:t,disabled:n,icon:o}){return bi(wa,{label:e,disabled:n,menu:!0,trigger:o??"+",children:(i)=>bi(Uc,{children:t.map((r)=>ss("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))})})}import{jsx as Jt,jsxs as us}from"react/jsx-runtime";function _c(e,t,n,o){if(t===n)return[...e];let i=e.filter((s)=>s!==t),r=i.indexOf(n);if(r<0||!e.includes(t))return[...e];return i.splice(o?r+1:r,0,t),i}var qc=["grid","kanban","gallery","calendar","form"];function zc(e,t){return{grid:e("Grid"),kanban:e("Kanban"),gallery:e("Gallery"),calendar:e("Calendar"),form:e("Form")}[t]}function $c({slot:e,items:t,label:n,children:o}){if(!t.length)return Jt("span",{children:o});if(e)return Jt(e,{items:t,"aria-label":n,children:o});return Jt(hi,{items:t,label:n,children:o})}function Sa(e){let t=le(e.locale),[n,o]=ka(null),[i,r]=ka(""),[s,a]=ka(null),l=cs(null),c=cs(null),d=Boolean(e.onReorder)&&!e.disabled&&e.views.length>1,g=e.views.map((P)=>P.id),f=(P,M,B)=>{let R=_c(g,P,M,B);if(R.join("\x00")!==g.join("\x00"))e.onReorder?.(R)};ds(()=>{let P=l.current;if(!P)return;l.current=null,document.querySelector(`[data-view-tab="${CSS.escape(P)}"]`)?.focus()}),ds(()=>{if(n)c.current?.select()},[n]);let u=Boolean(e.onDelete)&&e.views.length>1,x=(P)=>{if(!e.onRename||e.disabled)return;r(P.name),o(P.id)},b=()=>{if(!n)return;let P=e.views.find((B)=>B.id===n),M=i.trim();if(o(null),P&&M&&M!==P.name)e.onRename?.(P.id,M)},v=(P)=>[...e.onRename?[{id:"rename",icon:Jt(xe,{name:"pencil"}),label:t("Rename view"),onSelect:()=>x(P)}]:[],...e.onDuplicate?[{id:"duplicate",icon:Jt(xe,{name:"copy"}),label:t("Duplicate view"),onSelect:()=>e.onDuplicate?.(P.id)}]:[],...e.onDelete?[{id:"delete",icon:Jt(xe,{name:"trash"}),label:t("Delete view"),destructive:!0,disabled:!u,onSelect:()=>e.onDelete?.(P.id)}]:[]],y=(P,M)=>{let B=e.views.findIndex((R)=>R.id===M.id);if(P.altKey&&(P.key==="ArrowRight"||P.key==="ArrowLeft")){P.preventDefault();let R=e.views[B+(P.key==="ArrowRight"?1:-1)];if(d&&R)l.current=M.id,f(M.id,R.id,P.key==="ArrowRight")}else if(P.key==="F2")P.preventDefault(),x(M);else if(P.key==="Delete"&&u&&!e.disabled)P.preventDefault(),e.onDelete?.(M.id);else if(P.key==="ArrowRight"||P.key==="ArrowLeft"){P.preventDefault();let R=e.views[B+(P.key==="ArrowRight"?1:-1)];if(R)e.onSelect(R.id),P.currentTarget.parentElement?.parentElement?.querySelectorAll('[role="tab"]')?.[B+(P.key==="ArrowRight"?1:-1)]?.focus()}},C=(e.viewTypes??qc).map((P)=>({id:P,label:zc(t,P),disabled:e.disabledViewTypes?.includes(P)??!1,onSelect:()=>e.onAdd?.(P)})),p=e.ui?.ContextMenu,k=e.ui?.DropdownMenu;return us("div",{"data-uibot":"collection-view-tabs",style:{display:"flex",alignItems:"flex-end",gap:2,minWidth:0,maxWidth:"100%",overflowX:"auto"},children:[Jt("div",{role:"tablist","aria-label":t("Views"),style:{display:"flex",gap:2},children:e.views.map((P)=>{let M=P.id===e.activeId,B=v(P),R=n===P.id?Jt("input",{ref:c,"aria-label":t("View name"),value:i,maxLength:80,style:{height:30,padding:"0 8px",font:"inherit",border:"1px solid var(--primary, #1a56c4)",borderRadius:6,background:"var(--background, white)",color:"inherit"},onChange:(A)=>r(A.target.value),onBlur:b,onKeyDown:(A)=>{if(A.stopPropagation(),A.key==="Enter")A.preventDefault(),b();else if(A.key==="Escape")A.preventDefault(),o(null)}}):us("button",{type:"button",role:"tab","aria-selected":M,tabIndex:M?0:-1,disabled:e.disabled,title:e.onRename?t("Double click to rename"):void 0,"data-view-tab":P.id,draggable:d,onDragStart:(A)=>{if(!d)return;A.dataTransfer.effectAllowed="move",A.dataTransfer.setData("text/plain",P.id),a({id:P.id})},onDragOver:(A)=>{if(!s||s.id===P.id)return;A.preventDefault();let _=A.currentTarget.getBoundingClientRect(),L=(A.clientX||0)>_.left+_.width/2;if(s.over!==P.id||s.after!==L)a({id:s.id,over:P.id,after:L})},onDrop:(A)=>{if(!s)return;A.preventDefault(),f(s.id,P.id,Boolean(s.after)),a(null)},onDragEnd:()=>a(null),style:{boxShadow:s?.over===P.id?s.after?"inset -2px 0 0 var(--primary, #1a56c4)":"inset 2px 0 0 var(--primary, #1a56c4)":void 0,opacity:s?.id===P.id?0.5:1,position:"relative",display:"inline-flex",alignItems:"center",gap:6,height:34,padding:"0 12px",border:0,borderBottom:M?"2px solid var(--primary, #1a56c4)":"2px solid transparent",background:"transparent",color:M?"var(--primary, #1a56c4)":"inherit",fontWeight:M?600:400,fontSize:13,whiteSpace:"nowrap",cursor:"pointer"},onClick:()=>e.onSelect(P.id),onDoubleClick:()=>x(P),onKeyDown:(A)=>y(A,P),children:[Jt("span",{children:P.name}),e.dirty&&M&&Jt("span",{role:"img","aria-label":t("Unsaved changes"),style:{width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}})]});return Jt($c,{slot:p,items:n===P.id?[]:B,label:t("View actions"),children:R},P.id)})}),e.onAdd&&(k?Jt(k,{label:t("Add view"),items:C,disabled:e.disabled}):Jt(Ci,{label:t("Add view"),items:C,disabled:e.disabled}))]})}import{useRef as Hc,useState as Kc}from"react";import{jsx as yt,jsxs as tr}from"react/jsx-runtime";function Ra(e){let t=le(e.locale),n=e.descriptor.fields.find((l)=>l.id===e.view.groupByFieldId),o=ri(e),i=Hc(null),[r,s]=Kc(null);if(!n||!["singleSelect","checkbox"].includes(n.type))return yt("p",{role:"status",children:t("Choose a single-select or boolean grouping field.")});let a=fl(n,t);return tr("section",{"data-uibot":"collection-kanban",children:[yt(Go,{...e}),yt("div",{style:{display:"flex",gap:12,overflowX:"auto",alignItems:"flex-start",paddingBottom:12},children:a.map((l)=>yt(jc,{...e,field:n,lane:l,lanes:a,blocked:o.blocked,onOpen:s,onMove:(c,d)=>void o.move(c,{[n.id]:d.value}),onDrag:(c)=>{i.current=c},onDrop:(c)=>{if(i.current?.id===c)o.move(i.current,{[n.id]:l.value});i.current=null}},l.id))}),yt(ii,{state:o,locale:e.locale,ui:e.ui}),r&&yt(qn,{...e,row:r,onClose:()=>s(null)},r.id)]})}function jc({field:e,lane:t,lanes:n,blocked:o,onOpen:i,onMove:r,onDrag:s,onDrop:a,...l}){let c=le(l.locale),d=vt(l.features),g=d.optionChips,f=!l.readOnly&&d.rowUpdate,u=Yo(l,bl(l.view,e,t)),x=l.descriptor.fields.find((y)=>y.type==="singleLineText"||y.type==="longText")?.id,b=Po(l.descriptor.fields,l.view).filter((y)=>y.id!==e.id&&y.id!==x).slice(0,3),v=f&&!o&&!(e.required&&t.value===null);return tr("section",{"aria-label":c("Lane {name}",{name:t.name}),"data-lane-id":t.id,style:{...nn,flex:"0 0 290px",minWidth:0,...g?{background:"var(--muted, #f4f6f8)",padding:10}:{}},onDragOver:(y)=>{if(v)y.preventDefault()},onDrop:(y)=>{if(!v)return;y.preventDefault(),a(y.dataTransfer.getData("application/x-uibot-record"))},children:[tr("h3",{style:g?{display:"flex",alignItems:"center",gap:6,margin:"0 0 6px",fontSize:13}:void 0,children:[g&&yt("span",{"aria-hidden":"true",style:{width:8,height:8,borderRadius:999,...t.id.startsWith("option:")?{background:yn(Gc(n,t)).color}:{background:"var(--muted-foreground, #9a9892)"}}}),t.name," · ",vr(c,u.page.total,u.page.items.length,l.locale)]}),yt(Jo,{state:u,locale:l.locale,ui:l.ui,hideCount:!0}),tr("div",{style:{display:"flex",flexDirection:"column",gap:8,marginTop:12,maxHeight:"65vh",overflowY:"auto"},children:[u.page.items.map((y)=>{let C=Bt(y,l.descriptor.fields);return tr("article",{"data-record-id":y.id,style:g?{...nn,padding:10,boxShadow:"0 1px 2px rgb(0 0 0 / 0.06)",cursor:"grab",position:"relative"}:nn,draggable:f&&!o&&!u.loading,onDragStart:(p)=>{s(y),p.dataTransfer.setData("application/x-uibot-record",y.id),p.dataTransfer.effectAllowed="move"},onDragEnd:()=>s(null),children:[yt("button",{type:"button",style:{...Le,width:"100%",textAlign:"left",overflowWrap:"anywhere",...g?{border:0,padding:"0 28px 0 0",background:"transparent",fontWeight:600}:{}},"aria-label":c("Open {name}",{name:C}),onClick:()=>i(y),children:C}),g&&yt(Wc,{row:y,fields:b}),f&&(l.ui?.DropdownMenu?yt("span",{style:{position:"absolute",top:4,right:4},children:l.ui.DropdownMenu({label:c("Move {name}",{name:C}),icon:yt(xe,{name:"more"}),disabled:o||u.loading,items:n.map((p)=>({id:p.id,label:c("Move to {name}",{name:p.name}),disabled:p.id===t.id||!!e.required&&p.value===null,onSelect:()=>r(y,p)}))})}):tr("div",{style:{display:"flex",flexDirection:"column",gap:4,marginTop:8},children:[yt("span",{children:c("Move to")}),yt(Ge,{ui:l.ui,label:c("Move {name}",{name:C}),style:Le,disabled:o||u.loading,value:t.id,onChange:(p)=>{let k=n.find((P)=>P.id===p);if(k&&k.id!==t.id)r(y,k)},options:n.map((p)=>({value:p.id,label:p.name,disabled:!!e.required&&p.value===null}))})]}))]},y.id)}),!u.loading&&!u.error&&!u.page.items.length&&yt("p",{children:c("No records in this lane.")})]})]})}function Wc({row:e,fields:t}){let n=t.map((o)=>{let i=e.values[o.id],r=o.type==="singleSelect"||o.type==="multipleSelect",s=Array.isArray(i)?i:i==null?[]:[i],a=o.type==="linkedRecord"?wo(e,o):Sn(i,o,e.computedErrors?.[o.id]);return{field:o,chips:r,ids:s,text:a}}).filter((o)=>o.chips?o.ids.length>0:o.text!=="");if(!n.length)return null;return yt("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:6,alignItems:"center",fontSize:12,opacity:0.85},children:n.map((o)=>o.chips?yt(Eo,{ids:o.ids,field:o.field},o.field.id):yt("span",{style:{fontVariantNumeric:"tabular-nums"},children:o.text},o.field.id))})}function Gc(e,t){return e.filter((n)=>n.id.startsWith("option:")).findIndex((n)=>n.id===t.id)}import{useState as Yc}from"react";import{jsx as Tn,jsxs as Ia}from"react/jsx-runtime";function Aa(e){let t=le(e.locale),n=vt(e.features).optionChips,o=Yo(e,Gr(e.view)),[i,r]=Yc(null),s=e.descriptor.fields.find((l)=>l.type==="singleLineText"||l.type==="longText")?.id,a=Po(e.descriptor.fields,e.view).filter((l)=>!n||l.id!==s);return Ia("section",{"data-uibot":"collection-gallery",children:[Tn(Go,{...e}),Tn(Jo,{state:o,locale:e.locale,ui:e.ui}),Tn("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 240px), 1fr))",gap:12,marginTop:12},children:o.page.items.map((l)=>Ia("article",{"data-record-id":l.id,style:{...nn,minWidth:0,...n?{boxShadow:"0 1px 2px rgb(0 0 0 / 0.05)"}:{}},children:[Tn("button",{type:"button","aria-label":t("Open {name}",{name:Bt(l,e.descriptor.fields)}),style:{...Le,width:"100%",textAlign:"left",overflowWrap:"anywhere",...n?{border:0,padding:0,background:"transparent",fontWeight:600,fontSize:"var(--uibot-workspace-font-size, 13px)"}:{}},onClick:()=>r(l),children:Bt(l,e.descriptor.fields)}),Tn("dl",{children:a.filter((c)=>!n||!Jc(l,c)).slice(0,n?5:a.length).map((c)=>Ia("div",{children:[Tn("dt",{style:{fontSize:12,opacity:0.7},children:c.name}),Tn("dd",{style:{margin:"0 0 8px",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n&&(c.type==="singleSelect"||c.type==="multipleSelect")&&l.values[c.id]!=null?Tn(Eo,{ids:Array.isArray(l.values[c.id])?l.values[c.id]:[l.values[c.id]],field:c}):(c.type==="linkedRecord"?wo(l,c):Sn(l.values[c.id],c,l.computedErrors?.[c.id]))||"—"})]},c.id))})]},l.id))}),!o.loading&&!o.error&&!o.page.items.length&&Tn("p",{children:t("No records match this view.")}),i&&Tn(qn,{...e,row:i,onClose:()=>r(null)},i.id)]})}function Jc(e,t){let n=e.values[t.id];if(t.type==="linkedRecord")return!wo(e,t);return n==null||n===""||Array.isArray(n)&&n.length===0}import{useRef as Qc,useState as Da}from"react";import{jsx as nt,jsxs as so}from"react/jsx-runtime";function Fa(e){let t=le(e.locale),n=vt(e.features),o=n.optionChips,i=!e.readOnly&&n.rowUpdate,[r,s]=Da(()=>{let p=new Date().toISOString().slice(0,7),k=e.initialMonth??p;try{return fr(k),{month:k,error:""}}catch{return{month:p,error:t("Invalid initial month. Showing the current UTC month.")}}}),{month:a,error:l}=r,[c,d]=Da(null),g=e.descriptor.fields.find((p)=>p.id===e.view.dateFieldId&&p.type==="date"),f=Qc(null),u=ri(e),x=Yo(e,g?hl(e.view,g.id,a):{limit:1},!!g),b=fr(a),v=(p)=>{try{fr(p),s({month:p,error:""})}catch{s((k)=>({...k,error:t("Choose a valid month between years 1 and 9998.")}))}},y=(p)=>{let k=new Date(b.start);k.setUTCMonth(k.getUTCMonth()+p),v(k.toISOString().slice(0,7))},C=(p,k)=>{if(!g)return;try{u.move(p,{[g.id]:Yr(p.values[g.id],k)})}catch(P){u.mutation.setError(P instanceof Error?P.message:t("Invalid date"))}};if(!g)return nt("p",{role:"status",children:t("Choose a date field for this calendar.")});return so("section",{"data-uibot":"collection-calendar",children:[nt(Go,{...e}),so("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginBottom:12},children:[nt(G,{ui:e.ui,style:Le,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:t("Previous month"),onClick:()=>y(-1)}),e.ui?.MonthPicker?nt(e.ui.MonthPicker,{value:a,onChange:v,"aria-label":t("Calendar month")}):e.ui?.Button?nt("strong",{role:"status","aria-label":t("Calendar month"),style:{minWidth:96,textAlign:"center",fontVariantNumeric:"tabular-nums"},children:t("{year}-{month}",{year:a.slice(0,4),month:a.slice(5,7)})}):so("label",{children:[t("Month")," ",nt("input",{type:"month","aria-label":t("Calendar month"),min:"0001-01",max:"9998-12",value:a,onChange:(p)=>v(p.target.value),style:Le})]}),nt(G,{ui:e.ui,style:Le,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:t("Next month"),onClick:()=>y(1)}),nt(G,{ui:e.ui,style:Le,variant:"outline",size:"sm",onClick:()=>v(new Date().toISOString().slice(0,7)),children:t("Today")})]}),l&&nt("p",{role:"alert",children:l}),nt(Jo,{state:x,locale:e.locale,ui:e.ui}),nt("div",{style:{overflowX:"auto",minWidth:0},children:so("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, minmax(0, 1fr))"},children:[[t("Sun"),t("Mon"),t("Tue"),t("Wed"),t("Thu"),t("Fri"),t("Sat")].map((p)=>nt("strong",{style:o?{padding:"8px 10px",fontSize:12,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"}:{padding:8},children:p},p)),["sun","mon","tue","wed","thu","fri","sat"].slice(0,b.weekday).map((p)=>nt("div",{"aria-hidden":"true",style:o?{borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",background:"var(--muted, #f4f6f8)",opacity:0.5}:void 0},p)),Array.from({length:b.days},(p,k)=>{let P=`${a}-${String(k+1).padStart(2,"0")}`,M=x.page.items.filter((B)=>String(B.values[g.id]??"").slice(0,10)===P);return so("article",{"aria-label":t("Day {day}",{day:P}),"data-calendar-day":P,style:{...nn,minHeight:130,maxHeight:280,overflowY:"auto",minWidth:0,borderRadius:0,...o?{padding:8,border:0,borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",fontSize:12}:{}},onDragOver:(B)=>{if(i&&!u.blocked)B.preventDefault()},onDrop:(B)=>{if(!i||u.blocked)return;if(B.preventDefault(),f.current?.id===B.dataTransfer.getData("application/x-uibot-record"))C(f.current,P);f.current=null},children:[nt("time",{dateTime:P,children:k+1}),M.map((B)=>so("article",{"data-record-id":B.id,style:{marginTop:8},draggable:i&&!u.blocked&&!x.loading,onDragStart:(R)=>{f.current=B,R.dataTransfer.setData("application/x-uibot-record",B.id),R.dataTransfer.effectAllowed="move"},onDragEnd:()=>{f.current=null},children:[so("button",{type:"button",style:{...Le,textAlign:"left",width:"100%",overflowWrap:"anywhere",...o?{border:0,padding:"3px 8px",fontSize:12,fontWeight:500,...yn(0)}:{}},"aria-label":t("Open {name}",{name:Bt(B,e.descriptor.fields)}),onClick:()=>d(B),children:[Bt(B,e.descriptor.fields)," ",nt("small",{children:String(B.values[g.id]).slice(11,16)})]}),i&&nt(Zc,{ui:e.ui,t,row:B,fieldId:g.id,title:Bt(B,e.descriptor.fields),disabled:u.blocked||x.loading,onMove:C})]},B.id))]},P)})]})}),!x.loading&&!x.error&&!x.page.items.length&&nt("p",{children:t("No dated records match this month.")}),nt(ii,{state:u,locale:e.locale,ui:e.ui}),!u.intent&&u.mutation.error&&nt("p",{role:"alert",children:u.mutation.error}),c&&nt(qn,{...e,row:c,onClose:()=>d(null)},c.id)]})}function Zc({ui:e,t,row:n,fieldId:o,title:i,disabled:r,onMove:s}){let[a,l]=Da({day:String(n.values[o]).slice(0,10)}),c=e?.DateMove;if(c)return nt(c,{label:t("Move {name} to date",{name:i}),value:a.day,disabled:r,onPick:(d)=>s(a.baseline??n,d)});return so("div",{style:{marginTop:4,display:"flex",gap:4,flexWrap:"wrap"},children:[nt("input",{type:"date","aria-label":t("Move {name} to date",{name:i}),value:a.day,disabled:r,style:{width:"100%",minWidth:0},onChange:(d)=>l({day:d.target.value,baseline:a.baseline??n})}),nt("button",{type:"button",style:Le,"aria-label":t("Move {name}",{name:i}),disabled:r||!a.day,onClick:()=>s(a.baseline??n,a.day),children:t("Move")})]})}import{jsx as Hn,jsxs as nr}from"react/jsx-runtime";function Ta({fields:e,view:t,onChange:n,locale:o,ui:i,features:r,sections:s,filterEditor:a,grouping:l,rowHeight:c}){let d=le(o),g=vt(r),f=e.filter((C)=>C.type==="singleSelect"||C.type==="checkbox"),u=e.filter((C)=>C.type==="date"),x=(C)=>{let p={...t,type:C};if(delete p.groupByFieldId,delete p.dateFieldId,C==="kanban"&&f[0])p.groupByFieldId=f[0].id;if(C==="calendar"&&u[0])p.dateFieldId=u[0].id;if(C==="form")p.hiddenColumns=p.hiddenColumns.filter((k)=>!e.find((P)=>P.id===k)?.required);n(p)},b={grid:d("Grid"),kanban:d("Kanban"),gallery:d("Gallery"),calendar:d("Calendar"),form:d("Form")},v=g.viewTypes.map((C)=>({value:C,label:b[C],disabled:C==="kanban"&&!f.length||C==="calendar"&&!u.length})),y=t.type??"grid";return nr("div",{style:{display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},children:[nr("div",{children:[d("View type")," ",Hn(Ge,{ui:i,label:d("View type"),style:Le,value:y,options:v,onChange:(C)=>x(C)})]}),y==="grid"&&g.groupBy&&f.length>0&&l!==!1&&Hn("div",{style:{flexBasis:"100%"},children:Hn(pi,{fields:e,view:t,onChange:n,locale:o,ui:i})}),y==="grid"&&c!==!1&&nr("div",{children:[d("Row height")," ",Hn(Ge,{ui:i,label:d("Row height"),style:Le,value:t.rowHeight??"short",options:Br.map((C)=>({value:C,label:d(`Row height ${C}`)})),onChange:(C)=>{let p={...t};if(C==="short")delete p.rowHeight;else p.rowHeight=C;n(p)}})]}),y==="kanban"&&nr("div",{children:[d("Group by")," ",Hn(Ge,{ui:i,label:d("Kanban grouping field"),style:Le,value:t.groupByFieldId??"",options:f.map((C)=>({value:C.id,label:C.name})),onChange:(C)=>n({...t,groupByFieldId:C})})]}),y==="calendar"&&nr("div",{children:[d("Date field")," ",Hn(Ge,{ui:i,label:d("Calendar date field"),style:Le,value:t.dateFieldId??"",options:u.map((C)=>({value:C.id,label:C.name})),onChange:(C)=>n({...t,dateFieldId:C})})]}),(s?.filter||s?.columns||s?.sort)&&nr("div",{style:{display:"grid",gap:12,flexBasis:"100%"},children:[s?.filter&&Hn(ui,{fields:e,view:t,onChange:n,locale:o,ui:i,editor:a}),s?.columns&&Hn(Kl,{fields:e,view:t,onChange:n,locale:o,ui:i}),s?.sort&&Hn(gi,{fields:e,view:t,onChange:n,locale:o,ui:i})]})]})}function gs(e,t){if(!t)return e;let n=async(o,i)=>{let r=await e.mutate(o,i);if(r.ok||r.error.code!=="approval_required")return r;let s=await t(r.error.details??{approvalRequestId:""},i);return s?e.mutate(o,{...i,approvalReceiptId:s}):r};return new Proxy(e,{get(o,i){if(i==="mutate")return n;let r=Reflect.get(o,i,o);return typeof r==="function"?r.bind(o):r}})}var ps=(e)=>e.type==="singleLineText"||e.type==="longText",ms=(e)=>{let n=e.name.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9一-鿿]+/g,"_");return/(?:^|_)(?:id|uuid)$/.test(n)||n==="recordid"},fs=(e)=>{let t=e.toLowerCase().replace(/[\s_-]+/g,"");if(/^(name|名称|姓名|客户名称|公司名称|标题|title|label|displayname)$/.test(t))return 0;if(/(名称|姓名|标题|name|title|label)/.test(t))return 1;return 2};function Xc(e,t){let n=e?.fields??[],o=n.find((r)=>r.id===t),i=n.filter((r)=>ps(r)&&!ms(r)).sort((r,s)=>fs(r.name)-fs(s.name));return[...o&&ps(o)&&!ms(o)?[o]:[],...i].filter((r,s,a)=>a.findIndex((l)=>l.id===r.id)===s)}function eu(e){if(!e?.length)return;let t=[...new Set(e.filter((n)=>n!==""))].slice(0,50);return t.length?t:void 0}function ys(e,t){return async(n)=>{let o=eu(n.ids),i=await e.query(n.collectionId,{...o?{ids:o}:n.search?{search:n.search}:{},...!o&&n.cursor?{cursor:n.cursor}:{},limit:Math.min(50,n.limit)});if(!i.ok)return i;let r=Xc((typeof t==="function"?t():t).find((s)=>s.id===n.collectionId),n.labelFieldId);return{ok:!0,data:{items:i.data.items.map((s)=>{let a=r.map((l)=>s.values[l.id]).find((l)=>l!==null&&l!==void 0&&String(l).trim()!=="");return{id:s.id,label:a===void 0?s.id:String(a)}}),nextCursor:i.data.nextCursor}}}}import{useEffect as Cn,useLayoutEffect as ru,useMemo as bn,useRef as hn,useState as pt}from"react";import{DndContext as iu,PointerSensor as au,useDraggable as lu,useSensor as su,useSensors as du}from"@dnd-kit/core";import{defaultRangeExtractor as cu,useVirtualizer as ks}from"@tanstack/react-virtual";function bs(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 Ea(e,t){let n=new Set(e);if(n.has(t))n.delete(t);else n.add(t);return n}function vi(e){let t=Pn.findIndex((o)=>o===e);if(t<0)return;let n=yn(t);return{background:`color-mix(in srgb, ${n.background} 55%, var(--background, white))`,marker:String(n.color)}}var hs=(e,t)=>(e%t+t)%t;function Cs(e,t,n,o){let i=[],r=0,s=0,a=e.lastRow-e.firstRow+1,l=e.lastColumn-e.firstColumn+1;if(a<1||l<1||t.lastRow-t.firstRow+1>100)return{mutations:i,skipped:r,count:s,limitExceeded:!0};for(let c=t.firstRow;c<=t.lastRow;c++){let d=n[c];if(!d)continue;let g={};for(let f=t.firstColumn;f<=t.lastColumn;f++){if(c>=e.firstRow&&c<=e.lastRow&&f>=e.firstColumn&&f<=e.lastColumn)continue;let u=o[f];if(!u)continue;if(tt(u)||u.generation==="autoIncrement"||["blob","linkedRecord","relation"].includes(u.type)){r++;continue}let x=e.firstColumn+hs(f-e.firstColumn,l),b=o[x];if(!b||b.type!==u.type){r++;continue}let v=n[e.firstRow+hs(c-e.firstRow,a)]?.values[b.id]??null;if(l===1&&a>=2&&(u.type==="number"||u.type==="date")&&f===e.firstColumn){let y=n.slice(e.firstRow,e.lastRow+1).map((P)=>P.values[b.id]),C=y.map((P)=>u.type==="date"?typeof P==="string"&&P!==""?Date.parse(P)/86400000:Number.NaN:typeof P==="number"?P:Number.NaN),p=C[0]??Number.NaN,k=(C[1]??Number.NaN)-p;if(C.every((P,M)=>Number.isFinite(P)&&Math.abs(P-(p+k*M))<0.00000001)){let P=p+k*(c-e.firstRow);if(Number.isFinite(P))v=u.type==="date"?String(y[0]).length===10?new Date(P*86400000).toISOString().slice(0,10):new Date(P*86400000).toISOString():P}}g[u.id]=structuredClone(v),s++}if(Object.keys(g).length)i.push({op:"update",id:d.id,expectedVersion:d.version,values:g})}return{mutations:i,skipped:r,count:s,limitExceeded:!1}}import{useEffect as tu,useMemo as nu,useState as ou}from"react";function vs(e,t,n,o,i,r){let s=nu(()=>{let c=n.flatMap((d,g)=>{let f=t.footerStats?.[d.id];return f&&f!=="none"&&f!=="count"?[{fn:f,fieldId:d.id,as:`footer${g}`}]:[]});return JSON.stringify([e,Ur(t,{aggregates:c}),o.map((d)=>[d.id,d.version]),r])},[e,n,t,o,r]),[a,l]=ou({key:"",status:"ready",values:{}});return tu(()=>{if(!i)return;let c=!0,[d,g]=JSON.parse(s);return(async()=>{let f={};for(let u=0;u<g.aggregates.length;u+=8){let x={...g,aggregates:g.aggregates.slice(u,u+8)};if(_r(d,x))throw Error("Invalid summary");let b=await i.aggregate(d.id,x);if(!c)return;if(!b.ok||b.data.length!==1)throw Error("Summary unavailable");for(let v of x.aggregates){let y=b.data[0]?.values[v.as],C=d.fields.find((k)=>k.id===v.fieldId),p=C?.type==="date"||C?.resultType==="date";if(y!==null&&!(typeof y==="number"&&Number.isFinite(y))&&!(p&&(v.fn==="min"||v.fn==="max")&&typeof y==="string"&&Number.isFinite(Date.parse(y))))throw Error("Invalid summary result");f[v.as]=y}}if(c)l({key:s,client:i,status:"ready",values:f})})().catch(()=>{if(c)l({key:s,client:i,status:"error",values:{}})}),()=>{c=!1}},[i,s]),{status:!i?"local":a.key!==s||a.client!==i?"loading":a.status,values:a.key===s&&a.client===i?a.values:{}}}function ws(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 xs=(e)=>e!==null&&e!==void 0&&e!==""&&!(Array.isArray(e)&&e.length===0)&&e!==!1;function Ps(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(xs).length;if(n==="empty")return o.filter((r)=>!xs(r)).length;if(t.type==="date"){let r=o.filter((s)=>typeof s==="string"&&s!=="").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,s)=>r+s,0);if(n==="avg")return i.reduce((r,s)=>r+s,0)/i.length;if(n==="min")return Math.min(...i);return Math.max(...i)}import{jsx as Q,jsxs as ot}from"react/jsx-runtime";function uu(e,t){let n=e.find((o)=>o.fieldId===t);if(n?.direction==="desc")return[];return[{fieldId:t,direction:n?"desc":"asc"}]}var Kn={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},gu={padding:5,width:"100%",border:"1px solid #6688bb",background:"var(--background, white)",color:"inherit"};function Ss(e){let{descriptor:t,view:n}=e,o=le(e.locale),i=bn(()=>vt(e.features),[e.features]),r=!e.readOnly&&i.rowDelete,s=!e.readOnly&&i.rowCreate,a=!e.readOnly&&i.rowUpdate,[l,c]=pt({}),d=hn(new Set),[g,f]=pt(()=>new Set),u=hn(new Set);Cn(()=>{if(!d.current.size)return;let m=d.current;d.current=new Set,c((I)=>Object.fromEntries(Object.entries(I).filter(([E])=>!m.has(E))))},[e.rows]);let x=bn(()=>Object.keys(l).length?e.rows.map((m)=>l[m.id]?{...m,values:{...m.values,...l[m.id]}}:m):e.rows,[e.rows,l]),b=bn(()=>[...n.columnOrder,...t.fields.map((I)=>I.id).filter((I)=>!n.columnOrder.includes(I))].filter((I)=>!n.hiddenColumns.includes(I)).flatMap((I)=>{let E=t.fields.find((ne)=>ne.id===I);return E?[E]:[]}),[t.fields,n.columnOrder,n.hiddenColumns]),v=bn(()=>JSON.stringify([x.map((m)=>m.id),b.map((m)=>m.id)]),[x,b]),[y,C]=pt(v),p=hn(null),[k,P]=pt({row:0,column:0}),[M,B]=pt(!1),[R,A]=pt(()=>new Set),[_,L]=pt(()=>new Set),w=JSON.stringify([t.id,n.filter,n.search,n.sort,e.rowOffset]);Cn(()=>{A(new Set),L(new Set)},[e.rows,w]);let[N,O]=pt({row:0,column:0}),[D,J]=pt(null),T=hn(!1),j=hn(!1),[H,me]=pt(null),[Z,fe]=pt(!1),[X,K]=pt(!1);wn({dirty:Boolean(H||Z||D&&D.text!==D.originalText),busy:X||g.size>0},e);let[ee,ae]=pt(""),[he,Ce]=pt(null),re=hn(null),Se=D?.field.type==="linkedRecord"?JSON.stringify([D.rowId,D.field.id]):null;Cn(()=>{if(Se)re.current?.querySelector('input[type="search"]')?.focus({preventScroll:!0})},[Se]),Cn(()=>{B(!1),P({row:0,column:0}),O({row:0,column:0}),C(v)},[v]);let pe=bn(()=>{if(!i.groupBy||(n.type??"grid")!=="grid")return;let m=t.fields.find((I)=>I.id===n.groupByFieldId);return Oi(m)?m:void 0},[i.groupBy,n.type,n.groupByFieldId,t.fields]),[qe,S]=pt(()=>new Set),F=pe?.id;Cn(()=>S(new Set),[F]);let Y=bn(()=>il(x,pe,qe),[x,pe,qe]),V=(m)=>Boolean(pe)&&Y.rowItem[m]===void 0,de=al(n.rowHeight),we=Vi(n.rowHeight),Pe=ks({count:Y.items.length,getScrollElement:()=>p.current,estimateSize:(m)=>Y.items[m]?.kind==="group"?Li:de,overscan:5,scrollMargin:38,getItemKey:(m)=>`${de}:${Y.items[m]?.key??m}`}),Ae=n.showRowNumber===!1?0:56,Qe=n.showRecordId?220:0,Ft=Ae+Qe,[Qt,co]=pt(0);Cn(()=>{let m=p.current;if(!m)return;let I=()=>co(m.clientWidth);if(I(),typeof ResizeObserver>"u")return window.addEventListener("resize",I),()=>window.removeEventListener("resize",I);let E=new ResizeObserver(I);return E.observe(m),()=>E.disconnect()},[]);let Lt=Math.min(Math.max(0,n.frozenColumnCount??0),b.length),ht=bn(()=>{let m=[Ft];for(let I of b)m.push((m.at(-1)??Ft)+Sr(n.columnWidths[I.id]??180));return m},[Ft,b,n.columnWidths]),Tt=ht[Lt]??Ft,He=Qt>0&&Qt<=768&&Tt>Qt*0.6?0:Lt,Ze=(m)=>ht[m]??Ft,uo=hn(null),Ct=Boolean(e.onAddRecord)&&s,or=du(su(au,{activationConstraint:{distance:6}})),Wn=({active:m,delta:I})=>{let E=b.findIndex((Me)=>Me.id===m.id),ne=zt.getVirtualItems().find((Me)=>Me.index===E);if(E<0||!ne)return;let W=ne.start+ne.size/2+I.x,U=zt.getVirtualItems().find((Me)=>W>=Me.start&&W<Me.start+Me.size)?.index;if(U===void 0||U===E)return;if(E<He!==U<He)return;let te=[...n.columnOrder.filter((Me)=>t.fields.some((ur)=>ur.id===Me)),...t.fields.map((Me)=>Me.id).filter((Me)=>!n.columnOrder.includes(Me))],Re=String(m.id),ce=b[U]?.id;if(!ce)return;let ve=te.filter((Me)=>Me!==Re),ue=ve.indexOf(ce)+(U>E?1:0);ve.splice(ue,0,Re),e.onViewChange({...n,columnOrder:ve})},Zt=(m,I)=>({position:"sticky",float:"left",left:m,zIndex:2,...I?{boxShadow:"2px 0 4px -2px color-mix(in srgb, currentColor 28%, transparent)"}:{}}),zt=ks({paddingStart:Ft,horizontal:!0,count:b.length,rangeExtractor:(m)=>{let I=new Set(cu(m));for(let E=0;E<He;E+=1)I.add(E);return[...I].sort((E,ne)=>E-ne)},getScrollElement:()=>p.current,estimateSize:(m)=>Sr(n.columnWidths[b[m]?.id??""]??180),overscan:2,getItemKey:(m)=>b[m]?.id??m});Cn(()=>{b.forEach((m,I)=>{zt.resizeItem(I,Sr(n.columnWidths[m.id]??180))})},[zt,n.columnWidths,b]);let je=Math.max(1,zt.getTotalSize()),No=zt.getVirtualItems(),et=zi(k,N),En=bn(()=>M&&y===v?x.slice(et.firstRow,et.lastRow+1):[],[M,y,v,x,et.firstRow,et.lastRow]),Fe=bn(()=>{let m=new Set(x.filter((I,E)=>!pe||Y.rowItem[E]!==void 0).map((I)=>I.id));return bs(En,R,x,_).filter((I)=>m.has(I.id))},[En,R,x,_,pe,Y]),rn=bn(()=>Fe.map((m)=>m.id),[Fe]),Vt=bn(()=>new Set(rn),[rn]),go=M?{first:et.firstColumn,last:et.lastColumn}:{first:0,last:b.length-1},Mn=()=>Fe.length?gl(Fe,b,{row:0,column:go.first},{row:Fe.length-1,column:go.last}):"",rr=(m)=>{if(D||X||Z||H)return;let I=x[m];if(!I)return;if(C(v),En.some((E)=>E.id===I.id))L((E)=>Ea(E,I.id));else A((E)=>Ea(E,I.id));if(!M)P({row:m,column:0}),O({row:m,column:b.length-1})},[dt,ir]=pt(null),an=hn(null),ar=!R.size&&!_.size&&M&&a&&!X&&!D&&!Z&&!H&&!qe.size,Oo=(m,I)=>{if(!ar)return;let E=Cs(m,I,x,b),ne=(U)=>{ae(U),e.onNotify?.(U)};if(E.limitExceeded){ne(o("Fill at most 100 rows at once."));return}let W=E.skipped?o("Skipped {count} cells",{count:E.skipped}):"";if(!E.mutations.length){if(W)ne(W);return}ct({idempotencyKey:crypto.randomUUID(),items:E.mutations},()=>{ne([o("Filled {count} cells",{count:E.count}),W].filter(Boolean).join("; "))})};Cn(()=>{if(!dt)return;let m=()=>{let E=an.current;if(ir(null),an.current=null,E)Oo(dt,E)},I=()=>{ir(null),an.current=null};return window.addEventListener("mouseup",m),window.addEventListener("blur",I),()=>{window.removeEventListener("mouseup",m),window.removeEventListener("blur",I)}});let Lo=JSON.stringify({recordIds:y===v?rn:[],fieldIds:Fe.length?b.slice(go.first,go.last+1).map((m)=>m.id):[]}),ln=hn(e.onSelectionChange);ln.current=e.onSelectionChange,Cn(()=>{ln.current?.(JSON.parse(Lo))},[Lo]),Cn(()=>{if(!pe||!V(N.row))return;let m=Hr(Y,N.row,-1,x.length),I=m>=0?m:Hr(Y,N.row,1,x.length);if(I>=0)O({...N,row:I}),P({...N,row:I})},[Y]);let Vo=(m)=>{let I=new Set(qe);if(I.has(m))I.delete(m);else I.add(m);S(I),B(!1),A(new Set),L(new Set),P(N)},$t=(m,I=!1)=>{if(qe.size)I=!1;if(B(!0),C(v),O(m),!I)P(m),A(new Set),L(new Set);Pe.scrollToIndex(Y.rowItem[m.row]??m.row,{align:"auto"}),zt.scrollToIndex(m.column,{align:"auto"})},po=(m=N,I)=>{if(!a||X||D||Z||H||b[m.column]?.generation==="autoIncrement")return;let E=x[m.row],ne=b[m.column];if(!E||!ne||ne.type==="blob"||tt(ne))return;if(g.has(E.id))return;B(!0),C(v),T.current=!1;let W=ne.type==="linkedRecord"?JSON.stringify(E.values[ne.id]??[]):ne.type==="relation"?ml(E,ne):ne.type==="json"&&E.values[ne.id]!=null?JSON.stringify(E.values[ne.id]):Xe(E.values[ne.id]);J({rowId:E.id,expectedVersion:E.version,field:ne,originalText:W,text:ne.type==="linkedRecord"||ne.type==="relation"?W:I??W}),ae(i.optimisticEdit?"":o("Unsaved changes")),me(null),Ce(null)},St=hn([]),Ht=hn([]),[sn,Gn]=pt(null),Bo=(m,I)=>{for(let E of m.items){if(E.op!=="update")continue;let ne=I.items.find((W)=>W.id===E.id);if(!ne)continue;for(let W of[St,Ht])W.current=W.current.map((U)=>({...U,items:U.items.map((te)=>te.op!=="insert"&&te.id===E.id&&te.expectedVersion===E.expectedVersion?{...te,expectedVersion:ne.version}:te)}))}},mt=(m,I,E)=>{let ne=m.items;if(!ne.length)return null;let W=new Map(E.map((te)=>[te.id,te])),U=[];if(ne.every((te)=>te.op==="update")){let te=new Map(I.items.map((Re)=>[Re.id,Re]));for(let Re of ne){if(Re.op!=="update")continue;let ce=W.get(Re.id);if(!ce)return null;U.push({op:"update",id:Re.id,expectedVersion:te.get(Re.id)?.version??Re.expectedVersion+1,values:Object.fromEntries(Object.keys(Re.values).map((ve)=>[ve,ce.values[ve]??null]))})}}else if(ne.every((te)=>te.op==="insert")){if(I.items.length!==ne.length)return null;for(let te of I.items)U.push({op:"delete",id:te.id,expectedVersion:te.version})}else if(ne.every((te)=>te.op==="delete"))for(let te of ne){if(te.op!=="delete")continue;let Re=W.get(te.id);if(!Re)return null;U.push({op:"insert",values:Object.fromEntries(t.fields.filter((ce)=>ce.type!=="blob"&&ce.type!=="linkedRecord"&&!tt(ce)&&ce.generation!=="autoIncrement"&&Re.values[ce.id]!==void 0).map((ce)=>[ce.id,Re.values[ce.id]]))})}else return null;return{idempotencyKey:crypto.randomUUID(),items:U}},Fr=(m)=>{if(X||e.readOnly||D||Z||H)return;let E=(m==="undo"?St:Ht).current.at(-1);if(!E)return;ct({...E,idempotencyKey:crypto.randomUUID()},void 0,m)};async function ct(m,I,E){if(X||j.current||e.readOnly)return;let ne=E&&sn?sn.before:x;if(E)Gn({direction:E,before:ne,rejected:!1});j.current=!0,K(!0),me(m),ae("");let W=await e.onMutate(m).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:o("Saving failed. Your edit has been kept.")}}));if(j.current=!1,K(!1),W.ok){let U=mt(m,W.data,ne);if(E)(E==="undo"?St:Ht).current.pop();if(Bo(m,W.data),Gn(null),U)if(E==="undo")Ht.current.push(U);else{if(St.current.push(U),St.current.length>30)St.current.shift();if(!E)Ht.current=[]}e.onCommitted(W.data),me(null),J(null),fe(!1),Ce(null);let te=m.items.filter((ce)=>ce.op==="delete").length,Re=E?o(E==="undo"?"Undone":"Redone"):te>0&&te===m.items.length?o("Deleted {count} records",{count:te}):o("Saved");if(e.onNotify)ae(""),e.onNotify(Re);else ae(Re);p.current?.focus({preventScroll:!0}),I?.()}else{if(E){let te=W.error.status;Gn({direction:E,before:ne,rejected:te>=400&&te<500&&te!==408})}ae(W.error.message);let U=W.error.details;if(U?.current)Ce(U.current)}}async function We(m,I,E,ne){if(u.current.has(m.id))return;u.current.add(m.id),K(!0);let W=D??{rowId:m.id,expectedVersion:m.version,field:I,text:Xe(E),originalText:Xe(m.values[I.id])},U={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:m.id,expectedVersion:m.version,values:{[I.id]:E}}]};c((ce)=>({...ce,[m.id]:{...ce[m.id],[I.id]:E}})),f((ce)=>new Set(ce).add(m.id)),J(null),ae(""),p.current?.focus({preventScroll:!0});let te=await e.onMutate(U).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:o("Saving failed. Your edit has been kept.")}}));if(u.current.delete(m.id),K(!1),f((ce)=>{let ve=new Set(ce);return ve.delete(m.id),ve}),te.ok){d.current.add(m.id);let ce=mt(U,te.data,[m]);if(Bo(U,te.data),ce){if(St.current.push(ce),St.current.length>30)St.current.shift();Ht.current=[]}e.onCommitted(te.data),ne?.();return}c((ce)=>{let ve={...ce};return delete ve[m.id],ve}),J(W),me(U),ae(te.error.message);let Re=te.error.details;if(Re?.current)Ce(Re.current)}async function Xt(m){if(!D||T.current)return;let{field:I,rowId:E,expectedVersion:ne}=D;if(I.generation==="autoIncrement"||t.fields.find((W)=>W.id===I.id)?.generation==="autoIncrement"){ae(o("{name} is auto-generated and cannot be edited.",{name:I.name})),J(null);return}try{let W=I.type==="linkedRecord"?JSON.parse(D.text):I.type==="relation"?D.text||null:pn(D.text,I);if(I.type==="linkedRecord"&&I.required&&Array.isArray(W)&&!W.length)throw Error(`${I.name} is required.`);if(i.optimisticEdit&&I.type==="linkedRecord"&&!H&&D.text===D.originalText){dn();return}if(i.optimisticEdit&&I.type!=="linkedRecord"&&!H){let Re=x.find((ce)=>ce.id===E);if(!Re){J(null);return}if(JSON.stringify(W??null)===JSON.stringify(Re.values[I.id]??null)){dn();return}await We(Re,I,W,()=>{if(m)$t(Kr(N,"Tab",x.length,b.length,m==="previous"))});return}let U={[I.id]:W},te=H??{idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:E,expectedVersion:ne,values:U}]};await ct(te,m?()=>$t(Kr(N,"Tab",x.length,b.length,m==="previous")):void 0)}catch(W){ae((e.locale==="zh-CN"?Ho(I,D.text,"zh-CN"):null)||(W instanceof Error?W.message:o("Invalid value")))}}let vn=Boolean(e.readOnly||X||D||Z||H||rn.length===0),Uo=()=>{if(vn||!r)return;Nn()},dn=()=>{T.current=!0,ae(""),J(null),me(null),Ce(null),p.current?.focus({preventScroll:!0})},mo=(m)=>{if(!D||m===D.text)return;ae(i.optimisticEdit?"":o("Unsaved changes")),J({...D,text:m}),me(null),Ce(null)},Yn=(m,I,E)=>{if(!a||X||D||Z||H)return;if(i.optimisticEdit){We(m,I,E);return}J({rowId:m.id,expectedVersion:m.version,field:I,text:String(E),originalText:Xe(m.values[I.id])}),ct({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:m.id,expectedVersion:m.version,values:{[I.id]:E}}]})},cn=i.optionChips,fo=Boolean(e.renderRecordContextMenu)||i.recordContextMenu,Jn=i.optimisticEdit&&!H?{onBlur:(m)=>{if(!m.currentTarget.contains(m.relatedTarget))Xt()}}:{},Et=D?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:D.field,text:D.text,disabled:X||Boolean(e.readOnly),autoOpen:!0,onChange:mo,onSave:(m)=>void Xt(m),onCancel:dn}):void 0,Qn=i.optimisticEdit&&D?.field.type==="linkedRecord"&&(Et===void 0||Et===null)&&!H&&!X?{onBlur:(m)=>{let I=m.relatedTarget;if(!I||re.current?.contains(I)||I.closest('[role="gridcell"]')?.id===`wb-${D.rowId}-${D.field.id}`)return;Xt()}}:{},yo=D&&(D.field.type==="singleSelect"||D.field.type==="multipleSelect")?Et??ot("select",{"aria-label":o("Edit {name}",{name:D.field.name}),ref:(m)=>m?.focus(),style:gu,multiple:D.field.type==="multipleSelect",value:D.field.type==="multipleSelect"?D.text.split(",").filter(Boolean):D.text,disabled:X,onChange:(m)=>mo(D.field.type==="multipleSelect"?Array.from(m.currentTarget.selectedOptions,(I)=>I.value).join(","):m.currentTarget.value),onKeyDown:(m)=>{if(m.stopPropagation(),m.key==="Escape")m.preventDefault(),dn();if(m.key==="Tab")m.preventDefault(),Xt(m.shiftKey?"previous":"next");if(m.key==="Enter")m.preventDefault(),Xt()},children:[D.field.type==="singleSelect"&&Q("option",{value:"",disabled:D.field.required,children:o("Clear selection")}),(D.field.options??[]).map((m)=>Q("option",{value:m.id,children:m.name},m.id)),D.text.split(",").filter((m)=>m&&!D.field.options?.some((I)=>I.id===m)).map((m)=>Q("option",{value:m,disabled:!0,children:o("{id} (unavailable)",{id:m})},m))]}):void 0,Nn=()=>{if(!r||X||D||Z||H||Fe.length===0)return;if(Fe.length>100){ae(o("Select at most 100 rows per delete."));return}me({idempotencyKey:crypto.randomUUID(),items:Fe.map((m)=>({op:"delete",id:m.id,expectedVersion:m.version}))}),fe(!0),ae(""),Ce(null)},lr=(m,I,E,ne,W)=>{W.setPointerCapture(ne);let U=(Re)=>e.onViewChange({...n,columnWidths:{...n.columnWidths,[m]:Sr(E+Re.clientX-I)}}),te=()=>{W.removeEventListener("pointermove",U),W.removeEventListener("pointerup",te),W.removeEventListener("pointercancel",te)};W.addEventListener("pointermove",U),W.addEventListener("pointerup",te),W.addEventListener("pointercancel",te)},[sr,wi]=pt(480);ru(()=>{if(!e.display?.fill)return;let m=()=>{let I=p.current?.getBoundingClientRect().top??0;wi(Math.max(240,Math.round(window.innerHeight-I-64-(i.footerStats?34:0))))};return m(),window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[e.display?.fill,i.footerStats]);let xn=e.display?.summary===!1&&e.display?.keyboardHints===!1,dr=!!D&&Pe.getVirtualItems().some((m)=>{let I=Y.items[m.index];return I?.kind==="row"&&x[I.index]?.id===D.rowId})&&zt.getVirtualItems().some((m)=>b[m.index]?.id===D.field.id),On=ot("section",{"data-uibot":"paged-collection-grid",style:{display:xn?"grid":"flex",flexDirection:xn?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&&Fe.length>0&&!e.renderRecordContextMenu&&!i.recordContextMenu)&&ot("div",{"data-uibot":"paged-collection-toolbar",style:{display:"flex",gap:8,padding:8,alignItems:"center",flexWrap:"wrap",...xn?{}:{order:1,padding:"4px 10px",fontSize:12,borderTop:"1px solid var(--border, #d5d9df)"},...xn?{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&&Q("span",{children:vr(o,e.total,x.length,e.locale)}),e.aggregate&&!i.footerStats&&Q(Ao,{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}:{}}),Q("span",{style:{flex:1}}),e.display?.keyboardHints!==!1&&Q("span",{style:{fontSize:12},children:o(a?"Arrows · Shift select · Enter edit · Copy / paste":"Arrows · Shift select · Copy")}),e.onInspectRecord&&Q(G,{ui:e.ui,style:Kn,variant:"outline",size:"sm",disabled:X||Fe.length!==1,onClick:()=>{let m=Fe[0];if(m)e.onInspectRecord?.(m.id)},children:o("Open record activity")}),r&&Fe.length>0&&!e.renderRecordContextMenu&&!i.recordContextMenu&&Q(G,{ui:e.ui,style:Kn,variant:"outline",size:"sm",icon:"trash",disabled:vn,onClick:Nn,children:o("Delete selected rows")})]}),Q("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
|
+
`}),ot(pu,{ui:e.ui,paneRef:p,role:"grid","aria-label":o("{name} records",{name:t.name}),"aria-rowcount":e.total+1,"aria-colcount":b.length+Number(Boolean(Ae))+Number(Boolean(Qe)),"aria-activedescendant":x[N.row]&&b[N.column]?`wb-${x[N.row]?.id}-${b[N.column]?.id}`:void 0,tabIndex:0,style:{gridArea:xn?"1 / 1":void 0,overflow:"auto",height:e.display?.fill?sr:i.autoHeight?Math.min(e.display?.maxHeight??560,Math.max(120,ll(Y,de)+2+(Ct?Ma:0))):e.display?.maxHeight??480,position:"relative",outlineOffset:-2},onScroll:(m)=>uo.current?.style.setProperty("--uibot-sx",`${m.currentTarget.scrollLeft}px`),onCopy:(m)=>{if(D)return;m.preventDefault(),m.clipboardData.setData("text/plain",Mn())},onPaste:(m)=>{if(D||Z||H||!a||X)return;if(m.preventDefault(),qe.size){ae(o("Expand all groups before pasting."));return}let I=pl(m.clipboardData.getData("text/plain"),x,b,{row:et.firstRow,column:et.firstColumn},e.locale);if(!I.ok){ae(I.message);return}me({idempotencyKey:crypto.randomUUID(),items:I.items}),fe(!0),ae(""),Ce(null)},onKeyDown:(m)=>{if(m.target!==m.currentTarget&&m.target.closest("button, input, select, textarea, [contenteditable=true]"))return;if((m.metaKey||m.ctrlKey)&&!m.altKey&&!D){let I=m.key.toLowerCase();if(I==="d"||I==="r"){m.preventDefault();let E=I==="d"?{...et,lastRow:et.firstRow}:{...et,lastColumn:et.firstColumn};Oo(E,et);return}if(I==="z"||I==="y"){m.preventDefault(),Fr(I==="y"||m.shiftKey?"redo":"undo");return}}if(!D&&m.key==="Escape"){A(new Set),L(new Set);return}if(D||!x.length||!b.length||X)return;if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End"].includes(m.key)){m.preventDefault();let I=m.key==="Tab"&&m.shiftKey,E=Kr(N,m.key,x.length,b.length,I);if(V(E.row)){let ne=m.key==="ArrowUp"||I||E.row<N.row,W=Hr(Y,E.row,ne?-1:1,x.length);if(W<0)return;E={...E,row:W}}$t(E,m.shiftKey&&m.key!=="Tab")}else if(V(N.row))m.preventDefault();else if(m.key==="Delete"&&Fe.length>0&&r)m.preventDefault(),Nn();else if(a&&["Enter","F2"].includes(m.key))m.preventDefault(),po();else if(a&&m.key.length===1&&!m.metaKey&&!m.ctrlKey&&!m.altKey)m.preventDefault(),po(N,m.key)},children:[Q(iu,{sensors:or,modifiers:[bu],onDragEnd:Wn,children:ot("div",{role:"row",tabIndex:-1,style:{position:"sticky",top:0,height:38,width:je,zIndex:2,background:"var(--muted, #f4f6f8)"},children:[Ae>0&&Q("div",{role:"columnheader",tabIndex:-1,"aria-colindex":1,"aria-label":o("Row"),style:{...Zt(0,!Qe&&He===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:Ae,padding:4,display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center",height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:ot("label",{title:o("{count} selected",{count:Fe.length}),style:{position:"relative",display:"flex",alignItems:"center"},children:[Fe.length===0&&Q("span",{"aria-hidden":"true",children:o("Row")}),Q("input",{type:"checkbox","aria-label":o("Select all loaded records"),ref:(m)=>{if(m)m.indeterminate=Fe.length>0&&Fe.length<x.filter((I,E)=>!V(E)).length},style:Fe.length===0?{position:"absolute",inset:0,width:"100%",height:"100%",margin:0,opacity:0,cursor:"pointer"}:{margin:0,width:16,height:16},onKeyDown:(m)=>m.stopPropagation(),checked:Fe.length>0&&Fe.length===x.filter((m,I)=>!V(I)).length,disabled:Boolean(D||X||Z||H),onChange:(m)=>{B(!1),C(v),L(new Set),A(m.currentTarget.checked?new Set(x.filter((I,E)=>!V(E)).map((I)=>I.id)):new Set)},onFocus:(m)=>{m.currentTarget.parentElement?.style.setProperty("outline","2px solid var(--ring, currentColor)")},onBlur:(m)=>{m.currentTarget.parentElement?.style.removeProperty("outline")}})]})}),Qe>0&&Q("div",{role:"columnheader",tabIndex:-1,"aria-colindex":Ae>0?2:1,style:{...Zt(Ae,He===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:Qe,padding:8,height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:o("Record ID")}),No.map((m)=>{let I=b[m.index];if(!I)return null;let E=vi(n.columnColors?.[I.id]),ne=n.sort?.find((ce)=>ce.fieldId===I.id),W=i.sorting&&I.type!=="linkedRecord"&&tn(I),U=e.fieldMenu?.(I)??[],te=U.length?e.ui?.DropdownMenu?e.ui.DropdownMenu({label:o("Field menu {name}",{name:I.name}),icon:Q(xe,{name:"chevronDown"}),items:U}):Q(Ci,{label:o("Field menu {name}",{name:I.name}),icon:Q(xe,{name:"chevronDown"}),items:U},I.id):null,Re=Q(hu,{id:I.id,disabled:!i.columnReorder,children:(ce)=>ot("div",{ref:ce.setNodeRef,...ce.listeners,role:"columnheader",tabIndex:-1,"aria-colindex":m.index+1+Number(Boolean(Ae))+Number(Boolean(Qe)),onKeyDown:(ve)=>{if(ve.shiftKey&&ve.key==="F10"||ve.key==="ContextMenu"){ve.preventDefault(),ve.stopPropagation();let ue=ve.currentTarget.querySelector('button[aria-haspopup="menu"]');ue?.focus({preventScroll:!0}),ue?.click(),ue?.dispatchEvent(new KeyboardEvent("keydown",{key:"ArrowDown",bubbles:!0}))}},"aria-sort":ne?ne.direction==="asc"?"ascending":"descending":"none",style:{...m.index<He?{...Zt(Ze(m.index),m.index===He-1),background:"var(--muted, #f4f6f8)"}:{position:"absolute",left:m.start},boxSizing:"border-box",background:E?.background??"var(--muted, #f4f6f8)",borderTopWidth:E?3:void 0,borderTopStyle:E?"solid":void 0,borderTopColor:E?.marker,width:m.size,height:38,borderRight:"1px solid var(--border, #d5d9df)",display:"flex",alignItems:"center",...ce.style},children:[ot("button",{type:"button",disabled:!W,title:W||!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:uu(n.sort??[],I.id)}),children:[i.fieldTypeIcons&&Q(fi,{type:I.type}),i.fieldTypeIcons?Q("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:I.name}):I.name,ne?Q(xe,{name:ne.direction==="asc"?"sortAsc":"sortDesc",size:12,style:{marginLeft:"auto",opacity:0.7}}):null]}),te,i.columnResize&&Q("button",{type:"button","aria-label":o("Resize {name}",{name:I.name}),style:{border:0,background:"transparent",position:"absolute",top:0,bottom:0,right:-3,width:7,padding:0,cursor:"col-resize",zIndex:2},onPointerDown:(ve)=>{ve.stopPropagation(),lr(I.id,ve.clientX,m.size,ve.pointerId,ve.currentTarget)},onKeyDown:(ve)=>{if(ve.key==="ArrowLeft"||ve.key==="ArrowRight")ve.preventDefault(),e.onViewChange({...n,columnWidths:{...n.columnWidths,[I.id]:Sr(m.size+(ve.key==="ArrowRight"?20:-20))}})}})]})},I.id);return U.length&&e.ui?.ContextMenu?Q(e.ui.ContextMenu,{items:U,"aria-label":o("Field menu {name}",{name:I.name}),children:Re},I.id):Re})]})}),ot("div",{style:{position:"relative",width:je,height:Pe.getTotalSize()+(Ct?Ma:0)},children:[Pe.getVirtualItems().map((m)=>{let I=Y.items[m.index];if(I?.kind==="group"){let W=I.label===null?o("Not set"):I.label==="true"?o("Checked"):I.label==="false"?o("Unchecked"):I.label;return Q("div",{role:"presentation","data-uibot-group":W,style:{position:"absolute",top:m.start-38,height:m.size,width:je,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"},children:ot("button",{type:"button","aria-expanded":!I.collapsed,"aria-label":o(I.collapsed?"Expand group {name}":"Collapse group {name}",{name:W}),disabled:!i.groupCollapse,onClick:()=>Vo(I.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&&Q("span",{"aria-hidden":"true",style:{width:10,fontSize:10,opacity:0.6},children:I.collapsed?"▸":"▾"}),Q(Ca,{index:I.colorIndex,children:W}),Q("span",{style:{opacity:0.6},children:o("{count} records",{count:I.count})})]})},I.key)}let E=I?x[I.index]:void 0;if(I?.kind!=="row"||!E)return null;let ne=I.index;return ot("div",{role:"row",tabIndex:-1,"aria-rowindex":(e.rowOffset??0)+ne+2,style:{position:"absolute",top:m.start-38,height:m.size,width:je},children:[Ae>0&&ot("div",{role:"gridcell",tabIndex:-1,"aria-colindex":1,"aria-label":String((e.rowOffset??0)+ne+1),"aria-readonly":"true","aria-selected":Vt.has(E.id),style:{...Zt(0,!Qe&&He===0),width:Ae,height:m.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:Vt.has(E.id)?"var(--accent, #e8f0fe)":"var(--muted, #f4f6f8)"},onMouseDown:(W)=>{if(D||W.button!==0||b.length===0)return;if(W.target.closest("button, input"))return;if(W.preventDefault(),W.ctrlKey||W.metaKey){rr(ne),p.current?.focus({preventScroll:!0});return}if(!W.shiftKey)$t({row:ne,column:0});$t({row:ne,column:b.length-1},!0),p.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!fo||b.length===0)return;if(!Vt.has(E.id))$t({row:ne,column:0})},children:[Q("span",{"data-uibot-row-number":"",style:{opacity:Vt.has(E.id)?0:1},children:(e.rowOffset??0)+ne+1}),ot("span",{"data-uibot-row-actions":"",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",gap:4,opacity:Vt.has(E.id)?1:0},children:[Q("input",{type:"checkbox","aria-label":o("Select row"),checked:Vt.has(E.id),disabled:Boolean(D||X||Z||H),onChange:()=>rr(ne),onClick:(W)=>W.stopPropagation()}),e.onExpandRecord&&Q("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?.(E),children:Q(xe,{name:"expand"})})]})]}),Qe>0&&Q("div",{role:"gridcell",tabIndex:-1,"aria-colindex":Ae>0?2:1,"aria-readonly":"true",style:{...Zt(Ae,He===0),background:"var(--background, white)",boxSizing:"border-box",width:Qe,height:m.size,padding:7,borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)"},onContextMenu:()=>{if(!fo)return;if(!Vt.has(E.id))$t({row:ne,column:0})},children:Q("input",{"aria-label":o("Record ID {id}",{id:E.id}),readOnly:!0,value:E.id,style:{width:"100%",border:0,background:"transparent",color:"inherit",fontSize:12},onCopy:(W)=>W.stopPropagation(),onPaste:(W)=>W.stopPropagation(),onKeyDown:(W)=>W.stopPropagation()})}),No.map((W)=>{let U=b[W.index];if(!U)return null;let te={row:ne,column:W.index},Re=Vt.has(E.id)&&(R.has(E.id)||M&&te.column>=et.firstColumn&&te.column<=et.lastColumn),ce=D?.rowId===E.id&&D.field.id===U.id,ve=!ce&&U.type==="checkbox"?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:U,text:Xe(E.values[U.id]),disabled:Boolean(!a||X||D||Z||H),mode:"inline",autoOpen:!1,onChange:(ue)=>{if(!a||X||D||Z||H)return;try{let Me=pn(ue,U);J({rowId:E.id,expectedVersion:E.version,field:U,text:ue,originalText:Xe(E.values[U.id])}),ct({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:E.id,expectedVersion:E.version,values:{[U.id]:Me}}]})}catch(Me){ae(e.locale==="zh-CN"?Ho(U,ue,"zh-CN"):Me instanceof Error?Me.message:o("Invalid value"))}},onSave:()=>{},onCancel:dn}):void 0;return ot("div",{id:`wb-${E.id}-${U.id}`,role:"gridcell",tabIndex:-1,...ce&&U.type==="linkedRecord"?Qn:{},"aria-colindex":W.index+1+Number(Boolean(Ae))+Number(Boolean(Qe)),"aria-selected":Re,"aria-readonly":!a||U.generation==="autoIncrement"||U.type==="blob"||tt(U),style:{...W.index<He?Zt(Ze(W.index),W.index===He-1):{position:"absolute",left:W.start},width:W.size,height:m.size,padding:ce?0:cn?"0 10px":7,boxSizing:"border-box",borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",overflow:ce?"visible":"hidden",...ce?{zIndex:3}:{},whiteSpace:"nowrap",...cn&&!ce?{display:"flex",alignItems:"center",fontSize:13}:{},...we>1&&!ce&&(U.type==="singleLineText"||U.type==="longText")?{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:we,whiteSpace:"normal",wordBreak:"break-word",padding:cn?"6px 10px":7}:{},background:Re?"var(--accent, #e8f0fe)":vi(n.columnColors?.[U.id])?.background??"var(--background, white)",outline:N.row===te.row&&N.column===te.column?"2px solid #6488bd":"none",outlineOffset:-2},onMouseEnter:()=>{if(!dt)return;let ue=Math.max(dt.firstRow-te.row,te.row-dt.lastRow,0),Me=Math.max(dt.firstColumn-te.column,te.column-dt.lastColumn,0);an.current=ue>=Me?{...dt,firstRow:Math.min(te.row,dt.firstRow),lastRow:Math.max(te.row,dt.lastRow)}:{...dt,firstColumn:Math.min(te.column,dt.firstColumn),lastColumn:Math.max(te.column,dt.lastColumn)}},onMouseDown:(ue)=>{if(dt||D)return;if(ue.button!==0)return;ue.preventDefault(),$t(te,ue.shiftKey),p.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!fo)return;if(!(Vt.has(E.id)&&(R.has(E.id)||te.column>=et.firstColumn&&te.column<=et.lastColumn)))$t(te)},onClick:(ue)=>{if(!D&&!ue.shiftKey&&(U.type==="singleSelect"||U.type==="multipleSelect"))po(te)},onDoubleClick:()=>po(te),children:[ar&&te.row===et.lastRow&&te.column===et.lastColumn&&Q("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:dt?"grabbing":"grab",zIndex:4},onMouseDown:(ue)=>{ue.preventDefault(),ue.stopPropagation(),an.current=null,ir(et)},onClick:(ue)=>ue.stopPropagation()}),ce&&Et!==void 0&&Et!==null?Et:ce&&U.type==="relation"?Q(xr,{locale:e.locale,field:U,value:D.text,label:o("Edit {name}",{name:U.name}),getOptions:e.getRelationOptions,labels:E.linkedRecords?.[U.id],disabled:X,onChange:(ue)=>{ae(i.optimisticEdit?"":o("Unsaved changes")),J({...D,text:ue}),me(null),Ce(null)}}):ce&&yo!==void 0?Q("div",{style:{display:"contents"},...Jn,children:yo}):ce&&U.type!=="linkedRecord"?Q("div",{style:{display:"contents"},...Jn,children:Q(ji,{field:U,text:D.text,disabled:X||Boolean(e.readOnly),locale:e.locale,ariaLabel:o("Edit {name}",{name:U.name}),onChange:mo,onSave:(ue)=>void Xt(ue),onCancel:dn})}):U.type==="relation"||U.type==="linkedRecord"?wo(E,U):U.type==="lookup"?to(E.values[U.id]):U.type==="formula"||U.type==="rollup"?$o(E.values[U.id],E.computedErrors?.[U.id]):U.type==="checkbox"&&ve!==void 0&&ve!==null?ve:U.type==="checkbox"&&cn?Q(Jl,{checked:E.values[U.id]===!0,label:o("Edit {name}",{name:U.name}),onToggle:!a||X||D||Z||H||U.generation==="autoIncrement"?void 0:()=>Yn(E,U,E.values[U.id]!==!0)}):U.type==="checkbox"?Q("input",{type:"checkbox","aria-label":o("Edit {name}",{name:U.name}),checked:E.values[U.id]===!0,ref:(ue)=>{if(ue)ue.indeterminate=E.values[U.id]==null},disabled:!a||X||Boolean(D)||Boolean(Z)||Boolean(H)||U.generation==="autoIncrement",onMouseDown:(ue)=>ue.stopPropagation(),onKeyDown:(ue)=>ue.stopPropagation(),onChange:(ue)=>{if(!a||X||D||Z||H)return;let Me=ue.currentTarget.checked;J({rowId:E.id,expectedVersion:E.version,field:U,text:String(Me),originalText:Xe(E.values[U.id])}),ct({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:E.id,expectedVersion:E.version,values:{[U.id]:Me}}]})}}):U.type==="date"?Q("span",{title:Xe(E.values[U.id]),style:cn?{opacity:0.75,fontVariantNumeric:"tabular-nums"}:void 0,children:(()=>{let ue=xt(U);return ue?Bn(E.values[U.id],ue):jr(E.values[U.id])})()}):U.type==="number"&&cn?Q("span",{style:{display:"block",width:"100%",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:(()=>{let ue=vo(U);return ue?xo(E.values[U.id],ue):Xe(E.values[U.id])})()}):cn&&U.type==="singleSelect"&&E.values[U.id]!=null?Q(Eo,{ids:[E.values[U.id]],field:U,wrap:we>1}):cn&&U.type==="multipleSelect"&&Array.isArray(E.values[U.id])?Q(Eo,{ids:E.values[U.id],field:U,wrap:we>1}):U.type==="singleSelect"?U.options?.find((ue)=>ue.id===E.values[U.id])?.name??Xe(E.values[U.id]):U.type==="multipleSelect"&&Array.isArray(E.values[U.id])?E.values[U.id].map((ue)=>U.options?.find((Me)=>Me.id===ue)?.name??String(ue)).join(", "):Xe(E.values[U.id])]},U.id)})]},E.id)}),Ct?Q("div",{style:{position:"absolute",top:Pe.getTotalSize(),left:0,width:je,height:Ma,borderBottom:"1px solid var(--border, #d5d9df)"},children:ot("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:[Q(xe,{name:"plus"}),o("Add record")]})}):null]})]}),i.footerStats&&(n.type??"grid")==="grid"&&b.length>0?Q(Cu,{ui:e.ui,locale:e.locale,t:o,rows:x,total:e.total,descriptor:t,aggregateClient:e.serverFooterStats===!1?void 0:e.aggregate?.client,reloadKey:e.reloadKey,fields:b,columns:No,width:je,frozenCount:He,frozenLeft:Ze,view:n,footerRef:uo,onChange:e.onViewChange}):null,D&&(H||!(i.optimisticEdit&&D.field.type!=="linkedRecord"))&&!(dr&&Et!==void 0&&Et!==null)&&ot("div",{ref:re,...Qn,role:"dialog","aria-label":o("{name} editor",{name:D.field.name}),style:{padding:8,display:"flex",flexWrap:"wrap",gap:8},onKeyDown:(m)=>{if(D.field.type==="linkedRecord"&&m.key==="Escape"&&!X)m.preventDefault(),m.stopPropagation(),dn()},children:[!dr&&D.field.type!=="linkedRecord"&&(Et??yo??(D.field.type==="relation"?Q(xr,{locale:e.locale,field:D.field,value:D.text,label:o("Edit {name}",{name:D.field.name}),getOptions:e.getRelationOptions,labels:x.find((m)=>m.id===D.rowId)?.linkedRecords?.[D.field.id],disabled:X,onChange:mo}):Q(ji,{field:D.field,text:D.text,disabled:X||Boolean(e.readOnly),locale:e.locale,ariaLabel:o("Edit {name}",{name:D.field.name}),onChange:mo,onSave:(m)=>void Xt(m),onCancel:dn}))),D.field.type==="linkedRecord"&&Q("div",{style:{width:"100%"},children:Q(Wr,{disabled:X,field:D.field,value:JSON.parse(D.text),locale:e.locale,labels:x.find((m)=>m.id===D.rowId)?.linkedRecords?.[D.field.id],client:e.relationClient,onChange:(m)=>{J({...D,text:JSON.stringify(m)}),me(null),Ce(null)}})}),Q(G,{ui:e.ui,style:Kn,variant:"outline",size:"sm",disabled:X,onClick:()=>void Xt(),children:X?o("Saving…"):o("Save edit")}),Q(G,{ui:e.ui,style:Kn,variant:"outline",size:"sm",disabled:X,onClick:dn,children:o("Cancel edit")})]}),Z&&H&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:H.items.every((m)=>m.op==="delete"),title:H.items.every((m)=>m.op==="delete")?o("Delete {count} records?",{count:H.items.length}):o("Apply {count} row changes in one transaction?",{count:H.items.length}),description:H.items.every((m)=>m.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:X?o("Saving…"):H.items.every((m)=>m.op==="delete")?o("Delete"):o("Confirm changes"),cancelLabel:H.items.every((m)=>m.op==="delete")?o("Cancel"):o("Cancel changes"),busy:X,onConfirm:()=>void ct(H),onCancel:()=>{fe(!1),me(null),Ce(null)}}):null,Z&&H&&!e.ui?.ConfirmDialog&&ot(Jr,{label:o("Confirm bulk change"),busy:X,onCancel:()=>{fe(!1),me(null),Ce(null)},children:[Q("p",{children:o("Apply {count} row changes in one transaction?",{count:H.items.length})}),Q("p",{style:{fontSize:12},children:o("If any record changed or any value is invalid, all changes are rejected.")}),Q(G,{ui:e.ui,style:Kn,variant:"outline",size:"sm",disabled:X,onClick:()=>void ct(H),children:X?o("Saving…"):o("Confirm changes")})," ",Q(G,{ui:e.ui,style:Kn,variant:"outline",size:"sm",disabled:X,onClick:()=>{fe(!1),me(null),Ce(null)},children:o("Cancel changes")})]}),sn&&H&&ot("div",{role:"group","aria-label":o("Undo/redo recovery"),style:{padding:8},children:[!X&&ee&&Q("p",{role:"alert",children:ee}),Q(G,{ui:e.ui,style:Kn,variant:"outline",size:"sm",disabled:X||Boolean(e.readOnly),onClick:()=>void ct(H,void 0,sn.direction),children:o("Retry undo/redo")})," ",sn.rejected&&Q(G,{ui:e.ui,style:Kn,variant:"outline",size:"sm",disabled:X,onClick:()=>{St.current=[],Ht.current=[],Gn(null),me(null),Ce(null),ae("")},children:o("Clear undo/redo history")})]}),he&&!sn&&ot("div",{style:{padding:12},children:[Q("strong",{children:o("Current server version {version}",{version:he.version})}),Q("div",{style:{display:"grid",gap:8,margin:"8px 0"},children:H?.items.flatMap((m)=>m.op==="update"&&m.id===he.id?Object.entries(m.values).map(([I,E])=>{let ne=t.fields.find((U)=>U.id===I),W=(U)=>ne?.options?.find((te)=>te.id===U)?.name??Xe(U);return ot("div",{style:{border:"1px solid var(--border,#d5d9df)",borderRadius:6,padding:8},children:[Q("strong",{children:ne?.name??I}),ot("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"minmax(90px,auto) 1fr",gap:4},children:[Q("dt",{children:o("Your edit")}),Q("dd",{style:{margin:0,whiteSpace:"pre-wrap"},children:W(E)}),Q("dt",{children:o("Server value")}),Q("dd",{style:{margin:0,whiteSpace:"pre-wrap"},children:W(he.values[I])})]})]},I)}):[])}),Q(G,{ui:e.ui,style:Kn,variant:"outline",size:"sm",disabled:X,onClick:()=>{if(!H)return;let m=H.items.map((I)=>I.op!=="insert"&&I.id===he.id?{...I,expectedVersion:he.version}:I);ct({idempotencyKey:crypto.randomUUID(),items:m})},children:o("Retry against current version")})]}),Q("p",{role:"status","aria-live":"polite",style:e.onNotify?mu:{margin:0,padding:ee||X?8:0},children:X?o("Saving…"):sn?"":ee})]}),Tr=t.fields.filter((m)=>m.type!=="blob"&&m.type!=="linkedRecord"&&!tt(m)&&m.generation!=="autoIncrement"),cr=()=>{if(!s||vn||Fe.length===0||Fe.length>100)return;ct({idempotencyKey:crypto.randomUUID(),items:Fe.map((m)=>({op:"insert",values:Object.fromEntries(Tr.flatMap((I)=>m.values[I.id]===void 0?[]:[[I.id,m.values[I.id]]]))}))})};if(e.renderRecordContextMenu){let m=Fe.length===1?Fe[0]:void 0;return e.renderRecordContextMenu({children:On,recordIds:rn,disabled:vn,onDelete:Uo,...e.onExpandRecord&&m?{onExpand:()=>e.onExpandRecord?.(m)}:{},onCopy:()=>void navigator.clipboard?.writeText(Mn()),...s?{onDuplicate:cr}:{}})}if(!i.recordContextMenu)return On;let Er=[...e.onExpandRecord&&Fe.length===1?[{id:"expand",icon:Q(xe,{name:"expand"}),label:o("Expand record"),onSelect:()=>{let m=Fe[0];if(m)e.onExpandRecord?.(m)}}]:[],...s?[{id:"duplicate",icon:Q(xe,{name:"copy"}),label:o("Duplicate {count} selected records",{count:Fe.length}),disabled:vn||Fe.length===0,onSelect:cr}]:[],{id:"copy",separatorBefore:!0,icon:Q(xe,{name:"copy"}),label:o("Copy cells"),disabled:Fe.length===0,onSelect:()=>{navigator.clipboard?.writeText(Mn())}},...r?[{id:"delete",icon:Q(xe,{name:"trash"}),label:o("Delete {count} selected records",{count:Fe.length}),separatorBefore:!0,destructive:!0,disabled:vn,onSelect:Uo}]:[]],Zn=e.ui?.ContextMenu;return Zn?Q(Zn,{items:Er,"aria-label":o("Record actions"),children:On}):Q(hi,{block:!0,items:Er,label:o("Record actions"),children:On})}function pu({ui:e,paneRef:t,style:n,children:o,...i}){if(e?.ScrollArea)return e.ScrollArea({viewportRef:t,viewportProps:i,style:n,children:o});return Q("div",{ref:t,style:n,...i,children:o})}var mu={position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:0},fu=96,yu=560,Sr=(e)=>Math.max(fu,Math.min(yu,Math.round(e))),bu=({transform:e})=>({...e,y:0});function hu({id:e,disabled:t,children:n}){let{setNodeRef:o,listeners:i,transform:r,isDragging:s}=lu({id:e,disabled:t});return Cn(()=>{if(!s)return;let a=document.body.style.cursor;return document.body.style.cursor="grabbing",()=>{document.body.style.cursor=a}},[s]),n({setNodeRef:o,listeners:t?void 0:i,style:{...r?{transform:`translate3d(${Math.round(r.x)}px, 0, 0)`}:{},...s?{cursor:"grabbing",zIndex:6,opacity:0.9,background:"var(--accent, #e8f0fe)",boxShadow:"0 2px 10px color-mix(in srgb, currentColor 22%, transparent)"}:{}}})}function Cu({descriptor:e,aggregateClient:t,reloadKey:n,ui:o,locale:i,t:r,rows:s,total:a,fields:l,columns:c,width:d,frozenCount:g,frozenLeft:f,view:u,footerRef:x,onChange:b}){let v=vs(e,u,l,s,t,n),y=(C,p,k)=>{let P={...u.footerStats??{}};if(p)P[C]=p;else if(k)P[C]="none";else delete P[C];let{footerStats:M,...B}=u;b(Object.keys(P).length?{...B,footerStats:P}:B)};return ot("div",{ref:x,"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:[Q("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
|
+
`}),Q("div",{style:{position:"relative",width:d,height:"100%",transform:"translateX(calc(var(--uibot-sx, 0px) * -1))"},children:c.map((C)=>{let p=l[C.index];if(!p)return null;let k=C.index===0,P=u.footerStats?.[p.id],M=P!==void 0?P==="none"?void 0:P:k?"count":void 0,B=M?Ps(s,p,M):null,R=(O)=>O===null?"":typeof O==="number"&&M!=="count"&&M!=="filled"&&M!=="empty"?Sn(Math.round(O*100)/100,p):typeof O==="number"?O.toLocaleString(i):Sn(O,p),A=R(B),_=!t?B:M==="count"?a:v.values[`footer${C.index}`]??null,L=!M?"":!t||M==="count"?R(_):v.status==="loading"?"…":v.status==="error"||_===null?"—":R(_),w=M?M==="count"&&k?r("Footer record count",{count:L}):`${r(`Footer ${M}`)} ${L}`.trim():r("Auto summary"),N=C.index<g;return Q("div",{"data-uibot-footer-cell":"",style:{position:"absolute",left:N?f(C.index):C.start,width:C.size,height:"100%",boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"flex-end",padding:"0 4px",background:vi(u.columnColors?.[p.id])?.background??"var(--background, white)",zIndex:N?2:void 0,transform:N?"translateX(var(--uibot-sx, 0px))":void 0,opacity:M?1:0,transition:"opacity 120ms"},children:Q(Fn,{ui:o,chevron:!0,quiet:!0,active:!1,label:w,children:(O)=>ot("div",{style:{display:"grid",gap:2,minWidth:150},children:[Q(G,{ui:o,variant:M?"ghost":"outline",size:"sm",onClick:()=>{y(p.id,null,k),O()},children:r("No summary")}),ws(p).map((D)=>Q(G,{ui:o,variant:M===D?"outline":"ghost",size:"sm",onClick:()=>{y(p.id,D,k),O()},children:r(`Footer ${D}`)},D)),t&&v.status==="error"&&M&&M!=="count"?Q("small",{style:{opacity:0.7,padding:"4px 6px"},children:r("Loaded records fallback: {value}",{value:A||"—"})}):null,(!t||v.status==="error")&&a>s.length?Q("small",{style:{opacity:0.7,padding:"4px 6px"},children:r("Summaries cover the {count} loaded records.",{count:s.length})}):null]})})},p.id)})})]})}var Ma=36;import{DndContext as vu,KeyboardSensor as xu,PointerSensor as wu,closestCenter as Pu,useSensor as Rs,useSensors as ku}from"@dnd-kit/core";import{SortableContext as Su,arrayMove as Ru,sortableKeyboardCoordinates as Iu,useSortable as Au,verticalListSortingStrategy as Du}from"@dnd-kit/sortable";import{CSS as Fu}from"@dnd-kit/utilities";import{useState as Tu}from"react";import{jsx as At,jsxs as Mo}from"react/jsx-runtime";var Na="1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",Eu=({transform:e,draggingNodeRect:t,containerNodeRect:n})=>{let o=e.y;if(t&&n)o=Math.min(Math.max(o,n.top-t.top),n.bottom-t.bottom);return{...e,x:0,y:o}};function As({fields:e,view:t,onChange:n,locale:o,ui:i,onEditField:r,onAddField:s}){let a=le(o),[l,c]=Tu(""),d=ku(Rs(wu,{activationConstraint:{distance:4}}),Rs(xu,{coordinateGetter:Iu})),f=[...t.columnOrder.flatMap((C)=>{let p=e.find((k)=>k.id===C);return p?[p]:[]}),...e.filter((C)=>!t.columnOrder.includes(C.id))],u=f.map((C)=>C.id),x=({active:C,over:p})=>{if(!p||C.id===p.id)return;let k=u.indexOf(String(C.id)),P=u.indexOf(String(p.id));if(k<0||P<0)return;n({...t,columnOrder:Ru(u,k,P)})},b=e[0]?.id,v=l.trim().toLowerCase(),y=v?f.filter((C)=>C.name.toLowerCase().includes(v)):f;return Mo("div",{"data-uibot-field-config":"",style:{display:"grid",gap:6,minWidth:0},children:[At("input",{type:"search","aria-label":a("Search fields"),placeholder:a("Search fields"),value:l,onChange:(C)=>c(C.currentTarget.value),style:{boxSizing:"border-box",height:28,fontSize:12,padding:"0 8px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit"}}),At(vu,{sensors:d,collisionDetection:Pu,modifiers:[Eu],onDragEnd:x,children:At(Su,{items:y.map((C)=>C.id),strategy:Du,disabled:Boolean(v),children:Mo("div",{style:{display:"grid",gap:2,maxHeight:320,overflowY:"auto"},children:[y.map((C)=>{let p=!t.hiddenColumns.includes(C.id);return Mo(Mu,{id:C.id,label:a("Reorder {name}",{name:C.name}),disabled:Boolean(v),dimmed:!p,children:[At(fi,{type:C.type}),Mo("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[C.name,C.required?" *":""]}),At(G,{ui:i,variant:"ghost",size:"sm",icon:p?"eye":"eyeOff",iconOnly:!0,disabled:t.type==="form"&&C.required===!0||C.id===b,ariaLabel:a(p?"Hide {name}":"Show {name}",{name:C.name}),onClick:()=>n({...t,hiddenColumns:p?[...t.hiddenColumns,C.id]:t.hiddenColumns.filter((k)=>k!==C.id)})}),r&&At(G,{ui:i,variant:"ghost",size:"sm",icon:"more",iconOnly:!0,ariaLabel:a("Edit field {name}",{name:C.name}),onClick:()=>r(C.id)})]},C.id)}),y.length===0&&At("span",{style:{opacity:0.7,padding:6},children:a("No matching fields")})]})})}),Mo("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"8px 4px 2px",borderTop:Na},children:[At("span",{children:a("Show row numbers")}),At(Is,{ui:i,checked:t.showRowNumber!==!1,label:a("Show row numbers"),onChange:(C)=>n({...t,showRowNumber:C})})]}),Mo("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"8px 4px 2px",borderTop:Na},children:[At("span",{children:a("Show record IDs")}),At(Is,{ui:i,checked:t.showRecordId===!0,label:a("Show record IDs"),onChange:(C)=>n({...t,showRecordId:C})})]}),s&&At("div",{style:{borderTop:Na,paddingTop:6},children:At(G,{ui:i,variant:"ghost",size:"sm",icon:"plus",onClick:s,children:a("Add field")})})]})}function Mu({id:e,label:t,disabled:n,dimmed:o,children:i}){let{attributes:r,listeners:s,setNodeRef:a,setActivatorNodeRef:l,transform:c,transition:d,isDragging:g}=Au({id:e,disabled:n});return Mo("div",{ref:a,style:{display:"flex",alignItems:"center",gap:6,padding:"2px 4px",borderRadius:6,transform:Fu.Transform.toString(c),transition:d,position:"relative",zIndex:g?2:void 0,background:g?"var(--accent, color-mix(in srgb, currentColor 8%, transparent))":void 0,opacity:o&&!g?0.55:1},children:[At("button",{type:"button",ref:l,"aria-label":t,title:t,disabled:n,...r,...s,style:{display:"inline-flex",padding:0,border:0,background:"transparent",color:"inherit",cursor:n?"default":g?"grabbing":"grab",touchAction:"none"},children:At(xe,{name:"grip"})}),i]})}function Is({ui:e,checked:t,label:n,onChange:o}){if(e?.Switch)return e.Switch({checked:t,onChange:o,"aria-label":n});return At("input",{type:"checkbox","aria-label":n,checked:t,onChange:(i)=>o(i.currentTarget.checked)})}import{useEffect as Ls,useMemo as Vu,useRef as Vs,useState as qt}from"react";var Fs=50,Rr=1000,Ts=100;function Oa(e,t){let n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}function Es(e){let t=new Set,n=[],o=0;for(let i of e){o+=i.skipped;for(let r of i.changes){if(t.has(r.key)){o+=1;continue}t.add(r.key),n.push(r)}}return{changes:n,skipped:o}}var Nu=new Set(["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"]);function La(e){return e.filter((t)=>Nu.has(t.type)&&!tt(t)&&t.generation!=="autoIncrement")}var Ds=(e)=>e===null||e===void 0||e===""||Array.isArray(e)&&e.length===0,Ou=(e,t)=>Ds(e)&&Ds(t)?!0:JSON.stringify(e)===JSON.stringify(t);function Lu(e,t){if(t===null)return e.required?void 0:null;switch(e.type){case"singleLineText":case"longText":return typeof t==="string"||typeof t==="number"?String(t):void 0;case"number":{let n=typeof t==="string"&&t.trim()!==""?Number(t):t;return typeof n==="number"&&Number.isFinite(n)?n:void 0}case"checkbox":return typeof t==="boolean"?t:void 0;case"date":return typeof t==="string"&&!Number.isNaN(Date.parse(t))?t:void 0;case"singleSelect":case"multipleSelect":{let n=(i)=>e.options?.find((r)=>r.id===i||r.name===i)?.id;if(e.type==="singleSelect")return n(t);if(!Array.isArray(t))return;let o=t.map(n);return o.every((i)=>i!==void 0)?o:void 0}default:return}}function Ms(e,t,n,o){let i=new Map(La(e).filter((c)=>n.includes(c.id)).map((c)=>[c.id,c])),r=new Map(t.map((c)=>[c.id,c])),s=[],a=new Set,l=0;for(let c of o){let d=r.get(c.recordId);if(!d){l+=Object.keys(c.values).length;continue}for(let[g,f]of Object.entries(c.values)){let u=i.get(g),x=`${d.id}:${g}`,b=u?Lu(u,f):void 0;if(!u||b===void 0||a.has(x)||Ou(d.values[g],b)){l+=1;continue}a.add(x),s.push({key:x,recordId:d.id,expectedVersion:d.version,fieldId:g,before:d.values[g]??null,after:b,...c.reason?{reason:c.reason}:{}})}}return{changes:s,skipped:l}}function Ns(e){let t=new Map;for(let n of e){let o=t.get(n.recordId)??{op:"update",id:n.recordId,expectedVersion:n.expectedVersion,values:{}};o.values[n.fieldId]=n.after,t.set(n.recordId,o)}return[...t.values()]}function Os(e,t){let n=new Map(t.map((i)=>[i.id,i.version])),o=new Map;for(let i of e){let r=n.get(i.recordId);if(r===void 0)continue;let s=o.get(i.recordId)??{op:"update",id:i.recordId,expectedVersion:r,values:{}};s.values[i.fieldId]=i.before,o.set(i.recordId,s)}return[...o.values()]}import{jsx as $e,jsxs as kt,Fragment as Bs}from"react/jsx-runtime";var Bu=[{id:"empty",label:"Fill empty cells",text:"Fill the empty target cells using the other fields of the same record."},{id:"translate",label:"Translate to English",text:"Translate the target fields into English and keep proper nouns."},{id:"summarize",label:"Summarize",text:"Write a one-sentence summary of each record for the target fields."},{id:"classify",label:"Classify",text:"Pick the best matching option for each record from the allowed options."}],bt={border:"var(--border, #d5d9df)",background:"var(--background, white)",muted:"var(--muted, #f4f5f7)",faint:"var(--muted-foreground, #6b7280)",primary:"var(--primary, #2563eb)"},Pt={drawer:{position:"fixed",top:0,right:0,bottom:0,zIndex:80,width:"min(440px, 100vw)",display:"flex",flexDirection:"column",background:bt.background,color:"inherit",borderLeft:`1px solid ${bt.border}`,boxShadow:"-12px 0 32px color-mix(in srgb, currentColor 14%, transparent)"},head:{display:"flex",alignItems:"center",gap:8,padding:"12px 14px",borderBottom:`1px solid ${bt.border}`},body:{flex:1,minHeight:0,overflowY:"auto",padding:14,display:"grid",gap:14,alignContent:"start"},label:{display:"grid",gap:6,fontSize:12,color:bt.faint},chips:{display:"flex",flexWrap:"wrap",gap:6},textarea:{width:"100%",boxSizing:"border-box",minHeight:84,resize:"vertical",padding:8,borderRadius:6,border:`1px solid ${bt.border}`,background:bt.background,color:"inherit",font:"inherit"},foot:{display:"flex",alignItems:"center",gap:8,padding:"10px 14px",borderTop:`1px solid ${bt.border}`},group:{border:`1px solid ${bt.border}`,borderRadius:8,overflow:"hidden"},groupHead:{padding:"6px 10px",background:bt.muted,fontSize:12,fontWeight:600},change:{display:"grid",gridTemplateColumns:"auto 1fr",gap:8,padding:"8px 10px",borderTop:`1px solid ${bt.border}`,fontSize:13},before:{color:bt.faint,textDecoration:"line-through",overflowWrap:"anywhere"},after:{fontWeight:500,overflowWrap:"anywhere"},reason:{fontSize:12,color:bt.faint,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"}},Ir=(e)=>({padding:"3px 10px",borderRadius:999,fontSize:12,cursor:"pointer",border:`1px solid ${e?bt.primary:bt.border}`,background:e?"color-mix(in srgb, var(--primary, #2563eb) 14%, transparent)":"transparent",color:"inherit"});function Us(e){let{table:t,rows:n,selection:o,aiFillClient:i}=e,r=le(e.locale),s=Vu(()=>La(t.fields),[t.fields]),[a,l]=qt(o.recordIds.length?"selected":"page"),[c,d]=qt(()=>{let V=s.filter((de)=>o.fieldIds.includes(de.id)).map((de)=>de.id);return V.length?V:s.map((de)=>de.id)}),[g,f]=qt(""),[u,x]=qt([]),[b,v]=qt(""),[y,C]=qt("idle"),[p,k]=qt(),[P,M]=qt(new Set),[B,R]=qt(""),[A,_]=qt(""),[L,w]=qt(!1),[N,O]=qt(),[D,J]=qt([]),[T,j]=qt(),H=Vs(null),me=Vs(null);Ls(()=>{let V=!0;return i.models?.().then((de)=>{if(V&&de.ok)x(de.data),v((we)=>we||de.data[0]?.id||"")}),()=>{V=!1,H.current?.abort()}},[i]),Ls(()=>{me.current?.focus()},[]);let Z=n.filter((V)=>o.recordIds.includes(V.id)),fe=Math.min(e.total??n.length,Rr),X=a==="selected"?Z.length:a==="page"?n.length:fe,K=(V)=>t.fields.find((de)=>de.id===V),ee=y!=="running"&&X>0&&c.length>0&&g.trim()!=="",ae=async(V)=>{if(a==="selected")return Z;if(a==="page"||!e.query)return n.slice(0,Rr);let de=[],we;do{let Pe=await e.client.query(t.id,{...e.query,limit:100,...we?{cursor:we}:{}});if(!Pe.ok)throw Error(Pe.error.message);de.push(...Pe.data.items),we=Pe.data.nextCursor??void 0}while(we&&de.length<Rr&&!V.aborted);return de.slice(0,Rr)},he=async(V,de)=>{let we=new AbortController;H.current=we,C("running"),_("");let Pe=[...de],Ae=[],Qe=[],Ft="",Qt=Oa(V,Fs);O({done:0,total:Qt.length,failed:Ae,error:""});for(let[Lt,ht]of Qt.entries()){if(we.signal.aborted)break;let Tt=await i.fill({tableId:t.id,fields:t.fields,instruction:g.trim(),targetFieldIds:c,records:ht,...b?{model:b}:{}},{signal:we.signal}).catch((He)=>({ok:!1,error:{code:"unknown",message:He instanceof Error?He.message:typeof He==="object"&&He&&("message"in He)?String(He.message):String(He)}}));if(we.signal.aborted)break;if(Tt.ok){Pe.push(Ms(t.fields,ht,c,Tt.data.suggestions));let He=[Tt.data.summary,Tt.data.usage].filter(Boolean).join(" · ");if(He)Qe.push(Qt.length>1?`${Lt+1}/${Qt.length} ${He}`:He)}else Ae.push(...ht),Ft=Tt.error.message;O({done:Lt+1,total:Qt.length,failed:[...Ae],error:Ft})}let co=Es(Pe);if(!co.changes.length&&!Pe.length){_(Ft||r("No changes were suggested.")),C("idle");return}k(co),M(new Set(co.changes.map((Lt)=>Lt.key))),R(Qe.join(`
|
|
26
|
+
`)),C("review")},Ce=async()=>{let V=new AbortController;H.current=V,C("running"),_(""),j(void 0),k(void 0),O(void 0);let de;try{de=await ae(V.signal)}catch(we){_(we instanceof Error?we.message:String(we)),C("idle");return}if(V.signal.aborted){C("idle");return}J(de),await he(de,[])},re=async()=>{if(!N?.failed.length)return;await he(N.failed,p?[p]:[])},Se=()=>H.current?.abort(),pe=async(V)=>{let de=[];for(let we of Oa(V,Ts)){let Pe=await e.client.mutate(t.id,{idempotencyKey:crypto.randomUUID(),items:we});if(!Pe.ok)return{ok:!1,error:Pe.error,committedRecords:de};de.push(...Pe.data.items),e.onCommitted(Pe.data)}return{ok:!0,committedRecords:de}},qe=async()=>{if(!p)return;let V=p.changes.filter((Ae)=>P.has(Ae.key));if(!V.length)return;w(!0),_("");let de=await pe(Ns(V));w(!1);let we=new Set(de.committedRecords.map((Ae)=>Ae.id)),Pe=V.filter((Ae)=>we.has(Ae.recordId));if(Pe.length)j({changes:Pe,records:de.committedRecords});if(!de.ok){let Ae=de.error.code==="version_conflict"?r("Some records changed since the preview. Generate again to review the latest values."):de.error.message;if(_(Pe.length?`${r("Applied {count} AI changes",{count:Pe.length})} · ${Ae}`:Ae),Pe.length){let Qe=p.changes.filter((Ft)=>!we.has(Ft.recordId));k({changes:Qe,skipped:p.skipped})}return}e.onNotify?.(r("Applied {count} AI changes",{count:V.length})),k(void 0),O(void 0),C("idle")},S=async()=>{if(!T)return;w(!0);let V=await pe(Os(T.changes,T.records));if(w(!1),!V.ok){_(V.error.message);return}e.onNotify?.(r("AI changes undone")),j(void 0)},F=new Map;for(let V of p?.changes??[])F.set(V.recordId,[...F.get(V.recordId)??[],V]);let Y=(V,de)=>V.includes(de)?V.filter((we)=>we!==de):[...V,de];return kt("aside",{ref:me,tabIndex:-1,"aria-label":r("AI fill"),"data-uibot":"ai-fill-drawer",style:Pt.drawer,onKeyDown:(V)=>{if(V.key==="Escape"&&!V.nativeEvent.isComposing)V.stopPropagation(),e.onClose()},children:[kt("div",{style:Pt.head,children:[$e(xe,{name:"sparkles"}),$e("strong",{style:{flex:1},children:r("AI fill")}),$e(G,{ui:e.ui,variant:"ghost",size:"icon",icon:"x",iconOnly:!0,ariaLabel:r("Close"),onClick:e.onClose})]}),kt("div",{style:Pt.body,children:[kt("div",{style:Pt.label,children:[r("Records in scope"),$e(Ge,{ui:e.ui,label:r("Records in scope"),value:a,onChange:(V)=>l(V),options:[{value:"selected",label:r("Selected records ({count})",{count:Z.length}),disabled:Z.length===0},{value:"page",label:r("Loaded records ({count})",{count:n.length})},...e.query?[{value:"view",label:r("All records in this view ({count})",{count:fe})}]:[]]})]}),kt("fieldset",{style:{...Pt.label,border:0,margin:0,padding:0},children:[$e("legend",{style:{padding:0,marginBottom:6},children:r("Fields to fill")}),$e("div",{style:Pt.chips,children:s.map((V)=>$e("button",{type:"button","aria-pressed":c.includes(V.id),style:Ir(c.includes(V.id)),onClick:()=>d(Y(c,V.id)),children:V.name},V.id))})]}),kt("label",{style:Pt.label,children:[r("Instruction"),$e("textarea",{style:Pt.textarea,value:g,placeholder:r("Describe what to fill or change"),onChange:(V)=>f(V.target.value),onKeyDown:(V)=>{if(V.key==="Enter"&&(V.metaKey||V.ctrlKey)&&ee)V.preventDefault(),Ce()}}),$e("span",{style:Pt.chips,children:Bu.map((V)=>$e("button",{type:"button",style:Ir(!1),onClick:()=>f(r(V.text)),children:r(V.label)},V.id))})]}),u.length>0&&kt("div",{style:Pt.label,children:[r("Model"),$e(Ge,{ui:e.ui,label:r("Model"),value:b,onChange:v,options:u.map((V)=>({value:V.id,label:V.label}))})]}),A&&$e("p",{role:"alert",style:{margin:0,color:"var(--destructive, #b42318)"},children:A}),T&&kt("p",{role:"status",style:{margin:0},children:[r("Applied {count} AI changes",{count:T.changes.length})," ",$e("button",{type:"button",style:Ir(!1),disabled:L,onClick:()=>void S(),children:r("Undo")})]}),y!=="running"&&N&&N.failed.length>0&&kt("p",{role:"alert",style:{margin:0,color:"var(--destructive, #b42318)"},children:[r("{count} records could not be processed: {reason}",{count:N.failed.length,reason:N.error})," ",$e("button",{type:"button",style:Ir(!1),onClick:()=>void re(),children:r("Retry failed")})]}),y==="review"&&p&&kt("section",{"aria-label":r("Suggestions"),style:{display:"grid",gap:10},children:[kt("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:bt.faint},children:[kt("span",{style:{flex:1},children:[r("{count} suggested changes",{count:p.changes.length}),p.skipped?` · ${r("Skipped {count} cells",{count:p.skipped})}`:""]}),p.changes.length>0&&$e("button",{type:"button",style:Ir(!1),onClick:()=>M(P.size===p.changes.length?new Set:new Set(p.changes.map((V)=>V.key))),children:P.size===p.changes.length?r("Select none"):r("Select all")})]}),B&&$e("p",{style:{margin:0,fontSize:12,color:bt.faint,whiteSpace:"pre-wrap"},children:B}),p.changes.length===0&&$e("p",{style:{margin:0},children:r("No changes were suggested.")}),[...F.entries()].map(([V,de])=>{let we=D.find((Pe)=>Pe.id===V);return kt("div",{style:Pt.group,children:[$e("div",{style:Pt.groupHead,children:we?Bt(we,t.fields):V}),de.map((Pe)=>{let Ae=K(Pe.fieldId);if(!Ae)return null;let Qe=Sn(Pe.before,Ae);return kt("label",{style:Pt.change,children:[$e("input",{type:"checkbox",checked:P.has(Pe.key),"aria-label":`${Ae.name} ${V}`,onChange:()=>M(new Set(Y([...P],Pe.key)))}),kt("span",{style:{display:"grid",gap:2},children:[$e("span",{style:{fontSize:12,color:bt.faint},children:Ae.name}),Qe&&$e("span",{style:Pt.before,children:Qe}),$e("span",{style:Pt.after,children:Sn(Pe.after,Ae)||r("(empty)")}),Pe.reason&&$e("span",{title:Pe.reason,style:Pt.reason,children:Pe.reason})]})]},Pe.key)})]},V)})]})]}),$e("div",{style:Pt.foot,children:y==="running"?kt(Bs,{children:[$e("span",{role:"status",style:{flex:1,color:bt.faint},children:N&&N.total>1?r("Generating batch {done} of {total}…",{done:Math.min(N.done+1,N.total),total:N.total}):r("Generating suggestions…")}),$e(G,{ui:e.ui,variant:"outline",size:"sm",onClick:Se,children:r("Stop")})]}):y==="review"&&p&&p.changes.length>0?kt(Bs,{children:[$e(G,{ui:e.ui,variant:"default",size:"sm",disabled:L||P.size===0,onClick:()=>void qe(),children:r("Apply {count} changes",{count:P.size})}),$e(G,{ui:e.ui,variant:"outline",size:"sm",disabled:!ee,onClick:()=>void Ce(),children:r("Regenerate")})]}):$e(G,{ui:e.ui,variant:"default",size:"sm",disabled:!ee,onClick:()=>void Ce(),children:r("Generate preview")})})]})}import{jsx as z,jsxs as Be,Fragment as Dr}from"react/jsx-runtime";var _s={grid:"New grid view",kanban:"New kanban view",gallery:"New gallery view",calendar:"New calendar view",form:"New form view"},Uu=(e,t)=>{let n=sl(e,t);return n?.length?{sort:n}:{}},xi=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Ar(e,t){let[n,o]=Ve({loading:!0}),[i,r]=Ve(0);return Dt(()=>{let a=e();if(!a){o({loading:!1,scope:t,tick:i});return}let l=!0;return o((c)=>({...c.scope?.length===t.length&&c.scope.every((d,g)=>Object.is(d,t[g]))?c:{},loading:!0,scope:t,tick:i})),a.then((c)=>{if(!l)return;o(c.ok?{data:c.data,loading:!1,scope:t,tick:i}:{error:c.error.message,errorCode:c.error.code,loading:!1,scope:t,tick:i})}).catch((c)=>{if(l)o({error:c instanceof Error?c.message:String(c),loading:!1,scope:t,tick:i})}),()=>{l=!1}},[...t,i]),{...n.tick===i&&n.scope?.length===t.length&&n.scope.every((a,l)=>Object.is(a,t[l]))?n:{loading:!0,data:void 0,error:void 0,errorCode:void 0},reload:()=>r((a)=>a+1)}}function CC(e){let{client:t,requestApproval:n}=e,o=jn(()=>gs(t,n),[t,n]),i=jn(()=>{if(e.aggregateClient)return e.aggregateClient;let h=t.aggregate;if(!h)return;return{async aggregate(q,oe){let ie=await h.call(t,q,{...oe.filter?{filter:oe.filter}:{},...oe.search!==void 0?{search:oe.search}:{},groupBy:oe.groupBy,aggregates:oe.aggregates.map((ye)=>({fn:ye.fn,...ye.fieldId?{field:ye.fieldId}:{},as:ye.as}))});return ie.ok?{ok:!0,data:Za(oe,ie.data)}:ie}}},[e.aggregateClient,t]),r=on([]),s=jn(()=>e.getRelationOptions??ys(o,()=>r.current),[e.getRelationOptions,o]),a=le(e.locale),l=jn(()=>vt({preset:"full",...e.features}),[e.features]),c=e.pageSize??50,d=Ar(()=>o.list(),[o]);r.current=d.data??[];let[g,f]=Ve(e.tableId),u=e.tableId??g??d.data?.[0]?.id,x=on(e);x.current=e;let b=on(null),v=Va((h)=>{if(x.current.onBeforeNavigate?.(h)!==!1)return!0;let q=b.current;return requestAnimationFrame(()=>q?.isConnected&&q.focus({preventScroll:!0})),!1},[]),y=e.onTableChange,C=Va((h)=>{if(!v({tableId:h}))return!1;return f(h),y?.(h),!0},[y,v]),p=Ar(()=>e.capabilities||!o.capabilities?void 0:o.capabilities(u),[o,u,e.capabilities]),k=e.capabilities??p.data??{read:!0,write:!0,schema:!0},P=k.schema&&l.schemaEditor,M=k.write&&l.rowCreate,B=k.write&&l.rowUpdate,R=k.write&&l.rowDelete,A=(k.views??k.schema)&&l.viewManagement,_=Boolean(u&&d.data?.some((h)=>h.id===u)),L=Ar(()=>u&&_?o.describe(u):void 0,[o,u,_]),w=!L.loading&&L.data?.id===u?L.data:void 0,N=Ar(()=>u&&w?o.views(u):void 0,[o,u,Boolean(w)]),[O,D]=Ve([]),[J,T]=Ve(""),j=e.viewId??J,H=on({client:t,tableId:u,id:j});if(H.current.client!==t||H.current.tableId!==u||H.current.id!==j)H.current={client:t,tableId:u,id:j};let[me,Z]=Ve(),fe=me?.client===t&&me.tableId===u,X=fe&&me.snapshot===N.data,[K,ee]=Ve({});Dt(()=>{if(!N.data||N.loading)return;Z({client:t,tableId:u,snapshot:N.data}),D(N.data),ee({}),T((h)=>{let q=N.data??[];if(fe&&q.some((oe)=>oe.id===h))return h;return q.find((oe)=>oe.id===e.initialViewId)?.id??q[0]?.id??""})},[N.data,N.loading,e.initialViewId,t,u]);let ae=on({client:t,ids:new Map});if(ae.current.client!==t)ae.current={client:t,ids:new Map};let he=ae.current.ids;Dt(()=>{if(u&&N.data?.length)he.delete(u)},[he,u,N.data]);let Ce=N.data?.length===0?w?.id:void 0,re=le(e.locale)("All records"),Se=jn(()=>{if(!Ce)return;let h=he.get(Ce);if(!h)h=e.createViewId?.(Ce)??`default-${Ce}`,he.set(Ce,h);return{id:h,name:re,version:0,type:"grid",columnOrder:[],hiddenColumns:[],columnWidths:{}}},[he,Ce,re,e.createViewId]);Dt(()=>{if(!Se||!N.data||N.data.length>0)return;if(N.loading||L.data?.id!==u)return;ee((h)=>h[Se.id]?h:{...h,[Se.id]:Se}),T(Se.id)},[Se,N.data,N.loading,L.data?.id,u]);let pe=e.inlineViewControls===!0,qe=O.find((h)=>h.id===j),S=X&&w&&!N.loading&&!N.error?K[j]??qe:void 0,F=on(void 0);Dt(()=>{if(!S)return;let h=F.current;if(h?.client===t&&h.tableId===u)return;F.current={client:t,tableId:u},x.current.onViewChange?.(S,"initialize")},[t,u,S]);let[Y,V]=Ve({recordIds:[],fieldIds:[]}),[de,we]=Ve(!1),[Pe,Ae]=Ve(!1),[Qe,Ft]=Ve(null);Dt(()=>{if(!Qe||!S||u!==Qe.tableId)return;if(L.data?.id!==Qe.tableId||N.loading||O!==N.data)return;ee((h)=>({...h,[S.id]:{...S,filter:Qe.filter}})),Ft(null)},[Qe,S,u,L.data?.id,N.loading,N.data,O]),Dt(()=>{V({recordIds:[],fieldIds:[]}),we(!1)},[u]);let Qt=jn(()=>{if(!w)return[];let h=d.data??[],q=w.fields.flatMap((ie)=>{let ye=ie.relation&&h.find((it)=>it.id===ie.relation?.collectionId);return ye?[{key:`to:${ie.id}`,label:a("Open {name}",{name:ye.name}),needsRecord:!1,open:()=>C(ye.id)}]:[]}),oe=h.flatMap((ie)=>ie.id===w.id?[]:ie.fields.filter((ye)=>ye.relation?.collectionId===w.id).map((ye)=>({key:`from:${ie.id}:${ye.id}`,label:a("{name} · inverse records",{name:ie.name}),needsRecord:!0,open:()=>{let it=Y.recordIds[0];if(!it)return;if(!C(ie.id))return;Ft({tableId:ie.id,filter:{conjunction:"and",filterSet:[{fieldId:ye.id,operator:"is",value:it}]}})}})));return[...q,...oe]},[w,d.data,Y.recordIds,a,C]),co=Boolean(S&&Se&&S.id===Se.id&&xi(S,Se)),Lt=Boolean(S&&!co&&(!qe||!xi(qe,S))),ht=[...O,...Object.values(K).filter((h)=>!O.some((q)=>q.id===h.id)&&!(h.id===Se?.id&&O.length>0))],[Tt,He]=Ve(null),[Ze,uo]=Ve(!1),Ct=(h,q=!1)=>{if(h&&!q&&e.onNotify){e.onNotify(h),He(null);return}He(h?{text:h,error:q}:null)},or=on(!1),Wn=on(0),Zt=on(u);Zt.current=u,Dt(()=>{Wn.current+=1},[t]);async function zt(h,q){if(or.current)return;or.current=!0;let oe={client:Wn.current,table:Zt.current};uo(!0),Ct("");try{let ie=await h();if(oe.client!==Wn.current)return;if(ie.ok)q(ie.data,oe.table===Zt.current);else Ct(ie.error.message,!0)}catch(ie){if(oe.client!==Wn.current)return;Ct(ie instanceof Error?ie.message:a("Saving failed. Your edit has been kept."),!0)}finally{or.current=!1,uo(!1)}}let je=(h)=>{ee((q)=>({...q,[h.id]:h})),He((q)=>q?.error?null:q)},No=(h)=>{if(h===j)return;let q=K[h]??O.find((oe)=>oe.id===h);if(!q||!u||!v({tableId:u,viewId:h}))return;if(e.viewId===void 0)T(h);x.current.onViewChange?.(q,"select")},et=(h)=>{if(!u||!v({tableId:u,viewId:h.id}))return;if(ee((q)=>({...q,[h.id]:h})),e.viewId===void 0)T(h.id);x.current.onViewChange?.(h,"create")},En=(h,q)=>{if(!u)return;let oe=O.find((ye)=>ye.id===h.id),ie=H.current;if(h.id!==ie.id&&!v({tableId:u,viewId:h.id}))return;zt(async()=>{let ye={expectedVersion:oe?.version??0,view:h};return o.saveView(u,{...ye,idempotencyKey:Jn(`view:${h.id}`,ye)})},(ye,it)=>{if(Et(`view:${h.id}`),!it)return;if(D((ut)=>ut.some((en)=>en.id===ye.id)?ut.map((en)=>en.id===ye.id?ye:en):[...ut,ye]),ee((ut)=>{let{[ye.id]:en,...Rt}=ut;return Rt}),H.current===ie){if(x.current.viewId===void 0)T(ye.id);x.current.onViewChange?.(ye,"save")}if(!pe)Ct(a("View saved"));q?.(ye)})},Fe=pe&&Lt&&A&&!Ze&&!Tt?.error&&!!S?.name.trim();Dt(()=>{if(!Fe||!S)return;let h=setTimeout(()=>En(S),600);return()=>clearTimeout(h)},[Fe,S]);let[rn,Vt]=Ve(""),go=()=>{let h=ht.find((ut)=>ut.id===rn),q=o.deleteView;if(!h||!u)return;let ie=ht.filter((ut)=>ut.id!==h.id)[0],ye=H.current;if(j===h.id&&(!ie||!v({tableId:u,viewId:ie.id})))return;Vt("");let it=()=>{if(D((ut)=>ut.filter((en)=>en.id!==h.id)),ee((ut)=>{let{[h.id]:en,...Rt}=ut;return Rt}),ye===H.current&&j===h.id&&ie){if(x.current.viewId===void 0)T(ie.id);x.current.onViewChange?.(ie,"delete")}};if(!O.some((ut)=>ut.id===h.id))return it();if(!q)return;zt(()=>q.call(o,u,{viewId:h.id,expectedVersion:h.version,idempotencyKey:Jn(`delete:${h.id}`,h)}),(ut,en)=>{if(Et(`delete:${h.id}`),!en)return;Ct(a("View deleted")),it()})},[Mn,rr]=Ve(0),[dt,ir]=Ve(null),an=pe&&dt&&dt.viewId===S?.id?dt.text:S?.search??"",ar=(h)=>{if(pe&&S)ir({viewId:S.id,text:h});else if(S)je({...S,search:h})},Oo=jn(()=>({limit:c,search:an,...S?.filter?{filter:S.filter}:{},...Uu(S,w?.fields)}),[S,an,w?.fields,c]),Lo=JSON.stringify(Oo),ln=JSON.stringify([u,j,Lo]),[Vo,$t]=Ve({client:o,scope:ln,cursor:void 0,history:[]}),po=Vo.client===o&&Vo.scope===ln,St=po?Vo.cursor:void 0,Ht=po?Vo.history:[];Dt(()=>{$t({client:o,scope:ln,cursor:void 0,history:[]})},[o,ln]);let sn=(h)=>$t((q)=>({client:o,scope:ln,cursor:h,history:q.client===o&&q.scope===ln?q.history:[]})),Gn=(h)=>$t((q)=>({client:o,scope:ln,history:h,cursor:q.client===o&&q.scope===ln?q.cursor:void 0})),Bo=(S?.type??"grid")==="grid",mt=Ar(()=>u&&w&&S&&Bo?o.query(u,{...Oo,...St?{cursor:St}:{}}):void 0,[o,u,w?.schemaVersion,Boolean(S),Lo,St,Bo,Mn]),Fr=()=>{if(u&&!v({tableId:u,...S?{viewId:S.id}:{}}))return;L.reload(),N.reload(),rr((h)=>h+1)},ct=Va(()=>rr((h)=>h+1),[]),[We,Xt]=Ve("");Dt(()=>{Xt(""),Ae(!1)},[t,u,j]);let[vn,Uo]=Ve(!1),[dn,mo]=Ve(""),[Yn,cn]=Ve(""),fo=on({}),Jn=(h,q)=>{let oe=JSON.stringify(q),ie=fo.current[h];if(ie?.fingerprint===oe)return ie.key;let ye=crypto.randomUUID();return fo.current[h]={fingerprint:oe,key:ye},ye},Et=(h)=>{delete fo.current[h]},[Qn,yo]=Ve(""),[Nn,lr]=Ve([]),sr=jn(()=>[{fn:"count",as:"records"},...Yn?[{fn:"sum",fieldId:Yn,as:"sum"}]:[]],[Yn]),wi=jn(()=>{let h=le(e.locale),q=w?.fields.find((oe)=>oe.id===Yn);return{records:h("Records"),...q?{sum:h("Sum of {name}",{name:q.name})}:{}}},[e.locale,w,Yn]);Dt(()=>cn(""),[u]);let[xn,dr]=Ve([]),[On,Tr]=Ve(""),[cr,Er]=Ve(),Zn=(h)=>{Er(h),dr(structuredClone(w?.fields??[])),Tr(w?.name??""),ce("schema")},m=We==="schema"&&(!xi(xn,w?.fields)||On!==(w?.name??"")),I=We==="create"&&(Qn.trim()!==""||!xi(Nn,[{id:"name",name:a("Name"),type:"singleLineText",required:!0}])),[E,ne]=Ve(!1),[W,U]=Ve(!1),te=on(null),Re=on(null),ce=(h)=>{if(document.activeElement instanceof HTMLElement)Re.current=document.activeElement;Xt(h)},ve=()=>{Ae(!1),Xt("");let h=Re.current;if(Re.current=null,h)requestAnimationFrame(()=>h.isConnected&&h.focus())};Dt(()=>{if(!We)return;let h=requestAnimationFrame(()=>te.current?.querySelector("[data-uibot-panel] input:not([disabled]), [data-uibot-panel] textarea:not([disabled])")?.focus());return()=>cancelAnimationFrame(h)},[We]),Dt(()=>{if(We!=="add"&&We!=="record")ne(!1),U(!1)},[We]);let ue=()=>{if(m||I||(We==="add"||We==="record")&&E)Ae(!0);else ve()},Me=(h)=>(q)=>{if(q.nativeEvent.isComposing)return;if(q.key==="Escape"){if(q.stopPropagation(),!Ze&&!W)ue()}else if(h&&q.key==="Enter"&&(q.ctrlKey||q.metaKey)&&!Ze)q.preventDefault(),h()},ur=Wa(),zs=(We==="add"||We==="record")&&E,$s=(We==="add"||We==="record")&&W,Hs=Lt||m||I||ur.dirty||zs,Ks=Ze||ur.busy||$s;wn({dirty:Hs,busy:Ks},e);let Ba=()=>{if(!Qn.trim()||Nn.length===0)return;zt(()=>{let h={name:Qn.trim(),fields:Nn};return o.create({...h,idempotencyKey:Jn("create",h)})},(h,q)=>{if(Et("create"),d.reload(),!q)return;ve(),C(h.id)})},Ua=()=>void _o({fields:xn,name:On.trim()}).then(()=>{ve(),Ct(a("Fields saved"))}).catch((h)=>Ct(h instanceof Error?h.message:String(h),!0)),_o=(h)=>new Promise((q,oe)=>{if(!u||!w)return oe(Error(a("Choose a table first.")));uo(!0);let ie={client:Wn.current,table:Zt.current};o.updateSchema(u,{expectedSchemaVersion:w.schemaVersion,name:h.name??w.name,fields:h.fields??w.fields,...h.icon??w.icon?{icon:h.icon??w.icon}:{},idempotencyKey:Jn("schema",{version:w.schemaVersion,name:h.name??w.name,fields:h.fields??w.fields,icon:h.icon??w.icon})}).then((ye)=>{if(ie.client!==Wn.current||ie.table!==Zt.current)return q();if(!ye.ok)return oe(Error(ye.error.message));Et("schema"),N.reload(),L.reload(),d.reload(),sn(void 0),Gn([]),q()}).catch(oe).finally(()=>uo(!1))}),[Pi,ki]=Ve(""),[Xn,Si]=Ve("");Dt(()=>Si(""),[u,S?.id]);let[Mr,_a]=Ve("");Dt(()=>{if(!Mr||!w?.fields.some((h)=>h.id===Mr))return;_a(""),Zn(Mr)},[Mr,w]);let qa=()=>{let h=w?.fields??[],q=(S?.columnOrder??[]).filter((oe)=>h.some((ie)=>ie.id===oe));return[...q,...h.map((oe)=>oe.id).filter((oe)=>!q.includes(oe))]},za=(h,q)=>{if(!w||!S)return;let oe={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:a("New field"),type:"singleLineText"},ie=qa();ie.splice(Math.max(0,ie.indexOf(h)+(q==="right"?1:0)),0,oe.id);let ye=[...w.fields];ye.splice(w.fields.findIndex((it)=>it.id===h)+(q==="right"?1:0),0,oe),_o({fields:ye}).then(()=>{je({...S,columnOrder:ie}),_a(oe.id)}).catch((it)=>Ct(it instanceof Error?it.message:String(it),!0))},js=(h)=>{if(!w)return;let q={...structuredClone(h),id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:a("{name} copy",{name:h.name})};delete q.required;let oe=[...w.fields];oe.splice(w.fields.findIndex((ie)=>ie.id===h.id)+1,0,q),_o({fields:oe}).then(()=>Ct(a("Field duplicated"))).catch((ie)=>Ct(ie instanceof Error?ie.message:String(ie),!0))},Ws=()=>{let h=Pi;if(ki(""),!w||!h)return;_o({fields:w.fields.filter((q)=>q.id!==h)}).then(()=>Ct(a("Field deleted"))).catch((q)=>Ct(q instanceof Error?q.message:String(q),!0))},Gs=(h)=>{if(!w||!S)return[];let q=w.fields[0]?.id===h.id,oe=tn(h)&&h.type!=="linkedRecord",ie=h.type==="singleSelect"||h.type==="checkbox",ye=(S.type??"grid")==="grid"&&l.groupBy&&ie,it=S.groupByFieldId===h.id,ut=A&&l.viewTypes.includes("kanban")&&ie,en=!["relation","lookup","rollup"].includes(h.type),Rt=[];if(P){if(Rt.push({id:"edit",icon:z(xe,{name:"pencil"}),label:a("Edit field"),onSelect:()=>Zn(h.id)}),en)Rt.push({id:"duplicate",icon:z(xe,{name:"copy"}),label:a("Duplicate field"),onSelect:()=>js(h)})}if(l.columns)Rt.push({id:"hide",icon:z(xe,{name:"eyeOff"}),label:a("Hide field"),disabled:q||S.type==="form"&&h.required===!0,onSelect:()=>je({...S,hiddenColumns:[...S.hiddenColumns,h.id]})});if(A&&l.columnColors&&(S.type??"grid")==="grid")Rt.push({id:"column-color",icon:z(xe,{name:"palette"}),label:a("Column color"),separatorBefore:!0,onSelect:()=>Si(h.id)});let Or=qa().filter((ft)=>!S.hiddenColumns.includes(ft)).indexOf(h.id)+1,Ka=l.columnFreezing&&(S.type??"grid")==="grid"&&Or>0&&Or<=4;if(Ka){let ft=S.frozenColumnCount===Or;Rt.push({id:"freeze",icon:z(xe,{name:"freeze"}),label:a(ft?"Unfreeze columns":"Freeze up to this field"),separatorBefore:!0,onSelect:()=>{let Ln={...S};if(ft)delete Ln.frozenColumnCount;else Ln.frozenColumnCount=Or;je(Ln)}})}if(P)Rt.push({id:"insert-left",icon:z(xe,{name:"arrowLeft"}),label:a("Insert field left"),separatorBefore:!Ka,onSelect:()=>za(h.id,"left")},{id:"insert-right",icon:z(xe,{name:"arrowRight"}),label:a("Insert field right"),onSelect:()=>za(h.id,"right")});if(oe&&l.sorting){let ft=S.sort?.length===1?S.sort[0]:void 0,Ln=ft?.fieldId===h.id?ft.direction:void 0;Rt.push({id:"sort-asc",icon:z(xe,{name:"sortAsc"}),label:a("Sort {name} ascending",{name:h.name}),separatorBefore:!0,disabled:Ln==="asc",onSelect:()=>je({...S,sort:[{fieldId:h.id,direction:"asc"}]})},{id:"sort-desc",icon:z(xe,{name:"sortDesc"}),label:a("Sort {name} descending",{name:h.name}),disabled:Ln==="desc",onSelect:()=>je({...S,sort:[{fieldId:h.id,direction:"desc"}]})})}if(l.filter&&tn(h)&&h.type!=="linkedRecord")Rt.push({id:"filter",icon:z(xe,{name:"filter"}),label:a("Filter by {name}",{name:h.name}),separatorBefore:!ye&&!ut&&!(oe&&l.sorting),onSelect:()=>{let ft=S.filter,Ln={fieldId:h.id,operator:"isNotEmpty"};je({...S,filter:ft?{...ft,filterSet:[...ft.filterSet,Ln]}:{conjunction:"and",filterSet:[Ln]}})}});if(ye)Rt.push({id:"group",icon:z(xe,{name:"group"}),label:a(it?"Ungroup by {name}":"Group by {name}",{name:h.name}),separatorBefore:!0,onSelect:()=>{let ft={...S};if(it)delete ft.groupByFieldId;else ft.groupByFieldId=h.id;je(ft)}});if(ut)Rt.push({id:"kanban",icon:z(xe,{name:"kanban"}),label:a("Create kanban by {name}",{name:h.name}),separatorBefore:!ye,onSelect:()=>{let ft={...S,id:e.createViewId?.(w.id)??crypto.randomUUID(),name:a(_s.kanban),version:0,type:"kanban",columnOrder:S.columnOrder,hiddenColumns:[],groupByFieldId:h.id};delete ft.dateFieldId,et(ft)}});if(P&&!e.addOnlySchema&&!q)Rt.push({id:"delete",icon:z(xe,{name:"trash"}),label:a("Delete field"),destructive:!0,separatorBefore:!0,onSelect:()=>ki(h.id)});return Rt};if(d.error){let h={code:d.errorCode,message:d.error};return Be("div",{"data-uibot-workspace":"","data-uibot":"collection-workspace",style:se.main,children:[e.renderListError?e.renderListError(h,d.reload):z("p",{role:"alert",children:d.error}),Be("div",{style:se.actions,children:[z(G,{ui:e.ui,style:se.button,onClick:d.reload,children:a("Reload records")}),e.toolbarActions]})]})}let Ys=S&&w&&We==="settings"&&Be("fieldset",{disabled:Ze,style:se.fieldset,"data-uibot-panel":"settings",onKeyDown:Me(),children:[Be("label",{children:[a("View name")," ",z("input",{"aria-label":a("View name"),value:S.name,onChange:(h)=>je({...S,name:h.currentTarget.value})})]}),z(Ta,{fields:w.fields,view:S,onChange:je,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},features:e.features??{preset:"full"},sections:e.inlineViewControls?{}:{filter:l.filter,columns:l.columns,sort:l.sorting},grouping:!e.inlineViewControls,filterEditor:{advanced:e.advancedFilters!==!1,...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},getRelationOptions:s}}),Be("div",{style:se.actions,children:[z(G,{ui:e.ui,style:se.button,variant:"default",disabled:!Lt||!S.name.trim()||!A,onClick:()=>En(S),children:a("Save view")}),z(G,{ui:e.ui,style:se.button,onClick:ve,children:a("Done")})]})]}),Js=w&&We==="schema"&&Be("fieldset",{disabled:Ze,style:se.fieldset,"data-uibot-panel":"schema",onKeyDown:Me(Ua),children:[Be("label",{children:[a("Table title")," ",z("input",{"aria-label":a("Table title"),value:On,onChange:(h)=>Tr(h.currentTarget.value)})]}),z(yi,{fields:xn,...cr?{focusFieldId:cr}:{},onChange:dr,disabled:Ze,...e.schemaFieldTypes?{fieldTypes:e.schemaFieldTypes}:{},...e.schemaSettings?{settings:e.schemaSettings}:{},relationTargets:d.data??[],lockedFieldIds:e.addOnlySchema?(w?.fields??[]).map((h)=>h.id):[],...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}),Be("div",{style:e.renderPanel?se.stickyFooter:se.actions,children:[z(G,{ui:e.ui,style:se.button,variant:"default",disabled:!m||xn.length===0||!On.trim(),onClick:Ua,children:a("Save fields")}),e.renderPanel?null:z(G,{ui:e.ui,style:se.button,onClick:ue,children:a("Cancel field settings")})]})]}),Nr=(h,q,oe)=>oe?e.renderPanel?e.renderPanel({kind:h,title:q,content:oe,dirty:h==="schema"?m:h==="add"||h==="record"?E:!1,busy:Ze||(h==="add"||h==="record")&&W,onClose:ve}):oe:null,Ri=mt.data?.items.find((h)=>h.id===dn),Ii=w&&S?{descriptor:w,rows:mt.data?.items??[],total:mt.data?.total??0,reloadKey:Mn,serverFooterStats:e.serverFooterStats??!0,...i?{aggregate:{client:i,aggregates:sr}}:{},view:S,onViewChange:je,onSelectionChange:V,onMutate:(h)=>o.mutate(w.id,h),relationClient:o,...e.renderRecordContextMenu?{renderRecordContextMenu:e.renderRecordContextMenu}:{},onCommitted:ct,readOnly:Ze||!k.write,features:l,display:{keyboardHints:!1,fill:!0,...l.footerStats?{summary:!1}:{}},...e.inlineViewControls||l.columnFreezing?{fieldMenu:Gs}:{},...e.inlineViewControls&&M?{onAddRecord:()=>ce("add")}:{},onExpandRecord:(h)=>{mo(h.id),ce("record")},...e.onNotify?{onNotify:e.onNotify}:{},...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},getRelationOptions:s}:void 0,bo=w&&S?{descriptor:w,view:S,client:o,onCommitted:ct,reloadKey:Mn,readOnly:!k.write,features:l,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},...i?{aggregate:{client:i,aggregates:sr}}:{}}:void 0,$a=z(Dr,{children:e.toolbarActions}),Qs=!d.loading&&(d.data?.length??0)===0,Ha=(e.showTableList??l.tableList)!==!1,Zs=Be("div",{ref:te,onFocusCapture:(h)=>{if(h.target instanceof HTMLElement&&h.target.matches("input, textarea, select, [contenteditable=true]"))b.current=h.target},"data-uibot-workspace":"","data-uibot":"collection-workspace",style:{...se.root,gridTemplateColumns:[Ha?"auto":"","minmax(0, 1fr)",e.sidePanel||e.renderSidePanel?"auto":""].filter(Boolean).join(" ")},children:[Ha&&z(ga,{tables:d.data??[],activeId:u,onSelect:C,...P&&(e.allowCreateTable??!0)?{onCreate:()=>{yo(""),lr([{id:"name",name:a("Name"),type:"singleLineText",required:!0}]),ce("create")}}:{},createDisabled:Ze,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}),Be("main",{style:se.main,children:[Xn&&S&&w?.fields.some((h)=>h.id===Xn)&&A&&z("div",{style:{justifySelf:"start",alignSelf:"start"},children:z(Fn,{ui:e.ui,defaultOpen:!0,icon:"palette",label:a("Column color for {name}",{name:w.fields.find((h)=>h.id===Xn)?.name??""}),children:(h)=>z("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[null,...Pn].map((q,oe)=>z("button",{type:"button","aria-label":q?a("Column color {number}",{number:oe}):a("No color"),title:q?a("Column color {number}",{number:oe}):a("No color"),"aria-pressed":q?S.columnColors?.[Xn]===q:!S.columnColors?.[Xn],style:{...se.button,...q?yn(oe-1):{},width:q?28:void 0,height:28,padding:q?0:"0 8px"},onClick:()=>{let ie={...S.columnColors};if(q)ie[Xn]=q;else delete ie[Xn];let{columnColors:ye,...it}=S;je(Object.keys(ie).length?{...it,columnColors:ie}:it),h(),Si("")},children:q?"":a("No color")},q??"clear"))})},Xn)}),Qs||e.hideHeader?z("div",{style:se.actions,children:$a}):z(pa,{table:w,canManage:P,canWrite:M||B||R,onRename:(h)=>_o({name:h}),onIconChange:(h)=>_o({icon:h}),...e.locale?{locale:e.locale}:{},actions:$a}),Pe&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:!0,title:a("Discard unsaved changes?"),confirmLabel:a("Discard"),cancelLabel:a("Keep editing"),onConfirm:ve,onCancel:()=>Ae(!1)}):null,Pe&&!e.ui?.ConfirmDialog&&Be("div",{role:"alertdialog","aria-label":a("Discard unsaved changes?"),style:se.confirm,children:[a("Discard unsaved changes?"),z(G,{ui:e.ui,style:se.button,onClick:ve,children:a("Discard")}),z(G,{ui:e.ui,style:se.button,onClick:()=>Ae(!1),children:a("Keep editing")})]}),We==="create"?Be("fieldset",{disabled:Ze,style:se.fieldset,"data-uibot-panel":"create",onKeyDown:Me(Ba),children:[Be("label",{children:[a("Table name")," ",z("input",{"aria-label":a("Table name"),value:Qn,onChange:(h)=>yo(h.currentTarget.value)})]}),z(yi,{fields:Nn,onChange:lr,disabled:Ze,...e.schemaFieldTypes?{fieldTypes:e.schemaFieldTypes}:{},...e.schemaSettings?{settings:e.schemaSettings}:{},relationTargets:d.data??[],...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}),Tt?.error?z("p",{role:"alert",style:se.error,children:Tt.text}):null,Be("div",{style:se.actions,children:[z(G,{ui:e.ui,style:se.button,variant:"default",disabled:!Qn.trim()||Nn.length===0,onClick:Ba,children:a("Create table")}),z(G,{ui:e.ui,style:se.button,onClick:ue,children:a("Cancel")})]})]}):w&&S?Be(Dr,{children:[Be("div",{style:e.inlineViewControls?{display:"grid",gridTemplateColumns:"minmax(0, 1fr)",gap:8,minWidth:0}:se.bar,children:[z(Sa,{views:ht,activeId:S.id,dirty:Lt&&!pe,disabled:Ze,onSelect:No,viewTypes:l.viewTypes,disabledViewTypes:[...w.fields.some((h)=>h.type==="singleSelect"||h.type==="checkbox")?[]:["kanban"],...w.fields.some((h)=>h.type==="date")?[]:["calendar"]],...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},...A?{onAdd:(h)=>{let q={...S,id:e.createViewId?.(w.id)??crypto.randomUUID(),name:a(_s[h]),version:0,type:h,columnOrder:S.columnOrder,hiddenColumns:[]};delete q.groupByFieldId,delete q.dateFieldId;let oe=w.fields.find((ye)=>ye.type==="singleSelect"||ye.type==="checkbox"),ie=w.fields.find((ye)=>ye.type==="date");if(h==="kanban"&&oe)q.groupByFieldId=oe.id;if(h==="calendar"&&ie)q.dateFieldId=ie.id;et(q)},onRename:(h,q)=>{let oe=ht.find((ie)=>ie.id===h);if(oe&&q.trim()&&q!==oe.name)En({...oe,name:q.trim()})},onDuplicate:(h)=>{let q=ht.find((oe)=>oe.id===h);if(q)En({...q,id:e.createViewId?.(w.id)??crypto.randomUUID(),name:a("{name} copy",{name:q.name}),version:0})},...o.deleteView&&ht.length>1?{onDelete:(h)=>Vt(h)}:{},...o.reorderViews&&u&&O.length>1?{onReorder:(h)=>{let q=h.filter((ie)=>O.some((ye)=>ye.id===ie)),oe=o.reorderViews;if(!oe||q.length<2)return;zt(()=>oe.call(o,u,{viewIds:q,idempotencyKey:Jn("reorder",q)}),(ie,ye)=>{if(Et("reorder"),ye)D(ie)})}}:{}}:{}}),e.inlineViewControls?z(xa.Provider,{value:Ze||e.viewControlsDisabled===!0,children:Be("div",{style:{...se.actions,justifyContent:"space-between"},children:[Be("div",{style:se.actions,children:[M&&z(G,{ui:e.ui,style:se.button,icon:"plus",ariaLabel:a("Add record"),onClick:()=>We==="add"?ue():ce("add"),children:a("Add record")}),e.aiFillClient&&B&&z(G,{ui:e.ui,style:se.button,icon:"sparkles",ariaLabel:a("AI fill"),onClick:()=>Uo(!vn),children:a("AI fill")}),z(qs,{part:"main",fields:w.fields,view:S,onChange:je,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},groupable:l.groupBy,filter:l.filter,sort:l.sorting,filterEditor:{advanced:e.advancedFilters!==!1,...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},getRelationOptions:s}})]}),Be("div",{style:se.actions,children:[z("span",{role:"status","aria-live":"polite",style:e.onNotify?_u:se.status,children:Ze?a("Saving…"):""}),l.search?z("input",{type:"search","aria-label":a("Search records"),placeholder:a("Search"),style:se.search,value:an,onChange:(h)=>ar(h.currentTarget.value)}):null,l.columns?z(Fn,{ui:e.ui,icon:"fields",label:a("Field config"),active:S.hiddenColumns.length>0,children:(h)=>z(As,{fields:w.fields,view:S,onChange:je,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},...P?{onEditField:(q)=>{h(),Zn(q)},onAddField:()=>{h(),Zn()}}:{}})}):null,l.columns?z(qs,{part:"extra",fields:w.fields,view:S,onChange:je,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},groupable:l.groupBy,filter:l.filter,sort:l.sorting,filterEditor:{advanced:e.advancedFilters!==!1,...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},getRelationOptions:s}}):null,z(Fn,{ui:e.ui,icon:"sliders",label:a("View config"),children:Be("div",{"data-uibot-view-config":"",style:{display:"grid",gap:10,minWidth:0},children:[Be("label",{style:{display:"grid",gap:4},children:[a("View name"),z("input",{"aria-label":a("View name"),value:S.name,style:se.search,onChange:(h)=>je({...S,name:h.currentTarget.value})})]}),z(Ta,{fields:w.fields,view:S,onChange:je,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},features:e.features??{preset:"full"},sections:{},grouping:!1,rowHeight:!1})]})}),z(G,{ui:e.ui,style:se.button,icon:"refresh",iconOnly:!0,variant:"ghost",ariaLabel:a("Refresh"),onClick:Fr})]})]})}):Be("div",{style:se.actions,children:[l.search?z("input",{type:"search","aria-label":a("Search records"),placeholder:a("Search"),style:se.search,value:an,onChange:(h)=>ar(h.currentTarget.value)}):null,z(G,{ui:e.ui,style:se.button,icon:"refresh",iconOnly:!0,variant:"ghost",ariaLabel:a("Refresh"),onClick:Fr}),(A||l.filter||l.columns)&&z(G,{ui:e.ui,style:se.button,icon:"sliders",iconOnly:!0,variant:"ghost",ariaLabel:a("View settings"),onClick:()=>We==="settings"?ve():ce("settings")}),A?z(G,{ui:e.ui,style:se.button,icon:"save",iconOnly:!0,variant:"ghost",badge:Lt,ariaLabel:a("Save view"),disabled:!Lt||!S.name.trim()||Ze,onClick:()=>En(S)}):null,!e.inlineViewControls&&l.filter&&S.filter?.filterSet.length?z(G,{ui:e.ui,style:se.button,icon:"filter",ariaLabel:a("Clear current filter"),onClick:()=>{let{filter:h,...q}=S;je(q)},children:a("{count} filters",{count:S.filter.filterSet.length})}):null,P&&z(G,{ui:e.ui,style:se.button,icon:"fields",iconOnly:!0,variant:"ghost",ariaLabel:a("Configure fields"),onClick:()=>We==="schema"?ue():Zn()}),M&&z(G,{ui:e.ui,style:se.button,icon:"plus",ariaLabel:a("Add record"),onClick:()=>We==="add"?ue():ce("add"),children:a("Add record")}),e.aiFillClient&&B&&z(G,{ui:e.ui,style:se.button,icon:"sparkles",ariaLabel:a("AI fill"),onClick:()=>Uo(!vn),children:a("AI fill")}),z("span",{role:"status","aria-live":"polite",style:se.status,children:Ze?a("Saving…"):""})]})]}),e.relationNavigation!==!1&&Qt.length>0?Be("div",{style:se.actions,children:[z(G,{ui:e.ui,style:se.button,onClick:()=>we(!de),children:a("Relations")}),de?Qt.map((h)=>z(G,{ui:e.ui,style:se.button,disabled:h.needsRecord&&Y.recordIds.length!==1,onClick:h.open,children:h.label},h.key)):null]}):null,Pi&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:!0,title:a("Delete field “{name}”?",{name:w.fields.find((h)=>h.id===Pi)?.name??""}),description:a("The field and its values in every record are removed. This cannot be undone."),confirmLabel:a("Delete field"),cancelLabel:a("Cancel"),busy:Ze,onConfirm:Ws,onCancel:()=>ki("")}):null,rn&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:!0,title:a("Delete view “{name}”?",{name:ht.find((h)=>h.id===rn)?.name??""}),description:a("Only this view's filters, sort and layout are removed; no records are deleted."),confirmLabel:a("Delete view"),cancelLabel:a("Cancel"),busy:Ze,onConfirm:go,onCancel:()=>Vt("")}):null,rn&&!e.ui?.ConfirmDialog&&Be("div",{role:"alertdialog","aria-label":a("Delete view"),style:se.confirm,children:[a("Delete view “{name}”?",{name:ht.find((h)=>h.id===rn)?.name??""}),z("small",{style:se.status,children:a("Only this view's filters, sort and layout are removed; no records are deleted.")}),z(G,{ui:e.ui,style:se.button,disabled:Ze,onClick:go,children:a("Delete view")}),z(G,{ui:e.ui,style:se.button,onClick:()=>Vt(""),children:a("Cancel")})]}),Tt&&z("p",{role:Tt.error?"alert":"status",style:Tt.error?se.error:se.status,children:Tt.text}),e.transferClient&&l.export?z(Wi,{descriptor:w,fieldIds:w.fields.filter((h)=>!S.hiddenColumns.includes(h.id)).map((h)=>h.id),query:{search:an,...S.filter?{filter:S.filter}:{},...S.sort?.length?{sort:S.sort}:{}},client:e.transferClient,readOnly:!M,reloadKey:Mn,onImported:ct,onRefreshSchema:async()=>{let h=await o.describe(w.id);return L.reload(),h.ok?h.data:null}}):null,Nr("settings",a("View settings"),Ys),Nr("schema",a("Fields"),Js),Nr("add",a("Add record"),We==="add"&&Ii?z("fieldset",{"aria-label":a("Add record"),"data-uibot-panel":"add",style:{margin:0,padding:0,border:0,minWidth:0},onKeyDown:Me(),children:z(ha,{descriptor:w,client:o,readOnly:!M,autoFocus:!0,onDirtyChange:ne,onBusyChange:U,onCommitted:()=>ct(),onSaved:(h)=>{ve();let q=ba(w,h.items[0]);Ct(`${a("Record saved")}${q?`:${q}`:""}`)},onCancel:ue,stickyActions:Boolean(e.renderPanel),...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}})}):null),Nr("record",a("Record details"),We==="record"&&bo&&Ri?z(qn,{...bo,row:Ri,onClose:ve,onCancel:ue,onDirtyChange:ne,onBusyChange:U,stickyActions:Boolean(e.renderPanel)},Ri.id):null),Bo&&Ii?mt.error?Be("p",{role:"alert",children:[mt.error," ",z(G,{ui:e.ui,style:se.button,onClick:mt.reload,children:a("Reload records")})]}):Be(Dr,{children:[mt.loading&&z("p",{role:"status",children:a("Loading records…")}),z(Ss,{...Ii},`${u}:${j}:${w.schemaVersion}:${Lo}:${St??""}`),i&&!l.footerStats?Be("div",{style:se.actions,children:[z(Ge,{ui:e.ui,label:a("Sum field"),style:se.button,value:Yn,options:[{value:"",label:a("No sum")},...w.fields.filter((h)=>h.type==="number").map((h)=>({value:h.id,label:h.name}))],onChange:cn}),z(Ao,{collectionId:w.id,descriptor:w,view:S,aggregates:sr,client:i,labels:wi,reloadKey:Mn,...e.locale?{locale:e.locale}:{}})]}):null,z("div",{style:se.actions,children:z(ta,{hasPrevious:Ht.length>0,hasNext:Boolean(mt.data?.nextCursor),loading:mt.loading,onPrevious:()=>{sn(Ht.at(-1)),Gn(Ht.slice(0,-1))},onNext:()=>{Gn([...Ht,St]),sn(mt.data?.nextCursor??void 0)},page:Ht.length+1,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}})})]}):bo?S.type==="kanban"?z(Ra,{...bo},S.id):S.type==="gallery"?z(Aa,{...bo},S.id):S.type==="calendar"?z(Fa,{...bo},S.id):z(ra,{...bo,...ht.some((h)=>h.type!=="form")?{onShowRecords:()=>{let h=ht.find((q)=>q.type!=="form");if(h)No(h.id)}}:{}},S.id):null]}):!d.loading&&u&&!_?z("p",{role:"alert",children:a("Table not found")}):L.data&&L.data.id!==u?z("p",{role:"alert",children:a("Table not found")}):N.error?z("p",{role:"alert",children:N.error}):w&&X&&!N.loading&&e.viewId!==void 0&&!S?z("p",{role:"alert",children:a("View not found")}):L.error?z("p",{role:"alert",children:L.error}):d.loading||L.loading?z("p",{role:"status",children:a("Loading…")}):Be("div",{style:se.empty,children:[z("p",{style:{margin:0},children:a("No tables yet")}),P&&(e.allowCreateTable??!0)?z(G,{ui:e.ui,style:se.button,onClick:()=>{yo(""),lr([{id:"name",name:a("Name"),type:"singleLineText",required:!0}]),ce("create")},children:a("New table")}):null]})]}),vn&&e.aiFillClient&&w&&B?z(Us,{table:w,rows:mt.data?.items??[],selection:Y,aiFillClient:e.aiFillClient,client:o,query:Oo,...mt.data?{total:mt.data.total}:{},onCommitted:()=>ct(),onClose:()=>Uo(!1),...e.onNotify?{onNotify:e.onNotify}:{},...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}):null,e.renderOverlay?.({table:w,view:S,selection:Y,rows:mt.data?.items??[],reload:ct}),e.sidePanel||e.renderSidePanel?Be("aside",{style:se.side,children:[e.sidePanel,e.renderSidePanel?.({table:w,view:S,selection:Y,rows:mt.data?.items??[],reload:ct})]}):null]});return z(Di.Provider,{value:ur.report,children:Zs})}var se={root:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",gap:16,alignItems:"start",fontSize:"var(--uibot-workspace-font-size, 13px)"},main:{display:"grid",gridTemplateColumns:"minmax(0, 1fr)",gap:8,minWidth:0},bar:{minWidth:0,maxWidth:"100%",display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:8},actions:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},stickyFooter:{position:"sticky",bottom:0,zIndex:1,display:"flex",justifyContent:"flex-end",gap:8,padding:"12px 0",borderTop:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",background:"var(--background, white)"},button:{padding:"6px 10px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit",cursor:"pointer"},status:{margin:0,fontSize:12,opacity:0.8},error:{margin:0,fontSize:13,color:"var(--uibot-danger, #b3261e)"},confirm:{display:"flex",alignItems:"center",gap:8,padding:8,border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6},fieldset:{display:"grid",gap:12,margin:0,padding:12,border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:8},search:{boxSizing:"border-box",height:28,minHeight:28,fontSize:"0.8rem",padding:"0 8px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit"},empty:{display:"grid",justifyItems:"start",gap:12,padding:"24px 4px",opacity:0.9},side:{minWidth:280,maxWidth:420}};function qs({fields:e,view:t,onChange:n,locale:o,ui:i,groupable:r,filter:s=!0,sort:a=!0,filterEditor:l,part:c}){let d=le(o),g={fields:e,view:t,onChange:n,locale:o,ui:i},f=t.filter?.filterSet.length??0,u=t.sort?.length??0,x=r&&(t.type??"grid")==="grid"&&e.some((b)=>b.type==="singleSelect"||b.type==="checkbox");return Be(Dr,{children:[c==="main"&&Be(Dr,{children:[s?z(Fn,{ui:i,icon:"filter",active:f>0,label:f?d("{count} filters",{count:f}):d("Filter"),children:z("div",{style:{width:"100%",maxWidth:520,minWidth:0},children:z(ui,{...g,editor:l})})}):null,x&&z(Fn,{ui:i,icon:"group",active:Boolean(t.groupByFieldId),label:d("Group"),children:z("div",{style:{width:"100%",maxWidth:360,minWidth:0},children:z(pi,{...g})})}),a?z(Fn,{ui:i,icon:"sort",active:u>0,label:u?d("{count} sorts",{count:u}):d("Sort"),children:z("div",{style:{width:"100%",maxWidth:440,minWidth:0},children:z(gi,{...g})})}):null]}),c==="extra"&&(t.type??"grid")==="grid"&&z(Fn,{ui:i,icon:"rows",label:d("Row height"),active:Boolean(t.rowHeight),children:z("div",{style:{display:"grid",gap:2,minWidth:140},children:Br.map((b)=>z(G,{ui:i,variant:(t.rowHeight??"short")===b?"outline":"ghost",size:"sm",onClick:()=>{let v={...t};if(b==="short")delete v.rowHeight;else v.rowHeight=b;n(v)},children:d(`Row height ${b}`)},b))})})]})}var _u={position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)"};export{CC as PagedCollectionWorkspace};
|