@uibot/renderer-react 0.19.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
- import{createContext as Ud,useCallback as _d,useContext as zd,useLayoutEffect as Zi,useMemo as qd,useRef as Dl,useState as Hd}from"react";var Qi=Ud(void 0);function Fn(e,t={}){let n=zd(Qi),o=Dl({}),{dirty:i,busy:r}=e,{onDirtyChange:l,onBusyChange:d}=t;Zi(()=>{n?.(o.current,{dirty:i,busy:r}),l?.(i),d?.(r)},[n,i,r,l,d]),Zi(()=>()=>{n?.(o.current),l?.(!1),d?.(!1)},[n,l,d])}function El(){let e=Dl(new Map),[t,n]=Hd({dirty:!1,busy:!1}),o=_d((i,r)=>{if(r)e.current.set(i,r);else e.current.delete(i);let l=[...e.current.values()],d=l.some((s)=>s.dirty),a=l.some((s)=>s.busy);n((s)=>s.dirty===d&&s.busy===a?s:{dirty:d,busy:a})},[]);return{...t,report:o}}function ni(e,t){let n=qd(()=>({active:!0,client:e,id:t}),[e,t]);return Zi(()=>(n.active=!0,()=>{n.active=!1}),[n]),n}import{useCallback as hl,useEffect as Nt,useMemo as Qn,useRef as on,useState as Fe}from"react";function $g(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var Tn=["blue","green","red","orange","gray","teal","purple"];function $d(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 Fl(e,t,n){if(!t?.length)return[];return t.map((o)=>{if(o.fn==="count")return{fieldId:o.fieldId,fn:"count",value:e.length};let i=n.find((d)=>d.id===o.fieldId),l=i?.type==="number"||i?.type==="rating"||i?.type==="autoNumber"?e.reduce((d,a)=>d+($d(a.values[o.fieldId])??0),0):0;return{fieldId:o.fieldId,fn:"sum",value:l}})}function Tl(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function jd(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function Kd(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 Nl(e,t){if(!t)return!0;if(Tl(t)){let n=t.filterSet.map((o)=>Tl(o)?Nl(e,o):jd(o)?Kd(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 Ml(e,t,n,o){let i=e.views.find((p)=>p.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((p)=>Nl(p,i.filter));if(i.sort?.length)r.sort((p,m)=>{for(let h of i.sort??[]){let x=p.values[h.fieldId],C=m.values[h.fieldId];if(x===C)continue;if(x==null)return 1;if(C==null)return-1;let w=e.fields.find((L)=>L.id===h.fieldId)?.type,f=(L)=>{if(["number","rating","autoNumber"].includes(w??"")&&typeof L==="number")return L;if(["date","createdTime","lastModifiedTime"].includes(w??"")){let M=Date.parse(String(L));if(Number.isFinite(M))return M}return String(L)},R=f(x),S=f(C);if(R===S)continue;let A=R<S?-1:1;return h.direction==="desc"?-A:A}return p.id<m.id?-1:p.id===m.id?0:1});let l=i.projection?.length?e.fields.filter((p)=>i.projection?.includes(p.id)):e.fields,d=o?.search?.trim().toLowerCase();if(d)r=r.filter((p)=>l.some((m)=>String(p.values[m.id]??"").toLowerCase().includes(d)));let a=Fl(r,i.aggregates,e.fields),s=i.group?.fieldId;if(!s)return{view:i,columns:l,rows:r,...a.length?{aggregates:a}:{}};let u=[],c=new Map;for(let p of r){let m=String(p.values[s]??"");if(!c.has(m))c.set(m,[]),u.push(m);c.get(m)?.push(p)}let g=u.map((p)=>{let m=c.get(p)??[];return{key:p,fieldId:s,rows:m,aggregates:Fl(m,i.aggregates,e.fields)}});return{view:i,columns:l,rows:r,groups:g,...a.length?{aggregates:a}:{}}}var oi=500,ea=2000,Pr=new Set(["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"]);function it(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function cn(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 ri=["short","medium","tall","extra"];function Ll(e,t){return t.map((n)=>{let o={},i={};for(let r of e.groupBy){let l=n[r];if(!(r in n)||l!==null&&typeof l!=="string"&&typeof l!=="number"&&typeof l!=="boolean")throw Error(`Invalid aggregate group ${r}.`);o[r]=l}for(let{as:r,fn:l}of e.aggregates){let d=n[r];if(!(r in n)||d!==null&&!(typeof d==="number"&&Number.isFinite(d))&&!((l==="min"||l==="max")&&typeof d==="string"&&Number.isFinite(Date.parse(d))))throw Error(`Invalid aggregate value ${r}.`);i[r]=d}return{groups:o,values:i}})}var Wd=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,Gd=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function ii(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function Zt(e,t){return{code:e,...t}}function Yd(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function Xi(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function ai(e,t){if(t.aggregates.length===0)return Zt("empty");if(t.aggregates.length>8||t.groupBy.length>3)return Zt("too_many");let n=new Set;for(let i of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(i.fn))return Zt("function");if(!Wd.test(i.as)||n.has(i.as)||t.groupBy.includes(i.as))return Zt("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((l)=>l.id===i.fieldId);if(!r)return Zt(i.fn==="sum"?"sum_field":"unknown_field",{alias:i.as,...i.fieldId!==void 0?{fieldId:i.fieldId}:{}});if(i.fn==="sum"&&!Xi(r))return Zt("sum_field",{fieldId:r.id,alias:i.as});if(i.fn==="avg"&&!Xi(r))return Zt("numeric_field",{fieldId:r.id,alias:i.as});if((i.fn==="min"||i.fn==="max")&&!Xi(r)&&r.type!=="date"&&!((r.type==="formula"||r.type==="rollup")&&r.resultType==="date"))return Zt("extrema_field",{fieldId:r.id,alias:i.as});if((i.fn==="filled"||i.fn==="empty")&&!cn(r))return Zt("queryable_field",{fieldId:r.id,alias:i.as});if(i.fn==="count"&&!cn(r))return Zt("count_field",{fieldId:r.id,alias:i.as})}let o=new Set;for(let i of t.groupBy){if(o.has(i))return Zt("duplicate_group",{fieldId:i});o.add(i);let r=e.fields.find((l)=>l.id===i);if(!r)return Zt("unknown_field",{fieldId:i});if(!Gd.has(r.type)&&!Yd(r))return Zt("not_groupable",{fieldId:i})}return null}var Ol=(e)=>String(e).padStart(2,"0");function Nn(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 lo(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=Nn(new Date(o),t),l=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second);o+=n-l}return new Date(o)}function li(e,t){let n=Nn(e,t??"UTC");return`${n.year}-${Ol(n.month)}-${Ol(n.day)}`}var Jd=/^[a-z][a-z0-9_-]{0,31}$/,si=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function Vl(e){if(!e||e.length>2048||/\s/.test(e))return!1;for(let n=0;n<e.length;n++)if(e.charCodeAt(n)<32||e.charCodeAt(n)===127)return!1;if(e.startsWith("/"))return!e.startsWith("//")&&!e.startsWith("/\\");let t=/^([a-z][a-z0-9+.-]*):/i.exec(e)?.[1]?.toLowerCase();if(t==="http"||t==="https")try{return Boolean(new URL(e).hostname)}catch{return!1}return t==="mailto"||t==="tel"}function Zd(e){if(!si(e))return"hyperlink must be an object";if(Object.keys(e).some((t)=>t!=="url"&&t!=="text"&&t!=="ref"))return"hyperlink has unknown keys";if(typeof e.url!=="string"||!Vl(e.url))return"hyperlink URL is invalid";if(e.text!==void 0&&(typeof e.text!=="string"||e.text.length>500))return"hyperlink text is invalid";if(e.ref!==void 0){let t=e.ref;if(!si(t)||Object.keys(t).length!==2||typeof t.kind!=="string"||!Jd.test(t.kind)||typeof t.id!=="string"||!t.id||t.id.length>200)return"hyperlink reference is invalid"}return null}var Qo=(e)=>Zd(e)===null;function Sr(e){if(!si(e)||typeof e.url!=="string")return"";return typeof e.text==="string"&&e.text.trim()?e.text:e.url}function Bl(e){if(!si(e)||typeof e.url!=="string")return"";let t=typeof e.text==="string"?e.text.trim():"";return t&&t!==e.url?`[${t.replace(/[[\]]/g,"")}](${e.url})`:e.url}function Ao(e){let t=e.trim();if(!t)return null;if(t.startsWith("{"))try{let r=JSON.parse(t);return Qo(r)?r:null}catch{return null}let n=/^\[([^\]]*)\]\((\S+)\)$/.exec(t)??/^(.*?)\s*<(\S+)>$/.exec(t),o=n?.[1]?.trim().slice(0,500)??"",i=n?.[2]??t;if(!/^[a-z][a-z0-9+.-]*:/i.test(i)&&!i.startsWith("/")){if(/^[\w-]+(\.[\w-]+)+(:\d+)?([/?#]\S*)?$/.test(i))i=`https://${i}`;else if(/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(i))i=`mailto:${i}`}if(!Vl(i))return null;return o&&o!==i?{url:i,text:o}:{url:i}}function Rr(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 l=i.formatting;if(l&&"time"in l&&l.time==="none"){let d=Nn(t,n);o[i.id]=`${d.year}-${String(d.month).padStart(2,"0")}-${String(d.day).padStart(2,"0")}`}else o[i.id]=t.toISOString()}}return o}var na=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],di=new Set(["pastDays","nextDays","daysAgo","daysFromNow"]),Ul={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"]},Xo=new Set(["isEmpty","isNotEmpty"]);function bn(e){switch(e.type){case"singleLineText":case"longText":case"hyperlink":return"text";case"number":return"number";case"checkbox":return"checkbox";case"date":return"date";case"singleSelect":return"singleSelect";case"multipleSelect":return"multipleSelect";case"relation":return"relation";case"formula":case"rollup":return e.resultType==="text"?"text":e.resultType==="number"?"number":e.resultType==="date"?"date":null;default:return null}}function _l(e){let t=bn(e);return t?Ul[t]:[]}var ta=/^\d{4}-\d{2}-\d{2}$/,Qd=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function oa(e){if(!Qd(e))return!1;let t=e.mode;if(!na.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&&ta.test(e.date);if(t==="dateRange")return typeof e.date==="string"&&ta.test(e.date)&&typeof e.to==="string"&&ta.test(e.to)&&e.date<=e.to;if(di.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function zl(e,t){if(!e)return"unknown field";let n=bn(e),o=t.operator==="contains"&&(n==="number"||n==="checkbox"||n==="date"||n==="singleSelect");if(!n||!(Ul[n].includes(t.operator)||o))return"operator not allowed";if(Xo.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 oa(i)||typeof i==="string"&&Number.isFinite(Date.parse(i))?null:"date required"}}var Xd={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},Tp=Array.from(new Set(Object.values(Xd).flat()));var Lp=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([...[["function","functions"],["scenario","scenarios"],["unit","units"],["industry","industries"]].map(([e,t])=>Object.freeze({name:e,property:t,type:"string",multiple:!0,cliEncoding:"comma-separated"})),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([])}),Object.freeze({name:"docs",summary:"Read curated public documentation for one resource.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([{name:"locale",property:"locale",type:"string"},{name:"page",property:"page",type:"positive-integer"}])}),Object.freeze({name:"examples",summary:"Read one bounded page of examples and exact dependencies. Follow nextPage for complete source.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([{name:"page",property:"page",type:"positive-integer"}])}),Object.freeze({name:"install-plan",summary:"Describe distribution channels and fixed snapshot identity/closure without installing or writing.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([])})]);var ec=["background","foreground","card","card-foreground","popover","popover-foreground","primary","primary-foreground","secondary","secondary-foreground","muted","muted-foreground","accent","accent-foreground","border","input","ring","destructive","destructive-foreground","success","success-foreground","warning","warning-foreground"],Bp=[...ec,"radius","font-display","font-body","font-mono"];function tc(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function Kp(e,t){if(t===e.draft)return e;return{...e,draft:t}}function nc(e){return e.draft!==e.savedContent}function Wp(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 Gp(e,t){if(nc(e))return e;let n=tc(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 Hn=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),Do=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),Eo=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,ql=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,ci=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),Hl=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every(ci)&&new Set(e).size===e.length;function oc(e){if(!Hn(e)||!Do(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!ci(e.id)||!Eo(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)=>!Hn(t)||!Do(t,["id","name"])||!ci(t.id)||!Eo(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&&(!Hn(i)||!Do(i,[...o])||o.some((r)=>!Eo(i[r],r==="expression"?2048:512))))return!1}return!0}function Jp(e){if(!Hn(e)||!Do(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))||!Eo(e.collectionId,512)||!Eo(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(!Hn(t)||!Do(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!Eo(t.name,200)||!ql(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(oc)||new Set(t.fields.map((r)=>r.id)).size!==t.fields.length)return!1;if(!Hn(n)||!Do(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!ci(n.id)||!Eo(n.name,200)||!ql(n.version)||!Hl(n.columnOrder)||!Hl(n.hiddenColumns)||!Hn(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((l)=>Hn(l)&&l.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)=>!Hn(r)||!Do(r,["fieldId","direction"])||!i(r.fieldId)||!["asc","desc"].includes(String(r.direction)))))return!1;return!0}function ia(e){return e?.type==="singleSelect"||e?.type==="checkbox"}var rc="\x00none";function $l(e,t,n=new Set){if(!t)return{items:e.map((l,d)=>({kind:"row",index:d,key:l.id})),rowItem:e.map((l,d)=>d)};let o=[],i=[],r;return e.forEach((l,d)=>{let a=l.values[t.id],s=a==null?rc:String(a);if(!r||r.raw!==s){let u=t.options?.findIndex((c)=>c.id===a)??-1;r={kind:"group",key:`group:${o.length}:${s}`,raw:s,label:a==null?null:t.type==="checkbox"?a===!0?"true":"false":t.options?.[u]?.name??String(a),colorIndex:u,count:0,collapsed:n.has(s)},o.push(r)}if(r.count+=1,r.collapsed)return;i[d]=o.length,o.push({kind:"row",index:d,key:l.id})}),{items:o,rowItem:i}}function ui(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 aa=34,ra=38,ic={short:1,medium:2,tall:3,extra:4},la=(e)=>ic[e??"short"],jl=(e)=>ra+(la(e)-1)*22;function Kl(e,t=ra){return ra+e.items.reduce((n,o)=>n+(o.kind==="group"?aa:t),0)}function Wl(e,t){let n=e?.groupByFieldId;if(!e||!n||(e.type??"grid")!=="grid")return e?.sort;if(!t?.some((o)=>o.id===n&&ia(o)))return e.sort;return[{fieldId:n,direction:"asc"},...(e.sort??[]).filter((o)=>o.fieldId!==n)]}var Yl=["grid","kanban","gallery","calendar","form"],ac=["grid","form"],sa={search:!0,filter:!0,columns:!0,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!0,tableList:!0,viewManagement:!0,export:!0},lc={search:!0,filter:!1,columns:!1,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!1,tableList:!1,viewManagement:!1,export:!1},sc={search:!0,filter:!0,columns:!0,rowCreate:!1,rowUpdate:!1,rowDelete:!1,schemaEditor:!1,tableList:!0,viewManagement:!1,export:!0},Gl={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:Yl},da={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:Yl},Jl={basic:{...Gl,...sa},full:{...da,...sa},simple:{...Gl,...lc,viewTypes:ac},workbench:{...da,...sa},readonly:{...da,...sc,recordContextMenu:!1,optimisticEdit:!1}};function Dt(e){let{preset:t="basic",...n}=e??{},o={...Jl[t],...dc(n)};return o.groupBy?o:{...o,groupCollapse:!1}}function dc(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var cc={"AI fill":"AI 填充","AI field":"AI 字段","Generate {name} with AI":"AI 生成「{name}」","Only records with empty target cells":"只处理目标为空的记录","No records have empty target cells.":"没有目标为空的记录。","AI settings of field {name}":"字段 {name} 的 AI 设置","Generate this field with AI":"用 AI 生成此字段","Generate when a record is created":"新建记录时自动生成","AI auto-fill stopped: {message}":"AI 自动生成中断:{message}",Hyperlink:"超链接","Search or paste a link":"搜索文档或粘贴链接","Use link {url}":"使用链接 {url}","Display text":"显示文字","Remove link":"移除链接","Link suggestions":"链接建议","Searching…":"搜索中…","No matching resources":"没有匹配的内容","{name} needs a link.":"{name}需要有效链接(http(s)、邮箱或站内路径)。","Link targets":"可选的链接目标","None chosen offers every kind.":"都不选则提供全部类型。","AI prompt":"AI 提示词","e.g. Summarize the description in one sentence":"例如:用一句话概括描述","Fields the AI reads (none = all)":"AI 读取的字段(不选则读取全部)","AI reads {name}":"AI 读取 {name}","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":"修改字段","Field saved":"字段已保存","Field added":"字段已添加","Edit all fields":"批量编辑字段","Save field":"保存","Field name is required.":"请填写字段名。","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 se(e="en"){return(t,n={})=>(e==="zh-CN"?cc[t]??t:t).replace(/\{(\w+)\}/g,(o,i)=>String(n[i]??o))}import{useEffect as Si,useRef as Or,useState as tn}from"react";import{useId as Zc,useState as Pa}from"react";var hn=(e)=>String(e).padStart(2,"0"),uc=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function Et(e){let t=e.formatting;return uc(e)&&t&&"date"in t?t:void 0}function Fo(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function ua(e){let t=Et(e);return!t?"auto":t.time==="none"?"date":"datetime"}function ca(e,t,n,o){switch(o){case"YYYY/MM/DD":return`${e}/${hn(t)}/${hn(n)}`;case"MM/DD/YYYY":return`${hn(t)}/${hn(n)}/${e}`;case"DD/MM/YYYY":return`${hn(n)}/${hn(t)}/${e}`;case"YYYY年M月D日":return`${e}年${t}月${n}日`;default:return`${e}-${hn(t)}-${hn(n)}`}}function $n(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 ca(Number(o[1]),Number(o[2]),Number(o[3]),t.date);let d=new Date(n);if(!Number.isFinite(d.getTime()))return n;let a=Nn(d,t.timeZone??"UTC");return ca(a.year,a.month,a.day,t.date)}let i=o?lo({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=Nn(i,t.timeZone),l=ca(r.year,r.month,r.day,t.date);if(t.time==="12h"){let d=r.hour%12||12;return`${l} ${d}:${hn(r.minute)} ${r.hour<12?"AM":"PM"}`}return`${l} ${hn(r.hour)}:${hn(r.minute)}`}function To(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 Ir(e,t){let n=e?.findIndex((r)=>r.id===t)??-1,o=n>=0?e?.[n]?.color:void 0,i=Tn.findIndex((r)=>r===o);return i>=0?i:n}function gi(e,t,n,o,i=!1){let{row:r,column:l}=e;if(t==="ArrowUp")r--;if(t==="ArrowDown")r++;if(t==="ArrowLeft")l--;if(t==="ArrowRight")l++;if(t==="Home")l=0;if(t==="End")l=o-1;if(t==="Tab"){let d=Math.max(0,Math.min(n*o-1,r*o+l+(i?-1:1)));r=Math.floor(d/o),l=d%o}return{row:Math.max(0,Math.min(n-1,r)),column:Math.max(0,Math.min(o-1,l))}}function ga(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 et(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function Zl(e,t,n,o){let i=ga(n,o),r=[];for(let l=i.firstRow;l<=i.lastRow;l++){let d=[];for(let a=i.firstColumn;a<=i.lastColumn;a++){let s=t[a],u=e[l]?.values[s?.id??""],c=s?.type==="json"&&u!=null?JSON.stringify(u):s?.type==="hyperlink"?Bl(u):et(u);d.push(/[\t\r\n"]/.test(c)?`"${c.replaceAll('"','""')}"`:c)}r.push(d.join("\t"))}return r.join(`
2
- `)}function gc(e,t="en"){let n=se(t),o=[],i=[],r="",l=!1;for(let d=0;d<e.length;d++){let a=e[d];if(a==='"'&&(l||r===""))if(l&&e[d+1]==='"')r+='"',d++;else l=!l;else if(!l&&(a==="\t"||a===`
3
- `||a==="\r")){if(i.push(r),r="",a!=="\t"){if(o.push(i),i=[],a==="\r"&&e[d+1]===`
4
- `)d++}}else r+=a}if(l)throw Error(n("Unclosed quoted cell."));if(r||i.length||o.length===0)i.push(r),o.push(i);return o}function Cn(e,t,n="en"){let o=se(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==="hyperlink"){let r=Ao(e);if(!r)throw Error(o("{name} needs a link.",{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=Et(t);if(r){let S=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!S)throw Error(o("{name} needs a date.",{name:t.name}));let[,A,L,M]=S,U=new Date(Date.UTC(Number(A),Number(L)-1,Number(M)));if(U.getUTCMonth()!==Number(L)-1||U.getUTCDate()!==Number(M))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 li(new Date(e),r.timeZone);return`${A}-${L}-${M}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return lo({year:Number(A),month:Number(L),day:Number(M)},r.timeZone).toISOString()}let l=/^(\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(!l)throw Error(o("{name} needs a date.",{name:t.name}));let[,d,a,s,u,c,g,p,m]=l,h=Number(d),x=Number(a),C=Number(s),f=[31,h%4===0&&(h%100!==0||h%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(x<1||x>12||C<1||C>(f[x-1]??0)||Number(u??0)>23||Number(c??0)>59||Number(g??0)>59||Number(p??0)>23||Number(m??0)>59)throw Error(o("{name} needs a valid calendar date.",{name:t.name}));let R=new Date(e);if(!Number.isFinite(R.getTime()))throw Error(o("{name} needs a date.",{name:t.name}));return R.toISOString()}let i=(r)=>{let l=t.options?.find((d)=>d.id===r||d.name===r);if(!l)throw Error(o("{name} has no option '{option}'.",{name:t.name,option:r}));return l.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 Ql(e,t,n,o,i="en"){let r=se(i);try{if(e.length>1048576)throw Error(r("Paste is too large."));let l=gc(e,i);if(l.length>100||o.row+l.length>t.length)throw Error(r("Paste must fit within the loaded page and contain at most 100 rows."));return{ok:!0,items:l.map((a,s)=>{if(o.column+a.length>n.length)throw Error(r("Paste extends beyond the visible columns."));let u=t[o.row+s];if(!u)throw Error(r("Row is not loaded."));let c={};return a.forEach((g,p)=>{let m=n[o.column+p];if(m?.generation==="autoIncrement")throw Error(r("{name} is auto-generated and cannot be edited.",{name:m.name}));if(m)c[m.id]=Cn(g,m,i)}),{op:"update",id:u.id,expectedVersion:u.version,values:c}})}}catch(l){return{ok:!1,message:l instanceof Error?l.message:r("Invalid paste.")}}}function pi(e,t){let n=et(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=(s)=>i.find((u)=>u.type===s)?.value??"",l=o.getUTCMilliseconds(),d=r("second"),a=d!=="00"||l?`:${d}${l?`.${String(l).padStart(3,"0")}`:""}`:"";return`${r("year")}-${r("month")}-${r("day")} ${r("hour")}:${r("minute")}${a}`}import{useEffect as pc,useRef as mc,useState as er}from"react";import{jsx as vn,jsxs as Ar}from"react/jsx-runtime";function so(e){if(e==null)return"—";if(Array.isArray(e))return e.map(so).join(", ");return String(e)}function No(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((o)=>o.label||o.id).join(", "):void 0)??so(e.values[t.id])}function Xl(e,t){return et(e.values[t.id])}function mi({field:e,value:t,labels:n=[],client:o,onChange:i,disabled:r=!1,locale:l,"aria-describedby":d,"aria-invalid":a}){let s=se(l),u=Array.isArray(t)?t.filter((P)=>typeof P==="string"):[],c=mc(new Set(u));c.current=new Set(u);let[g,p]=er(""),[m,h]=er(),[x,C]=er([]),[w,f]=er(0),[R,S]=er({}),[A,L]=er({rows:[],next:null,error:"",loading:!0}),M=e.link?.collectionId,U=e.link?.displayFieldId;pc(()=>{let P=!0;if(L({rows:[],next:null,error:"",loading:!0}),!o||!M||!U){L({rows:[],next:null,error:s("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return o.query(M,{limit:50,search:g,...m?{cursor:m}:{}}).then((I)=>{if(!P)return;if(!I.ok){L({rows:[],next:null,error:I.error.message,loading:!1});return}S((k)=>({...Object.fromEntries(Object.entries(k).filter(([T])=>c.current.has(T))),...Object.fromEntries(I.data.items.map((T)=>{let D=String(T.values[U]??"");return[T.id,D.trim()?D.slice(0,256):T.id]}))})),L({rows:I.data.items,next:I.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(P)L({rows:[],next:null,error:s("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{P=!1}},[o,M,U,g,m,w]);let J=(P)=>R[P]??n.find((I)=>I.id===P)?.label??P;return Ar("fieldset",{disabled:r,"aria-label":s("{name} linked records",{name:e.name}),...d?{"aria-describedby":d}:{},...a?{"aria-invalid":!0}:{},className:"flex min-w-0 flex-col gap-2 rounded-md border p-2",children:[vn("div",{className:"flex flex-wrap gap-1",children:u.map((P)=>Ar("span",{className:"rounded border px-2 py-1 text-sm",children:[J(P)," ",vn("button",{type:"button","aria-label":s("Remove {name}",{name:J(P)}),onClick:()=>i(u.filter((I)=>I!==P)),children:"×"})]},P))}),vn("input",{"aria-label":s("Search {name} records",{name:e.name}),type:"search",placeholder:s("Search linked records"),value:g,onChange:(P)=>{p(P.target.value),h(void 0),C([])}}),A.loading&&vn("p",{role:"status",children:s("Loading linked records…")}),A.error&&Ar("div",{role:"alert",children:[A.error," ",vn("button",{type:"button",onClick:()=>f((P)=>P+1),children:s("Retry linked records")})]}),vn("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:A.rows.map((P)=>Ar("label",{className:"flex items-center gap-2 text-sm",children:[vn("input",{type:"checkbox","aria-label":s("Link {name}",{name:J(P.id)}),checked:u.includes(P.id),disabled:!u.includes(P.id)&&u.length>=100,onChange:(I)=>i(I.target.checked?[...u,P.id]:u.filter((k)=>k!==P.id))}),J(P.id)]},P.id))}),!A.loading&&!A.error&&!A.rows.length&&vn("p",{children:s("No matching records.")}),Ar("div",{className:"flex gap-2",children:[vn("button",{type:"button",disabled:!x.length||A.loading,onClick:()=>{h(x.at(-1)),C((P)=>P.slice(0,-1))},children:s("Previous linked records")}),vn("button",{type:"button",disabled:!A.next||A.loading,onClick:()=>{C((P)=>[...P,m]),h(A.next??void 0)},children:s("Next linked records")})]}),vn("small",{children:s("{count} selected · up to 100 per record across all link fields",{count:u.length})})]})}var fc={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function tr(e,t,n){return t?se(n)(fc[t]):e==null?"—":String(e)}function es(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 ts(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function fi(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function ns(e,t,n){let o=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...fi(e),filter:ts(e.filter,o)}}function Dr(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 os(e,t,n){let{start:o,end:i}=Dr(n);return{...fi(e),filter:ts(e.filter,{fieldId:t,operator:"onOrAfter",value:o},{fieldId:t,operator:"before",value:i})}}function yi(e,t){let n={id:"date",name:"Date",type:"date"},o=String(Cn(t,n)),i=String(Cn(String(e),n));return`${o.slice(0,10)}${i.slice(10)}`}function Mo(e,t){return[...t.columnOrder,...e.map((o)=>o.id).filter((o)=>!t.columnOrder.includes(o))].filter((o)=>!t.hiddenColumns.includes(o)).flatMap((o)=>e.filter((i)=>i.id===o))}function $t(e,t){let n=t.find((o)=>o.type==="singleLineText"||o.type==="longText");return(n?et(e.values[n.id]):"")||e.id}function Mn(e,t,n){if(t.type==="lookup")return so(e);if(t.type==="hyperlink")return Sr(e);if(t.type==="date"){let o=Et(t);return o?$n(e,o):pi(e)}if(t.type==="number"){let o=Fo(t);return o?To(e,o):et(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return tr(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 et(e)}import{createContext as yc,useContext as bc,useEffect as hc,useId as Cc,useLayoutEffect as vc,useMemo as xc,useRef as kc,useState as nr}from"react";import{jsx as un,jsxs as or}from"react/jsx-runtime";var is=yc(void 0);function pa(e){return un(is.Provider,{value:e.client,children:e.children})}var Fr=()=>bc(is),rs=(e)=>/^https?:/i.test(e);function bi(e){let t=Fr();if(!Qo(e.value))return null;let n=e.value,o=t?.href?.(n)??n.url;return un("a",{href:o,title:n.url,"data-uibot-link":n.ref?.kind??(rs(o)?"external":"internal"),...rs(o)?{target:"_blank",rel:"noopener noreferrer"}:{},style:{color:"var(--uibot-link, currentColor)",textDecoration:"underline",textUnderlineOffset:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...e.style},onMouseDown:(i)=>i.stopPropagation(),onDoubleClick:(i)=>i.stopPropagation(),onClick:(i)=>{if(i.stopPropagation(),!(i.button!==0||i.metaKey||i.ctrlKey||i.shiftKey||i.altKey)&&t?.open?.(n))i.preventDefault()},children:Sr(n)})}var Er=(e)=>e?JSON.stringify(e):"",wc=(e)=>e.trim().startsWith("{")?Ao(e):null;function Tr(e){let t=xc(()=>se(e.locale),[e.locale]),n=Fr(),o=Cc(),i=wc(e.text),[r,l]=nr(()=>i?"":e.text),[d,a]=nr(!1),[s,u]=nr([]),[c,g]=nr(""),[p,m]=nr(-1),h=kc(null),[x,C]=nr(null),f=e.field.hyperlink?.kinds?.join(",")??"";hc(()=>{if(!n||!d||e.disabled)return;let P=new AbortController,I=setTimeout(()=>{g(t("Searching…")),n.search({search:r.trim(),...f?{kinds:f.split(",")}:{},limit:8},{signal:P.signal}).then((k)=>{if(P.signal.aborted)return;u(k.ok?k.data.slice(0,8):[]),g(k.ok?"":k.error.message)}).catch((k)=>{if(!P.signal.aborted)g(k instanceof Error?k.message:String(k))})},200);return()=>{clearTimeout(I),P.abort()}},[n,d,r,f,e.disabled,t]);let R=Ao(r),S=(P)=>n?.kinds?.find((I)=>I.id===P)?.label??P,A=[...R&&!R.ref?[{key:"typed",value:R,title:t("Use link {url}",{url:R.url})}]:[],...s.map((P)=>({key:`${P.kind}:${P.id}`,value:{url:P.url,text:P.title,ref:{kind:P.kind,id:P.id}},title:P.title,subtitle:[S(P.kind),P.subtitle].filter(Boolean).join(" · ")}))],L=Boolean(n&&!c&&!s.length&&r.trim()),M=d&&!e.disabled&&(A.length>0||Boolean(c)||L);vc(()=>{if(!M)return;let P=()=>C(h.current?.getBoundingClientRect()??null);return P(),window.addEventListener("scroll",P,!0),window.addEventListener("resize",P),()=>{window.removeEventListener("scroll",P,!0),window.removeEventListener("resize",P)}},[M]);let U=(P)=>{l(""),m(-1),e.onChange(Er(P.value))},J=(P)=>{l(P),m(-1),e.onChange(P||Er(i))};return or("div",{style:{display:"grid",gap:4,minWidth:0,height:"100%"},children:[un("input",{ref:h,id:e.id,role:"combobox","aria-label":e.ariaLabel,"aria-expanded":M,"aria-controls":o,"aria-autocomplete":"list","aria-invalid":e.invalid,...e.describedBy?{"aria-describedby":e.describedBy}:{},...p>=0?{"aria-activedescendant":`${o}-${p}`}:{},disabled:e.disabled,placeholder:i?Sr(i):t("Search or paste a link"),value:r,style:e.inputStyle,className:e.inputClassName,onFocus:()=>a(!0),onBlur:()=>a(!1),onChange:(P)=>J(P.currentTarget.value),onKeyDown:(P)=>{if(e.onSave||e.onCancel)P.stopPropagation();if(P.key==="ArrowDown"||P.key==="ArrowUp"){if(!A.length)return;P.preventDefault();let I=P.key==="ArrowDown"?1:-1;m((k)=>I>0?(k+1)%A.length:k<=0?A.length-1:k-1)}else if(P.key==="Enter"){P.preventDefault();let I=A[p];if(I)U(I);else e.onSave?.()}else if(P.key==="Tab"&&e.onSave)P.preventDefault(),e.onSave();else if(P.key==="Escape")if(P.preventDefault(),r)J("");else e.onCancel?.()}}),i&&!r&&!e.onSave&&or("div",{style:{display:"grid",gap:4,minWidth:0,fontSize:12},children:[or("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[un(bi,{value:i,style:{flex:"0 1 auto"}}),un("span",{style:{flex:"1 1 0",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:0.6},children:i.url}),un("button",{type:"button","aria-label":t("Remove link"),title:t("Remove link"),disabled:e.disabled,onMouseDown:(P)=>P.preventDefault(),onClick:()=>e.onChange(""),style:{border:0,background:"none",color:"inherit",cursor:"pointer",opacity:0.6},children:"×"})]}),or("label",{style:{display:"grid",gap:2},children:[un("span",{style:{opacity:0.7},children:t("Display text")}),un("input",{"aria-label":t("Display text"),placeholder:i.url,value:i.text??"",disabled:e.disabled,className:e.inputClassName,onChange:(P)=>{let I=P.currentTarget.value.slice(0,500),{text:k,...T}=i;e.onChange(Er(I?{...T,text:I}:T))}})]})]}),M&&x&&or("div",{id:o,role:"listbox","aria-label":t("Link suggestions"),style:{position:"fixed",top:x.bottom+4,left:x.left,width:Math.max(x.width,280),maxHeight:320,overflowY:"auto",zIndex:1000,padding:4,border:"1px solid var(--uibot-border, #d4d4d8)",borderRadius:8,background:"var(--uibot-surface, var(--background, #fff))",color:"var(--uibot-text, inherit)",boxShadow:"0 8px 24px rgb(0 0 0 / 0.12)"},onMouseDown:(P)=>P.preventDefault(),children:[A.map((P,I)=>or("div",{id:`${o}-${I}`,role:"option","aria-selected":I===p,tabIndex:-1,onMouseEnter:()=>m(I),onClick:()=>U(P),onKeyDown:()=>{},style:{display:"grid",gap:2,padding:"6px 8px",borderRadius:6,cursor:"pointer",background:I===p?"var(--uibot-hover, rgb(0 0 0 / 0.06))":void 0},children:[un("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:P.title}),P.subtitle&&un("span",{style:{fontSize:12,opacity:0.65},children:P.subtitle})]},P.key)),c&&un("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:c}),L&&un("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:t("No matching resources")})]})]})}import{useEffect as ls,useId as Sc,useMemo as Rc,useRef as Ic,useState as ss}from"react";var Pc=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function co(e){return Pc.test(e)}var jn=(e)=>String(e).padStart(2,"0");function as(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${jn(t.getMonth()+1)}-${jn(t.getDate())}T${jn(t.getHours())}:${jn(t.getMinutes())}:${jn(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var ma=(e,t)=>{let n=Nn(e,t);return`${n.year}-${jn(n.month)}-${jn(n.day)}T${jn(n.hour)}:${jn(n.minute)}`};function fa(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!co(e))return e.slice(0,10);return ma(new Date(e),t.timeZone??"UTC").slice(0,10)}if(co(e))return ma(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function ya(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||co(t)))return e;let i=e.length>10?e.slice(11,16):t&&co(t)?ma(new Date(t),n.timeZone).slice(11,16):"00:00",[r,l,d]=e.slice(0,10).split("-").map(Number),[a,s]=i.split(":").map(Number),u=lo({year:r??0,month:l??1,day:d??1,hour:a??0,minute:s??0},n.timeZone);return Number.isFinite(u.getTime())?u.toISOString():e}import{jsx as uo,jsxs as ds}from"react/jsx-runtime";function rr(e,t,n){if(e.type==="blob")return"";try{return Cn(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==="hyperlink")return se(n)("{name} needs a link.",{name:e.name});if(e.type==="json")return n==="zh-CN"?`${e.name}必须是有效 JSON。`:`${e.name} needs valid JSON.`;return n==="zh-CN"?"输入值无效":"Invalid value"}}function ba({field:e,text:t,disabled:n,id:o,label:i,ariaLabel:r,onChange:l,onSave:d,onCancel:a,locale:s="en",submitted:u=!1,describedBy:c}){let g=Rc(()=>se(s),[s]),p=Sc(),m=Ic(null),h=Boolean(d);ls(()=>{if(h)m.current?.querySelector("input,textarea,select")?.focus()},[h]);let x=o??p,C=`${x}-error`,[w,f]=ss(t),[R,S]=ss(!1);ls(()=>f(t),[t]);let A=rr(e,w,s),M=Boolean(e.required&&w===""&&A)&&!R&&!u?"":A,U=r??i??e.name,J=e.type==="date"&&co(w),P=J&&!A?as(w):w,I=[c,M?C:void 0].filter(Boolean).join(" "),k={id:x,"aria-label":U,"aria-invalid":Boolean(M),...I?{"aria-describedby":I}:{},disabled:n,onBlur:()=>S(!0),onKeyDown:(F)=>{if(d||a)F.stopPropagation();let H=e.type==="longText"||e.type==="json";if(F.key==="Tab"&&d)F.preventDefault(),d(F.shiftKey?"previous":"next");else if(F.key==="Enter"&&!F.shiftKey&&d&&(!H||F.ctrlKey||F.metaKey))F.preventDefault(),d();else if(F.key==="Escape"&&a)F.preventDefault(),a()},style:{width:"100%",...h?{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"},T=(F)=>{S(!0),f(F),l(F)},D=(F)=>{if(e.type==="date"&&J&&F){let H=new Date(F);T(Number.isFinite(H.getTime())?H.toISOString():F)}else T(F)},B;if(e.type==="hyperlink")B=uo(Tr,{field:e,text:w,id:x,ariaLabel:U,invalid:Boolean(M),describedBy:I||void 0,disabled:n,locale:s,inputStyle:k.style,inputClassName:k.className,onChange:T,onSave:d,onCancel:a});else if(e.type==="checkbox")B=ds("select",{...k,value:w,onChange:(F)=>T(F.currentTarget.value),children:[!e.required&&uo("option",{value:"",children:g("No value")}),uo("option",{value:"true",children:g("Yes")}),uo("option",{value:"false",children:g("No")})]});else if(e.type==="longText"||e.type==="json")B=uo("textarea",{...k,value:w,rows:e.type==="json"?4:3,onChange:(F)=>T(F.currentTarget.value)});else{let F=e.type==="date"&&!(A&&w)?J?"datetime-local":"date":"text",H=e.type==="blob";B=uo("input",{...k,type:F,inputMode:e.type==="number"?"decimal":void 0,step:J?"0.001":void 0,value:P,readOnly:H,onInput:e.type==="date"?(z)=>D(z.currentTarget.value):void 0,onChange:(z)=>D(z.currentTarget.value)})}return ds("div",{ref:m,className:"grid min-w-0 gap-1",style:h?{height:"100%"}:void 0,children:[i&&uo("label",{className:"text-xs font-medium",htmlFor:x,children:i}),B,M&&uo("span",{id:C,role:"alert",className:"text-xs text-red-600",children:M})]})}import{useEffect as Dc,useRef as Ec}from"react";import{jsx as cs}from"react/jsx-runtime";var Ac={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 Ce({name:e,size:t=15,style:n}){return cs("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:cs("path",{d:Ac[e]})})}import{jsx as go,jsxs as us,Fragment as Fc}from"react/jsx-runtime";var ir={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function W({ui:e,style:t,variant:n,size:o,children:i,disabled:r,onClick:l,title:d,ariaLabel:a,icon:s,iconOnly:u,badge:c}){let g=e?.Button,p=s?us("span",{style:{position:"relative",display:"inline-flex"},children:[go(Ce,{name:s}),c?go("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,m=u?p:us(Fc,{children:[p,i]}),h=a,x=d??(u?h:void 0),C=u?"icon":o;if(g)return go(g,{...n?{variant:n}:{},...C?{size:C}:{},disabled:r,onClick:l,title:x,"aria-label":h,children:m});return go("button",{type:"button",style:{...s?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?ir:{},...u?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:r,onClick:l,title:x,"aria-label":h,children:m})}function Je({ui:e,value:t,options:n,onChange:o,disabled:i,label:r,style:l,"aria-describedby":d,"aria-invalid":a}){let s=e?.Select,u={...d?{"aria-describedby":d}:{},...a?{"aria-invalid":!0}:{}};if(s)return go(s,{value:t,options:n,onChange:o,disabled:i,"aria-label":r,...u});return go("select",{"aria-label":r,...u,style:l,disabled:i,value:t,onChange:(c)=>o(c.target.value),children:n.map((c)=>go("option",{value:c.value,disabled:c.disabled,children:c.label},c.value))})}function hi({label:e,busy:t,onCancel:n,children:o,alert:i=!1}){let r=Ec(null);return Dc(()=>{let l=r.current,d=document.activeElement;if(l?.showModal)l.showModal();else l?.setAttribute("open","");return()=>{if(l?.close?.(),d instanceof HTMLElement&&d.isConnected)d.focus({preventScroll:!0})}},[]),go("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:(l)=>{if(l.key!=="Tab")return;let d=l.currentTarget,a=[...d.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter((c)=>!c.hidden),s=a[0],u=a.at(-1);if(!s||(l.shiftKey?document.activeElement===s:document.activeElement===u)||!d.contains(document.activeElement)){if(l.preventDefault(),(l.shiftKey?u:s)?.focus(),!s)d.focus()}},tabIndex:-1,onCancel:(l)=>{if(l.preventDefault(),!t)n()},children:o})}import{useEffect as gs,useRef as Nr,useState as Ln}from"react";import{jsx as ke,jsxs as _e,Fragment as Mc}from"react/jsx-runtime";function Tc(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 Nc=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function ha({descriptor:e,fieldIds:t,query:n,client:o,readOnly:i=!1,reloadKey:r=0,onImported:l,onRefreshSchema:d}){let[a,s]=Ln(null),[u,c]=Ln(null),[g,p]=Ln(null),[m,h]=Ln([]),[x,C]=Ln(""),[w,f]=Ln(!1),[R,S]=Ln(!1),[A,L]=Ln(!0),[M,U]=Ln(null),[J,P]=Ln(!1),I=Nr(!1),k=Nr(!1),T=Nr(!1),D=Nr(null),B=Nr({client:o,onImported:l,descriptor:e});B.current={client:o,onImported:l,descriptor:e},gs(()=>(I.current=!0,()=>{I.current=!1,k.current=!1}),[]),gs(()=>{let q=!0;if(!i)o.imports(e.id).then((te)=>{if(!q||!I.current||!te.ok)return;if(h((le)=>te.data.map((ve)=>{let xe=le.find((ae)=>ae.id===ve.id);return xe&&xe.version>ve.version?xe:ve})),!T.current)p((le)=>{let ve=te.data.find((xe)=>xe.id===le?.id);return le&&ve&&ve.version>le.version?ve:le})});return()=>{q=!1}},[o,e.id,i,r]);let F=(q)=>{p(q),h((te)=>[q,...te.filter((le)=>le.id!==q.id)].slice(0,50)),U(null)};async function H(q){if(T.current||i)return;T.current=!0,k.current=!0,f(!0),S(!0),C("");let te=q;try{while(I.current&&k.current&&te.status==="ready"){let le=await B.current.client.advanceImport(e.id,te.id,te.version);if(!I.current)break;if(!le.ok){C(le.error.message);break}let ve=le.data;if(F(ve),ve.importedRows>te.importedRows)B.current.onImported();if(ve.version===te.version&&ve.status==="ready"){C("Import paused. Refresh the saved progress before retrying.");break}te=ve}}finally{if(T.current=!1,k.current=!1,I.current)f(!1),S(!1)}}async function z(){if(!a||T.current)return;T.current=!0,f(!0),C("");let q=await o.previewImport(e.id,{...a,expectedSchemaVersion:e.schemaVersion});if(T.current=!1,!I.current)return;if(f(!1),q.ok)c(q.data),s({...a,expectedSchemaVersion:q.data.schemaVersion,mapping:q.data.mapping});else C(q.error.message)}async function ce(){if(!a||!u||u.missingRequiredFieldIds.length||!u.totalRows||T.current||i)return;T.current=!0,f(!0),C(""),D.current??=crypto.randomUUID();let q=await o.createImport(e.id,{...a,idempotencyKey:D.current});if(T.current=!1,!I.current)return;if(f(!1),q.ok)F(q.data),s(null),c(null),D.current=null,H(q.data);else C(q.error.message)}async function Z(){if(!g||T.current||i)return;if(g.status==="ready"){H(g);return}T.current=!0,f(!0),C("");let q=d?await d():B.current.descriptor;if(!q){T.current=!1,f(!1),C("Refresh the collection schema and try again.");return}let te=await o.resumeImport(e.id,g.id,g.version,q.schemaVersion);if(T.current=!1,!I.current)return;if(f(!1),te.ok)F(te.data),H(te.data);else C(te.error.message)}async function fe(q){if(!g)return;let te=await o.importErrors(e.id,g.id,{limit:100,...q===void 0?{}:{cursor:q},expectedVersion:g.version});if(!I.current)return;if(te.ok)U(te.data);else C(te.error.message)}async function Q(q=!1){if(w||T.current)return;T.current=!0,f(!0),C("");let te=q&&g?await o.exportImportErrors(e.id,g.id):await o.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:A});if(T.current=!1,!I.current)return;if(f(!1),te.ok)Tc(te.data),C(`${te.data.rowCount} rows downloaded${te.data.protectedCells?`; ${te.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else C(te.error.message)}return _e("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"}),_e("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[_e("div",{className:"flex flex-wrap items-center gap-3",children:[ke("button",{type:"button",disabled:w||!t.length,onClick:()=>void Q(),children:"Export CSV"}),_e("label",{className:"flex items-center gap-2 text-sm",children:[ke("input",{type:"checkbox",checked:A,onChange:(q)=>L(q.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&&_e(Mc,{children:[_e("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:w,onChange:async(q)=>{let te=q.target.files?.[0];if(!te)return;if(C(""),c(null),s(null),D.current=null,te.size>20971520){C("Choose a UTF-8 CSV file no larger than 20 MiB.");return}f(!0),T.current=!0;try{let le=new TextDecoder("utf-8",{fatal:!0}).decode(await te.arrayBuffer());if(I.current)s({fileName:te.name,csv:le,expectedSchemaVersion:e.schemaVersion})}catch{if(I.current)C("The file must be valid UTF-8 text.")}finally{if(T.current=!1,I.current)f(!1)}}})]}),a&&_e("div",{className:"flex flex-wrap gap-3",children:[ke("span",{className:"break-all text-sm",children:a.fileName}),ke("button",{type:"button",disabled:w,onClick:()=>void z(),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."}),u&&a&&_e("div",{className:"flex min-w-0 flex-col gap-3",children:[_e("p",{className:"text-sm",children:[u.totalRows," rows · ",u.validRows," valid · ",u.invalidRows," ","invalid · ",u.ignoredColumns.length," skipped columns"]}),u.headers.map((q,te)=>_e("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[_e("span",{className:"max-w-64 break-all",children:["Column ",te+1,": ",q||"(empty)"]}),_e("select",{"aria-label":`Column ${te+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:a.mapping?.[te]??"",disabled:w,onChange:(le)=>{let ve=[...a.mapping??u.mapping];ve[te]=le.target.value||null,s({...a,mapping:ve}),c(null),D.current=null},children:[ke("option",{value:"",children:"Skip column"}),e.fields.filter((le)=>!it(le)).map((le)=>_e("option",{value:le.id,children:[le.name," (",le.id,")",le.required?" · required":""]},le.id))]})]},`${te}:${q}`)),u.missingRequiredFieldIds.length>0&&_e("p",{role:"alert",children:["Map required fields: ",u.missingRequiredFieldIds.join(", ")]}),ke("div",{className:"max-w-full overflow-x-auto",children:_e("table",{className:"w-full text-xs",children:[_e("caption",{children:["First ",u.sample.length," normalized rows; row numbers include the header."]}),ke("thead",{children:_e("tr",{children:[ke("th",{children:"Row"}),ke("th",{children:"Normalized values"}),ke("th",{children:"Error"})]})}),ke("tbody",{children:u.sample.map((q)=>_e("tr",{children:[ke("td",{children:q.rowNumber}),ke("td",{className:"max-w-96 break-all",children:Nc(q.values)}),ke("td",{children:q.error?.code??""})]},q.rowNumber))})]})}),ke("button",{type:"button",className:"self-start",disabled:w||!u.totalRows||u.missingRequiredFieldIds.length>0,onClick:()=>void ce(),children:"Confirm import"})]}),_e("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",_e("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:g?.id??"",disabled:w,onChange:async(q)=>{if(!q.target.value){p(null);return}let te=await o.importJob(e.id,q.target.value);if(I.current)if(te.ok)F(te.data),P(!1);else C(te.error.message)},children:[ke("option",{value:"",children:"Choose saved progress…"}),m.map((q)=>_e("option",{value:q.id,children:[q.fileName," · ",q.processedRows,"/",q.totalRows," · ",q.status]},q.id))]})]}),ke("button",{type:"button",className:"self-start",disabled:w,onClick:async()=>{let q=await o.imports(e.id);if(I.current)if(q.ok)h(q.data);else C(q.error.message)},children:"Refresh saved imports"}),g&&_e("div",{className:"flex flex-col gap-3",children:[_e("p",{role:"status",children:[R?"Importing":g.status==="ready"?"Paused":g.status==="schemaChanged"?"Schema changed — confirm before continuing":g.status==="completed"?"Completed":"Cancelled"," ","· ",g.processedRows," of ",g.totalRows," processed · ",g.importedRows," imported ·"," ",g.failedRows," failed"]}),ke("progress",{"aria-label":"Import progress",max:g.totalRows,value:g.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."}),_e("div",{className:"flex flex-wrap gap-3",children:[R&&ke("button",{type:"button",onClick:()=>{k.current=!1,S(!1)},children:"Pause import"}),!R&&(g.status==="ready"||g.status==="schemaChanged")&&ke("button",{type:"button",disabled:w,onClick:()=>void Z(),children:g.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(g.status==="ready"||g.status==="schemaChanged")&&ke("button",{type:"button",disabled:w,onClick:()=>P(!0),children:"Cancel import"}),ke("button",{type:"button",disabled:w||!g.failedRows,onClick:()=>void fe(),children:"Show import errors"}),ke("button",{type:"button",disabled:w||!g.failedRows,onClick:()=>void Q(!0),children:"Download all import errors"})]}),J&&_e("div",{children:[_e("p",{children:["Stop remaining rows? The ",g.importedRows," imported records will remain."]}),ke("button",{type:"button",disabled:w,onClick:async()=>{T.current=!0,f(!0);let q=await o.cancelImport(e.id,g.id);if(T.current=!1,!I.current)return;if(f(!1),q.ok)F(q.data),P(!1);else C(q.error.message)},children:"Confirm cancellation"}),ke("button",{type:"button",onClick:()=>P(!1),children:"Keep import"})]}),M&&_e("div",{className:"max-w-full overflow-x-auto",children:[_e("table",{className:"w-full text-xs",children:[_e("caption",{children:[M.total," failed rows"]}),ke("thead",{children:_e("tr",{children:[ke("th",{children:"Row"}),ke("th",{children:"Field"}),ke("th",{children:"Error"})]})}),ke("tbody",{children:M.items.map((q)=>_e("tr",{children:[ke("td",{children:q.rowNumber}),ke("td",{children:q.fieldId??""}),ke("td",{children:q.code})]},q.rowNumber))})]}),M.nextCursor!==null&&ke("button",{type:"button",onClick:()=>void fe(M.nextCursor??void 0),children:"Next errors"})]})]})]}),x&&ke("p",{role:"alert",className:"break-words text-sm",children:x})]})]})}import{useEffect as ps,useRef as Lo,useState as Oo}from"react";import{jsx as Ze,jsxs as jt,Fragment as Oc}from"react/jsx-runtime";var Ci=[{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 Lc({descriptor:e,client:t,onConverted:n}){let o=e.fields.filter((F)=>Ci.some((H)=>H.type===F.type)),[i,r]=Oo(o[0]?.id??""),l=o.find((F)=>F.id===i)??o[0],[d,a]=Oo(l?.type??"singleLineText"),[s,u]=Oo(l?.required??!1),[c,g]=Oo(l?.options?.map((F)=>`${F.id}=${F.name}`).join(`
5
- `)??""),[p,m]=Oo(null),[h,x]=Oo(""),[C,w]=Oo(!1),f=Lo(null),R=Lo(null),S=Lo(0),A=Lo(e);A.current=e;let L=f.current?.field??l,M=C||f.current!==null,U=`${e.id}:${e.schemaVersion}:${JSON.stringify(e.fields)}`,J=Lo(e.fields);J.current=e.fields;let P=Lo(U);P.current=U;let I=Lo(!0);ps(()=>(I.current=!0,()=>{I.current=!1,S.current++}),[]),ps(()=>{if(P.current!==U)return;if(f.current&&R.current===e.id)return;S.current++;let F=J.current.find((H)=>H.id===i&&Ci.some((z)=>z.type===H.type))??J.current.find((H)=>Ci.some((z)=>z.type===H.type));if(F)r(F.id),a(F.type),u(F.required??!1),g(F.options?.map((H)=>`${H.id}=${H.name}`).join(`
6
- `)??"");m(null),f.current=null,R.current=null,x(""),w(!1)},[U,i,e.id]);let k=()=>{m(null),f.current=null,R.current=null,S.current++,x("")},T=(F)=>{r(F.id),a(F.type),u(F.required??!1),g(F.options?.map((H)=>`${H.id}=${H.name}`).join(`
7
- `)??""),k()};if(!L)return null;let D=()=>{let F={id:L.id,name:L.name,type:d,required:s};if(d==="singleSelect"||d==="multipleSelect")F.options=c.split(`
8
- `).filter((H)=>H.trim()).map((H)=>{let z=H.indexOf("=");if(z<1)throw Error("Each option must use stable_id=Display name.");return{id:H.slice(0,z).trim(),name:H.slice(z+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:F}},B=()=>I.current&&P.current===U;return jt("details",{className:"rounded-lg border p-4",children:[Ze("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),jt("div",{className:"mt-4 flex flex-col gap-3",children:[Ze("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."}),jt("label",{children:["Field"," ",jt("select",{"aria-label":"Conversion field",value:L.id,disabled:M,onChange:(F)=>{let H=o.find((z)=>z.id===F.target.value);if(H)T(H)},children:[f.current&&!o.some((F)=>F.id===L.id)&&Ze("option",{value:L.id,children:L.name}),o.map((F)=>Ze("option",{value:F.id,children:F.name},F.id))]})]}),jt("label",{children:["Target type"," ",Ze("select",{"aria-label":"Conversion target type",value:d,disabled:M,onChange:(F)=>{a(F.target.value),k()},children:Ci.map((F)=>Ze("option",{value:F.type,children:F.label},F.type))})]}),jt("label",{children:[Ze("input",{type:"checkbox",checked:s,disabled:M,onChange:(F)=>{u(F.target.checked),k()}})," ","Required after conversion"]}),(d==="singleSelect"||d==="multipleSelect")&&jt("label",{children:["Stable option IDs and display names",Ze("textarea",{"aria-label":"Conversion options",className:"block w-full rounded border p-2",disabled:M,value:c,onChange:(F)=>{g(F.target.value),k()},placeholder:`open=Open
9
- done=Done`})]}),h&&Ze("p",{role:"alert",className:"text-sm text-destructive",children:h}),Ze("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:M,onClick:async()=>{let F;try{F=D()}catch(H){x(H instanceof Error?H.message:"Invalid conversion options.");return}w(!0),x(""),m(null),f.current=null;try{let H=await t.previewConversion(e.id,F);if(!B())return;if(H.ok)m(H.data);else x(H.error.message)}catch{if(B())x("Preview unavailable. Your draft is kept.")}finally{if(B())w(!1)}},children:C?"Working…":"Preview conversion"}),p&&jt(Oc,{children:[jt("p",{role:"status",children:[p.validRows," valid · ",p.invalidRows," invalid"]}),jt("p",{className:"text-xs",children:["Preview covers ",p.totalRows," records. Samples and errors show at most 20 records."]}),Ze("div",{className:"overflow-x-auto",children:jt("table",{className:"w-full text-sm",children:[Ze("thead",{children:jt("tr",{children:[Ze("th",{children:"Record"}),Ze("th",{children:"Before"}),Ze("th",{children:"After"}),Ze("th",{children:"Error"})]})}),Ze("tbody",{children:p.sample.map((F)=>jt("tr",{children:[Ze("td",{className:"max-w-32 break-all",children:F.id}),Ze("td",{className:"max-w-48 break-words",children:JSON.stringify(F.before)}),Ze("td",{className:"max-w-48 break-words",children:JSON.stringify(F.after)}),Ze("td",{children:F.error})]},F.id))})]})}),p.errors.length>0&&Ze("ul",{children:p.errors.map((F)=>jt("li",{children:[Ze("span",{className:"break-all",children:F.id}),": ",Ze("span",{children:F.code})]},F.id))}),Ze("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:C||p.invalidRows>0,onClick:async()=>{if(!f.current)R.current=e.id,S.current++;f.current??={expectedSchemaVersion:p.schemaVersion,field:p.field,previewToken:p.previewToken,idempotencyKey:crypto.randomUUID()};let F=f.current,H=S.current,z=()=>I.current&&A.current.id===e.id&&H===S.current;w(!0),x("");try{let ce=await t.convertField(e.id,F);if(!z())return;if(ce.ok){if(m(null),f.current=null,R.current=null,ce.data.descriptor.schemaVersion>=A.current.schemaVersion)n(ce.data.descriptor)}else if(x(ce.error.message),ce.error.status===409)m(null),f.current=null,R.current=null}catch{if(z())x("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(z())w(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as Vc,useRef as Ca,useState as ms}from"react";import{jsx as fs,jsxs as Uc}from"react/jsx-runtime";function Bc({collectionIds:e,client:t,onChanges:n,pollIntervalMs:o=2000}){let i=JSON.stringify([...new Set(e)].sort()),r=Ca(i);r.current=i;let l=Ca(n);l.current=n;let d=Ca(()=>{}),[a,s]=ms("connecting"),[u,c]=ms(!1);return Vc(()=>{let g=JSON.parse(i),p=new Map,m=!1,h=!1,x=0,C,w=()=>!m&&r.current===i,f=Math.max(50,Math.min(60000,o)),R=async()=>{if(!w()||h)return;h=!0,c(!0);let L=!1;try{let M=x>0;for(let U of g){let J=p.get(U),P=await t.changes(U,{...J!==void 0?{cursor:J}:{},limit:100});if(!w())return;if(!P.ok)throw s(P.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let I=J===void 0;if(I||M||P.data.items.length>0)await l.current(U,P.data,I);if(!w())return;p.set(U,P.data.cursor),L||=P.data.hasMore}x=0,s("live")}catch{if(x++,w())s((M)=>M==="expired"?"expired":"offline")}finally{if(h=!1,w())c(!1),C=setTimeout(()=>{R()},L&&x===0?0:Math.min(30000,f*2**Math.min(x,8)))}},S=()=>{if(C!==void 0)clearTimeout(C);R()};d.current=S,s("connecting"),R();let A=()=>{if(document.visibilityState==="visible")S()};return window.addEventListener("online",S),document.addEventListener("visibilitychange",A),()=>{if(m=!0,C!==void 0)clearTimeout(C);window.removeEventListener("online",S),document.removeEventListener("visibilitychange",A)}},[i,t,o]),Uc("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[fs("p",{role:"status",children:a==="live"?"Live updates":a==="connecting"?"Connecting live updates…":a==="expired"?"Session expired. Renew your session; drafts are kept.":"Connection interrupted. Drafts are kept."}),(a==="offline"||a==="expired")&&fs("button",{type:"button",className:"rounded border px-2 py-1",disabled:u,onClick:()=>d.current(),children:"Reconnect now"})]})}import{useEffect as vi,useRef as po,useState as Qt}from"react";import{jsx as Ie,jsxs as qe,Fragment as ka}from"react/jsx-runtime";var xa={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function Mr(e){try{return await e()}catch{return{ok:!1,error:xa}}}function va({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return qe("div",{className:"min-w-0",children:[Ie("strong",{children:t}),Ie("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&&qe(ka,{children:[Ie("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),Ie("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 _c({descriptor:e,recordId:t,client:n,readOnly:o=!1,onCommitted:i,registerRefresh:r}){let[l,d]=Qt(null),[a,s]=Qt(null),[u,c]=Qt(null),[g,p]=Qt(),[m,h]=Qt(),[x,C]=Qt([]),[w,f]=Qt([]),[R,S]=Qt(""),[A,L]=Qt(null),[M,U]=Qt(null),[J,P]=Qt(null),[I,k]=Qt(!1),[T,D]=Qt(""),B=po(null),F=po(null),H=po(n);H.current=n;let z=po(!1),ce=po(0),Z=`${e.id}:${t}`,fe=po(Z);fe.current=Z;let Q=po({historyBefore:g,commentBefore:m});Q.current={historyBefore:g,commentBefore:m};let q=po(async()=>{}),te=(v=Z)=>z.current&&fe.current===v&&H.current===n,le=async()=>{let v=Z,X=++ce.current,oe=Q.current,[tt,Pt]=await Promise.all([Mr(()=>n.history(e.id,t,{...oe.historyBefore===void 0?{}:{before:oe.historyBefore},limit:20})),Mr(()=>n.comments(e.id,t,{...oe.commentBefore===void 0?{}:{before:oe.commentBefore},limit:50}))]);if(!te(v)||X!==ce.current)throw Error("Refresh superseded");if(!tt.ok||!Pt.ok)throw D(!tt.ok?tt.error.message:!Pt.ok?Pt.error.message:xa.message),Error("Activity refresh failed");s(tt.data),c(Pt.data),d(v)};q.current=le,vi(()=>(z.current=!0,()=>{z.current=!1,ce.current++}),[]),vi(()=>(r?.(()=>q.current()),()=>r?.(null)),[r]),vi(()=>{if(fe.current!==Z)return;s(null),c(null),d(null),p(void 0),h(void 0),C([]),f([]),Q.current={historyBefore:void 0,commentBefore:void 0},S(""),L(null),U(null),P(null),B.current=null,F.current=null,k(!1),D("")},[Z]),vi(()=>{if(fe.current!==Z||H.current!==n||Q.current.historyBefore!==g||Q.current.commentBefore!==m)return;q.current().catch(()=>{})},[Z,n,g,m]);let ve=(v)=>{let X=B.current;if(X?.signature===v)return X.key;let oe={signature:v,key:crypto.randomUUID()};return B.current=oe,oe.key},xe=async(v)=>{if(I||o||!u||l!==Z)return;let X=v==="delete"?M:A;if(v!=="create"&&(!X||X.authorId!==u.actorId))return;let oe=v==="create"?R:A?.draft??"";if(v!=="delete"&&(!oe.trim()||oe.length>4000||oe.includes("\x00"))){D("Comments require 1–4,000 characters.");return}let tt=ve(JSON.stringify([v,X?.id,X?.version,oe]));k(!0),D("");let Pt=await Mr(async()=>{if(v==="create")return n.createComment(e.id,t,{text:oe,idempotencyKey:tt});if(!X)return{ok:!1,error:xa};if(v==="edit")return n.editComment(e.id,t,X.id,{text:oe,expectedVersion:X.version,idempotencyKey:tt});return n.deleteComment(e.id,t,X.id,{expectedVersion:X.version,idempotencyKey:tt})});if(!te())return;if(k(!1),!Pt.ok){D(Pt.error.message);return}if(B.current=null,v==="create")S("");else if(v==="edit")L(null);else U(null);if(v==="create"&&m!==void 0)h(void 0),f([]);else await q.current().catch(()=>{})},ae=async(v)=>{if(I||o||!a||l!==Z)return;k(!0),D(""),F.current=null;let X={targetVersion:v,expectedCurrentVersion:a.currentVersion,expectedSchemaVersion:e.schemaVersion},oe=await Mr(()=>n.previewUndo(e.id,t,X));if(!te())return;if(k(!1),oe.ok)P(oe.data);else P(null),D(oe.error.message)},Te=async()=>{if(I||o||l!==Z||!J&&!F.current)return;let v=F.current;if(!v){if(!J)return;v={targetVersion:J.targetVersion,expectedCurrentVersion:J.currentVersion,expectedSchemaVersion:J.schemaVersion,idempotencyKey:crypto.randomUUID()},F.current=v}let X=v;k(!0),D("");let oe=await Mr(()=>n.undo(e.id,t,X));if(!te())return;if(k(!1),!oe.ok){if(oe.error.code==="version_conflict"||oe.error.code==="reference_conflict"||oe.error.code==="validation")F.current=null,P(null);D(oe.error.message),await q.current().catch(()=>{});return}F.current=null,P(null),i(oe.data),p(void 0),C([]),await q.current().catch(()=>{})},pe=u?.items.find((v)=>v.id===A?.id),Me=A&&pe&&pe.version!==A.version,j=J&&(J.currentVersion!==a?.currentVersion||J.schemaVersion!==e.schemaVersion);return qe("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[qe("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[qe("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),Ie("button",{type:"button",disabled:I,onClick:()=>{D(""),q.current().catch(()=>{})},children:"Refresh activity"})]}),T&&Ie("p",{role:"alert",className:"text-sm text-destructive",children:T}),!a||!u||l!==Z?Ie("p",{role:"status",children:"Loading record activity…"}):qe(ka,{children:[qe("p",{role:"status",children:["Current version ",a.currentVersion,a.currentDeleted?" · Deleted record":""]}),Ie("h3",{className:"font-medium",children:"Comments"}),u.items.length===0&&Ie("p",{className:"text-sm",children:"No comments yet."}),Ie("ol",{className:"flex flex-col gap-3",children:u.items.map((v)=>qe("li",{className:"min-w-0 rounded border p-3",children:[qe("p",{className:"break-all text-xs",children:[v.authorId," · ",v.updatedAt," · version ",v.version]}),Ie("p",{className:"whitespace-pre-wrap break-words text-sm",children:v.text??"Comment deleted"}),!o&&v.text!==null&&v.authorId===u.actorId&&qe("div",{className:"flex gap-3",children:[Ie("button",{type:"button",disabled:I,onClick:()=>{L({...v,draft:v.text??""}),U(null),B.current=null},children:"Edit comment"}),Ie("button",{type:"button",disabled:I,onClick:()=>{U(v),L(null),B.current=null},children:"Delete comment"})]})]},v.id))}),qe("div",{className:"flex gap-3",children:[Ie("button",{type:"button",disabled:I||!w.length,onClick:()=>{h(w.at(-1)),f((v)=>v.slice(0,-1))},children:"Newer comments"}),Ie("button",{type:"button",disabled:I||u.nextCursor===null,onClick:()=>{f((v)=>[...v,m]),h(u.nextCursor??void 0)},children:"Older comments"})]}),!o&&qe(ka,{children:[A&&qe("div",{className:"flex flex-col gap-2",children:[qe("label",{children:["Edit comment text",Ie("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:I,maxLength:4000,value:A.draft,onChange:(v)=>{L({...A,draft:v.target.value}),B.current=null}})]}),Me&&qe("div",{role:"status",children:[Ie("p",{children:"This comment changed. Your draft and original version are kept."}),qe("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",pe.text??"Comment deleted"]}),pe.text!==null&&pe.authorId===u.actorId&&Ie("button",{type:"button",disabled:I,onClick:()=>{L({...pe,draft:A.draft}),B.current=null},children:"Use current comment version"})]}),qe("div",{className:"flex gap-3",children:[Ie("button",{type:"button",disabled:I||A.authorId!==u.actorId,onClick:()=>void xe("edit"),children:"Save comment"}),Ie("button",{type:"button",disabled:I,onClick:()=>{L(null),B.current=null},children:"Cancel comment edit"})]})]}),M&&qe("div",{children:[Ie("p",{children:"Delete this comment? A deletion marker will remain."}),Ie("p",{className:"whitespace-pre-wrap break-words",children:M.text}),Ie("button",{type:"button",disabled:I||M.authorId!==u.actorId,onClick:()=>void xe("delete"),children:"Confirm delete comment"}),Ie("button",{type:"button",disabled:I,onClick:()=>U(null),children:"Cancel delete comment"})]}),qe("label",{children:["New comment",Ie("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:I,maxLength:4000,value:R,onChange:(v)=>{S(v.target.value),B.current=null}})]}),Ie("button",{type:"button",className:"self-start",disabled:I||!R.trim(),onClick:()=>void xe("create"),children:"Add comment"})]}),Ie("h3",{className:"font-medium",children:"Record history"}),Ie("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."}),Ie("ol",{className:"flex flex-col gap-3",children:a.items.map((v)=>qe("li",{className:"min-w-0 rounded border p-3",children:[qe("p",{className:"break-all text-xs",children:["Version ",v.version," · ",v.operation," · schema ",v.schemaVersion," · ",v.actorId," ·"," ",v.createdAt]}),qe("details",{children:[qe("summary",{children:["Stored values at version ",v.version]}),Ie(va,{record:v.snapshot,label:`Version ${v.version}`})]}),!o&&v.version<a.currentVersion&&qe("button",{type:"button",disabled:I,onClick:()=>void ae(v.version),children:["Preview restore version ",v.version]})]},v.id))}),qe("div",{className:"flex gap-3",children:[Ie("button",{type:"button",disabled:I||!x.length,onClick:()=>{p(x.at(-1)),C((v)=>v.slice(0,-1))},children:"Newer history"}),Ie("button",{type:"button",disabled:I||a.nextCursor===null,onClick:()=>{C((v)=>[...v,g]),p(a.nextCursor??void 0)},children:"Older history"})]}),!o&&J&&qe("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[qe("h3",{children:["Restore version ",J.targetVersion," as a new version"]}),qe("p",{children:["Current version ",J.currentVersion," · schema ",J.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),qe("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[Ie(va,{record:J.before,label:"Current stored values"}),Ie(va,{record:J.target,label:"Values to restore"})]}),j&&!F.current&&Ie("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),qe("div",{className:"flex gap-3",children:[Ie("button",{type:"button",disabled:I||!!j&&!F.current,onClick:()=>void Te(),children:F.current?"Retry undo":"Confirm restore"}),Ie("button",{type:"button",disabled:I,onClick:()=>{P(null),F.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as xi,useRef as mo,useState as Kn}from"react";import{jsx as Ft,jsxs as Xt,Fragment as ys}from"react/jsx-runtime";async function ki(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 zc(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let o of t)n+=String.fromCharCode(o);return btoa(n)}function qc({collectionId:e,recordId:t,client:n,readOnly:o=!1,registerRefresh:i}){let r=`${e}:${t}`,l=mo({identity:r,client:n});l.current={identity:r,client:n};let d=mo(!1),a=mo(0),s=mo(0),[u,c]=Kn(null),[g,p]=Kn(null),[m,h]=Kn(),[x,C]=Kn([]),w=mo(m);w.current=m;let[f,R]=Kn(null),[S,A]=Kn(null),L=mo(null),M=mo(null),[U,J]=Kn(!1),[P,I]=Kn(!1),[k,T]=Kn(""),D=()=>d.current&&l.current.identity===r&&l.current.client===n,B=async()=>{let Z=++a.current,fe=await ki(()=>n.list(e,t,{limit:20,...w.current===void 0?{}:{before:w.current}}));if(!D()||Z!==a.current)throw Error("Refresh superseded");if(!fe.ok)throw T(fe.error.message),Error("Attachment refresh failed");p(fe.data),c(r)},F=mo(B);F.current=B,xi(()=>(d.current=!0,()=>{d.current=!1,++a.current,++s.current}),[]),xi(()=>{if(l.current.identity!==r||l.current.client!==n)return;c(null),p(null),R(null),A(null),L.current=null,J(!1),I(!1),T(""),h(void 0),C([]),w.current=void 0,++s.current,F.current().catch(()=>{})},[r,n]),xi(()=>{if(w.current===m&&u===r)F.current().catch(()=>{})},[m,r,u]),xi(()=>(i?.(()=>F.current()),()=>i?.(null)),[i]);let H=async()=>{if(U||o||!f||u!==r)return;let Z=f;J(!0),T("");let fe=await ki(()=>n.upload(e,t,Z));if(!D())return;if(J(!1),!fe.ok){T(fe.error.message);return}if(R(null),M.current)M.current.value="";h(void 0),C([]),w.current=void 0,await F.current().catch(()=>{})},z=async()=>{if(U||o||!S||S.authorId!==g?.actorId||u!==r)return;L.current??=crypto.randomUUID();let Z=S,fe=L.current;J(!0),T("");let Q=await ki(()=>n.delete(e,t,Z.id,{expectedVersion:Z.version,idempotencyKey:fe}));if(!D())return;if(J(!1),!Q.ok){T(Q.error.message),await F.current().catch(()=>{});return}A(null),L.current=null,await F.current().catch(()=>{})},ce=async(Z)=>{if(U||u!==r)return;J(!0),T("");let fe=await ki(()=>n.content(e,t,Z.id));if(!D())return;if(J(!1),!fe.ok){T(fe.error.message);return}let Q=Uint8Array.from(atob(fe.data.base64),(le)=>le.charCodeAt(0)),q=URL.createObjectURL(new Blob([Q],{type:"application/octet-stream"})),te=document.createElement("a");te.href=q,te.download=fe.data.attachment.name,te.click(),setTimeout(()=>URL.revokeObjectURL(q),1000)};return Xt("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Xt("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ft("h3",{className:"font-medium",children:"Attachments"}),Ft("button",{type:"button",disabled:U,onClick:()=>{T(""),F.current().catch(()=>{})},children:"Refresh attachments"})]}),k&&Ft("p",{role:"alert",children:k}),!g||u!==r?Ft("p",{role:"status",children:"Loading attachments…"}):Xt(ys,{children:[g.items.length===0&&Ft("p",{children:"No attachments yet."}),Ft("ol",{className:"flex min-w-0 flex-col gap-2",children:g.items.map((Z)=>Xt("li",{className:"min-w-0 rounded border p-2",children:[Ft("p",{className:"break-all",children:Z.name}),Xt("p",{className:"break-all text-xs",children:[Z.size," bytes · version ",Z.version," · ",Z.authorId]}),Z.deletedAt?Ft("p",{children:"Attachment deleted"}):Xt("div",{className:"flex flex-wrap gap-3",children:[Ft("button",{type:"button",disabled:U,"aria-label":`Download attachment ${Z.name}`,onClick:()=>void ce(Z),children:"Download"}),!o&&Z.authorId===g.actorId&&Ft("button",{type:"button",disabled:U,"aria-label":`Delete attachment ${Z.name}`,onClick:()=>{A(Z),L.current=null},children:"Delete"})]})]},Z.id))}),Xt("div",{className:"flex flex-wrap gap-3",children:[Ft("button",{type:"button",disabled:U||!x.length,onClick:()=>{h(x.at(-1)),C((Z)=>Z.slice(0,-1))},children:"Newer attachments"}),Ft("button",{type:"button",disabled:U||g.nextCursor===null,onClick:()=>{C((Z)=>[...Z,m]),h(g.nextCursor??void 0)},children:"Older attachments"})]}),!o&&Xt(ys,{children:[Ft("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."}),Xt("label",{children:["Attachment file",Ft("input",{ref:M,"aria-label":"Attachment file",type:"file",disabled:U||P,onChange:async(Z)=>{let fe=Z.target.files?.[0];if(!fe)return;let Q=++s.current;if(R(null),T(""),!fe.size||fe.size>1048576){T("Choose a nonempty file up to 1 MiB.");return}I(!0);try{let q=await zc(fe);if(!D()||Q!==s.current)return;let te=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(fe.type)?fe.type:"application/octet-stream";R({name:fe.name,contentType:te,base64:q,idempotencyKey:crypto.randomUUID()})}catch{if(D()&&Q===s.current)T("The selected file could not be read.")}finally{if(D()&&Q===s.current)I(!1)}}},r)]}),f&&Xt("p",{className:"break-all",children:["Selected file: ",f.name]}),Ft("button",{type:"button",className:"self-start",disabled:U||P||!f,onClick:()=>void H(),children:"Upload attachment"}),S&&Xt("div",{children:[Xt("p",{className:"break-all",children:["Delete ",S.name,"? This permanently removes its bytes and keeps a deletion marker."]}),Xt("div",{className:"flex flex-wrap gap-3",children:[Ft("button",{type:"button",disabled:U,onClick:()=>void z(),children:"Confirm delete attachment"}),Ft("button",{type:"button",disabled:U,onClick:()=>{A(null),L.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as wi,useRef as ar,useState as en}from"react";import{jsx as Ke,jsxs as ct,Fragment as bs}from"react/jsx-runtime";async function wa(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function Hc(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function $c({descriptor:e,recordIds:t,client:n,linkForGrant:o,registerRefresh:i}){let r=e.id,l=ar({identity:r,client:n});l.current={identity:r,client:n};let d=ar(!1),a=ar(0),[s,u]=en(null),[c,g]=en(null),[p,m]=en(),h=ar(p);h.current=p;let[x,C]=en([]),[w,f]=en([]),[R,S]=en([]),[A,L]=en(3600),[M,U]=en(null),[J,P]=en(!1),[I,k]=en(""),[T,D]=en(null),B=ar(null),[F,H]=en(!1),[z,ce]=en(""),Z=()=>d.current&&l.current.identity===r&&l.current.client===n,fe=async()=>{let ae=++a.current,Te=await wa(()=>n.list(r,{limit:20,...h.current===void 0?{}:{before:h.current}}));if(!Z()||ae!==a.current)throw Error("Refresh superseded");if(!Te.ok)throw ce(Te.error.message),Error("Share refresh failed");g(Te.data),u(r)},Q=ar(fe);Q.current=fe,wi(()=>(d.current=!0,()=>{d.current=!1,++a.current}),[]),wi(()=>{if(l.current.identity!==r||l.current.client!==n)return;u(null),g(null),f([]),S([]),U(null),P(!1),k(""),D(null),B.current=null,H(!1),ce(""),m(void 0),C([]),h.current=void 0,Q.current().catch(()=>{})},[r,n]),wi(()=>{if(h.current===p&&s===r)Q.current().catch(()=>{})},[p,s,r]),wi(()=>(i?.(()=>Q.current()),()=>i?.(null)),[i]);let q=()=>{if(!J)U(null)},te=async()=>{if(F||!M||s!==r)return;let ae=M;H(!0),P(!0),ce("");let Te=await wa(()=>n.create(r,ae));if(!Z())return;if(H(!1),!Te.ok){ce(Te.error.message);return}k(o(Te.data,ae.key)),U(null),P(!1),m(void 0),C([]),h.current=void 0,await Q.current().catch(()=>{})},le=async()=>{if(F||!T||s!==r)return;let ae=T;B.current??=crypto.randomUUID();let Te=B.current;H(!0),ce("");let pe=await wa(()=>n.revoke(r,ae.id,{expectedVersion:ae.version,idempotencyKey:Te}));if(!Z())return;if(H(!1),!pe.ok){ce(pe.error.message),await Q.current().catch(()=>{});return}D(null),B.current=null,k(""),await Q.current().catch(()=>{})},ve=e.fields.filter((ae)=>!["linkedRecord","lookup","formula","rollup"].includes(ae.type)),xe=F||J;return ct("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[ct("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ke("h3",{className:"font-medium",children:"Read-only sharing"}),Ke("button",{type:"button",disabled:F,onClick:()=>{ce(""),Q.current().catch(()=>{})},children:"Refresh share grants"})]}),Ke("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."}),Ke("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."}),z&&Ke("p",{role:"alert",children:z}),ct("fieldset",{disabled:xe,className:"flex min-w-0 flex-col gap-2",children:[Ke("legend",{children:"Fields to share"}),ve.map((ae)=>ct("label",{className:"break-all",children:[Ke("input",{type:"checkbox","aria-label":`Share field ${ae.name}`,checked:w.includes(ae.id),onChange:(Te)=>{q(),f((pe)=>Te.target.checked?[...pe,ae.id]:pe.filter((Me)=>Me!==ae.id))}})," ",ae.name]},ae.id))]}),ct("fieldset",{disabled:xe,className:"flex min-w-0 flex-col gap-2",children:[Ke("legend",{children:"Records on the current page"}),t.slice(0,100).map((ae)=>ct("label",{className:"break-all",children:[Ke("input",{type:"checkbox","aria-label":`Share record ${ae}`,checked:R.includes(ae),onChange:(Te)=>{q(),S((pe)=>Te.target.checked?[...pe,ae]:pe.filter((Me)=>Me!==ae))}})," ",ae]},ae)),t.length===0&&Ke("p",{children:"Load records in Grid to choose a share scope."})]}),ct("p",{className:"break-all text-xs",children:["Selected record IDs: ",R.join(", ")||"none"]}),ct("label",{children:["Link lifetime"," ",ct("select",{"aria-label":"Share link lifetime",disabled:xe,value:A,onChange:(ae)=>{q(),L(Number(ae.target.value))},children:[Ke("option",{value:60,children:"1 minute"}),Ke("option",{value:3600,children:"1 hour"}),Ke("option",{value:86400,children:"24 hours"})]})]}),Ke("button",{type:"button",className:"self-start",disabled:xe||s!==r||!w.length||!R.length||R.length>100||w.some((ae)=>!ve.some((Te)=>Te.id===ae)),onClick:()=>{ce("");try{U({expectedSchemaVersion:e.schemaVersion,fieldIds:[...w],recordIds:[...R],expiresInSeconds:A,key:Hc(),idempotencyKey:crypto.randomUUID()})}catch{ce("A secure share key could not be generated.")}},children:"Review read-only share"}),M&&ct("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[ct("p",{className:"break-all",children:["Confirm schema ",M.expectedSchemaVersion,", fields ",M.fieldIds.join(", "),", records ",M.recordIds.join(", ")," for ",M.expiresInSeconds," seconds."]}),M.expectedSchemaVersion!==e.schemaVersion&&Ke("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),ct("div",{className:"flex flex-wrap gap-3",children:[Ke("button",{type:"button",disabled:F,onClick:()=>void te(),children:J?"Retry create read link":"Create read link"}),Ke("button",{type:"button",disabled:F,onClick:()=>{U(null),P(!1),ce("")},children:"Discard share confirmation"})]}),J&&Ke("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."})]}),I&&ct("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",Ke("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:I,onFocus:(ae)=>ae.target.select()})]}),!c||s!==r?Ke("p",{role:"status",children:"Loading share grants…"}):ct(bs,{children:[c.items.length===0&&Ke("p",{children:"No share grants yet."}),Ke("ol",{className:"flex min-w-0 flex-col gap-2",children:c.items.map((ae)=>ct("li",{className:"min-w-0 rounded border p-2",children:[ct("p",{className:"break-all",children:["Grant ",ae.id," · version ",ae.version," · schema ",ae.schemaVersion]}),ct("p",{className:"break-all text-xs",children:["Fields: ",ae.fieldIds.join(", ")," · Records: ",ae.recordIds.join(", ")," · Expires:"," ",ae.expiresAt]}),ae.revokedAt?Ke("p",{children:"Share revoked"}):ct(bs,{children:[Ke("p",{children:ae.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(ae.expiresAt)<=Date.now()?"Share expired":"Share active"}),Ke("button",{type:"button",disabled:F,"aria-label":`Revoke share ${ae.id}`,onClick:()=>{D(ae),B.current=null},children:"Revoke"})]})]},ae.id))}),ct("div",{className:"flex flex-wrap gap-3",children:[Ke("button",{type:"button",disabled:F||!x.length,onClick:()=>{m(x.at(-1)),C((ae)=>ae.slice(0,-1))},children:"Newer share grants"}),Ke("button",{type:"button",disabled:F||c.nextCursor===null,onClick:()=>{C((ae)=>[...ae,p]),m(c.nextCursor??void 0)},children:"Older share grants"})]})]}),T&&ct("div",{children:[ct("p",{className:"break-all",children:["Revoke grant ",T.id," at version ",T.version,"? Every existing share session will lose access."]}),ct("div",{className:"flex flex-wrap gap-3",children:[Ke("button",{type:"button",disabled:F,onClick:()=>void le(),children:"Confirm revoke share"}),Ke("button",{type:"button",disabled:F,onClick:()=>{D(null),B.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as hs,useRef as lr,useState as _t}from"react";import{jsx as De,jsxs as gt}from"react/jsx-runtime";var Cs=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],jc=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function Kc({descriptor:e,recordIds:t,client:n,webhookRequest:o}){let i=e.id,r=lr({id:i,client:n});r.current={id:i,client:n};let l=lr(!0),d=lr(0),[a,s]=_t([]),[u,c]=_t(""),g=lr(u);g.current=u;let[p,m]=_t(null),[h,x]=_t(),C=lr(h);C.current=h;let[w,f]=_t(""),[R,S]=_t("record"),[A,L]=_t(60),[M,U]=_t([]),[J,P]=_t([]),[I,k]=_t({}),[T,D]=_t(null),[B,F]=_t(!1),[H,z]=_t(!1),[ce,Z]=_t(""),[fe,Q]=_t(""),q=()=>l.current&&r.current.id===i&&r.current.client===n,te=async(j)=>{try{return await j()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},le=async()=>{let j=++d.current,v=await te(()=>n.list(i));if(!q()||j!==d.current)return;if(!v.ok){Z(v.error.message);return}s(v.data);let X=v.data.find((tt)=>tt.id===g.current)?.id??v.data[0]?.id??"";if(g.current=X,c(X),!X){m(null);return}let oe=await te(()=>n.runs(i,X,{limit:20,...C.current?{before:C.current}:{}}));if(!q()||j!==d.current||g.current!==X)return;if(oe.ok)m(oe.data);else Z(oe.error.message)},ve=lr(le);ve.current=le,hs(()=>{if(r.current.id!==i||r.current.client!==n)return;l.current=!0,ve.current();let j=setInterval(()=>void ve.current(),5000);return()=>{l.current=!1,++d.current,clearInterval(j)}},[i,n]),hs(()=>{if(g.current!==u||C.current!==h)return;ve.current()},[u,h]);let xe=()=>{if(Z(""),!w.trim()||!M.length||R!=="record"&&!J.length){Z("Choose a name, writable fields, and target records for time or webhook triggers.");return}let j=Object.fromEntries(M.map((X)=>[X,I[X]??null])),v={expectedSchemaVersion:e.schemaVersion,name:w.trim(),trigger:R==="time"?{kind:R,intervalSeconds:A}:{kind:R},targetRecordIds:J,values:j,idempotencyKey:crypto.randomUUID(),...R==="webhook"?{webhookKey:jc()}:{}};D({kind:"create",input:v}),F(!1)},ae=(j)=>{D(j),F(!1),Z("")},Te=async()=>{if(!T||H)return;let j=T,v=B;F(!0),z(!0),Z("");let X=await te(()=>j.kind==="create"?n.create(i,j.input):j.kind==="toggle"?n.toggle(i,j.a.id,j.input):j.kind==="run"?n.runNow(i,j.a.id,j.input):n.retry(i,j.a.id,j.run.id,j.input));if(!q())return;if(z(!1),!X.ok){if(!v&&X.error.status>=400&&X.error.status<500)F(!1);Z(`${X.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(j.kind==="create"){let oe=X.data;if(g.current=oe.id,c(oe.id),j.input.webhookKey&&o)Q(JSON.stringify(o(oe,j.input.webhookKey),null,2));f(""),U([]),P([]),k({})}D(null),F(!1),C.current=void 0,x(void 0),await ve.current()},pe=a.find((j)=>j.id===u),Me=!!T||H;return gt("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[De("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."}),De("button",{type:"button",onClick:()=>void ve.current(),children:"Refresh automation"}),ce&&De("p",{role:"alert",children:ce}),De("form",{onSubmit:(j)=>{j.preventDefault(),xe()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:gt("fieldset",{disabled:Me,style:{minWidth:0},children:[De("legend",{children:"New automation"}),gt("label",{children:["Name"," ",De("input",{"aria-label":"Automation name",value:w,maxLength:200,onChange:(j)=>f(j.target.value)})]}),gt("label",{children:["Trigger"," ",gt("select",{"aria-label":"Automation trigger",value:R,onChange:(j)=>S(j.target.value),children:[De("option",{value:"record",children:"Record changes"}),De("option",{value:"time",children:"Timed interval"}),De("option",{value:"webhook",children:"Private webhook"})]})]}),R==="time"&&gt("label",{children:["Interval in seconds"," ",De("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:A,onChange:(j)=>L(Number(j.target.value))})]}),gt("fieldset",{children:[De("legend",{children:"Fields to update"}),e.fields.filter((j)=>Cs.includes(j.type)).map((j)=>gt("label",{style:{display:"block"},children:[De("input",{type:"checkbox",checked:M.includes(j.id),onChange:(v)=>{U(v.target.checked?[...M,j.id]:M.filter((X)=>X!==j.id))}}),j.name]},j.id))]}),De(Vo,{fields:e.fields.filter((j)=>M.includes(j.id)&&Cs.includes(j.type)),values:I,onChange:k}),gt("fieldset",{children:[De("legend",{children:"Target records from this page"}),R==="record"&&De("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&De("p",{children:"Open a grid page to choose fixed records."}),t.map((j)=>gt("label",{style:{display:"block",overflowWrap:"anywhere"},children:[De("input",{type:"checkbox","aria-label":`Automation target ${j}`,checked:J.includes(j),onChange:(v)=>P(v.target.checked?[...J,j]:J.filter((X)=>X!==j))}),j]},j))]}),De("button",{type:"submit",children:"Review automation"})]})}),T&&gt("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[De("p",{children:T.kind==="create"?`Create ${T.input.name} using schema ${T.input.expectedSchemaVersion}; ${T.input.targetRecordIds.length||"event"} targets.`:T.kind==="toggle"?`${T.input.enabled?"Enable":"Disable"} ${T.a.name}. Disabling fences queued and running work.`:T.kind==="run"?`Run ${T.a.name} for ${T.input.recordIds.length} explicitly selected records.`:`Retry ${T.a.name}, run ${T.run.sequence}, using its original record versions.`}),T.kind==="create"&&De("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(T.input.values,null,2)}),De("button",{type:"button",disabled:H,onClick:()=>void Te(),children:H?"Confirming…":B?"Retry automation confirmation":"Confirm automation"}),De("button",{type:"button",disabled:B||H,onClick:()=>D(null),children:"Cancel automation review"}),B&&De("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),fe&&gt("div",{children:[De("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),De("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:fe}),De("button",{type:"button",onClick:()=>Q(""),children:"Hide webhook key"})]}),a.length>0&&gt("label",{children:["Automation"," ",De("select",{"aria-label":"Selected automation",disabled:Me,value:u,onChange:(j)=>{g.current=j.target.value,C.current=void 0,x(void 0),c(j.target.value),m(null)},children:a.map((j)=>De("option",{value:j.id,children:j.name},j.id))})]}),pe&&gt("div",{children:[gt("p",{children:[pe.enabled?"Enabled":"Disabled"," · ",pe.trigger.kind," · schema ",pe.schemaVersion," · configuration ",pe.version]}),De("button",{type:"button",disabled:Me,onClick:()=>ae({kind:"toggle",a:pe,input:{expectedVersion:pe.version,enabled:!pe.enabled,idempotencyKey:crypto.randomUUID()}}),children:pe.enabled?"Review disable automation":"Review enable automation"}),De("button",{type:"button",disabled:Me||!pe.enabled||!(pe.targetRecordIds.length||t.length),onClick:()=>ae({kind:"run",a:pe,input:{recordIds:pe.targetRecordIds.length?pe.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),p&&gt("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!p.items.length&&De("p",{children:"No runs yet."}),p.items.map((j)=>gt("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[gt("p",{children:["Run ",j.sequence," · ",j.triggerKind," · ",j.status," · step ",j.step]}),gt("p",{children:["Attempts: evaluate ",j.stepAttempts.evaluate,", apply ",j.stepAttempts.apply," · original versions: ",j.expectedRows.map((v)=>`${v.id}: ${v.version}`).join(", ")]}),j.errorCode&&De("p",{role:"status",children:j.errorCode}),j.leaseUntil&&gt("p",{children:["Lease expires ",j.leaseUntil]}),pe&&j.status==="failed"&&gt("button",{type:"button",disabled:Me||!pe.enabled,onClick:()=>ae({kind:"retry",a:pe,run:j,input:{expectedVersion:j.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",j.sequence]})]},j.id)),De("button",{type:"button",disabled:Me||h===void 0,onClick:()=>{C.current=void 0,x(void 0)},children:"Newest runs"}),De("button",{type:"button",disabled:Me||p.nextCursor===null,onClick:()=>{C.current=p.nextCursor??void 0,x(C.current)},children:"Older runs"})]})]})}import{useEffect as Wc,useId as Gc,useRef as vs,useState as Lt}from"react";import{jsx as He,jsxs as pt}from"react/jsx-runtime";var xs=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function Yc(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((l)=>l.id===r&&xs.includes(l.type))))throw Error("Choose up to ten basic source and target fields.");let o=n.recordIds.map((i)=>{let r=t.find((l)=>l.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 Jc({descriptor:e,records:t,client:n,onApplied:o}){let i=Gc(),r=e.id,l=vs({id:r,client:n}),d=vs(!0);l.current={id:r,client:n};let[a,s]=Lt([]),[u,c]=Lt(!1),[g,p]=Lt(""),[m,h]=Lt(""),[x,C]=Lt(""),[w,f]=Lt([]),[R,S]=Lt([]),[A,L]=Lt([]),[M,U]=Lt(null),[J,P]=Lt(null),[I,k]=Lt(null),[T,D]=Lt(!1),[B,F]=Lt(!1),[H,z]=Lt(""),[ce,Z]=Lt(""),[fe,Q]=Lt(""),q=()=>d.current&&l.current.id===r&&l.current.client===n,te=async(v)=>{try{return await v()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};Wc(()=>{d.current=!0,U(null),P(null),k(null),D(!1),z(""),Z(""),Q(""),f([]),S([]),L([]),C("");let v=!0;return c(!1),F(!1),s([]),p(""),h(""),n.providers(r).then((X)=>{if(!v||l.current.id!==r||l.current.client!==n)return;if(c(!0),X.ok)s(X.data),p(X.data[0]?.resourceId??""),h(X.data[0]?.allowedModels[0]??"");else z(X.error.message)}).catch(()=>{if(v)c(!0),z("AI configuration is unavailable.")}),()=>{v=!1,d.current=!1}},[r,n]);let le=()=>{try{let v=Yc(e,t,{resourceId:g,model:m,instruction:x,recordIds:w,sourceFieldIds:R,targetFieldIds:A});P(structuredClone(v.records.map((X)=>({id:X.id,version:X.expectedVersion,values:Object.fromEntries(v.sourceFieldIds.map((oe)=>[oe,t.find((tt)=>tt.id===X.id)?.values[oe]??null]))})))),U(v),D(!1),z(""),Z("")}catch(v){z(v instanceof Error?v.message:"Invalid selection.")}},ve=async()=>{if(!M||B)return;let v=M,X=T;F(!0),D(!0),z("");let oe=await te(()=>n.propose(r,v));if(!q())return;if(F(!1),!oe.ok){if(!X&&oe.error.status>=400&&oe.error.status<500)D(!1);z(`${oe.error.message} Retry keeps the original selection and versions.`);return}k(oe.data),Q(oe.data.id),D(!1)},xe=async()=>{if(!I||B)return;let v=I,X=T;F(!0),D(!0),z("");let oe=await te(()=>n.confirm(r,v));if(!q())return;if(F(!1),!oe.ok){if(!X&&oe.error.status>=400&&oe.error.status<500)D(!1);z(`${oe.error.message} The reviewed proposal keeps its original versions.`);return}Z(`${oe.data.items.length} records filled${oe.data.replayed?"; original receipt recovered":""}.`),k(null),U(null),P(null),D(!1);try{await o?.()}catch{if(q())z("The fill committed. Refresh the Collection to see its records.")}},ae=async()=>{if(B||M||I)return;F(!0),z("");let v=await te(()=>n.get(r,fe));if(!q())return;if(F(!1),v.ok)k(v.data),D(!1),Z("");else z(v.error.message)},Te=(v,X,oe)=>oe(v.includes(X)?v.filter((tt)=>tt!==X):[...v,X]),pe=B||!!M||!!I,Me=e.fields.filter((v)=>xs.includes(v.type)),j=a.find((v)=>v.resourceId===g);return pt("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[He("p",{children:"Choose the records and fields to send to your configured AI service. Review suggested values before writing. Conflicts keep the original record versions."}),H&&He("p",{role:"alert",children:H}),ce&&He("p",{role:"status",children:ce}),u&&a.length===0&&He("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),He("form",{onSubmit:(v)=>{v.preventDefault(),le()},children:pt("fieldset",{disabled:pe,style:{minWidth:0},children:[He("legend",{children:"AI fill request"}),pt("label",{children:["AI resource"," ",pt("select",{"aria-label":"AI resource",value:g,onChange:(v)=>{p(v.target.value),h(a.find((X)=>X.resourceId===v.target.value)?.allowedModels[0]??"")},children:[He("option",{value:"",children:"Choose resource"}),a.map((v)=>He("option",{value:v.resourceId,children:v.name},v.resourceId))]})]}),pt("label",{htmlFor:i,children:["Model"," ",j?.allowedModels.length?He("select",{id:i,"aria-label":"AI model",value:m,onChange:(v)=>h(v.target.value),children:j.allowedModels.map((v)=>He("option",{value:v,children:v},v))}):He("input",{id:i,"aria-label":"AI model",maxLength:200,value:m,onChange:(v)=>h(v.target.value)})]}),pt("label",{children:["Instructions"," ",He("textarea",{"aria-label":"AI instructions",maxLength:2000,value:x,onChange:(v)=>C(v.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),pt("fieldset",{children:[He("legend",{children:"Source fields to send"}),Me.map((v)=>pt("label",{style:{display:"block"},children:[He("input",{type:"checkbox","aria-label":`Send ${v.name}`,checked:R.includes(v.id),onChange:()=>Te(R,v.id,S)}),v.name]},v.id))]}),pt("fieldset",{children:[He("legend",{children:"Fields to fill"}),Me.map((v)=>pt("label",{style:{display:"block"},children:[He("input",{type:"checkbox","aria-label":`Fill ${v.name}`,checked:A.includes(v.id),onChange:()=>Te(A,v.id,L)}),v.name]},v.id))]}),pt("fieldset",{children:[He("legend",{children:"Target records from this page"}),t.map((v)=>pt("label",{style:{display:"block",overflowWrap:"anywhere"},children:[He("input",{type:"checkbox","aria-label":`AI record ${v.id}`,checked:w.includes(v.id),onChange:()=>Te(w,v.id,f)}),v.id," · version ",v.version]},v.id))]}),He("button",{type:"submit",disabled:!g,children:"Review AI request"})]})}),M&&!I&&pt("section",{"aria-label":"AI data disclosure",children:[pt("p",{children:["Selected service: ",M.resourceId," · model ",M.model," · schema"," ",M.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),He("p",{children:M.instruction}),He("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(J,null,2)}),He("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),He("button",{type:"button",disabled:B,onClick:()=>void ve(),children:T?"Retry original AI request":"Generate proposal"}),He("button",{type:"button",disabled:B||T,onClick:()=>{U(null),P(null),z("")},children:"Cancel AI request"})]}),I&&pt("section",{"aria-label":"AI fill confirmation",children:[pt("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",I.id," · ",I.provider," · schema ",I.schemaVersion]}),I.schemaVersion!==e.schemaVersion&&He("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),I.rows.map((v)=>pt("div",{style:{overflowWrap:"anywhere"},children:[pt("p",{children:[v.id," · original version ",v.expectedVersion]}),Object.keys(v.values).map((X)=>pt("div",{children:[He("strong",{children:e.fields.find((oe)=>oe.id===X)?.name??X}),pt("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(v.before[X]),`
10
- `,"Suggested: ",JSON.stringify(v.values[X])]})]},X))]},v.id)),He("button",{type:"button",disabled:B,onClick:()=>void xe(),children:T?"Retry original AI fill":"Confirm fill"}),He("button",{type:"button",disabled:B||T,onClick:()=>{k(null),U(null),P(null),z("")},children:"Dismiss proposal"})]}),pt("label",{children:["Recover a saved proposal"," ",He("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:fe,onChange:(v)=>Q(v.target.value),disabled:pe,style:{width:"100%",boxSizing:"border-box"}})]}),He("button",{type:"button",disabled:pe||!/^[a-f0-9]{64}$/.test(fe),onClick:()=>void ae(),children:"Load saved proposal"})]})}import{jsx as me,jsxs as Ee}from"react/jsx-runtime";var Qc=[{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 zy({fields:e,onChange:t,lockedIds:n=[],collections:o=[]}){let i=(r,l)=>t(e.map((d,a)=>a===r?{...d,...l}:d));return Ee("div",{className:"flex flex-col gap-3",children:[e.map((r,l)=>{let d=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:[me("input",{"aria-label":`Field ${l+1} name`,placeholder:"Display name",value:r.name,onChange:(a)=>i(l,{name:a.target.value})}),me("input",{"aria-label":`Field ${l+1} ID`,placeholder:"field_id",value:r.id,disabled:d,onChange:(a)=>i(l,{id:a.target.value})}),me("select",{"aria-label":`Field ${l+1} type`,className:"rounded-md border bg-background px-2 text-sm",value:r.type,disabled:d,onChange:(a)=>{let s=a.target.value,u={id:r.id,name:r.name,type:s,required:it({type:s})?!1:r.required??!1};if(s==="formula")u.formula={expression:""};if(s==="rollup")u.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(s==="singleSelect"||s==="multipleSelect")u.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((c,g)=>g===l?u:c))},children:Qc.map((a)=>me("option",{value:a.value,children:a.name},a.value))}),Ee("div",{className:"flex items-center gap-2",children:[Ee("label",{className:"flex items-center gap-1 text-xs",children:[me("input",{type:"checkbox",checked:r.required??!1,disabled:d||n.length>0||it(r),onChange:(a)=>i(l,{required:a.target.checked})}),"Required"]}),!d&&me("button",{type:"button",onClick:()=>t(e.filter((a,s)=>s!==l)),children:"Remove"})]}),(r.type==="singleSelect"||r.type==="multipleSelect")&&me("input",{className:"md:col-span-4","aria-label":`Field ${l+1} options`,placeholder:"Open, Done",value:r.options?.map((a)=>a.name).join(", ")??"",disabled:d,onChange:(a)=>i(l,{options:a.target.value.split(",").map((s,u)=>({id:s.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${u}`,name:s.trim()})).filter((s)=>s.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 ${l+1} linked collection`,value:r.link?.collectionId??"",disabled:d,onChange:(a)=>{let s=o.find((u)=>u.id===a.target.value);i(l,{link:{collectionId:a.target.value,displayFieldId:s?.fields.find((u)=>u.type==="singleLineText"||u.type==="longText")?.id??""}})},children:[me("option",{value:"",children:"Choose collection…"}),o.map((a)=>me("option",{value:a.id,children:a.name},a.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 ${l+1} record label`,value:r.link?.displayFieldId??"",disabled:d||!r.link?.collectionId,onChange:(a)=>i(l,{link:{collectionId:r.link?.collectionId??"",displayFieldId:a.target.value}}),children:[me("option",{value:"",children:"Choose text field…"}),o.find((a)=>a.id===r.link?.collectionId)?.fields.filter((a)=>a.type==="singleLineText"||a.type==="longText").map((a)=>me("option",{value:a.id,children:a.name},a.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 ${l+1} lookup link`,value:r.lookup?.linkFieldId??"",disabled:d,onChange:(a)=>i(l,{lookup:{linkFieldId:a.target.value,targetFieldId:""}}),children:[me("option",{value:"",children:"Choose linked field…"}),e.filter((a)=>a.type==="linkedRecord"&&a.link).map((a)=>me("option",{value:a.id,children:a.name},a.id))]})]}),Ee("label",{children:["Read target field"," ",Ee("select",{"aria-label":`Field ${l+1} lookup target`,value:r.lookup?.targetFieldId??"",disabled:d||!r.lookup?.linkFieldId,onChange:(a)=>i(l,{lookup:{linkFieldId:r.lookup?.linkFieldId??"",targetFieldId:a.target.value}}),children:[me("option",{value:"",children:"Choose target field…"}),o.find((a)=>a.id===e.find((s)=>s.id===r.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((a)=>!it(a)&&a.type!=="linkedRecord").map((a)=>me("option",{value:a.id,children:a.name},a.id))]})]}),me("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",me("textarea",{"aria-label":`Field ${l+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:(a)=>i(l,{formula:{expression:a.target.value}})})]}),me("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((a)=>a.id!==r.id&&(a.type==="singleLineText"||a.type==="longText"||a.type==="date"||a.type==="number"||a.type==="formula"||a.type==="rollup")).map((a)=>`{${a.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 ${l+1} rollup link`,value:r.rollup?.linkFieldId??"",onChange:(a)=>i(l,{rollup:{linkFieldId:a.target.value,targetFieldId:"",function:r.rollup?.function??"sum"}}),children:[me("option",{value:"",children:"Choose linked field…"}),e.filter((a)=>a.type==="linkedRecord"&&a.link).map((a)=>me("option",{value:a.id,children:a.name},a.id))]})]}),Ee("label",{children:["Aggregate"," ",Ee("select",{"aria-label":`Field ${l+1} rollup function`,value:r.rollup?.function??"sum",onChange:(a)=>{let s=a.target.value,u=o.find((c)=>c.id===e.find((g)=>g.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((c)=>c.id===r.rollup?.targetFieldId);i(l,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:s==="count"||u?.type==="number"?r.rollup?.targetFieldId??"":"",function:s}})},children:[me("option",{value:"sum",children:"Sum"}),me("option",{value:"average",children:"Average"}),me("option",{value:"min",children:"Minimum"}),me("option",{value:"max",children:"Maximum"}),me("option",{value:"count",children:"Count values"})]})]}),Ee("label",{children:["Target field"," ",Ee("select",{"aria-label":`Field ${l+1} rollup target`,value:r.rollup?.targetFieldId??"",disabled:!r.rollup?.linkFieldId,onChange:(a)=>i(l,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:a.target.value,function:r.rollup?.function??"sum"}}),children:[me("option",{value:"",children:"Choose target field…"}),o.find((a)=>a.id===e.find((s)=>s.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((a)=>!it(a)&&a.type!=="linkedRecord"&&(r.rollup?.function==="count"||a.type==="number")).map((a)=>me("option",{value:a.id,children:a.name},a.id))]})]}),me("small",{className:"w-full",children:"Null targets are skipped. Count counts values; empty sum/count are zero. Other empty aggregates have no result."})]})]},l)}),me("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 Xc(e,t,n){if(it(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 rr(e,et(t),n)}function Lr(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 l=t[r.id];if(r.type==="linkedRecord"){if(!Array.isArray(l)||l.some((d)=>typeof d!=="string")||l.length>100||new Set(l).size!==l.length)throw Error(n("{name} needs unique linked records.",{name:r.name}));if(r.required&&!l.length)throw Error(n("{name} is required.",{name:r.name}));i[r.id]=l;continue}if(r.type==="relation"){if(l==null||l===""){if(r.required)throw Error(n("{name} is required.",{name:r.name}));i[r.id]=null;continue}if(typeof l!=="string")throw Error(n("{name} needs a server-provided option.",{name:r.name}));i[r.id]=l;continue}if(r.type==="hyperlink"&&l!==null&&typeof l==="object"){if(!Qo(l))throw Error(n("{name} needs a link.",{name:r.name}));i[r.id]=l;continue}if(r.required&&typeof l==="string"&&!l.trim())throw Error(n("{name} is required.",{name:r.name}));i[r.id]=Cn(Array.isArray(l)?l.join(","):String(l??""),r,o)}return i}function Vo({fields:e,values:t,onChange:n,relationClient:o,linkedRecords:i,computedErrors:r,locale:l,ui:d,submitted:a=!1}){let s=se(l),u=Zc();return me("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((c)=>{let g=c.description?.trim()??"",p=g?`${u}-${c.id}-hint`:void 0,m=Xc(c,t[c.id],l??"en"),x=Boolean(c.required&&et(t[c.id])===""&&m)&&!a?"":m,C=x?`${u}-${c.id}-error`:void 0,w=[p,C].filter(Boolean).join(" "),f={...w?{"aria-describedby":w}:{},...x?{"aria-invalid":!0}:{}};return Ee("div",{className:"flex flex-col gap-1 text-sm",children:[Ee("label",{htmlFor:`${u}-${c.id}`,children:[c.name,c.required?" *":""]}),g?me("p",{id:p,className:"m-0 text-xs opacity-70",children:g}):null,it(c)?me("output",{id:`${u}-${c.id}`,"aria-label":s("{name} (read only)",{name:c.name}),...f,children:c.type==="lookup"?so(t[c.id]):tr(t[c.id],r?.[c.id],l)}):c.type==="linkedRecord"?me(mi,{...l?{locale:l}:{},field:c,value:t[c.id],labels:i?.[c.id],client:o,onChange:(R)=>n({...t,[c.id]:R}),...f}):c.type==="checkbox"?me("input",{id:`${u}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,type:"checkbox",checked:t[c.id]===!0,onChange:(R)=>n({...t,[c.id]:R.target.checked}),...f}):c.type==="singleSelect"&&d?.Select?me(Je,{ui:d,label:`${c.name}${c.required?" *":""}`,...f,value:String(t[c.id]??""),options:[{value:"",label:s("Choose…")},...(c.options??[]).map((R)=>({value:R.id,label:R.name}))],onChange:(R)=>n({...t,[c.id]:R||null})}):c.type==="multipleSelect"&&d?.MultiSelect?me(d.MultiSelect,{"aria-label":`${c.name}${c.required?" *":""}`,...f,options:(c.options??[]).map((R)=>({value:R.id,label:R.name,slot:Ir(c.options,R.id)})),values:Array.isArray(t[c.id])?t[c.id]:[],placeholder:s("Choose…"),onChange:(R)=>n({...t,[c.id]:R})}):c.type==="singleSelect"||c.type==="multipleSelect"?Ee("select",{id:`${u}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...f,className:"min-h-9 rounded-md border bg-background p-2",multiple:c.type==="multipleSelect",value:c.type==="multipleSelect"?Array.isArray(t[c.id])?t[c.id]:[]:String(t[c.id]??""),onChange:(R)=>n({...t,[c.id]:c.type==="multipleSelect"?Array.from(R.target.selectedOptions,(S)=>S.value):R.target.value||null}),children:[c.type==="singleSelect"&&me("option",{value:"",children:s("Choose…")}),c.options?.map((R)=>me("option",{value:R.id,children:R.name},R.id))]}):c.type==="date"&&d?.DatePicker?(()=>{let R={kind:ua(c),timeZone:Et(c)?.timeZone},S=String(t[c.id]??"");return me(d.DatePicker,{id:`${u}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...f,value:fa(S,R),withTime:R.kind==="auto"?co(S):R.kind==="datetime",fixedKind:R.kind!=="auto",clearable:!c.required,onChange:(A)=>n({...t,[c.id]:A?ya(A,S,R):null})})})():c.type==="hyperlink"?me(Tr,{field:c,id:`${u}-${c.id}`,ariaLabel:`${c.name}${c.required?" *":""}`,describedBy:f["aria-describedby"],invalid:Boolean(x),locale:l,inputClassName:"min-h-9 min-w-0 rounded-md border bg-background p-2",text:typeof t[c.id]==="string"?String(t[c.id]):Er(Qo(t[c.id])?t[c.id]:null),onChange:(R)=>{let S=R.trim().startsWith("{")?Ao(R):null;n({...t,[c.id]:S??(R||null)})}}):c.type==="longText"?me("textarea",{id:`${u}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...f,className:"rounded-md border bg-background p-2",value:String(t[c.id]??""),onChange:(R)=>n({...t,[c.id]:R.target.value||null})}):me("input",{id:`${u}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...f,className:"min-h-9 min-w-0 rounded-md border bg-background p-2",type:c.type==="number"?"number":c.type==="date"?"date":"text",step:c.type==="number"?"any":void 0,value:c.type==="date"?String(t[c.id]??"").slice(0,10):String(t[c.id]??""),onChange:(R)=>n({...t,[c.id]:R.target.value===""?null:c.type==="number"?Number(R.target.value):c.type==="date"&&t[c.id]?yi(t[c.id],R.target.value):R.target.value})}),x?me("span",{id:C,className:"text-xs text-red-600",children:x}):null]},c.id)})})}function eu(e,t,n){if(t==="isEmpty")return;let o=it(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(it(e)&&!cn(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 qy({fields:e,view:t,onChange:n,onError:o}){let i=e.filter(cn),[r,l]=Pa(i[0]?.id??""),d=i.some((C)=>C.id===r)?r:i[0]?.id??"",[a,s]=Pa("contains"),u=d?(()=>{let C=e.find((w)=>w.id===d);return C&&it(C)?C.resultType:C?.type})():void 0,c=u==="number"?["is","isNot","isEmpty"]:u==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],g=c.includes(a)?a:u==="number"||u==="date"?"is":"contains",[p,m]=Pa(""),x=[...t.columnOrder.flatMap((C)=>{let w=e.find((f)=>f.id===C);return w?[w]:[]}),...e.filter((C)=>!t.columnOrder.includes(C.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",me("input",{type:"search",className:"min-h-9 min-w-0 rounded-md border bg-background p-2",value:t.search??"",onChange:(C)=>n({...t,search:C.target.value})})]}),Ee("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(C)=>{C.preventDefault();let w=e.find((R)=>R.id===d);if(!w)return;let f;try{f=eu(w,g,p)}catch(R){o(R instanceof Error?R.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:d,operator:g,...g==="isEmpty"?{}:{value:f}}]}})},children:[Ee("label",{className:"flex flex-col gap-1 text-sm",children:["Filter field",me("select",{className:"h-9 rounded-md border bg-background px-2",value:d,onChange:(C)=>l(C.target.value),children:i.map((C)=>me("option",{value:C.id,children:C.name},C.id))})]}),me("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:g,onChange:(C)=>s(C.target.value),children:c.map((C)=>me("option",{value:C,children:C==="isNot"?"is not":C==="isEmpty"?"is empty":C==="onOrAfter"?"on or after":C},C))}),g!=="isEmpty"&&me("input",{type:u==="number"?"number":u==="date"?"date":"text",step:u==="number"?"any":void 0,className:"min-h-9 max-w-40 rounded-md border bg-background p-2","aria-label":"Filter value",value:p,onChange:(C)=>m(C.target.value)}),me("button",{type:"submit",disabled:!d,children:"Apply filter"}),me("button",{type:"button",onClick:()=>{let C={...t};delete C.filter,n(C)},children:"Clear filter"})]}),Ee("details",{className:"relative",children:[me("summary",{className:"cursor-pointer rounded-md border px-3 py-2 text-sm",children:"Columns"}),me("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:x.map((C,w)=>Ee("div",{className:"flex items-center gap-2 text-sm",children:[Ee("label",{className:"flex flex-1 items-center gap-2",children:[me("input",{type:"checkbox",checked:!t.hiddenColumns.includes(C.id),disabled:t.type==="form"&&C.required===!0,onChange:(f)=>n({...t,hiddenColumns:f.target.checked?t.hiddenColumns.filter((R)=>R!==C.id):[...t.hiddenColumns,C.id]})}),C.name]}),me("button",{type:"button","aria-label":`Move ${C.name} left`,disabled:w===0,onClick:()=>{let f=x.map((S)=>S.id),R=f[w-1];if(R!==void 0)[f[w-1],f[w]]=[C.id,R];n({...t,columnOrder:f})},children:"←"}),me("button",{type:"button","aria-label":`Move ${C.name} right`,disabled:w===x.length-1,onClick:()=>{let f=x.map((S)=>S.id),R=f[w+1];if(R!==void 0)[f[w],f[w+1]]=[R,C.id];n({...t,columnOrder:f})},children:"→"})]},C.id))})]})]})}import{useEffect as tu,useMemo as ks,useState as ws}from"react";import{jsx as Sa}from"react/jsx-runtime";function nu(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 ou(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 Ps(e,t,n,o={},i={}){return n.map((r)=>{let l=t.groupBy.map((a)=>{let s=e.fields.find((u)=>u.id===a);return`${s?.name??a} ${ou(s,r.groups[a],i)}`}),d=t.aggregates.map((a)=>{let s=r.values[a.as];return`${o[a.as]??a.as}: ${typeof s==="number"||typeof s==="string"?String(s):i.none??"none"}`});return[...l,...d].join(" · ")})}function ru({descriptor:e,query:t,rows:n}){return Sa("ul",{"data-uibot":"collection-aggregate",children:Ps(e,t,n).map((o)=>Sa("li",{children:o},o))})}function Bo({collectionId:e,descriptor:t,view:n,groupBy:o,aggregates:i,client:r,locale:l,labels:d,reloadKey:a=0}){let s=ks(()=>ii(n,{aggregates:i,...o?{groupBy:o}:{}}),[n,o,i]),u=ks(()=>se(l),[l]),[c,g]=ws(u("Loading summary…")),[p,m]=ws(!1);return tu(()=>{let h=ai(t,s);if(h){g(u(nu(h))),m(!0);return}let x=!0;return g(u("Loading summary…")),m(!1),r.aggregate(e,s).then((C)=>{if(!x)return;if(!C.ok){g(C.error.message),m(!0);return}let w=Ps(t,s,C.data,d??{},{unassigned:u("Unassigned"),checked:u("Checked"),unchecked:u("Unchecked"),none:u("none")});g(w.length?w.join(" · "):u("No summary rows.")),m(!1)}).catch(()=>{if(!x)return;g(u("The collection service is unavailable.")),m(!0)}),()=>{x=!1}},[r,e,t,s,d,u,a]),Sa("p",{role:p?"alert":"status","data-uibot":"collection-aggregate",children:c})}import{jsx as Se,jsxs as Kt,Fragment as Ea}from"react/jsx-runtime";function sr(e){if(!e.aggregate)return null;return Se(Bo,{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 ze={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},gn={padding:12,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)"},Pi={items:[],total:0,nextCursor:null,limit:50};function dr(e,t,n=!0){let o=se(e.locale),i=JSON.stringify([e.descriptor.id,e.descriptor.schemaVersion,t]),[r,l]=tn({key:i,history:[]}),d=r.key===i?r.cursor:void 0,a=r.key===i?r.history:[],s=JSON.stringify([i,d]),[u,c]=tn(0),[g,p]=tn({key:s,page:Pi,loading:n,error:""});Si(()=>{let h=!0;if(!n){p({key:s,page:Pi,loading:!1,error:""});return}p((w)=>({key:s,page:w.key===s?w.page:Pi,loading:!0,error:""}));let[x,,C]=JSON.parse(i);return e.client.query(x,{...C,...d?{cursor:d}:{}}).then((w)=>{if(!h)return;if(w.ok)p({key:s,page:w.data,loading:!1,error:""});else p((f)=>({...f,loading:!1,error:w.error.message}))}).catch(()=>{if(h)p((w)=>({...w,loading:!1,error:o("Collection query failed. Retry to load records.")}))}),()=>{h=!1}},[s,i,d,e.client,e.reloadKey,n,u]);let m=g.key===s?g.page:Pi;return{page:m,loading:n&&(g.key!==s||g.loading),error:g.key===s?g.error:"",previous:a.length?()=>l({key:i,cursor:a.at(-1),history:a.slice(0,-1)}):void 0,next:m.nextCursor?()=>l({key:i,cursor:m.nextCursor??void 0,history:[...a,d]}):void 0,retry:()=>c((h)=>h+1),pageNumber:a.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 Ra({hasPrevious:e,hasNext:t,onPrevious:n,onNext:o,loading:i,page:r,locale:l,ui:d}){let a=se(l);if(!e&&!t)return null;return Kt("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[Se(W,{ui:d,style:ze,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:a("Previous page"),disabled:!e||i,onClick:n}),r?Se("span",{style:{fontSize:12},children:a("Page {page}",{page:r})}):null,Se(W,{ui:d,style:ze,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:a("Next page"),disabled:!t||i,onClick:o})]})}function cr({state:e,locale:t,ui:n,hideCount:o}){let i=se(t);return Kt("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[o?null:Se("span",{children:Vr(i,e.page.total,e.page.items.length,t)}),Se(Ra,{hasPrevious:Boolean(e.previous),hasNext:Boolean(e.next),onPrevious:e.previous,onNext:e.next,loading:e.loading,page:e.pageNumber,locale:t,ui:n}),e.loading&&Se("span",{role:"status",children:i("Loading records…")}),e.error&&Kt(Ea,{children:[Se("span",{role:"alert",children:e.error}),Se(W,{ui:n,style:ze,variant:"outline",size:"sm",disabled:e.loading,onClick:e.retry,children:i("Retry query")})]})]})}function Ia(e){let t=ni(e.client,e.descriptor.id),n=se(e.locale),[o,i]=tn(!1),[r,l]=tn(""),[d,a]=tn(null),s=Or(null);Fn({dirty:Boolean(s.current),busy:o});let u=()=>{s.current=null,l(""),a(null)};return{saving:o,error:r,setError:l,remote:d,pending:s,reset:u,commit:async(p)=>{if(o||e.readOnly)return!1;s.current=p,i(!0),l(""),a(null);let m=await e.client.mutate(e.descriptor.id,p).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),m.ok)return u(),e.onCommitted(m.data),!0;l(m.error.message);let h=m.error.details?.current;if(h&&typeof h.id==="string"&&Number.isSafeInteger(h.version)&&h.version>0)a(h);return!1},retryRequest:()=>s.current&&d?{idempotencyKey:crypto.randomUUID(),items:s.current.items.map((p)=>p.op!=="insert"&&p.id===d.id?{...p,expectedVersion:d.version}:p)}:s.current}}function Aa({mutation:e,onRetry:t,locale:n,ui:o}){let i=se(n);return Kt(Ea,{children:[e.error&&Se("p",{role:"alert",children:e.error}),e.remote&&Kt("div",{style:gn,children:[Se("strong",{children:i("Current server version {version}",{version:e.remote.version})}),Se("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(e.remote.values,null,2)}),Se(W,{ui:o,style:ze,variant:"outline",size:"sm",disabled:e.saving,onClick:t,children:i("Retry against current version")})]})]})}function Wn({row:e,onClose:t,onCancel:n,onDirtyChange:o,onBusyChange:i,stickyActions:r,...l}){let d=se(l.locale),a=Dt(l.features),s=!l.readOnly&&a.rowDelete,u=!l.readOnly&&a.rowUpdate,c=Or(e.values),[g,p]=tn(()=>({...c.current})),[m,h]=tn(!1);Fn({dirty:JSON.stringify(g)!==JSON.stringify(c.current),busy:!1});let x=Or(null),[C,w]=tn(!1);Si(()=>{x.current?.focus()},[]);let f=Ia(l),R=Mo(l.descriptor.fields,l.view),S=JSON.stringify(g)!==JSON.stringify(e.values);Si(()=>{o?.(S)},[S,o]),Si(()=>{i?.(f.saving)},[f.saving,i]);let A=async(M=!1)=>{h(!0);try{let U=M?f.retryRequest():f.pending.current;if(!U){let J=R.filter((I)=>I.type!=="lookup"&&I.type!=="formula"&&I.type!=="rollup"&&JSON.stringify(g[I.id])!==JSON.stringify(e.values[I.id]));if(!J.length){f.setError(d("Change a field before saving."));return}let P=Lr(J,g,d,l.locale);U={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:e.id,expectedVersion:e.version,values:P}]}}if(await f.commit(U))t()}catch(U){f.setError(U instanceof Error?U.message:d("Invalid value"))}},L=async()=>{let M=f.pending.current?.items[0]?.op==="delete"?f.pending.current:{idempotencyKey:crypto.randomUUID(),items:[{op:"delete",id:e.id,expectedVersion:e.version}]};if(await f.commit(M))t()};return Kt("div",{ref:x,tabIndex:-1,onKeyDown:(M)=>{if(M.key==="Escape"&&!f.saving)M.stopPropagation(),(n??t)()},role:"dialog","aria-label":d("{name} record",{name:$t(e,l.descriptor.fields)}),style:{...gn,marginTop:12},children:[Se("h3",{children:$t(e,l.descriptor.fields)}),l.onInspectRecord&&Se(W,{ui:l.ui,style:ze,variant:"outline",size:"sm",disabled:f.saving,onClick:()=>l.onInspectRecord?.(e.id),children:d("Open record activity")}),Kt("form",{onSubmit:(M)=>{M.preventDefault(),A()},children:[Se("fieldset",{disabled:f.saving||C||!u,style:{border:0,padding:0},children:Se(Vo,{fields:R,values:g,submitted:m,...l.locale?{locale:l.locale}:{},...l.ui?{ui:l.ui}:{},relationClient:l.client,linkedRecords:e.linkedRecords,computedErrors:e.computedErrors,onChange:(M)=>{p(M),f.reset()}})}),Kt("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:[u&&Se("button",{type:"submit",style:{...ze,...ir},disabled:f.saving||C,children:f.saving?d("Saving…"):d("Save record")}),r?null:Se("button",{type:"button",style:ze,disabled:f.saving,onClick:n??t,children:d("Close record")}),r&&s?Se("span",{style:{marginLeft:"auto"},children:Se(W,{ui:l.ui,variant:"ghost",size:"sm",icon:"trash",disabled:f.saving,onClick:()=>w(!0),children:d("Delete record")})}):null]})]}),s&&!r&&Se("button",{type:"button",style:ze,disabled:f.saving,onClick:()=>w(!0),children:d("Delete record")}),C&&l.ui?.ConfirmDialog?l.ui.ConfirmDialog({open:!0,destructive:!0,title:d("Delete this record?"),description:d("Delete this record? Your unsaved changes will be discarded after deletion."),confirmLabel:d("Delete"),cancelLabel:d("Cancel"),busy:f.saving,onConfirm:()=>void L(),onCancel:()=>{if(w(!1),f.pending.current?.items[0]?.op==="delete")f.reset()}}):null,C&&!l.ui?.ConfirmDialog&&Kt(hi,{alert:!0,label:d("Confirm record deletion"),busy:f.saving,onCancel:()=>{if(w(!1),f.pending.current?.items[0]?.op==="delete")f.reset()},children:[Se("p",{children:d("Delete this record? Your unsaved changes will be discarded after deletion.")}),Se("button",{type:"button",style:ze,disabled:f.saving,onClick:()=>void L(),children:d("Confirm deletion")}),Se("button",{type:"button",style:ze,disabled:f.saving,onClick:()=>{if(w(!1),f.pending.current?.items[0]?.op==="delete")f.reset()},children:d("Cancel deletion")})]}),Se(Aa,{mutation:f,onRetry:()=>void A(!0),locale:l.locale,ui:l.ui})]})}function Da(e){let t=se(e.locale),n=!e.readOnly&&Dt(e.features).rowCreate,o=Or(null),i=Mo(e.descriptor.fields,{...e.view,hiddenColumns:e.view.hiddenColumns.filter((x)=>!e.descriptor.fields.find((C)=>C.id===x)?.required)}),r=()=>({...Object.fromEntries(i.filter((x)=>x.type==="checkbox").map((x)=>[x.id,!1])),...Rr(i)}),l=Or(r()),[d,a]=tn(l.current),[s,u]=tn(!1),[c,g]=tn(!1);Fn({dirty:JSON.stringify(d)!==JSON.stringify(l.current),busy:!1});let p=Ia(e),m=()=>o.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")?.focus(),h=async()=>{if(!n)return;g(!0);try{let x=p.pending.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:Lr(i,d,t,e.locale)}]};if(await p.commit(x))l.current=r(),a(l.current),u(!0),g(!1),requestAnimationFrame(m)}catch(x){p.setError(x instanceof Error?x.message:t("Invalid value"))}};return Kt("section",{"data-uibot":"collection-form",style:gn,children:[Se("h3",{children:e.view.name}),e.readOnly&&Se("p",{children:t("Record creation requires editor permission.")}),Kt("form",{ref:o,onSubmit:(x)=>{x.preventDefault(),h()},children:[Se("fieldset",{disabled:p.saving||!n,style:{border:0,padding:0},children:Se(Vo,{fields:i,values:d,submitted:c,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},relationClient:e.client,onChange:(x)=>{a(x),u(!1),p.reset()}})}),n&&Se("button",{type:"submit",style:{...ze,...ir},disabled:p.saving,children:p.saving?t("Creating…"):t("Create record")})]}),Se(Aa,{mutation:p,onRetry:()=>void h(),locale:e.locale,ui:e.ui}),s?Kt("p",{role:"status",children:[t("Record created. Add another below."),e.onShowRecords?Kt(Ea,{children:[" ",Se(W,{ui:e.ui,style:ze,variant:"outline",size:"sm",onClick:e.onShowRecords,children:t("Show records")})]}):null]}):null]})}function Ri(e){let[t,n]=tn(null),o=Ia(e),i=!e.readOnly&&Dt(e.features).rowUpdate;return{intent:t,mutation:o,move:async(d,a)=>{if(!i||o.saving||t)return;n({row:d,values:a});let s={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:d.id,expectedVersion:d.version,values:a}]};if(await o.commit(s))n(null)},retry:async()=>{let d=o.retryRequest();if(d&&await o.commit(d))n(null)},cancel:()=>{n(null),o.reset()},blocked:o.saving||!!t}}function Ii({state:e,locale:t,ui:n}){let o=se(t);if(!e.intent)return null;return Kt("div",{role:"dialog","aria-label":o("Pending record move"),style:gn,children:[Se("p",{children:e.mutation.saving?o("Moving record…"):o("The move has been kept for retry.")}),Se("pre",{children:JSON.stringify(e.intent.values,null,2)}),Se(Aa,{mutation:e.mutation,onRetry:()=>void e.retry(),locale:t,ui:n}),!e.mutation.remote&&Se(W,{ui:n,style:ze,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:()=>void e.retry(),children:o("Retry move")}),Se(W,{ui:n,style:ze,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:e.cancel,children:o("Cancel move")})]})}import{useEffect as du,useMemo as Is,useRef as cu,useState as uu}from"react";import{useEffect as Fa,useMemo as iu,useState as Uo}from"react";import{jsx as ur,jsxs as Ss}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 Br(e){let t=iu(()=>se(e.locale),[e.locale]),[n,o]=Uo(""),[i,r]=Uo(),[l,d]=Uo(null),[a,s]=Uo([]),[u,c]=Uo(()=>Ai({},e.labels)),[g,p]=Uo(""),[m,h]=Uo(!1),x=e.field.relation?.collectionId,C=e.field.relation?.labelFieldId,{getOptions:w,value:f}=e;Fa(()=>{c((A)=>Ai(A,e.labels))},[e.labels]),Fa(()=>{let A=!1;if(!x||!w)return;return h(!0),p(""),w({collectionId:x,...C?{labelFieldId:C}:{},search:n,...i?{cursor:i}:{},limit:50}).then((L)=>{if(A)return;if(!L.ok){p(L.error.message),d(null);return}let M=L.data.items.slice(0,50);c((U)=>Ai(U,M)),s((U)=>{let J=i?[...U,...M]:M;return[...new Map(J.map((P)=>[P.id,P])).values()]}),d(L.data.nextCursor)}).catch(()=>{if(!A)p(t("Relation options unavailable."))}).finally(()=>{if(!A)h(!1)}),()=>{A=!0}},[x,C,n,i,w,t]),Fa(()=>{if(!f||!x||!w)return;if(e.labels?.some((L)=>L.id===f&&L.label.trim()))return;let A=!1;return w({collectionId:x,...C?{labelFieldId:C}:{},ids:[f],limit:50}).then((L)=>{if(A||!L.ok)return;let M=L.data.items.find((U)=>U.id===f);if(M)c((U)=>Ai(U,[M]))}).catch(()=>{}),()=>{A=!0}},[f,x,C,w,e.labels]);let R=!x||!w,S=f?u[f]??a.find((A)=>A.id===f)?.label??f:"";return Ss("div",{children:[ur("input",{"aria-label":t("Search {name}",{name:e.field.name}),value:n,disabled:e.disabled||R,onChange:(A)=>{o(A.currentTarget.value),r(void 0),s([]),d(null)}}),Ss("select",{"aria-label":e.label??e.field.name,value:e.value,disabled:e.disabled||R||m,onChange:(A)=>{let L=A.currentTarget.value;if(!L||a.some((M)=>M.id===L))e.onChange(L)},children:[ur("option",{value:"",children:t("No relation")}),f&&!a.some((A)=>A.id===f)&&ur("option",{value:f,children:S}),a.map((A)=>ur("option",{value:A.id,children:A.label},A.id))]}),l&&ur("button",{type:"button",disabled:m||e.disabled,onClick:()=>r(l),children:t("More {name} options",{name:e.field.name})}),(g||R)&&ur("span",{role:"status",children:g||t("Relation option provider unavailable.")})]})}var au={"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"}},lu={"zh-CN":{is:"恰好是",isNot:"不是恰好",contains:"包含任一",notContains:"不包含任一"},en:{is:"is exactly",isNot:"is not exactly",contains:"has any of",notContains:"has none of"}},su={"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"}},Di=(e,t="en",n)=>{if(n&&bn(n)==="multipleSelect"){let o=lu[t][e];if(o)return o}return au[t][e]??e},Ei=(e,t="en")=>su[t][e]??e;function Ta(e,t){if(!t)return"";let n=e?Et(e):void 0;return n?$n(t,{...n,time:"none"}):t}function Rs(e,t,n="en"){let o=n==="zh-CN";return e.filterSet.map((i)=>{if("filterSet"in i)return`(${Rs(i,t,n)})`;let r=t.find((s)=>s.id===i.fieldId),l=Di(i.operator,n,r);if(i.operator==="isEmpty"||i.operator==="isNotEmpty")return`${r?.name??i.fieldId} ${l}`;let d=(s)=>r?.options?.find((u)=>u.id===s)?.name??String(s??""),a;if(oa(i.value)){let s=i.value,u=Ei(s.mode,n);a=s.mode==="exactDate"?Ta(r,s.date):s.mode==="dateRange"?`${Ta(r,s.date)} ~ ${Ta(r,s.to)}`:s.days!==void 0?u.replace("N",String(s.days)):u}else a=Array.isArray(i.value)?i.value.map(d).join(o?"、":", "):d(i.value);return`${r?.name??i.fieldId} ${l} ${a}`}).join(e.conjunction==="or"?o?" 或 ":" OR ":o?" 且 ":" AND ")}import{jsx as Ve,jsxs as On,Fragment as Fs}from"react/jsx-runtime";var gu={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 gr(e){return Ve("span",{style:Ye.cell,children:Ve(Je,{...e})})}var Fi=()=>`row_${Math.random().toString(36).slice(2,10)}`,pu=(e)=>("filterSet"in e),mu=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}};function Na(e,t){if(t)return _l(e);let n=bn(e);return n?gu[n]??[]:[]}function Ma(e,t,n){if(Xo.has(t))return;let o=bn(e);if(o==="date"&&n)return{mode:"today",timeZone:Et(e)?.timeZone??mu()};if(o==="checkbox")return!0;if(o==="multipleSelect")return[];return o==="number"?void 0:""}function As(e){let t=[],n=[];for(let o of e?.filterSet??[])if(pu(o))n.push({key:Fi(),node:o});else t.push({key:Fi(),fieldId:o.fieldId,operator:o.operator,value:o.value});return{rows:t,groups:n,conjunction:e?.conjunction??"and"}}function Ds(e,t,n,o){let i=[],r=!0;for(let a of t){let s=e.find((g)=>g.id===a.fieldId);if(!s||!a.operator){r=!1;continue}let u=a.value===""||Array.isArray(a.value)&&a.value.length===0;if(!Xo.has(a.operator)&&u){r=!1;continue}let c={fieldId:a.fieldId,operator:a.operator,...Xo.has(a.operator)?{}:{value:a.value}};if(zl(s,c))r=!1;else i.push(c)}let l=n.map((a)=>a.node).filter((a)=>Boolean(a?.filterSet.length)),d=[...i,...l];return{node:d.length?{conjunction:o,filterSet:d}:void 0,complete:r}}function Ti(e){let{ui:t,locale:n}=e,o=e.advanced!==!1,i=e.allowGroups!==!1,r=Is(()=>se(n),[n]),l=Is(()=>e.fields.filter((h)=>!it(h)&&bn(h)!==null),[e.fields]),[d,a]=uu(()=>As(e.filter)),s=cu(JSON.stringify(e.filter??null));du(()=>{let h=JSON.stringify(e.filter??null);if(h!==s.current)s.current=h,a(As(e.filter))},[e.filter]);let u=(h)=>{a(h);let{node:x}=Ds(l,h.rows,h.groups,h.conjunction),C=JSON.stringify(x??null);if(C!==s.current)s.current=C,e.onChange(x)},c=(h,x)=>u({...d,rows:d.rows.map((C)=>C.key===h?{...C,...x}:C)}),g=()=>{let h=l[0];if(!h)return;let x=Na(h,o)[0]??"";u({...d,rows:[...d.rows,{key:Fi(),fieldId:h.id,operator:x,value:x?Ma(h,x,o):void 0}]})},p=()=>u({...d,groups:[...d.groups,{key:Fi(),node:void 0}]}),m=Ds(l,d.rows,d.groups,d.conjunction).complete===!1||d.groups.some((h)=>h.node===void 0);return On("div",{"data-uibot-filter-builder":"",style:Ye.root,children:[d.rows.length+d.groups.length>1?On("div",{style:Ye.inline,children:[Ve("span",{children:r("Match")}),Ve(gr,{ui:t,label:r("Filter conjunction"),style:Ye.control,value:d.conjunction,options:[{value:"and",label:r("all conditions")},{value:"or",label:r("any condition")}],onChange:(h)=>u({...d,conjunction:h==="or"?"or":"and"})})]}):null,d.rows.map((h,x)=>{let C=l.find((R)=>R.id===h.fieldId),w=C?bn(C):null,f=C?Na(C,o):[];return On("fieldset",{"aria-label":r("Condition {index}",{index:x+1}),style:{...Ye.condition,margin:0,padding:0,border:0,minWidth:0},children:[Ve("span",{style:Ye.slot,children:Ve(gr,{ui:t,label:r("Filter field"),style:Ye.control,value:h.fieldId,options:l.map((R)=>({value:R.id,label:R.name})),onChange:(R)=>{let S=l.find((U)=>U.id===R);if(!S)return;let A=Na(S,o),L=A.includes(h.operator)?h.operator:A[0]??"",M=bn(S)===w;c(h.key,{fieldId:R,operator:L,value:L&&!(M&&L===h.operator)?Ma(S,L,o):h.value})}})}),Ve("span",{style:Ye.slot,children:Ve(gr,{ui:t,label:r("Filter operator"),style:Ye.control,value:h.operator,options:f.map((R)=>({value:R,label:Di(R,n??"en",C)})),onChange:(R)=>{if(!C)return;let S=R;c(h.key,{operator:S,value:Ma(C,S,o)})}})}),C&&h.operator&&!Xo.has(h.operator)?Ve("span",{style:Ye.slot,children:Ve(fu,{field:C,row:h,advanced:o,t:r,props:e,onValue:(R)=>c(h.key,{value:R})})}):null,Ve(W,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove condition {index}",{index:x+1}),title:r("Remove condition {index}",{index:x+1}),style:{flex:"0 0 auto"},onClick:()=>u({...d,rows:d.rows.filter((R)=>R.key!==h.key)})})]},h.key)}),i?d.groups.map((h,x)=>On("fieldset",{"aria-label":r("Condition group {index}",{index:x+1}),style:Ye.group,children:[On("div",{style:Ye.groupHead,children:[Ve("strong",{style:{fontSize:13},children:r("Condition group {index}",{index:x+1})}),Ve(W,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove group {index}",{index:x+1}),title:r("Remove group {index}",{index:x+1}),onClick:()=>u({...d,groups:d.groups.filter((C)=>C.key!==h.key)})})]}),Ve(Ti,{fields:e.fields,filter:h.node,allowGroups:!1,advanced:o,...n?{locale:n}:{},...t?{ui:t}:{},...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},onChange:(C)=>u({...d,groups:C?d.groups.map((w)=>w.key===h.key?{...w,node:C}:w):d.groups.filter((w)=>w.key!==h.key)})})]},h.key)):d.groups.length?On("p",{style:Ye.hint,children:[r("{count} grouped conditions are kept.",{count:d.groups.length})," ",Ve(W,{ui:t,variant:"ghost",size:"sm",onClick:()=>u({...d,groups:[]}),children:r("Remove")})]}):null,m?Ve("p",{role:"status",style:Ye.hint,children:r("Finish the highlighted condition to apply it.")}):null,On("div",{style:Ye.inline,children:[Ve(W,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:l.length===0,onClick:g,children:r("Add condition")}),i?Ve(W,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:l.length===0,onClick:p,children:r("Add group")}):null,d.rows.length||d.groups.length?Ve(W,{ui:t,variant:"ghost",size:"sm",onClick:()=>u({rows:[],groups:[],conjunction:"and"}),children:r("Clear filter")}):null]})]})}function fu({field:e,row:t,advanced:n,t:o,props:i,onValue:r}){let{ui:l}=i,d=bn(e),a=o("Filter value"),s=(u,c,g,p)=>i.renderCellEditor?.({...i.getRelationOptions?{getRelationOptions:i.getRelationOptions}:{},field:{...e,...p,required:!1},text:u,disabled:!1,mode:"filter",label:g,autoOpen:!1,onChange:c,onSave:()=>{},onCancel:()=>c("")});if(d==="number")return Ve("input",{"aria-label":a,type:"number",step:"any",style:Ye.control,value:typeof t.value==="number"?String(t.value):"",onChange:(u)=>{let c=u.currentTarget.value;r(c===""||!Number.isFinite(Number(c))?void 0:Number(c))}});if(d==="text")return Ve("input",{"aria-label":a,style:Ye.control,value:typeof t.value==="string"?t.value:"",onChange:(u)=>r(u.currentTarget.value)});if(d==="checkbox")return Ve(gr,{ui:l,label:a,style:Ye.control,value:t.value===!1?"false":"true",options:[{value:"true",label:o("Yes")},{value:"false",label:o("No")}],onChange:(u)=>r(u==="true")});if(d==="singleSelect"||d==="multipleSelect"){let u=Array.isArray(t.value)?t.value.join(","):typeof t.value==="string"?t.value:"",c=s(u,(p)=>r(d==="multipleSelect"?p.split(",").filter(Boolean):p),a);if(c)return c;if(d==="singleSelect")return Ve(gr,{ui:l,label:a,style:Ye.control,value:u,options:[{value:"",label:o("Choose option")},...(e.options??[]).map((p)=>({value:p.id,label:p.name}))],onChange:r});let g=new Set(u.split(",").filter(Boolean));return Ve("fieldset",{"aria-label":a,style:{...Ye.inline,margin:0,padding:0,border:0},children:(e.options??[]).map((p)=>On("label",{style:Ye.inline,children:[Ve("input",{type:"checkbox",checked:g.has(p.id),onChange:(m)=>{let h=new Set(g);if(m.currentTarget.checked)h.add(p.id);else h.delete(p.id);r([...h])}}),p.name]},p.id))})}if(d==="relation"){let u=typeof t.value==="string"?t.value:"";return s(u,r,a)??Ve(Br,{field:e,value:u,onChange:r,label:a,getOptions:i.getRelationOptions,locale:i.locale})}if(d==="date"){if(!n||typeof t.value==="string"){let u=typeof t.value==="string"?t.value:"";return s(u,r,a)??Ve("input",{"aria-label":a,type:"date",style:Ye.control,value:u.slice(0,10),onChange:(c)=>r(c.currentTarget.value)})}return Ve(yu,{field:e,value:t.value,t:o,props:i,custom:s,onValue:r})}return null}function yu({field:e,value:t,t:n,props:o,custom:i,onValue:r}){let l=t??{mode:"today"},d=(u)=>r({...l,...u}),a=(u,c,g)=>i(c??"",(p)=>g(p.slice(0,10)),u,{formatting:{date:"YYYY-MM-DD",time:"none"}})??Ve("input",{"aria-label":u,type:"date",style:Ye.control,value:c??"",onChange:(p)=>g(p.currentTarget.value)}),s=(u)=>{let{date:c,to:g,days:p,...m}=l;r({...m,mode:u,...di.has(u)?{days:7}:{}})};return On(Fs,{children:[Ve(gr,{ui:o.ui,label:n("Date mode"),style:Ye.control,value:l.mode,options:na.map((u)=>({value:u,label:Ei(u,o.locale??"en")})),onChange:(u)=>s(u)}),l.mode==="exactDate"?a(n("Filter value"),l.date,(u)=>d({date:u})):null,l.mode==="dateRange"?On(Fs,{children:[a(n("From date"),l.date,(u)=>d({date:u})),a(n("To date"),l.to,(u)=>d({to:u}))]}):null,di.has(l.mode)?Ve("input",{"aria-label":n("Number of days"),type:"number",min:0,step:1,style:{...Ye.control,width:84},value:l.days??"",onChange:(u)=>{let c=u.currentTarget.value;if(c===""){let{days:g,...p}=l;r(p)}else d({days:Number(c)})}}):null,Ve("span",{style:Ye.hint,children:Et(e)?.timeZone??l.timeZone??""})]})}var Es="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",Ye={group:{margin:0,minWidth:0,display:"grid",gap:8,padding:10,border:`1px solid ${Es}`,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 ${Es}`,borderRadius:6,background:"transparent",color:"inherit",font:"inherit"},hint:{margin:0,fontSize:12,opacity:0.7}};import{jsx as Qe,jsxs as Gn,Fragment as hu}from"react/jsx-runtime";var La={display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},Oa={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 Ni({fields:e,view:t,onChange:n,locale:o,ui:i,editor:r}){return Qe("div",{"data-uibot-view-filter":"",children:Qe(Ti,{fields:e,filter:t.filter,locale:o,ui:i,renderCellEditor:r?.renderCellEditor,getRelationOptions:r?.getRelationOptions,advanced:r?.advanced,onChange:(l)=>{if(l)n({...t,filter:l});else{let{filter:d,...a}=t;n(a)}}})})}var bu=10;function Mi({fields:e,view:t,onChange:n,locale:o,ui:i}){let r=se(o),l=t.sort??[],d=e.filter((c)=>cn(c)),a=d.filter((c)=>!l.some((g)=>g.fieldId===c.id)),s=(c)=>{if(c.length)n({...t,sort:c});else{let{sort:g,...p}=t;n(p)}},u=(c,g)=>{let p=[...l],[m]=p.splice(c,1);if(m)p.splice(c+g,0,m);s(p)};return Gn("div",{"data-uibot-view-sort":"",style:{display:"grid",gap:8},children:[l.map((c,g)=>Gn("fieldset",{"aria-label":r("Sort {index}",{index:g+1}),style:{...La,margin:0,padding:0,border:0,minWidth:0},children:[Qe("span",{style:{flex:"1 1 120px",minWidth:110,display:"flex"},children:Qe(Je,{ui:i,label:r("Sort field"),style:Oa,value:c.fieldId,options:d.filter((p)=>p.id===c.fieldId||a.includes(p)).map((p)=>({value:p.id,label:p.name})),onChange:(p)=>s(l.map((m,h)=>h===g?{...m,fieldId:p}:m))})}),Qe("span",{style:{flex:"0 1 110px",minWidth:90,display:"flex"},children:Qe(Je,{ui:i,label:r("Sort direction"),style:Oa,value:c.direction,options:[{value:"asc",label:r("Ascending")},{value:"desc",label:r("Descending")}],onChange:(p)=>s(l.map((m,h)=>h===g?{...m,direction:p}:m))})}),Qe(W,{ui:i,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:g===0,ariaLabel:r("Move sort {index} up",{index:g+1}),title:r("Move sort {index} up",{index:g+1}),onClick:()=>u(g,-1),children:" "}),Qe(W,{ui:i,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:g===l.length-1,ariaLabel:r("Move sort {index} down",{index:g+1}),title:r("Move sort {index} down",{index:g+1}),onClick:()=>u(g,1),children:" "}),Qe(W,{ui:i,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove sort {index}",{index:g+1}),title:r("Remove sort {index}",{index:g+1}),onClick:()=>s(l.filter((p,m)=>m!==g)),children:" "})]},c.fieldId)),Gn("div",{style:La,children:[Qe(W,{ui:i,variant:"outline",size:"sm",icon:"plus",disabled:a.length===0||l.length>=bu,onClick:()=>{let c=a[0];if(c)s([...l,{fieldId:c.id,direction:"asc"}])},children:r("Add sort")}),l.length?Qe(W,{ui:i,variant:"ghost",size:"sm",onClick:()=>s([]),children:r("Clear sort")}):Qe("span",{style:{fontSize:12,opacity:0.7},children:r("Default order")})]})]})}function Ts({fields:e,view:t,onChange:n,locale:o,ui:i,bare:r}){let l=se(o),a=[...t.columnOrder.flatMap((c)=>{let g=e.find((p)=>p.id===c);return g?[g]:[]}),...e.filter((c)=>!t.columnOrder.includes(c.id))],s=(c,g)=>{let p=a.map((x)=>x.id),m=p[c],h=p[c+g];if(m===void 0||h===void 0)return;p[c]=h,p[c+g]=m,n({...t,columnOrder:p})},u=Gn("div",{style:{display:"grid",gap:6,paddingTop:r?0:6,minWidth:0},children:[Gn("label",{children:[Qe("input",{type:"checkbox",checked:t.showRowNumber!==!1,onChange:(c)=>n({...t,showRowNumber:c.currentTarget.checked})})," ",l("Show row numbers")]}),Gn("label",{children:[Qe("input",{type:"checkbox",checked:t.showRecordId===!0,onChange:(c)=>n({...t,showRecordId:c.currentTarget.checked})})," ",l("Show record IDs")]}),a.map((c,g)=>{let p=!t.hiddenColumns.includes(c.id),m=`${c.name}${c.required?" *":""}`;return Gn("div",{style:{...La,flexWrap:"nowrap",gap:4},children:[Qe(W,{ui:i,variant:"ghost",size:"sm",icon:p?"eye":"eyeOff",iconOnly:!0,disabled:t.type==="form"&&c.required===!0,ariaLabel:m,title:l(p?"Hide {name}":"Show {name}",{name:c.name}),onClick:()=>n({...t,hiddenColumns:p?[...t.hiddenColumns,c.id]:t.hiddenColumns.filter((h)=>h!==c.id)})}),Qe("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:p?1:0.5},children:m}),Qe(W,{ui:i,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:g===0,ariaLabel:l("Move {name} left",{name:c.name}),onClick:()=>s(g,-1)}),Qe(W,{ui:i,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:g===a.length-1,ariaLabel:l("Move {name} right",{name:c.name}),onClick:()=>s(g,1)})]},c.id)})]});if(r)return Qe("div",{"data-uibot-view-columns":"",children:u});return Gn("details",{"data-uibot-view-columns":"",children:[Qe("summary",{children:l("Columns")}),u]})}function Li({fields:e,view:t,onChange:n,locale:o,ui:i}){let r=se(o),l=e.filter((d)=>d.type==="singleSelect"||d.type==="checkbox");return Qe("div",{style:{display:"flex",gap:6,alignItems:"center"},children:t.groupByFieldId?Gn(hu,{children:[Qe(Ce,{name:"group"}),Qe(Je,{ui:i,label:r("Grid grouping field"),style:Oa,value:t.groupByFieldId,options:l.map((d)=>({value:d.id,label:d.name})),onChange:(d)=>n({...t,groupByFieldId:d})}),Qe(W,{ui:i,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove grouping"),onClick:()=>{let d={...t};delete d.groupByFieldId,n(d)}})]}):Qe(W,{ui:i,variant:"outline",size:"sm",icon:"plus",onClick:()=>{let d=l[0];if(d)n({...t,groupByFieldId:d.id})},children:r("Add grouping")})})}import{useState as Ur}from"react";import{jsx as ft,jsxs as fo}from"react/jsx-runtime";var _r={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"}},Ms="table";function Oi({icon:e,size:t=15,icons:n=_r}){let o=(e?n[e]:void 0)??n[Ms]??_r.table;return ft("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:ft("path",{d:o?.path??""})})}function Va(e){let t=se(e.locale);return fo("aside",{"data-uibot-table-list":"",style:_o.root,children:[fo("div",{style:_o.title,children:[ft("span",{children:t("Tables")}),ft("span",{children:e.tables.length})]}),ft("nav",{"aria-label":t("Tables"),style:_o.nav,children:e.tables.map((n)=>fo("button",{type:"button","aria-current":n.id===e.activeId?"page":void 0,onClick:()=>e.onSelect(n.id),style:{..._o.item,...n.id===e.activeId?_o.active:{}},children:[ft(Oi,{icon:n.icon,icons:e.icons??_r}),ft("span",{style:_o.name,children:n.name})]},n.id))}),e.onCreate?ft(W,{ui:e.ui,variant:"ghost",style:_o.create,disabled:e.createDisabled,onClick:e.onCreate,children:t("New table")}):null]})}function Ba(e){let t=se(e.locale),n=e.icons??_r,[o,i]=Ur(!1),[r,l]=Ur(""),[d,a]=Ur(!1),[s,u]=Ur(!1),[c,g]=Ur(""),p=e.table,m=e.canManage&&Boolean(p)&&!s;async function h(f){u(!0),g("");try{return await f(),!0}catch(R){return g(R instanceof Error?R.message:t("Saving failed. Your edit has been kept.")),!1}finally{u(!1)}}let x=()=>{if(!m||!e.onRename)return;l(p?.name??""),g(""),i(!0)};async function C(){let f=r.trim();if(!f||f===p?.name){i(!1);return}if(await h(()=>e.onRename?.(f)))i(!1)}let w=(f)=>{if(f.key==="Enter"||f.key==="F2")f.preventDefault(),x()};return fo("header",{"data-uibot-table-header":"",style:xn.root,children:[fo("div",{style:xn.left,children:[fo("span",{style:{position:"relative"},children:[ft("button",{type:"button","aria-label":t("Change table icon"),"aria-haspopup":"menu","aria-expanded":d,title:e.canManage?t("Double click to change the icon"):t("Schema permission required"),disabled:!m||!e.onIconChange,style:xn.iconButton,onDoubleClick:()=>a(!0),onKeyDown:(f)=>{if(f.key==="Enter"||f.key===" ")f.preventDefault(),a(!0)},children:ft(Oi,{icon:p?.icon,size:17,icons:n})}),d?ft("div",{role:"menu","aria-label":t("Table icon"),style:xn.menu,children:Object.entries(n).map(([f,R])=>fo("button",{type:"button",role:"menuitemradio","aria-checked":(p?.icon??Ms)===f,title:R.label,style:xn.menuItem,onClick:()=>{a(!1),h(()=>e.onIconChange?.(f))},children:[ft(Oi,{icon:f,icons:n}),ft("span",{children:R.label})]},f))}):null]}),fo("div",{style:{minWidth:0},children:[o?ft("input",{"aria-label":t("Table name"),value:r,disabled:s,style:xn.input,autoFocus:!0,onChange:(f)=>l(f.currentTarget.value),onBlur:()=>{if(!c)C()},onKeyDown:(f)=>{if(f.key==="Enter")f.preventDefault(),C();if(f.key==="Escape")f.preventDefault(),i(!1),g("")}}):ft("h2",{style:xn.title,children:ft("button",{type:"button","aria-label":t("Rename table {name}",{name:p?.name??""}),title:e.canManage?t("Double click to rename"):t("Schema permission required"),disabled:!m||!e.onRename,style:xn.titleButton,onDoubleClick:x,onKeyDown:w,children:p?.name??t("Start with a table")})}),c?ft("p",{role:"alert",style:xn.error,children:c}):null,ft("p",{style:xn.summary,children:p?t("{count} fields · {mode}",{count:p.fields.length,mode:e.canWrite?t("Editable"):t("Read only")}):t("Start with a table")})]})]}),ft("div",{style:xn.actions,children:e.actions})]})}var Ns="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",_o={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%"}},xn={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 ${Ns}`,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 ${Ns}`,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 Ua,useMemo as _a,useRef as zo,useState as pr}from"react";import{jsx as yo,jsxs as za}from"react/jsx-runtime";function qa(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=_a(()=>se(e.locale),[e.locale]),n=ni(e.client,e.descriptor.id),o=zo(null);if(o.current===null)o.current=Rr(e.descriptor.fields);let[i,r]=pr(o.current),[l,d]=pr(!1),a=_a(()=>({client:e.client,descriptor:e.descriptor}),[e.client,e.descriptor]),s=zo(a);s.current=a;let u=zo(!0);Ua(()=>(u.current=!0,()=>{u.current=!1}),[]);let[c,g]=pr(),p=_a(()=>{let k=new Map,T=(D,B)=>{if(!u.current||s.current!==a)return;g((F)=>({scope:a,targets:{...F?.scope===a?F.targets:{},[D]:B}}))};return{query:async(...D)=>{let B=D[0],F=(k.get(B)??0)+1;k.set(B,F),T(B,!1);try{let H=await e.client.query(...D);if(k.get(B)===F)T(B,H.ok);return H}catch(H){if(k.get(B)===F)T(B,!1);throw H}}}},[e.client,a]),m=e.descriptor.fields.some((k)=>k.type==="linkedRecord"&&(!k.link||c?.scope!==a||!c.targets[k.link.collectionId])),[h,x]=pr(null),C=zo(null),w=zo(!1),f=zo(null),R=zo(null),{autoFocus:S}=e;Ua(()=>{if(h?.error)R.current?.focus()},[h]);let[A,L]=pr(!1),[M,U]=pr(!1),J=JSON.stringify(i)!==JSON.stringify(o.current)||A;Fn({dirty:J,busy:l},e);let P=()=>f.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled])")?.focus();Ua(()=>{if(S)P()},[S]);async function I(k){if(w.current||e.readOnly||m)return;U(!0);let T;try{T=Lr(e.descriptor.fields,i,t,e.locale)}catch(B){x({text:B instanceof Error?B.message:t("Invalid value"),error:!0,clearable:!0});return}w.current=!0,d(!0),x(null);let D=C.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:T}]};C.current=D;try{let B=await e.client.mutate(e.descriptor.id,D);if(!n.active)return;if(!B.ok){let H=B.error.code==="validation";L(!H),x({text:B.error.message,error:!0,clearable:H});return}C.current=null,L(!1),U(!1),o.current=Rr(e.descriptor.fields),r(o.current),e.onCommitted(B.data);let F=qa(e.descriptor,B.data.items[0]);if(x({text:`${k?t("Record saved, keep adding"):t("Record saved")}${F?`:${F}`:""}`,error:!1,clearable:!1}),k)requestAnimationFrame(P);else e.onSaved?.(B.data)}catch{if(!n.active)return;L(!0),x({text:t("Saving failed. Your draft has been kept."),error:!0,clearable:!1})}finally{w.current=!1,d(!1)}}return za("form",{ref:f,noValidate:!0,"aria-label":t("New record form"),"data-uibot":"record-creator",onSubmit:(k)=>{k.preventDefault();let T=k.nativeEvent.submitter;I(T?.getAttribute("data-continue")==="true")},onKeyDown:(k)=>{if(k.key==="Enter"&&(k.ctrlKey||k.metaKey)&&!k.nativeEvent.isComposing&&!l)k.preventDefault(),k.currentTarget.requestSubmit()},children:[yo("fieldset",{disabled:l||e.readOnly,style:Vn.fields,children:yo(Vo,{fields:e.descriptor.fields,values:i,submitted:M,relationClient:p,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},onChange:(k)=>{if(r(k),C.current=null,L(!1),h?.clearable)x(null)}})}),h?yo("p",{ref:R,role:h.error?"alert":"status",tabIndex:-1,style:h.error?Vn.error:Vn.status,children:h.text}):null,za("div",{"data-uibot":"record-creator-actions",style:e.stickyActions?{...Vn.actions,...Vn.sticky}:Vn.actions,children:[za("span",{style:Vn.hint,children:[yo("kbd",{children:"Ctrl / ⌘"})," + ",yo("kbd",{children:"Enter"})," ",t("Save")]}),yo("button",{type:"submit","aria-label":t("Save new record"),"aria-busy":l,disabled:l||e.readOnly||m,style:{...Vn.button,...ir},children:l?t("Saving…"):t("Save new record")}),yo("button",{type:"submit","data-continue":"true",disabled:l||e.readOnly||m,style:Vn.button,children:t("Save and continue")}),e.onCancel&&!e.stickyActions?yo(W,{ui:e.ui,style:Vn.button,disabled:l,onClick:e.onCancel,children:t("Cancel adding")}):null]})]})}var Vn={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 Su,useLayoutEffect as Ru,useRef as zr}from"react";import{jsx as mr}from"react/jsx-runtime";var Ls=[["#e8f0fe","#1a56c4"],["#e6f4ea","#1e7a3c"],["#fdecea","#b3261e"],["#fff1e0","#a05a00"],["#e8eaed","#3c4043"],["#e0f2f1","#00695c"],["#f3e8fd","#6a1b9a"]];function kn(e){let t=Math.max(e,0)%Ls.length,[n,o]=Ls[t]??["#e8eaed","#3c4043"];return{background:`var(--uibot-chip-${t}-bg, ${n})`,color:`var(--uibot-chip-${t}-fg, ${o})`}}function $a({index:e,children:t}){return mr("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",...kn(e)},children:t})}function qo({ids:e,field:t,wrap:n}){let o=t.options??[];return mr("span",{style:{display:"inline-flex",gap:4,alignItems:"center",maxWidth:"100%",overflow:"hidden",...n?{flexWrap:"wrap"}:{}},children:e.map((i)=>{let r=o.findIndex((l)=>l.id===i);return mr($a,{index:Ir(o,i),children:o[r]?.name??String(i)},String(i))})})}function Vs({checked:e,label:t,onToggle:n}){return mr("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 Os={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",hyperlink:"M9 3h4v4M13 3 7.5 8.5M11 9.5V13H3V5h3.5",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 Vi({type:e}){return mr("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:mr("path",{d:Os[e]??Os.singleLineText})})}var ue={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 ut,jsxs as mt,Fragment as ja}from"react/jsx-runtime";var Cu=["YYYY-MM-DD","YYYY/MM/DD","MM/DD/YYYY","DD/MM/YYYY","YYYY年M月D日"],vu=["Asia/Shanghai","Asia/Hong_Kong","Asia/Tokyo","Asia/Singapore","Europe/London","Europe/Paris","America/New_York","America/Los_Angeles","UTC"],xu=["CNY","USD","EUR","JPY","GBP","HKD"],ku=[0,1,2,3,4,5,6,7,8],wu={date:"YYYY-MM-DD",time:"none"},Pu={kind:"decimal",precision:0,grouping:!0};function Bs({field:e,onChange:t,disabled:n,locale:o,ui:i,settings:r,dateFormatLocked:l}){let d=r?.formatting!==!1,a=r?.defaults!==!1,s=se(o),u=(p)=>t((m)=>({...m,...p})),c=()=>t((p)=>{let{defaultValue:m,...h}=p;return h}),g=(p,m,h,x,C=!1)=>mt("div",{style:ue.control,children:[ut("span",{style:ue.label,children:p}),ut(Je,{ui:i,label:p,style:ue.input,disabled:n||C,value:m,options:h,onChange:x})]});if(e.type==="date"){let p=Et(e)??wu,m=(x)=>{let{timeZone:C,...w}=p,f={...w,...C?{timeZone:C}:{},...x};if(x.timeZone==="")delete f.timeZone;u({formatting:f})},h=p.time!=="none";if(!d&&!a)return null;return mt("fieldset",{style:ue.settings,"aria-label":s("Format of field {name}",{name:e.name}),children:[d?mt(ja,{children:[ut("strong",{style:{fontSize:13},children:s("Format")}),mt("div",{style:ue.row,children:[g(s("Date format"),p.date,Cu.map((x)=>({value:x,label:x})),(x)=>m({date:x}),Boolean(l)),g(s("Time format"),p.time,[{value:"none",label:s("No time (date only)")},{value:"24h",label:s("24-hour")},{value:"12h",label:s("12-hour")}],(x)=>m({time:x}),Boolean(l)),h?g(s("Time zone"),p.timeZone??"",[{value:"",label:s("Viewer's time zone")},...vu.map((x)=>({value:x,label:x}))],(x)=>m({timeZone:x}),Boolean(l)):null]}),mt("p",{style:{...ue.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[s("Preview"),": ",$n(new Date().toISOString(),p)]})]}):null,a&&g(s("Default value"),e.defaultValue?.kind==="now"?"now":"",[{value:"",label:s("Empty")},{value:"now",label:h?s("Current date and time"):s("Today")}],(x)=>x==="now"?u({defaultValue:{kind:"now"}}):c())]})}if(e.type==="number"){let p=Fo(e)??Pu,m=(x)=>u({formatting:{...p,...x}}),h=e.defaultValue?.kind==="value"?String(e.defaultValue.value):"";if(!d&&!a)return null;return mt("fieldset",{style:ue.settings,"aria-label":s("Format of field {name}",{name:e.name}),children:[d?mt(ja,{children:[ut("strong",{style:{fontSize:13},children:s("Format")}),mt("div",{style:ue.row,children:[g(s("Number style"),p.kind,[{value:"decimal",label:s("Number")},{value:"percent",label:s("Percent")},{value:"currency",label:s("Currency")}],(x)=>m({kind:x})),g(s("Decimal places"),String(p.precision),ku.map((x)=>({value:String(x),label:String(x)})),(x)=>m({precision:Number(x)})),p.kind==="currency"?g(s("Currency"),p.currency??"CNY",xu.map((x)=>({value:x,label:x})),(x)=>m({currency:x})):null]}),mt("label",{style:ue.checkbox,children:[ut("input",{type:"checkbox","aria-label":s("Thousands separator"),checked:p.grouping!==!1,disabled:n,onChange:(x)=>m({grouping:x.currentTarget.checked})}),s("Thousands separator")]}),mt("p",{style:{...ue.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[s("Preview"),":"," ",To(p.kind==="percent"?0.1234:1234.5678,p)]})]}):null,a&&mt("label",{style:ue.control,children:[ut("span",{style:ue.label,children:s("Default value")}),ut("input",{"aria-label":s("Default value"),style:ue.input,type:"number",step:"any",disabled:n,value:h,onChange:(x)=>{let C=x.currentTarget.value;if(C===""||!Number.isFinite(Number(C)))c();else u({defaultValue:{kind:"value",value:Number(C)}})}})]})]})}if(!a)return null;if(e.type==="singleLineText"||e.type==="longText")return ut("fieldset",{style:ue.settings,"aria-label":s("Defaults of field {name}",{name:e.name}),children:mt("label",{style:ue.control,children:[ut("span",{style:ue.label,children:s("Default value")}),ut("input",{"aria-label":s("Default value"),style:ue.input,disabled:n,value:e.defaultValue?.kind==="value"?String(e.defaultValue.value):"",onChange:(p)=>{let m=p.currentTarget.value;if(m==="")c();else u({defaultValue:{kind:"value",value:m}})}})]})});if(e.type==="checkbox")return ut("fieldset",{style:ue.settings,"aria-label":s("Defaults of field {name}",{name:e.name}),children:mt("label",{style:ue.checkbox,children:[ut("input",{type:"checkbox","aria-label":s("Checked by default"),checked:e.defaultValue?.kind==="value"&&e.defaultValue.value===!0,disabled:n,onChange:(p)=>p.currentTarget.checked?u({defaultValue:{kind:"value",value:!0}}):c()}),s("Checked by default")]})});if((e.type==="singleSelect"||e.type==="multipleSelect")&&(e.options?.length??0)>0){let p=e.options??[],m=e.defaultValue?.kind==="value"?e.defaultValue.value:void 0;if(e.type==="singleSelect")return ut("fieldset",{style:ue.settings,"aria-label":s("Defaults of field {name}",{name:e.name}),children:g(s("Default value"),typeof m==="string"?m:"",[{value:"",label:s("Empty")},...p.map((x)=>({value:x.id,label:x.name}))],(x)=>x?u({defaultValue:{kind:"value",value:x}}):c())});let h=Array.isArray(m)?m:[];return mt("fieldset",{style:ue.settings,"aria-label":s("Defaults of field {name}",{name:e.name}),children:[ut("span",{style:ue.label,children:s("Default value")}),p.map((x)=>mt("label",{style:ue.checkbox,children:[ut("input",{type:"checkbox","aria-label":s("Default option {name}",{name:x.name}),checked:h.includes(x.id),disabled:n,onChange:(C)=>{let w=C.currentTarget.checked?[...h,x.id]:h.filter((f)=>f!==x.id);if(w.length)u({defaultValue:{kind:"value",value:w}});else c()}}),x.name]},x.id))]})}return null}function Us({field:e,fields:t,onChange:n,disabled:o,locale:i}){let r=se(i);if(!Pr.has(e.type))return null;let l=e.ai,d=t.filter((u)=>u.id!==e.id&&u.type!=="blob"&&u.type!=="lookup"),a=l?.sourceFieldIds??[],s=(u)=>n((c)=>{if(u)return{...c,ai:u};let{ai:g,...p}=c;return p});return mt("fieldset",{style:ue.settings,"aria-label":r("AI settings of field {name}",{name:e.name}),children:[mt("label",{style:ue.checkbox,children:[ut("input",{type:"checkbox",checked:Boolean(l),disabled:o,onChange:(u)=>s(u.currentTarget.checked?{prompt:""}:void 0)}),r("Generate this field with AI")]}),l?mt(ja,{children:[mt("label",{style:ue.control,children:[ut("span",{style:ue.label,children:r("AI prompt")}),ut("textarea",{"aria-label":r("AI prompt"),style:{...ue.input,minHeight:72,resize:"vertical"},rows:3,maxLength:ea,placeholder:r("e.g. Summarize the description in one sentence"),value:l.prompt,disabled:o,onChange:(u)=>{let c=u.currentTarget.value;n((g)=>({...g,ai:{...g.ai,prompt:c}}))}})]}),mt("label",{style:ue.checkbox,children:[ut("input",{type:"checkbox",checked:Boolean(l.autoFill),disabled:o,onChange:(u)=>{let c=u.currentTarget.checked;n((g)=>{let{autoFill:p,...m}=g.ai??{prompt:""};return{...g,ai:c?{...m,autoFill:!0}:m}})}}),r("Generate when a record is created")]}),ut("span",{style:ue.label,children:r("Fields the AI reads (none = all)")}),ut("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px"},children:d.map((u)=>mt("label",{style:ue.checkbox,children:[ut("input",{type:"checkbox","aria-label":r("AI reads {name}",{name:u.name}),checked:a.includes(u.id),disabled:o,onChange:(c)=>{let g=c.currentTarget.checked;n((p)=>{let m=p.ai?.sourceFieldIds??[],h=g?[...m,u.id]:m.filter((w)=>w!==u.id),{sourceFieldIds:x,...C}=p.ai??{prompt:""};return{...p,ai:h.length?{...C,sourceFieldIds:h}:C}})}}),u.name]},u.id))})]}):null]})}import{jsx as Xe,jsxs as pn}from"react/jsx-runtime";var Ka=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],_s=(e)=>e==="singleSelect"||e==="multipleSelect";function Iu(e,t){let n=t.slice(0,oi);if(!n.trim()){let{description:o,...i}=e;return i}return{...e,description:n}}function qr({fields:e,onChange:t,disabled:n=!1,focusFieldId:o,locale:i,ui:r,fieldTypes:l=Ka,relationTargets:d=[],lockedFieldIds:a=[],settings:s,single:u=!1,contextFields:c}){let g=se(i),p={singleLineText:g("Single line text"),longText:g("Long text"),number:g("Number"),checkbox:g("Checkbox"),date:g("Date"),singleSelect:g("Single select"),multipleSelect:g("Multiple select"),relation:g("Linked record"),hyperlink:g("Hyperlink")},m=Fr()?.kinds??[],h=(P)=>l.includes(P.type),x=zr(new Map),C=zr(new Map),w=zr(null),f=zr(new Map),R=zr(null);function S(P,I){let k={fields:P,target:I};R.current=k,t(P),queueMicrotask(()=>{if(R.current===k)R.current=null})}Ru(()=>{let P=R.current;if(!P||P.fields!==e)return;if(R.current=null,n)return;let{target:I}=P,k=I.type==="field-name"?x.current.get(I.fieldId):I.type==="option-name"?C.current.get(`${I.fieldId}:${I.optionId}`):null;if(k){k.focus(),k.select();return}(I.type==="add-field"?w.current:I.type==="add-option"?f.current.get(I.fieldId):null)?.querySelector("button")?.focus()},[n,e]),Su(()=>{if(!o)return;let P=window.setTimeout(()=>{let I=x.current.get(o);I?.scrollIntoView({block:"center"}),I?.focus(),I?.select()},200);return()=>window.clearTimeout(P)},[o]);let A=(P,I)=>{if(!n)t(e.map((k)=>k.id===P?I(k):k))};function L(){if(n)return;let P={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:g("New field"),type:"singleLineText"};S([...e,P],{type:"field-name",fieldId:P.id})}function M(P){if(n)return;let I=e.filter(h),k=I.findIndex((B)=>B.id===P),T=I.filter((B)=>B.id!==P),D=T[k]??T[k-1];S(e.filter((B)=>B.id!==P),D?{type:"field-name",fieldId:D.id}:{type:"add-field"})}function U(P){if(n)return;let I={id:crypto.randomUUID(),name:g("New option")};S(e.map((k)=>k.id===P.id?{...k,options:[...k.options??[],I]}:k),{type:"option-name",fieldId:P.id,optionId:I.id})}function J(P,I){if(n)return;let k=P.options??[],T=k.findIndex((F)=>F.id===I),D=k.filter((F)=>F.id!==I),B=D[T]??D[T-1];S(e.map((F)=>{if(F.id!==P.id)return F;let H=F.defaultValue;if(!(H?.kind==="value"&&(Array.isArray(H.value)?H.value.includes(I):H.value===I)))return{...F,options:D};let{defaultValue:ce,...Z}=F;return{...Z,options:D}}),B?{type:"option-name",fieldId:P.id,optionId:B.id}:{type:"add-option",fieldId:P.id})}return pn("section",{"aria-label":g("Collection fields"),"data-uibot-schema-editor":"",style:ue.root,children:[e.filter(h).map((P)=>pn("fieldset",{"aria-label":g("Field {name}",{name:P.name}),style:u?{...ue.field,border:0,padding:0,background:"none"}:ue.field,children:[pn("div",{style:ue.row,children:[pn("label",{style:ue.control,children:[Xe("span",{style:ue.label,children:g("Field name")}),Xe("input",{"aria-label":g("Field name"),ref:(I)=>{if(I)x.current.set(P.id,I);else x.current.delete(P.id)},style:ue.input,value:P.name,disabled:n,onChange:(I)=>{let k=I.currentTarget.value;A(P.id,(T)=>({...T,name:k}))}})]}),pn("div",{style:ue.control,children:[Xe("span",{style:ue.label,children:g("Field type")}),Xe(Je,{ui:r,label:g("Field type"),style:ue.input,disabled:n||a.includes(P.id),value:P.type,options:l.map((I)=>({value:I,label:p[I]})),onChange:(I)=>A(P.id,(k)=>{let{options:T,relation:D,hyperlink:B,formatting:F,defaultValue:H,...z}=k;return{...z,type:I,..._s(I)?{options:k.options??[]}:{},...I==="relation"?{relation:{collectionId:""}}:{}}})})]}),pn("label",{style:ue.checkbox,children:[Xe("input",{type:"checkbox","aria-label":g("Required"),checked:Boolean(P.required),disabled:n,onChange:(I)=>{let k=I.currentTarget.checked;A(P.id,(T)=>({...T,required:k}))}}),g("Required")]}),u?null:Xe(W,{ui:r,style:{...ue.button,...ue.danger},disabled:n||a.includes(P.id),icon:"trash",iconOnly:!0,ariaLabel:g("Delete field"),title:g("Delete field {name}",{name:P.name}),onClick:()=>M(P.id)})]}),s?.descriptions===!1?null:pn("label",{style:ue.control,children:[Xe("span",{style:ue.label,children:g("Field description")}),Xe("textarea",{"aria-label":g("Field description"),style:{...ue.input,minHeight:64,resize:"vertical"},rows:2,maxLength:oi,value:P.description??"",disabled:n,onChange:(I)=>{let k=I.currentTarget.value;A(P.id,(T)=>Iu(T,k))}})]}),P.type==="relation"?pn("div",{style:ue.control,children:[Xe("span",{style:ue.label,children:g("Related table")}),Xe(Je,{ui:r,label:g("Related table"),style:ue.input,disabled:n||a.includes(P.id),value:P.relation?.collectionId??"",options:[{value:"",label:g("Choose a related table")},...d.map((I)=>({value:I.id,label:I.name}))],onChange:(I)=>A(P.id,(k)=>({...k,relation:{collectionId:I}}))})]}):null,P.type==="hyperlink"&&m.length>0?pn("fieldset",{style:ue.settings,"aria-label":g("Link targets"),children:[Xe("span",{style:ue.label,children:g("Link targets")}),Xe("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px"},children:m.map((I)=>{let k=P.hyperlink?.kinds??[];return pn("label",{style:ue.checkbox,children:[Xe("input",{type:"checkbox",checked:k.includes(I.id),disabled:n,onChange:(T)=>{let D=T.currentTarget.checked;A(P.id,(B)=>{let F=B.hyperlink?.kinds??[],H=D?[...F,I.id]:F.filter((Z)=>Z!==I.id),{hyperlink:z,...ce}=B;return H.length?{...ce,hyperlink:{kinds:H}}:ce})}}),I.label]},I.id)})}),Xe("span",{style:{...ue.label,opacity:0.7},children:g("None chosen offers every kind.")})]}):null,_s(P.type)?pn("fieldset",{style:ue.options,"aria-label":g("Options of field {name}",{name:P.name}),children:[Xe("strong",{style:{fontSize:13},children:g("Options")}),(P.options??[]).map((I,k)=>pn("div",{style:ue.optionRow,children:[Xe("input",{"aria-label":g("Option name {index}",{index:k+1}),ref:(T)=>{let D=`${P.id}:${I.id}`;if(T)C.current.set(D,T);else C.current.delete(D)},style:{...ue.input,flex:"1 1 120px",minWidth:0,width:"auto"},value:I.name,disabled:n,onChange:(T)=>{let D=T.currentTarget.value;A(P.id,(B)=>({...B,options:(B.options??[]).map((F)=>F.id===I.id?{...F,name:D}:F)}))}}),s?.optionColors===!1?null:Xe("fieldset",{"aria-label":g("Colour of option {index}",{index:k+1}),style:{display:"inline-flex",flex:"none",gap:4,margin:0,padding:0,border:0,minWidth:0},children:Tn.map((T,D)=>{let B=(I.color??Tn[k%Tn.length])===T;return Xe("button",{type:"button","aria-label":g(`Colour ${T}`),"aria-pressed":B,disabled:n,style:{...ue.swatch,background:kn(D).color,border:B?"2px solid currentColor":"1px solid transparent"},onClick:()=>A(P.id,(F)=>({...F,options:(F.options??[]).map((H)=>H.id===I.id?{...H,color:T}:H)}))},T)})}),Xe(W,{ui:r,style:{...ue.button,...ue.danger},disabled:n,icon:"trash",iconOnly:!0,ariaLabel:g("Delete option {index}",{index:k+1}),title:g("Delete option {index}",{index:k+1}),onClick:()=>J(P,I.id)})]},I.id)),Xe("div",{ref:(I)=>{if(I)f.current.set(P.id,I);else f.current.delete(P.id)},children:Xe(W,{ui:r,style:ue.button,icon:"plus",disabled:n,onClick:()=>U(P),children:g("Add option")})})]}):null,Xe(Bs,{field:P,...s?{settings:s}:{},dateFormatLocked:a.includes(P.id),disabled:n,locale:i,ui:r,onChange:(I)=>A(P.id,I)}),s?.ai?Xe(Us,{field:P,fields:u&&c?[...c,P]:e,disabled:n,locale:i,onChange:(I)=>A(P.id,I)}):null]},P.id)),u?null:Xe("div",{ref:w,children:Xe(W,{ui:r,style:ue.button,icon:"plus",disabled:n,onClick:L,children:g("Add field")})})]})}import{useEffect as Js,useRef as Zs,useState as Za}from"react";import{useCallback as Nu,useEffect as Ws,useLayoutEffect as Mu,useRef as Ja,useState as Gs}from"react";import{createContext as Au,useContext as Du,useCallback as Eu,useEffect as zs,useId as Fu,useLayoutEffect as qs,useRef as Hs,useState as $s}from"react";import{createPortal as Tu}from"react-dom";import{jsx as Yn,jsxs as Ks,Fragment as js}from"react/jsx-runtime";var Ga=Au(!1),Wa="uibot:collection-popover-open";function Ya({label:e,trigger:t,defaultOpen:n=!1,disabled:o,menu:i,children:r}){let[l,d]=$s(n),[a,s]=$s({left:8,top:8}),u=Hs(null),c=Hs(null),g=Fu();zs(()=>{let h=(x)=>{let C=x.detail,w=u.current;if(!C||!w||C===w)return;let f=w.closest("[data-uibot-workspace]")??w.parentElement,R=C.closest("[data-uibot-workspace]")??C.parentElement;if(f===R)d(!1)};return document.addEventListener(Wa,h),()=>document.removeEventListener(Wa,h)},[]);let p=()=>{d(!1),u.current?.focus({preventScroll:!0})},m=Eu(()=>{if(!l)return;let h=u.current?.getBoundingClientRect(),x=c.current?.getBoundingClientRect();if(h&&x){let C={left:Math.max(8,Math.min(h.left,window.innerWidth-x.width-8)),top:Math.max(8,h.bottom+x.height+8<=window.innerHeight?h.bottom+4:h.top-x.height-4)};s((w)=>w.left===C.left&&w.top===C.top?w:C)}},[l]);return qs(m),qs(()=>{if(!l)return;if(u.current)document.dispatchEvent(new CustomEvent(Wa,{detail:u.current}));(c.current?.querySelector("button:not(:disabled), input, select, textarea")??c.current)?.focus({preventScroll:!0})},[l]),zs(()=>{if(!l)return;let h=(C)=>{if(C.target instanceof Node&&!c.current?.contains(C.target)&&!u.current?.contains(C.target))d(!1)},x=(C)=>{if(C.key!=="Escape")return;C.preventDefault(),C.stopPropagation(),d(!1),u.current?.focus({preventScroll:!0})};return window.addEventListener("resize",m),window.addEventListener("scroll",m,!0),document.addEventListener("pointerdown",h),document.addEventListener("keydown",x),()=>{window.removeEventListener("resize",m),window.removeEventListener("scroll",m,!0),document.removeEventListener("pointerdown",h),document.removeEventListener("keydown",x)}},[l,m]),Ks(js,{children:[Yn("button",{ref:u,type:"button","aria-label":e,"aria-haspopup":i?"menu":"dialog","aria-expanded":l,"aria-controls":l?g:void 0,disabled:o,style:{display:"inline-flex",alignItems:"center",gap:6,border:0,background:"transparent",color:"inherit",font:"inherit",padding:"4px 6px",cursor:"pointer"},onPointerDown:(h)=>h.stopPropagation(),onClick:()=>l?p():d(!0),children:t}),l&&Tu(Yn("div",{ref:c,id:g,role:i?"menu":"dialog","aria-label":e,tabIndex:-1,style:{position:"fixed",...a,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:(h)=>{if(!i||!["ArrowDown","ArrowUp","Home","End"].includes(h.key))return;h.preventDefault();let x=[...h.currentTarget.querySelectorAll('button[role="menuitem"]:not(:disabled)')],C=x.indexOf(document.activeElement),w=h.key==="Home"?0:h.key==="End"?x.length-1:(C+(h.key==="ArrowUp"?-1:1)+x.length)%x.length;x[w]?.focus()},children:r(p)}),document.body)]})}function Bn({ui:e,label:t,defaultOpen:n,icon:o,chevron:i,quiet:r,active:l,children:d}){let a=Du(Ga),s=(u)=>Yn("div",{style:{fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},children:Yn("fieldset",{disabled:a,style:{border:0,padding:0,margin:0,minWidth:0},children:u})});if(e?.Popover)return e.Popover({label:t,defaultOpen:n,...o?{icon:Yn(Ce,{name:o})}:{},...i?{iconEnd:Yn(Ce,{name:"chevronDown",size:13})}:{},...r?{quiet:r}:{},active:l,children:typeof d==="function"?(u)=>s(d(u)):s(d)});return Yn(Ya,{label:t,defaultOpen:n,trigger:Ks(js,{children:[o?Yn(Ce,{name:o}):null,t,i?Yn(Ce,{name:"chevronDown",size:13}):null]}),children:(u)=>s(typeof d==="function"?d(u):d)})}import{jsx as Bi,jsxs as Ys,Fragment as Lu}from"react/jsx-runtime";function Ui({items:e,label:t,children:n,block:o=!1}){let[i,r]=Gs(null),l=Ja(null),d=Ja(null),[a,s]=Gs({x:0,y:0}),u=Nu(()=>{if(!i||!d.current)return;let g=Math.max(12,Math.min(i.x,window.innerWidth-12-d.current.offsetWidth)),p=Math.max(12,Math.min(i.y,window.innerHeight-12-d.current.offsetHeight));s((m)=>m.x===g&&m.y===p?m:{x:g,y:p})},[i]);Mu(u),Ws(()=>{if(!i)return;return window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[i,u]);let c=Ja(null);return Ws(()=>{if(!i)return;c.current=document.activeElement instanceof HTMLElement?document.activeElement:null,d.current?.querySelector("button:not(:disabled)")?.focus();let g=()=>r(null),p=(m)=>{if(m.key==="Escape")m.preventDefault(),m.stopPropagation(),r(null),c.current?.focus({preventScroll:!0})};return window.addEventListener("keydown",p),window.addEventListener("pointerdown",g),window.addEventListener("blur",g),()=>{window.removeEventListener("keydown",p),window.removeEventListener("pointerdown",g),window.removeEventListener("blur",g)}},[i]),Ys("span",{ref:l,style:{display:o?"block":"inline-flex"},onKeyDown:(g)=>{if(g.shiftKey&&g.key==="F10"||g.key==="ContextMenu"){g.preventDefault(),g.stopPropagation();let p=g.target.getBoundingClientRect();r({x:Math.max(8,Math.min(p.left,window.innerWidth-240)),y:Math.max(8,Math.min(p.bottom,window.innerHeight-280))})}},onContextMenu:(g)=>{g.preventDefault(),g.stopPropagation(),r({x:Math.max(8,Math.min(g.clientX,window.innerWidth-240)),y:Math.max(8,Math.min(g.clientY,window.innerHeight-280))})},children:[n,i&&Bi("div",{ref:d,role:"menu","aria-label":t,style:{position:"fixed",left:a.x,top:a.y,boxSizing:"border-box",maxWidth:"calc(100vw - 24px)",maxHeight:"min(70vh, calc(100vh - 24px))",overflow:"auto",zIndex:60,minWidth:140,font:"inherit",padding:4,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",boxShadow:"0 4px 16px rgb(0 0 0 / 0.12)"},onPointerDown:(g)=>g.stopPropagation(),onKeyDown:(g)=>{if(!["ArrowDown","ArrowUp"].includes(g.key))return;g.preventDefault();let p=[...g.currentTarget.querySelectorAll("button:not(:disabled)")],m=p.indexOf(document.activeElement);p[(m+(g.key==="ArrowUp"?-1:1)+p.length)%p.length]?.focus()},children:e.map((g)=>Bi("button",{type:"button",role:"menuitem",disabled:g.disabled,style:{display:"block",width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderRadius:6,background:"transparent",color:g.destructive?"var(--destructive, #b3261e)":"inherit",cursor:g.disabled?"default":"pointer",opacity:g.disabled?0.5:1},onClick:()=>{r(null),g.onSelect()},children:g.label},g.id))})]})}function _i({label:e,items:t,disabled:n,icon:o}){return Bi(Ya,{label:e,disabled:n,menu:!0,trigger:o??"+",children:(i)=>Bi(Lu,{children:t.map((r)=>Ys("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 nn,jsxs as Qs}from"react/jsx-runtime";function Ou(e,t,n,o){if(t===n)return[...e];let i=e.filter((l)=>l!==t),r=i.indexOf(n);if(r<0||!e.includes(t))return[...e];return i.splice(o?r+1:r,0,t),i}var Vu=["grid","kanban","gallery","calendar","form"];function Bu(e,t){return{grid:e("Grid"),kanban:e("Kanban"),gallery:e("Gallery"),calendar:e("Calendar"),form:e("Form")}[t]}function Uu({slot:e,items:t,label:n,children:o}){if(!t.length)return nn("span",{children:o});if(e)return nn(e,{items:t,"aria-label":n,children:o});return nn(Ui,{items:t,label:n,children:o})}function Qa(e){let t=se(e.locale),[n,o]=Za(null),[i,r]=Za(""),[l,d]=Za(null),a=Zs(null),s=Zs(null),u=Boolean(e.onReorder)&&!e.disabled&&e.views.length>1,c=e.views.map((S)=>S.id),g=(S,A,L)=>{let M=Ou(c,S,A,L);if(M.join("\x00")!==c.join("\x00"))e.onReorder?.(M)};Js(()=>{let S=a.current;if(!S)return;a.current=null,document.querySelector(`[data-view-tab="${CSS.escape(S)}"]`)?.focus()}),Js(()=>{if(n)s.current?.select()},[n]);let p=Boolean(e.onDelete)&&e.views.length>1,m=(S)=>{if(!e.onRename||e.disabled)return;r(S.name),o(S.id)},h=()=>{if(!n)return;let S=e.views.find((L)=>L.id===n),A=i.trim();if(o(null),S&&A&&A!==S.name)e.onRename?.(S.id,A)},x=(S)=>[...e.onRename?[{id:"rename",icon:nn(Ce,{name:"pencil"}),label:t("Rename view"),onSelect:()=>m(S)}]:[],...e.onDuplicate?[{id:"duplicate",icon:nn(Ce,{name:"copy"}),label:t("Duplicate view"),onSelect:()=>e.onDuplicate?.(S.id)}]:[],...e.onDelete?[{id:"delete",icon:nn(Ce,{name:"trash"}),label:t("Delete view"),destructive:!0,disabled:!p,onSelect:()=>e.onDelete?.(S.id)}]:[]],C=(S,A)=>{let L=e.views.findIndex((M)=>M.id===A.id);if(S.altKey&&(S.key==="ArrowRight"||S.key==="ArrowLeft")){S.preventDefault();let M=e.views[L+(S.key==="ArrowRight"?1:-1)];if(u&&M)a.current=A.id,g(A.id,M.id,S.key==="ArrowRight")}else if(S.key==="F2")S.preventDefault(),m(A);else if(S.key==="Delete"&&p&&!e.disabled)S.preventDefault(),e.onDelete?.(A.id);else if(S.key==="ArrowRight"||S.key==="ArrowLeft"){S.preventDefault();let M=e.views[L+(S.key==="ArrowRight"?1:-1)];if(M)e.onSelect(M.id),S.currentTarget.parentElement?.parentElement?.querySelectorAll('[role="tab"]')?.[L+(S.key==="ArrowRight"?1:-1)]?.focus()}},w=(e.viewTypes??Vu).map((S)=>({id:S,label:Bu(t,S),disabled:e.disabledViewTypes?.includes(S)??!1,onSelect:()=>e.onAdd?.(S)})),f=e.ui?.ContextMenu,R=e.ui?.DropdownMenu;return Qs("div",{"data-uibot":"collection-view-tabs",style:{display:"flex",alignItems:"flex-end",gap:2,minWidth:0,maxWidth:"100%",overflowX:"auto"},children:[nn("div",{role:"tablist","aria-label":t("Views"),style:{display:"flex",gap:2},children:e.views.map((S)=>{let A=S.id===e.activeId,L=x(S),M=n===S.id?nn("input",{ref:s,"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:(U)=>r(U.target.value),onBlur:h,onKeyDown:(U)=>{if(U.stopPropagation(),U.key==="Enter")U.preventDefault(),h();else if(U.key==="Escape")U.preventDefault(),o(null)}}):Qs("button",{type:"button",role:"tab","aria-selected":A,tabIndex:A?0:-1,disabled:e.disabled,title:e.onRename?t("Double click to rename"):void 0,"data-view-tab":S.id,draggable:u,onDragStart:(U)=>{if(!u)return;U.dataTransfer.effectAllowed="move",U.dataTransfer.setData("text/plain",S.id),d({id:S.id})},onDragOver:(U)=>{if(!l||l.id===S.id)return;U.preventDefault();let J=U.currentTarget.getBoundingClientRect(),P=(U.clientX||0)>J.left+J.width/2;if(l.over!==S.id||l.after!==P)d({id:l.id,over:S.id,after:P})},onDrop:(U)=>{if(!l)return;U.preventDefault(),g(l.id,S.id,Boolean(l.after)),d(null)},onDragEnd:()=>d(null),style:{boxShadow:l?.over===S.id?l.after?"inset -2px 0 0 var(--primary, #1a56c4)":"inset 2px 0 0 var(--primary, #1a56c4)":void 0,opacity:l?.id===S.id?0.5:1,position:"relative",display:"inline-flex",alignItems:"center",gap:6,height:34,padding:"0 12px",border:0,borderBottom:A?"2px solid var(--primary, #1a56c4)":"2px solid transparent",background:"transparent",color:A?"var(--primary, #1a56c4)":"inherit",fontWeight:A?600:400,fontSize:13,whiteSpace:"nowrap",cursor:"pointer"},onClick:()=>e.onSelect(S.id),onDoubleClick:()=>m(S),onKeyDown:(U)=>C(U,S),children:[nn("span",{children:S.name}),e.dirty&&A&&nn("span",{role:"img","aria-label":t("Unsaved changes"),style:{width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}})]});return nn(Uu,{slot:f,items:n===S.id?[]:L,label:t("View actions"),children:M},S.id)})}),e.onAdd&&(R?nn(R,{label:t("Add view"),items:w,disabled:e.disabled}):nn(_i,{label:t("Add view"),items:w,disabled:e.disabled}))]})}import{useRef as _u,useState as zu}from"react";import{jsx as kt,jsxs as fr}from"react/jsx-runtime";function Xa(e){let t=se(e.locale),n=e.descriptor.fields.find((a)=>a.id===e.view.groupByFieldId),o=Ri(e),i=_u(null),[r,l]=zu(null);if(!n||!["singleSelect","checkbox"].includes(n.type))return kt("p",{role:"status",children:t("Choose a single-select or boolean grouping field.")});let d=es(n,t);return fr("section",{"data-uibot":"collection-kanban",children:[kt(sr,{...e}),kt("div",{style:{display:"flex",gap:12,overflowX:"auto",alignItems:"flex-start",paddingBottom:12},children:d.map((a)=>kt(qu,{...e,field:n,lane:a,lanes:d,blocked:o.blocked,onOpen:l,onMove:(s,u)=>void o.move(s,{[n.id]:u.value}),onDrag:(s)=>{i.current=s},onDrop:(s)=>{if(i.current?.id===s)o.move(i.current,{[n.id]:a.value});i.current=null}},a.id))}),kt(Ii,{state:o,locale:e.locale,ui:e.ui}),r&&kt(Wn,{...e,row:r,onClose:()=>l(null)},r.id)]})}function qu({field:e,lane:t,lanes:n,blocked:o,onOpen:i,onMove:r,onDrag:l,onDrop:d,...a}){let s=se(a.locale),u=Dt(a.features),c=u.optionChips,g=!a.readOnly&&u.rowUpdate,p=dr(a,ns(a.view,e,t)),m=a.descriptor.fields.find((C)=>C.type==="singleLineText"||C.type==="longText")?.id,h=Mo(a.descriptor.fields,a.view).filter((C)=>C.id!==e.id&&C.id!==m).slice(0,3),x=g&&!o&&!(e.required&&t.value===null);return fr("section",{"aria-label":s("Lane {name}",{name:t.name}),"data-lane-id":t.id,style:{...gn,flex:"0 0 290px",minWidth:0,...c?{background:"var(--muted, #f4f6f8)",padding:10}:{}},onDragOver:(C)=>{if(x)C.preventDefault()},onDrop:(C)=>{if(!x)return;C.preventDefault(),d(C.dataTransfer.getData("application/x-uibot-record"))},children:[fr("h3",{style:c?{display:"flex",alignItems:"center",gap:6,margin:"0 0 6px",fontSize:13}:void 0,children:[c&&kt("span",{"aria-hidden":"true",style:{width:8,height:8,borderRadius:999,...t.id.startsWith("option:")?{background:kn($u(n,t)).color}:{background:"var(--muted-foreground, #9a9892)"}}}),t.name," · ",Vr(s,p.page.total,p.page.items.length,a.locale)]}),kt(cr,{state:p,locale:a.locale,ui:a.ui,hideCount:!0}),fr("div",{style:{display:"flex",flexDirection:"column",gap:8,marginTop:12,maxHeight:"65vh",overflowY:"auto"},children:[p.page.items.map((C)=>{let w=$t(C,a.descriptor.fields);return fr("article",{"data-record-id":C.id,style:c?{...gn,padding:10,boxShadow:"0 1px 2px rgb(0 0 0 / 0.06)",cursor:"grab",position:"relative"}:gn,draggable:g&&!o&&!p.loading,onDragStart:(f)=>{l(C),f.dataTransfer.setData("application/x-uibot-record",C.id),f.dataTransfer.effectAllowed="move"},onDragEnd:()=>l(null),children:[kt("button",{type:"button",style:{...ze,width:"100%",textAlign:"left",overflowWrap:"anywhere",...c?{border:0,padding:"0 28px 0 0",background:"transparent",fontWeight:600}:{}},"aria-label":s("Open {name}",{name:w}),onClick:()=>i(C),children:w}),c&&kt(Hu,{row:C,fields:h}),g&&(a.ui?.DropdownMenu?kt("span",{style:{position:"absolute",top:4,right:4},children:a.ui.DropdownMenu({label:s("Move {name}",{name:w}),icon:kt(Ce,{name:"more"}),disabled:o||p.loading,items:n.map((f)=>({id:f.id,label:s("Move to {name}",{name:f.name}),disabled:f.id===t.id||!!e.required&&f.value===null,onSelect:()=>r(C,f)}))})}):fr("div",{style:{display:"flex",flexDirection:"column",gap:4,marginTop:8},children:[kt("span",{children:s("Move to")}),kt(Je,{ui:a.ui,label:s("Move {name}",{name:w}),style:ze,disabled:o||p.loading,value:t.id,onChange:(f)=>{let R=n.find((S)=>S.id===f);if(R&&R.id!==t.id)r(C,R)},options:n.map((f)=>({value:f.id,label:f.name,disabled:!!e.required&&f.value===null}))})]}))]},C.id)}),!p.loading&&!p.error&&!p.page.items.length&&kt("p",{children:s("No records in this lane.")})]})]})}function Hu({row:e,fields:t}){let n=t.map((o)=>{let i=e.values[o.id],r=o.type==="singleSelect"||o.type==="multipleSelect",l=Array.isArray(i)?i:i==null?[]:[i],d=o.type==="linkedRecord"?No(e,o):Mn(i,o,e.computedErrors?.[o.id]);return{field:o,chips:r,ids:l,text:d}}).filter((o)=>o.chips?o.ids.length>0:o.text!=="");if(!n.length)return null;return kt("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:6,alignItems:"center",fontSize:12,opacity:0.85},children:n.map((o)=>o.chips?kt(qo,{ids:o.ids,field:o.field},o.field.id):kt("span",{style:{fontVariantNumeric:"tabular-nums"},children:o.text},o.field.id))})}function $u(e,t){return e.filter((n)=>n.id.startsWith("option:")).findIndex((n)=>n.id===t.id)}import{useState as ju}from"react";import{jsx as Un,jsxs as el}from"react/jsx-runtime";function tl(e){let t=se(e.locale),n=Dt(e.features).optionChips,o=dr(e,fi(e.view)),[i,r]=ju(null),l=e.descriptor.fields.find((a)=>a.type==="singleLineText"||a.type==="longText")?.id,d=Mo(e.descriptor.fields,e.view).filter((a)=>!n||a.id!==l);return el("section",{"data-uibot":"collection-gallery",children:[Un(sr,{...e}),Un(cr,{state:o,locale:e.locale,ui:e.ui}),Un("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 240px), 1fr))",gap:12,marginTop:12},children:o.page.items.map((a)=>el("article",{"data-record-id":a.id,style:{...gn,minWidth:0,...n?{boxShadow:"0 1px 2px rgb(0 0 0 / 0.05)"}:{}},children:[Un("button",{type:"button","aria-label":t("Open {name}",{name:$t(a,e.descriptor.fields)}),style:{...ze,width:"100%",textAlign:"left",overflowWrap:"anywhere",...n?{border:0,padding:0,background:"transparent",fontWeight:600,fontSize:"var(--uibot-workspace-font-size, 13px)"}:{}},onClick:()=>r(a),children:$t(a,e.descriptor.fields)}),Un("dl",{children:d.filter((s)=>!n||!Ku(a,s)).slice(0,n?5:d.length).map((s)=>el("div",{children:[Un("dt",{style:{fontSize:12,opacity:0.7},children:s.name}),Un("dd",{style:{margin:"0 0 8px",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n&&(s.type==="singleSelect"||s.type==="multipleSelect")&&a.values[s.id]!=null?Un(qo,{ids:Array.isArray(a.values[s.id])?a.values[s.id]:[a.values[s.id]],field:s}):(s.type==="linkedRecord"?No(a,s):Mn(a.values[s.id],s,a.computedErrors?.[s.id]))||"—"})]},s.id))})]},a.id))}),!o.loading&&!o.error&&!o.page.items.length&&Un("p",{children:t("No records match this view.")}),i&&Un(Wn,{...e,row:i,onClose:()=>r(null)},i.id)]})}function Ku(e,t){let n=e.values[t.id];if(t.type==="linkedRecord")return!No(e,t);return n==null||n===""||Array.isArray(n)&&n.length===0}import{useRef as Wu,useState as nl}from"react";import{jsx as at,jsxs as bo}from"react/jsx-runtime";function ol(e){let t=se(e.locale),n=Dt(e.features),o=n.optionChips,i=!e.readOnly&&n.rowUpdate,[r,l]=nl(()=>{let f=new Date().toISOString().slice(0,7),R=e.initialMonth??f;try{return Dr(R),{month:R,error:""}}catch{return{month:f,error:t("Invalid initial month. Showing the current UTC month.")}}}),{month:d,error:a}=r,[s,u]=nl(null),c=e.descriptor.fields.find((f)=>f.id===e.view.dateFieldId&&f.type==="date"),g=Wu(null),p=Ri(e),m=dr(e,c?os(e.view,c.id,d):{limit:1},!!c),h=Dr(d),x=(f)=>{try{Dr(f),l({month:f,error:""})}catch{l((R)=>({...R,error:t("Choose a valid month between years 1 and 9998.")}))}},C=(f)=>{let R=new Date(h.start);R.setUTCMonth(R.getUTCMonth()+f),x(R.toISOString().slice(0,7))},w=(f,R)=>{if(!c)return;try{p.move(f,{[c.id]:yi(f.values[c.id],R)})}catch(S){p.mutation.setError(S instanceof Error?S.message:t("Invalid date"))}};if(!c)return at("p",{role:"status",children:t("Choose a date field for this calendar.")});return bo("section",{"data-uibot":"collection-calendar",children:[at(sr,{...e}),bo("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginBottom:12},children:[at(W,{ui:e.ui,style:ze,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:t("Previous month"),onClick:()=>C(-1)}),e.ui?.MonthPicker?at(e.ui.MonthPicker,{value:d,onChange:x,"aria-label":t("Calendar month")}):e.ui?.Button?at("strong",{role:"status","aria-label":t("Calendar month"),style:{minWidth:96,textAlign:"center",fontVariantNumeric:"tabular-nums"},children:t("{year}-{month}",{year:d.slice(0,4),month:d.slice(5,7)})}):bo("label",{children:[t("Month")," ",at("input",{type:"month","aria-label":t("Calendar month"),min:"0001-01",max:"9998-12",value:d,onChange:(f)=>x(f.target.value),style:ze})]}),at(W,{ui:e.ui,style:ze,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:t("Next month"),onClick:()=>C(1)}),at(W,{ui:e.ui,style:ze,variant:"outline",size:"sm",onClick:()=>x(new Date().toISOString().slice(0,7)),children:t("Today")})]}),a&&at("p",{role:"alert",children:a}),at(cr,{state:m,locale:e.locale,ui:e.ui}),at("div",{style:{overflowX:"auto",minWidth:0},children:bo("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((f)=>at("strong",{style:o?{padding:"8px 10px",fontSize:12,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"}:{padding:8},children:f},f)),["sun","mon","tue","wed","thu","fri","sat"].slice(0,h.weekday).map((f)=>at("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},f)),Array.from({length:h.days},(f,R)=>{let S=`${d}-${String(R+1).padStart(2,"0")}`,A=m.page.items.filter((L)=>String(L.values[c.id]??"").slice(0,10)===S);return bo("article",{"aria-label":t("Day {day}",{day:S}),"data-calendar-day":S,style:{...gn,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:(L)=>{if(i&&!p.blocked)L.preventDefault()},onDrop:(L)=>{if(!i||p.blocked)return;if(L.preventDefault(),g.current?.id===L.dataTransfer.getData("application/x-uibot-record"))w(g.current,S);g.current=null},children:[at("time",{dateTime:S,children:R+1}),A.map((L)=>bo("article",{"data-record-id":L.id,style:{marginTop:8},draggable:i&&!p.blocked&&!m.loading,onDragStart:(M)=>{g.current=L,M.dataTransfer.setData("application/x-uibot-record",L.id),M.dataTransfer.effectAllowed="move"},onDragEnd:()=>{g.current=null},children:[bo("button",{type:"button",style:{...ze,textAlign:"left",width:"100%",overflowWrap:"anywhere",...o?{border:0,padding:"3px 8px",fontSize:12,fontWeight:500,...kn(0)}:{}},"aria-label":t("Open {name}",{name:$t(L,e.descriptor.fields)}),onClick:()=>u(L),children:[$t(L,e.descriptor.fields)," ",at("small",{children:String(L.values[c.id]).slice(11,16)})]}),i&&at(Gu,{ui:e.ui,t,row:L,fieldId:c.id,title:$t(L,e.descriptor.fields),disabled:p.blocked||m.loading,onMove:w})]},L.id))]},S)})]})}),!m.loading&&!m.error&&!m.page.items.length&&at("p",{children:t("No dated records match this month.")}),at(Ii,{state:p,locale:e.locale,ui:e.ui}),!p.intent&&p.mutation.error&&at("p",{role:"alert",children:p.mutation.error}),s&&at(Wn,{...e,row:s,onClose:()=>u(null)},s.id)]})}function Gu({ui:e,t,row:n,fieldId:o,title:i,disabled:r,onMove:l}){let[d,a]=nl({day:String(n.values[o]).slice(0,10)}),s=e?.DateMove;if(s)return at(s,{label:t("Move {name} to date",{name:i}),value:d.day,disabled:r,onPick:(u)=>l(d.baseline??n,u)});return bo("div",{style:{marginTop:4,display:"flex",gap:4,flexWrap:"wrap"},children:[at("input",{type:"date","aria-label":t("Move {name} to date",{name:i}),value:d.day,disabled:r,style:{width:"100%",minWidth:0},onChange:(u)=>a({day:u.target.value,baseline:d.baseline??n})}),at("button",{type:"button",style:ze,"aria-label":t("Move {name}",{name:i}),disabled:r||!d.day,onClick:()=>l(d.baseline??n,d.day),children:t("Move")})]})}import{jsx as Jn,jsxs as yr}from"react/jsx-runtime";function rl({fields:e,view:t,onChange:n,locale:o,ui:i,features:r,sections:l,filterEditor:d,grouping:a,rowHeight:s}){let u=se(o),c=Dt(r),g=e.filter((w)=>w.type==="singleSelect"||w.type==="checkbox"),p=e.filter((w)=>w.type==="date"),m=(w)=>{let f={...t,type:w};if(delete f.groupByFieldId,delete f.dateFieldId,w==="kanban"&&g[0])f.groupByFieldId=g[0].id;if(w==="calendar"&&p[0])f.dateFieldId=p[0].id;if(w==="form")f.hiddenColumns=f.hiddenColumns.filter((R)=>!e.find((S)=>S.id===R)?.required);n(f)},h={grid:u("Grid"),kanban:u("Kanban"),gallery:u("Gallery"),calendar:u("Calendar"),form:u("Form")},x=c.viewTypes.map((w)=>({value:w,label:h[w],disabled:w==="kanban"&&!g.length||w==="calendar"&&!p.length})),C=t.type??"grid";return yr("div",{style:{display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},children:[yr("div",{children:[u("View type")," ",Jn(Je,{ui:i,label:u("View type"),style:ze,value:C,options:x,onChange:(w)=>m(w)})]}),C==="grid"&&c.groupBy&&g.length>0&&a!==!1&&Jn("div",{style:{flexBasis:"100%"},children:Jn(Li,{fields:e,view:t,onChange:n,locale:o,ui:i})}),C==="grid"&&s!==!1&&yr("div",{children:[u("Row height")," ",Jn(Je,{ui:i,label:u("Row height"),style:ze,value:t.rowHeight??"short",options:ri.map((w)=>({value:w,label:u(`Row height ${w}`)})),onChange:(w)=>{let f={...t};if(w==="short")delete f.rowHeight;else f.rowHeight=w;n(f)}})]}),C==="kanban"&&yr("div",{children:[u("Group by")," ",Jn(Je,{ui:i,label:u("Kanban grouping field"),style:ze,value:t.groupByFieldId??"",options:g.map((w)=>({value:w.id,label:w.name})),onChange:(w)=>n({...t,groupByFieldId:w})})]}),C==="calendar"&&yr("div",{children:[u("Date field")," ",Jn(Je,{ui:i,label:u("Calendar date field"),style:ze,value:t.dateFieldId??"",options:p.map((w)=>({value:w.id,label:w.name})),onChange:(w)=>n({...t,dateFieldId:w})})]}),(l?.filter||l?.columns||l?.sort)&&yr("div",{style:{display:"grid",gap:12,flexBasis:"100%"},children:[l?.filter&&Jn(Ni,{fields:e,view:t,onChange:n,locale:o,ui:i,editor:d}),l?.columns&&Jn(Ts,{fields:e,view:t,onChange:n,locale:o,ui:i}),l?.sort&&Jn(Mi,{fields:e,view:t,onChange:n,locale:o,ui:i})]})]})}function Xs(e,t){if(!t)return e;return il(e,async(o,i)=>{let r=await e.mutate(o,i);if(r.ok||r.error.code!=="approval_required")return r;let l=await t(r.error.details??{approvalRequestId:""},i);return l?e.mutate(o,{...i,approvalReceiptId:l}):r})}function il(e,t){return new Proxy(e,{get(n,o){if(o==="mutate")return t;let i=Reflect.get(n,o,n);return typeof i==="function"?i.bind(n):i}})}var ed=(e)=>e.type==="singleLineText"||e.type==="longText",td=(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"},nd=(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 Yu(e,t){let n=e?.fields??[],o=n.find((r)=>r.id===t),i=n.filter((r)=>ed(r)&&!td(r)).sort((r,l)=>nd(r.name)-nd(l.name));return[...o&&ed(o)&&!td(o)?[o]:[],...i].filter((r,l,d)=>d.findIndex((a)=>a.id===r.id)===l)}function Ju(e){if(!e?.length)return;let t=[...new Set(e.filter((n)=>n!==""))].slice(0,50);return t.length?t:void 0}function od(e,t){return async(n)=>{let o=Ju(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=Yu((typeof t==="function"?t():t).find((l)=>l.id===n.collectionId),n.labelFieldId);return{ok:!0,data:{items:i.data.items.map((l)=>{let d=r.map((a)=>l.values[a.id]).find((a)=>a!==null&&a!==void 0&&String(a).trim()!=="");return{id:l.id,label:d===void 0?l.id:String(d)}}),nextCursor:i.data.nextCursor}}}}import{useEffect as Sn,useLayoutEffect as eg,useMemo as wn,useRef as Pn,useState as yt}from"react";import{DndContext as tg,PointerSensor as ng,useDraggable as og,useSensor as rg,useSensors as ig}from"@dnd-kit/core";import{defaultRangeExtractor as ag,useVirtualizer as ud}from"@tanstack/react-virtual";function rd(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 al(e,t){let n=new Set(e);if(n.has(t))n.delete(t);else n.add(t);return n}function zi(e){let t=Tn.findIndex((o)=>o===e);if(t<0)return;let n=kn(t);return{background:`color-mix(in srgb, ${n.background} 55%, var(--background, white))`,marker:String(n.color)}}var id=(e,t)=>(e%t+t)%t;function ad(e,t,n,o){let i=[],r=0,l=0,d=e.lastRow-e.firstRow+1,a=e.lastColumn-e.firstColumn+1;if(d<1||a<1||t.lastRow-t.firstRow+1>100)return{mutations:i,skipped:r,count:l,limitExceeded:!0};for(let s=t.firstRow;s<=t.lastRow;s++){let u=n[s];if(!u)continue;let c={};for(let g=t.firstColumn;g<=t.lastColumn;g++){if(s>=e.firstRow&&s<=e.lastRow&&g>=e.firstColumn&&g<=e.lastColumn)continue;let p=o[g];if(!p)continue;if(it(p)||p.generation==="autoIncrement"||["blob","linkedRecord","relation"].includes(p.type)){r++;continue}let m=e.firstColumn+id(g-e.firstColumn,a),h=o[m];if(!h||h.type!==p.type){r++;continue}let x=n[e.firstRow+id(s-e.firstRow,d)]?.values[h.id]??null;if(a===1&&d>=2&&(p.type==="number"||p.type==="date")&&g===e.firstColumn){let C=n.slice(e.firstRow,e.lastRow+1).map((S)=>S.values[h.id]),w=C.map((S)=>p.type==="date"?typeof S==="string"&&S!==""?Date.parse(S)/86400000:Number.NaN:typeof S==="number"?S:Number.NaN),f=w[0]??Number.NaN,R=(w[1]??Number.NaN)-f;if(w.every((S,A)=>Number.isFinite(S)&&Math.abs(S-(f+R*A))<0.00000001)){let S=f+R*(s-e.firstRow);if(Number.isFinite(S))x=p.type==="date"?String(C[0]).length===10?new Date(S*86400000).toISOString().slice(0,10):new Date(S*86400000).toISOString():S}}c[p.id]=structuredClone(x),l++}if(Object.keys(c).length)i.push({op:"update",id:u.id,expectedVersion:u.version,values:c})}return{mutations:i,skipped:r,count:l,limitExceeded:!1}}import{useEffect as Zu,useMemo as Qu,useState as Xu}from"react";function ld(e,t,n,o,i,r){let l=Qu(()=>{let s=n.flatMap((u,c)=>{let g=t.footerStats?.[u.id];return g&&g!=="none"&&g!=="count"?[{fn:g,fieldId:u.id,as:`footer${c}`}]:[]});return JSON.stringify([e,ii(t,{aggregates:s}),o.map((u)=>[u.id,u.version]),r])},[e,n,t,o,r]),[d,a]=Xu({key:"",status:"ready",values:{}});return Zu(()=>{if(!i)return;let s=!0,[u,c]=JSON.parse(l);return(async()=>{let g={};for(let p=0;p<c.aggregates.length;p+=8){let m={...c,aggregates:c.aggregates.slice(p,p+8)};if(ai(u,m))throw Error("Invalid summary");let h=await i.aggregate(u.id,m);if(!s)return;if(!h.ok||h.data.length!==1)throw Error("Summary unavailable");for(let x of m.aggregates){let C=h.data[0]?.values[x.as],w=u.fields.find((R)=>R.id===x.fieldId),f=w?.type==="date"||w?.resultType==="date";if(C!==null&&!(typeof C==="number"&&Number.isFinite(C))&&!(f&&(x.fn==="min"||x.fn==="max")&&typeof C==="string"&&Number.isFinite(Date.parse(C))))throw Error("Invalid summary result");g[x.as]=C}}if(s)a({key:l,client:i,status:"ready",values:g})})().catch(()=>{if(s)a({key:l,client:i,status:"error",values:{}})}),()=>{s=!1}},[i,l]),{status:!i?"local":d.key!==l||d.client!==i?"loading":d.status,values:d.key===l&&d.client===i?d.values:{}}}function dd(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 sd=(e)=>e!==null&&e!==void 0&&e!==""&&!(Array.isArray(e)&&e.length===0)&&e!==!1;function cd(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(sd).length;if(n==="empty")return o.filter((r)=>!sd(r)).length;if(t.type==="date"){let r=o.filter((l)=>typeof l==="string"&&l!=="").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,l)=>r+l,0);if(n==="avg")return i.reduce((r,l)=>r+l,0)/i.length;if(n==="min")return Math.min(...i);return Math.max(...i)}import{jsx as Y,jsxs as lt}from"react/jsx-runtime";function lg(e,t){let n=e.find((o)=>o.fieldId===t);if(n?.direction==="desc")return[];return[{fieldId:t,direction:n?"desc":"asc"}]}var Zn={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},sg={padding:5,width:"100%",border:"1px solid #6688bb",background:"var(--background, white)",color:"inherit"};function gd(e){let{descriptor:t,view:n}=e,o=se(e.locale),i=wn(()=>Dt(e.features),[e.features]),r=!e.readOnly&&i.rowDelete,l=!e.readOnly&&i.rowCreate,d=!e.readOnly&&i.rowUpdate,[a,s]=yt({}),u=Pn(new Set),[c,g]=yt(()=>new Set),p=Pn(new Set);Sn(()=>{if(!u.current.size)return;let b=u.current;u.current=new Set,s((E)=>Object.fromEntries(Object.entries(E).filter(([N])=>!b.has(N))))},[e.rows]);let m=wn(()=>Object.keys(a).length?e.rows.map((b)=>a[b.id]?{...b,values:{...b.values,...a[b.id]}}:b):e.rows,[e.rows,a]),h=wn(()=>[...n.columnOrder,...t.fields.map((E)=>E.id).filter((E)=>!n.columnOrder.includes(E))].filter((E)=>!n.hiddenColumns.includes(E)).flatMap((E)=>{let N=t.fields.find((re)=>re.id===E);return N?[N]:[]}),[t.fields,n.columnOrder,n.hiddenColumns]),x=wn(()=>JSON.stringify([m.map((b)=>b.id),h.map((b)=>b.id)]),[m,h]),[C,w]=yt(x),f=Pn(null),[R,S]=yt({row:0,column:0}),[A,L]=yt(!1),[M,U]=yt(()=>new Set),[J,P]=yt(()=>new Set),I=JSON.stringify([t.id,n.filter,n.search,n.sort,e.rowOffset]);Sn(()=>{U(new Set),P(new Set)},[e.rows,I]);let[k,T]=yt({row:0,column:0}),[D,B]=yt(null),F=Pn(!1),H=Pn(!1),[z,ce]=yt(null),[Z,fe]=yt(!1),[Q,q]=yt(!1);Fn({dirty:Boolean(z||Z||D&&D.text!==D.originalText),busy:Q||c.size>0},e);let[te,le]=yt(""),[ve,xe]=yt(null),ae=Pn(null),Te=D?.field.type==="linkedRecord"?JSON.stringify([D.rowId,D.field.id]):null;Sn(()=>{if(Te)ae.current?.querySelector('input[type="search"]')?.focus({preventScroll:!0})},[Te]),Sn(()=>{L(!1),S({row:0,column:0}),T({row:0,column:0}),w(x)},[x]);let pe=wn(()=>{if(!i.groupBy||(n.type??"grid")!=="grid")return;let b=t.fields.find((E)=>E.id===n.groupByFieldId);return ia(b)?b:void 0},[i.groupBy,n.type,n.groupByFieldId,t.fields]),[Me,j]=yt(()=>new Set),v=pe?.id;Sn(()=>j(new Set),[v]);let X=wn(()=>$l(m,pe,Me),[m,pe,Me]),oe=(b)=>Boolean(pe)&&X.rowItem[b]===void 0,tt=jl(n.rowHeight),Pt=la(n.rowHeight),rn=ud({count:X.items.length,getScrollElement:()=>f.current,estimateSize:(b)=>X.items[b]?.kind==="group"?aa:tt,overscan:5,scrollMargin:38,getItemKey:(b)=>`${tt}:${X.items[b]?.key??b}`}),ht=n.showRowNumber===!1?0:56,K=n.showRecordId?220:0,ye=ht+K,[Le,Ae]=yt(0);Sn(()=>{let b=f.current;if(!b)return;let E=()=>Ae(b.clientWidth);if(E(),typeof ResizeObserver>"u")return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E);let N=new ResizeObserver(E);return N.observe(b),()=>N.disconnect()},[]);let nt=Math.min(Math.max(0,n.frozenColumnCount??0),h.length),St=wn(()=>{let b=[ye];for(let E of h)b.push((b.at(-1)??ye)+Hr(n.columnWidths[E.id]??180));return b},[ye,h,n.columnWidths]),Ct=St[nt]??ye,We=Le>0&&Le<=768&&Ct>Le*0.6?0:nt,mn=(b)=>St[b]??ye,Oe=Pn(null),an=Boolean(e.onAddRecord)&&l,st=ig(rg(ng,{activationConstraint:{distance:6}})),Rt=({active:b,delta:E})=>{let N=h.findIndex((Ue)=>Ue.id===b.id),re=Bt.getVirtualItems().find((Ue)=>Ue.index===N);if(N<0||!re)return;let G=re.start+re.size/2+E.x,V=Bt.getVirtualItems().find((Ue)=>G>=Ue.start&&G<Ue.start+Ue.size)?.index;if(V===void 0||V===N)return;if(N<We!==V<We)return;let ne=[...n.columnOrder.filter((Ue)=>t.fields.some((Dn)=>Dn.id===Ue)),...t.fields.map((Ue)=>Ue.id).filter((Ue)=>!n.columnOrder.includes(Ue))],Pe=String(b.id),be=h[V]?.id;if(!be)return;let Re=ne.filter((Ue)=>Ue!==Pe),he=Re.indexOf(be)+(V>N?1:0);Re.splice(he,0,Pe),e.onViewChange({...n,columnOrder:Re})},Vt=(b,E)=>({position:"sticky",float:"left",left:b,zIndex:2,...E?{boxShadow:"2px 0 4px -2px color-mix(in srgb, currentColor 28%, transparent)"}:{}}),Bt=ud({paddingStart:ye,paddingEnd:e.onAddField?ll:0,horizontal:!0,count:h.length,rangeExtractor:(b)=>{let E=new Set(ag(b));for(let N=0;N<We;N+=1)E.add(N);return[...E].sort((N,re)=>N-re)},getScrollElement:()=>f.current,estimateSize:(b)=>Hr(n.columnWidths[h[b]?.id??""]??180),overscan:2,getItemKey:(b)=>h[b]?.id??b});Sn(()=>{h.forEach((b,E)=>{Bt.resizeItem(E,Hr(n.columnWidths[b.id]??180))})},[Bt,n.columnWidths,h]);let ln=Math.max(1,Bt.getTotalSize()),dt=Bt.getVirtualItems(),ot=ga(R,k),Ho=wn(()=>A&&C===x?m.slice(ot.firstRow,ot.lastRow+1):[],[A,C,x,m,ot.firstRow,ot.lastRow]),we=wn(()=>{let b=new Set(m.filter((E,N)=>!pe||X.rowItem[N]!==void 0).map((E)=>E.id));return rd(Ho,M,m,J).filter((E)=>b.has(E.id))},[Ho,M,m,J,pe,X]),Xn=wn(()=>we.map((b)=>b.id),[we]),Ut=wn(()=>new Set(Xn),[Xn]),_n=A?{first:ot.firstColumn,last:ot.lastColumn}:{first:0,last:h.length-1},$o=()=>we.length?Zl(we,h,{row:0,column:_n.first},{row:we.length-1,column:_n.last}):"",eo=(b)=>{if(D||Q||Z||z)return;let E=m[b];if(!E)return;if(w(x),Ho.some((N)=>N.id===E.id))P((N)=>al(N,E.id));else U((N)=>al(N,E.id));if(!A)S({row:b,column:0}),T({row:b,column:h.length-1})},[vt,Co]=yt(null),vo=Pn(null),to=!M.size&&!J.size&&A&&d&&!Q&&!D&&!Z&&!z&&!Me.size,hr=(b,E)=>{if(!to)return;let N=ad(b,E,m,h),re=(V)=>{le(V),e.onNotify?.(V)};if(N.limitExceeded){re(o("Fill at most 100 rows at once."));return}let G=N.skipped?o("Skipped {count} cells",{count:N.skipped}):"";if(!N.mutations.length){if(G)re(G);return}Ht({idempotencyKey:crypto.randomUUID(),items:N.mutations},()=>{re([o("Filled {count} cells",{count:N.count}),G].filter(Boolean).join("; "))})};Sn(()=>{if(!vt)return;let b=()=>{let N=vo.current;if(Co(null),vo.current=null,N)hr(vt,N)},E=()=>{Co(null),vo.current=null};return window.addEventListener("mouseup",b),window.addEventListener("blur",E),()=>{window.removeEventListener("mouseup",b),window.removeEventListener("blur",E)}});let jo=JSON.stringify({recordIds:C===x?Xn:[],fieldIds:we.length?h.slice(_n.first,_n.last+1).map((b)=>b.id):[]}),Ko=Pn(e.onSelectionChange);Ko.current=e.onSelectionChange,Sn(()=>{Ko.current?.(JSON.parse(jo))},[jo]),Sn(()=>{if(!pe||!oe(k.row))return;let b=ui(X,k.row,-1,m.length),E=b>=0?b:ui(X,k.row,1,m.length);if(E>=0)T({...k,row:E}),S({...k,row:E})},[X]);let Rn=(b)=>{let E=new Set(Me);if(E.has(b))E.delete(b);else E.add(b);j(E),L(!1),U(new Set),P(new Set),S(k)},qt=(b,E=!1)=>{if(Me.size)E=!1;if(L(!0),w(x),T(b),!E)S(b),U(new Set),P(new Set);rn.scrollToIndex(X.rowItem[b.row]??b.row,{align:"auto"}),Bt.scrollToIndex(b.column,{align:"auto"})},no=(b=k,E)=>{if(!d||Q||D||Z||z||h[b.column]?.generation==="autoIncrement")return;let N=m[b.row],re=h[b.column];if(!N||!re||re.type==="blob"||it(re))return;if(c.has(N.id))return;L(!0),w(x),F.current=!1;let G=re.type==="linkedRecord"?JSON.stringify(N.values[re.id]??[]):re.type==="relation"?Xl(N,re):re.type==="json"&&N.values[re.id]!=null?JSON.stringify(N.values[re.id]):et(N.values[re.id]);B({rowId:N.id,expectedVersion:N.version,field:re,originalText:G,text:re.type==="linkedRecord"||re.type==="relation"?G:E??G}),le(i.optimisticEdit?"":o("Unsaved changes")),ce(null),xe(null)},Wt=Pn([]),Gt=Pn([]),[Yt,oo]=yt(null),Wo=(b,E)=>{for(let N of b.items){if(N.op!=="update")continue;let re=E.items.find((G)=>G.id===N.id);if(!re)continue;for(let G of[Wt,Gt])G.current=G.current.map((V)=>({...V,items:V.items.map((ne)=>ne.op!=="insert"&&ne.id===N.id&&ne.expectedVersion===N.expectedVersion?{...ne,expectedVersion:re.version}:ne)}))}},Go=(b,E,N)=>{let re=b.items;if(!re.length)return null;let G=new Map(N.map((ne)=>[ne.id,ne])),V=[];if(re.every((ne)=>ne.op==="update")){let ne=new Map(E.items.map((Pe)=>[Pe.id,Pe]));for(let Pe of re){if(Pe.op!=="update")continue;let be=G.get(Pe.id);if(!be)return null;V.push({op:"update",id:Pe.id,expectedVersion:ne.get(Pe.id)?.version??Pe.expectedVersion+1,values:Object.fromEntries(Object.keys(Pe.values).map((Re)=>[Re,be.values[Re]??null]))})}}else if(re.every((ne)=>ne.op==="insert")){if(E.items.length!==re.length)return null;for(let ne of E.items)V.push({op:"delete",id:ne.id,expectedVersion:ne.version})}else if(re.every((ne)=>ne.op==="delete"))for(let ne of re){if(ne.op!=="delete")continue;let Pe=G.get(ne.id);if(!Pe)return null;V.push({op:"insert",values:Object.fromEntries(t.fields.filter((be)=>be.type!=="blob"&&be.type!=="linkedRecord"&&!it(be)&&be.generation!=="autoIncrement"&&Pe.values[be.id]!==void 0).map((be)=>[be.id,Pe.values[be.id]]))})}else return null;return{idempotencyKey:crypto.randomUUID(),items:V}},It=(b)=>{if(Q||e.readOnly||D||Z||z)return;let N=(b==="undo"?Wt:Gt).current.at(-1);if(!N)return;Ht({...N,idempotencyKey:crypto.randomUUID()},void 0,b)};async function Ht(b,E,N){if(Q||H.current||e.readOnly)return;let re=N&&Yt?Yt.before:m;if(N)oo({direction:N,before:re,rejected:!1});H.current=!0,q(!0),ce(b),le("");let G=await e.onMutate(b).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:o("Saving failed. Your edit has been kept.")}}));if(H.current=!1,q(!1),G.ok){let V=Go(b,G.data,re);if(N)(N==="undo"?Wt:Gt).current.pop();if(Wo(b,G.data),oo(null),V)if(N==="undo")Gt.current.push(V);else{if(Wt.current.push(V),Wt.current.length>30)Wt.current.shift();if(!N)Gt.current=[]}e.onCommitted(G.data),ce(null),B(null),fe(!1),xe(null);let ne=b.items.filter((be)=>be.op==="delete").length,Pe=N?o(N==="undo"?"Undone":"Redone"):ne>0&&ne===b.items.length?o("Deleted {count} records",{count:ne}):o("Saved");if(e.onNotify)le(""),e.onNotify(Pe);else le(Pe);f.current?.focus({preventScroll:!0}),E?.()}else{if(N){let ne=G.error.status;oo({direction:N,before:re,rejected:ne>=400&&ne<500&&ne!==408})}le(G.error.message);let V=G.error.details;if(V?.current)xe(V.current)}}async function fn(b,E,N,re){if(p.current.has(b.id))return;p.current.add(b.id),q(!0);let G=D??{rowId:b.id,expectedVersion:b.version,field:E,text:et(N),originalText:et(b.values[E.id])},V={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:b.id,expectedVersion:b.version,values:{[E.id]:N}}]};s((be)=>({...be,[b.id]:{...be[b.id],[E.id]:N}})),g((be)=>new Set(be).add(b.id)),B(null),le(""),f.current?.focus({preventScroll:!0});let ne=await e.onMutate(V).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:o("Saving failed. Your edit has been kept.")}}));if(p.current.delete(b.id),q(!1),g((be)=>{let Re=new Set(be);return Re.delete(b.id),Re}),ne.ok){u.current.add(b.id);let be=Go(V,ne.data,[b]);if(Wo(V,ne.data),be){if(Wt.current.push(be),Wt.current.length>30)Wt.current.shift();Gt.current=[]}e.onCommitted(ne.data),re?.();return}s((be)=>{let Re={...be};return delete Re[b.id],Re}),F.current=!1,B(G),ce(V),le(ne.error.message);let Pe=ne.error.details;if(Pe?.current)xe(Pe.current)}async function Be(b){if(!D||F.current)return;let{field:E,rowId:N,expectedVersion:re}=D;if(E.generation==="autoIncrement"||t.fields.find((G)=>G.id===E.id)?.generation==="autoIncrement"){le(o("{name} is auto-generated and cannot be edited.",{name:E.name})),B(null);return}try{let G=E.type==="linkedRecord"?JSON.parse(D.text):E.type==="relation"?D.text||null:Cn(D.text,E);if(E.type==="linkedRecord"&&E.required&&Array.isArray(G)&&!G.length)throw Error(`${E.name} is required.`);if(i.optimisticEdit&&E.type==="linkedRecord"&&!z&&D.text===D.originalText){Jt();return}if(i.optimisticEdit&&E.type!=="linkedRecord"&&!z){let Pe=m.find((be)=>be.id===N);if(!Pe){B(null);return}if(JSON.stringify(G??null)===JSON.stringify(Pe.values[E.id]??null)){Jt();return}await fn(Pe,E,G,()=>{if(b)qt(gi(k,"Tab",m.length,h.length,b==="previous"))});return}let V={[E.id]:G},ne=z??{idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:N,expectedVersion:re,values:V}]};await Ht(ne,b?()=>qt(gi(k,"Tab",m.length,h.length,b==="previous")):void 0)}catch(G){le((e.locale==="zh-CN"?rr(E,D.text,"zh-CN"):null)||(G instanceof Error?G.message:o("Invalid value")))}}let In=Boolean(e.readOnly||Q||D||Z||z||Xn.length===0),Yo=()=>{if(In||!r)return;zn()},Jt=()=>{F.current=!0,le(""),B(null),ce(null),xe(null),f.current?.focus({preventScroll:!0})},An=(b)=>{if(!D||b===D.text)return;le(i.optimisticEdit?"":o("Unsaved changes")),B({...D,text:b}),ce(null),xe(null)},Cr=(b,E,N)=>{if(!d||Q||D||Z||z)return;if(i.optimisticEdit){fn(b,E,N);return}B({rowId:b.id,expectedVersion:b.version,field:E,text:String(N),originalText:et(b.values[E.id])}),Ht({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:b.id,expectedVersion:b.version,values:{[E.id]:N}}]})},sn=i.optionChips,vr=Boolean(e.renderRecordContextMenu)||i.recordContextMenu,Yr=i.optimisticEdit&&!z?{onBlur:(b)=>{if(!b.currentTarget.contains(b.relatedTarget))Be()}}:{},Mt=D?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:D.field,text:D.text,disabled:Q||Boolean(e.readOnly),autoOpen:!0,onChange:An,onSave:(b)=>void Be(b),onCancel:Jt}):void 0,xr=i.optimisticEdit&&D?.field.type==="linkedRecord"&&(Mt===void 0||Mt===null)&&!z&&!Q?{onBlur:(b)=>{let E=b.relatedTarget;if(!E||ae.current?.contains(E)||E.closest('[role="gridcell"]')?.id===`wb-${D.rowId}-${D.field.id}`)return;Be()}}:{},xo=D&&(D.field.type==="singleSelect"||D.field.type==="multipleSelect")?Mt??lt("select",{"aria-label":o("Edit {name}",{name:D.field.name}),ref:(b)=>b?.focus(),style:sg,multiple:D.field.type==="multipleSelect",value:D.field.type==="multipleSelect"?D.text.split(",").filter(Boolean):D.text,disabled:Q,onChange:(b)=>An(D.field.type==="multipleSelect"?Array.from(b.currentTarget.selectedOptions,(E)=>E.value).join(","):b.currentTarget.value),onKeyDown:(b)=>{if(b.stopPropagation(),b.key==="Escape")b.preventDefault(),Jt();if(b.key==="Tab")b.preventDefault(),Be(b.shiftKey?"previous":"next");if(b.key==="Enter")b.preventDefault(),Be()},children:[D.field.type==="singleSelect"&&Y("option",{value:"",disabled:D.field.required,children:o("Clear selection")}),(D.field.options??[]).map((b)=>Y("option",{value:b.id,children:b.name},b.id)),D.text.split(",").filter((b)=>b&&!D.field.options?.some((E)=>E.id===b)).map((b)=>Y("option",{value:b,disabled:!0,children:o("{id} (unavailable)",{id:b})},b))]}):void 0,zn=()=>{if(!r||Q||D||Z||z||we.length===0)return;if(we.length>100){le(o("Select at most 100 rows per delete."));return}ce({idempotencyKey:crypto.randomUUID(),items:we.map((b)=>({op:"delete",id:b.id,expectedVersion:b.version}))}),fe(!0),le(""),xe(null)},ko=(b,E,N,re,G)=>{G.setPointerCapture(re);let V=(Pe)=>e.onViewChange({...n,columnWidths:{...n.columnWidths,[b]:Hr(N+Pe.clientX-E)}}),ne=()=>{G.removeEventListener("pointermove",V),G.removeEventListener("pointerup",ne),G.removeEventListener("pointercancel",ne)};G.addEventListener("pointermove",V),G.addEventListener("pointerup",ne),G.addEventListener("pointercancel",ne)},[wo,kr]=yt(480);eg(()=>{if(!e.display?.fill)return;let b=()=>{let E=f.current?.getBoundingClientRect().top??0;kr(Math.max(240,Math.round(window.innerHeight-E-64-(i.footerStats?34:0))))};return b(),window.addEventListener("resize",b),()=>window.removeEventListener("resize",b)},[e.display?.fill,i.footerStats]);let yn=e.display?.summary===!1&&e.display?.keyboardHints===!1,Jo=!!D&&rn.getVirtualItems().some((b)=>{let E=X.items[b.index];return E?.kind==="row"&&m[E.index]?.id===D.rowId})&&Bt.getVirtualItems().some((b)=>h[b.index]?.id===D.field.id),ro=lt("section",{"data-uibot":"paged-collection-grid",style:{display:yn?"grid":"flex",flexDirection:yn?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&&we.length>0&&!e.renderRecordContextMenu&&!i.recordContextMenu)&&lt("div",{"data-uibot":"paged-collection-toolbar",style:{display:"flex",gap:8,padding:8,alignItems:"center",flexWrap:"wrap",...yn?{}:{order:1,padding:"4px 10px",fontSize:12,borderTop:"1px solid var(--border, #d5d9df)"},...yn?{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&&Y("span",{children:Vr(o,e.total,m.length,e.locale)}),e.aggregate&&!i.footerStats&&Y(Bo,{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}:{}}),Y("span",{style:{flex:1}}),e.display?.keyboardHints!==!1&&Y("span",{style:{fontSize:12},children:o(d?"Arrows · Shift select · Enter edit · Copy / paste":"Arrows · Shift select · Copy")}),e.onInspectRecord&&Y(W,{ui:e.ui,style:Zn,variant:"outline",size:"sm",disabled:Q||we.length!==1,onClick:()=>{let b=we[0];if(b)e.onInspectRecord?.(b.id)},children:o("Open record activity")}),r&&we.length>0&&!e.renderRecordContextMenu&&!i.recordContextMenu&&Y(W,{ui:e.ui,style:Zn,variant:"outline",size:"sm",icon:"trash",disabled:In,onClick:zn,children:o("Delete selected rows")})]}),Y("style",{children:`
1
+ import{createContext as Qd,useCallback as Xd,useContext as ec,useLayoutEffect as la,useMemo as tc,useRef as Ul,useState as nc}from"react";var sa=Qd(void 0);function On(e,t={}){let n=ec(sa),o=Ul({}),{dirty:r,busy:i}=e,{onDirtyChange:l,onBusyChange:s}=t;la(()=>{n?.(o.current,{dirty:r,busy:i}),l?.(r),s?.(i)},[n,r,i,l,s]),la(()=>()=>{n?.(o.current),l?.(!1),s?.(!1)},[n,l,s])}function _l(){let e=Ul(new Map),[t,n]=nc({dirty:!1,busy:!1}),o=Xd((r,i)=>{if(i)e.current.set(r,i);else e.current.delete(r);let l=[...e.current.values()],s=l.some((d)=>d.dirty),a=l.some((d)=>d.busy);n((d)=>d.dirty===s&&d.busy===a?d:{dirty:s,busy:a})},[]);return{...t,report:o}}function ci(e,t){let n=tc(()=>({active:!0,client:e,id:t}),[e,t]);return la(()=>(n.active=!0,()=>{n.active=!1}),[n]),n}import{useCallback as Al,useEffect as Et,useMemo as no,useRef as Ht,useState as Me}from"react";function ig(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var Ln=["blue","green","red","orange","gray","teal","purple"];function oc(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 zl(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 r=n.find((s)=>s.id===o.fieldId),l=r?.type==="number"||r?.type==="rating"||r?.type==="autoNumber"?e.reduce((s,a)=>s+(oc(a.values[o.fieldId])??0),0):0;return{fieldId:o.fieldId,fn:"sum",value:l}})}function ql(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function rc(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function ic(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 Hl(e,t){if(!t)return!0;if(ql(t)){let n=t.filterSet.map((o)=>ql(o)?Hl(e,o):rc(o)?ic(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 jl(e,t,n,o){let r=e.views.find((c)=>c.id===n)??e.views[0];if(!r)return{view:{id:n,name:n,kind:"table"},columns:e.fields,rows:[...t]};let i=[...t];if(r.filter)i=i.filter((c)=>Hl(c,r.filter));if(r.sort?.length)i.sort((c,C)=>{for(let x of r.sort??[]){let h=c.values[x.fieldId],g=C.values[x.fieldId];if(h===g)continue;if(h==null)return 1;if(g==null)return-1;let w=e.fields.find((O)=>O.id===x.fieldId)?.type,y=(O)=>{if(["number","rating","autoNumber"].includes(w??"")&&typeof O==="number")return O;if(["date","createdTime","lastModifiedTime"].includes(w??"")){let L=Date.parse(String(O));if(Number.isFinite(L))return L}return String(O)},E=y(h),S=y(g);if(E===S)continue;let k=E<S?-1:1;return x.direction==="desc"?-k:k}return c.id<C.id?-1:c.id===C.id?0:1});let l=r.projection?.length?e.fields.filter((c)=>r.projection?.includes(c.id)):e.fields,s=o?.search?.trim().toLowerCase();if(s)i=i.filter((c)=>l.some((C)=>String(c.values[C.id]??"").toLowerCase().includes(s)));let a=zl(i,r.aggregates,e.fields),d=r.group?.fieldId;if(!d)return{view:r,columns:l,rows:i,...a.length?{aggregates:a}:{}};let u=[],f=new Map;for(let c of i){let C=String(c.values[d]??"");if(!f.has(C))f.set(C,[]),u.push(C);f.get(C)?.push(c)}let p=u.map((c)=>{let C=f.get(c)??[];return{key:c,fieldId:d,rows:C,aggregates:zl(C,r.aggregates,e.fields)}});return{view:r,columns:l,rows:i,groups:p,...a.length?{aggregates:a}:{}}}var ui=500,ca=2000,Fr=new Set(["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"]);function it(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function ln(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 pi=["short","medium","tall","extra"];function $l(e,t){return t.map((n)=>{let o={},r={};for(let i of e.groupBy){let l=n[i];if(!(i in n)||l!==null&&typeof l!=="string"&&typeof l!=="number"&&typeof l!=="boolean")throw Error(`Invalid aggregate group ${i}.`);o[i]=l}for(let{as:i,fn:l}of e.aggregates){let s=n[i];if(!(i in n)||s!==null&&!(typeof s==="number"&&Number.isFinite(s))&&!((l==="min"||l==="max")&&typeof s==="string"&&Number.isFinite(Date.parse(s))))throw Error(`Invalid aggregate value ${i}.`);r[i]=s}return{groups:o,values:r}})}var ac=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,lc=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function gi(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function Zt(e,t){return{code:e,...t}}function sc(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function da(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function mi(e,t){if(t.aggregates.length===0)return Zt("empty");if(t.aggregates.length>8||t.groupBy.length>3)return Zt("too_many");let n=new Set;for(let r of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(r.fn))return Zt("function");if(!ac.test(r.as)||n.has(r.as)||t.groupBy.includes(r.as))return Zt("alias",{alias:r.as,...r.fieldId!==void 0?{fieldId:r.fieldId}:{}});if(n.add(r.as),r.fn==="count"&&r.fieldId===void 0)continue;let i=e.fields.find((l)=>l.id===r.fieldId);if(!i)return Zt(r.fn==="sum"?"sum_field":"unknown_field",{alias:r.as,...r.fieldId!==void 0?{fieldId:r.fieldId}:{}});if(r.fn==="sum"&&!da(i))return Zt("sum_field",{fieldId:i.id,alias:r.as});if(r.fn==="avg"&&!da(i))return Zt("numeric_field",{fieldId:i.id,alias:r.as});if((r.fn==="min"||r.fn==="max")&&!da(i)&&i.type!=="date"&&!((i.type==="formula"||i.type==="rollup")&&i.resultType==="date"))return Zt("extrema_field",{fieldId:i.id,alias:r.as});if((r.fn==="filled"||r.fn==="empty")&&!ln(i))return Zt("queryable_field",{fieldId:i.id,alias:r.as});if(r.fn==="count"&&!ln(i))return Zt("count_field",{fieldId:i.id,alias:r.as})}let o=new Set;for(let r of t.groupBy){if(o.has(r))return Zt("duplicate_group",{fieldId:r});o.add(r);let i=e.fields.find((l)=>l.id===r);if(!i)return Zt("unknown_field",{fieldId:r});if(!lc.has(i.type)&&!sc(i))return Zt("not_groupable",{fieldId:r})}return null}var Kl=(e)=>String(e).padStart(2,"0");function Bn(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=(r)=>Number(n.find((i)=>i.type===r)?.value??0);return{year:o("year"),month:o("month"),day:o("day"),hour:o("hour"),minute:o("minute"),second:o("second")}}function uo(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 r=0;r<2;r++){let i=Bn(new Date(o),t),l=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second);o+=n-l}return new Date(o)}function fi(e,t){let n=Bn(e,t??"UTC");return`${n.year}-${Kl(n.month)}-${Kl(n.day)}`}var dc=/^[a-z][a-z0-9_-]{0,31}$/,yi=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function Wl(e){if(!e||e.length>2048||/\s/.test(e))return!1;for(let n=0;n<e.length;n++)if(e.charCodeAt(n)<32||e.charCodeAt(n)===127)return!1;if(e.startsWith("/"))return!e.startsWith("//")&&!e.startsWith("/\\");let t=/^([a-z][a-z0-9+.-]*):/i.exec(e)?.[1]?.toLowerCase();if(t==="http"||t==="https")try{return Boolean(new URL(e).hostname)}catch{return!1}return t==="mailto"||t==="tel"}function cc(e){if(!yi(e))return"hyperlink must be an object";if(Object.keys(e).some((t)=>t!=="url"&&t!=="text"&&t!=="ref"))return"hyperlink has unknown keys";if(typeof e.url!=="string"||!Wl(e.url))return"hyperlink URL is invalid";if(e.text!==void 0&&(typeof e.text!=="string"||e.text.length>500))return"hyperlink text is invalid";if(e.ref!==void 0){let t=e.ref;if(!yi(t)||Object.keys(t).length!==2||typeof t.kind!=="string"||!dc.test(t.kind)||typeof t.id!=="string"||!t.id||t.id.length>200)return"hyperlink reference is invalid"}return null}var nr=(e)=>cc(e)===null;function Nr(e){if(!yi(e)||typeof e.url!=="string")return"";return typeof e.text==="string"&&e.text.trim()?e.text:e.url}function Gl(e){if(!yi(e)||typeof e.url!=="string")return"";let t=typeof e.text==="string"?e.text.trim():"";return t&&t!==e.url?`[${t.replace(/[[\]]/g,"")}](${e.url})`:e.url}function Fo(e){let t=e.trim();if(!t)return null;if(t.startsWith("{"))try{let i=JSON.parse(t);return nr(i)?i:null}catch{return null}let n=/^\[([^\]]*)\]\((\S+)\)$/.exec(t)??/^(.*?)\s*<(\S+)>$/.exec(t),o=n?.[1]?.trim().slice(0,500)??"",r=n?.[2]??t;if(!/^[a-z][a-z0-9+.-]*:/i.test(r)&&!r.startsWith("/")){if(/^[\w-]+(\.[\w-]+)+(:\d+)?([/?#]\S*)?$/.test(r))r=`https://${r}`;else if(/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(r))r=`mailto:${r}`}if(!Wl(r))return null;return o&&o!==r?{url:r,text:o}:{url:r}}function Mr(e,t=new Date,n){let o={};for(let r of e){let i=r.defaultValue;if(!i)continue;if(i.kind==="value")o[r.id]=Array.isArray(i.value)?[...i.value]:i.value;else if(r.type==="date"){let l=r.formatting;if(l&&"time"in l&&l.time==="none"){let s=Bn(t,n);o[r.id]=`${s.year}-${String(s.month).padStart(2,"0")}-${String(s.day).padStart(2,"0")}`}else o[r.id]=t.toISOString()}}return o}var pa=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],bi=new Set(["pastDays","nextDays","daysAgo","daysFromNow"]),Yl={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"]},or=new Set(["isEmpty","isNotEmpty"]);function Cn(e){switch(e.type){case"singleLineText":case"longText":case"hyperlink":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 Jl(e){let t=Cn(e);return t?Yl[t]:[]}var ua=/^\d{4}-\d{2}-\d{2}$/,uc=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function ga(e){if(!uc(e))return!1;let t=e.mode;if(!pa.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&&ua.test(e.date);if(t==="dateRange")return typeof e.date==="string"&&ua.test(e.date)&&typeof e.to==="string"&&ua.test(e.to)&&e.date<=e.to;if(bi.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function Zl(e,t){if(!e)return"unknown field";let n=Cn(e),o=t.operator==="contains"&&(n==="number"||n==="checkbox"||n==="date"||n==="singleSelect");if(!n||!(Yl[n].includes(t.operator)||o))return"operator not allowed";if(or.has(t.operator))return null;let r=t.value;if(o)return n==="number"?typeof r==="number"&&Number.isFinite(r)?null:"number required":n==="checkbox"?typeof r==="boolean"?null:"boolean required":typeof r==="string"?null:"text required";switch(n){case"text":return typeof r==="string"?null:"text value required";case"number":return typeof r==="number"&&Number.isFinite(r)?null:"number required";case"checkbox":return typeof r==="boolean"?null:"boolean required";case"singleSelect":return typeof r==="string"?null:"option required";case"relation":return typeof r==="string"&&r!==""?null:"record required";case"multipleSelect":return typeof r==="string"||Array.isArray(r)&&r.every((i)=>typeof i==="string")?null:"options required";case"date":return ga(r)||typeof r==="string"&&Number.isFinite(Date.parse(r))?null:"date required"}}var pc={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},Wg=Array.from(new Set(Object.values(pc).flat()));var Jg=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([...[["function","functions"],["scenario","scenarios"],["unit","units"],["industry","industries"]].map(([e,t])=>Object.freeze({name:e,property:t,type:"string",multiple:!0,cliEncoding:"comma-separated"})),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([])}),Object.freeze({name:"docs",summary:"Read curated public documentation for one resource.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([{name:"locale",property:"locale",type:"string"},{name:"page",property:"page",type:"positive-integer"}])}),Object.freeze({name:"examples",summary:"Read one bounded page of examples and exact dependencies. Follow nextPage for complete source.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([{name:"page",property:"page",type:"positive-integer"}])}),Object.freeze({name:"install-plan",summary:"Describe distribution channels and fixed snapshot identity/closure without installing or writing.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([])})]);var gc=["background","foreground","card","card-foreground","popover","popover-foreground","primary","primary-foreground","secondary","secondary-foreground","muted","muted-foreground","accent","accent-foreground","border","input","ring","destructive","destructive-foreground","success","success-foreground","warning","warning-foreground"],Xg=[...gc,"radius","font-display","font-body","font-mono"];function mc(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function lm(e,t){if(t===e.draft)return e;return{...e,draft:t}}function fc(e){return e.draft!==e.savedContent}function sm(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 dm(e,t){if(fc(e))return e;let n=mc(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 Wn=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),No=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),Mo=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,Ql=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,hi=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),Xl=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every(hi)&&new Set(e).size===e.length;function yc(e){if(!Wn(e)||!No(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!hi(e.id)||!Mo(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)=>!Wn(t)||!No(t,["id","name"])||!hi(t.id)||!Mo(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 r=e[n];if(e.type===t!==(r!==void 0))return!1;if(r!==void 0&&(!Wn(r)||!No(r,[...o])||o.some((i)=>!Mo(r[i],i==="expression"?2048:512))))return!1}return!0}function um(e){if(!Wn(e)||!No(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))||!Mo(e.collectionId,512)||!Mo(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(!Wn(t)||!No(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!Mo(t.name,200)||!Ql(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(yc)||new Set(t.fields.map((i)=>i.id)).size!==t.fields.length)return!1;if(!Wn(n)||!No(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!hi(n.id)||!Mo(n.name,200)||!Ql(n.version)||!Xl(n.columnOrder)||!Xl(n.hiddenColumns)||!Wn(n.columnWidths)||Object.values(n.columnWidths).some((i)=>typeof i!=="number"||!Number.isInteger(i)||i<72||i>800))return!1;let o=t.fields,r=(i)=>o.some((l)=>Wn(l)&&l.id===i);if([...n.columnOrder,...n.hiddenColumns,...Object.keys(n.columnWidths)].some((i)=>!r(i)))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((i)=>i.id===n.groupByFieldId&&["singleSelect","checkbox"].includes(i.type)))return!1;if(n.type==="calendar"&&!t.fields.some((i)=>i.id===n.dateFieldId&&i.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((i)=>!Wn(i)||!No(i,["fieldId","direction"])||!r(i.fieldId)||!["asc","desc"].includes(String(i.direction)))))return!1;return!0}function fa(e){return e?.type==="singleSelect"||e?.type==="checkbox"}var hc="\x00none";function ts(e,t,n=new Set){if(!t)return{items:e.map((l,s)=>({kind:"row",index:s,key:l.id})),rowItem:e.map((l,s)=>s)};let o=[],r=[],i;return e.forEach((l,s)=>{let a=l.values[t.id],d=a==null?hc:String(a);if(!i||i.raw!==d){let u=t.options?.findIndex((f)=>f.id===a)??-1;i={kind:"group",key:`group:${o.length}:${d}`,raw:d,label:a==null?null:t.type==="checkbox"?a===!0?"true":"false":t.options?.[u]?.name??String(a),colorIndex:u,count:0,collapsed:n.has(d)},o.push(i)}if(i.count+=1,i.collapsed)return;r[s]=o.length,o.push({kind:"row",index:s,key:l.id})}),{items:o,rowItem:r}}function Ci(e,t,n,o){for(let r=t;r>=0&&r<o;r+=n)if(e.rowItem[r]!==void 0)return r;return-1}var ya=34,ma=38,Cc={short:1,medium:2,tall:3,extra:4},ba=(e)=>Cc[e??"short"],ns=(e)=>ma+(ba(e)-1)*22;function os(e,t=ma){return ma+e.items.reduce((n,o)=>n+(o.kind==="group"?ya:t),0)}function rs(e,t){let n=e?.groupByFieldId;if(!e||!n||(e.type??"grid")!=="grid")return e?.sort;if(!t?.some((o)=>o.id===n&&fa(o)))return e.sort;return[{fieldId:n,direction:"asc"},...(e.sort??[]).filter((o)=>o.fieldId!==n)]}var as=["grid","kanban","gallery","calendar","form"],vc=["grid","form"],ha={search:!0,filter:!0,columns:!0,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!0,tableList:!0,viewManagement:!0,export:!0},xc={search:!0,filter:!1,columns:!1,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!1,tableList:!1,viewManagement:!1,export:!1},wc={search:!0,filter:!0,columns:!0,rowCreate:!1,rowUpdate:!1,rowDelete:!1,schemaEditor:!1,tableList:!0,viewManagement:!1,export:!0},is={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:as},Ca={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:as},ls={basic:{...is,...ha},full:{...Ca,...ha},simple:{...is,...xc,viewTypes:vc},workbench:{...Ca,...ha},readonly:{...Ca,...wc,recordContextMenu:!1,optimisticEdit:!1}};function wt(e){let{preset:t="basic",...n}=e??{},o={...ls[t],...kc(n)};return o.groupBy?o:{...o,groupCollapse:!1}}function kc(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var ss={"Footer record count":"{count} records","Footer count":"Count","Footer filled":"Filled","Footer empty":"Empty","Footer sum":"Sum","Footer avg":"Average","Footer min":"Minimum","Footer max":"Maximum"},Pc={"AI fill":"AI 填充","AI field":"AI 字段","Generate {name} with AI":"AI 生成「{name}」","Only records with empty target cells":"只处理目标为空的记录","No records have empty target cells.":"没有目标为空的记录。","AI settings of field {name}":"字段 {name} 的 AI 设置","Generate this field with AI":"用 AI 生成此字段","Generate when a record is created":"新建记录时自动生成","AI auto-fill stopped: {message}":"AI 自动生成中断:{message}",Hyperlink:"超链接","Search or paste a link":"搜索文档或粘贴链接","Use link {url}":"使用链接 {url}","Display text":"显示文字","Remove link":"移除链接","Link suggestions":"链接建议","Searching…":"搜索中…","No matching resources":"没有匹配的内容","{name} needs a link.":"{name}需要有效链接(http(s)、邮箱或站内路径)。","Link targets":"可选的链接目标","None chosen offers every kind.":"都不选则提供全部类型。","AI prompt":"AI 提示词","e.g. Summarize the description in one sentence":"例如:用一句话概括描述","Fields the AI reads (none = all)":"AI 读取的字段(不选则读取全部)","AI reads {name}":"AI 读取 {name}","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":"修改字段","Field saved":"字段已保存","Field added":"字段已添加","Edit all fields":"批量编辑字段","Save field":"保存","Field name is required.":"请填写字段名。","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":"重新加载记录","Reload permissions":"重新加载权限","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.":"数据服务暂不可用","You do not have permission to make this change.":"你没有权限进行此修改。","You do not have permission to view this data.":"你没有权限查看此数据。","Sign in to view this data.":"请登录后查看此数据。","This data is missing or inaccessible.":"此数据不存在或无法访问。","This record has changed. Review the current version.":"记录已被修改,请核对当前版本。",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 oe(e="en"){return(t,n={})=>(e==="zh-CN"?Pc[t]??t:Object.hasOwn(ss,t)?ss[t]??t:t).replace(/\{(\w+)\}/g,(o,r)=>String(n[r]??o))}var ds={permission_denied:"You do not have permission to make this change.",version_conflict:"This record has changed. Review the current version.",unavailable:"The collection service is unavailable."};function Oo(e,t="en"){if(t!=="zh-CN"||!Object.hasOwn(ds,e.code))return e.message;let n=ds[e.code];return n?oe(t)(n):e.message}function po({code:e,message:t},n="en"){if(n!=="zh-CN")return t;let o=oe(n);switch(e){case"permission_denied":return o("You do not have permission to view this data.");case"unauthorized":return o("Sign in to view this data.");case"not_found":return o("This data is missing or inaccessible.");case"unavailable":return o("The collection service is unavailable.");default:return t}}import{useEffect as Li,useRef as gr,useState as tn}from"react";import{useId as mu,useMemo as fu,useState as Oa}from"react";var vn=(e)=>String(e).padStart(2,"0"),Sc=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function Rt(e){let t=e.formatting;return Sc(e)&&t&&"date"in t?t:void 0}function Lo(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function xa(e){let t=Rt(e);return!t?"auto":t.time==="none"?"date":"datetime"}function va(e,t,n,o){switch(o){case"YYYY/MM/DD":return`${e}/${vn(t)}/${vn(n)}`;case"MM/DD/YYYY":return`${vn(t)}/${vn(n)}/${e}`;case"DD/MM/YYYY":return`${vn(n)}/${vn(t)}/${e}`;case"YYYY年M月D日":return`${e}年${t}月${n}日`;default:return`${e}-${vn(t)}-${vn(n)}`}}function Gn(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 va(Number(o[1]),Number(o[2]),Number(o[3]),t.date);let s=new Date(n);if(!Number.isFinite(s.getTime()))return n;let a=Bn(s,t.timeZone??"UTC");return va(a.year,a.month,a.day,t.date)}let r=o?uo({year:Number(o[1]),month:Number(o[2]),day:Number(o[3])},t.timeZone):new Date(n);if(!Number.isFinite(r.getTime()))return n;let i=Bn(r,t.timeZone),l=va(i.year,i.month,i.day,t.date);if(t.time==="12h"){let s=i.hour%12||12;return`${l} ${s}:${vn(i.minute)} ${i.hour<12?"AM":"PM"}`}return`${l} ${vn(i.hour)}:${vn(i.minute)}`}function Bo(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 Or(e,t){let n=e?.findIndex((i)=>i.id===t)??-1,o=n>=0?e?.[n]?.color:void 0,r=Ln.findIndex((i)=>i===o);return r>=0?r:n}function vi(e,t,n,o,r=!1){let{row:i,column:l}=e;if(t==="ArrowUp")i--;if(t==="ArrowDown")i++;if(t==="ArrowLeft")l--;if(t==="ArrowRight")l++;if(t==="Home")l=0;if(t==="End")l=o-1;if(t==="Tab"){let s=Math.max(0,Math.min(n*o-1,i*o+l+(r?-1:1)));i=Math.floor(s/o),l=s%o}return{row:Math.max(0,Math.min(n-1,i)),column:Math.max(0,Math.min(o-1,l))}}function wa(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 at(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function cs(e,t,n,o){let r=wa(n,o),i=[];for(let l=r.firstRow;l<=r.lastRow;l++){let s=[];for(let a=r.firstColumn;a<=r.lastColumn;a++){let d=t[a],u=e[l]?.values[d?.id??""],f=d?.type==="json"&&u!=null?JSON.stringify(u):d?.type==="hyperlink"?Gl(u):at(u);s.push(/[\t\r\n"]/.test(f)?`"${f.replaceAll('"','""')}"`:f)}i.push(s.join("\t"))}return i.join(`
2
+ `)}function Rc(e,t="en"){let n=oe(t),o=[],r=[],i="",l=!1;for(let s=0;s<e.length;s++){let a=e[s];if(a==='"'&&(l||i===""))if(l&&e[s+1]==='"')i+='"',s++;else l=!l;else if(!l&&(a==="\t"||a===`
3
+ `||a==="\r")){if(r.push(i),i="",a!=="\t"){if(o.push(r),r=[],a==="\r"&&e[s+1]===`
4
+ `)s++}}else i+=a}if(l)throw Error(n("Unclosed quoted cell."));if(i||r.length||o.length===0)r.push(i),o.push(r);return o}function xn(e,t,n="en"){let o=oe(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 i=Number(e);if(!e.trim()||!Number.isFinite(i))throw Error(o("{name} needs a number.",{name:t.name}));return i}if(t.type==="hyperlink"){let i=Fo(e);if(!i)throw Error(o("{name} needs a link.",{name:t.name}));return i}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 i=Rt(t);if(i){let S=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!S)throw Error(o("{name} needs a date.",{name:t.name}));let[,k,O,L]=S,z=new Date(Date.UTC(Number(k),Number(O)-1,Number(L)));if(z.getUTCMonth()!==Number(O)-1||z.getUTCDate()!==Number(L))throw Error(o("{name} needs a valid calendar date.",{name:t.name}));if(i.time==="none"){if(/T.*(?:Z|[+-]\d{2}:\d{2})$/i.test(e)&&Number.isFinite(Date.parse(e)))return fi(new Date(e),i.timeZone);return`${k}-${O}-${L}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return uo({year:Number(k),month:Number(O),day:Number(L)},i.timeZone).toISOString()}let l=/^(\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(!l)throw Error(o("{name} needs a date.",{name:t.name}));let[,s,a,d,u,f,p,c,C]=l,x=Number(s),h=Number(a),g=Number(d),y=[31,x%4===0&&(x%100!==0||x%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(h<1||h>12||g<1||g>(y[h-1]??0)||Number(u??0)>23||Number(f??0)>59||Number(p??0)>59||Number(c??0)>23||Number(C??0)>59)throw Error(o("{name} needs a valid calendar date.",{name:t.name}));let E=new Date(e);if(!Number.isFinite(E.getTime()))throw Error(o("{name} needs a date.",{name:t.name}));return E.toISOString()}let r=(i)=>{let l=t.options?.find((s)=>s.id===i||s.name===i);if(!l)throw Error(o("{name} has no option '{option}'.",{name:t.name,option:i}));return l.id};if(t.type==="singleSelect")return r(e);if(t.type==="multipleSelect")return[...new Set(e.split(",").map((i)=>r(i.trim())))];return e}function us(e,t,n,o,r="en"){let i=oe(r);try{if(e.length>1048576)throw Error(i("Paste is too large."));let l=Rc(e,r);if(l.length>100||o.row+l.length>t.length)throw Error(i("Paste must fit within the loaded page and contain at most 100 rows."));return{ok:!0,items:l.map((a,d)=>{if(o.column+a.length>n.length)throw Error(i("Paste extends beyond the visible columns."));let u=t[o.row+d];if(!u)throw Error(i("Row is not loaded."));let f={};return a.forEach((p,c)=>{let C=n[o.column+c];if(C?.generation==="autoIncrement")throw Error(i("{name} is auto-generated and cannot be edited.",{name:C.name}));if(C)f[C.id]=xn(p,C,r)}),{op:"update",id:u.id,expectedVersion:u.version,values:f}})}}catch(l){return{ok:!1,message:l instanceof Error?l.message:i("Invalid paste.")}}}function xi(e,t){let n=at(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 r=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),i=(d)=>r.find((u)=>u.type===d)?.value??"",l=o.getUTCMilliseconds(),s=i("second"),a=s!=="00"||l?`:${s}${l?`.${String(l).padStart(3,"0")}`:""}`:"";return`${i("year")}-${i("month")}-${i("day")} ${i("hour")}:${i("minute")}${a}`}import{useEffect as Ic,useRef as Ac,useState as rr}from"react";import{jsx as wn,jsxs as Lr}from"react/jsx-runtime";function go(e){if(e==null)return"—";if(Array.isArray(e))return e.map(go).join(", ");return String(e)}function Vo(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((o)=>o.label||o.id).join(", "):void 0)??go(e.values[t.id])}function ps(e,t){return at(e.values[t.id])}function wi({field:e,value:t,labels:n=[],client:o,onChange:r,disabled:i=!1,locale:l,"aria-describedby":s,"aria-invalid":a}){let d=oe(l),u=Array.isArray(t)?t.filter((P)=>typeof P==="string"):[],f=Ac(new Set(u));f.current=new Set(u);let[p,c]=rr(""),[C,x]=rr(),[h,g]=rr([]),[w,y]=rr(0),[E,S]=rr({}),[k,O]=rr({rows:[],next:null,error:"",loading:!0}),L=e.link?.collectionId,z=e.link?.displayFieldId;Ic(()=>{let P=!0;if(O({rows:[],next:null,error:"",loading:!0}),!o||!L||!z){O({rows:[],next:null,error:d("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return o.query(L,{limit:50,search:p,...C?{cursor:C}:{}}).then((R)=>{if(!P)return;if(!R.ok){O({rows:[],next:null,error:R.error.message,loading:!1});return}S((M)=>({...Object.fromEntries(Object.entries(M).filter(([N])=>f.current.has(N))),...Object.fromEntries(R.data.items.map((N)=>{let I=String(N.values[z]??"");return[N.id,I.trim()?I.slice(0,256):N.id]}))})),O({rows:R.data.items,next:R.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(P)O({rows:[],next:null,error:d("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{P=!1}},[o,L,z,p,C,w]);let G=(P)=>E[P]??n.find((R)=>R.id===P)?.label??P;return Lr("fieldset",{disabled:i,"aria-label":d("{name} linked records",{name:e.name}),...s?{"aria-describedby":s}:{},...a?{"aria-invalid":!0}:{},className:"flex min-w-0 flex-col gap-2 rounded-md border p-2",children:[wn("div",{className:"flex flex-wrap gap-1",children:u.map((P)=>Lr("span",{className:"rounded border px-2 py-1 text-sm",children:[G(P)," ",wn("button",{type:"button","aria-label":d("Remove {name}",{name:G(P)}),onClick:()=>r(u.filter((R)=>R!==P)),children:"×"})]},P))}),wn("input",{"aria-label":d("Search {name} records",{name:e.name}),type:"search",placeholder:d("Search linked records"),value:p,onChange:(P)=>{c(P.target.value),x(void 0),g([])}}),k.loading&&wn("p",{role:"status",children:d("Loading linked records…")}),k.error&&Lr("div",{role:"alert",children:[k.error," ",wn("button",{type:"button",onClick:()=>y((P)=>P+1),children:d("Retry linked records")})]}),wn("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:k.rows.map((P)=>Lr("label",{className:"flex items-center gap-2 text-sm",children:[wn("input",{type:"checkbox","aria-label":d("Link {name}",{name:G(P.id)}),checked:u.includes(P.id),disabled:!u.includes(P.id)&&u.length>=100,onChange:(R)=>r(R.target.checked?[...u,P.id]:u.filter((M)=>M!==P.id))}),G(P.id)]},P.id))}),!k.loading&&!k.error&&!k.rows.length&&wn("p",{children:d("No matching records.")}),Lr("div",{className:"flex gap-2",children:[wn("button",{type:"button",disabled:!h.length||k.loading,onClick:()=>{x(h.at(-1)),g((P)=>P.slice(0,-1))},children:d("Previous linked records")}),wn("button",{type:"button",disabled:!k.next||k.loading,onClick:()=>{g((P)=>[...P,C]),x(k.next??void 0)},children:d("Next linked records")})]}),wn("small",{children:d("{count} selected · up to 100 per record across all link fields",{count:u.length})})]})}var Ec={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function ir(e,t,n){return t?oe(n)(Ec[t]):e==null?"—":String(e)}function gs(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 ms(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function ki(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function fs(e,t,n){let o=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...ki(e),filter:ms(e.filter,o)}}function Br(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 r=new Date(`${e}-01T00:00:00.000Z`),i=new Date(r);return i.setUTCMonth(i.getUTCMonth()+1),{start:r.toISOString(),end:i.toISOString(),days:Math.round((i.getTime()-r.getTime())/86400000),weekday:r.getUTCDay()}}function ys(e,t,n){let{start:o,end:r}=Br(n);return{...ki(e),filter:ms(e.filter,{fieldId:t,operator:"onOrAfter",value:o},{fieldId:t,operator:"before",value:r})}}function Pi(e,t){let n={id:"date",name:"Date",type:"date"},o=String(xn(t,n)),r=String(xn(String(e),n));return`${o.slice(0,10)}${r.slice(10)}`}function mo(e,t){return[...t.columnOrder,...e.map((o)=>o.id).filter((o)=>!t.columnOrder.includes(o))].filter((o)=>!t.hiddenColumns.includes(o)).flatMap((o)=>e.filter((r)=>r.id===o))}function jt(e,t){let n=t.find((o)=>o.type==="singleLineText"||o.type==="longText");return(n?at(e.values[n.id]):"")||e.id}function sn(e,t,n){if(t.type==="lookup")return go(e);if(t.type==="hyperlink")return Nr(e);if(t.type==="date"){let o=Rt(t);return o?Gn(e,o):xi(e)}if(t.type==="number"){let o=Lo(t);return o?Bo(e,o):at(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return ir(e,n);if(t.type==="singleSelect"||t.type==="multipleSelect")return(Array.isArray(e)?e:e==null?[]:[e]).map((r)=>t.options?.find((i)=>i.id===r)?.name??String(r)).join(", ");return at(e)}import{useEffect as ka,useMemo as Dc,useState as Uo}from"react";import{jsx as ar,jsxs as bs}from"react/jsx-runtime";function Si(e,t){if(!t?.length)return e;let n=!1,o={...e};for(let r of t){let i=r.label.trim();if(!i||o[r.id]===i)continue;o[r.id]=i,n=!0}return n?o:e}function _o(e){let t=Dc(()=>oe(e.locale),[e.locale]),[n,o]=Uo(""),[r,i]=Uo(),[l,s]=Uo(null),[a,d]=Uo([]),[u,f]=Uo(()=>Si({},e.labels)),[p,c]=Uo(""),[C,x]=Uo(!1),h=e.field.relation?.collectionId,g=e.field.relation?.labelFieldId,{getOptions:w,value:y}=e;ka(()=>{f((k)=>Si(k,e.labels))},[e.labels]),ka(()=>{let k=!1;if(!h||!w)return;return x(!0),c(""),w({collectionId:h,...g?{labelFieldId:g}:{},search:n,...r?{cursor:r}:{},limit:50}).then((O)=>{if(k)return;if(!O.ok){c(O.error.message),s(null);return}let L=O.data.items.slice(0,50);f((z)=>Si(z,L)),d((z)=>{let G=r?[...z,...L]:L;return[...new Map(G.map((P)=>[P.id,P])).values()]}),s(O.data.nextCursor)}).catch(()=>{if(!k)c(t("Relation options unavailable."))}).finally(()=>{if(!k)x(!1)}),()=>{k=!0}},[h,g,n,r,w,t]),ka(()=>{if(!y||!h||!w)return;if(e.labels?.some((O)=>O.id===y&&O.label.trim()))return;let k=!1;return w({collectionId:h,...g?{labelFieldId:g}:{},ids:[y],limit:50}).then((O)=>{if(k||!O.ok)return;let L=O.data.items.find((z)=>z.id===y);if(L)f((z)=>Si(z,[L]))}).catch(()=>{}),()=>{k=!0}},[y,h,g,w,e.labels]);let E=!h||!w,S=y?u[y]??a.find((k)=>k.id===y)?.label??y:"";return bs("div",{children:[ar("input",{"aria-label":t("Search {name}",{name:e.field.name}),value:n,disabled:e.disabled||E,onKeyDown:(k)=>{if(k.key==="Enter"&&!k.ctrlKey&&!k.metaKey)k.preventDefault()},onChange:(k)=>{o(k.currentTarget.value),i(void 0),d([]),s(null)}}),bs("select",{id:e.id,"aria-describedby":e["aria-describedby"],"aria-invalid":e["aria-invalid"],"aria-label":e.label??e.field.name,value:e.value,disabled:e.disabled||E||C,onChange:(k)=>{let O=k.currentTarget.value;if(!O||a.some((L)=>L.id===O))e.onChange(O)},children:[ar("option",{value:"",children:t("No relation")}),y&&!a.some((k)=>k.id===y)&&ar("option",{value:y,children:S}),a.map((k)=>ar("option",{value:k.id,children:k.label},k.id))]}),l&&ar("button",{type:"button",disabled:C||e.disabled,onClick:()=>i(l),children:t("More {name} options",{name:e.field.name})}),(p||E)&&ar("span",{role:"status",children:p||t("Relation option provider unavailable.")})]})}var hs=(e)=>e.type==="singleLineText"||e.type==="longText",Cs=(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"},vs=(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 Tc(e,t){let n=e?.fields??[],o=n.find((i)=>i.id===t),r=n.filter((i)=>hs(i)&&!Cs(i)).sort((i,l)=>vs(i.name)-vs(l.name));return[...o&&hs(o)&&!Cs(o)?[o]:[],...r].filter((i,l,s)=>s.findIndex((a)=>a.id===i.id)===l)}function Fc(e){if(!e?.length)return;let t=[...new Set(e.filter((n)=>n!==""))].slice(0,50);return t.length?t:void 0}function Ri(e,t){return async(n)=>{let o=Fc(n.ids),r=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(!r.ok)return r;let i=Tc((typeof t==="function"?t():t).find((l)=>l.id===n.collectionId),n.labelFieldId);return{ok:!0,data:{items:r.data.items.map((l)=>{let s=i.map((a)=>l.values[a.id]).find((a)=>a!==null&&a!==void 0&&String(a).trim()!=="");return{id:l.id,label:s===void 0?l.id:String(s)}}),nextCursor:r.data.nextCursor}}}}import{createContext as Nc,useContext as Mc,useEffect as Oc,useId as Lc,useLayoutEffect as Bc,useMemo as Vc,useRef as Uc,useState as lr}from"react";import{jsx as dn,jsxs as sr}from"react/jsx-runtime";var ws=Nc(void 0);function Pa(e){return dn(ws.Provider,{value:e.client,children:e.children})}var Ur=()=>Mc(ws),xs=(e)=>/^https?:/i.test(e);function Ii(e){let t=Ur();if(!nr(e.value))return null;let n=e.value,o=t?.href?.(n)??n.url;return dn("a",{href:o,title:n.url,"data-uibot-link":n.ref?.kind??(xs(o)?"external":"internal"),...xs(o)?{target:"_blank",rel:"noopener noreferrer"}:{},style:{color:"var(--uibot-link, currentColor)",textDecoration:"underline",textUnderlineOffset:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...e.style},onMouseDown:(r)=>r.stopPropagation(),onDoubleClick:(r)=>r.stopPropagation(),onClick:(r)=>{if(r.stopPropagation(),!(r.button!==0||r.metaKey||r.ctrlKey||r.shiftKey||r.altKey)&&t?.open?.(n))r.preventDefault()},children:Nr(n)})}var Vr=(e)=>e?JSON.stringify(e):"",_c=(e)=>e.trim().startsWith("{")?Fo(e):null;function _r(e){let t=Vc(()=>oe(e.locale),[e.locale]),n=Ur(),o=Lc(),r=_c(e.text),[i,l]=lr(()=>r?"":e.text),[s,a]=lr(!1),[d,u]=lr([]),[f,p]=lr(""),[c,C]=lr(-1),x=Uc(null),[h,g]=lr(null),y=e.field.hyperlink?.kinds?.join(",")??"";Oc(()=>{if(!n||!s||e.disabled)return;let P=new AbortController,R=setTimeout(()=>{p(t("Searching…")),n.search({search:i.trim(),...y?{kinds:y.split(",")}:{},limit:8},{signal:P.signal}).then((M)=>{if(P.signal.aborted)return;u(M.ok?M.data.slice(0,8):[]),p(M.ok?"":M.error.message)}).catch((M)=>{if(!P.signal.aborted)p(M instanceof Error?M.message:String(M))})},200);return()=>{clearTimeout(R),P.abort()}},[n,s,i,y,e.disabled,t]);let E=Fo(i),S=(P)=>n?.kinds?.find((R)=>R.id===P)?.label??P,k=[...E&&!E.ref?[{key:"typed",value:E,title:t("Use link {url}",{url:E.url})}]:[],...d.map((P)=>({key:`${P.kind}:${P.id}`,value:{url:P.url,text:P.title,ref:{kind:P.kind,id:P.id}},title:P.title,subtitle:[S(P.kind),P.subtitle].filter(Boolean).join(" · ")}))],O=Boolean(n&&!f&&!d.length&&i.trim()),L=s&&!e.disabled&&(k.length>0||Boolean(f)||O);Bc(()=>{if(!L)return;let P=()=>g(x.current?.getBoundingClientRect()??null);return P(),window.addEventListener("scroll",P,!0),window.addEventListener("resize",P),()=>{window.removeEventListener("scroll",P,!0),window.removeEventListener("resize",P)}},[L]);let z=(P)=>{l(""),C(-1),e.onChange(Vr(P.value))},G=(P)=>{l(P),C(-1),e.onChange(P||Vr(r))};return sr("div",{style:{display:"grid",gap:4,minWidth:0,height:"100%"},children:[dn("input",{ref:x,id:e.id,role:"combobox","aria-label":e.ariaLabel,"aria-expanded":L,"aria-controls":o,"aria-autocomplete":"list","aria-invalid":e.invalid,...e.describedBy?{"aria-describedby":e.describedBy}:{},...c>=0?{"aria-activedescendant":`${o}-${c}`}:{},disabled:e.disabled,placeholder:r?Nr(r):t("Search or paste a link"),value:i,style:e.inputStyle,className:e.inputClassName,onFocus:()=>a(!0),onBlur:()=>a(!1),onChange:(P)=>G(P.currentTarget.value),onKeyDown:(P)=>{if(e.onSave||e.onCancel)P.stopPropagation();if(P.key==="ArrowDown"||P.key==="ArrowUp"){if(!k.length)return;P.preventDefault();let R=P.key==="ArrowDown"?1:-1;C((M)=>R>0?(M+1)%k.length:M<=0?k.length-1:M-1)}else if(P.key==="Enter"){P.preventDefault();let R=k[c];if(R)z(R);else e.onSave?.()}else if(P.key==="Tab"&&e.onSave)P.preventDefault(),e.onSave();else if(P.key==="Escape")if(P.preventDefault(),i)G("");else e.onCancel?.()}}),r&&!i&&!e.onSave&&sr("div",{style:{display:"grid",gap:4,minWidth:0,fontSize:12},children:[sr("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[dn(Ii,{value:r,style:{flex:"0 1 auto"}}),dn("span",{style:{flex:"1 1 0",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:0.6},children:r.url}),dn("button",{type:"button","aria-label":t("Remove link"),title:t("Remove link"),disabled:e.disabled,onMouseDown:(P)=>P.preventDefault(),onClick:()=>e.onChange(""),style:{border:0,background:"none",color:"inherit",cursor:"pointer",opacity:0.6},children:"×"})]}),sr("label",{style:{display:"grid",gap:2},children:[dn("span",{style:{opacity:0.7},children:t("Display text")}),dn("input",{"aria-label":t("Display text"),placeholder:r.url,value:r.text??"",disabled:e.disabled,className:e.inputClassName,onChange:(P)=>{let R=P.currentTarget.value.slice(0,500),{text:M,...N}=r;e.onChange(Vr(R?{...N,text:R}:N))}})]})]}),L&&h&&sr("div",{id:o,role:"listbox","aria-label":t("Link suggestions"),style:{position:"fixed",top:h.bottom+4,left:h.left,width:Math.max(h.width,280),maxHeight:320,overflowY:"auto",zIndex:1000,padding:4,border:"1px solid var(--uibot-border, #d4d4d8)",borderRadius:8,background:"var(--uibot-surface, var(--background, #fff))",color:"var(--uibot-text, inherit)",boxShadow:"0 8px 24px rgb(0 0 0 / 0.12)"},onMouseDown:(P)=>P.preventDefault(),children:[k.map((P,R)=>sr("div",{id:`${o}-${R}`,role:"option","aria-selected":R===c,tabIndex:-1,onMouseEnter:()=>C(R),onClick:()=>z(P),onKeyDown:()=>{},style:{display:"grid",gap:2,padding:"6px 8px",borderRadius:6,cursor:"pointer",background:R===c?"var(--uibot-hover, rgb(0 0 0 / 0.06))":void 0},children:[dn("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:P.title}),P.subtitle&&dn("span",{style:{fontSize:12,opacity:0.65},children:P.subtitle})]},P.key)),f&&dn("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:f}),O&&dn("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:t("No matching resources")})]})]})}import{useEffect as Ps,useId as qc,useMemo as Hc,useRef as jc,useState as Ss}from"react";var zc=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function fo(e){return zc.test(e)}var Yn=(e)=>String(e).padStart(2,"0");function ks(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${Yn(t.getMonth()+1)}-${Yn(t.getDate())}T${Yn(t.getHours())}:${Yn(t.getMinutes())}:${Yn(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var Sa=(e,t)=>{let n=Bn(e,t);return`${n.year}-${Yn(n.month)}-${Yn(n.day)}T${Yn(n.hour)}:${Yn(n.minute)}`};function Ra(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!fo(e))return e.slice(0,10);return Sa(new Date(e),t.timeZone??"UTC").slice(0,10)}if(fo(e))return Sa(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function Ia(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||fo(t)))return e;let r=e.length>10?e.slice(11,16):t&&fo(t)?Sa(new Date(t),n.timeZone).slice(11,16):"00:00",[i,l,s]=e.slice(0,10).split("-").map(Number),[a,d]=r.split(":").map(Number),u=uo({year:i??0,month:l??1,day:s??1,hour:a??0,minute:d??0},n.timeZone);return Number.isFinite(u.getTime())?u.toISOString():e}import{jsx as yo,jsxs as Rs}from"react/jsx-runtime";function dr(e,t,n){if(e.type==="blob")return"";try{return xn(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==="hyperlink")return oe(n)("{name} needs a link.",{name:e.name});if(e.type==="json")return n==="zh-CN"?`${e.name}必须是有效 JSON。`:`${e.name} needs valid JSON.`;return n==="zh-CN"?"输入值无效":"Invalid value"}}function Aa({field:e,text:t,disabled:n,id:o,label:r,ariaLabel:i,onChange:l,onSave:s,onCancel:a,locale:d="en",submitted:u=!1,describedBy:f}){let p=Hc(()=>oe(d),[d]),c=qc(),C=jc(null),x=Boolean(s);Ps(()=>{if(x)C.current?.querySelector("input,textarea,select")?.focus()},[x]);let h=o??c,g=`${h}-error`,[w,y]=Ss(t),[E,S]=Ss(!1);Ps(()=>y(t),[t]);let k=dr(e,w,d),L=Boolean(e.required&&w===""&&k)&&!E&&!u?"":k,z=i??r??e.name,G=e.type==="date"&&fo(w),P=G&&!k?ks(w):w,R=[f,L?g:void 0].filter(Boolean).join(" "),M={id:h,"aria-label":z,"aria-invalid":Boolean(L),...R?{"aria-describedby":R}:{},disabled:n,onBlur:()=>S(!0),onKeyDown:(v)=>{if(s||a)v.stopPropagation();let K=e.type==="longText"||e.type==="json";if(v.key==="Tab"&&s)v.preventDefault(),s(v.shiftKey?"previous":"next");else if(v.key==="Enter"&&!v.shiftKey&&s&&(!K||v.ctrlKey||v.metaKey))v.preventDefault(),s();else if(v.key==="Escape"&&a)v.preventDefault(),a()},style:{width:"100%",...x?{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"},N=(v)=>{S(!0),y(v),l(v)},I=(v)=>{if(e.type==="date"&&G&&v){let K=new Date(v);N(Number.isFinite(K.getTime())?K.toISOString():v)}else N(v)},B;if(e.type==="hyperlink")B=yo(_r,{field:e,text:w,id:h,ariaLabel:z,invalid:Boolean(L),describedBy:R||void 0,disabled:n,locale:d,inputStyle:M.style,inputClassName:M.className,onChange:N,onSave:s,onCancel:a});else if(e.type==="checkbox")B=Rs("select",{...M,value:w,onChange:(v)=>N(v.currentTarget.value),children:[!e.required&&yo("option",{value:"",children:p("No value")}),yo("option",{value:"true",children:p("Yes")}),yo("option",{value:"false",children:p("No")})]});else if(e.type==="longText"||e.type==="json")B=yo("textarea",{...M,value:w,rows:e.type==="json"?4:3,onChange:(v)=>N(v.currentTarget.value)});else{let v=e.type==="date"&&!(k&&w)?G?"datetime-local":"date":"text",K=e.type==="blob";B=yo("input",{...M,type:v,inputMode:e.type==="number"?"decimal":void 0,step:G?"0.001":void 0,value:P,readOnly:K,onInput:e.type==="date"?(ce)=>I(ce.currentTarget.value):void 0,onChange:(ce)=>I(ce.currentTarget.value)})}return Rs("div",{ref:C,className:"grid min-w-0 gap-1",style:x?{height:"100%"}:void 0,children:[r&&yo("label",{className:"text-xs font-medium",htmlFor:h,children:r}),B,L&&yo("span",{id:g,role:"alert",className:"text-xs text-red-600",children:L})]})}import{useEffect as Kc,useRef as Wc}from"react";import{jsx as Is}from"react/jsx-runtime";var $c={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 ve({name:e,size:t=15,style:n}){return Is("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:Is("path",{d:$c[e]})})}import{jsx as bo,jsxs as As,Fragment as Gc}from"react/jsx-runtime";var cr={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function Y({ui:e,style:t,variant:n,size:o,children:r,disabled:i,onClick:l,title:s,ariaLabel:a,icon:d,iconOnly:u,badge:f}){let p=e?.Button,c=d?As("span",{style:{position:"relative",display:"inline-flex"},children:[bo(ve,{name:d}),f?bo("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,C=u?c:As(Gc,{children:[c,r]}),x=a,h=s??(u?x:void 0),g=u?"icon":o;if(p)return bo(p,{...n?{variant:n}:{},...g?{size:g}:{},disabled:i,onClick:l,title:h,"aria-label":x,children:C});return bo("button",{type:"button",style:{...d?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?cr:{},...u?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:i,onClick:l,title:h,"aria-label":x,children:C})}function Xe({ui:e,value:t,options:n,onChange:o,disabled:r,label:i,style:l,"aria-describedby":s,"aria-invalid":a}){let d=e?.Select,u={...s?{"aria-describedby":s}:{},...a?{"aria-invalid":!0}:{}};if(d)return bo(d,{value:t,options:n,onChange:o,disabled:r,"aria-label":i,...u});return bo("select",{"aria-label":i,...u,style:l,disabled:r,value:t,onChange:(f)=>o(f.target.value),children:n.map((f)=>bo("option",{value:f.value,disabled:f.disabled,children:f.label},f.value))})}function Ai({label:e,busy:t,onCancel:n,children:o,alert:r=!1}){let i=Wc(null);return Kc(()=>{let l=i.current,s=document.activeElement;if(l?.showModal)l.showModal();else l?.setAttribute("open","");return()=>{if(l?.close?.(),s instanceof HTMLElement&&s.isConnected)s.focus({preventScroll:!0})}},[]),bo("dialog",{ref:i,role:r?"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:(l)=>{if(l.key!=="Tab")return;let s=l.currentTarget,a=[...s.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter((f)=>!f.hidden),d=a[0],u=a.at(-1);if(!d||(l.shiftKey?document.activeElement===d:document.activeElement===u)||!s.contains(document.activeElement)){if(l.preventDefault(),(l.shiftKey?u:d)?.focus(),!d)s.focus()}},tabIndex:-1,onCancel:(l)=>{if(l.preventDefault(),!t)n()},children:o})}import{useEffect as Es,useRef as zr,useState as Vn}from"react";import{jsx as Se,jsxs as Ue,Fragment as Zc}from"react/jsx-runtime";function Yc(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 Jc=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function Ea({descriptor:e,fieldIds:t,query:n,client:o,readOnly:r=!1,reloadKey:i=0,onImported:l,onRefreshSchema:s}){let[a,d]=Vn(null),[u,f]=Vn(null),[p,c]=Vn(null),[C,x]=Vn([]),[h,g]=Vn(""),[w,y]=Vn(!1),[E,S]=Vn(!1),[k,O]=Vn(!0),[L,z]=Vn(null),[G,P]=Vn(!1),R=zr(!1),M=zr(!1),N=zr(!1),I=zr(null),B=zr({client:o,onImported:l,descriptor:e});B.current={client:o,onImported:l,descriptor:e},Es(()=>(R.current=!0,()=>{R.current=!1,M.current=!1}),[]),Es(()=>{let W=!0;if(!r)o.imports(e.id).then((q)=>{if(!W||!R.current||!q.ok)return;if(x((xe)=>q.data.map((ke)=>{let ye=xe.find((re)=>re.id===ke.id);return ye&&ye.version>ke.version?ye:ke})),!N.current)c((xe)=>{let ke=q.data.find((ye)=>ye.id===xe?.id);return xe&&ke&&ke.version>xe.version?ke:xe})});return()=>{W=!1}},[o,e.id,r,i]);let v=(W)=>{c(W),x((q)=>[W,...q.filter((xe)=>xe.id!==W.id)].slice(0,50)),z(null)};async function K(W){if(N.current||r)return;N.current=!0,M.current=!0,y(!0),S(!0),g("");let q=W;try{while(R.current&&M.current&&q.status==="ready"){let xe=await B.current.client.advanceImport(e.id,q.id,q.version);if(!R.current)break;if(!xe.ok){g(xe.error.message);break}let ke=xe.data;if(v(ke),ke.importedRows>q.importedRows)B.current.onImported();if(ke.version===q.version&&ke.status==="ready"){g("Import paused. Refresh the saved progress before retrying.");break}q=ke}}finally{if(N.current=!1,M.current=!1,R.current)y(!1),S(!1)}}async function ce(){if(!a||N.current)return;N.current=!0,y(!0),g("");let W=await o.previewImport(e.id,{...a,expectedSchemaVersion:e.schemaVersion});if(N.current=!1,!R.current)return;if(y(!1),W.ok)f(W.data),d({...a,expectedSchemaVersion:W.data.schemaVersion,mapping:W.data.mapping});else g(W.error.message)}async function fe(){if(!a||!u||u.missingRequiredFieldIds.length||!u.totalRows||N.current||r)return;N.current=!0,y(!0),g(""),I.current??=crypto.randomUUID();let W=await o.createImport(e.id,{...a,idempotencyKey:I.current});if(N.current=!1,!R.current)return;if(y(!1),W.ok)v(W.data),d(null),f(null),I.current=null,K(W.data);else g(W.error.message)}async function _(){if(!p||N.current||r)return;if(p.status==="ready"){K(p);return}N.current=!0,y(!0),g("");let W=s?await s():B.current.descriptor;if(!W){N.current=!1,y(!1),g("Refresh the collection schema and try again.");return}let q=await o.resumeImport(e.id,p.id,p.version,W.schemaVersion);if(N.current=!1,!R.current)return;if(y(!1),q.ok)v(q.data),K(q.data);else g(q.error.message)}async function ie(W){if(!p)return;let q=await o.importErrors(e.id,p.id,{limit:100,...W===void 0?{}:{cursor:W},expectedVersion:p.version});if(!R.current)return;if(q.ok)z(q.data);else g(q.error.message)}async function ue(W=!1){if(w||N.current)return;N.current=!0,y(!0),g("");let q=W&&p?await o.exportImportErrors(e.id,p.id):await o.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:k});if(N.current=!1,!R.current)return;if(y(!1),q.ok)Yc(q.data),g(`${q.data.rowCount} rows downloaded${q.data.protectedCells?`; ${q.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else g(q.error.message)}return Ue("details",{className:"min-w-0 rounded-lg border p-4",children:[Se("summary",{className:"cursor-pointer text-sm font-medium",children:"CSV import and export"}),Ue("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[Ue("div",{className:"flex flex-wrap items-center gap-3",children:[Se("button",{type:"button",disabled:w||!t.length,onClick:()=>void ue(),children:"Export CSV"}),Ue("label",{className:"flex items-center gap-2 text-sm",children:[Se("input",{type:"checkbox",checked:k,onChange:(W)=>O(W.target.checked)}),"Spreadsheet view"]})]}),Se("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."}),!r&&Ue(Zc,{children:[Ue("label",{className:"flex min-w-0 flex-col gap-2 text-sm",children:["CSV file",Se("input",{"aria-label":"CSV file",className:"max-w-full",type:"file",accept:".csv,text/csv",disabled:w,onChange:async(W)=>{let q=W.target.files?.[0];if(!q)return;if(g(""),f(null),d(null),I.current=null,q.size>20971520){g("Choose a UTF-8 CSV file no larger than 20 MiB.");return}y(!0),N.current=!0;try{let xe=new TextDecoder("utf-8",{fatal:!0}).decode(await q.arrayBuffer());if(R.current)d({fileName:q.name,csv:xe,expectedSchemaVersion:e.schemaVersion})}catch{if(R.current)g("The file must be valid UTF-8 text.")}finally{if(N.current=!1,R.current)y(!1)}}})]}),a&&Ue("div",{className:"flex flex-wrap gap-3",children:[Se("span",{className:"break-all text-sm",children:a.fileName}),Se("button",{type:"button",disabled:w,onClick:()=>void ce(),children:"Preview CSV"})]}),Se("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."}),u&&a&&Ue("div",{className:"flex min-w-0 flex-col gap-3",children:[Ue("p",{className:"text-sm",children:[u.totalRows," rows · ",u.validRows," valid · ",u.invalidRows," ","invalid · ",u.ignoredColumns.length," skipped columns"]}),u.headers.map((W,q)=>Ue("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[Ue("span",{className:"max-w-64 break-all",children:["Column ",q+1,": ",W||"(empty)"]}),Ue("select",{"aria-label":`Column ${q+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:a.mapping?.[q]??"",disabled:w,onChange:(xe)=>{let ke=[...a.mapping??u.mapping];ke[q]=xe.target.value||null,d({...a,mapping:ke}),f(null),I.current=null},children:[Se("option",{value:"",children:"Skip column"}),e.fields.filter((xe)=>!it(xe)).map((xe)=>Ue("option",{value:xe.id,children:[xe.name," (",xe.id,")",xe.required?" · required":""]},xe.id))]})]},`${q}:${W}`)),u.missingRequiredFieldIds.length>0&&Ue("p",{role:"alert",children:["Map required fields: ",u.missingRequiredFieldIds.join(", ")]}),Se("div",{className:"max-w-full overflow-x-auto",children:Ue("table",{className:"w-full text-xs",children:[Ue("caption",{children:["First ",u.sample.length," normalized rows; row numbers include the header."]}),Se("thead",{children:Ue("tr",{children:[Se("th",{children:"Row"}),Se("th",{children:"Normalized values"}),Se("th",{children:"Error"})]})}),Se("tbody",{children:u.sample.map((W)=>Ue("tr",{children:[Se("td",{children:W.rowNumber}),Se("td",{className:"max-w-96 break-all",children:Jc(W.values)}),Se("td",{children:W.error?.code??""})]},W.rowNumber))})]})}),Se("button",{type:"button",className:"self-start",disabled:w||!u.totalRows||u.missingRequiredFieldIds.length>0,onClick:()=>void fe(),children:"Confirm import"})]}),Ue("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",Ue("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:p?.id??"",disabled:w,onChange:async(W)=>{if(!W.target.value){c(null);return}let q=await o.importJob(e.id,W.target.value);if(R.current)if(q.ok)v(q.data),P(!1);else g(q.error.message)},children:[Se("option",{value:"",children:"Choose saved progress…"}),C.map((W)=>Ue("option",{value:W.id,children:[W.fileName," · ",W.processedRows,"/",W.totalRows," · ",W.status]},W.id))]})]}),Se("button",{type:"button",className:"self-start",disabled:w,onClick:async()=>{let W=await o.imports(e.id);if(R.current)if(W.ok)x(W.data);else g(W.error.message)},children:"Refresh saved imports"}),p&&Ue("div",{className:"flex flex-col gap-3",children:[Ue("p",{role:"status",children:[E?"Importing":p.status==="ready"?"Paused":p.status==="schemaChanged"?"Schema changed — confirm before continuing":p.status==="completed"?"Completed":"Cancelled"," ","· ",p.processedRows," of ",p.totalRows," processed · ",p.importedRows," imported ·"," ",p.failedRows," failed"]}),Se("progress",{"aria-label":"Import progress",max:p.totalRows,value:p.processedRows,className:"max-w-full"}),Se("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."}),Ue("div",{className:"flex flex-wrap gap-3",children:[E&&Se("button",{type:"button",onClick:()=>{M.current=!1,S(!1)},children:"Pause import"}),!E&&(p.status==="ready"||p.status==="schemaChanged")&&Se("button",{type:"button",disabled:w,onClick:()=>void _(),children:p.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(p.status==="ready"||p.status==="schemaChanged")&&Se("button",{type:"button",disabled:w,onClick:()=>P(!0),children:"Cancel import"}),Se("button",{type:"button",disabled:w||!p.failedRows,onClick:()=>void ie(),children:"Show import errors"}),Se("button",{type:"button",disabled:w||!p.failedRows,onClick:()=>void ue(!0),children:"Download all import errors"})]}),G&&Ue("div",{children:[Ue("p",{children:["Stop remaining rows? The ",p.importedRows," imported records will remain."]}),Se("button",{type:"button",disabled:w,onClick:async()=>{N.current=!0,y(!0);let W=await o.cancelImport(e.id,p.id);if(N.current=!1,!R.current)return;if(y(!1),W.ok)v(W.data),P(!1);else g(W.error.message)},children:"Confirm cancellation"}),Se("button",{type:"button",onClick:()=>P(!1),children:"Keep import"})]}),L&&Ue("div",{className:"max-w-full overflow-x-auto",children:[Ue("table",{className:"w-full text-xs",children:[Ue("caption",{children:[L.total," failed rows"]}),Se("thead",{children:Ue("tr",{children:[Se("th",{children:"Row"}),Se("th",{children:"Field"}),Se("th",{children:"Error"})]})}),Se("tbody",{children:L.items.map((W)=>Ue("tr",{children:[Se("td",{children:W.rowNumber}),Se("td",{children:W.fieldId??""}),Se("td",{children:W.code})]},W.rowNumber))})]}),L.nextCursor!==null&&Se("button",{type:"button",onClick:()=>void ie(L.nextCursor??void 0),children:"Next errors"})]})]})]}),h&&Se("p",{role:"alert",className:"break-words text-sm",children:h})]})]})}import{useEffect as Ds,useRef as zo,useState as qo}from"react";import{jsx as et,jsxs as $t,Fragment as Xc}from"react/jsx-runtime";var Ei=[{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 Qc({descriptor:e,client:t,onConverted:n}){let o=e.fields.filter((v)=>Ei.some((K)=>K.type===v.type)),[r,i]=qo(o[0]?.id??""),l=o.find((v)=>v.id===r)??o[0],[s,a]=qo(l?.type??"singleLineText"),[d,u]=qo(l?.required??!1),[f,p]=qo(l?.options?.map((v)=>`${v.id}=${v.name}`).join(`
5
+ `)??""),[c,C]=qo(null),[x,h]=qo(""),[g,w]=qo(!1),y=zo(null),E=zo(null),S=zo(0),k=zo(e);k.current=e;let O=y.current?.field??l,L=g||y.current!==null,z=`${e.id}:${e.schemaVersion}:${JSON.stringify(e.fields)}`,G=zo(e.fields);G.current=e.fields;let P=zo(z);P.current=z;let R=zo(!0);Ds(()=>(R.current=!0,()=>{R.current=!1,S.current++}),[]),Ds(()=>{if(P.current!==z)return;if(y.current&&E.current===e.id)return;S.current++;let v=G.current.find((K)=>K.id===r&&Ei.some((ce)=>ce.type===K.type))??G.current.find((K)=>Ei.some((ce)=>ce.type===K.type));if(v)i(v.id),a(v.type),u(v.required??!1),p(v.options?.map((K)=>`${K.id}=${K.name}`).join(`
6
+ `)??"");C(null),y.current=null,E.current=null,h(""),w(!1)},[z,r,e.id]);let M=()=>{C(null),y.current=null,E.current=null,S.current++,h("")},N=(v)=>{i(v.id),a(v.type),u(v.required??!1),p(v.options?.map((K)=>`${K.id}=${K.name}`).join(`
7
+ `)??""),M()};if(!O)return null;let I=()=>{let v={id:O.id,name:O.name,type:s,required:d};if(s==="singleSelect"||s==="multipleSelect")v.options=f.split(`
8
+ `).filter((K)=>K.trim()).map((K)=>{let ce=K.indexOf("=");if(ce<1)throw Error("Each option must use stable_id=Display name.");return{id:K.slice(0,ce).trim(),name:K.slice(ce+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:v}},B=()=>R.current&&P.current===z;return $t("details",{className:"rounded-lg border p-4",children:[et("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),$t("div",{className:"mt-4 flex flex-col gap-3",children:[et("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."}),$t("label",{children:["Field"," ",$t("select",{"aria-label":"Conversion field",value:O.id,disabled:L,onChange:(v)=>{let K=o.find((ce)=>ce.id===v.target.value);if(K)N(K)},children:[y.current&&!o.some((v)=>v.id===O.id)&&et("option",{value:O.id,children:O.name}),o.map((v)=>et("option",{value:v.id,children:v.name},v.id))]})]}),$t("label",{children:["Target type"," ",et("select",{"aria-label":"Conversion target type",value:s,disabled:L,onChange:(v)=>{a(v.target.value),M()},children:Ei.map((v)=>et("option",{value:v.type,children:v.label},v.type))})]}),$t("label",{children:[et("input",{type:"checkbox",checked:d,disabled:L,onChange:(v)=>{u(v.target.checked),M()}})," ","Required after conversion"]}),(s==="singleSelect"||s==="multipleSelect")&&$t("label",{children:["Stable option IDs and display names",et("textarea",{"aria-label":"Conversion options",className:"block w-full rounded border p-2",disabled:L,value:f,onChange:(v)=>{p(v.target.value),M()},placeholder:`open=Open
9
+ done=Done`})]}),x&&et("p",{role:"alert",className:"text-sm text-destructive",children:x}),et("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:L,onClick:async()=>{let v;try{v=I()}catch(K){h(K instanceof Error?K.message:"Invalid conversion options.");return}w(!0),h(""),C(null),y.current=null;try{let K=await t.previewConversion(e.id,v);if(!B())return;if(K.ok)C(K.data);else h(K.error.message)}catch{if(B())h("Preview unavailable. Your draft is kept.")}finally{if(B())w(!1)}},children:g?"Working…":"Preview conversion"}),c&&$t(Xc,{children:[$t("p",{role:"status",children:[c.validRows," valid · ",c.invalidRows," invalid"]}),$t("p",{className:"text-xs",children:["Preview covers ",c.totalRows," records. Samples and errors show at most 20 records."]}),et("div",{className:"overflow-x-auto",children:$t("table",{className:"w-full text-sm",children:[et("thead",{children:$t("tr",{children:[et("th",{children:"Record"}),et("th",{children:"Before"}),et("th",{children:"After"}),et("th",{children:"Error"})]})}),et("tbody",{children:c.sample.map((v)=>$t("tr",{children:[et("td",{className:"max-w-32 break-all",children:v.id}),et("td",{className:"max-w-48 break-words",children:JSON.stringify(v.before)}),et("td",{className:"max-w-48 break-words",children:JSON.stringify(v.after)}),et("td",{children:v.error})]},v.id))})]})}),c.errors.length>0&&et("ul",{children:c.errors.map((v)=>$t("li",{children:[et("span",{className:"break-all",children:v.id}),": ",et("span",{children:v.code})]},v.id))}),et("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:g||c.invalidRows>0,onClick:async()=>{if(!y.current)E.current=e.id,S.current++;y.current??={expectedSchemaVersion:c.schemaVersion,field:c.field,previewToken:c.previewToken,idempotencyKey:crypto.randomUUID()};let v=y.current,K=S.current,ce=()=>R.current&&k.current.id===e.id&&K===S.current;w(!0),h("");try{let fe=await t.convertField(e.id,v);if(!ce())return;if(fe.ok){if(C(null),y.current=null,E.current=null,fe.data.descriptor.schemaVersion>=k.current.schemaVersion)n(fe.data.descriptor)}else if(h(fe.error.message),fe.error.status===409)C(null),y.current=null,E.current=null}catch{if(ce())h("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(ce())w(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as eu,useRef as Da,useState as Ts}from"react";import{jsx as Fs,jsxs as nu}from"react/jsx-runtime";function tu({collectionIds:e,client:t,onChanges:n,pollIntervalMs:o=2000}){let r=JSON.stringify([...new Set(e)].sort()),i=Da(r);i.current=r;let l=Da(n);l.current=n;let s=Da(()=>{}),[a,d]=Ts("connecting"),[u,f]=Ts(!1);return eu(()=>{let p=JSON.parse(r),c=new Map,C=!1,x=!1,h=0,g,w=()=>!C&&i.current===r,y=Math.max(50,Math.min(60000,o)),E=async()=>{if(!w()||x)return;x=!0,f(!0);let O=!1;try{let L=h>0;for(let z of p){let G=c.get(z),P=await t.changes(z,{...G!==void 0?{cursor:G}:{},limit:100});if(!w())return;if(!P.ok)throw d(P.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let R=G===void 0;if(R||L||P.data.items.length>0)await l.current(z,P.data,R);if(!w())return;c.set(z,P.data.cursor),O||=P.data.hasMore}h=0,d("live")}catch{if(h++,w())d((L)=>L==="expired"?"expired":"offline")}finally{if(x=!1,w())f(!1),g=setTimeout(()=>{E()},O&&h===0?0:Math.min(30000,y*2**Math.min(h,8)))}},S=()=>{if(g!==void 0)clearTimeout(g);E()};s.current=S,d("connecting"),E();let k=()=>{if(document.visibilityState==="visible")S()};return window.addEventListener("online",S),document.addEventListener("visibilitychange",k),()=>{if(C=!0,g!==void 0)clearTimeout(g);window.removeEventListener("online",S),document.removeEventListener("visibilitychange",k)}},[r,t,o]),nu("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[Fs("p",{role:"status",children:a==="live"?"Live updates":a==="connecting"?"Connecting live updates…":a==="expired"?"Session expired. Renew your session; drafts are kept.":"Connection interrupted. Drafts are kept."}),(a==="offline"||a==="expired")&&Fs("button",{type:"button",className:"rounded border px-2 py-1",disabled:u,onClick:()=>s.current(),children:"Reconnect now"})]})}import{useEffect as Di,useRef as ho,useState as Qt}from"react";import{jsx as Ee,jsxs as ze,Fragment as Na}from"react/jsx-runtime";var Fa={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function qr(e){try{return await e()}catch{return{ok:!1,error:Fa}}}function Ta({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return ze("div",{className:"min-w-0",children:[Ee("strong",{children:t}),Ee("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&&ze(Na,{children:[Ee("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),Ee("button",{type:"button",onClick:()=>{let o=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),r=document.createElement("a");r.href=o,r.download=`record-${e?.id}-${e?.version}.json`,r.click(),setTimeout(()=>URL.revokeObjectURL(o),1000)},children:"Download snapshot"})]})]})}function ou({descriptor:e,recordId:t,client:n,readOnly:o=!1,onCommitted:r,registerRefresh:i}){let[l,s]=Qt(null),[a,d]=Qt(null),[u,f]=Qt(null),[p,c]=Qt(),[C,x]=Qt(),[h,g]=Qt([]),[w,y]=Qt([]),[E,S]=Qt(""),[k,O]=Qt(null),[L,z]=Qt(null),[G,P]=Qt(null),[R,M]=Qt(!1),[N,I]=Qt(""),B=ho(null),v=ho(null),K=ho(n);K.current=n;let ce=ho(!1),fe=ho(0),_=`${e.id}:${t}`,ie=ho(_);ie.current=_;let ue=ho({historyBefore:p,commentBefore:C});ue.current={historyBefore:p,commentBefore:C};let W=ho(async()=>{}),q=(D=_)=>ce.current&&ie.current===D&&K.current===n,xe=async()=>{let D=_,te=++fe.current,T=ue.current,[Te,ot]=await Promise.all([qr(()=>n.history(e.id,t,{...T.historyBefore===void 0?{}:{before:T.historyBefore},limit:20})),qr(()=>n.comments(e.id,t,{...T.commentBefore===void 0?{}:{before:T.commentBefore},limit:50}))]);if(!q(D)||te!==fe.current)throw Error("Refresh superseded");if(!Te.ok||!ot.ok)throw I(!Te.ok?Te.error.message:!ot.ok?ot.error.message:Fa.message),Error("Activity refresh failed");d(Te.data),f(ot.data),s(D)};W.current=xe,Di(()=>(ce.current=!0,()=>{ce.current=!1,fe.current++}),[]),Di(()=>(i?.(()=>W.current()),()=>i?.(null)),[i]),Di(()=>{if(ie.current!==_)return;d(null),f(null),s(null),c(void 0),x(void 0),g([]),y([]),ue.current={historyBefore:void 0,commentBefore:void 0},S(""),O(null),z(null),P(null),B.current=null,v.current=null,M(!1),I("")},[_]),Di(()=>{if(ie.current!==_||K.current!==n||ue.current.historyBefore!==p||ue.current.commentBefore!==C)return;W.current().catch(()=>{})},[_,n,p,C]);let ke=(D)=>{let te=B.current;if(te?.signature===D)return te.key;let T={signature:D,key:crypto.randomUUID()};return B.current=T,T.key},ye=async(D)=>{if(R||o||!u||l!==_)return;let te=D==="delete"?L:k;if(D!=="create"&&(!te||te.authorId!==u.actorId))return;let T=D==="create"?E:k?.draft??"";if(D!=="delete"&&(!T.trim()||T.length>4000||T.includes("\x00"))){I("Comments require 1–4,000 characters.");return}let Te=ke(JSON.stringify([D,te?.id,te?.version,T]));M(!0),I("");let ot=await qr(async()=>{if(D==="create")return n.createComment(e.id,t,{text:T,idempotencyKey:Te});if(!te)return{ok:!1,error:Fa};if(D==="edit")return n.editComment(e.id,t,te.id,{text:T,expectedVersion:te.version,idempotencyKey:Te});return n.deleteComment(e.id,t,te.id,{expectedVersion:te.version,idempotencyKey:Te})});if(!q())return;if(M(!1),!ot.ok){I(ot.error.message);return}if(B.current=null,D==="create")S("");else if(D==="edit")O(null);else z(null);if(D==="create"&&C!==void 0)x(void 0),y([]);else await W.current().catch(()=>{})},re=async(D)=>{if(R||o||!a||l!==_)return;M(!0),I(""),v.current=null;let te={targetVersion:D,expectedCurrentVersion:a.currentVersion,expectedSchemaVersion:e.schemaVersion},T=await qr(()=>n.previewUndo(e.id,t,te));if(!q())return;if(M(!1),T.ok)P(T.data);else P(null),I(T.error.message)},Ce=async()=>{if(R||o||l!==_||!G&&!v.current)return;let D=v.current;if(!D){if(!G)return;D={targetVersion:G.targetVersion,expectedCurrentVersion:G.currentVersion,expectedSchemaVersion:G.schemaVersion,idempotencyKey:crypto.randomUUID()},v.current=D}let te=D;M(!0),I("");let T=await qr(()=>n.undo(e.id,t,te));if(!q())return;if(M(!1),!T.ok){if(T.error.code==="version_conflict"||T.error.code==="reference_conflict"||T.error.code==="validation")v.current=null,P(null);I(T.error.message),await W.current().catch(()=>{});return}v.current=null,P(null),r(T.data),c(void 0),g([]),await W.current().catch(()=>{})},he=u?.items.find((D)=>D.id===k?.id),Ye=k&&he&&he.version!==k.version,j=G&&(G.currentVersion!==a?.currentVersion||G.schemaVersion!==e.schemaVersion);return ze("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[ze("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[ze("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),Ee("button",{type:"button",disabled:R,onClick:()=>{I(""),W.current().catch(()=>{})},children:"Refresh activity"})]}),N&&Ee("p",{role:"alert",className:"text-sm text-destructive",children:N}),!a||!u||l!==_?Ee("p",{role:"status",children:"Loading record activity…"}):ze(Na,{children:[ze("p",{role:"status",children:["Current version ",a.currentVersion,a.currentDeleted?" · Deleted record":""]}),Ee("h3",{className:"font-medium",children:"Comments"}),u.items.length===0&&Ee("p",{className:"text-sm",children:"No comments yet."}),Ee("ol",{className:"flex flex-col gap-3",children:u.items.map((D)=>ze("li",{className:"min-w-0 rounded border p-3",children:[ze("p",{className:"break-all text-xs",children:[D.authorId," · ",D.updatedAt," · version ",D.version]}),Ee("p",{className:"whitespace-pre-wrap break-words text-sm",children:D.text??"Comment deleted"}),!o&&D.text!==null&&D.authorId===u.actorId&&ze("div",{className:"flex gap-3",children:[Ee("button",{type:"button",disabled:R,onClick:()=>{O({...D,draft:D.text??""}),z(null),B.current=null},children:"Edit comment"}),Ee("button",{type:"button",disabled:R,onClick:()=>{z(D),O(null),B.current=null},children:"Delete comment"})]})]},D.id))}),ze("div",{className:"flex gap-3",children:[Ee("button",{type:"button",disabled:R||!w.length,onClick:()=>{x(w.at(-1)),y((D)=>D.slice(0,-1))},children:"Newer comments"}),Ee("button",{type:"button",disabled:R||u.nextCursor===null,onClick:()=>{y((D)=>[...D,C]),x(u.nextCursor??void 0)},children:"Older comments"})]}),!o&&ze(Na,{children:[k&&ze("div",{className:"flex flex-col gap-2",children:[ze("label",{children:["Edit comment text",Ee("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:R,maxLength:4000,value:k.draft,onChange:(D)=>{O({...k,draft:D.target.value}),B.current=null}})]}),Ye&&ze("div",{role:"status",children:[Ee("p",{children:"This comment changed. Your draft and original version are kept."}),ze("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",he.text??"Comment deleted"]}),he.text!==null&&he.authorId===u.actorId&&Ee("button",{type:"button",disabled:R,onClick:()=>{O({...he,draft:k.draft}),B.current=null},children:"Use current comment version"})]}),ze("div",{className:"flex gap-3",children:[Ee("button",{type:"button",disabled:R||k.authorId!==u.actorId,onClick:()=>void ye("edit"),children:"Save comment"}),Ee("button",{type:"button",disabled:R,onClick:()=>{O(null),B.current=null},children:"Cancel comment edit"})]})]}),L&&ze("div",{children:[Ee("p",{children:"Delete this comment? A deletion marker will remain."}),Ee("p",{className:"whitespace-pre-wrap break-words",children:L.text}),Ee("button",{type:"button",disabled:R||L.authorId!==u.actorId,onClick:()=>void ye("delete"),children:"Confirm delete comment"}),Ee("button",{type:"button",disabled:R,onClick:()=>z(null),children:"Cancel delete comment"})]}),ze("label",{children:["New comment",Ee("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:R,maxLength:4000,value:E,onChange:(D)=>{S(D.target.value),B.current=null}})]}),Ee("button",{type:"button",className:"self-start",disabled:R||!E.trim(),onClick:()=>void ye("create"),children:"Add comment"})]}),Ee("h3",{className:"font-medium",children:"Record history"}),Ee("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."}),Ee("ol",{className:"flex flex-col gap-3",children:a.items.map((D)=>ze("li",{className:"min-w-0 rounded border p-3",children:[ze("p",{className:"break-all text-xs",children:["Version ",D.version," · ",D.operation," · schema ",D.schemaVersion," · ",D.actorId," ·"," ",D.createdAt]}),ze("details",{children:[ze("summary",{children:["Stored values at version ",D.version]}),Ee(Ta,{record:D.snapshot,label:`Version ${D.version}`})]}),!o&&D.version<a.currentVersion&&ze("button",{type:"button",disabled:R,onClick:()=>void re(D.version),children:["Preview restore version ",D.version]})]},D.id))}),ze("div",{className:"flex gap-3",children:[Ee("button",{type:"button",disabled:R||!h.length,onClick:()=>{c(h.at(-1)),g((D)=>D.slice(0,-1))},children:"Newer history"}),Ee("button",{type:"button",disabled:R||a.nextCursor===null,onClick:()=>{g((D)=>[...D,p]),c(a.nextCursor??void 0)},children:"Older history"})]}),!o&&G&&ze("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[ze("h3",{children:["Restore version ",G.targetVersion," as a new version"]}),ze("p",{children:["Current version ",G.currentVersion," · schema ",G.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),ze("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[Ee(Ta,{record:G.before,label:"Current stored values"}),Ee(Ta,{record:G.target,label:"Values to restore"})]}),j&&!v.current&&Ee("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),ze("div",{className:"flex gap-3",children:[Ee("button",{type:"button",disabled:R||!!j&&!v.current,onClick:()=>void Ce(),children:v.current?"Retry undo":"Confirm restore"}),Ee("button",{type:"button",disabled:R,onClick:()=>{P(null),v.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as Ti,useRef as Co,useState as Jn}from"react";import{jsx as It,jsxs as Xt,Fragment as Ns}from"react/jsx-runtime";async function Fi(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 ru(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let o of t)n+=String.fromCharCode(o);return btoa(n)}function iu({collectionId:e,recordId:t,client:n,readOnly:o=!1,registerRefresh:r}){let i=`${e}:${t}`,l=Co({identity:i,client:n});l.current={identity:i,client:n};let s=Co(!1),a=Co(0),d=Co(0),[u,f]=Jn(null),[p,c]=Jn(null),[C,x]=Jn(),[h,g]=Jn([]),w=Co(C);w.current=C;let[y,E]=Jn(null),[S,k]=Jn(null),O=Co(null),L=Co(null),[z,G]=Jn(!1),[P,R]=Jn(!1),[M,N]=Jn(""),I=()=>s.current&&l.current.identity===i&&l.current.client===n,B=async()=>{let _=++a.current,ie=await Fi(()=>n.list(e,t,{limit:20,...w.current===void 0?{}:{before:w.current}}));if(!I()||_!==a.current)throw Error("Refresh superseded");if(!ie.ok)throw N(ie.error.message),Error("Attachment refresh failed");c(ie.data),f(i)},v=Co(B);v.current=B,Ti(()=>(s.current=!0,()=>{s.current=!1,++a.current,++d.current}),[]),Ti(()=>{if(l.current.identity!==i||l.current.client!==n)return;f(null),c(null),E(null),k(null),O.current=null,G(!1),R(!1),N(""),x(void 0),g([]),w.current=void 0,++d.current,v.current().catch(()=>{})},[i,n]),Ti(()=>{if(w.current===C&&u===i)v.current().catch(()=>{})},[C,i,u]),Ti(()=>(r?.(()=>v.current()),()=>r?.(null)),[r]);let K=async()=>{if(z||o||!y||u!==i)return;let _=y;G(!0),N("");let ie=await Fi(()=>n.upload(e,t,_));if(!I())return;if(G(!1),!ie.ok){N(ie.error.message);return}if(E(null),L.current)L.current.value="";x(void 0),g([]),w.current=void 0,await v.current().catch(()=>{})},ce=async()=>{if(z||o||!S||S.authorId!==p?.actorId||u!==i)return;O.current??=crypto.randomUUID();let _=S,ie=O.current;G(!0),N("");let ue=await Fi(()=>n.delete(e,t,_.id,{expectedVersion:_.version,idempotencyKey:ie}));if(!I())return;if(G(!1),!ue.ok){N(ue.error.message),await v.current().catch(()=>{});return}k(null),O.current=null,await v.current().catch(()=>{})},fe=async(_)=>{if(z||u!==i)return;G(!0),N("");let ie=await Fi(()=>n.content(e,t,_.id));if(!I())return;if(G(!1),!ie.ok){N(ie.error.message);return}let ue=Uint8Array.from(atob(ie.data.base64),(xe)=>xe.charCodeAt(0)),W=URL.createObjectURL(new Blob([ue],{type:"application/octet-stream"})),q=document.createElement("a");q.href=W,q.download=ie.data.attachment.name,q.click(),setTimeout(()=>URL.revokeObjectURL(W),1000)};return Xt("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Xt("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[It("h3",{className:"font-medium",children:"Attachments"}),It("button",{type:"button",disabled:z,onClick:()=>{N(""),v.current().catch(()=>{})},children:"Refresh attachments"})]}),M&&It("p",{role:"alert",children:M}),!p||u!==i?It("p",{role:"status",children:"Loading attachments…"}):Xt(Ns,{children:[p.items.length===0&&It("p",{children:"No attachments yet."}),It("ol",{className:"flex min-w-0 flex-col gap-2",children:p.items.map((_)=>Xt("li",{className:"min-w-0 rounded border p-2",children:[It("p",{className:"break-all",children:_.name}),Xt("p",{className:"break-all text-xs",children:[_.size," bytes · version ",_.version," · ",_.authorId]}),_.deletedAt?It("p",{children:"Attachment deleted"}):Xt("div",{className:"flex flex-wrap gap-3",children:[It("button",{type:"button",disabled:z,"aria-label":`Download attachment ${_.name}`,onClick:()=>void fe(_),children:"Download"}),!o&&_.authorId===p.actorId&&It("button",{type:"button",disabled:z,"aria-label":`Delete attachment ${_.name}`,onClick:()=>{k(_),O.current=null},children:"Delete"})]})]},_.id))}),Xt("div",{className:"flex flex-wrap gap-3",children:[It("button",{type:"button",disabled:z||!h.length,onClick:()=>{x(h.at(-1)),g((_)=>_.slice(0,-1))},children:"Newer attachments"}),It("button",{type:"button",disabled:z||p.nextCursor===null,onClick:()=>{g((_)=>[..._,C]),x(p.nextCursor??void 0)},children:"Older attachments"})]}),!o&&Xt(Ns,{children:[It("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."}),Xt("label",{children:["Attachment file",It("input",{ref:L,"aria-label":"Attachment file",type:"file",disabled:z||P,onChange:async(_)=>{let ie=_.target.files?.[0];if(!ie)return;let ue=++d.current;if(E(null),N(""),!ie.size||ie.size>1048576){N("Choose a nonempty file up to 1 MiB.");return}R(!0);try{let W=await ru(ie);if(!I()||ue!==d.current)return;let q=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(ie.type)?ie.type:"application/octet-stream";E({name:ie.name,contentType:q,base64:W,idempotencyKey:crypto.randomUUID()})}catch{if(I()&&ue===d.current)N("The selected file could not be read.")}finally{if(I()&&ue===d.current)R(!1)}}},i)]}),y&&Xt("p",{className:"break-all",children:["Selected file: ",y.name]}),It("button",{type:"button",className:"self-start",disabled:z||P||!y,onClick:()=>void K(),children:"Upload attachment"}),S&&Xt("div",{children:[Xt("p",{className:"break-all",children:["Delete ",S.name,"? This permanently removes its bytes and keeps a deletion marker."]}),Xt("div",{className:"flex flex-wrap gap-3",children:[It("button",{type:"button",disabled:z,onClick:()=>void ce(),children:"Confirm delete attachment"}),It("button",{type:"button",disabled:z,onClick:()=>{k(null),O.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as Ni,useRef as ur,useState as en}from"react";import{jsx as $e,jsxs as dt,Fragment as Ms}from"react/jsx-runtime";async function Ma(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function au(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function lu({descriptor:e,recordIds:t,client:n,linkForGrant:o,registerRefresh:r}){let i=e.id,l=ur({identity:i,client:n});l.current={identity:i,client:n};let s=ur(!1),a=ur(0),[d,u]=en(null),[f,p]=en(null),[c,C]=en(),x=ur(c);x.current=c;let[h,g]=en([]),[w,y]=en([]),[E,S]=en([]),[k,O]=en(3600),[L,z]=en(null),[G,P]=en(!1),[R,M]=en(""),[N,I]=en(null),B=ur(null),[v,K]=en(!1),[ce,fe]=en(""),_=()=>s.current&&l.current.identity===i&&l.current.client===n,ie=async()=>{let re=++a.current,Ce=await Ma(()=>n.list(i,{limit:20,...x.current===void 0?{}:{before:x.current}}));if(!_()||re!==a.current)throw Error("Refresh superseded");if(!Ce.ok)throw fe(Ce.error.message),Error("Share refresh failed");p(Ce.data),u(i)},ue=ur(ie);ue.current=ie,Ni(()=>(s.current=!0,()=>{s.current=!1,++a.current}),[]),Ni(()=>{if(l.current.identity!==i||l.current.client!==n)return;u(null),p(null),y([]),S([]),z(null),P(!1),M(""),I(null),B.current=null,K(!1),fe(""),C(void 0),g([]),x.current=void 0,ue.current().catch(()=>{})},[i,n]),Ni(()=>{if(x.current===c&&d===i)ue.current().catch(()=>{})},[c,d,i]),Ni(()=>(r?.(()=>ue.current()),()=>r?.(null)),[r]);let W=()=>{if(!G)z(null)},q=async()=>{if(v||!L||d!==i)return;let re=L;K(!0),P(!0),fe("");let Ce=await Ma(()=>n.create(i,re));if(!_())return;if(K(!1),!Ce.ok){fe(Ce.error.message);return}M(o(Ce.data,re.key)),z(null),P(!1),C(void 0),g([]),x.current=void 0,await ue.current().catch(()=>{})},xe=async()=>{if(v||!N||d!==i)return;let re=N;B.current??=crypto.randomUUID();let Ce=B.current;K(!0),fe("");let he=await Ma(()=>n.revoke(i,re.id,{expectedVersion:re.version,idempotencyKey:Ce}));if(!_())return;if(K(!1),!he.ok){fe(he.error.message),await ue.current().catch(()=>{});return}I(null),B.current=null,M(""),await ue.current().catch(()=>{})},ke=e.fields.filter((re)=>!["linkedRecord","lookup","formula","rollup"].includes(re.type)),ye=v||G;return dt("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[dt("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[$e("h3",{className:"font-medium",children:"Read-only sharing"}),$e("button",{type:"button",disabled:v,onClick:()=>{fe(""),ue.current().catch(()=>{})},children:"Refresh share grants"})]}),$e("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."}),$e("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."}),ce&&$e("p",{role:"alert",children:ce}),dt("fieldset",{disabled:ye,className:"flex min-w-0 flex-col gap-2",children:[$e("legend",{children:"Fields to share"}),ke.map((re)=>dt("label",{className:"break-all",children:[$e("input",{type:"checkbox","aria-label":`Share field ${re.name}`,checked:w.includes(re.id),onChange:(Ce)=>{W(),y((he)=>Ce.target.checked?[...he,re.id]:he.filter((Ye)=>Ye!==re.id))}})," ",re.name]},re.id))]}),dt("fieldset",{disabled:ye,className:"flex min-w-0 flex-col gap-2",children:[$e("legend",{children:"Records on the current page"}),t.slice(0,100).map((re)=>dt("label",{className:"break-all",children:[$e("input",{type:"checkbox","aria-label":`Share record ${re}`,checked:E.includes(re),onChange:(Ce)=>{W(),S((he)=>Ce.target.checked?[...he,re]:he.filter((Ye)=>Ye!==re))}})," ",re]},re)),t.length===0&&$e("p",{children:"Load records in Grid to choose a share scope."})]}),dt("p",{className:"break-all text-xs",children:["Selected record IDs: ",E.join(", ")||"none"]}),dt("label",{children:["Link lifetime"," ",dt("select",{"aria-label":"Share link lifetime",disabled:ye,value:k,onChange:(re)=>{W(),O(Number(re.target.value))},children:[$e("option",{value:60,children:"1 minute"}),$e("option",{value:3600,children:"1 hour"}),$e("option",{value:86400,children:"24 hours"})]})]}),$e("button",{type:"button",className:"self-start",disabled:ye||d!==i||!w.length||!E.length||E.length>100||w.some((re)=>!ke.some((Ce)=>Ce.id===re)),onClick:()=>{fe("");try{z({expectedSchemaVersion:e.schemaVersion,fieldIds:[...w],recordIds:[...E],expiresInSeconds:k,key:au(),idempotencyKey:crypto.randomUUID()})}catch{fe("A secure share key could not be generated.")}},children:"Review read-only share"}),L&&dt("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[dt("p",{className:"break-all",children:["Confirm schema ",L.expectedSchemaVersion,", fields ",L.fieldIds.join(", "),", records ",L.recordIds.join(", ")," for ",L.expiresInSeconds," seconds."]}),L.expectedSchemaVersion!==e.schemaVersion&&$e("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),dt("div",{className:"flex flex-wrap gap-3",children:[$e("button",{type:"button",disabled:v,onClick:()=>void q(),children:G?"Retry create read link":"Create read link"}),$e("button",{type:"button",disabled:v,onClick:()=>{z(null),P(!1),fe("")},children:"Discard share confirmation"})]}),G&&$e("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."})]}),R&&dt("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",$e("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:R,onFocus:(re)=>re.target.select()})]}),!f||d!==i?$e("p",{role:"status",children:"Loading share grants…"}):dt(Ms,{children:[f.items.length===0&&$e("p",{children:"No share grants yet."}),$e("ol",{className:"flex min-w-0 flex-col gap-2",children:f.items.map((re)=>dt("li",{className:"min-w-0 rounded border p-2",children:[dt("p",{className:"break-all",children:["Grant ",re.id," · version ",re.version," · schema ",re.schemaVersion]}),dt("p",{className:"break-all text-xs",children:["Fields: ",re.fieldIds.join(", ")," · Records: ",re.recordIds.join(", ")," · Expires:"," ",re.expiresAt]}),re.revokedAt?$e("p",{children:"Share revoked"}):dt(Ms,{children:[$e("p",{children:re.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(re.expiresAt)<=Date.now()?"Share expired":"Share active"}),$e("button",{type:"button",disabled:v,"aria-label":`Revoke share ${re.id}`,onClick:()=>{I(re),B.current=null},children:"Revoke"})]})]},re.id))}),dt("div",{className:"flex flex-wrap gap-3",children:[$e("button",{type:"button",disabled:v||!h.length,onClick:()=>{C(h.at(-1)),g((re)=>re.slice(0,-1))},children:"Newer share grants"}),$e("button",{type:"button",disabled:v||f.nextCursor===null,onClick:()=>{g((re)=>[...re,c]),C(f.nextCursor??void 0)},children:"Older share grants"})]})]}),N&&dt("div",{children:[dt("p",{className:"break-all",children:["Revoke grant ",N.id," at version ",N.version,"? Every existing share session will lose access."]}),dt("div",{className:"flex flex-wrap gap-3",children:[$e("button",{type:"button",disabled:v,onClick:()=>void xe(),children:"Confirm revoke share"}),$e("button",{type:"button",disabled:v,onClick:()=>{I(null),B.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as Os,useRef as pr,useState as zt}from"react";import{jsx as Fe,jsxs as ut}from"react/jsx-runtime";var Ls=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],su=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function du({descriptor:e,recordIds:t,client:n,webhookRequest:o}){let r=e.id,i=pr({id:r,client:n});i.current={id:r,client:n};let l=pr(!0),s=pr(0),[a,d]=zt([]),[u,f]=zt(""),p=pr(u);p.current=u;let[c,C]=zt(null),[x,h]=zt(),g=pr(x);g.current=x;let[w,y]=zt(""),[E,S]=zt("record"),[k,O]=zt(60),[L,z]=zt([]),[G,P]=zt([]),[R,M]=zt({}),[N,I]=zt(null),[B,v]=zt(!1),[K,ce]=zt(!1),[fe,_]=zt(""),[ie,ue]=zt(""),W=()=>l.current&&i.current.id===r&&i.current.client===n,q=async(j)=>{try{return await j()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},xe=async()=>{let j=++s.current,D=await q(()=>n.list(r));if(!W()||j!==s.current)return;if(!D.ok){_(D.error.message);return}d(D.data);let te=D.data.find((Te)=>Te.id===p.current)?.id??D.data[0]?.id??"";if(p.current=te,f(te),!te){C(null);return}let T=await q(()=>n.runs(r,te,{limit:20,...g.current?{before:g.current}:{}}));if(!W()||j!==s.current||p.current!==te)return;if(T.ok)C(T.data);else _(T.error.message)},ke=pr(xe);ke.current=xe,Os(()=>{if(i.current.id!==r||i.current.client!==n)return;l.current=!0,ke.current();let j=setInterval(()=>void ke.current(),5000);return()=>{l.current=!1,++s.current,clearInterval(j)}},[r,n]),Os(()=>{if(p.current!==u||g.current!==x)return;ke.current()},[u,x]);let ye=()=>{if(_(""),!w.trim()||!L.length||E!=="record"&&!G.length){_("Choose a name, writable fields, and target records for time or webhook triggers.");return}let j=Object.fromEntries(L.map((te)=>[te,R[te]??null])),D={expectedSchemaVersion:e.schemaVersion,name:w.trim(),trigger:E==="time"?{kind:E,intervalSeconds:k}:{kind:E},targetRecordIds:G,values:j,idempotencyKey:crypto.randomUUID(),...E==="webhook"?{webhookKey:su()}:{}};I({kind:"create",input:D}),v(!1)},re=(j)=>{I(j),v(!1),_("")},Ce=async()=>{if(!N||K)return;let j=N,D=B;v(!0),ce(!0),_("");let te=await q(()=>j.kind==="create"?n.create(r,j.input):j.kind==="toggle"?n.toggle(r,j.a.id,j.input):j.kind==="run"?n.runNow(r,j.a.id,j.input):n.retry(r,j.a.id,j.run.id,j.input));if(!W())return;if(ce(!1),!te.ok){if(!D&&te.error.status>=400&&te.error.status<500)v(!1);_(`${te.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(j.kind==="create"){let T=te.data;if(p.current=T.id,f(T.id),j.input.webhookKey&&o)ue(JSON.stringify(o(T,j.input.webhookKey),null,2));y(""),z([]),P([]),M({})}I(null),v(!1),g.current=void 0,h(void 0),await ke.current()},he=a.find((j)=>j.id===u),Ye=!!N||K;return ut("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[Fe("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."}),Fe("button",{type:"button",onClick:()=>void ke.current(),children:"Refresh automation"}),fe&&Fe("p",{role:"alert",children:fe}),Fe("form",{onSubmit:(j)=>{j.preventDefault(),ye()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:ut("fieldset",{disabled:Ye,style:{minWidth:0},children:[Fe("legend",{children:"New automation"}),ut("label",{children:["Name"," ",Fe("input",{"aria-label":"Automation name",value:w,maxLength:200,onChange:(j)=>y(j.target.value)})]}),ut("label",{children:["Trigger"," ",ut("select",{"aria-label":"Automation trigger",value:E,onChange:(j)=>S(j.target.value),children:[Fe("option",{value:"record",children:"Record changes"}),Fe("option",{value:"time",children:"Timed interval"}),Fe("option",{value:"webhook",children:"Private webhook"})]})]}),E==="time"&&ut("label",{children:["Interval in seconds"," ",Fe("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:k,onChange:(j)=>O(Number(j.target.value))})]}),ut("fieldset",{children:[Fe("legend",{children:"Fields to update"}),e.fields.filter((j)=>Ls.includes(j.type)).map((j)=>ut("label",{style:{display:"block"},children:[Fe("input",{type:"checkbox",checked:L.includes(j.id),onChange:(D)=>{z(D.target.checked?[...L,j.id]:L.filter((te)=>te!==j.id))}}),j.name]},j.id))]}),Fe(Ho,{fields:e.fields.filter((j)=>L.includes(j.id)&&Ls.includes(j.type)),values:R,onChange:M}),ut("fieldset",{children:[Fe("legend",{children:"Target records from this page"}),E==="record"&&Fe("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&Fe("p",{children:"Open a grid page to choose fixed records."}),t.map((j)=>ut("label",{style:{display:"block",overflowWrap:"anywhere"},children:[Fe("input",{type:"checkbox","aria-label":`Automation target ${j}`,checked:G.includes(j),onChange:(D)=>P(D.target.checked?[...G,j]:G.filter((te)=>te!==j))}),j]},j))]}),Fe("button",{type:"submit",children:"Review automation"})]})}),N&&ut("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[Fe("p",{children:N.kind==="create"?`Create ${N.input.name} using schema ${N.input.expectedSchemaVersion}; ${N.input.targetRecordIds.length||"event"} targets.`:N.kind==="toggle"?`${N.input.enabled?"Enable":"Disable"} ${N.a.name}. Disabling fences queued and running work.`:N.kind==="run"?`Run ${N.a.name} for ${N.input.recordIds.length} explicitly selected records.`:`Retry ${N.a.name}, run ${N.run.sequence}, using its original record versions.`}),N.kind==="create"&&Fe("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(N.input.values,null,2)}),Fe("button",{type:"button",disabled:K,onClick:()=>void Ce(),children:K?"Confirming…":B?"Retry automation confirmation":"Confirm automation"}),Fe("button",{type:"button",disabled:B||K,onClick:()=>I(null),children:"Cancel automation review"}),B&&Fe("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),ie&&ut("div",{children:[Fe("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),Fe("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:ie}),Fe("button",{type:"button",onClick:()=>ue(""),children:"Hide webhook key"})]}),a.length>0&&ut("label",{children:["Automation"," ",Fe("select",{"aria-label":"Selected automation",disabled:Ye,value:u,onChange:(j)=>{p.current=j.target.value,g.current=void 0,h(void 0),f(j.target.value),C(null)},children:a.map((j)=>Fe("option",{value:j.id,children:j.name},j.id))})]}),he&&ut("div",{children:[ut("p",{children:[he.enabled?"Enabled":"Disabled"," · ",he.trigger.kind," · schema ",he.schemaVersion," · configuration ",he.version]}),Fe("button",{type:"button",disabled:Ye,onClick:()=>re({kind:"toggle",a:he,input:{expectedVersion:he.version,enabled:!he.enabled,idempotencyKey:crypto.randomUUID()}}),children:he.enabled?"Review disable automation":"Review enable automation"}),Fe("button",{type:"button",disabled:Ye||!he.enabled||!(he.targetRecordIds.length||t.length),onClick:()=>re({kind:"run",a:he,input:{recordIds:he.targetRecordIds.length?he.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),c&&ut("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!c.items.length&&Fe("p",{children:"No runs yet."}),c.items.map((j)=>ut("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[ut("p",{children:["Run ",j.sequence," · ",j.triggerKind," · ",j.status," · step ",j.step]}),ut("p",{children:["Attempts: evaluate ",j.stepAttempts.evaluate,", apply ",j.stepAttempts.apply," · original versions: ",j.expectedRows.map((D)=>`${D.id}: ${D.version}`).join(", ")]}),j.errorCode&&Fe("p",{role:"status",children:j.errorCode}),j.leaseUntil&&ut("p",{children:["Lease expires ",j.leaseUntil]}),he&&j.status==="failed"&&ut("button",{type:"button",disabled:Ye||!he.enabled,onClick:()=>re({kind:"retry",a:he,run:j,input:{expectedVersion:j.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",j.sequence]})]},j.id)),Fe("button",{type:"button",disabled:Ye||x===void 0,onClick:()=>{g.current=void 0,h(void 0)},children:"Newest runs"}),Fe("button",{type:"button",disabled:Ye||c.nextCursor===null,onClick:()=>{g.current=c.nextCursor??void 0,h(g.current)},children:"Older runs"})]})]})}import{useEffect as cu,useId as uu,useRef as Bs,useState as Ft}from"react";import{jsx as qe,jsxs as pt}from"react/jsx-runtime";var Vs=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function pu(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 r of[n.sourceFieldIds,n.targetFieldIds])if(r.length<1||r.length>10||new Set(r).size!==r.length||r.some((i)=>!e.fields.some((l)=>l.id===i&&Vs.includes(l.type))))throw Error("Choose up to ten basic source and target fields.");let o=n.recordIds.map((r)=>{let i=t.find((l)=>l.id===r);if(!i)throw Error("A selected record is no longer on this page.");return{id:r,expectedVersion:i.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 gu({descriptor:e,records:t,client:n,onApplied:o}){let r=uu(),i=e.id,l=Bs({id:i,client:n}),s=Bs(!0);l.current={id:i,client:n};let[a,d]=Ft([]),[u,f]=Ft(!1),[p,c]=Ft(""),[C,x]=Ft(""),[h,g]=Ft(""),[w,y]=Ft([]),[E,S]=Ft([]),[k,O]=Ft([]),[L,z]=Ft(null),[G,P]=Ft(null),[R,M]=Ft(null),[N,I]=Ft(!1),[B,v]=Ft(!1),[K,ce]=Ft(""),[fe,_]=Ft(""),[ie,ue]=Ft(""),W=()=>s.current&&l.current.id===i&&l.current.client===n,q=async(D)=>{try{return await D()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};cu(()=>{s.current=!0,z(null),P(null),M(null),I(!1),ce(""),_(""),ue(""),y([]),S([]),O([]),g("");let D=!0;return f(!1),v(!1),d([]),c(""),x(""),n.providers(i).then((te)=>{if(!D||l.current.id!==i||l.current.client!==n)return;if(f(!0),te.ok)d(te.data),c(te.data[0]?.resourceId??""),x(te.data[0]?.allowedModels[0]??"");else ce(te.error.message)}).catch(()=>{if(D)f(!0),ce("AI configuration is unavailable.")}),()=>{D=!1,s.current=!1}},[i,n]);let xe=()=>{try{let D=pu(e,t,{resourceId:p,model:C,instruction:h,recordIds:w,sourceFieldIds:E,targetFieldIds:k});P(structuredClone(D.records.map((te)=>({id:te.id,version:te.expectedVersion,values:Object.fromEntries(D.sourceFieldIds.map((T)=>[T,t.find((Te)=>Te.id===te.id)?.values[T]??null]))})))),z(D),I(!1),ce(""),_("")}catch(D){ce(D instanceof Error?D.message:"Invalid selection.")}},ke=async()=>{if(!L||B)return;let D=L,te=N;v(!0),I(!0),ce("");let T=await q(()=>n.propose(i,D));if(!W())return;if(v(!1),!T.ok){if(!te&&T.error.status>=400&&T.error.status<500)I(!1);ce(`${T.error.message} Retry keeps the original selection and versions.`);return}M(T.data),ue(T.data.id),I(!1)},ye=async()=>{if(!R||B)return;let D=R,te=N;v(!0),I(!0),ce("");let T=await q(()=>n.confirm(i,D));if(!W())return;if(v(!1),!T.ok){if(!te&&T.error.status>=400&&T.error.status<500)I(!1);ce(`${T.error.message} The reviewed proposal keeps its original versions.`);return}_(`${T.data.items.length} records filled${T.data.replayed?"; original receipt recovered":""}.`),M(null),z(null),P(null),I(!1);try{await o?.()}catch{if(W())ce("The fill committed. Refresh the Collection to see its records.")}},re=async()=>{if(B||L||R)return;v(!0),ce("");let D=await q(()=>n.get(i,ie));if(!W())return;if(v(!1),D.ok)M(D.data),I(!1),_("");else ce(D.error.message)},Ce=(D,te,T)=>T(D.includes(te)?D.filter((Te)=>Te!==te):[...D,te]),he=B||!!L||!!R,Ye=e.fields.filter((D)=>Vs.includes(D.type)),j=a.find((D)=>D.resourceId===p);return pt("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[qe("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."}),K&&qe("p",{role:"alert",children:K}),fe&&qe("p",{role:"status",children:fe}),u&&a.length===0&&qe("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),qe("form",{onSubmit:(D)=>{D.preventDefault(),xe()},children:pt("fieldset",{disabled:he,style:{minWidth:0},children:[qe("legend",{children:"AI fill request"}),pt("label",{children:["AI resource"," ",pt("select",{"aria-label":"AI resource",value:p,onChange:(D)=>{c(D.target.value),x(a.find((te)=>te.resourceId===D.target.value)?.allowedModels[0]??"")},children:[qe("option",{value:"",children:"Choose resource"}),a.map((D)=>qe("option",{value:D.resourceId,children:D.name},D.resourceId))]})]}),pt("label",{htmlFor:r,children:["Model"," ",j?.allowedModels.length?qe("select",{id:r,"aria-label":"AI model",value:C,onChange:(D)=>x(D.target.value),children:j.allowedModels.map((D)=>qe("option",{value:D,children:D},D))}):qe("input",{id:r,"aria-label":"AI model",maxLength:200,value:C,onChange:(D)=>x(D.target.value)})]}),pt("label",{children:["Instructions"," ",qe("textarea",{"aria-label":"AI instructions",maxLength:2000,value:h,onChange:(D)=>g(D.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),pt("fieldset",{children:[qe("legend",{children:"Source fields to send"}),Ye.map((D)=>pt("label",{style:{display:"block"},children:[qe("input",{type:"checkbox","aria-label":`Send ${D.name}`,checked:E.includes(D.id),onChange:()=>Ce(E,D.id,S)}),D.name]},D.id))]}),pt("fieldset",{children:[qe("legend",{children:"Fields to fill"}),Ye.map((D)=>pt("label",{style:{display:"block"},children:[qe("input",{type:"checkbox","aria-label":`Fill ${D.name}`,checked:k.includes(D.id),onChange:()=>Ce(k,D.id,O)}),D.name]},D.id))]}),pt("fieldset",{children:[qe("legend",{children:"Target records from this page"}),t.map((D)=>pt("label",{style:{display:"block",overflowWrap:"anywhere"},children:[qe("input",{type:"checkbox","aria-label":`AI record ${D.id}`,checked:w.includes(D.id),onChange:()=>Ce(w,D.id,y)}),D.id," · version ",D.version]},D.id))]}),qe("button",{type:"submit",disabled:!p,children:"Review AI request"})]})}),L&&!R&&pt("section",{"aria-label":"AI data disclosure",children:[pt("p",{children:["Selected service: ",L.resourceId," · model ",L.model," · schema"," ",L.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),qe("p",{children:L.instruction}),qe("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(G,null,2)}),qe("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),qe("button",{type:"button",disabled:B,onClick:()=>void ke(),children:N?"Retry original AI request":"Generate proposal"}),qe("button",{type:"button",disabled:B||N,onClick:()=>{z(null),P(null),ce("")},children:"Cancel AI request"})]}),R&&pt("section",{"aria-label":"AI fill confirmation",children:[pt("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",R.id," · ",R.provider," · schema ",R.schemaVersion]}),R.schemaVersion!==e.schemaVersion&&qe("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),R.rows.map((D)=>pt("div",{style:{overflowWrap:"anywhere"},children:[pt("p",{children:[D.id," · original version ",D.expectedVersion]}),Object.keys(D.values).map((te)=>pt("div",{children:[qe("strong",{children:e.fields.find((T)=>T.id===te)?.name??te}),pt("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(D.before[te]),`
10
+ `,"Suggested: ",JSON.stringify(D.values[te])]})]},te))]},D.id)),qe("button",{type:"button",disabled:B,onClick:()=>void ye(),children:N?"Retry original AI fill":"Confirm fill"}),qe("button",{type:"button",disabled:B||N,onClick:()=>{M(null),z(null),P(null),ce("")},children:"Dismiss proposal"})]}),pt("label",{children:["Recover a saved proposal"," ",qe("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:ie,onChange:(D)=>ue(D.target.value),disabled:he,style:{width:"100%",boxSizing:"border-box"}})]}),qe("button",{type:"button",disabled:he||!/^[a-f0-9]{64}$/.test(ie),onClick:()=>void re(),children:"Load saved proposal"})]})}import{jsx as pe,jsxs as Ne}from"react/jsx-runtime";var yu=[{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 Ib({fields:e,onChange:t,lockedIds:n=[],collections:o=[]}){let r=(i,l)=>t(e.map((s,a)=>a===i?{...s,...l}:s));return Ne("div",{className:"flex flex-col gap-3",children:[e.map((i,l)=>{let s=n.includes(i.id);return Ne("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:[pe("input",{"aria-label":`Field ${l+1} name`,placeholder:"Display name",value:i.name,onChange:(a)=>r(l,{name:a.target.value})}),pe("input",{"aria-label":`Field ${l+1} ID`,placeholder:"field_id",value:i.id,disabled:s,onChange:(a)=>r(l,{id:a.target.value})}),pe("select",{"aria-label":`Field ${l+1} type`,className:"rounded-md border bg-background px-2 text-sm",value:i.type,disabled:s,onChange:(a)=>{let d=a.target.value,u={id:i.id,name:i.name,type:d,required:it({type:d})?!1:i.required??!1};if(d==="formula")u.formula={expression:""};if(d==="rollup")u.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(d==="singleSelect"||d==="multipleSelect")u.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((f,p)=>p===l?u:f))},children:yu.map((a)=>pe("option",{value:a.value,children:a.name},a.value))}),Ne("div",{className:"flex items-center gap-2",children:[Ne("label",{className:"flex items-center gap-1 text-xs",children:[pe("input",{type:"checkbox",checked:i.required??!1,disabled:s||n.length>0||it(i),onChange:(a)=>r(l,{required:a.target.checked})}),"Required"]}),!s&&pe("button",{type:"button",onClick:()=>t(e.filter((a,d)=>d!==l)),children:"Remove"})]}),(i.type==="singleSelect"||i.type==="multipleSelect")&&pe("input",{className:"md:col-span-4","aria-label":`Field ${l+1} options`,placeholder:"Open, Done",value:i.options?.map((a)=>a.name).join(", ")??"",disabled:s,onChange:(a)=>r(l,{options:a.target.value.split(",").map((d,u)=>({id:d.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${u}`,name:d.trim()})).filter((d)=>d.name)})}),i.type==="linkedRecord"&&Ne("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Ne("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",Ne("select",{className:"min-w-0 max-w-full","aria-label":`Field ${l+1} linked collection`,value:i.link?.collectionId??"",disabled:s,onChange:(a)=>{let d=o.find((u)=>u.id===a.target.value);r(l,{link:{collectionId:a.target.value,displayFieldId:d?.fields.find((u)=>u.type==="singleLineText"||u.type==="longText")?.id??""}})},children:[pe("option",{value:"",children:"Choose collection…"}),o.map((a)=>pe("option",{value:a.id,children:a.name},a.id))]})]}),Ne("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",Ne("select",{className:"min-w-0 max-w-full","aria-label":`Field ${l+1} record label`,value:i.link?.displayFieldId??"",disabled:s||!i.link?.collectionId,onChange:(a)=>r(l,{link:{collectionId:i.link?.collectionId??"",displayFieldId:a.target.value}}),children:[pe("option",{value:"",children:"Choose text field…"}),o.find((a)=>a.id===i.link?.collectionId)?.fields.filter((a)=>a.type==="singleLineText"||a.type==="longText").map((a)=>pe("option",{value:a.id,children:a.name},a.id))]})]})]}),i.type==="lookup"&&Ne("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Ne("label",{children:["Through linked field"," ",Ne("select",{"aria-label":`Field ${l+1} lookup link`,value:i.lookup?.linkFieldId??"",disabled:s,onChange:(a)=>r(l,{lookup:{linkFieldId:a.target.value,targetFieldId:""}}),children:[pe("option",{value:"",children:"Choose linked field…"}),e.filter((a)=>a.type==="linkedRecord"&&a.link).map((a)=>pe("option",{value:a.id,children:a.name},a.id))]})]}),Ne("label",{children:["Read target field"," ",Ne("select",{"aria-label":`Field ${l+1} lookup target`,value:i.lookup?.targetFieldId??"",disabled:s||!i.lookup?.linkFieldId,onChange:(a)=>r(l,{lookup:{linkFieldId:i.lookup?.linkFieldId??"",targetFieldId:a.target.value}}),children:[pe("option",{value:"",children:"Choose target field…"}),o.find((a)=>a.id===e.find((d)=>d.id===i.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((a)=>!it(a)&&a.type!=="linkedRecord").map((a)=>pe("option",{value:a.id,children:a.name},a.id))]})]}),pe("small",{children:"Computed from linked records. Values cannot be edited."})]}),i.type==="formula"&&Ne("div",{className:"flex flex-col gap-1 md:col-span-4",children:[Ne("label",{children:["Formula",pe("textarea",{"aria-label":`Field ${l+1} formula`,maxLength:2048,className:"min-h-16 w-full rounded-md border bg-background p-2",placeholder:"{quantity} * {price}",value:i.formula?.expression??"",onChange:(a)=>r(l,{formula:{expression:a.target.value}})})]}),pe("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."}),Ne("small",{children:["References:"," ",e.filter((a)=>a.id!==i.id&&(a.type==="singleLineText"||a.type==="longText"||a.type==="date"||a.type==="number"||a.type==="formula"||a.type==="rollup")).map((a)=>`{${a.id}}`).join(", ")||"None yet"]})]}),i.type==="rollup"&&Ne("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Ne("label",{children:["Through linked field"," ",Ne("select",{"aria-label":`Field ${l+1} rollup link`,value:i.rollup?.linkFieldId??"",onChange:(a)=>r(l,{rollup:{linkFieldId:a.target.value,targetFieldId:"",function:i.rollup?.function??"sum"}}),children:[pe("option",{value:"",children:"Choose linked field…"}),e.filter((a)=>a.type==="linkedRecord"&&a.link).map((a)=>pe("option",{value:a.id,children:a.name},a.id))]})]}),Ne("label",{children:["Aggregate"," ",Ne("select",{"aria-label":`Field ${l+1} rollup function`,value:i.rollup?.function??"sum",onChange:(a)=>{let d=a.target.value,u=o.find((f)=>f.id===e.find((p)=>p.id===i.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((f)=>f.id===i.rollup?.targetFieldId);r(l,{rollup:{linkFieldId:i.rollup?.linkFieldId??"",targetFieldId:d==="count"||u?.type==="number"?i.rollup?.targetFieldId??"":"",function:d}})},children:[pe("option",{value:"sum",children:"Sum"}),pe("option",{value:"average",children:"Average"}),pe("option",{value:"min",children:"Minimum"}),pe("option",{value:"max",children:"Maximum"}),pe("option",{value:"count",children:"Count values"})]})]}),Ne("label",{children:["Target field"," ",Ne("select",{"aria-label":`Field ${l+1} rollup target`,value:i.rollup?.targetFieldId??"",disabled:!i.rollup?.linkFieldId,onChange:(a)=>r(l,{rollup:{linkFieldId:i.rollup?.linkFieldId??"",targetFieldId:a.target.value,function:i.rollup?.function??"sum"}}),children:[pe("option",{value:"",children:"Choose target field…"}),o.find((a)=>a.id===e.find((d)=>d.id===i.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((a)=>!it(a)&&a.type!=="linkedRecord"&&(i.rollup?.function==="count"||a.type==="number")).map((a)=>pe("option",{value:a.id,children:a.name},a.id))]})]}),pe("small",{className:"w-full",children:"Null targets are skipped. Count counts values; empty sum/count are zero. Other empty aggregates have no result."})]})]},l)}),pe("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 bu(e,t,n){if(it(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 dr(e,at(t),n)}function Hr(e,t,n,o){let r=Object.create(null);for(let i of e){if(i.type==="lookup"||i.type==="formula"||i.type==="rollup"||i.type==="blob"||i.generation==="autoIncrement")continue;if(!Object.hasOwn(t,i.id)){if(i.required)throw Error(n("{name} is required.",{name:i.name}));continue}let l=t[i.id];if(i.type==="linkedRecord"){if(!Array.isArray(l)||l.some((s)=>typeof s!=="string")||l.length>100||new Set(l).size!==l.length)throw Error(n("{name} needs unique linked records.",{name:i.name}));if(i.required&&!l.length)throw Error(n("{name} is required.",{name:i.name}));r[i.id]=l;continue}if(i.type==="relation"){if(l==null||l===""){if(i.required)throw Error(n("{name} is required.",{name:i.name}));r[i.id]=null;continue}if(typeof l!=="string")throw Error(n("{name} needs a server-provided option.",{name:i.name}));r[i.id]=l;continue}if(i.type==="hyperlink"&&l!==null&&typeof l==="object"){if(!nr(l))throw Error(n("{name} needs a link.",{name:i.name}));r[i.id]=l;continue}if(i.required&&typeof l==="string"&&!l.trim())throw Error(n("{name} is required.",{name:i.name}));r[i.id]=xn(Array.isArray(l)?l.join(","):String(l??""),i,o)}return r}function Ho({fields:e,values:t,onChange:n,relationClient:o,getRelationOptions:r,linkedRecords:i,computedErrors:l,locale:s,ui:a,submitted:d=!1}){let u=oe(s),f=mu(),p=fu(()=>r??(o?Ri(o,[]):void 0),[r,o]);return pe("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((c)=>{let C=c.description?.trim()??"",x=C?`${f}-${c.id}-hint`:void 0,h=bu(c,t[c.id],s??"en"),w=Boolean(c.required&&at(t[c.id])===""&&h)&&!d?"":h,y=w?`${f}-${c.id}-error`:void 0,E=[x,y].filter(Boolean).join(" "),S={...E?{"aria-describedby":E}:{},...w?{"aria-invalid":!0}:{}};return Ne("div",{className:"flex flex-col gap-1 text-sm",children:[Ne("label",{htmlFor:`${f}-${c.id}`,children:[c.name,c.required?" *":""]}),C?pe("p",{id:x,className:"m-0 text-xs opacity-70",children:C}):null,it(c)?pe("output",{id:`${f}-${c.id}`,"aria-label":u("{name} (read only)",{name:c.name}),...S,children:c.type==="lookup"?go(t[c.id]):ir(t[c.id],l?.[c.id],s)}):c.type==="relation"?pe(_o,{field:c,id:`${f}-${c.id}`,label:`${c.name}${c.required?" *":""}`,value:typeof t[c.id]==="string"?String(t[c.id]):"",labels:i?.[c.id],getOptions:p,locale:s,onChange:(k)=>n({...t,[c.id]:k||null}),...S}):c.type==="linkedRecord"?pe(wi,{...s?{locale:s}:{},field:c,value:t[c.id],labels:i?.[c.id],client:o,onChange:(k)=>n({...t,[c.id]:k}),...S}):c.type==="checkbox"?pe("input",{id:`${f}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,type:"checkbox",checked:t[c.id]===!0,onChange:(k)=>n({...t,[c.id]:k.target.checked}),...S}):c.type==="singleSelect"&&a?.Select?pe(Xe,{ui:a,label:`${c.name}${c.required?" *":""}`,...S,value:String(t[c.id]??""),options:[{value:"",label:u("Choose…")},...(c.options??[]).map((k)=>({value:k.id,label:k.name}))],onChange:(k)=>n({...t,[c.id]:k||null})}):c.type==="multipleSelect"&&a?.MultiSelect?pe(a.MultiSelect,{"aria-label":`${c.name}${c.required?" *":""}`,...S,options:(c.options??[]).map((k)=>({value:k.id,label:k.name,slot:Or(c.options,k.id)})),values:Array.isArray(t[c.id])?t[c.id]:[],placeholder:u("Choose…"),onChange:(k)=>n({...t,[c.id]:k})}):c.type==="singleSelect"||c.type==="multipleSelect"?Ne("select",{id:`${f}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...S,className:"min-h-9 rounded-md border bg-background p-2",multiple:c.type==="multipleSelect",value:c.type==="multipleSelect"?Array.isArray(t[c.id])?t[c.id]:[]:String(t[c.id]??""),onChange:(k)=>n({...t,[c.id]:c.type==="multipleSelect"?Array.from(k.target.selectedOptions,(O)=>O.value):k.target.value||null}),children:[c.type==="singleSelect"&&pe("option",{value:"",children:u("Choose…")}),c.options?.map((k)=>pe("option",{value:k.id,children:k.name},k.id))]}):c.type==="date"&&a?.DatePicker?(()=>{let k={kind:xa(c),timeZone:Rt(c)?.timeZone},O=String(t[c.id]??"");return pe(a.DatePicker,{id:`${f}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...S,value:Ra(O,k),withTime:k.kind==="auto"?fo(O):k.kind==="datetime",fixedKind:k.kind!=="auto",clearable:!c.required,onChange:(L)=>n({...t,[c.id]:L?Ia(L,O,k):null})})})():c.type==="hyperlink"?pe(_r,{field:c,id:`${f}-${c.id}`,ariaLabel:`${c.name}${c.required?" *":""}`,describedBy:S["aria-describedby"],invalid:Boolean(w),locale:s,inputClassName:"min-h-9 min-w-0 rounded-md border bg-background p-2",text:typeof t[c.id]==="string"?String(t[c.id]):Vr(nr(t[c.id])?t[c.id]:null),onChange:(k)=>{let O=k.trim().startsWith("{")?Fo(k):null;n({...t,[c.id]:O??(k||null)})}}):c.type==="longText"?pe("textarea",{id:`${f}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...S,className:"rounded-md border bg-background p-2",value:String(t[c.id]??""),onChange:(k)=>n({...t,[c.id]:k.target.value||null})}):pe("input",{id:`${f}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...S,className:"min-h-9 min-w-0 rounded-md border bg-background p-2",type:c.type==="number"?"number":c.type==="date"?"date":"text",step:c.type==="number"?"any":void 0,value:c.type==="date"?String(t[c.id]??"").slice(0,10):String(t[c.id]??""),onChange:(k)=>n({...t,[c.id]:k.target.value===""?null:c.type==="number"?Number(k.target.value):c.type==="date"&&t[c.id]?Pi(t[c.id],k.target.value):k.target.value})}),w?pe("span",{id:y,className:"text-xs text-red-600",children:w}):null]},c.id)})})}function hu(e,t,n){if(t==="isEmpty")return;let o=it(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 r=Number(n);if(!n.trim()||!Number.isFinite(r))throw Error("Filter needs a number.");return r}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(it(e)&&!ln(e))throw Error("Computed filters are not available for this field.");if((e.type==="multipleSelect"||e.type==="linkedRecord")&&t!=="contains")return n.split(",").map((r)=>r.trim());return n}function Ab({fields:e,view:t,onChange:n,onError:o}){let r=e.filter(ln),[i,l]=Oa(r[0]?.id??""),s=r.some((g)=>g.id===i)?i:r[0]?.id??"",[a,d]=Oa("contains"),u=s?(()=>{let g=e.find((w)=>w.id===s);return g&&it(g)?g.resultType:g?.type})():void 0,f=u==="number"?["is","isNot","isEmpty"]:u==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],p=f.includes(a)?a:u==="number"||u==="date"?"is":"contains",[c,C]=Oa(""),h=[...t.columnOrder.flatMap((g)=>{let w=e.find((y)=>y.id===g);return w?[w]:[]}),...e.filter((g)=>!t.columnOrder.includes(g.id))];return Ne("div",{className:"flex flex-wrap items-end gap-3",children:[Ne("label",{className:"flex min-w-52 flex-col gap-1 text-sm",children:["Search",pe("input",{type:"search",className:"min-h-9 min-w-0 rounded-md border bg-background p-2",value:t.search??"",onChange:(g)=>n({...t,search:g.target.value})})]}),Ne("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(g)=>{g.preventDefault();let w=e.find((E)=>E.id===s);if(!w)return;let y;try{y=hu(w,p,c)}catch(E){o(E instanceof Error?E.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:s,operator:p,...p==="isEmpty"?{}:{value:y}}]}})},children:[Ne("label",{className:"flex flex-col gap-1 text-sm",children:["Filter field",pe("select",{className:"h-9 rounded-md border bg-background px-2",value:s,onChange:(g)=>l(g.target.value),children:r.map((g)=>pe("option",{value:g.id,children:g.name},g.id))})]}),pe("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:p,onChange:(g)=>d(g.target.value),children:f.map((g)=>pe("option",{value:g,children:g==="isNot"?"is not":g==="isEmpty"?"is empty":g==="onOrAfter"?"on or after":g},g))}),p!=="isEmpty"&&pe("input",{type:u==="number"?"number":u==="date"?"date":"text",step:u==="number"?"any":void 0,className:"min-h-9 max-w-40 rounded-md border bg-background p-2","aria-label":"Filter value",value:c,onChange:(g)=>C(g.target.value)}),pe("button",{type:"submit",disabled:!s,children:"Apply filter"}),pe("button",{type:"button",onClick:()=>{let g={...t};delete g.filter,n(g)},children:"Clear filter"})]}),Ne("details",{className:"relative",children:[pe("summary",{className:"cursor-pointer rounded-md border px-3 py-2 text-sm",children:"Columns"}),pe("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:h.map((g,w)=>Ne("div",{className:"flex items-center gap-2 text-sm",children:[Ne("label",{className:"flex flex-1 items-center gap-2",children:[pe("input",{type:"checkbox",checked:!t.hiddenColumns.includes(g.id),disabled:t.type==="form"&&g.required===!0,onChange:(y)=>n({...t,hiddenColumns:y.target.checked?t.hiddenColumns.filter((E)=>E!==g.id):[...t.hiddenColumns,g.id]})}),g.name]}),pe("button",{type:"button","aria-label":`Move ${g.name} left`,disabled:w===0,onClick:()=>{let y=h.map((S)=>S.id),E=y[w-1];if(E!==void 0)[y[w-1],y[w]]=[g.id,E];n({...t,columnOrder:y})},children:"←"}),pe("button",{type:"button","aria-label":`Move ${g.name} right`,disabled:w===h.length-1,onClick:()=>{let y=h.map((S)=>S.id),E=y[w+1];if(E!==void 0)[y[w],y[w+1]]=[E,g.id];n({...t,columnOrder:y})},children:"→"})]},g.id))})]})]})}import{useEffect as Cu,useMemo as Us,useState as _s}from"react";import{jsx as La}from"react/jsx-runtime";function vu(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 xu(e,t,n){let o=n.unassigned??"Unassigned";if(t===null||t===void 0)return o;if(e?.type==="singleSelect")return e.options?.find((r)=>r.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 zs(e,t,n,o={},r={}){return n.map((i)=>{let l=t.groupBy.map((a)=>{let d=e.fields.find((u)=>u.id===a);return`${d?.name??a} ${xu(d,i.groups[a],r)}`}),s=t.aggregates.map((a)=>{let d=i.values[a.as];return`${o[a.as]??a.as}: ${typeof d==="number"||typeof d==="string"?String(d):r.none??"none"}`});return[...l,...s].join(" · ")})}function wu({descriptor:e,query:t,rows:n}){return La("ul",{"data-uibot":"collection-aggregate",children:zs(e,t,n).map((o)=>La("li",{children:o},o))})}function jo({collectionId:e,descriptor:t,view:n,groupBy:o,aggregates:r,client:i,locale:l,labels:s,reloadKey:a=0}){let d=Us(()=>gi(n,{aggregates:r,...o?{groupBy:o}:{}}),[n,o,r]),u=Us(()=>oe(l),[l]),[f,p]=_s(u("Loading summary…")),[c,C]=_s(!1);return Cu(()=>{let x=mi(t,d);if(x){p(u(vu(x))),C(!0);return}let h=!0;return p(u("Loading summary…")),C(!1),i.aggregate(e,d).then((g)=>{if(!h)return;if(!g.ok){p(g.error.message),C(!0);return}let w=zs(t,d,g.data,s??{},{unassigned:u("Unassigned"),checked:u("Checked"),unchecked:u("Unchecked"),none:u("none")});p(w.length?w.join(" · "):u("No summary rows.")),C(!1)}).catch(()=>{if(!h)return;p(u("The collection service is unavailable.")),C(!0)}),()=>{h=!1}},[i,e,t,d,s,u,a]),La("p",{role:c?"alert":"status","data-uibot":"collection-aggregate",children:f})}import{jsx as $o,jsxs as qs}from"react/jsx-runtime";function Mi(e,t){return Object.fromEntries(e?.items.flatMap((n)=>n.op==="update"&&n.id===t?Object.entries(n.values):[])??[])}function jr({fields:e,values:t,serverValues:n,locale:o}){let r=oe(o);return $o("div",{"data-uibot":"collection-field-changes",style:{display:"grid",gap:8,margin:"8px 0"},children:Object.entries(t).flatMap(([i,l])=>{let s=e.find((d)=>d.id===i);if(!s)return[];let a=(d)=>s.type==="checkbox"&&typeof d==="boolean"?r(d?"Checked":"Unchecked"):sn(d,s)||"—";return qs("div",{style:{border:"1px solid var(--border,#d5d9df)",borderRadius:6,padding:8},children:[$o("strong",{children:s.name}),n?qs("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"minmax(90px,auto) minmax(0,1fr)",gap:4},children:[$o("dt",{children:r("Your edit")}),$o("dd",{style:{margin:0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:a(l)}),$o("dt",{children:r("Server value")}),$o("dd",{style:{margin:0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:a(n[i])})]}):$o("p",{style:{margin:0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:a(l)})]},i)})})}import{jsx as Re,jsxs as Kt,Fragment as za}from"react/jsx-runtime";function mr(e){if(!e.aggregate)return null;return Re(jo,{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.aggregate.labels?{labels:e.aggregate.labels}:{},...e.locale?{locale:e.locale}:{},...e.reloadKey!==void 0?{reloadKey:e.reloadKey}:{}})}var _e={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},cn={padding:12,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)"},Oi={items:[],total:0,nextCursor:null,limit:50};function fr(e,t,n=!0){let o=JSON.stringify([e.descriptor.id,e.descriptor.schemaVersion,t]),[r,i]=tn({key:o,history:[]}),l=r.key===o?r.cursor:void 0,s=r.key===o?r.history:[],a=JSON.stringify([o,l]),[d,u]=tn(0),[f,p]=tn({key:a,page:Oi,loading:n,error:null});Li(()=>{let x=!0;if(!n){p({key:a,page:Oi,loading:!1,error:null});return}p((w)=>({key:a,page:w.key===a?w.page:Oi,loading:!0,error:null}));let[h,,g]=JSON.parse(o);return e.client.query(h,{...g,...l?{cursor:l}:{}}).then((w)=>{if(!x)return;if(w.ok)p({key:a,page:w.data,loading:!1,error:null});else p((y)=>({...y,loading:!1,error:w.error}))}).catch(()=>{if(x)p((w)=>({...w,loading:!1,error:{message:"Collection query failed. Retry to load records."}}))}),()=>{x=!1}},[a,o,l,e.client,e.reloadKey,n,d]);let c=f.key===a?f.page:Oi,C=f.key===a?f.error:null;return{page:c,loading:n&&(f.key!==a||f.loading),error:C?C.code?po(C,e.locale):oe(e.locale)(C.message):"",previous:s.length?()=>i({key:o,cursor:s.at(-1),history:s.slice(0,-1)}):void 0,next:c.nextCursor?()=>i({key:o,cursor:c.nextCursor??void 0,history:[...s,l]}):void 0,retry:()=>u((x)=>x+1),pageNumber:s.length+1}}function $r(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 Ba({hasPrevious:e,hasNext:t,onPrevious:n,onNext:o,loading:r,page:i,locale:l,ui:s}){let a=oe(l);if(!e&&!t)return null;return Kt("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[Re(Y,{ui:s,style:_e,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:a("Previous page"),disabled:!e||r,onClick:n}),i?Re("span",{style:{fontSize:12},children:a("Page {page}",{page:i})}):null,Re(Y,{ui:s,style:_e,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:a("Next page"),disabled:!t||r,onClick:o})]})}function yr({state:e,locale:t,ui:n,hideCount:o}){let r=oe(t);return Kt("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[o?null:Re("span",{children:$r(r,e.page.total,e.page.items.length,t)}),Re(Ba,{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&&Re("span",{role:"status",children:r("Loading records…")}),e.error&&Kt(za,{children:[Re("span",{role:"alert",children:e.error}),Re(Y,{ui:n,style:_e,variant:"outline",size:"sm",disabled:e.loading,onClick:e.retry,children:r("Retry query")})]})]})}function Va(e){let t=ci(e.client,e.descriptor.id),n=oe(e.locale),[o,r]=tn(!1),[i,l]=tn(""),[s,a]=tn(null),d=gr(null),u=gr(e);u.current=e;let f=(x)=>{if(!x||u.current.readOnly)return!1;let h=wt(u.current.features),g={insert:h.rowCreate,update:h.rowUpdate,delete:h.rowDelete};return x.items.every((w)=>g[w.op])};On({dirty:Boolean(d.current),busy:o});let p=()=>{d.current=null,l(""),a(null)};return{saving:o,error:i,setError:l,remote:s,pending:d,reset:p,commit:async(x)=>{if(o||!t.active||!f(x))return!1;d.current=x,r(!0),l(""),a(null);let h=await e.client.mutate(e.descriptor.id,x).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:n("Saving failed. Your change has been kept.")}}));if(!t.active)return!1;if(r(!1),h.ok)return p(),e.onCommitted(h.data),!0;l(Oo(h.error,e.locale));let g=h.error.details?.current;if(g&&typeof g.id==="string"&&Number.isSafeInteger(g.version)&&g.version>0)a(g);return!1},retryRequest:()=>d.current&&s?{idempotencyKey:crypto.randomUUID(),items:d.current.items.map((x)=>x.op!=="insert"&&x.id===s.id?{...x,expectedVersion:s.version}:x)}:d.current,canRetry:f(d.current),fields:mo(e.descriptor.fields,e.view)}}function Ua({mutation:e,onRetry:t,locale:n,ui:o}){let r=oe(n);return Kt(za,{children:[e.error&&Re("p",{role:"alert",children:e.error}),e.pending.current&&!e.canRetry&&Re("p",{role:"status",children:r("You do not have permission to make this change.")}),e.remote&&Kt("div",{style:cn,children:[Re("strong",{children:r("Current server version {version}",{version:e.remote.version})}),Re(jr,{fields:e.fields,values:Mi(e.pending.current,e.remote.id),serverValues:e.remote.values,locale:n}),Re(Y,{ui:o,style:_e,variant:"outline",size:"sm",disabled:e.saving||!e.canRetry,onClick:t,children:r("Retry against current version")})]})]})}function Zn({row:e,onClose:t,onCancel:n,onDirtyChange:o,onBusyChange:r,stickyActions:i,...l}){let s=oe(l.locale),a=wt(l.features),d=!l.readOnly&&a.rowDelete,u=!l.readOnly&&a.rowUpdate,f=gr(e.values),[p,c]=tn(()=>({...f.current})),[C,x]=tn(!1);On({dirty:JSON.stringify(p)!==JSON.stringify(f.current),busy:!1});let h=gr(null),[g,w]=tn(!1);Li(()=>{h.current?.focus()},[]);let y=Va(l),E=mo(l.descriptor.fields,l.view),S=JSON.stringify(p)!==JSON.stringify(e.values);Li(()=>{o?.(S)},[S,o]),Li(()=>{r?.(y.saving)},[y.saving,r]);let k=async(L=!1)=>{x(!0);try{let z=L?y.retryRequest():y.pending.current;if(!z){let G=E.filter((R)=>R.type!=="lookup"&&R.type!=="formula"&&R.type!=="rollup"&&JSON.stringify(p[R.id])!==JSON.stringify(e.values[R.id]));if(!G.length){y.setError(s("Change a field before saving."));return}let P=Hr(G,p,s,l.locale);z={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:e.id,expectedVersion:e.version,values:P}]}}if(await y.commit(z))t()}catch(z){y.setError(z instanceof Error?z.message:s("Invalid value"))}},O=async()=>{let L=y.pending.current?.items[0]?.op==="delete"?y.pending.current:{idempotencyKey:crypto.randomUUID(),items:[{op:"delete",id:e.id,expectedVersion:e.version}]};if(await y.commit(L))t()};return Kt("div",{ref:h,tabIndex:-1,onKeyDown:(L)=>{if(L.key==="Escape"&&!y.saving)L.stopPropagation(),(n??t)()},role:"dialog","aria-label":s("{name} record",{name:jt(e,l.descriptor.fields)}),style:{...cn,marginTop:12},children:[Re("h3",{children:jt(e,l.descriptor.fields)}),l.onInspectRecord&&Re(Y,{ui:l.ui,style:_e,variant:"outline",size:"sm",disabled:y.saving,onClick:()=>l.onInspectRecord?.(e.id),children:s("Open record activity")}),Kt("form",{onSubmit:(L)=>{L.preventDefault(),k()},children:[Re("fieldset",{disabled:y.saving||g||!u,style:{border:0,padding:0},children:Re(Ho,{fields:E,values:p,submitted:C,...l.locale?{locale:l.locale}:{},...l.ui?{ui:l.ui}:{},relationClient:l.client,getRelationOptions:l.getRelationOptions,linkedRecords:e.linkedRecords,computedErrors:e.computedErrors,onChange:(L)=>{c(L),y.reset()}})}),Kt("div",{"data-uibot":"record-editor-actions",style:i?{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:[u&&Re("button",{type:"submit",style:{..._e,...cr},disabled:y.saving||g,children:y.saving?s("Saving…"):s("Save record")}),i?null:Re("button",{type:"button",style:_e,disabled:y.saving,onClick:n??t,children:s("Close record")}),i&&d?Re("span",{style:{marginLeft:"auto"},children:Re(Y,{ui:l.ui,variant:"ghost",size:"sm",icon:"trash",disabled:y.saving,onClick:()=>w(!0),children:s("Delete record")})}):null]})]}),d&&!i&&Re("button",{type:"button",style:_e,disabled:y.saving,onClick:()=>w(!0),children:s("Delete record")}),g&&l.ui?.ConfirmDialog?l.ui.ConfirmDialog({open:!0,destructive:!0,title:s("Delete this record?"),description:s(d?"Delete this record? Your unsaved changes will be discarded after deletion.":"You do not have permission to make this change."),confirmLabel:s("Delete"),cancelLabel:s("Cancel"),busy:y.saving,confirmDisabled:!d,onConfirm:()=>void O(),onCancel:()=>{if(w(!1),y.pending.current?.items[0]?.op==="delete")y.reset()}}):null,g&&!l.ui?.ConfirmDialog&&Kt(Ai,{alert:!0,label:s("Confirm record deletion"),busy:y.saving,onCancel:()=>{if(w(!1),y.pending.current?.items[0]?.op==="delete")y.reset()},children:[Re("p",{children:s("Delete this record? Your unsaved changes will be discarded after deletion.")}),!d&&Re("p",{role:"status",children:s("You do not have permission to make this change.")}),Re("button",{type:"button",style:_e,disabled:y.saving||!d,onClick:()=>void O(),children:s("Confirm deletion")}),Re("button",{type:"button",style:_e,disabled:y.saving,onClick:()=>{if(w(!1),y.pending.current?.items[0]?.op==="delete")y.reset()},children:s("Cancel deletion")})]}),Re(Ua,{mutation:y,onRetry:()=>void k(!0),locale:l.locale,ui:l.ui})]})}function _a(e){let t=oe(e.locale),n=!e.readOnly&&wt(e.features).rowCreate,o=gr(null),r=mo(e.descriptor.fields,{...e.view,hiddenColumns:e.view.hiddenColumns.filter((h)=>!e.descriptor.fields.find((g)=>g.id===h)?.required)}),i=()=>({...Object.fromEntries(r.filter((h)=>h.type==="checkbox").map((h)=>[h.id,!1])),...Mr(r)}),l=gr(i()),[s,a]=tn(l.current),[d,u]=tn(!1),[f,p]=tn(!1);On({dirty:JSON.stringify(s)!==JSON.stringify(l.current),busy:!1});let c=Va(e),C=()=>o.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")?.focus(),x=async()=>{if(!n)return;p(!0);try{let h=c.pending.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:Hr(r,s,t,e.locale)}]};if(await c.commit(h))l.current=i(),a(l.current),u(!0),p(!1),requestAnimationFrame(C)}catch(h){c.setError(h instanceof Error?h.message:t("Invalid value"))}};return Kt("section",{"data-uibot":"collection-form",style:cn,children:[Re("h3",{children:e.view.name}),e.readOnly&&Re("p",{children:t("Record creation requires editor permission.")}),Kt("form",{ref:o,onSubmit:(h)=>{h.preventDefault(),x()},children:[Re("fieldset",{disabled:c.saving||!n,style:{border:0,padding:0},children:Re(Ho,{fields:r,values:s,submitted:f,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},relationClient:e.client,getRelationOptions:e.getRelationOptions,onChange:(h)=>{a(h),u(!1),c.reset()}})}),n&&Re("button",{type:"submit",style:{..._e,...cr},disabled:c.saving,children:c.saving?t("Creating…"):t("Create record")})]}),Re(Ua,{mutation:c,onRetry:()=>void x(),locale:e.locale,ui:e.ui}),d?Kt("p",{role:"status",children:[t("Record created. Add another below."),e.onShowRecords?Kt(za,{children:[" ",Re(Y,{ui:e.ui,style:_e,variant:"outline",size:"sm",onClick:e.onShowRecords,children:t("Show records")})]}):null]}):null]})}function Bi(e){let[t,n]=tn(null),o=Va(e),r=!e.readOnly&&wt(e.features).rowUpdate;return{intent:t,mutation:o,move:async(s,a)=>{if(!r||o.saving||t)return;n({row:s,values:a});let d={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:s.id,expectedVersion:s.version,values:a}]};if(await o.commit(d))n(null)},retry:async()=>{let s=o.retryRequest();if(s&&await o.commit(s))n(null)},cancel:()=>{n(null),o.reset()},blocked:o.saving||!!t}}function Vi({state:e,locale:t,ui:n}){let o=oe(t);if(!e.intent)return null;return Kt("div",{role:"dialog","aria-label":o("Pending record move"),style:cn,children:[Re("p",{children:e.mutation.saving?o("Moving record…"):o("The move has been kept for retry.")}),!e.mutation.remote&&Re(jr,{fields:e.mutation.fields,values:e.intent.values,locale:t}),Re(Ua,{mutation:e.mutation,onRetry:()=>void e.retry(),locale:t,ui:n}),!e.mutation.remote&&Re(Y,{ui:n,style:_e,variant:"outline",size:"sm",disabled:e.mutation.saving||!e.mutation.canRetry,onClick:()=>void e.retry(),children:o("Retry move")}),Re(Y,{ui:n,style:_e,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:e.cancel,children:o("Cancel move")})]})}import{useEffect as Ru,useMemo as js,useRef as Iu,useState as Au}from"react";var ku={"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"}},Pu={"zh-CN":{is:"恰好是",isNot:"不是恰好",contains:"包含任一",notContains:"不包含任一"},en:{is:"is exactly",isNot:"is not exactly",contains:"has any of",notContains:"has none of"}},Su={"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"}},Ui=(e,t="en",n)=>{if(n&&Cn(n)==="multipleSelect"){let o=Pu[t][e];if(o)return o}return ku[t][e]??e},_i=(e,t="en")=>Su[t][e]??e;function qa(e,t){if(!t)return"";let n=e?Rt(e):void 0;return n?Gn(t,{...n,time:"none"}):t}function Hs(e,t,n="en"){let o=n==="zh-CN";return e.filterSet.map((r)=>{if("filterSet"in r)return`(${Hs(r,t,n)})`;let i=t.find((d)=>d.id===r.fieldId),l=Ui(r.operator,n,i);if(r.operator==="isEmpty"||r.operator==="isNotEmpty")return`${i?.name??r.fieldId} ${l}`;let s=(d)=>i?.options?.find((u)=>u.id===d)?.name??String(d??""),a;if(ga(r.value)){let d=r.value,u=_i(d.mode,n);a=d.mode==="exactDate"?qa(i,d.date):d.mode==="dateRange"?`${qa(i,d.date)} ~ ${qa(i,d.to)}`:d.days!==void 0?u.replace("N",String(d.days)):u}else a=Array.isArray(r.value)?r.value.map(s).join(o?"、":", "):s(r.value);return`${i?.name??r.fieldId} ${l} ${a}`}).join(e.conjunction==="or"?o?" 或 ":" OR ":o?" 且 ":" AND ")}import{jsx as Be,jsxs as Un,Fragment as Gs}from"react/jsx-runtime";var Eu={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 br(e){return Be("span",{style:Ge.cell,children:Be(Xe,{...e})})}var zi=()=>`row_${Math.random().toString(36).slice(2,10)}`,Du=(e)=>("filterSet"in e),Tu=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}};function Ha(e,t){if(t)return Jl(e);let n=Cn(e);return n?Eu[n]??[]:[]}function ja(e,t,n){if(or.has(t))return;let o=Cn(e);if(o==="date"&&n)return{mode:"today",timeZone:Rt(e)?.timeZone??Tu()};if(o==="checkbox")return!0;if(o==="multipleSelect")return[];return o==="number"?void 0:""}function $s(e){let t=[],n=[];for(let o of e?.filterSet??[])if(Du(o))n.push({key:zi(),node:o});else t.push({key:zi(),fieldId:o.fieldId,operator:o.operator,value:o.value});return{rows:t,groups:n,conjunction:e?.conjunction??"and"}}function Ks(e,t,n,o){let r=[],i=!0;for(let a of t){let d=e.find((p)=>p.id===a.fieldId);if(!d||!a.operator){i=!1;continue}let u=a.value===""||Array.isArray(a.value)&&a.value.length===0;if(!or.has(a.operator)&&u){i=!1;continue}let f={fieldId:a.fieldId,operator:a.operator,...or.has(a.operator)?{}:{value:a.value}};if(Zl(d,f))i=!1;else r.push(f)}let l=n.map((a)=>a.node).filter((a)=>Boolean(a?.filterSet.length)),s=[...r,...l];return{node:s.length?{conjunction:o,filterSet:s}:void 0,complete:i}}function qi(e){let{ui:t,locale:n}=e,o=e.advanced!==!1,r=e.allowGroups!==!1,i=js(()=>oe(n),[n]),l=js(()=>e.fields.filter((x)=>!it(x)&&Cn(x)!==null),[e.fields]),[s,a]=Au(()=>$s(e.filter)),d=Iu(JSON.stringify(e.filter??null));Ru(()=>{let x=JSON.stringify(e.filter??null);if(x!==d.current)d.current=x,a($s(e.filter))},[e.filter]);let u=(x)=>{a(x);let{node:h}=Ks(l,x.rows,x.groups,x.conjunction),g=JSON.stringify(h??null);if(g!==d.current)d.current=g,e.onChange(h)},f=(x,h)=>u({...s,rows:s.rows.map((g)=>g.key===x?{...g,...h}:g)}),p=()=>{let x=l[0];if(!x)return;let h=Ha(x,o)[0]??"";u({...s,rows:[...s.rows,{key:zi(),fieldId:x.id,operator:h,value:h?ja(x,h,o):void 0}]})},c=()=>u({...s,groups:[...s.groups,{key:zi(),node:void 0}]}),C=Ks(l,s.rows,s.groups,s.conjunction).complete===!1||s.groups.some((x)=>x.node===void 0);return Un("div",{"data-uibot-filter-builder":"",style:Ge.root,children:[s.rows.length+s.groups.length>1?Un("div",{style:Ge.inline,children:[Be("span",{children:i("Match")}),Be(br,{ui:t,label:i("Filter conjunction"),style:Ge.control,value:s.conjunction,options:[{value:"and",label:i("all conditions")},{value:"or",label:i("any condition")}],onChange:(x)=>u({...s,conjunction:x==="or"?"or":"and"})})]}):null,s.rows.map((x,h)=>{let g=l.find((E)=>E.id===x.fieldId),w=g?Cn(g):null,y=g?Ha(g,o):[];return Un("fieldset",{"aria-label":i("Condition {index}",{index:h+1}),style:{...Ge.condition,margin:0,padding:0,border:0,minWidth:0},children:[Be("span",{style:Ge.slot,children:Be(br,{ui:t,label:i("Filter field"),style:Ge.control,value:x.fieldId,options:l.map((E)=>({value:E.id,label:E.name})),onChange:(E)=>{let S=l.find((z)=>z.id===E);if(!S)return;let k=Ha(S,o),O=k.includes(x.operator)?x.operator:k[0]??"",L=Cn(S)===w;f(x.key,{fieldId:E,operator:O,value:O&&!(L&&O===x.operator)?ja(S,O,o):x.value})}})}),Be("span",{style:Ge.slot,children:Be(br,{ui:t,label:i("Filter operator"),style:Ge.control,value:x.operator,options:y.map((E)=>({value:E,label:Ui(E,n??"en",g)})),onChange:(E)=>{if(!g)return;let S=E;f(x.key,{operator:S,value:ja(g,S,o)})}})}),g&&x.operator&&!or.has(x.operator)?Be("span",{style:Ge.slot,children:Be(Fu,{field:g,row:x,advanced:o,t:i,props:e,onValue:(E)=>f(x.key,{value:E})})}):null,Be(Y,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:i("Remove condition {index}",{index:h+1}),title:i("Remove condition {index}",{index:h+1}),style:{flex:"0 0 auto"},onClick:()=>u({...s,rows:s.rows.filter((E)=>E.key!==x.key)})})]},x.key)}),r?s.groups.map((x,h)=>Un("fieldset",{"aria-label":i("Condition group {index}",{index:h+1}),style:Ge.group,children:[Un("div",{style:Ge.groupHead,children:[Be("strong",{style:{fontSize:13},children:i("Condition group {index}",{index:h+1})}),Be(Y,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:i("Remove group {index}",{index:h+1}),title:i("Remove group {index}",{index:h+1}),onClick:()=>u({...s,groups:s.groups.filter((g)=>g.key!==x.key)})})]}),Be(qi,{fields:e.fields,filter:x.node,allowGroups:!1,advanced:o,...n?{locale:n}:{},...t?{ui:t}:{},...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},onChange:(g)=>u({...s,groups:g?s.groups.map((w)=>w.key===x.key?{...w,node:g}:w):s.groups.filter((w)=>w.key!==x.key)})})]},x.key)):s.groups.length?Un("p",{style:Ge.hint,children:[i("{count} grouped conditions are kept.",{count:s.groups.length})," ",Be(Y,{ui:t,variant:"ghost",size:"sm",onClick:()=>u({...s,groups:[]}),children:i("Remove")})]}):null,C?Be("p",{role:"status",style:Ge.hint,children:i("Finish the highlighted condition to apply it.")}):null,Un("div",{style:Ge.inline,children:[Be(Y,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:l.length===0,onClick:p,children:i("Add condition")}),r?Be(Y,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:l.length===0,onClick:c,children:i("Add group")}):null,s.rows.length||s.groups.length?Be(Y,{ui:t,variant:"ghost",size:"sm",onClick:()=>u({rows:[],groups:[],conjunction:"and"}),children:i("Clear filter")}):null]})]})}function Fu({field:e,row:t,advanced:n,t:o,props:r,onValue:i}){let{ui:l}=r,s=Cn(e),a=o("Filter value"),d=(u,f,p,c)=>r.renderCellEditor?.({...r.getRelationOptions?{getRelationOptions:r.getRelationOptions}:{},field:{...e,...c,required:!1},text:u,disabled:!1,mode:"filter",label:p,autoOpen:!1,onChange:f,onSave:()=>{},onCancel:()=>f("")});if(s==="number")return Be("input",{"aria-label":a,type:"number",step:"any",style:Ge.control,value:typeof t.value==="number"?String(t.value):"",onChange:(u)=>{let f=u.currentTarget.value;i(f===""||!Number.isFinite(Number(f))?void 0:Number(f))}});if(s==="text")return Be("input",{"aria-label":a,style:Ge.control,value:typeof t.value==="string"?t.value:"",onChange:(u)=>i(u.currentTarget.value)});if(s==="checkbox")return Be(br,{ui:l,label:a,style:Ge.control,value:t.value===!1?"false":"true",options:[{value:"true",label:o("Yes")},{value:"false",label:o("No")}],onChange:(u)=>i(u==="true")});if(s==="singleSelect"||s==="multipleSelect"){let u=Array.isArray(t.value)?t.value.join(","):typeof t.value==="string"?t.value:"",f=d(u,(c)=>i(s==="multipleSelect"?c.split(",").filter(Boolean):c),a);if(f)return f;if(s==="singleSelect")return Be(br,{ui:l,label:a,style:Ge.control,value:u,options:[{value:"",label:o("Choose option")},...(e.options??[]).map((c)=>({value:c.id,label:c.name}))],onChange:i});let p=new Set(u.split(",").filter(Boolean));return Be("fieldset",{"aria-label":a,style:{...Ge.inline,margin:0,padding:0,border:0},children:(e.options??[]).map((c)=>Un("label",{style:Ge.inline,children:[Be("input",{type:"checkbox",checked:p.has(c.id),onChange:(C)=>{let x=new Set(p);if(C.currentTarget.checked)x.add(c.id);else x.delete(c.id);i([...x])}}),c.name]},c.id))})}if(s==="relation"){let u=typeof t.value==="string"?t.value:"";return d(u,i,a)??Be(_o,{field:e,value:u,onChange:i,label:a,getOptions:r.getRelationOptions,locale:r.locale})}if(s==="date"){if(!n||typeof t.value==="string"){let u=typeof t.value==="string"?t.value:"";return d(u,i,a)??Be("input",{"aria-label":a,type:"date",style:Ge.control,value:u.slice(0,10),onChange:(f)=>i(f.currentTarget.value)})}return Be(Nu,{field:e,value:t.value,t:o,props:r,custom:d,onValue:i})}return null}function Nu({field:e,value:t,t:n,props:o,custom:r,onValue:i}){let l=t??{mode:"today"},s=(u)=>i({...l,...u}),a=(u,f,p)=>r(f??"",(c)=>p(c.slice(0,10)),u,{formatting:{date:"YYYY-MM-DD",time:"none"}})??Be("input",{"aria-label":u,type:"date",style:Ge.control,value:f??"",onChange:(c)=>p(c.currentTarget.value)}),d=(u)=>{let{date:f,to:p,days:c,...C}=l;i({...C,mode:u,...bi.has(u)?{days:7}:{}})};return Un(Gs,{children:[Be(br,{ui:o.ui,label:n("Date mode"),style:Ge.control,value:l.mode,options:pa.map((u)=>({value:u,label:_i(u,o.locale??"en")})),onChange:(u)=>d(u)}),l.mode==="exactDate"?a(n("Filter value"),l.date,(u)=>s({date:u})):null,l.mode==="dateRange"?Un(Gs,{children:[a(n("From date"),l.date,(u)=>s({date:u})),a(n("To date"),l.to,(u)=>s({to:u}))]}):null,bi.has(l.mode)?Be("input",{"aria-label":n("Number of days"),type:"number",min:0,step:1,style:{...Ge.control,width:84},value:l.days??"",onChange:(u)=>{let f=u.currentTarget.value;if(f===""){let{days:p,...c}=l;i(c)}else s({days:Number(f)})}}):null,Be("span",{style:Ge.hint,children:Rt(e)?.timeZone??l.timeZone??""})]})}var Ws="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",Ge={group:{margin:0,minWidth:0,display:"grid",gap:8,padding:10,border:`1px solid ${Ws}`,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 ${Ws}`,borderRadius:6,background:"transparent",color:"inherit",font:"inherit"},hint:{margin:0,fontSize:12,opacity:0.7}};import{jsx as tt,jsxs as Qn,Fragment as Ou}from"react/jsx-runtime";var $a={display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},Ka={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 Hi({fields:e,view:t,onChange:n,locale:o,ui:r,editor:i}){return tt("div",{"data-uibot-view-filter":"",children:tt(qi,{fields:e,filter:t.filter,locale:o,ui:r,renderCellEditor:i?.renderCellEditor,getRelationOptions:i?.getRelationOptions,advanced:i?.advanced,onChange:(l)=>{if(l)n({...t,filter:l});else{let{filter:s,...a}=t;n(a)}}})})}var Mu=10;function ji({fields:e,view:t,onChange:n,locale:o,ui:r}){let i=oe(o),l=t.sort??[],s=e.filter((f)=>ln(f)),a=s.filter((f)=>!l.some((p)=>p.fieldId===f.id)),d=(f)=>{if(f.length)n({...t,sort:f});else{let{sort:p,...c}=t;n(c)}},u=(f,p)=>{let c=[...l],[C]=c.splice(f,1);if(C)c.splice(f+p,0,C);d(c)};return Qn("div",{"data-uibot-view-sort":"",style:{display:"grid",gap:8},children:[l.map((f,p)=>Qn("fieldset",{"aria-label":i("Sort {index}",{index:p+1}),style:{...$a,margin:0,padding:0,border:0,minWidth:0},children:[tt("span",{style:{flex:"1 1 120px",minWidth:110,display:"flex"},children:tt(Xe,{ui:r,label:i("Sort field"),style:Ka,value:f.fieldId,options:s.filter((c)=>c.id===f.fieldId||a.includes(c)).map((c)=>({value:c.id,label:c.name})),onChange:(c)=>d(l.map((C,x)=>x===p?{...C,fieldId:c}:C))})}),tt("span",{style:{flex:"0 1 110px",minWidth:90,display:"flex"},children:tt(Xe,{ui:r,label:i("Sort direction"),style:Ka,value:f.direction,options:[{value:"asc",label:i("Ascending")},{value:"desc",label:i("Descending")}],onChange:(c)=>d(l.map((C,x)=>x===p?{...C,direction:c}:C))})}),tt(Y,{ui:r,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:p===0,ariaLabel:i("Move sort {index} up",{index:p+1}),title:i("Move sort {index} up",{index:p+1}),onClick:()=>u(p,-1),children:" "}),tt(Y,{ui:r,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:p===l.length-1,ariaLabel:i("Move sort {index} down",{index:p+1}),title:i("Move sort {index} down",{index:p+1}),onClick:()=>u(p,1),children:" "}),tt(Y,{ui:r,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:i("Remove sort {index}",{index:p+1}),title:i("Remove sort {index}",{index:p+1}),onClick:()=>d(l.filter((c,C)=>C!==p)),children:" "})]},f.fieldId)),Qn("div",{style:$a,children:[tt(Y,{ui:r,variant:"outline",size:"sm",icon:"plus",disabled:a.length===0||l.length>=Mu,onClick:()=>{let f=a[0];if(f)d([...l,{fieldId:f.id,direction:"asc"}])},children:i("Add sort")}),l.length?tt(Y,{ui:r,variant:"ghost",size:"sm",onClick:()=>d([]),children:i("Clear sort")}):tt("span",{style:{fontSize:12,opacity:0.7},children:i("Default order")})]})]})}function Ys({fields:e,view:t,onChange:n,locale:o,ui:r,bare:i}){let l=oe(o),a=[...t.columnOrder.flatMap((f)=>{let p=e.find((c)=>c.id===f);return p?[p]:[]}),...e.filter((f)=>!t.columnOrder.includes(f.id))],d=(f,p)=>{let c=a.map((h)=>h.id),C=c[f],x=c[f+p];if(C===void 0||x===void 0)return;c[f]=x,c[f+p]=C,n({...t,columnOrder:c})},u=Qn("div",{style:{display:"grid",gap:6,paddingTop:i?0:6,minWidth:0},children:[Qn("label",{children:[tt("input",{type:"checkbox",checked:t.showRowNumber!==!1,onChange:(f)=>n({...t,showRowNumber:f.currentTarget.checked})})," ",l("Show row numbers")]}),Qn("label",{children:[tt("input",{type:"checkbox",checked:t.showRecordId===!0,onChange:(f)=>n({...t,showRecordId:f.currentTarget.checked})})," ",l("Show record IDs")]}),a.map((f,p)=>{let c=!t.hiddenColumns.includes(f.id),C=`${f.name}${f.required?" *":""}`;return Qn("div",{style:{...$a,flexWrap:"nowrap",gap:4},children:[tt(Y,{ui:r,variant:"ghost",size:"sm",icon:c?"eye":"eyeOff",iconOnly:!0,disabled:t.type==="form"&&f.required===!0,ariaLabel:C,title:l(c?"Hide {name}":"Show {name}",{name:f.name}),onClick:()=>n({...t,hiddenColumns:c?[...t.hiddenColumns,f.id]:t.hiddenColumns.filter((x)=>x!==f.id)})}),tt("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:c?1:0.5},children:C}),tt(Y,{ui:r,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:p===0,ariaLabel:l("Move {name} left",{name:f.name}),onClick:()=>d(p,-1)}),tt(Y,{ui:r,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:p===a.length-1,ariaLabel:l("Move {name} right",{name:f.name}),onClick:()=>d(p,1)})]},f.id)})]});if(i)return tt("div",{"data-uibot-view-columns":"",children:u});return Qn("details",{"data-uibot-view-columns":"",children:[tt("summary",{children:l("Columns")}),u]})}function $i({fields:e,view:t,onChange:n,locale:o,ui:r}){let i=oe(o),l=e.filter((s)=>s.type==="singleSelect"||s.type==="checkbox");return tt("div",{style:{display:"flex",gap:6,alignItems:"center"},children:t.groupByFieldId?Qn(Ou,{children:[tt(ve,{name:"group"}),tt(Xe,{ui:r,label:i("Grid grouping field"),style:Ka,value:t.groupByFieldId,options:l.map((s)=>({value:s.id,label:s.name})),onChange:(s)=>n({...t,groupByFieldId:s})}),tt(Y,{ui:r,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:i("Remove grouping"),onClick:()=>{let s={...t};delete s.groupByFieldId,n(s)}})]}):tt(Y,{ui:r,variant:"outline",size:"sm",icon:"plus",onClick:()=>{let s=l[0];if(s)n({...t,groupByFieldId:s.id})},children:i("Add grouping")})})}import{useState as Kr}from"react";import{jsx as bt,jsxs as vo}from"react/jsx-runtime";var Wr={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"}},Zs="table";function Ki({icon:e,size:t=15,icons:n=Wr}){let o=(e?n[e]:void 0)??n[Zs]??Wr.table;return bt("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:bt("path",{d:o?.path??""})})}function Wa(e){let t=oe(e.locale);return vo("aside",{"data-uibot-table-list":"",style:Ko.root,children:[vo("div",{style:Ko.title,children:[bt("span",{children:t("Tables")}),bt("span",{children:e.tables.length})]}),bt("nav",{"aria-label":t("Tables"),style:Ko.nav,children:e.tables.map((n)=>vo("button",{type:"button","aria-current":n.id===e.activeId?"page":void 0,onClick:()=>e.onSelect(n.id),style:{...Ko.item,...n.id===e.activeId?Ko.active:{}},children:[bt(Ki,{icon:n.icon,icons:e.icons??Wr}),bt("span",{style:Ko.name,children:n.name})]},n.id))}),e.onCreate?bt(Y,{ui:e.ui,variant:"ghost",style:Ko.create,disabled:e.createDisabled,onClick:e.onCreate,children:t("New table")}):null]})}function Ga(e){let t=oe(e.locale),n=e.icons??Wr,[o,r]=Kr(!1),[i,l]=Kr(""),[s,a]=Kr(!1),[d,u]=Kr(!1),[f,p]=Kr(""),c=e.table,C=e.canManage&&Boolean(c)&&!d;async function x(y){u(!0),p("");try{return await y(),!0}catch(E){return p(E instanceof Error?E.message:t("Saving failed. Your edit has been kept.")),!1}finally{u(!1)}}let h=()=>{if(!C||!e.onRename)return;l(c?.name??""),p(""),r(!0)};async function g(){let y=i.trim();if(!y||y===c?.name){r(!1);return}if(await x(()=>e.onRename?.(y)))r(!1)}let w=(y)=>{if(y.key==="Enter"||y.key==="F2")y.preventDefault(),h()};return vo("header",{"data-uibot-table-header":"",style:kn.root,children:[vo("div",{style:kn.left,children:[vo("span",{style:{position:"relative"},children:[bt("button",{type:"button","aria-label":t("Change table icon"),"aria-haspopup":"menu","aria-expanded":s,title:e.canManage?t("Double click to change the icon"):t("Schema permission required"),disabled:!C||!e.onIconChange,style:kn.iconButton,onDoubleClick:()=>a(!0),onKeyDown:(y)=>{if(y.key==="Enter"||y.key===" ")y.preventDefault(),a(!0)},children:bt(Ki,{icon:c?.icon,size:17,icons:n})}),s?bt("div",{role:"menu","aria-label":t("Table icon"),style:kn.menu,children:Object.entries(n).map(([y,E])=>vo("button",{type:"button",role:"menuitemradio","aria-checked":(c?.icon??Zs)===y,title:E.label,style:kn.menuItem,onClick:()=>{a(!1),x(()=>e.onIconChange?.(y))},children:[bt(Ki,{icon:y,icons:n}),bt("span",{children:E.label})]},y))}):null]}),vo("div",{style:{minWidth:0},children:[o?bt("input",{"aria-label":t("Table name"),value:i,disabled:d,style:kn.input,autoFocus:!0,onChange:(y)=>l(y.currentTarget.value),onBlur:()=>{if(!f)g()},onKeyDown:(y)=>{if(y.key==="Enter")y.preventDefault(),g();if(y.key==="Escape")y.preventDefault(),r(!1),p("")}}):bt("h2",{style:kn.title,children:bt("button",{type:"button","aria-label":t("Rename table {name}",{name:c?.name??""}),title:e.canManage?t("Double click to rename"):t("Schema permission required"),disabled:!C||!e.onRename,style:kn.titleButton,onDoubleClick:h,onKeyDown:w,children:c?.name??t("Start with a table")})}),f?bt("p",{role:"alert",style:kn.error,children:f}):null,bt("p",{style:kn.summary,children:c?t("{count} fields · {mode}",{count:c.fields.length,mode:e.canWrite?t("Editable"):t("Read only")}):t("Start with a table")})]})]}),bt("div",{style:kn.actions,children:e.actions})]})}var Js="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",Ko={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%"}},kn={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 ${Js}`,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 ${Js}`,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 Ya,useMemo as Ja,useRef as Wo,useState as hr}from"react";import{jsx as xo,jsxs as Za}from"react/jsx-runtime";function Qa(e,t){if(!t)return"";let n=e.fields.find((r)=>r.id==="title")??e.fields[0],o=n?t.values[n.id]:void 0;return typeof o==="string"?o.trim():""}function Xa(e){let t=Ja(()=>oe(e.locale),[e.locale]),n=ci(e.client,e.descriptor.id),o=Wo(null);if(o.current===null)o.current=Mr(e.descriptor.fields);let[r,i]=hr(o.current),[l,s]=hr(!1),a=Ja(()=>({client:e.client,descriptor:e.descriptor}),[e.client,e.descriptor]),d=Wo(a);d.current=a;let u=Wo(!0);Ya(()=>(u.current=!0,()=>{u.current=!1}),[]);let[f,p]=hr(),c=Ja(()=>{let M=new Map,N=(I,B)=>{if(!u.current||d.current!==a)return;p((v)=>({scope:a,targets:{...v?.scope===a?v.targets:{},[I]:B}}))};return{query:async(...I)=>{let B=I[0],v=(M.get(B)??0)+1;M.set(B,v),N(B,!1);try{let K=await e.client.query(...I);if(M.get(B)===v)N(B,K.ok);return K}catch(K){if(M.get(B)===v)N(B,!1);throw K}}}},[e.client,a]),C=e.descriptor.fields.some((M)=>M.type==="linkedRecord"&&(!M.link||f?.scope!==a||!f.targets[M.link.collectionId])),[x,h]=hr(null),g=Wo(null),w=Wo(!1),y=Wo(null),E=Wo(null),{autoFocus:S}=e;Ya(()=>{if(x?.error)E.current?.focus()},[x]);let[k,O]=hr(!1),[L,z]=hr(!1),G=JSON.stringify(r)!==JSON.stringify(o.current)||k;On({dirty:G,busy:l},e);let P=()=>y.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled])")?.focus();Ya(()=>{if(S)P()},[S]);async function R(M){if(w.current||e.readOnly||C)return;z(!0);let N;try{N=Hr(e.descriptor.fields,r,t,e.locale)}catch(B){h({text:B instanceof Error?B.message:t("Invalid value"),error:!0,clearable:!0});return}w.current=!0,s(!0),h(null);let I=g.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:N}]};g.current=I;try{let B=await e.client.mutate(e.descriptor.id,I);if(!n.active)return;if(!B.ok){let K=B.error.code==="validation";O(!K),h({text:Oo(B.error,e.locale),error:!0,clearable:K});return}g.current=null,O(!1),z(!1),o.current=Mr(e.descriptor.fields),i(o.current),e.onCommitted(B.data);let v=Qa(e.descriptor,B.data.items[0]);if(h({text:`${M?t("Record saved, keep adding"):t("Record saved")}${v?`:${v}`:""}`,error:!1,clearable:!1}),M)requestAnimationFrame(P);else e.onSaved?.(B.data)}catch{if(!n.active)return;O(!0),h({text:t("Saving failed. Your draft has been kept."),error:!0,clearable:!1})}finally{w.current=!1,s(!1)}}return Za("form",{ref:y,noValidate:!0,"aria-label":t("New record form"),"data-uibot":"record-creator",onSubmit:(M)=>{M.preventDefault();let N=M.nativeEvent.submitter;R(N?.getAttribute("data-continue")==="true")},onKeyDown:(M)=>{if(M.key==="Enter"&&(M.ctrlKey||M.metaKey)&&!M.nativeEvent.isComposing&&!l)M.preventDefault(),M.currentTarget.requestSubmit()},children:[xo("fieldset",{disabled:l||e.readOnly,style:_n.fields,children:xo(Ho,{fields:e.descriptor.fields,values:r,submitted:L,relationClient:c,getRelationOptions:e.getRelationOptions,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},onChange:(M)=>{if(i(M),g.current=null,O(!1),x?.clearable)h(null)}})}),x?xo("p",{ref:E,role:x.error?"alert":"status",tabIndex:-1,style:x.error?_n.error:_n.status,children:x.text}):null,Za("div",{"data-uibot":"record-creator-actions",style:e.stickyActions?{..._n.actions,..._n.sticky}:_n.actions,children:[Za("span",{style:_n.hint,children:[xo("kbd",{children:"Ctrl / ⌘"})," + ",xo("kbd",{children:"Enter"})," ",t("Save")]}),xo("button",{type:"submit","aria-label":t("Save new record"),"aria-busy":l,disabled:l||e.readOnly||C,style:{..._n.button,...cr},children:l?t("Saving…"):t("Save new record")}),xo("button",{type:"submit","data-continue":"true",disabled:l||e.readOnly||C,style:_n.button,children:t("Save and continue")}),e.onCancel&&!e.stickyActions?xo(Y,{ui:e.ui,style:_n.button,disabled:l,onClick:e.onCancel,children:t("Cancel adding")}):null]})]})}var _n={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 qu,useLayoutEffect as Hu,useRef as Gr}from"react";import{jsx as Cr}from"react/jsx-runtime";var Qs=[["#e8f0fe","#1a56c4"],["#e6f4ea","#1e7a3c"],["#fdecea","#b3261e"],["#fff1e0","#a05a00"],["#e8eaed","#3c4043"],["#e0f2f1","#00695c"],["#f3e8fd","#6a1b9a"]];function Pn(e){let t=Math.max(e,0)%Qs.length,[n,o]=Qs[t]??["#e8eaed","#3c4043"];return{background:`var(--uibot-chip-${t}-bg, ${n})`,color:`var(--uibot-chip-${t}-fg, ${o})`}}function el({index:e,children:t}){return Cr("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",...Pn(e)},children:t})}function Go({ids:e,field:t,wrap:n}){let o=t.options??[];return Cr("span",{style:{display:"inline-flex",gap:4,alignItems:"center",maxWidth:"100%",overflow:"hidden",...n?{flexWrap:"wrap"}:{}},children:e.map((r)=>{let i=o.findIndex((l)=>l.id===r);return Cr(el,{index:Or(o,r),children:o[i]?.name??String(r)},String(r))})})}function ed({checked:e,label:t,onToggle:n}){return Cr("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 Xs={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",hyperlink:"M9 3h4v4M13 3 7.5 8.5M11 9.5V13H3V5h3.5",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 Wi({type:e}){return Cr("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:Cr("path",{d:Xs[e]??Xs.singleLineText})})}var se={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 ct,jsxs as gt,Fragment as tl}from"react/jsx-runtime";var Lu=["YYYY-MM-DD","YYYY/MM/DD","MM/DD/YYYY","DD/MM/YYYY","YYYY年M月D日"],Bu=["Asia/Shanghai","Asia/Hong_Kong","Asia/Tokyo","Asia/Singapore","Europe/London","Europe/Paris","America/New_York","America/Los_Angeles","UTC"],Vu=["CNY","USD","EUR","JPY","GBP","HKD"],Uu=[0,1,2,3,4,5,6,7,8],_u={date:"YYYY-MM-DD",time:"none"},zu={kind:"decimal",precision:0,grouping:!0};function td({field:e,onChange:t,disabled:n,locale:o,ui:r,settings:i,dateFormatLocked:l}){let s=i?.formatting!==!1,a=i?.defaults!==!1,d=oe(o),u=(c)=>t((C)=>({...C,...c})),f=()=>t((c)=>{let{defaultValue:C,...x}=c;return x}),p=(c,C,x,h,g=!1)=>gt("div",{style:se.control,children:[ct("span",{style:se.label,children:c}),ct(Xe,{ui:r,label:c,style:se.input,disabled:n||g,value:C,options:x,onChange:h})]});if(e.type==="date"){let c=Rt(e)??_u,C=(h)=>{let{timeZone:g,...w}=c,y={...w,...g?{timeZone:g}:{},...h};if(h.timeZone==="")delete y.timeZone;u({formatting:y})},x=c.time!=="none";if(!s&&!a)return null;return gt("fieldset",{style:se.settings,"aria-label":d("Format of field {name}",{name:e.name}),children:[s?gt(tl,{children:[ct("strong",{style:{fontSize:13},children:d("Format")}),gt("div",{style:se.row,children:[p(d("Date format"),c.date,Lu.map((h)=>({value:h,label:h})),(h)=>C({date:h}),Boolean(l)),p(d("Time format"),c.time,[{value:"none",label:d("No time (date only)")},{value:"24h",label:d("24-hour")},{value:"12h",label:d("12-hour")}],(h)=>C({time:h}),Boolean(l)),x?p(d("Time zone"),c.timeZone??"",[{value:"",label:d("Viewer's time zone")},...Bu.map((h)=>({value:h,label:h}))],(h)=>C({timeZone:h}),Boolean(l)):null]}),gt("p",{style:{...se.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[d("Preview"),": ",Gn(new Date().toISOString(),c)]})]}):null,a&&p(d("Default value"),e.defaultValue?.kind==="now"?"now":"",[{value:"",label:d("Empty")},{value:"now",label:x?d("Current date and time"):d("Today")}],(h)=>h==="now"?u({defaultValue:{kind:"now"}}):f())]})}if(e.type==="number"){let c=Lo(e)??zu,C=(h)=>u({formatting:{...c,...h}}),x=e.defaultValue?.kind==="value"?String(e.defaultValue.value):"";if(!s&&!a)return null;return gt("fieldset",{style:se.settings,"aria-label":d("Format of field {name}",{name:e.name}),children:[s?gt(tl,{children:[ct("strong",{style:{fontSize:13},children:d("Format")}),gt("div",{style:se.row,children:[p(d("Number style"),c.kind,[{value:"decimal",label:d("Number")},{value:"percent",label:d("Percent")},{value:"currency",label:d("Currency")}],(h)=>C({kind:h})),p(d("Decimal places"),String(c.precision),Uu.map((h)=>({value:String(h),label:String(h)})),(h)=>C({precision:Number(h)})),c.kind==="currency"?p(d("Currency"),c.currency??"CNY",Vu.map((h)=>({value:h,label:h})),(h)=>C({currency:h})):null]}),gt("label",{style:se.checkbox,children:[ct("input",{type:"checkbox","aria-label":d("Thousands separator"),checked:c.grouping!==!1,disabled:n,onChange:(h)=>C({grouping:h.currentTarget.checked})}),d("Thousands separator")]}),gt("p",{style:{...se.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[d("Preview"),":"," ",Bo(c.kind==="percent"?0.1234:1234.5678,c)]})]}):null,a&&gt("label",{style:se.control,children:[ct("span",{style:se.label,children:d("Default value")}),ct("input",{"aria-label":d("Default value"),style:se.input,type:"number",step:"any",disabled:n,value:x,onChange:(h)=>{let g=h.currentTarget.value;if(g===""||!Number.isFinite(Number(g)))f();else u({defaultValue:{kind:"value",value:Number(g)}})}})]})]})}if(!a)return null;if(e.type==="singleLineText"||e.type==="longText")return ct("fieldset",{style:se.settings,"aria-label":d("Defaults of field {name}",{name:e.name}),children:gt("label",{style:se.control,children:[ct("span",{style:se.label,children:d("Default value")}),ct("input",{"aria-label":d("Default value"),style:se.input,disabled:n,value:e.defaultValue?.kind==="value"?String(e.defaultValue.value):"",onChange:(c)=>{let C=c.currentTarget.value;if(C==="")f();else u({defaultValue:{kind:"value",value:C}})}})]})});if(e.type==="checkbox")return ct("fieldset",{style:se.settings,"aria-label":d("Defaults of field {name}",{name:e.name}),children:gt("label",{style:se.checkbox,children:[ct("input",{type:"checkbox","aria-label":d("Checked by default"),checked:e.defaultValue?.kind==="value"&&e.defaultValue.value===!0,disabled:n,onChange:(c)=>c.currentTarget.checked?u({defaultValue:{kind:"value",value:!0}}):f()}),d("Checked by default")]})});if((e.type==="singleSelect"||e.type==="multipleSelect")&&(e.options?.length??0)>0){let c=e.options??[],C=e.defaultValue?.kind==="value"?e.defaultValue.value:void 0;if(e.type==="singleSelect")return ct("fieldset",{style:se.settings,"aria-label":d("Defaults of field {name}",{name:e.name}),children:p(d("Default value"),typeof C==="string"?C:"",[{value:"",label:d("Empty")},...c.map((h)=>({value:h.id,label:h.name}))],(h)=>h?u({defaultValue:{kind:"value",value:h}}):f())});let x=Array.isArray(C)?C:[];return gt("fieldset",{style:se.settings,"aria-label":d("Defaults of field {name}",{name:e.name}),children:[ct("span",{style:se.label,children:d("Default value")}),c.map((h)=>gt("label",{style:se.checkbox,children:[ct("input",{type:"checkbox","aria-label":d("Default option {name}",{name:h.name}),checked:x.includes(h.id),disabled:n,onChange:(g)=>{let w=g.currentTarget.checked?[...x,h.id]:x.filter((y)=>y!==h.id);if(w.length)u({defaultValue:{kind:"value",value:w}});else f()}}),h.name]},h.id))]})}return null}function nd({field:e,fields:t,onChange:n,disabled:o,locale:r}){let i=oe(r);if(!Fr.has(e.type))return null;let l=e.ai,s=t.filter((u)=>u.id!==e.id&&u.type!=="blob"&&u.type!=="lookup"),a=l?.sourceFieldIds??[],d=(u)=>n((f)=>{if(u)return{...f,ai:u};let{ai:p,...c}=f;return c});return gt("fieldset",{style:se.settings,"aria-label":i("AI settings of field {name}",{name:e.name}),children:[gt("label",{style:se.checkbox,children:[ct("input",{type:"checkbox",checked:Boolean(l),disabled:o,onChange:(u)=>d(u.currentTarget.checked?{prompt:""}:void 0)}),i("Generate this field with AI")]}),l?gt(tl,{children:[gt("label",{style:se.control,children:[ct("span",{style:se.label,children:i("AI prompt")}),ct("textarea",{"aria-label":i("AI prompt"),style:{...se.input,minHeight:72,resize:"vertical"},rows:3,maxLength:ca,placeholder:i("e.g. Summarize the description in one sentence"),value:l.prompt,disabled:o,onChange:(u)=>{let f=u.currentTarget.value;n((p)=>({...p,ai:{...p.ai,prompt:f}}))}})]}),gt("label",{style:se.checkbox,children:[ct("input",{type:"checkbox",checked:Boolean(l.autoFill),disabled:o,onChange:(u)=>{let f=u.currentTarget.checked;n((p)=>{let{autoFill:c,...C}=p.ai??{prompt:""};return{...p,ai:f?{...C,autoFill:!0}:C}})}}),i("Generate when a record is created")]}),ct("span",{style:se.label,children:i("Fields the AI reads (none = all)")}),ct("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px"},children:s.map((u)=>gt("label",{style:se.checkbox,children:[ct("input",{type:"checkbox","aria-label":i("AI reads {name}",{name:u.name}),checked:a.includes(u.id),disabled:o,onChange:(f)=>{let p=f.currentTarget.checked;n((c)=>{let C=c.ai?.sourceFieldIds??[],x=p?[...C,u.id]:C.filter((w)=>w!==u.id),{sourceFieldIds:h,...g}=c.ai??{prompt:""};return{...c,ai:x.length?{...g,sourceFieldIds:x}:g}})}}),u.name]},u.id))})]}):null]})}import{jsx as nt,jsxs as un}from"react/jsx-runtime";var nl=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],od=(e)=>e==="singleSelect"||e==="multipleSelect";function ju(e,t){let n=t.slice(0,ui);if(!n.trim()){let{description:o,...r}=e;return r}return{...e,description:n}}function Yr({fields:e,onChange:t,disabled:n=!1,focusFieldId:o,locale:r,ui:i,fieldTypes:l=nl,relationTargets:s=[],lockedFieldIds:a=[],settings:d,single:u=!1,contextFields:f}){let p=oe(r),c={singleLineText:p("Single line text"),longText:p("Long text"),number:p("Number"),checkbox:p("Checkbox"),date:p("Date"),singleSelect:p("Single select"),multipleSelect:p("Multiple select"),relation:p("Linked record"),hyperlink:p("Hyperlink")},C=Ur()?.kinds??[],x=(P)=>l.includes(P.type),h=Gr(new Map),g=Gr(new Map),w=Gr(null),y=Gr(new Map),E=Gr(null);function S(P,R){let M={fields:P,target:R};E.current=M,t(P),queueMicrotask(()=>{if(E.current===M)E.current=null})}Hu(()=>{let P=E.current;if(!P||P.fields!==e)return;if(E.current=null,n)return;let{target:R}=P,M=R.type==="field-name"?h.current.get(R.fieldId):R.type==="option-name"?g.current.get(`${R.fieldId}:${R.optionId}`):null;if(M){M.focus(),M.select();return}(R.type==="add-field"?w.current:R.type==="add-option"?y.current.get(R.fieldId):null)?.querySelector("button")?.focus()},[n,e]),qu(()=>{if(!o)return;let P=window.setTimeout(()=>{let R=h.current.get(o);R?.scrollIntoView({block:"center"}),R?.focus(),R?.select()},200);return()=>window.clearTimeout(P)},[o]);let k=(P,R)=>{if(!n)t(e.map((M)=>M.id===P?R(M):M))};function O(){if(n)return;let P={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:p("New field"),type:"singleLineText"};S([...e,P],{type:"field-name",fieldId:P.id})}function L(P){if(n)return;let R=e.filter(x),M=R.findIndex((B)=>B.id===P),N=R.filter((B)=>B.id!==P),I=N[M]??N[M-1];S(e.filter((B)=>B.id!==P),I?{type:"field-name",fieldId:I.id}:{type:"add-field"})}function z(P){if(n)return;let R={id:crypto.randomUUID(),name:p("New option")};S(e.map((M)=>M.id===P.id?{...M,options:[...M.options??[],R]}:M),{type:"option-name",fieldId:P.id,optionId:R.id})}function G(P,R){if(n)return;let M=P.options??[],N=M.findIndex((v)=>v.id===R),I=M.filter((v)=>v.id!==R),B=I[N]??I[N-1];S(e.map((v)=>{if(v.id!==P.id)return v;let K=v.defaultValue;if(!(K?.kind==="value"&&(Array.isArray(K.value)?K.value.includes(R):K.value===R)))return{...v,options:I};let{defaultValue:fe,..._}=v;return{..._,options:I}}),B?{type:"option-name",fieldId:P.id,optionId:B.id}:{type:"add-option",fieldId:P.id})}return un("section",{"aria-label":p("Collection fields"),"data-uibot-schema-editor":"",style:se.root,children:[e.filter(x).map((P)=>un("fieldset",{"aria-label":p("Field {name}",{name:P.name}),style:u?{...se.field,border:0,padding:0,background:"none"}:se.field,children:[un("div",{style:se.row,children:[un("label",{style:se.control,children:[nt("span",{style:se.label,children:p("Field name")}),nt("input",{"aria-label":p("Field name"),ref:(R)=>{if(R)h.current.set(P.id,R);else h.current.delete(P.id)},style:se.input,value:P.name,disabled:n,onChange:(R)=>{let M=R.currentTarget.value;k(P.id,(N)=>({...N,name:M}))}})]}),un("div",{style:se.control,children:[nt("span",{style:se.label,children:p("Field type")}),nt(Xe,{ui:i,label:p("Field type"),style:se.input,disabled:n||a.includes(P.id),value:P.type,options:l.map((R)=>({value:R,label:c[R]})),onChange:(R)=>k(P.id,(M)=>{let{options:N,relation:I,hyperlink:B,formatting:v,defaultValue:K,...ce}=M;return{...ce,type:R,...od(R)?{options:M.options??[]}:{},...R==="relation"?{relation:{collectionId:""}}:{}}})})]}),un("label",{style:se.checkbox,children:[nt("input",{type:"checkbox","aria-label":p("Required"),checked:Boolean(P.required),disabled:n,onChange:(R)=>{let M=R.currentTarget.checked;k(P.id,(N)=>({...N,required:M}))}}),p("Required")]}),u?null:nt(Y,{ui:i,style:{...se.button,...se.danger},disabled:n||a.includes(P.id),icon:"trash",iconOnly:!0,ariaLabel:p("Delete field"),title:p("Delete field {name}",{name:P.name}),onClick:()=>L(P.id)})]}),d?.descriptions===!1?null:un("label",{style:se.control,children:[nt("span",{style:se.label,children:p("Field description")}),nt("textarea",{"aria-label":p("Field description"),style:{...se.input,minHeight:64,resize:"vertical"},rows:2,maxLength:ui,value:P.description??"",disabled:n,onChange:(R)=>{let M=R.currentTarget.value;k(P.id,(N)=>ju(N,M))}})]}),P.type==="relation"?un("div",{style:se.control,children:[nt("span",{style:se.label,children:p("Related table")}),nt(Xe,{ui:i,label:p("Related table"),style:se.input,disabled:n||a.includes(P.id),value:P.relation?.collectionId??"",options:[{value:"",label:p("Choose a related table")},...s.map((R)=>({value:R.id,label:R.name}))],onChange:(R)=>k(P.id,(M)=>({...M,relation:{collectionId:R}}))})]}):null,P.type==="hyperlink"&&C.length>0?un("fieldset",{style:se.settings,"aria-label":p("Link targets"),children:[nt("span",{style:se.label,children:p("Link targets")}),nt("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px"},children:C.map((R)=>{let M=P.hyperlink?.kinds??[];return un("label",{style:se.checkbox,children:[nt("input",{type:"checkbox",checked:M.includes(R.id),disabled:n,onChange:(N)=>{let I=N.currentTarget.checked;k(P.id,(B)=>{let v=B.hyperlink?.kinds??[],K=I?[...v,R.id]:v.filter((_)=>_!==R.id),{hyperlink:ce,...fe}=B;return K.length?{...fe,hyperlink:{kinds:K}}:fe})}}),R.label]},R.id)})}),nt("span",{style:{...se.label,opacity:0.7},children:p("None chosen offers every kind.")})]}):null,od(P.type)?un("fieldset",{style:se.options,"aria-label":p("Options of field {name}",{name:P.name}),children:[nt("strong",{style:{fontSize:13},children:p("Options")}),(P.options??[]).map((R,M)=>un("div",{style:se.optionRow,children:[nt("input",{"aria-label":p("Option name {index}",{index:M+1}),ref:(N)=>{let I=`${P.id}:${R.id}`;if(N)g.current.set(I,N);else g.current.delete(I)},style:{...se.input,flex:"1 1 120px",minWidth:0,width:"auto"},value:R.name,disabled:n,onChange:(N)=>{let I=N.currentTarget.value;k(P.id,(B)=>({...B,options:(B.options??[]).map((v)=>v.id===R.id?{...v,name:I}:v)}))}}),d?.optionColors===!1?null:nt("fieldset",{"aria-label":p("Colour of option {index}",{index:M+1}),style:{display:"inline-flex",flex:"none",gap:4,margin:0,padding:0,border:0,minWidth:0},children:Ln.map((N,I)=>{let B=(R.color??Ln[M%Ln.length])===N;return nt("button",{type:"button","aria-label":p(`Colour ${N}`),"aria-pressed":B,disabled:n,style:{...se.swatch,background:Pn(I).color,border:B?"2px solid currentColor":"1px solid transparent"},onClick:()=>k(P.id,(v)=>({...v,options:(v.options??[]).map((K)=>K.id===R.id?{...K,color:N}:K)}))},N)})}),nt(Y,{ui:i,style:{...se.button,...se.danger},disabled:n,icon:"trash",iconOnly:!0,ariaLabel:p("Delete option {index}",{index:M+1}),title:p("Delete option {index}",{index:M+1}),onClick:()=>G(P,R.id)})]},R.id)),nt("div",{ref:(R)=>{if(R)y.current.set(P.id,R);else y.current.delete(P.id)},children:nt(Y,{ui:i,style:se.button,icon:"plus",disabled:n,onClick:()=>z(P),children:p("Add option")})})]}):null,nt(td,{field:P,...d?{settings:d}:{},dateFormatLocked:a.includes(P.id),disabled:n,locale:r,ui:i,onChange:(R)=>k(P.id,R)}),d?.ai?nt(nd,{field:P,fields:u&&f?[...f,P]:e,disabled:n,locale:r,onChange:(R)=>k(P.id,R)}):null]},P.id)),u?null:nt("div",{ref:w,children:nt(Y,{ui:i,style:se.button,icon:"plus",disabled:n,onClick:O,children:p("Add field")})})]})}import{useEffect as gd,useRef as md,useState as ll}from"react";import{useCallback as Ju,useEffect as cd,useLayoutEffect as Zu,useRef as al,useState as ud}from"react";import{createContext as $u,useContext as Ku,useCallback as Wu,useEffect as rd,useId as Gu,useLayoutEffect as id,useRef as ad,useState as ld}from"react";import{createPortal as Yu}from"react-dom";import{jsx as Xn,jsxs as dd,Fragment as sd}from"react/jsx-runtime";var rl=$u(!1),ol="uibot:collection-popover-open";function il({label:e,trigger:t,defaultOpen:n=!1,disabled:o,menu:r,children:i}){let[l,s]=ld(n),[a,d]=ld({left:8,top:8}),u=ad(null),f=ad(null),p=Gu();rd(()=>{let x=(h)=>{let g=h.detail,w=u.current;if(!g||!w||g===w)return;let y=w.closest("[data-uibot-workspace]")??w.parentElement,E=g.closest("[data-uibot-workspace]")??g.parentElement;if(y===E)s(!1)};return document.addEventListener(ol,x),()=>document.removeEventListener(ol,x)},[]);let c=()=>{s(!1),u.current?.focus({preventScroll:!0})},C=Wu(()=>{if(!l)return;let x=u.current?.getBoundingClientRect(),h=f.current?.getBoundingClientRect();if(x&&h){let g={left:Math.max(8,Math.min(x.left,window.innerWidth-h.width-8)),top:Math.max(8,x.bottom+h.height+8<=window.innerHeight?x.bottom+4:x.top-h.height-4)};d((w)=>w.left===g.left&&w.top===g.top?w:g)}},[l]);return id(C),id(()=>{if(!l)return;if(u.current)document.dispatchEvent(new CustomEvent(ol,{detail:u.current}));(f.current?.querySelector("button:not(:disabled), input, select, textarea")??f.current)?.focus({preventScroll:!0})},[l]),rd(()=>{if(!l)return;let x=(g)=>{if(g.target instanceof Node&&!f.current?.contains(g.target)&&!u.current?.contains(g.target))s(!1)},h=(g)=>{if(g.key!=="Escape")return;g.preventDefault(),g.stopPropagation(),s(!1),u.current?.focus({preventScroll:!0})};return window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),document.addEventListener("pointerdown",x),document.addEventListener("keydown",h),()=>{window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0),document.removeEventListener("pointerdown",x),document.removeEventListener("keydown",h)}},[l,C]),dd(sd,{children:[Xn("button",{ref:u,type:"button","aria-label":e,"aria-haspopup":r?"menu":"dialog","aria-expanded":l,"aria-controls":l?p: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:(x)=>x.stopPropagation(),onClick:()=>l?c():s(!0),children:t}),l&&Yu(Xn("div",{ref:f,id:p,role:r?"menu":"dialog","aria-label":e,tabIndex:-1,style:{position:"fixed",...a,zIndex:80,padding:r?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:(x)=>{if(!r||!["ArrowDown","ArrowUp","Home","End"].includes(x.key))return;x.preventDefault();let h=[...x.currentTarget.querySelectorAll('button[role="menuitem"]:not(:disabled)')],g=h.indexOf(document.activeElement),w=x.key==="Home"?0:x.key==="End"?h.length-1:(g+(x.key==="ArrowUp"?-1:1)+h.length)%h.length;h[w]?.focus()},children:i(c)}),document.body)]})}function zn({ui:e,label:t,defaultOpen:n,icon:o,chevron:r,quiet:i,active:l,children:s}){let a=Ku(rl),d=(u)=>Xn("div",{style:{fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},children:Xn("fieldset",{disabled:a,style:{border:0,padding:0,margin:0,minWidth:0},children:u})});if(e?.Popover)return e.Popover({label:t,defaultOpen:n,...o?{icon:Xn(ve,{name:o})}:{},...r?{iconEnd:Xn(ve,{name:"chevronDown",size:13})}:{},...i?{quiet:i}:{},active:l,children:typeof s==="function"?(u)=>d(s(u)):d(s)});return Xn(il,{label:t,defaultOpen:n,trigger:dd(sd,{children:[o?Xn(ve,{name:o}):null,t,r?Xn(ve,{name:"chevronDown",size:13}):null]}),children:(u)=>d(typeof s==="function"?s(u):s)})}import{jsx as Gi,jsxs as pd,Fragment as Qu}from"react/jsx-runtime";function Yi({items:e,label:t,children:n,block:o=!1}){let[r,i]=ud(null),l=al(null),s=al(null),[a,d]=ud({x:0,y:0}),u=Ju(()=>{if(!r||!s.current)return;let p=Math.max(12,Math.min(r.x,window.innerWidth-12-s.current.offsetWidth)),c=Math.max(12,Math.min(r.y,window.innerHeight-12-s.current.offsetHeight));d((C)=>C.x===p&&C.y===c?C:{x:p,y:c})},[r]);Zu(u),cd(()=>{if(!r)return;return window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[r,u]);let f=al(null);return cd(()=>{if(!r)return;f.current=document.activeElement instanceof HTMLElement?document.activeElement:null,s.current?.querySelector("button:not(:disabled)")?.focus();let p=()=>i(null),c=(C)=>{if(C.key==="Escape")C.preventDefault(),C.stopPropagation(),i(null),f.current?.focus({preventScroll:!0})};return window.addEventListener("keydown",c),window.addEventListener("pointerdown",p),window.addEventListener("blur",p),()=>{window.removeEventListener("keydown",c),window.removeEventListener("pointerdown",p),window.removeEventListener("blur",p)}},[r]),pd("span",{ref:l,style:{display:o?"block":"inline-flex"},onKeyDown:(p)=>{if(p.shiftKey&&p.key==="F10"||p.key==="ContextMenu"){p.preventDefault(),p.stopPropagation();let c=p.target.getBoundingClientRect();i({x:Math.max(8,Math.min(c.left,window.innerWidth-240)),y:Math.max(8,Math.min(c.bottom,window.innerHeight-280))})}},onContextMenu:(p)=>{p.preventDefault(),p.stopPropagation(),i({x:Math.max(8,Math.min(p.clientX,window.innerWidth-240)),y:Math.max(8,Math.min(p.clientY,window.innerHeight-280))})},children:[n,r&&Gi("div",{ref:s,role:"menu","aria-label":t,style:{position:"fixed",left:a.x,top:a.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:(p)=>p.stopPropagation(),onKeyDown:(p)=>{if(!["ArrowDown","ArrowUp"].includes(p.key))return;p.preventDefault();let c=[...p.currentTarget.querySelectorAll("button:not(:disabled)")],C=c.indexOf(document.activeElement);c[(C+(p.key==="ArrowUp"?-1:1)+c.length)%c.length]?.focus()},children:e.map((p)=>Gi("button",{type:"button",role:"menuitem",disabled:p.disabled,style:{display:"block",width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderRadius:6,background:"transparent",color:p.destructive?"var(--destructive, #b3261e)":"inherit",cursor:p.disabled?"default":"pointer",opacity:p.disabled?0.5:1},onClick:()=>{i(null),p.onSelect()},children:p.label},p.id))})]})}function Ji({label:e,items:t,disabled:n,icon:o}){return Gi(il,{label:e,disabled:n,menu:!0,trigger:o??"+",children:(r)=>Gi(Qu,{children:t.map((i)=>pd("button",{type:"button",role:"menuitem",disabled:i.disabled,style:{display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderTop:i.separatorBefore?"1px solid var(--border, #d5d9df)":void 0,background:"transparent",color:i.destructive?"var(--destructive, #b3261e)":"inherit",opacity:i.disabled?0.5:1,font:"inherit"},onClick:()=>{r(),i.onSelect()},children:[i.icon,i.label]},i.id))})})}import{jsx as nn,jsxs as fd}from"react/jsx-runtime";function Xu(e,t,n,o){if(t===n)return[...e];let r=e.filter((l)=>l!==t),i=r.indexOf(n);if(i<0||!e.includes(t))return[...e];return r.splice(o?i+1:i,0,t),r}var ep=["grid","kanban","gallery","calendar","form"];function tp(e,t){return{grid:e("Grid"),kanban:e("Kanban"),gallery:e("Gallery"),calendar:e("Calendar"),form:e("Form")}[t]}function np({slot:e,items:t,label:n,children:o}){if(!t.length)return nn("span",{children:o});if(e)return nn(e,{items:t,"aria-label":n,children:o});return nn(Yi,{items:t,label:n,children:o})}function sl(e){let t=oe(e.locale),[n,o]=ll(null),[r,i]=ll(""),[l,s]=ll(null),a=md(null),d=md(null),u=Boolean(e.onReorder)&&!e.disabled&&e.views.length>1,f=e.views.map((S)=>S.id),p=(S,k,O)=>{let L=Xu(f,S,k,O);if(L.join("\x00")!==f.join("\x00"))e.onReorder?.(L)};gd(()=>{let S=a.current;if(!S)return;a.current=null,document.querySelector(`[data-view-tab="${CSS.escape(S)}"]`)?.focus()}),gd(()=>{if(n)d.current?.select()},[n]);let c=Boolean(e.onDelete)&&e.views.length>1,C=(S)=>{if(!e.onRename||e.disabled)return;i(S.name),o(S.id)},x=()=>{if(!n)return;let S=e.views.find((O)=>O.id===n),k=r.trim();if(o(null),S&&k&&k!==S.name)e.onRename?.(S.id,k)},h=(S)=>[...e.onRename?[{id:"rename",icon:nn(ve,{name:"pencil"}),label:t("Rename view"),onSelect:()=>C(S)}]:[],...e.onDuplicate?[{id:"duplicate",icon:nn(ve,{name:"copy"}),label:t("Duplicate view"),onSelect:()=>e.onDuplicate?.(S.id)}]:[],...e.onDelete?[{id:"delete",icon:nn(ve,{name:"trash"}),label:t("Delete view"),destructive:!0,disabled:!c,onSelect:()=>e.onDelete?.(S.id)}]:[]],g=(S,k)=>{let O=e.views.findIndex((L)=>L.id===k.id);if(S.altKey&&(S.key==="ArrowRight"||S.key==="ArrowLeft")){S.preventDefault();let L=e.views[O+(S.key==="ArrowRight"?1:-1)];if(u&&L)a.current=k.id,p(k.id,L.id,S.key==="ArrowRight")}else if(S.key==="F2")S.preventDefault(),C(k);else if(S.key==="Delete"&&c&&!e.disabled)S.preventDefault(),e.onDelete?.(k.id);else if(S.key==="ArrowRight"||S.key==="ArrowLeft"){S.preventDefault();let L=e.views[O+(S.key==="ArrowRight"?1:-1)];if(L)e.onSelect(L.id),S.currentTarget.parentElement?.parentElement?.querySelectorAll('[role="tab"]')?.[O+(S.key==="ArrowRight"?1:-1)]?.focus()}},w=(e.viewTypes??ep).map((S)=>({id:S,label:tp(t,S),disabled:e.disabledViewTypes?.includes(S)??!1,onSelect:()=>e.onAdd?.(S)})),y=e.ui?.ContextMenu,E=e.ui?.DropdownMenu;return fd("div",{"data-uibot":"collection-view-tabs",style:{display:"flex",alignItems:"flex-end",gap:2,minWidth:0,maxWidth:"100%",overflowX:"auto"},children:[nn("div",{role:"tablist","aria-label":t("Views"),style:{display:"flex",gap:2},children:e.views.map((S)=>{let k=S.id===e.activeId,O=h(S),L=n===S.id?nn("input",{ref:d,"aria-label":t("View name"),value:r,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:(z)=>i(z.target.value),onBlur:x,onKeyDown:(z)=>{if(z.stopPropagation(),z.key==="Enter")z.preventDefault(),x();else if(z.key==="Escape")z.preventDefault(),o(null)}}):fd("button",{type:"button",role:"tab","aria-selected":k,tabIndex:k?0:-1,disabled:e.disabled,title:e.onRename?t("Double click to rename"):void 0,"data-view-tab":S.id,draggable:u,onDragStart:(z)=>{if(!u)return;z.dataTransfer.effectAllowed="move",z.dataTransfer.setData("text/plain",S.id),s({id:S.id})},onDragOver:(z)=>{if(!l||l.id===S.id)return;z.preventDefault();let G=z.currentTarget.getBoundingClientRect(),P=(z.clientX||0)>G.left+G.width/2;if(l.over!==S.id||l.after!==P)s({id:l.id,over:S.id,after:P})},onDrop:(z)=>{if(!l)return;z.preventDefault(),p(l.id,S.id,Boolean(l.after)),s(null)},onDragEnd:()=>s(null),style:{boxShadow:l?.over===S.id?l.after?"inset -2px 0 0 var(--primary, #1a56c4)":"inset 2px 0 0 var(--primary, #1a56c4)":void 0,opacity:l?.id===S.id?0.5:1,position:"relative",display:"inline-flex",alignItems:"center",gap:6,height:34,padding:"0 12px",border:0,borderBottom:k?"2px solid var(--primary, #1a56c4)":"2px solid transparent",background:"transparent",color:k?"var(--primary, #1a56c4)":"inherit",fontWeight:k?600:400,fontSize:13,whiteSpace:"nowrap",cursor:"pointer"},onClick:()=>e.onSelect(S.id),onDoubleClick:()=>C(S),onKeyDown:(z)=>g(z,S),children:[nn("span",{children:S.name}),e.dirty&&k&&nn("span",{role:"img","aria-label":t("Unsaved changes"),style:{width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}})]});return nn(np,{slot:y,items:n===S.id?[]:O,label:t("View actions"),children:L},S.id)})}),e.onAdd&&(E?nn(E,{label:t("Add view"),items:w,disabled:e.disabled}):nn(Ji,{label:t("Add view"),items:w,disabled:e.disabled}))]})}import{useRef as op,useState as rp}from"react";import{jsx as kt,jsxs as vr}from"react/jsx-runtime";function dl(e){let t=oe(e.locale),n=e.descriptor.fields.find((a)=>a.id===e.view.groupByFieldId),o=Bi(e),r=op(null),[i,l]=rp(null);if(!n||!["singleSelect","checkbox"].includes(n.type))return kt("p",{role:"status",children:t("Choose a single-select or boolean grouping field.")});let s=gs(n,t);return vr("section",{"data-uibot":"collection-kanban",children:[kt(mr,{...e}),kt("div",{style:{display:"flex",gap:12,overflowX:"auto",alignItems:"flex-start",paddingBottom:12},children:s.map((a)=>kt(ip,{...e,field:n,lane:a,lanes:s,blocked:o.blocked,onOpen:l,onMove:(d,u)=>void o.move(d,{[n.id]:u.value}),onDrag:(d)=>{r.current=d},onDrop:(d)=>{if(r.current?.id===d)o.move(r.current,{[n.id]:a.value});r.current=null}},a.id))}),kt(Vi,{state:o,locale:e.locale,ui:e.ui}),i&&kt(Zn,{...e,row:i,onClose:()=>l(null)},i.id)]})}function ip({field:e,lane:t,lanes:n,blocked:o,onOpen:r,onMove:i,onDrag:l,onDrop:s,...a}){let d=oe(a.locale),u=wt(a.features),f=u.optionChips,p=!a.readOnly&&u.rowUpdate,c=fr(a,fs(a.view,e,t)),C=a.descriptor.fields.find((g)=>g.type==="singleLineText"||g.type==="longText")?.id,x=mo(a.descriptor.fields,a.view).filter((g)=>g.id!==e.id&&g.id!==C).slice(0,3),h=p&&!o&&!(e.required&&t.value===null);return vr("section",{"aria-label":d("Lane {name}",{name:t.name}),"data-lane-id":t.id,style:{...cn,flex:"0 0 290px",minWidth:0,...f?{background:"var(--muted, #f4f6f8)",padding:10}:{}},onDragOver:(g)=>{if(h)g.preventDefault()},onDrop:(g)=>{if(!h)return;g.preventDefault(),s(g.dataTransfer.getData("application/x-uibot-record"))},children:[vr("h3",{style:f?{display:"flex",alignItems:"center",gap:6,margin:"0 0 6px",fontSize:13}:void 0,children:[f&&kt("span",{"aria-hidden":"true",style:{width:8,height:8,borderRadius:999,...t.id.startsWith("option:")?{background:Pn(lp(n,t)).color}:{background:"var(--muted-foreground, #9a9892)"}}}),t.name," · ",$r(d,c.page.total,c.page.items.length,a.locale)]}),kt(yr,{state:c,locale:a.locale,ui:a.ui,hideCount:!0}),vr("div",{style:{display:"flex",flexDirection:"column",gap:8,marginTop:12,maxHeight:"65vh",overflowY:"auto"},children:[c.page.items.map((g)=>{let w=jt(g,a.descriptor.fields);return vr("article",{"data-record-id":g.id,style:f?{...cn,padding:10,boxShadow:"0 1px 2px rgb(0 0 0 / 0.06)",cursor:"grab",position:"relative"}:cn,draggable:p&&!o&&!c.loading,onDragStart:(y)=>{l(g),y.dataTransfer.setData("application/x-uibot-record",g.id),y.dataTransfer.effectAllowed="move"},onDragEnd:()=>l(null),children:[kt("button",{type:"button",style:{..._e,width:"100%",textAlign:"left",overflowWrap:"anywhere",...f?{border:0,padding:"0 28px 0 0",background:"transparent",fontWeight:600}:{}},"aria-label":d("Open {name}",{name:w}),onClick:()=>r(g),children:w}),f&&kt(ap,{row:g,fields:x}),p&&(a.ui?.DropdownMenu?kt("span",{style:{position:"absolute",top:4,right:4},children:a.ui.DropdownMenu({label:d("Move {name}",{name:w}),icon:kt(ve,{name:"more"}),disabled:o||c.loading,items:n.map((y)=>({id:y.id,label:d("Move to {name}",{name:y.name}),disabled:y.id===t.id||!!e.required&&y.value===null,onSelect:()=>i(g,y)}))})}):vr("div",{style:{display:"flex",flexDirection:"column",gap:4,marginTop:8},children:[kt("span",{children:d("Move to")}),kt(Xe,{ui:a.ui,label:d("Move {name}",{name:w}),style:_e,disabled:o||c.loading,value:t.id,onChange:(y)=>{let E=n.find((S)=>S.id===y);if(E&&E.id!==t.id)i(g,E)},options:n.map((y)=>({value:y.id,label:y.name,disabled:!!e.required&&y.value===null}))})]}))]},g.id)}),!c.loading&&!c.error&&!c.page.items.length&&kt("p",{children:d("No records in this lane.")})]})]})}function ap({row:e,fields:t}){let n=t.map((o)=>{let r=e.values[o.id],i=o.type==="singleSelect"||o.type==="multipleSelect",l=Array.isArray(r)?r:r==null?[]:[r],s=o.type==="linkedRecord"?Vo(e,o):sn(r,o,e.computedErrors?.[o.id]);return{field:o,chips:i,ids:l,text:s}}).filter((o)=>o.chips?o.ids.length>0:o.text!=="");if(!n.length)return null;return kt("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:6,alignItems:"center",fontSize:12,opacity:0.85},children:n.map((o)=>o.chips?kt(Go,{ids:o.ids,field:o.field},o.field.id):kt("span",{style:{fontVariantNumeric:"tabular-nums"},children:o.text},o.field.id))})}function lp(e,t){return e.filter((n)=>n.id.startsWith("option:")).findIndex((n)=>n.id===t.id)}import{useState as sp}from"react";import{jsx as qn,jsxs as cl}from"react/jsx-runtime";function ul(e){let t=oe(e.locale),n=wt(e.features).optionChips,o=fr(e,ki(e.view)),[r,i]=sp(null),l=e.descriptor.fields.find((a)=>a.type==="singleLineText"||a.type==="longText")?.id,s=mo(e.descriptor.fields,e.view).filter((a)=>!n||a.id!==l);return cl("section",{"data-uibot":"collection-gallery",children:[qn(mr,{...e}),qn(yr,{state:o,locale:e.locale,ui:e.ui}),qn("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 240px), 1fr))",gap:12,marginTop:12},children:o.page.items.map((a)=>cl("article",{"data-record-id":a.id,style:{...cn,minWidth:0,...n?{boxShadow:"0 1px 2px rgb(0 0 0 / 0.05)"}:{}},children:[qn("button",{type:"button","aria-label":t("Open {name}",{name:jt(a,e.descriptor.fields)}),style:{..._e,width:"100%",textAlign:"left",overflowWrap:"anywhere",...n?{border:0,padding:0,background:"transparent",fontWeight:600,fontSize:"var(--uibot-workspace-font-size, 13px)"}:{}},onClick:()=>i(a),children:jt(a,e.descriptor.fields)}),qn("dl",{children:s.filter((d)=>!n||!dp(a,d)).slice(0,n?5:s.length).map((d)=>cl("div",{children:[qn("dt",{style:{fontSize:12,opacity:0.7},children:d.name}),qn("dd",{style:{margin:"0 0 8px",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n&&(d.type==="singleSelect"||d.type==="multipleSelect")&&a.values[d.id]!=null?qn(Go,{ids:Array.isArray(a.values[d.id])?a.values[d.id]:[a.values[d.id]],field:d}):(d.type==="linkedRecord"?Vo(a,d):sn(a.values[d.id],d,a.computedErrors?.[d.id]))||"—"})]},d.id))})]},a.id))}),!o.loading&&!o.error&&!o.page.items.length&&qn("p",{children:t("No records match this view.")}),r&&qn(Zn,{...e,row:r,onClose:()=>i(null)},r.id)]})}function dp(e,t){let n=e.values[t.id];if(t.type==="linkedRecord")return!Vo(e,t);return n==null||n===""||Array.isArray(n)&&n.length===0}import{useRef as cp,useState as pl}from"react";import{jsx as lt,jsxs as wo}from"react/jsx-runtime";function gl(e){let t=oe(e.locale),n=wt(e.features),o=n.optionChips,r=!e.readOnly&&n.rowUpdate,[i,l]=pl(()=>{let y=new Date().toISOString().slice(0,7),E=e.initialMonth??y;try{return Br(E),{month:E,error:""}}catch{return{month:y,error:t("Invalid initial month. Showing the current UTC month.")}}}),{month:s,error:a}=i,[d,u]=pl(null),f=e.descriptor.fields.find((y)=>y.id===e.view.dateFieldId&&y.type==="date"),p=cp(null),c=Bi(e),C=fr(e,f?ys(e.view,f.id,s):{limit:1},!!f),x=Br(s),h=(y)=>{try{Br(y),l({month:y,error:""})}catch{l((E)=>({...E,error:t("Choose a valid month between years 1 and 9998.")}))}},g=(y)=>{let E=new Date(x.start);E.setUTCMonth(E.getUTCMonth()+y),h(E.toISOString().slice(0,7))},w=(y,E)=>{if(!f)return;try{c.move(y,{[f.id]:Pi(y.values[f.id],E)})}catch(S){c.mutation.setError(S instanceof Error?S.message:t("Invalid date"))}};if(!f)return lt("p",{role:"status",children:t("Choose a date field for this calendar.")});return wo("section",{"data-uibot":"collection-calendar",children:[lt(mr,{...e}),wo("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginBottom:12},children:[lt(Y,{ui:e.ui,style:_e,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:t("Previous month"),onClick:()=>g(-1)}),e.ui?.MonthPicker?lt(e.ui.MonthPicker,{value:s,onChange:h,"aria-label":t("Calendar month")}):e.ui?.Button?lt("strong",{role:"status","aria-label":t("Calendar month"),style:{minWidth:96,textAlign:"center",fontVariantNumeric:"tabular-nums"},children:t("{year}-{month}",{year:s.slice(0,4),month:s.slice(5,7)})}):wo("label",{children:[t("Month")," ",lt("input",{type:"month","aria-label":t("Calendar month"),min:"0001-01",max:"9998-12",value:s,onChange:(y)=>h(y.target.value),style:_e})]}),lt(Y,{ui:e.ui,style:_e,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:t("Next month"),onClick:()=>g(1)}),lt(Y,{ui:e.ui,style:_e,variant:"outline",size:"sm",onClick:()=>h(new Date().toISOString().slice(0,7)),children:t("Today")})]}),a&&lt("p",{role:"alert",children:a}),lt(yr,{state:C,locale:e.locale,ui:e.ui}),lt("div",{style:{overflowX:"auto",minWidth:0},children:wo("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((y)=>lt("strong",{style:o?{padding:"8px 10px",fontSize:12,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"}:{padding:8},children:y},y)),["sun","mon","tue","wed","thu","fri","sat"].slice(0,x.weekday).map((y)=>lt("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},y)),Array.from({length:x.days},(y,E)=>{let S=`${s}-${String(E+1).padStart(2,"0")}`,k=C.page.items.filter((O)=>String(O.values[f.id]??"").slice(0,10)===S);return wo("article",{"aria-label":t("Day {day}",{day:S}),"data-calendar-day":S,style:{...cn,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:(O)=>{if(r&&!c.blocked)O.preventDefault()},onDrop:(O)=>{if(!r||c.blocked)return;if(O.preventDefault(),p.current?.id===O.dataTransfer.getData("application/x-uibot-record"))w(p.current,S);p.current=null},children:[lt("time",{dateTime:S,children:E+1}),k.map((O)=>wo("article",{"data-record-id":O.id,style:{marginTop:8},draggable:r&&!c.blocked&&!C.loading,onDragStart:(L)=>{p.current=O,L.dataTransfer.setData("application/x-uibot-record",O.id),L.dataTransfer.effectAllowed="move"},onDragEnd:()=>{p.current=null},children:[wo("button",{type:"button",style:{..._e,textAlign:"left",width:"100%",overflowWrap:"anywhere",...o?{border:0,padding:"3px 8px",fontSize:12,fontWeight:500,...Pn(0)}:{}},"aria-label":t("Open {name}",{name:jt(O,e.descriptor.fields)}),onClick:()=>u(O),children:[jt(O,e.descriptor.fields)," ",lt("small",{children:String(O.values[f.id]).slice(11,16)})]}),r&&lt(up,{ui:e.ui,t,row:O,fieldId:f.id,title:jt(O,e.descriptor.fields),disabled:c.blocked||C.loading,onMove:w})]},O.id))]},S)})]})}),!C.loading&&!C.error&&!C.page.items.length&&lt("p",{children:t("No dated records match this month.")}),lt(Vi,{state:c,locale:e.locale,ui:e.ui}),!c.intent&&c.mutation.error&&lt("p",{role:"alert",children:c.mutation.error}),d&&lt(Zn,{...e,row:d,onClose:()=>u(null)},d.id)]})}function up({ui:e,t,row:n,fieldId:o,title:r,disabled:i,onMove:l}){let[s,a]=pl({day:String(n.values[o]).slice(0,10)}),d=e?.DateMove;if(d)return lt(d,{label:t("Move {name} to date",{name:r}),value:s.day,disabled:i,onPick:(u)=>l(s.baseline??n,u)});return wo("div",{style:{marginTop:4,display:"flex",gap:4,flexWrap:"wrap"},children:[lt("input",{type:"date","aria-label":t("Move {name} to date",{name:r}),value:s.day,disabled:i,style:{width:"100%",minWidth:0},onChange:(u)=>a({day:u.target.value,baseline:s.baseline??n})}),lt("button",{type:"button",style:_e,"aria-label":t("Move {name}",{name:r}),disabled:i||!s.day,onClick:()=>l(s.baseline??n,s.day),children:t("Move")})]})}import{jsx as eo,jsxs as xr}from"react/jsx-runtime";function ml({fields:e,view:t,onChange:n,locale:o,ui:r,features:i,sections:l,filterEditor:s,grouping:a,rowHeight:d}){let u=oe(o),f=wt(i),p=e.filter((w)=>w.type==="singleSelect"||w.type==="checkbox"),c=e.filter((w)=>w.type==="date"),C=(w)=>{let y={...t,type:w};if(delete y.groupByFieldId,delete y.dateFieldId,w==="kanban"&&p[0])y.groupByFieldId=p[0].id;if(w==="calendar"&&c[0])y.dateFieldId=c[0].id;if(w==="form")y.hiddenColumns=y.hiddenColumns.filter((E)=>!e.find((S)=>S.id===E)?.required);n(y)},x={grid:u("Grid"),kanban:u("Kanban"),gallery:u("Gallery"),calendar:u("Calendar"),form:u("Form")},h=f.viewTypes.map((w)=>({value:w,label:x[w],disabled:w==="kanban"&&!p.length||w==="calendar"&&!c.length})),g=t.type??"grid";return xr("div",{style:{display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},children:[xr("div",{children:[u("View type")," ",eo(Xe,{ui:r,label:u("View type"),style:_e,value:g,options:h,onChange:(w)=>C(w)})]}),g==="grid"&&f.groupBy&&p.length>0&&a!==!1&&eo("div",{style:{flexBasis:"100%"},children:eo($i,{fields:e,view:t,onChange:n,locale:o,ui:r})}),g==="grid"&&d!==!1&&xr("div",{children:[u("Row height")," ",eo(Xe,{ui:r,label:u("Row height"),style:_e,value:t.rowHeight??"short",options:pi.map((w)=>({value:w,label:u(`Row height ${w}`)})),onChange:(w)=>{let y={...t};if(w==="short")delete y.rowHeight;else y.rowHeight=w;n(y)}})]}),g==="kanban"&&xr("div",{children:[u("Group by")," ",eo(Xe,{ui:r,label:u("Kanban grouping field"),style:_e,value:t.groupByFieldId??"",options:p.map((w)=>({value:w.id,label:w.name})),onChange:(w)=>n({...t,groupByFieldId:w})})]}),g==="calendar"&&xr("div",{children:[u("Date field")," ",eo(Xe,{ui:r,label:u("Calendar date field"),style:_e,value:t.dateFieldId??"",options:c.map((w)=>({value:w.id,label:w.name})),onChange:(w)=>n({...t,dateFieldId:w})})]}),(l?.filter||l?.columns||l?.sort)&&xr("div",{style:{display:"grid",gap:12,flexBasis:"100%"},children:[l?.filter&&eo(Hi,{fields:e,view:t,onChange:n,locale:o,ui:r,editor:s}),l?.columns&&eo(Ys,{fields:e,view:t,onChange:n,locale:o,ui:r}),l?.sort&&eo(ji,{fields:e,view:t,onChange:n,locale:o,ui:r})]})]})}function yd(e,t){if(!t)return e;return fl(e,async(o,r)=>{let i=await e.mutate(o,r);if(i.ok||i.error.code!=="approval_required")return i;let l=await t(i.error.details??{approvalRequestId:""},r);return l?e.mutate(o,{...r,approvalReceiptId:l}):i})}function fl(e,t){return new Proxy(e,{get(n,o){if(o==="mutate")return t;let r=Reflect.get(n,o,n);return typeof r==="function"?r.bind(n):r}})}import{useEffect as Rn,useLayoutEffect as fp,useMemo as Sn,useRef as pn,useState as ht}from"react";import{DndContext as yp,PointerSensor as bp,useDraggable as hp,useSensor as Cp,useSensors as vp}from"@dnd-kit/core";import{defaultRangeExtractor as xp,useVirtualizer as Pd}from"@tanstack/react-virtual";function bd(e,t,n,o=new Set){let r=new Set([...e.map((i)=>i.id),...t]);return n.filter((i)=>r.has(i.id)&&!o.has(i.id))}function yl(e,t){let n=new Set(e);if(n.has(t))n.delete(t);else n.add(t);return n}function Zi(e){let t=Ln.findIndex((o)=>o===e);if(t<0)return;let n=Pn(t);return{background:`color-mix(in srgb, ${n.background} 55%, var(--background, white))`,marker:String(n.color)}}var hd=(e,t)=>(e%t+t)%t;function Cd(e,t,n,o){let r=[],i=0,l=0,s=e.lastRow-e.firstRow+1,a=e.lastColumn-e.firstColumn+1;if(s<1||a<1||t.lastRow-t.firstRow+1>100)return{mutations:r,skipped:i,count:l,limitExceeded:!0};for(let d=t.firstRow;d<=t.lastRow;d++){let u=n[d];if(!u)continue;let f={};for(let p=t.firstColumn;p<=t.lastColumn;p++){if(d>=e.firstRow&&d<=e.lastRow&&p>=e.firstColumn&&p<=e.lastColumn)continue;let c=o[p];if(!c)continue;if(it(c)||c.generation==="autoIncrement"||["blob","linkedRecord","relation"].includes(c.type)){i++;continue}let C=e.firstColumn+hd(p-e.firstColumn,a),x=o[C];if(!x||x.type!==c.type){i++;continue}let h=n[e.firstRow+hd(d-e.firstRow,s)]?.values[x.id]??null;if(a===1&&s>=2&&(c.type==="number"||c.type==="date")&&p===e.firstColumn){let g=n.slice(e.firstRow,e.lastRow+1).map((S)=>S.values[x.id]),w=g.map((S)=>c.type==="date"?typeof S==="string"&&S!==""?Date.parse(S)/86400000:Number.NaN:typeof S==="number"?S:Number.NaN),y=w[0]??Number.NaN,E=(w[1]??Number.NaN)-y;if(w.every((S,k)=>Number.isFinite(S)&&Math.abs(S-(y+E*k))<0.00000001)){let S=y+E*(d-e.firstRow);if(Number.isFinite(S))h=c.type==="date"?String(g[0]).length===10?new Date(S*86400000).toISOString().slice(0,10):new Date(S*86400000).toISOString():S}}f[c.id]=structuredClone(h),l++}if(Object.keys(f).length)r.push({op:"update",id:u.id,expectedVersion:u.version,values:f})}return{mutations:r,skipped:i,count:l,limitExceeded:!1}}import{useEffect as pp,useMemo as gp,useState as mp}from"react";function vd(e,t,n,o,r,i){let l=gp(()=>{let d=n.flatMap((u,f)=>{let p=t.footerStats?.[u.id];return p&&p!=="none"&&p!=="count"?[{fn:p,fieldId:u.id,as:`footer${f}`}]:[]});return JSON.stringify([e,gi(t,{aggregates:d}),o.map((u)=>[u.id,u.version]),i])},[e,n,t,o,i]),[s,a]=mp({key:"",status:"ready",values:{}});return pp(()=>{if(!r)return;let d=!0,[u,f]=JSON.parse(l);return(async()=>{let p={};for(let c=0;c<f.aggregates.length;c+=8){let C={...f,aggregates:f.aggregates.slice(c,c+8)};if(mi(u,C))throw Error("Invalid summary");let x=await r.aggregate(u.id,C);if(!d)return;if(!x.ok||x.data.length!==1)throw Error("Summary unavailable");for(let h of C.aggregates){let g=x.data[0]?.values[h.as],w=u.fields.find((E)=>E.id===h.fieldId),y=w?.type==="date"||w?.resultType==="date";if(g!==null&&!(typeof g==="number"&&Number.isFinite(g))&&!(y&&(h.fn==="min"||h.fn==="max")&&typeof g==="string"&&Number.isFinite(Date.parse(g))))throw Error("Invalid summary result");p[h.as]=g}}if(d)a({key:l,client:r,status:"ready",values:p})})().catch(()=>{if(d)a({key:l,client:r,status:"error",values:{}})}),()=>{d=!1}},[r,l]),{status:!r?"local":s.key!==l||s.client!==r?"loading":s.status,values:s.key===l&&s.client===r?s.values:{}}}function wd(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 xd=(e)=>e!==null&&e!==void 0&&e!==""&&!(Array.isArray(e)&&e.length===0)&&e!==!1;function kd(e,t,n){let o=e.map((i)=>i.values[t.id]);if(n==="none")return null;if(n==="count")return e.length;if(n==="filled")return o.filter(xd).length;if(n==="empty")return o.filter((i)=>!xd(i)).length;if(t.type==="date"){let i=o.filter((l)=>typeof l==="string"&&l!=="").sort();if(!i.length)return null;return n==="min"?i[0]??null:i[i.length-1]??null}let r=o.filter((i)=>typeof i==="number"&&Number.isFinite(i));if(!r.length)return null;if(n==="sum")return r.reduce((i,l)=>i+l,0);if(n==="avg")return r.reduce((i,l)=>i+l,0)/r.length;if(n==="min")return Math.min(...r);return Math.max(...r)}import{jsx as Z,jsxs as mt}from"react/jsx-runtime";function wp(e,t){let n=e.find((o)=>o.fieldId===t);if(n?.direction==="desc")return[];return[{fieldId:t,direction:n?"desc":"asc"}]}var to={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},kp={padding:5,width:"100%",border:"1px solid #6688bb",background:"var(--background, white)",color:"inherit"};function Sd(e){let{descriptor:t,view:n}=e,o=oe(e.locale),r=Sn(()=>wt(e.features),[e.features]),i=!e.readOnly&&r.rowDelete,l=!e.readOnly&&r.rowCreate,s=!e.readOnly&&r.rowUpdate,a=pn({readOnly:e.readOnly,features:r});a.current={readOnly:e.readOnly,features:r};let d=(b)=>{if(!b||a.current.readOnly)return!1;let A={insert:a.current.features.rowCreate,update:a.current.features.rowUpdate,delete:a.current.features.rowDelete};return b.items.every((F)=>A[F.op])},[u,f]=ht({}),p=pn(new Set),[c,C]=ht(()=>new Set),x=pn(new Set);Rn(()=>{if(!p.current.size)return;let b=p.current;p.current=new Set,f((A)=>Object.fromEntries(Object.entries(A).filter(([F])=>!b.has(F))))},[e.rows]);let h=Sn(()=>Object.keys(u).length?e.rows.map((b)=>u[b.id]?{...b,values:{...b.values,...u[b.id]}}:b):e.rows,[e.rows,u]),g=Sn(()=>[...n.columnOrder,...t.fields.map((A)=>A.id).filter((A)=>!n.columnOrder.includes(A))].filter((A)=>!n.hiddenColumns.includes(A)).flatMap((A)=>{let F=t.fields.find((ae)=>ae.id===A);return F?[F]:[]}),[t.fields,n.columnOrder,n.hiddenColumns]),w=Sn(()=>JSON.stringify([h.map((b)=>b.id),g.map((b)=>b.id)]),[h,g]),[y,E]=ht(w),S=pn(null),[k,O]=ht({row:0,column:0}),[L,z]=ht(!1),[G,P]=ht(()=>new Set),[R,M]=ht(()=>new Set),N=JSON.stringify([t.id,n.filter,n.search,n.sort,e.rowOffset]);Rn(()=>{P(new Set),M(new Set)},[e.rows,N]);let[I,B]=ht({row:0,column:0}),[v,K]=ht(null),ce=pn(!1),fe=pn(!1),[_,ie]=ht(null),[ue,W]=ht(!1),[q,xe]=ht(!1);On({dirty:Boolean(_||ue||v&&v.text!==v.originalText),busy:q||c.size>0},e);let[ke,ye]=ht(""),[re,Ce]=ht(null),he=pn(null),Ye=v?.field.type==="linkedRecord"?JSON.stringify([v.rowId,v.field.id]):null;Rn(()=>{if(Ye)he.current?.querySelector('input[type="search"]')?.focus({preventScroll:!0})},[Ye]),Rn(()=>{z(!1),O({row:0,column:0}),B({row:0,column:0}),E(w)},[w]);let j=Sn(()=>{if(!r.groupBy||(n.type??"grid")!=="grid")return;let b=t.fields.find((A)=>A.id===n.groupByFieldId);return fa(b)?b:void 0},[r.groupBy,n.type,n.groupByFieldId,t.fields]),[D,te]=ht(()=>new Set),T=j?.id;Rn(()=>te(new Set),[T]);let Te=Sn(()=>ts(h,j,D),[h,j,D]),ot=(b)=>Boolean(j)&&Te.rowItem[b]===void 0,In=ns(n.rowHeight),An=ba(n.rowHeight),Q=Pd({count:Te.items.length,getScrollElement:()=>S.current,estimateSize:(b)=>Te.items[b]?.kind==="group"?ya:In,overscan:5,scrollMargin:38,getItemKey:(b)=>`${In}:${Te.items[b]?.key??b}`}),ge=n.showRowNumber===!1?0:56,Pe=n.showRecordId?220:0,we=ge+Pe,[Je,on]=ht(0);Rn(()=>{let b=S.current;if(!b)return;let A=()=>on(b.clientWidth);if(A(),typeof ResizeObserver>"u")return window.addEventListener("resize",A),()=>window.removeEventListener("resize",A);let F=new ResizeObserver(A);return F.observe(b),()=>F.disconnect()},[]);let En=Math.min(Math.max(0,n.frozenColumnCount??0),g.length),Mt=Sn(()=>{let b=[we];for(let A of g)b.push((b.at(-1)??we)+Jr(n.columnWidths[A.id]??180));return b},[we,g,n.columnWidths]),Dt=Mt[En]??we,Ze=Je>0&&Je<=768&&Dt>Je*0.6?0:En,gn=(b)=>Mt[b]??we,Le=pn(null),ft=Boolean(e.onAddRecord)&&l,Tt=vp(Cp(bp,{activationConstraint:{distance:6}})),kr=({active:b,delta:A})=>{let F=g.findIndex((Ve)=>Ve.id===b.id),ae=Lt.getVirtualItems().find((Ve)=>Ve.index===F);if(F<0||!ae)return;let X=ae.start+ae.size/2+A.x,U=Lt.getVirtualItems().find((Ve)=>X>=Ve.start&&X<Ve.start+Ve.size)?.index;if(U===void 0||U===F)return;if(F<Ze!==U<Ze)return;let ee=[...n.columnOrder.filter((Ve)=>t.fields.some((Tr)=>Tr.id===Ve)),...t.fields.map((Ve)=>Ve.id).filter((Ve)=>!n.columnOrder.includes(Ve))],Ie=String(b.id),me=g[U]?.id;if(!me)return;let Ae=ee.filter((Ve)=>Ve!==Ie),be=Ae.indexOf(me)+(U>F?1:0);Ae.splice(be,0,Ie),e.onViewChange({...n,columnOrder:Ae})},Ot=(b,A)=>({position:"sticky",float:"left",left:b,zIndex:2,...A?{boxShadow:"2px 0 4px -2px color-mix(in srgb, currentColor 28%, transparent)"}:{}}),Lt=Pd({paddingStart:we,paddingEnd:e.onAddField?bl:0,horizontal:!0,count:g.length,rangeExtractor:(b)=>{let A=new Set(xp(b));for(let F=0;F<Ze;F+=1)A.add(F);return[...A].sort((F,ae)=>F-ae)},getScrollElement:()=>S.current,estimateSize:(b)=>Jr(n.columnWidths[g[b]?.id??""]??180),overscan:2,getItemKey:(b)=>g[b]?.id??b});Rn(()=>{g.forEach((b,A)=>{Lt.resizeItem(A,Jr(n.columnWidths[b.id]??180))})},[Lt,n.columnWidths,g]);let rn=Math.max(1,Lt.getTotalSize()),mn=Lt.getVirtualItems(),Ke=wa(k,I),st=Sn(()=>L&&y===w?h.slice(Ke.firstRow,Ke.lastRow+1):[],[L,y,w,h,Ke.firstRow,Ke.lastRow]),De=Sn(()=>{let b=new Set(h.filter((A,F)=>!j||Te.rowItem[F]!==void 0).map((A)=>A.id));return bd(st,G,h,R).filter((A)=>b.has(A.id))},[st,G,h,R,j,Te]),oo=Sn(()=>De.map((b)=>b.id),[De]),Bt=Sn(()=>new Set(oo),[oo]),Po=L?{first:Ke.firstColumn,last:Ke.lastColumn}:{first:0,last:g.length-1},Hn=()=>De.length?cs(De,g,{row:0,column:Po.first},{row:De.length-1,column:Po.last}):"",So=(b)=>{if(v||q||ue||_)return;let A=h[b];if(!A)return;if(E(w),st.some((F)=>F.id===A.id))M((F)=>yl(F,A.id));else P((F)=>yl(F,A.id));if(!L)O({row:b,column:0}),B({row:b,column:g.length-1})},[vt,jn]=ht(null),ro=pn(null),Yo=!G.size&&!R.size&&L&&s&&!q&&!v&&!ue&&!_&&!D.size,ni=(b,A)=>{if(!Yo)return;let F=Cd(b,A,h,g),ae=(U)=>{ye(U),e.onNotify?.(U)};if(F.limitExceeded){ae(o("Fill at most 100 rows at once."));return}let X=F.skipped?o("Skipped {count} cells",{count:F.skipped}):"";if(!F.mutations.length){if(X)ae(X);return}Ut({idempotencyKey:crypto.randomUUID(),items:F.mutations},()=>{ae([o("Filled {count} cells",{count:F.count}),X].filter(Boolean).join("; "))})};Rn(()=>{if(!vt)return;let b=()=>{let F=ro.current;if(jn(null),ro.current=null,F)ni(vt,F)},A=()=>{jn(null),ro.current=null};return window.addEventListener("mouseup",b),window.addEventListener("blur",A),()=>{window.removeEventListener("mouseup",b),window.removeEventListener("blur",A)}});let io=JSON.stringify({recordIds:y===w?oo:[],fieldIds:De.length?g.slice(Po.first,Po.last+1).map((b)=>b.id):[]}),Pr=pn(e.onSelectionChange);Pr.current=e.onSelectionChange,Rn(()=>{Pr.current?.(JSON.parse(io))},[io]),Rn(()=>{if(!j||!ot(I.row))return;let b=Ci(Te,I.row,-1,h.length),A=b>=0?b:Ci(Te,I.row,1,h.length);if(A>=0)B({...I,row:A}),O({...I,row:A})},[Te]);let Sr=(b)=>{let A=new Set(D);if(A.has(b))A.delete(b);else A.add(b);te(A),z(!1),P(new Set),M(new Set),O(I)},Wt=(b,A=!1)=>{if(D.size)A=!1;if(z(!0),E(w),B(b),!A)O(b),P(new Set),M(new Set);Q.scrollToIndex(Te.rowItem[b.row]??b.row,{align:"auto"}),Lt.scrollToIndex(b.column,{align:"auto"})},Gt=(b=I,A)=>{if(!s||q||v||ue||_||g[b.column]?.generation==="autoIncrement")return;let F=h[b.row],ae=g[b.column];if(!F||!ae||ae.type==="blob"||it(ae))return;if(c.has(F.id))return;z(!0),E(w),ce.current=!1;let X=ae.type==="linkedRecord"?JSON.stringify(F.values[ae.id]??[]):ae.type==="relation"?ps(F,ae):ae.type==="json"&&F.values[ae.id]!=null?JSON.stringify(F.values[ae.id]):at(F.values[ae.id]);K({rowId:F.id,expectedVersion:F.version,field:ae,originalText:X,text:ae.type==="linkedRecord"||ae.type==="relation"?X:A??X}),ye(r.optimisticEdit?"":o("Unsaved changes")),ie(null),Ce(null)},Vt=pn([]),fn=pn([]),[Dn,Tn]=ht(null),ao=(b,A)=>{for(let F of b.items){if(F.op!=="update")continue;let ae=A.items.find((X)=>X.id===F.id);if(!ae)continue;for(let X of[Vt,fn])X.current=X.current.map((U)=>({...U,items:U.items.map((ee)=>ee.op!=="insert"&&ee.id===F.id&&ee.expectedVersion===F.expectedVersion?{...ee,expectedVersion:ae.version}:ee)}))}},Jo=(b,A,F)=>{let ae=b.items;if(!ae.length)return null;let X=new Map(F.map((ee)=>[ee.id,ee])),U=[];if(ae.every((ee)=>ee.op==="update")){let ee=new Map(A.items.map((Ie)=>[Ie.id,Ie]));for(let Ie of ae){if(Ie.op!=="update")continue;let me=X.get(Ie.id);if(!me)return null;U.push({op:"update",id:Ie.id,expectedVersion:ee.get(Ie.id)?.version??Ie.expectedVersion+1,values:Object.fromEntries(Object.keys(Ie.values).map((Ae)=>[Ae,me.values[Ae]??null]))})}}else if(ae.every((ee)=>ee.op==="insert")){if(A.items.length!==ae.length)return null;for(let ee of A.items)U.push({op:"delete",id:ee.id,expectedVersion:ee.version})}else if(ae.every((ee)=>ee.op==="delete"))for(let ee of ae){if(ee.op!=="delete")continue;let Ie=X.get(ee.id);if(!Ie)return null;U.push({op:"insert",values:Object.fromEntries(t.fields.filter((me)=>me.type!=="blob"&&me.type!=="linkedRecord"&&!it(me)&&me.generation!=="autoIncrement"&&Ie.values[me.id]!==void 0).map((me)=>[me.id,Ie.values[me.id]]))})}else return null;return{idempotencyKey:crypto.randomUUID(),items:U}},Rr=(b)=>{if(q||e.readOnly||v||ue||_)return;let F=(b==="undo"?Vt:fn).current.at(-1);if(!F||!d(F))return;Ut({...F,idempotencyKey:crypto.randomUUID()},void 0,b)};async function Ut(b,A,F){if(q||fe.current||!d(b))return;let ae=F&&Dn?Dn.before:h;if(F)Tn({direction:F,before:ae,rejected:!1});fe.current=!0,xe(!0),ie(b),ye("");let X=await e.onMutate(b).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:o("Saving failed. Your edit has been kept.")}}));if(fe.current=!1,xe(!1),X.ok){let U=Jo(b,X.data,ae);if(F)(F==="undo"?Vt:fn).current.pop();if(ao(b,X.data),Tn(null),U)if(F==="undo")fn.current.push(U);else{if(Vt.current.push(U),Vt.current.length>30)Vt.current.shift();if(!F)fn.current=[]}e.onCommitted(X.data),ie(null),K(null),W(!1),Ce(null);let ee=b.items.filter((me)=>me.op==="delete").length,Ie=F?o(F==="undo"?"Undone":"Redone"):ee>0&&ee===b.items.length?o("Deleted {count} records",{count:ee}):o("Saved");if(e.onNotify)ye(""),e.onNotify(Ie);else ye(Ie);S.current?.focus({preventScroll:!0}),A?.()}else{if(F){let ee=X.error.status;Tn({direction:F,before:ae,rejected:ee>=400&&ee<500&&ee!==408})}ye(Oo(X.error,e.locale));let U=X.error.details;if(U?.current)Ce(U.current)}}async function yt(b,A,F,ae){if(x.current.has(b.id)||a.current.readOnly||!a.current.features.rowUpdate)return;x.current.add(b.id),xe(!0);let X=v??{rowId:b.id,expectedVersion:b.version,field:A,text:at(F),originalText:at(b.values[A.id])},U={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:b.id,expectedVersion:b.version,values:{[A.id]:F}}]};f((me)=>({...me,[b.id]:{...me[b.id],[A.id]:F}})),C((me)=>new Set(me).add(b.id)),K(null),ye(""),S.current?.focus({preventScroll:!0});let ee=await e.onMutate(U).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:o("Saving failed. Your edit has been kept.")}}));if(x.current.delete(b.id),xe(!1),C((me)=>{let Ae=new Set(me);return Ae.delete(b.id),Ae}),ee.ok){p.current.add(b.id);let me=Jo(U,ee.data,[b]);if(ao(U,ee.data),me){if(Vt.current.push(me),Vt.current.length>30)Vt.current.shift();fn.current=[]}e.onCommitted(ee.data),ae?.();return}f((me)=>{let Ae={...me};return delete Ae[b.id],Ae}),ce.current=!1,K(X),ie(U),ye(Oo(ee.error,e.locale));let Ie=ee.error.details;if(Ie?.current)Ce(Ie.current)}async function yn(b){if(!v||ce.current||a.current.readOnly||!a.current.features.rowUpdate)return;let{field:A,rowId:F,expectedVersion:ae}=v;if(A.generation==="autoIncrement"||t.fields.find((X)=>X.id===A.id)?.generation==="autoIncrement"){ye(o("{name} is auto-generated and cannot be edited.",{name:A.name})),K(null);return}try{let X=A.type==="linkedRecord"?JSON.parse(v.text):A.type==="relation"?v.text||null:xn(v.text,A);if(A.type==="linkedRecord"&&A.required&&Array.isArray(X)&&!X.length)throw Error(`${A.name} is required.`);if(r.optimisticEdit&&A.type==="linkedRecord"&&!_&&v.text===v.originalText){Yt();return}if(r.optimisticEdit&&A.type!=="linkedRecord"&&!_){let Ie=h.find((me)=>me.id===F);if(!Ie){K(null);return}if(JSON.stringify(X??null)===JSON.stringify(Ie.values[A.id]??null)){Yt();return}await yt(Ie,A,X,()=>{if(b)Wt(vi(I,"Tab",h.length,g.length,b==="previous"))});return}let U={[A.id]:X},ee=_??{idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:F,expectedVersion:ae,values:U}]};await Ut(ee,b?()=>Wt(vi(I,"Tab",h.length,g.length,b==="previous")):void 0)}catch(X){ye((e.locale==="zh-CN"?dr(A,v.text,"zh-CN"):null)||(X instanceof Error?X.message:o("Invalid value")))}}let _t=Boolean(e.readOnly||q||v||ue||_||oo.length===0),Qe=()=>{if(_t||!i)return;Qo()},Yt=()=>{ce.current=!0,ye(""),K(null),ie(null),Ce(null),S.current?.focus({preventScroll:!0})},$n=(b)=>{if(!v||b===v.text)return;ye(r.optimisticEdit?"":o("Unsaved changes")),K({...v,text:b}),ie(null),Ce(null)},Ir=(b,A,F)=>{if(!s||q||v||ue||_)return;if(r.optimisticEdit){yt(b,A,F);return}K({rowId:b.id,expectedVersion:b.version,field:A,text:String(F),originalText:at(b.values[A.id])}),Ut({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:b.id,expectedVersion:b.version,values:{[A.id]:F}}]})},Jt=r.optionChips,Ro=Boolean(e.renderRecordContextMenu)||r.recordContextMenu,Zo=r.optimisticEdit&&!_?{onBlur:(b)=>{if(!b.currentTarget.contains(b.relatedTarget))yn()}}:{},bn=v?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:v.field,text:v.text,disabled:q||!s,autoOpen:!0,onChange:$n,onSave:(b)=>void yn(b),onCancel:Yt}):void 0,oi=r.optimisticEdit&&v?.field.type==="linkedRecord"&&(bn===void 0||bn===null)&&!_&&!q?{onBlur:(b)=>{let A=b.relatedTarget;if(!A||he.current?.contains(A)||A.closest('[role="gridcell"]')?.id===`wb-${v.rowId}-${v.field.id}`)return;yn()}}:{},Fn=v&&(v.field.type==="singleSelect"||v.field.type==="multipleSelect")?bn??mt("select",{"aria-label":o("Edit {name}",{name:v.field.name}),ref:(b)=>b?.focus(),style:kp,multiple:v.field.type==="multipleSelect",value:v.field.type==="multipleSelect"?v.text.split(",").filter(Boolean):v.text,disabled:q||!s,onChange:(b)=>$n(v.field.type==="multipleSelect"?Array.from(b.currentTarget.selectedOptions,(A)=>A.value).join(","):b.currentTarget.value),onKeyDown:(b)=>{if(b.stopPropagation(),b.key==="Escape")b.preventDefault(),Yt();if(b.key==="Tab")b.preventDefault(),yn(b.shiftKey?"previous":"next");if(b.key==="Enter")b.preventDefault(),yn()},children:[v.field.type==="singleSelect"&&Z("option",{value:"",disabled:v.field.required,children:o("Clear selection")}),(v.field.options??[]).map((b)=>Z("option",{value:b.id,children:b.name},b.id)),v.text.split(",").filter((b)=>b&&!v.field.options?.some((A)=>A.id===b)).map((b)=>Z("option",{value:b,disabled:!0,children:o("{id} (unavailable)",{id:b})},b))]}):void 0,Qo=()=>{if(!i||q||v||ue||_||De.length===0)return;if(De.length>100){ye(o("Select at most 100 rows per delete."));return}ie({idempotencyKey:crypto.randomUUID(),items:De.map((b)=>({op:"delete",id:b.id,expectedVersion:b.version}))}),W(!0),ye(""),Ce(null)},Ar=(b,A,F,ae,X)=>{X.setPointerCapture(ae);let U=(Ie)=>e.onViewChange({...n,columnWidths:{...n.columnWidths,[b]:Jr(F+Ie.clientX-A)}}),ee=()=>{X.removeEventListener("pointermove",U),X.removeEventListener("pointerup",ee),X.removeEventListener("pointercancel",ee)};X.addEventListener("pointermove",U),X.addEventListener("pointerup",ee),X.addEventListener("pointercancel",ee)},[Io,Ao]=ht(480);fp(()=>{if(!e.display?.fill)return;let b=()=>{let A=S.current?.getBoundingClientRect().top??0;Ao(Math.max(240,Math.round(window.innerHeight-A-64-(r.footerStats?34:0))))};return b(),window.addEventListener("resize",b),()=>window.removeEventListener("resize",b)},[e.display?.fill,r.footerStats]);let hn=e.display?.summary===!1&&e.display?.keyboardHints===!1,Xo=!!v&&Q.getVirtualItems().some((b)=>{let A=Te.items[b.index];return A?.kind==="row"&&h[A.index]?.id===v.rowId})&&Lt.getVirtualItems().some((b)=>g[b.index]?.id===v.field.id),Nn=mt("section",{"data-uibot":"paged-collection-grid",style:{display:hn?"grid":"flex",flexDirection:hn?void 0:"column",border:"1px solid var(--border, #d5d9df)",borderRadius:8,overflow:"hidden"},children:[(e.display?.summary!==!1||e.display?.keyboardHints!==!1||e.aggregate&&!r.footerStats||e.onInspectRecord||!e.readOnly&&De.length>0&&!e.renderRecordContextMenu&&!r.recordContextMenu)&&mt("div",{"data-uibot":"paged-collection-toolbar",style:{display:"flex",gap:8,padding:8,alignItems:"center",flexWrap:"wrap",...hn?{}:{order:1,padding:"4px 10px",fontSize:12,borderTop:"1px solid var(--border, #d5d9df)"},...hn?{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&&Z("span",{children:$r(o,e.total,h.length,e.locale)}),e.aggregate&&!r.footerStats&&Z(jo,{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}:{}}),Z("span",{style:{flex:1}}),e.display?.keyboardHints!==!1&&Z("span",{style:{fontSize:12},children:o(s?"Arrows · Shift select · Enter edit · Copy / paste":"Arrows · Shift select · Copy")}),e.onInspectRecord&&Z(Y,{ui:e.ui,style:to,variant:"outline",size:"sm",disabled:q||De.length!==1,onClick:()=>{let b=De[0];if(b)e.onInspectRecord?.(b.id)},children:o("Open record activity")}),i&&De.length>0&&!e.renderRecordContextMenu&&!r.recordContextMenu&&Z(Y,{ui:e.ui,style:to,variant:"outline",size:"sm",icon:"trash",disabled:_t,onClick:Qo,children:o("Delete selected rows")})]}),Z("style",{children:`
11
11
  [data-uibot="paged-collection-grid"] [role="gridcell"]:hover > [data-uibot-row-actions],
12
12
  [data-uibot="paged-collection-grid"] [role="gridcell"]:focus-within > [data-uibot-row-actions] { opacity: 1 !important; }
13
13
  [data-uibot="paged-collection-grid"] [role="gridcell"]:hover > [data-uibot-row-number],
@@ -16,11 +16,11 @@ done=Done`})]}),h&&Ze("p",{role:"alert",className:"text-sm text-destructive",chi
16
16
  [data-uibot="paged-collection-grid"] [data-uibot-row-actions] { opacity: 1 !important; }
17
17
  [data-uibot="paged-collection-grid"] [data-uibot-row-number] { opacity: 0 !important; }
18
18
  }
19
- `}),lt(dg,{ui:e.ui,paneRef:f,role:"grid","aria-label":o("{name} records",{name:t.name}),"aria-rowcount":e.total+1,"aria-colcount":h.length+Number(Boolean(ht))+Number(Boolean(K)),"aria-activedescendant":m[k.row]&&h[k.column]?`wb-${m[k.row]?.id}-${h[k.column]?.id}`:void 0,tabIndex:0,style:{gridArea:yn?"1 / 1":void 0,overflow:"auto",height:e.display?.fill?wo:i.autoHeight?Math.min(e.display?.maxHeight??560,Math.max(120,Kl(X,tt)+2+(an?sl:0))):e.display?.maxHeight??480,position:"relative",outlineOffset:-2},onScroll:(b)=>Oe.current?.style.setProperty("--uibot-sx",`${b.currentTarget.scrollLeft}px`),onCopy:(b)=>{if(D)return;b.preventDefault(),b.clipboardData.setData("text/plain",$o())},onPaste:(b)=>{if(D||Z||z||!d||Q)return;if(b.preventDefault(),Me.size){le(o("Expand all groups before pasting."));return}let E=Ql(b.clipboardData.getData("text/plain"),m,h,{row:ot.firstRow,column:ot.firstColumn},e.locale);if(!E.ok){le(E.message);return}ce({idempotencyKey:crypto.randomUUID(),items:E.items}),fe(!0),le(""),xe(null)},onKeyDown:(b)=>{if(b.target!==b.currentTarget&&b.target.closest("button, input, select, textarea, [contenteditable=true]"))return;if((b.metaKey||b.ctrlKey)&&!b.altKey&&!D){let E=b.key.toLowerCase();if(E==="d"||E==="r"){b.preventDefault();let N=E==="d"?{...ot,lastRow:ot.firstRow}:{...ot,lastColumn:ot.firstColumn};hr(N,ot);return}if(E==="z"||E==="y"){b.preventDefault(),It(E==="y"||b.shiftKey?"redo":"undo");return}}if(!D&&b.key==="Escape"){U(new Set),P(new Set);return}if(D||!m.length||!h.length||Q)return;if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End"].includes(b.key)){b.preventDefault();let E=b.key==="Tab"&&b.shiftKey,N=gi(k,b.key,m.length,h.length,E);if(oe(N.row)){let re=b.key==="ArrowUp"||E||N.row<k.row,G=ui(X,N.row,re?-1:1,m.length);if(G<0)return;N={...N,row:G}}qt(N,b.shiftKey&&b.key!=="Tab")}else if(oe(k.row))b.preventDefault();else if(b.key==="Delete"&&we.length>0&&r)b.preventDefault(),zn();else if(d&&["Enter","F2"].includes(b.key))b.preventDefault(),no();else if(d&&b.key.length===1&&!b.metaKey&&!b.ctrlKey&&!b.altKey)b.preventDefault(),no(k,b.key)},children:[Y(tg,{sensors:st,modifiers:[pg],onDragEnd:Rt,children:lt("div",{role:"row",tabIndex:-1,style:{position:"sticky",top:0,height:38,width:ln,zIndex:2,background:"var(--muted, #f4f6f8)"},children:[ht>0&&Y("div",{role:"columnheader",tabIndex:-1,"aria-colindex":1,"aria-label":o("Row"),style:{...Vt(0,!K&&We===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:ht,padding:4,display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center",height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:lt("label",{title:o("{count} selected",{count:we.length}),style:{position:"relative",display:"flex",alignItems:"center"},children:[we.length===0&&Y("span",{"aria-hidden":"true",children:o("Row")}),Y("input",{type:"checkbox","aria-label":o("Select all loaded records"),ref:(b)=>{if(b)b.indeterminate=we.length>0&&we.length<m.filter((E,N)=>!oe(N)).length},style:we.length===0?{position:"absolute",inset:0,width:"100%",height:"100%",margin:0,opacity:0,cursor:"pointer"}:{margin:0,width:16,height:16},onKeyDown:(b)=>b.stopPropagation(),checked:we.length>0&&we.length===m.filter((b,E)=>!oe(E)).length,disabled:Boolean(D||Q||Z||z),onChange:(b)=>{L(!1),w(x),P(new Set),U(b.currentTarget.checked?new Set(m.filter((E,N)=>!oe(N)).map((E)=>E.id)):new Set)},onFocus:(b)=>{b.currentTarget.parentElement?.style.setProperty("outline","2px solid var(--ring, currentColor)")},onBlur:(b)=>{b.currentTarget.parentElement?.style.removeProperty("outline")}})]})}),K>0&&Y("div",{role:"columnheader",tabIndex:-1,"aria-colindex":ht>0?2:1,style:{...Vt(ht,We===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:K,padding:8,height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:o("Record ID")}),dt.map((b)=>{let E=h[b.index];if(!E)return null;let N=zi(n.columnColors?.[E.id]),re=n.sort?.find((be)=>be.fieldId===E.id),G=i.sorting&&E.type!=="linkedRecord"&&cn(E),V=e.fieldMenu?.(E)??[],ne=V.length?e.ui?.DropdownMenu?e.ui.DropdownMenu({label:o("Field menu {name}",{name:E.name}),icon:Y(Ce,{name:"chevronDown"}),items:V}):Y(_i,{label:o("Field menu {name}",{name:E.name}),icon:Y(Ce,{name:"chevronDown"}),items:V},E.id):null,Pe=Y(mg,{id:E.id,disabled:!i.columnReorder,children:(be)=>lt("div",{ref:be.setNodeRef,...be.listeners,role:"columnheader","data-uibot-field":E.id,tabIndex:-1,"aria-colindex":b.index+1+Number(Boolean(ht))+Number(Boolean(K)),onKeyDown:(Re)=>{if(Re.shiftKey&&Re.key==="F10"||Re.key==="ContextMenu"){Re.preventDefault(),Re.stopPropagation();let he=Re.currentTarget.querySelector('button[aria-haspopup="menu"]');he?.focus({preventScroll:!0}),he?.click(),he?.dispatchEvent(new KeyboardEvent("keydown",{key:"ArrowDown",bubbles:!0}))}},"aria-sort":re?re.direction==="asc"?"ascending":"descending":"none",style:{...b.index<We?{...Vt(mn(b.index),b.index===We-1),background:"var(--muted, #f4f6f8)"}:{position:"absolute",left:b.start},boxSizing:"border-box",background:N?.background??"var(--muted, #f4f6f8)",borderTopWidth:N?3:void 0,borderTopStyle:N?"solid":void 0,borderTopColor:N?.marker,width:b.size,height:38,borderRight:"1px solid var(--border, #d5d9df)",display:"flex",alignItems:"center",...be.style},children:[lt("button",{type:"button",disabled:!G,title:G||!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:lg(n.sort??[],E.id)}),children:[i.fieldTypeIcons&&Y(Vi,{type:E.type}),i.fieldTypeIcons?Y("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:E.name}):E.name,E.ai?Y("span",{role:"img","aria-label":o("AI field"),title:o("AI field"),"data-uibot-ai-field":"",style:{display:"inline-flex",flex:"none",opacity:0.7},children:Y(Ce,{name:"sparkles",size:12})}):null,re?Y(Ce,{name:re.direction==="asc"?"sortAsc":"sortDesc",size:12,style:{marginLeft:"auto",opacity:0.7}}):null]}),ne,i.columnResize&&Y("button",{type:"button","aria-label":o("Resize {name}",{name:E.name}),style:{border:0,background:"transparent",position:"absolute",top:0,bottom:0,right:-3,width:7,padding:0,cursor:"col-resize",zIndex:2},onPointerDown:(Re)=>{Re.stopPropagation(),ko(E.id,Re.clientX,b.size,Re.pointerId,Re.currentTarget)},onKeyDown:(Re)=>{if(Re.key==="ArrowLeft"||Re.key==="ArrowRight")Re.preventDefault(),e.onViewChange({...n,columnWidths:{...n.columnWidths,[E.id]:Hr(b.size+(Re.key==="ArrowRight"?20:-20))}})}})]})},E.id);return V.length&&e.ui?.ContextMenu?Y(e.ui.ContextMenu,{items:V,"aria-label":o("Field menu {name}",{name:E.name}),children:Pe},E.id):Pe}),e.onAddField&&Y("div",{"data-uibot-add-field":"",style:{position:"absolute",left:ln-ll,width:ll,height:38,boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--muted, #f4f6f8)",borderRight:"1px solid var(--border, #d5d9df)"},children:Y("button",{type:"button","aria-label":o("Add field"),title:o("Add field"),onClick:()=>e.onAddField?.(),style:{border:0,background:"transparent",color:"inherit",cursor:"pointer",width:"100%",height:"100%",display:"grid",placeItems:"center"},children:Y(Ce,{name:"plus"})})})]})}),lt("div",{style:{position:"relative",width:ln,height:rn.getTotalSize()+(an?sl:0)},children:[rn.getVirtualItems().map((b)=>{let E=X.items[b.index];if(E?.kind==="group"){let G=E.label===null?o("Not set"):E.label==="true"?o("Checked"):E.label==="false"?o("Unchecked"):E.label;return Y("div",{role:"presentation","data-uibot-group":G,style:{position:"absolute",top:b.start-38,height:b.size,width:ln,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"},children:lt("button",{type:"button","aria-expanded":!E.collapsed,"aria-label":o(E.collapsed?"Expand group {name}":"Collapse group {name}",{name:G}),disabled:!i.groupCollapse,onClick:()=>Rn(E.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&&Y("span",{"aria-hidden":"true",style:{width:10,fontSize:10,opacity:0.6},children:E.collapsed?"▸":"▾"}),Y($a,{index:E.colorIndex,children:G}),Y("span",{style:{opacity:0.6},children:o("{count} records",{count:E.count})})]})},E.key)}let N=E?m[E.index]:void 0;if(E?.kind!=="row"||!N)return null;let re=E.index;return lt("div",{role:"row",tabIndex:-1,"aria-rowindex":(e.rowOffset??0)+re+2,style:{position:"absolute",top:b.start-38,height:b.size,width:ln},children:[ht>0&&lt("div",{role:"gridcell",tabIndex:-1,"aria-colindex":1,"aria-label":String((e.rowOffset??0)+re+1),"aria-readonly":"true","aria-selected":Ut.has(N.id),style:{...Vt(0,!K&&We===0),width:ht,height:b.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:Ut.has(N.id)?"var(--accent, #e8f0fe)":"var(--muted, #f4f6f8)"},onMouseDown:(G)=>{if(D||G.button!==0||h.length===0)return;if(G.target.closest("button, input"))return;if(G.preventDefault(),G.ctrlKey||G.metaKey){eo(re),f.current?.focus({preventScroll:!0});return}if(!G.shiftKey)qt({row:re,column:0});qt({row:re,column:h.length-1},!0),f.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!vr||h.length===0)return;if(!Ut.has(N.id))qt({row:re,column:0})},children:[Y("span",{"data-uibot-row-number":"",style:{opacity:Ut.has(N.id)?0:1},children:(e.rowOffset??0)+re+1}),lt("span",{"data-uibot-row-actions":"",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",gap:4,opacity:Ut.has(N.id)?1:0},children:[Y("input",{type:"checkbox","aria-label":o("Select row"),checked:Ut.has(N.id),disabled:Boolean(D||Q||Z||z),onChange:()=>eo(re),onClick:(G)=>G.stopPropagation()}),e.onExpandRecord&&Y("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?.(N),children:Y(Ce,{name:"expand"})})]})]}),K>0&&Y("div",{role:"gridcell",tabIndex:-1,"aria-colindex":ht>0?2:1,"aria-readonly":"true",style:{...Vt(ht,We===0),background:"var(--background, white)",boxSizing:"border-box",width:K,height:b.size,padding:7,borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)"},onContextMenu:()=>{if(!vr)return;if(!Ut.has(N.id))qt({row:re,column:0})},children:Y("input",{"aria-label":o("Record ID {id}",{id:N.id}),readOnly:!0,value:N.id,style:{width:"100%",border:0,background:"transparent",color:"inherit",fontSize:12},onCopy:(G)=>G.stopPropagation(),onPaste:(G)=>G.stopPropagation(),onKeyDown:(G)=>G.stopPropagation()})}),dt.map((G)=>{let V=h[G.index];if(!V)return null;let ne={row:re,column:G.index},Pe=Ut.has(N.id)&&(M.has(N.id)||A&&ne.column>=ot.firstColumn&&ne.column<=ot.lastColumn),be=D?.rowId===N.id&&D.field.id===V.id,Re=!be&&V.type==="checkbox"?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:V,text:et(N.values[V.id]),disabled:Boolean(!d||Q||D||Z||z),mode:"inline",autoOpen:!1,onChange:(he)=>{if(!d||Q||D||Z||z)return;try{let Ue=Cn(he,V);B({rowId:N.id,expectedVersion:N.version,field:V,text:he,originalText:et(N.values[V.id])}),Ht({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:N.id,expectedVersion:N.version,values:{[V.id]:Ue}}]})}catch(Ue){le(e.locale==="zh-CN"?rr(V,he,"zh-CN"):Ue instanceof Error?Ue.message:o("Invalid value"))}},onSave:()=>{},onCancel:Jt}):void 0;return lt("div",{id:`wb-${N.id}-${V.id}`,role:"gridcell",tabIndex:-1,...be&&V.type==="linkedRecord"?xr:{},"aria-colindex":G.index+1+Number(Boolean(ht))+Number(Boolean(K)),"aria-selected":Pe,"aria-readonly":!d||V.generation==="autoIncrement"||V.type==="blob"||it(V),style:{...G.index<We?Vt(mn(G.index),G.index===We-1):{position:"absolute",left:G.start},width:G.size,height:b.size,padding:be?0:sn?"0 10px":7,boxSizing:"border-box",borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",overflow:be?"visible":"hidden",...be?{zIndex:3}:{},whiteSpace:"nowrap",...sn&&!be?{display:"flex",alignItems:"center",fontSize:13}:{},...Pt>1&&!be&&(V.type==="singleLineText"||V.type==="longText")?{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:Pt,whiteSpace:"normal",wordBreak:"break-word",padding:sn?"6px 10px":7}:{},background:Pe?"var(--accent, #e8f0fe)":zi(n.columnColors?.[V.id])?.background??"var(--background, white)",outline:k.row===ne.row&&k.column===ne.column?"2px solid #6488bd":"none",outlineOffset:-2},onMouseEnter:()=>{if(!vt)return;let he=Math.max(vt.firstRow-ne.row,ne.row-vt.lastRow,0),Ue=Math.max(vt.firstColumn-ne.column,ne.column-vt.lastColumn,0);vo.current=he>=Ue?{...vt,firstRow:Math.min(ne.row,vt.firstRow),lastRow:Math.max(ne.row,vt.lastRow)}:{...vt,firstColumn:Math.min(ne.column,vt.firstColumn),lastColumn:Math.max(ne.column,vt.lastColumn)}},onMouseDown:(he)=>{if(vt||D)return;if(he.button!==0)return;he.preventDefault(),qt(ne,he.shiftKey),f.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!vr)return;if(!(Ut.has(N.id)&&(M.has(N.id)||ne.column>=ot.firstColumn&&ne.column<=ot.lastColumn)))qt(ne)},onClick:(he)=>{if(!D&&!he.shiftKey&&(V.type==="singleSelect"||V.type==="multipleSelect"))no(ne)},onDoubleClick:()=>no(ne),children:[to&&ne.row===ot.lastRow&&ne.column===ot.lastColumn&&Y("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:vt?"grabbing":"grab",zIndex:4},onMouseDown:(he)=>{he.preventDefault(),he.stopPropagation(),vo.current=null,Co(ot)},onClick:(he)=>he.stopPropagation()}),be&&Mt!==void 0&&Mt!==null?Mt:be&&V.type==="relation"?Y(Br,{locale:e.locale,field:V,value:D.text,label:o("Edit {name}",{name:V.name}),getOptions:e.getRelationOptions,labels:N.linkedRecords?.[V.id],disabled:Q,onChange:(he)=>{le(i.optimisticEdit?"":o("Unsaved changes")),B({...D,text:he}),ce(null),xe(null)}}):be&&xo!==void 0?Y("div",{style:{display:"contents"},...Yr,children:xo}):be&&V.type!=="linkedRecord"?Y("div",{style:{display:"contents"},...Yr,children:Y(ba,{field:V,text:D.text,disabled:Q||Boolean(e.readOnly),locale:e.locale,ariaLabel:o("Edit {name}",{name:V.name}),onChange:An,onSave:(he)=>void Be(he),onCancel:Jt})}):V.type==="relation"||V.type==="linkedRecord"?No(N,V):V.type==="lookup"?so(N.values[V.id]):V.type==="formula"||V.type==="rollup"?tr(N.values[V.id],N.computedErrors?.[V.id]):V.type==="checkbox"&&Re!==void 0&&Re!==null?Re:V.type==="checkbox"&&sn?Y(Vs,{checked:N.values[V.id]===!0,label:o("Edit {name}",{name:V.name}),onToggle:!d||Q||D||Z||z||V.generation==="autoIncrement"?void 0:()=>Cr(N,V,N.values[V.id]!==!0)}):V.type==="checkbox"?Y("input",{type:"checkbox","aria-label":o("Edit {name}",{name:V.name}),checked:N.values[V.id]===!0,ref:(he)=>{if(he)he.indeterminate=N.values[V.id]==null},disabled:!d||Q||Boolean(D)||Boolean(Z)||Boolean(z)||V.generation==="autoIncrement",onMouseDown:(he)=>he.stopPropagation(),onKeyDown:(he)=>he.stopPropagation(),onChange:(he)=>{if(!d||Q||D||Z||z)return;let Ue=he.currentTarget.checked;B({rowId:N.id,expectedVersion:N.version,field:V,text:String(Ue),originalText:et(N.values[V.id])}),Ht({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:N.id,expectedVersion:N.version,values:{[V.id]:Ue}}]})}}):V.type==="date"?Y("span",{title:et(N.values[V.id]),style:sn?{opacity:0.75,fontVariantNumeric:"tabular-nums"}:void 0,children:(()=>{let he=Et(V);return he?$n(N.values[V.id],he):pi(N.values[V.id])})()}):V.type==="number"&&sn?Y("span",{style:{display:"block",width:"100%",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:(()=>{let he=Fo(V);return he?To(N.values[V.id],he):et(N.values[V.id])})()}):sn&&V.type==="singleSelect"&&N.values[V.id]!=null?Y(qo,{ids:[N.values[V.id]],field:V,wrap:Pt>1}):sn&&V.type==="multipleSelect"&&Array.isArray(N.values[V.id])?Y(qo,{ids:N.values[V.id],field:V,wrap:Pt>1}):V.type==="hyperlink"?Y(bi,{value:N.values[V.id]}):V.type==="singleSelect"?V.options?.find((he)=>he.id===N.values[V.id])?.name??et(N.values[V.id]):V.type==="multipleSelect"&&Array.isArray(N.values[V.id])?N.values[V.id].map((he)=>V.options?.find((Ue)=>Ue.id===he)?.name??String(he)).join(", "):et(N.values[V.id])]},V.id)})]},N.id)}),an?Y("div",{style:{position:"absolute",top:rn.getTotalSize(),left:0,width:ln,height:sl,borderBottom:"1px solid var(--border, #d5d9df)"},children:lt("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:[Y(Ce,{name:"plus"}),o("Add record")]})}):null]})]}),i.footerStats&&(n.type??"grid")==="grid"&&h.length>0?Y(fg,{ui:e.ui,locale:e.locale,t:o,rows:m,total:e.total,descriptor:t,aggregateClient:e.serverFooterStats===!1?void 0:e.aggregate?.client,reloadKey:e.reloadKey,fields:h,columns:dt,width:ln,frozenCount:We,frozenLeft:mn,view:n,footerRef:Oe,onChange:e.onViewChange}):null,D&&(z||!(i.optimisticEdit&&D.field.type!=="linkedRecord"))&&!(Jo&&Mt!==void 0&&Mt!==null)&&lt("div",{ref:ae,...xr,role:"dialog","aria-label":o("{name} editor",{name:D.field.name}),style:{padding:8,display:"flex",flexWrap:"wrap",gap:8},onKeyDown:(b)=>{if(D.field.type==="linkedRecord"&&b.key==="Escape"&&!Q)b.preventDefault(),b.stopPropagation(),Jt()},children:[!Jo&&D.field.type!=="linkedRecord"&&(Mt??xo??(D.field.type==="relation"?Y(Br,{locale:e.locale,field:D.field,value:D.text,label:o("Edit {name}",{name:D.field.name}),getOptions:e.getRelationOptions,labels:m.find((b)=>b.id===D.rowId)?.linkedRecords?.[D.field.id],disabled:Q,onChange:An}):Y(ba,{field:D.field,text:D.text,disabled:Q||Boolean(e.readOnly),locale:e.locale,ariaLabel:o("Edit {name}",{name:D.field.name}),onChange:An,onSave:(b)=>void Be(b),onCancel:Jt}))),D.field.type==="linkedRecord"&&Y("div",{style:{width:"100%"},children:Y(mi,{disabled:Q,field:D.field,value:JSON.parse(D.text),locale:e.locale,labels:m.find((b)=>b.id===D.rowId)?.linkedRecords?.[D.field.id],client:e.relationClient,onChange:(b)=>{B({...D,text:JSON.stringify(b)}),ce(null),xe(null)}})}),Y(W,{ui:e.ui,style:Zn,variant:"outline",size:"sm",disabled:Q,onClick:()=>void Be(),children:Q?o("Saving…"):o("Save edit")}),Y(W,{ui:e.ui,style:Zn,variant:"outline",size:"sm",disabled:Q,onClick:Jt,children:o("Cancel edit")})]}),Z&&z&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:z.items.every((b)=>b.op==="delete"),title:z.items.every((b)=>b.op==="delete")?o("Delete {count} records?",{count:z.items.length}):o("Apply {count} row changes in one transaction?",{count:z.items.length}),description:z.items.every((b)=>b.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:Q?o("Saving…"):z.items.every((b)=>b.op==="delete")?o("Delete"):o("Confirm changes"),cancelLabel:z.items.every((b)=>b.op==="delete")?o("Cancel"):o("Cancel changes"),busy:Q,onConfirm:()=>void Ht(z),onCancel:()=>{fe(!1),ce(null),xe(null)}}):null,Z&&z&&!e.ui?.ConfirmDialog&&lt(hi,{label:o("Confirm bulk change"),busy:Q,onCancel:()=>{fe(!1),ce(null),xe(null)},children:[Y("p",{children:o("Apply {count} row changes in one transaction?",{count:z.items.length})}),Y("p",{style:{fontSize:12},children:o("If any record changed or any value is invalid, all changes are rejected.")}),Y(W,{ui:e.ui,style:Zn,variant:"outline",size:"sm",disabled:Q,onClick:()=>void Ht(z),children:Q?o("Saving…"):o("Confirm changes")})," ",Y(W,{ui:e.ui,style:Zn,variant:"outline",size:"sm",disabled:Q,onClick:()=>{fe(!1),ce(null),xe(null)},children:o("Cancel changes")})]}),Yt&&z&&lt("div",{role:"group","aria-label":o("Undo/redo recovery"),style:{padding:8},children:[!Q&&te&&Y("p",{role:"alert",children:te}),Y(W,{ui:e.ui,style:Zn,variant:"outline",size:"sm",disabled:Q||Boolean(e.readOnly),onClick:()=>void Ht(z,void 0,Yt.direction),children:o("Retry undo/redo")})," ",Yt.rejected&&Y(W,{ui:e.ui,style:Zn,variant:"outline",size:"sm",disabled:Q,onClick:()=>{Wt.current=[],Gt.current=[],oo(null),ce(null),xe(null),le("")},children:o("Clear undo/redo history")})]}),ve&&!Yt&&lt("div",{style:{padding:12},children:[Y("strong",{children:o("Current server version {version}",{version:ve.version})}),Y("div",{style:{display:"grid",gap:8,margin:"8px 0"},children:z?.items.flatMap((b)=>b.op==="update"&&b.id===ve.id?Object.entries(b.values).map(([E,N])=>{let re=t.fields.find((V)=>V.id===E),G=(V)=>re?.options?.find((ne)=>ne.id===V)?.name??et(V);return lt("div",{style:{border:"1px solid var(--border,#d5d9df)",borderRadius:6,padding:8},children:[Y("strong",{children:re?.name??E}),lt("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"minmax(90px,auto) 1fr",gap:4},children:[Y("dt",{children:o("Your edit")}),Y("dd",{style:{margin:0,whiteSpace:"pre-wrap"},children:G(N)}),Y("dt",{children:o("Server value")}),Y("dd",{style:{margin:0,whiteSpace:"pre-wrap"},children:G(ve.values[E])})]})]},E)}):[])}),Y(W,{ui:e.ui,style:Zn,variant:"outline",size:"sm",disabled:Q,onClick:()=>{if(!z)return;let b=z.items.map((E)=>E.op!=="insert"&&E.id===ve.id?{...E,expectedVersion:ve.version}:E);Ht({idempotencyKey:crypto.randomUUID(),items:b})},children:o("Retry against current version")})]}),Y("p",{role:"status","aria-live":"polite",style:e.onNotify?cg:{margin:0,padding:te||Q?8:0},children:Q?o("Saving…"):Yt?"":te})]}),$i=t.fields.filter((b)=>b.type!=="blob"&&b.type!=="linkedRecord"&&!it(b)&&b.generation!=="autoIncrement"),Po=()=>{if(!l||In||we.length===0||we.length>100)return;Ht({idempotencyKey:crypto.randomUUID(),items:we.map((b)=>({op:"insert",values:Object.fromEntries($i.flatMap((E)=>b.values[E.id]===void 0?[]:[[E.id,b.values[E.id]]]))}))})};if(e.renderRecordContextMenu){let b=we.length===1?we[0]:void 0;return e.renderRecordContextMenu({children:ro,recordIds:Xn,disabled:In,onDelete:Yo,...e.onExpandRecord&&b?{onExpand:()=>e.onExpandRecord?.(b)}:{},onCopy:()=>void navigator.clipboard?.writeText($o()),...l?{onDuplicate:Po}:{}})}if(!i.recordContextMenu)return ro;let wr=[...e.onExpandRecord&&we.length===1?[{id:"expand",icon:Y(Ce,{name:"expand"}),label:o("Expand record"),onSelect:()=>{let b=we[0];if(b)e.onExpandRecord?.(b)}}]:[],...l?[{id:"duplicate",icon:Y(Ce,{name:"copy"}),label:o("Duplicate {count} selected records",{count:we.length}),disabled:In||we.length===0,onSelect:Po}]:[],{id:"copy",separatorBefore:!0,icon:Y(Ce,{name:"copy"}),label:o("Copy cells"),disabled:we.length===0,onSelect:()=>{navigator.clipboard?.writeText($o())}},...r?[{id:"delete",icon:Y(Ce,{name:"trash"}),label:o("Delete {count} selected records",{count:we.length}),separatorBefore:!0,destructive:!0,disabled:In,onSelect:Yo}]:[]],So=e.ui?.ContextMenu;return So?Y(So,{items:wr,"aria-label":o("Record actions"),children:ro}):Y(Ui,{block:!0,items:wr,label:o("Record actions"),children:ro})}function dg({ui:e,paneRef:t,style:n,children:o,...i}){if(e?.ScrollArea)return e.ScrollArea({viewportRef:t,viewportProps:i,style:n,children:o});return Y("div",{ref:t,style:n,...i,children:o})}var cg={position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:0},ug=96,gg=560,Hr=(e)=>Math.max(ug,Math.min(gg,Math.round(e))),pg=({transform:e})=>({...e,y:0});function mg({id:e,disabled:t,children:n}){let{setNodeRef:o,listeners:i,transform:r,isDragging:l}=og({id:e,disabled:t});return Sn(()=>{if(!l)return;let d=document.body.style.cursor;return document.body.style.cursor="grabbing",()=>{document.body.style.cursor=d}},[l]),n({setNodeRef:o,listeners:t?void 0:i,style:{...r?{transform:`translate3d(${Math.round(r.x)}px, 0, 0)`}:{},...l?{cursor:"grabbing",zIndex:6,opacity:0.9,background:"var(--accent, #e8f0fe)",boxShadow:"0 2px 10px color-mix(in srgb, currentColor 22%, transparent)"}:{}}})}function fg({descriptor:e,aggregateClient:t,reloadKey:n,ui:o,locale:i,t:r,rows:l,total:d,fields:a,columns:s,width:u,frozenCount:c,frozenLeft:g,view:p,footerRef:m,onChange:h}){let x=ld(e,p,a,l,t,n),C=(w,f,R)=>{let S={...p.footerStats??{}};if(f)S[w]=f;else if(R)S[w]="none";else delete S[w];let{footerStats:A,...L}=p;h(Object.keys(S).length?{...L,footerStats:S}:L)};return lt("div",{ref:m,"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:[Y("style",{children:`
19
+ `}),mt(Pp,{ui:e.ui,paneRef:S,role:"grid","aria-label":o("{name} records",{name:t.name}),"aria-rowcount":e.total+1,"aria-colcount":g.length+Number(Boolean(ge))+Number(Boolean(Pe)),"aria-activedescendant":h[I.row]&&g[I.column]?`wb-${h[I.row]?.id}-${g[I.column]?.id}`:void 0,tabIndex:0,style:{gridArea:hn?"1 / 1":void 0,overflow:"auto",height:e.display?.fill?Io:r.autoHeight?Math.min(e.display?.maxHeight??560,Math.max(120,os(Te,In)+2+(ft?hl:0))):e.display?.maxHeight??480,position:"relative",outlineOffset:-2},onScroll:(b)=>Le.current?.style.setProperty("--uibot-sx",`${b.currentTarget.scrollLeft}px`),onCopy:(b)=>{if(v)return;b.preventDefault(),b.clipboardData.setData("text/plain",Hn())},onPaste:(b)=>{if(v||ue||_||!s||q)return;if(b.preventDefault(),D.size){ye(o("Expand all groups before pasting."));return}let A=us(b.clipboardData.getData("text/plain"),h,g,{row:Ke.firstRow,column:Ke.firstColumn},e.locale);if(!A.ok){ye(A.message);return}ie({idempotencyKey:crypto.randomUUID(),items:A.items}),W(!0),ye(""),Ce(null)},onKeyDown:(b)=>{if(b.target!==b.currentTarget&&b.target.closest("button, input, select, textarea, [contenteditable=true]"))return;if((b.metaKey||b.ctrlKey)&&!b.altKey&&!v){let A=b.key.toLowerCase();if(A==="d"||A==="r"){b.preventDefault();let F=A==="d"?{...Ke,lastRow:Ke.firstRow}:{...Ke,lastColumn:Ke.firstColumn};ni(F,Ke);return}if(A==="z"||A==="y"){b.preventDefault(),Rr(A==="y"||b.shiftKey?"redo":"undo");return}}if(!v&&b.key==="Escape"){P(new Set),M(new Set);return}if(v||!h.length||!g.length||q)return;if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End"].includes(b.key)){b.preventDefault();let A=b.key==="Tab"&&b.shiftKey,F=vi(I,b.key,h.length,g.length,A);if(ot(F.row)){let ae=b.key==="ArrowUp"||A||F.row<I.row,X=Ci(Te,F.row,ae?-1:1,h.length);if(X<0)return;F={...F,row:X}}Wt(F,b.shiftKey&&b.key!=="Tab")}else if(ot(I.row))b.preventDefault();else if(b.key==="Delete"&&De.length>0&&i)b.preventDefault(),Qo();else if(s&&["Enter","F2"].includes(b.key))b.preventDefault(),Gt();else if(s&&b.key.length===1&&!b.metaKey&&!b.ctrlKey&&!b.altKey)b.preventDefault(),Gt(I,b.key)},children:[Z(yp,{sensors:Tt,modifiers:[Ap],onDragEnd:kr,children:mt("div",{role:"row",tabIndex:-1,style:{position:"sticky",top:0,height:38,width:rn,zIndex:2,background:"var(--muted, #f4f6f8)"},children:[ge>0&&Z("div",{role:"columnheader",tabIndex:-1,"aria-colindex":1,"aria-label":o("Row"),style:{...Ot(0,!Pe&&Ze===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:ge,padding:4,display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center",height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:mt("label",{title:o("{count} selected",{count:De.length}),style:{position:"relative",display:"flex",alignItems:"center"},children:[De.length===0&&Z("span",{"aria-hidden":"true",children:o("Row")}),Z("input",{type:"checkbox","aria-label":o("Select all loaded records"),ref:(b)=>{if(b)b.indeterminate=De.length>0&&De.length<h.filter((A,F)=>!ot(F)).length},style:De.length===0?{position:"absolute",inset:0,width:"100%",height:"100%",margin:0,opacity:0,cursor:"pointer"}:{margin:0,width:16,height:16},onKeyDown:(b)=>b.stopPropagation(),checked:De.length>0&&De.length===h.filter((b,A)=>!ot(A)).length,disabled:Boolean(v||q||ue||_),onChange:(b)=>{z(!1),E(w),M(new Set),P(b.currentTarget.checked?new Set(h.filter((A,F)=>!ot(F)).map((A)=>A.id)):new Set)},onFocus:(b)=>{b.currentTarget.parentElement?.style.setProperty("outline","2px solid var(--ring, currentColor)")},onBlur:(b)=>{b.currentTarget.parentElement?.style.removeProperty("outline")}})]})}),Pe>0&&Z("div",{role:"columnheader",tabIndex:-1,"aria-colindex":ge>0?2:1,style:{...Ot(ge,Ze===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:Pe,padding:8,height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:o("Record ID")}),mn.map((b)=>{let A=g[b.index];if(!A)return null;let F=Zi(n.columnColors?.[A.id]),ae=n.sort?.find((me)=>me.fieldId===A.id),X=r.sorting&&A.type!=="linkedRecord"&&ln(A),U=e.fieldMenu?.(A)??[],ee=U.length?e.ui?.DropdownMenu?e.ui.DropdownMenu({label:o("Field menu {name}",{name:A.name}),icon:Z(ve,{name:"chevronDown"}),items:U}):Z(Ji,{label:o("Field menu {name}",{name:A.name}),icon:Z(ve,{name:"chevronDown"}),items:U},A.id):null,Ie=Z(Ep,{id:A.id,disabled:!r.columnReorder,children:(me)=>mt("div",{ref:me.setNodeRef,...me.listeners,role:"columnheader","data-uibot-field":A.id,tabIndex:-1,"aria-colindex":b.index+1+Number(Boolean(ge))+Number(Boolean(Pe)),onKeyDown:(Ae)=>{if(Ae.shiftKey&&Ae.key==="F10"||Ae.key==="ContextMenu"){Ae.preventDefault(),Ae.stopPropagation();let be=Ae.currentTarget.querySelector('button[aria-haspopup="menu"]');be?.focus({preventScroll:!0}),be?.click(),be?.dispatchEvent(new KeyboardEvent("keydown",{key:"ArrowDown",bubbles:!0}))}},"aria-sort":ae?ae.direction==="asc"?"ascending":"descending":"none",style:{...b.index<Ze?{...Ot(gn(b.index),b.index===Ze-1),background:"var(--muted, #f4f6f8)"}:{position:"absolute",left:b.start},boxSizing:"border-box",background:F?.background??"var(--muted, #f4f6f8)",borderTopWidth:F?3:void 0,borderTopStyle:F?"solid":void 0,borderTopColor:F?.marker,width:b.size,height:38,borderRight:"1px solid var(--border, #d5d9df)",display:"flex",alignItems:"center",...me.style},children:[mt("button",{type:"button",disabled:!X,title:X||!r.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",...r.fieldTypeIcons?{display:"flex",alignItems:"center",gap:6,fontSize:12,fontWeight:600,whiteSpace:"nowrap"}:{}},onClick:()=>e.onViewChange({...n,sort:wp(n.sort??[],A.id)}),children:[r.fieldTypeIcons&&Z(Wi,{type:A.type}),r.fieldTypeIcons?Z("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:A.name}):A.name,A.ai?Z("span",{role:"img","aria-label":o("AI field"),title:o("AI field"),"data-uibot-ai-field":"",style:{display:"inline-flex",flex:"none",opacity:0.7},children:Z(ve,{name:"sparkles",size:12})}):null,ae?Z(ve,{name:ae.direction==="asc"?"sortAsc":"sortDesc",size:12,style:{marginLeft:"auto",opacity:0.7}}):null]}),ee,r.columnResize&&Z("button",{type:"button","aria-label":o("Resize {name}",{name:A.name}),style:{border:0,background:"transparent",position:"absolute",top:0,bottom:0,right:-3,width:7,padding:0,cursor:"col-resize",zIndex:2},onPointerDown:(Ae)=>{Ae.stopPropagation(),Ar(A.id,Ae.clientX,b.size,Ae.pointerId,Ae.currentTarget)},onKeyDown:(Ae)=>{if(Ae.key==="ArrowLeft"||Ae.key==="ArrowRight")Ae.preventDefault(),e.onViewChange({...n,columnWidths:{...n.columnWidths,[A.id]:Jr(b.size+(Ae.key==="ArrowRight"?20:-20))}})}})]})},A.id);return U.length&&e.ui?.ContextMenu?Z(e.ui.ContextMenu,{items:U,"aria-label":o("Field menu {name}",{name:A.name}),children:Ie},A.id):Ie}),e.onAddField&&Z("div",{"data-uibot-add-field":"",style:{position:"absolute",left:rn-bl,width:bl,height:38,boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--muted, #f4f6f8)",borderRight:"1px solid var(--border, #d5d9df)"},children:Z("button",{type:"button","aria-label":o("Add field"),title:o("Add field"),onClick:()=>e.onAddField?.(),style:{border:0,background:"transparent",color:"inherit",cursor:"pointer",width:"100%",height:"100%",display:"grid",placeItems:"center"},children:Z(ve,{name:"plus"})})})]})}),mt("div",{style:{position:"relative",width:rn,height:Q.getTotalSize()+(ft?hl:0)},children:[Q.getVirtualItems().map((b)=>{let A=Te.items[b.index];if(A?.kind==="group"){let X=A.label===null?o("Not set"):A.label==="true"?o("Checked"):A.label==="false"?o("Unchecked"):A.label;return Z("div",{role:"presentation","data-uibot-group":X,style:{position:"absolute",top:b.start-38,height:b.size,width:rn,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"},children:mt("button",{type:"button","aria-expanded":!A.collapsed,"aria-label":o(A.collapsed?"Expand group {name}":"Collapse group {name}",{name:X}),disabled:!r.groupCollapse,onClick:()=>Sr(A.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:r.groupCollapse?"pointer":"default"},children:[r.groupCollapse&&Z("span",{"aria-hidden":"true",style:{width:10,fontSize:10,opacity:0.6},children:A.collapsed?"▸":"▾"}),Z(el,{index:A.colorIndex,children:X}),Z("span",{style:{opacity:0.6},children:o("{count} records",{count:A.count})})]})},A.key)}let F=A?h[A.index]:void 0;if(A?.kind!=="row"||!F)return null;let ae=A.index;return mt("div",{role:"row",tabIndex:-1,"aria-rowindex":(e.rowOffset??0)+ae+2,style:{position:"absolute",top:b.start-38,height:b.size,width:rn},children:[ge>0&&mt("div",{role:"gridcell",tabIndex:-1,"aria-colindex":1,"aria-label":String((e.rowOffset??0)+ae+1),"aria-readonly":"true","aria-selected":Bt.has(F.id),style:{...Ot(0,!Pe&&Ze===0),width:ge,height:b.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:Bt.has(F.id)?"var(--accent, #e8f0fe)":"var(--muted, #f4f6f8)"},onMouseDown:(X)=>{if(v||X.button!==0||g.length===0)return;if(X.target.closest("button, input"))return;if(X.preventDefault(),X.ctrlKey||X.metaKey){So(ae),S.current?.focus({preventScroll:!0});return}if(!X.shiftKey)Wt({row:ae,column:0});Wt({row:ae,column:g.length-1},!0),S.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!Ro||g.length===0)return;if(!Bt.has(F.id))Wt({row:ae,column:0})},children:[Z("span",{"data-uibot-row-number":"",style:{opacity:Bt.has(F.id)?0:1},children:(e.rowOffset??0)+ae+1}),mt("span",{"data-uibot-row-actions":"",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",gap:4,opacity:Bt.has(F.id)?1:0},children:[Z("input",{type:"checkbox","aria-label":o("Select row"),checked:Bt.has(F.id),disabled:Boolean(v||q||ue||_),onChange:()=>So(ae),onClick:(X)=>X.stopPropagation()}),e.onExpandRecord&&Z("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?.(F),children:Z(ve,{name:"expand"})})]})]}),Pe>0&&Z("div",{role:"gridcell",tabIndex:-1,"aria-colindex":ge>0?2:1,"aria-readonly":"true",style:{...Ot(ge,Ze===0),background:"var(--background, white)",boxSizing:"border-box",width:Pe,height:b.size,padding:7,borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)"},onContextMenu:()=>{if(!Ro)return;if(!Bt.has(F.id))Wt({row:ae,column:0})},children:Z("input",{"aria-label":o("Record ID {id}",{id:F.id}),readOnly:!0,value:F.id,style:{width:"100%",border:0,background:"transparent",color:"inherit",fontSize:12},onCopy:(X)=>X.stopPropagation(),onPaste:(X)=>X.stopPropagation(),onKeyDown:(X)=>X.stopPropagation()})}),mn.map((X)=>{let U=g[X.index];if(!U)return null;let ee={row:ae,column:X.index},Ie=Bt.has(F.id)&&(G.has(F.id)||L&&ee.column>=Ke.firstColumn&&ee.column<=Ke.lastColumn),me=v?.rowId===F.id&&v.field.id===U.id,Ae=!me&&U.type==="checkbox"?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:U,text:at(F.values[U.id]),disabled:Boolean(!s||q||v||ue||_),mode:"inline",autoOpen:!1,onChange:(be)=>{if(!s||q||v||ue||_)return;try{let Ve=xn(be,U);K({rowId:F.id,expectedVersion:F.version,field:U,text:be,originalText:at(F.values[U.id])}),Ut({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:F.id,expectedVersion:F.version,values:{[U.id]:Ve}}]})}catch(Ve){ye(e.locale==="zh-CN"?dr(U,be,"zh-CN"):Ve instanceof Error?Ve.message:o("Invalid value"))}},onSave:()=>{},onCancel:Yt}):void 0;return mt("div",{id:`wb-${F.id}-${U.id}`,role:"gridcell",tabIndex:-1,...me&&U.type==="linkedRecord"?oi:{},"aria-colindex":X.index+1+Number(Boolean(ge))+Number(Boolean(Pe)),"aria-selected":Ie,"aria-readonly":!s||U.generation==="autoIncrement"||U.type==="blob"||it(U),style:{...X.index<Ze?Ot(gn(X.index),X.index===Ze-1):{position:"absolute",left:X.start},width:X.size,height:b.size,padding:me?0:Jt?"0 10px":7,boxSizing:"border-box",borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",overflow:me?"visible":"hidden",...me?{zIndex:3}:{},whiteSpace:"nowrap",...Jt&&!me?{display:"flex",alignItems:"center",fontSize:13}:{},...An>1&&!me&&(U.type==="singleLineText"||U.type==="longText")?{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:An,whiteSpace:"normal",wordBreak:"break-word",padding:Jt?"6px 10px":7}:{},background:Ie?"var(--accent, #e8f0fe)":Zi(n.columnColors?.[U.id])?.background??"var(--background, white)",outline:I.row===ee.row&&I.column===ee.column?"2px solid #6488bd":"none",outlineOffset:-2},onMouseEnter:()=>{if(!vt)return;let be=Math.max(vt.firstRow-ee.row,ee.row-vt.lastRow,0),Ve=Math.max(vt.firstColumn-ee.column,ee.column-vt.lastColumn,0);ro.current=be>=Ve?{...vt,firstRow:Math.min(ee.row,vt.firstRow),lastRow:Math.max(ee.row,vt.lastRow)}:{...vt,firstColumn:Math.min(ee.column,vt.firstColumn),lastColumn:Math.max(ee.column,vt.lastColumn)}},onMouseDown:(be)=>{if(vt||v)return;if(be.button!==0)return;be.preventDefault(),Wt(ee,be.shiftKey),S.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!Ro)return;if(!(Bt.has(F.id)&&(G.has(F.id)||ee.column>=Ke.firstColumn&&ee.column<=Ke.lastColumn)))Wt(ee)},onClick:(be)=>{if(!v&&!be.shiftKey&&(U.type==="singleSelect"||U.type==="multipleSelect"))Gt(ee)},onDoubleClick:()=>Gt(ee),children:[Yo&&ee.row===Ke.lastRow&&ee.column===Ke.lastColumn&&Z("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:vt?"grabbing":"grab",zIndex:4},onMouseDown:(be)=>{be.preventDefault(),be.stopPropagation(),ro.current=null,jn(Ke)},onClick:(be)=>be.stopPropagation()}),me&&bn!==void 0&&bn!==null?bn:me&&U.type==="relation"?Z(_o,{locale:e.locale,field:U,value:v.text,label:o("Edit {name}",{name:U.name}),getOptions:e.getRelationOptions,labels:F.linkedRecords?.[U.id],disabled:q||!s,onChange:(be)=>{ye(r.optimisticEdit?"":o("Unsaved changes")),K({...v,text:be}),ie(null),Ce(null)}}):me&&Fn!==void 0?Z("div",{style:{display:"contents"},...Zo,children:Fn}):me&&U.type!=="linkedRecord"?Z("div",{style:{display:"contents"},...Zo,children:Z(Aa,{field:U,text:v.text,disabled:q||!s,locale:e.locale,ariaLabel:o("Edit {name}",{name:U.name}),onChange:$n,onSave:(be)=>void yn(be),onCancel:Yt})}):U.type==="relation"||U.type==="linkedRecord"?Vo(F,U):U.type==="lookup"?go(F.values[U.id]):U.type==="formula"||U.type==="rollup"?ir(F.values[U.id],F.computedErrors?.[U.id]):U.type==="checkbox"&&Ae!==void 0&&Ae!==null?Ae:U.type==="checkbox"&&Jt?Z(ed,{checked:F.values[U.id]===!0,label:o("Edit {name}",{name:U.name}),onToggle:!s||q||v||ue||_||U.generation==="autoIncrement"?void 0:()=>Ir(F,U,F.values[U.id]!==!0)}):U.type==="checkbox"?Z("input",{type:"checkbox","aria-label":o("Edit {name}",{name:U.name}),checked:F.values[U.id]===!0,ref:(be)=>{if(be)be.indeterminate=F.values[U.id]==null},disabled:!s||q||Boolean(v)||Boolean(ue)||Boolean(_)||U.generation==="autoIncrement",onMouseDown:(be)=>be.stopPropagation(),onKeyDown:(be)=>be.stopPropagation(),onChange:(be)=>{if(!s||q||v||ue||_)return;let Ve=be.currentTarget.checked;K({rowId:F.id,expectedVersion:F.version,field:U,text:String(Ve),originalText:at(F.values[U.id])}),Ut({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:F.id,expectedVersion:F.version,values:{[U.id]:Ve}}]})}}):U.type==="date"?Z("span",{title:at(F.values[U.id]),style:Jt?{opacity:0.75,fontVariantNumeric:"tabular-nums"}:void 0,children:(()=>{let be=Rt(U);return be?Gn(F.values[U.id],be):xi(F.values[U.id])})()}):U.type==="number"&&Jt?Z("span",{style:{display:"block",width:"100%",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:(()=>{let be=Lo(U);return be?Bo(F.values[U.id],be):at(F.values[U.id])})()}):Jt&&U.type==="singleSelect"&&F.values[U.id]!=null?Z(Go,{ids:[F.values[U.id]],field:U,wrap:An>1}):Jt&&U.type==="multipleSelect"&&Array.isArray(F.values[U.id])?Z(Go,{ids:F.values[U.id],field:U,wrap:An>1}):U.type==="hyperlink"?Z(Ii,{value:F.values[U.id]}):U.type==="singleSelect"?U.options?.find((be)=>be.id===F.values[U.id])?.name??at(F.values[U.id]):U.type==="multipleSelect"&&Array.isArray(F.values[U.id])?F.values[U.id].map((be)=>U.options?.find((Ve)=>Ve.id===be)?.name??String(be)).join(", "):at(F.values[U.id])]},U.id)})]},F.id)}),ft?Z("div",{style:{position:"absolute",top:Q.getTotalSize(),left:0,width:rn,height:hl,borderBottom:"1px solid var(--border, #d5d9df)"},children:mt("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:[Z(ve,{name:"plus"}),o("Add record")]})}):null]})]}),r.footerStats&&(n.type??"grid")==="grid"&&g.length>0?Z(Dp,{ui:e.ui,locale:e.locale,t:o,rows:h,total:e.total,descriptor:t,aggregateClient:e.serverFooterStats===!1?void 0:e.aggregate?.client,reloadKey:e.reloadKey,fields:g,columns:mn,width:rn,frozenCount:Ze,frozenLeft:gn,view:n,footerRef:Le,onChange:e.onViewChange}):null,v&&(_||!(r.optimisticEdit&&v.field.type!=="linkedRecord"))&&!(Xo&&bn!==void 0&&bn!==null)&&mt("div",{ref:he,...oi,role:"dialog","aria-label":o("{name} editor",{name:v.field.name}),style:{padding:8,display:"flex",flexWrap:"wrap",gap:8},onKeyDown:(b)=>{if(v.field.type==="linkedRecord"&&b.key==="Escape"&&!q)b.preventDefault(),b.stopPropagation(),Yt()},children:[!Xo&&v.field.type!=="linkedRecord"&&(bn??Fn??(v.field.type==="relation"?Z(_o,{locale:e.locale,field:v.field,value:v.text,label:o("Edit {name}",{name:v.field.name}),getOptions:e.getRelationOptions,labels:h.find((b)=>b.id===v.rowId)?.linkedRecords?.[v.field.id],disabled:q||!s,onChange:$n}):Z(Aa,{field:v.field,text:v.text,disabled:q||!s,locale:e.locale,ariaLabel:o("Edit {name}",{name:v.field.name}),onChange:$n,onSave:(b)=>void yn(b),onCancel:Yt}))),v.field.type==="linkedRecord"&&Z("div",{style:{width:"100%"},children:Z(wi,{disabled:q||!s,field:v.field,value:JSON.parse(v.text),locale:e.locale,labels:h.find((b)=>b.id===v.rowId)?.linkedRecords?.[v.field.id],client:e.relationClient,onChange:(b)=>{K({...v,text:JSON.stringify(b)}),ie(null),Ce(null)}})}),Z(Y,{ui:e.ui,style:to,variant:"outline",size:"sm",disabled:q||!s,onClick:()=>void yn(),children:q?o("Saving…"):o("Save edit")}),Z(Y,{ui:e.ui,style:to,variant:"outline",size:"sm",disabled:q,onClick:Yt,children:o("Cancel edit")})]}),ue&&_&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:_.items.every((b)=>b.op==="delete"),title:_.items.every((b)=>b.op==="delete")?o("Delete {count} records?",{count:_.items.length}):o("Apply {count} row changes in one transaction?",{count:_.items.length}),description:_.items.every((b)=>b.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:q?o("Saving…"):_.items.every((b)=>b.op==="delete")?o("Delete"):o("Confirm changes"),cancelLabel:_.items.every((b)=>b.op==="delete")?o("Cancel"):o("Cancel changes"),busy:q,confirmDisabled:!d(_),onConfirm:()=>void Ut(_),onCancel:()=>{W(!1),ie(null),Ce(null)}}):null,ue&&_&&!e.ui?.ConfirmDialog&&mt(Ai,{label:o("Confirm bulk change"),busy:q,onCancel:()=>{W(!1),ie(null),Ce(null)},children:[Z("p",{children:o("Apply {count} row changes in one transaction?",{count:_.items.length})}),Z("p",{style:{fontSize:12},children:o("If any record changed or any value is invalid, all changes are rejected.")}),Z(Y,{ui:e.ui,style:to,variant:"outline",size:"sm",disabled:q||!d(_),onClick:()=>void Ut(_),children:q?o("Saving…"):o("Confirm changes")})," ",Z(Y,{ui:e.ui,style:to,variant:"outline",size:"sm",disabled:q,onClick:()=>{W(!1),ie(null),Ce(null)},children:o("Cancel changes")})]}),Dn&&_&&mt("div",{role:"group","aria-label":o("Undo/redo recovery"),style:{padding:8},children:[!q&&ke&&Z("p",{role:"alert",children:ke}),Z(Y,{ui:e.ui,style:to,variant:"outline",size:"sm",disabled:q||!d(_),onClick:()=>void Ut(_,void 0,Dn.direction),children:o("Retry undo/redo")})," ",Dn.rejected&&Z(Y,{ui:e.ui,style:to,variant:"outline",size:"sm",disabled:q,onClick:()=>{Vt.current=[],fn.current=[],Tn(null),ie(null),Ce(null),ye("")},children:o("Clear undo/redo history")})]}),re&&!Dn&&mt("div",{style:{padding:12},children:[Z("strong",{children:o("Current server version {version}",{version:re.version})}),Z(jr,{fields:g,values:Mi(_,re.id),serverValues:re.values,locale:e.locale}),Z(Y,{ui:e.ui,style:to,variant:"outline",size:"sm",disabled:q||!d(_),onClick:()=>{if(!_)return;let b=_.items.map((A)=>A.op!=="insert"&&A.id===re.id?{...A,expectedVersion:re.version}:A);Ut({idempotencyKey:crypto.randomUUID(),items:b})},children:o("Retry against current version")})]}),Z("p",{role:"status","aria-live":"polite",style:e.onNotify?Sp:{margin:0,padding:ke||q?8:0},children:q?o("Saving…"):Dn?"":ke})]}),Er=t.fields.filter((b)=>b.type!=="blob"&&b.type!=="linkedRecord"&&!it(b)&&b.generation!=="autoIncrement"),er=()=>{if(!l||_t||De.length===0||De.length>100)return;Ut({idempotencyKey:crypto.randomUUID(),items:De.map((b)=>({op:"insert",values:Object.fromEntries(Er.flatMap((A)=>b.values[A.id]===void 0?[]:[[A.id,b.values[A.id]]]))}))})};if(e.renderRecordContextMenu){let b=De.length===1?De[0]:void 0;return e.renderRecordContextMenu({children:Nn,recordIds:oo,disabled:_t,onDelete:Qe,...e.onExpandRecord&&b?{onExpand:()=>e.onExpandRecord?.(b)}:{},onCopy:()=>void navigator.clipboard?.writeText(Hn()),...l?{onDuplicate:er}:{}})}if(!r.recordContextMenu)return Nn;let Dr=[...e.onExpandRecord&&De.length===1?[{id:"expand",icon:Z(ve,{name:"expand"}),label:o("Expand record"),onSelect:()=>{let b=De[0];if(b)e.onExpandRecord?.(b)}}]:[],...l?[{id:"duplicate",icon:Z(ve,{name:"copy"}),label:o("Duplicate {count} selected records",{count:De.length}),disabled:_t||De.length===0,onSelect:er}]:[],{id:"copy",separatorBefore:!0,icon:Z(ve,{name:"copy"}),label:o("Copy cells"),disabled:De.length===0,onSelect:()=>{navigator.clipboard?.writeText(Hn())}},...i?[{id:"delete",icon:Z(ve,{name:"trash"}),label:o("Delete {count} selected records",{count:De.length}),separatorBefore:!0,destructive:!0,disabled:_t,onSelect:Qe}]:[]],Eo=e.ui?.ContextMenu;return Eo?Z(Eo,{items:Dr,"aria-label":o("Record actions"),children:Nn}):Z(Yi,{block:!0,items:Dr,label:o("Record actions"),children:Nn})}function Pp({ui:e,paneRef:t,style:n,children:o,...r}){if(e?.ScrollArea)return e.ScrollArea({viewportRef:t,viewportProps:r,style:n,children:o});return Z("div",{ref:t,style:n,...r,children:o})}var Sp={position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:0},Rp=96,Ip=560,Jr=(e)=>Math.max(Rp,Math.min(Ip,Math.round(e))),Ap=({transform:e})=>({...e,y:0});function Ep({id:e,disabled:t,children:n}){let{setNodeRef:o,listeners:r,transform:i,isDragging:l}=hp({id:e,disabled:t});return Rn(()=>{if(!l)return;let s=document.body.style.cursor;return document.body.style.cursor="grabbing",()=>{document.body.style.cursor=s}},[l]),n({setNodeRef:o,listeners:t?void 0:r,style:{...i?{transform:`translate3d(${Math.round(i.x)}px, 0, 0)`}:{},...l?{cursor:"grabbing",zIndex:6,opacity:0.9,background:"var(--accent, #e8f0fe)",boxShadow:"0 2px 10px color-mix(in srgb, currentColor 22%, transparent)"}:{}}})}function Dp({descriptor:e,aggregateClient:t,reloadKey:n,ui:o,locale:r,t:i,rows:l,total:s,fields:a,columns:d,width:u,frozenCount:f,frozenLeft:p,view:c,footerRef:C,onChange:x}){let h=vd(e,c,a,l,t,n),g=(w,y,E)=>{let S={...c.footerStats??{}};if(y)S[w]=y;else if(E)S[w]="none";else delete S[w];let{footerStats:k,...O}=c;x(Object.keys(S).length?{...O,footerStats:S}:O)};return mt("div",{ref:C,"data-uibot":"paged-collection-footer",style:{position:"relative",overflow:"hidden",height:34,flex:"none",borderTop:"1px solid var(--border, #d5d9df)",background:"var(--background, white)",fontSize:12,color:"var(--muted-foreground, #71717a)"},children:[Z("style",{children:`
20
20
  [data-uibot="paged-collection-footer"]:hover [data-uibot-footer-cell],
21
21
  [data-uibot="paged-collection-footer"] [data-uibot-footer-cell]:focus-within { opacity: 1 !important; }
22
22
  @media (hover: none) {
23
23
  [data-uibot="paged-collection-footer"] [data-uibot-footer-cell] { opacity: 1 !important; }
24
24
  }
25
- `}),Y("div",{style:{position:"relative",width:u,height:"100%",transform:"translateX(calc(var(--uibot-sx, 0px) * -1))"},children:s.map((w)=>{let f=a[w.index];if(!f)return null;let R=w.index===0,S=p.footerStats?.[f.id],A=S!==void 0?S==="none"?void 0:S:R?"count":void 0,L=A?cd(l,f,A):null,M=(T)=>T===null?"":typeof T==="number"&&A!=="count"&&A!=="filled"&&A!=="empty"?Mn(Math.round(T*100)/100,f):typeof T==="number"?T.toLocaleString(i):Mn(T,f),U=M(L),J=!t?L:A==="count"?d:x.values[`footer${w.index}`]??null,P=!A?"":!t||A==="count"?M(J):x.status==="loading"?"…":x.status==="error"||J===null?"—":M(J),I=A?A==="count"&&R?r("Footer record count",{count:P}):`${r(`Footer ${A}`)} ${P}`.trim():r("Auto summary"),k=w.index<c;return Y("div",{"data-uibot-footer-cell":"",style:{position:"absolute",left:k?g(w.index):w.start,width:w.size,height:"100%",boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"flex-end",padding:"0 4px",background:zi(p.columnColors?.[f.id])?.background??"var(--background, white)",zIndex:k?2:void 0,transform:k?"translateX(var(--uibot-sx, 0px))":void 0,opacity:A?1:0,transition:"opacity 120ms"},children:Y(Bn,{ui:o,chevron:!0,quiet:!0,active:!1,label:I,children:(T)=>lt("div",{style:{display:"grid",gap:2,minWidth:150},children:[Y(W,{ui:o,variant:A?"ghost":"outline",size:"sm",onClick:()=>{C(f.id,null,R),T()},children:r("No summary")}),dd(f).map((D)=>Y(W,{ui:o,variant:A===D?"outline":"ghost",size:"sm",onClick:()=>{C(f.id,D,R),T()},children:r(`Footer ${D}`)},D)),t&&x.status==="error"&&A&&A!=="count"?Y("small",{style:{opacity:0.7,padding:"4px 6px"},children:r("Loaded records fallback: {value}",{value:U||"—"})}):null,(!t||x.status==="error")&&d>l.length?Y("small",{style:{opacity:0.7,padding:"4px 6px"},children:r("Summaries cover the {count} loaded records.",{count:l.length})}):null]})})},f.id)})})]})}var ll=44,sl=36;import{DndContext as yg,KeyboardSensor as bg,PointerSensor as hg,closestCenter as Cg,useSensor as pd,useSensors as vg}from"@dnd-kit/core";import{SortableContext as xg,arrayMove as kg,sortableKeyboardCoordinates as wg,useSortable as Pg,verticalListSortingStrategy as Sg}from"@dnd-kit/sortable";import{CSS as Rg}from"@dnd-kit/utilities";import{useState as Ig}from"react";import{jsx as Ot,jsxs as ho}from"react/jsx-runtime";var dl="1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",Ag=({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 fd({fields:e,view:t,onChange:n,locale:o,ui:i,onEditField:r,onAddField:l,onEditAllFields:d}){let a=se(o),[s,u]=Ig(""),c=vg(pd(hg,{activationConstraint:{distance:4}}),pd(bg,{coordinateGetter:wg})),p=[...t.columnOrder.flatMap((f)=>{let R=e.find((S)=>S.id===f);return R?[R]:[]}),...e.filter((f)=>!t.columnOrder.includes(f.id))],m=p.map((f)=>f.id),h=({active:f,over:R})=>{if(!R||f.id===R.id)return;let S=m.indexOf(String(f.id)),A=m.indexOf(String(R.id));if(S<0||A<0)return;n({...t,columnOrder:kg(m,S,A)})},x=e[0]?.id,C=s.trim().toLowerCase(),w=C?p.filter((f)=>f.name.toLowerCase().includes(C)):p;return ho("div",{"data-uibot-field-config":"",style:{display:"grid",gap:6,minWidth:0},children:[Ot("input",{type:"search","aria-label":a("Search fields"),placeholder:a("Search fields"),value:s,onChange:(f)=>u(f.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"}}),Ot(yg,{sensors:c,collisionDetection:Cg,modifiers:[Ag],onDragEnd:h,children:Ot(xg,{items:w.map((f)=>f.id),strategy:Sg,disabled:Boolean(C),children:ho("div",{style:{display:"grid",gap:2,maxHeight:320,overflowY:"auto"},children:[w.map((f)=>{let R=!t.hiddenColumns.includes(f.id);return ho(Dg,{id:f.id,label:a("Reorder {name}",{name:f.name}),disabled:Boolean(C),dimmed:!R,children:[Ot(Vi,{type:f.type}),ho("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[f.name,f.required?" *":""]}),Ot(W,{ui:i,variant:"ghost",size:"sm",icon:R?"eye":"eyeOff",iconOnly:!0,disabled:t.type==="form"&&f.required===!0||f.id===x,ariaLabel:a(R?"Hide {name}":"Show {name}",{name:f.name}),onClick:()=>n({...t,hiddenColumns:R?[...t.hiddenColumns,f.id]:t.hiddenColumns.filter((S)=>S!==f.id)})}),r&&Ot(W,{ui:i,variant:"ghost",size:"sm",icon:"more",iconOnly:!0,ariaLabel:a("Edit field {name}",{name:f.name}),onClick:()=>r(f.id)})]},f.id)}),w.length===0&&Ot("span",{style:{opacity:0.7,padding:6},children:a("No matching fields")})]})})}),ho("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"8px 4px 2px",borderTop:dl},children:[Ot("span",{children:a("Show row numbers")}),Ot(md,{ui:i,checked:t.showRowNumber!==!1,label:a("Show row numbers"),onChange:(f)=>n({...t,showRowNumber:f})})]}),ho("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"8px 4px 2px",borderTop:dl},children:[Ot("span",{children:a("Show record IDs")}),Ot(md,{ui:i,checked:t.showRecordId===!0,label:a("Show record IDs"),onChange:(f)=>n({...t,showRecordId:f})})]}),(l||d)&&ho("div",{style:{borderTop:dl,paddingTop:6,display:"flex",justifyContent:"space-between",gap:8},children:[l&&Ot(W,{ui:i,variant:"ghost",size:"sm",icon:"plus",onClick:l,children:a("Add field")}),d&&Ot(W,{ui:i,variant:"ghost",size:"sm",icon:"fields",onClick:d,children:a("Edit all fields")})]})]})}function Dg({id:e,label:t,disabled:n,dimmed:o,children:i}){let{attributes:r,listeners:l,setNodeRef:d,setActivatorNodeRef:a,transform:s,transition:u,isDragging:c}=Pg({id:e,disabled:n});return ho("div",{ref:d,style:{display:"flex",alignItems:"center",gap:6,padding:"2px 4px",borderRadius:6,transform:Rg.Transform.toString(s),transition:u,position:"relative",zIndex:c?2:void 0,background:c?"var(--accent, color-mix(in srgb, currentColor 8%, transparent))":void 0,opacity:o&&!c?0.55:1},children:[Ot("button",{type:"button",ref:a,"aria-label":t,title:t,disabled:n,...r,...l,style:{display:"inline-flex",padding:0,border:0,background:"transparent",color:"inherit",cursor:n?"default":c?"grabbing":"grab",touchAction:"none"},children:Ot(Ce,{name:"grip"})}),i]})}function md({ui:e,checked:t,label:n,onChange:o}){if(e?.Switch)return e.Switch({checked:t,onChange:o,"aria-label":n});return Ot("input",{type:"checkbox","aria-label":n,checked:t,onChange:(i)=>o(i.currentTarget.checked)})}import{useEffect as vd,useMemo as Tg,useRef as xd,useState as zt}from"react";var cl=50,jr=1000,ul=100;function $r(e,t){let n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}function yd(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}}function Hi(e){return e.filter((t)=>Pr.has(t.type)&&!it(t)&&t.generation!=="autoIncrement")}var qi=(e)=>e===null||e===void 0||e===""||Array.isArray(e)&&e.length===0,Eg=(e,t)=>qi(e)&&qi(t)?!0:JSON.stringify(e)===JSON.stringify(t);function bd(e,t){return e.filter((n)=>t.some((o)=>qi(n.values[o])))}function gl(e,t){let n=new Set(t);for(let o of t){let i=e.find((r)=>r.id===o)?.ai?.sourceFieldIds;if(!i?.length)return;for(let r of i)n.add(r)}return e.filter((o)=>n.has(o.id)).map((o)=>o.id)}function pl(e,t){if(!t)return e;return e.map((n)=>({...n,values:Object.fromEntries(t.filter((o)=>(o in n.values)).map((o)=>[o,n.values[o]]))}))}function Fg(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 ml(e,t,n,o){let i=new Map(Hi(e).filter((s)=>n.includes(s.id)).map((s)=>[s.id,s])),r=new Map(t.map((s)=>[s.id,s])),l=[],d=new Set,a=0;for(let s of o){let u=r.get(s.recordId);if(!u){a+=Object.keys(s.values).length;continue}for(let[c,g]of Object.entries(s.values)){let p=i.get(c),m=`${u.id}:${c}`,h=p?Fg(p,g):void 0;if(!p||h===void 0||d.has(m)||Eg(u.values[c],h)){a+=1;continue}d.add(m),l.push({key:m,recordId:u.id,expectedVersion:u.version,fieldId:c,before:u.values[c]??null,after:h,...s.reason?{reason:s.reason}:{}})}}return{changes:l,skipped:a}}function fl(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 hd(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 l=o.get(i.recordId)??{op:"update",id:i.recordId,expectedVersion:r,values:{}};l.values[i.fieldId]=i.before,o.set(i.recordId,l)}return[...o.values()]}function yl(e,t){return Hi(e).filter((n)=>n.ai?.autoFill&&n.ai.prompt.trim()).map((n)=>({field:n,records:t.filter((o)=>qi(o.values[n.id]))})).filter((n)=>n.records.length>0)}async function Cd(e){let t=new Map(e.records.map((o)=>[o.id,o])),n=0;try{for(let o of yl(e.fields,e.records)){let i=[o.field.id],r=gl(e.fields,i),l=r?e.fields.filter((d)=>r.includes(d.id)):e.fields;for(let d of $r(o.records,cl)){let a=d.map((c)=>t.get(c.id)??c),s=await e.fill({tableId:e.tableId,fields:l,instruction:o.field.ai?.prompt.trim()??"",targetFieldIds:i,records:pl(a,r)});if(!s.ok)return{filled:n,error:s.error.message};let{changes:u}=ml(e.fields,a,i,s.data.suggestions);for(let c of $r(fl(u),ul)){let g=await e.mutate(c);if(!g.ok)return{filled:n,error:g.error.message};for(let p of g.data.items)t.set(p.id,p);n+=c.length}}}}catch(o){return{filled:n,error:o instanceof Error?o.message:String(o)}}return{filled:n}}import{jsx as $e,jsxs as bt,Fragment as kd}from"react/jsx-runtime";var Ng=[{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."}],wt={border:"var(--border, #d5d9df)",background:"var(--background, white)",muted:"var(--muted, #f4f5f7)",faint:"var(--muted-foreground, #6b7280)",primary:"var(--primary, #2563eb)"},Tt={drawer:{position:"fixed",top:0,right:0,bottom:0,zIndex:80,width:"min(440px, 100vw)",display:"flex",flexDirection:"column",background:wt.background,color:"inherit",borderLeft:`1px solid ${wt.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 ${wt.border}`},body:{flex:1,minHeight:0,overflowY:"auto",padding:14,display:"grid",gap:14,alignContent:"start"},label:{display:"grid",gap:6,fontSize:12,color:wt.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 ${wt.border}`,background:wt.background,color:"inherit",font:"inherit"},foot:{display:"flex",alignItems:"center",gap:8,padding:"10px 14px",borderTop:`1px solid ${wt.border}`},group:{border:`1px solid ${wt.border}`,borderRadius:8,overflow:"hidden"},groupHead:{padding:"6px 10px",background:wt.muted,fontSize:12,fontWeight:600},change:{display:"grid",gridTemplateColumns:"auto 1fr",gap:8,padding:"8px 10px",borderTop:`1px solid ${wt.border}`,fontSize:13},before:{color:wt.faint,textDecoration:"line-through",overflowWrap:"anywhere"},after:{fontWeight:500,overflowWrap:"anywhere"},reason:{fontSize:12,color:wt.faint,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"}},Kr=(e)=>({display:"inline-flex",alignItems:"center",gap:4,padding:"3px 10px",borderRadius:999,fontSize:12,cursor:"pointer",border:`1px solid ${e?wt.primary:wt.border}`,background:e?"color-mix(in srgb, var(--primary, #2563eb) 14%, transparent)":"transparent",color:"inherit"});function wd(e){let{table:t,rows:n,selection:o,aiFillClient:i}=e,r=se(e.locale),l=Tg(()=>Hi(t.fields),[t.fields]),d=l.find((K)=>K.id===e.presetFieldId&&K.ai),[a,s]=zt(d?e.query?"view":"page":o.recordIds.length?"selected":"page"),[u,c]=zt(()=>{if(d)return[d.id];let K=l.filter((ye)=>o.fieldIds.includes(ye.id)).map((ye)=>ye.id);return K.length?K:l.map((ye)=>ye.id)}),[g,p]=zt(d?.ai?.prompt??""),[m,h]=zt(Boolean(d)),[x,C]=zt([]),[w,f]=zt(""),[R,S]=zt("idle"),[A,L]=zt(),[M,U]=zt(new Set),[J,P]=zt(""),[I,k]=zt(""),[T,D]=zt(!1),[B,F]=zt(),[H,z]=zt([]),[ce,Z]=zt(),fe=xd(null),Q=xd(null);vd(()=>{let K=!0;return i.models?.().then((ye)=>{if(K&&ye.ok)C(ye.data),f((Le)=>Le||ye.data[0]?.id||"")}),()=>{K=!1,fe.current?.abort()}},[i]),vd(()=>{Q.current?.focus()},[]);let q=n.filter((K)=>o.recordIds.includes(K.id)),te=Math.min(e.total??n.length,jr),le=a==="selected"?q.length:a==="page"?n.length:te,ve=(K)=>t.fields.find((ye)=>ye.id===K),xe=R!=="running"&&le>0&&u.length>0&&g.trim()!=="",ae=async(K)=>{if(a==="selected")return q;if(a==="page"||!e.query)return n.slice(0,jr);let ye=[],Le;do{let Ae=await e.client.query(t.id,{...e.query,limit:100,...Le?{cursor:Le}:{}});if(!Ae.ok)throw Error(Ae.error.message);ye.push(...Ae.data.items),Le=Ae.data.nextCursor??void 0}while(Le&&ye.length<jr&&!K.aborted);return ye.slice(0,jr)},Te=gl(t.fields,u),pe=Te?t.fields.filter((K)=>Te.includes(K.id)):t.fields,Me=async(K,ye)=>{let Le=new AbortController;fe.current=Le,S("running"),k("");let Ae=[...ye],nt=[],St=[],Ct="",We=$r(K,cl);F({done:0,total:We.length,failed:nt,error:""});for(let[Oe,an]of We.entries()){if(Le.signal.aborted)break;let st=await i.fill({tableId:t.id,fields:pe,instruction:g.trim(),targetFieldIds:u,records:pl(an,Te),...w?{model:w}:{}},{signal:Le.signal}).catch((Rt)=>({ok:!1,error:{code:"unknown",message:Rt instanceof Error?Rt.message:typeof Rt==="object"&&Rt&&("message"in Rt)?String(Rt.message):String(Rt)}}));if(Le.signal.aborted)break;if(st.ok){Ae.push(ml(t.fields,an,u,st.data.suggestions));let Rt=[st.data.summary,st.data.usage].filter(Boolean).join(" · ");if(Rt)St.push(We.length>1?`${Oe+1}/${We.length} ${Rt}`:Rt)}else nt.push(...an),Ct=st.error.message;F({done:Oe+1,total:We.length,failed:[...nt],error:Ct})}let mn=yd(Ae);if(!mn.changes.length&&!Ae.length){k(Ct||r("No changes were suggested.")),S("idle");return}L(mn),U(new Set(mn.changes.map((Oe)=>Oe.key))),P(St.join(`
26
- `)),S("review")},j=async()=>{let K=new AbortController;fe.current=K,S("running"),k(""),Z(void 0),L(void 0),F(void 0);let ye;try{ye=await ae(K.signal)}catch(Le){k(Le instanceof Error?Le.message:String(Le)),S("idle");return}if(K.signal.aborted){S("idle");return}if(m)ye=bd(ye,u);if(!ye.length){k(r("No records have empty target cells.")),S("idle");return}z(ye),await Me(ye,[])},v=async()=>{if(!B?.failed.length)return;await Me(B.failed,A?[A]:[])},X=()=>fe.current?.abort(),oe=async(K)=>{let ye=[];for(let Le of $r(K,ul)){let Ae=await e.client.mutate(t.id,{idempotencyKey:crypto.randomUUID(),items:Le});if(!Ae.ok)return{ok:!1,error:Ae.error,committedRecords:ye};ye.push(...Ae.data.items),e.onCommitted(Ae.data)}return{ok:!0,committedRecords:ye}},tt=async()=>{if(!A)return;let K=A.changes.filter((nt)=>M.has(nt.key));if(!K.length)return;D(!0),k("");let ye=await oe(fl(K));D(!1);let Le=new Set(ye.committedRecords.map((nt)=>nt.id)),Ae=K.filter((nt)=>Le.has(nt.recordId));if(Ae.length)Z({changes:Ae,records:ye.committedRecords});if(!ye.ok){let nt=ye.error.code==="version_conflict"?r("Some records changed since the preview. Generate again to review the latest values."):ye.error.message;if(k(Ae.length?`${r("Applied {count} AI changes",{count:Ae.length})} · ${nt}`:nt),Ae.length){let St=A.changes.filter((Ct)=>!Le.has(Ct.recordId));L({changes:St,skipped:A.skipped})}return}e.onNotify?.(r("Applied {count} AI changes",{count:K.length})),L(void 0),F(void 0),S("idle")},Pt=async()=>{if(!ce)return;D(!0);let K=await oe(hd(ce.changes,ce.records));if(D(!1),!K.ok){k(K.error.message);return}e.onNotify?.(r("AI changes undone")),Z(void 0)},rn=new Map;for(let K of A?.changes??[])rn.set(K.recordId,[...rn.get(K.recordId)??[],K]);let ht=(K,ye)=>K.includes(ye)?K.filter((Le)=>Le!==ye):[...K,ye];return bt("aside",{ref:Q,tabIndex:-1,"aria-label":r("AI fill"),"data-uibot":"ai-fill-drawer",style:Tt.drawer,onKeyDown:(K)=>{if(K.key==="Escape"&&!K.nativeEvent.isComposing)K.stopPropagation(),e.onClose()},children:[bt("div",{style:Tt.head,children:[$e(Ce,{name:"sparkles"}),$e("strong",{style:{flex:1},children:r("AI fill")}),$e(W,{ui:e.ui,variant:"ghost",size:"icon",icon:"x",iconOnly:!0,ariaLabel:r("Close"),onClick:e.onClose})]}),bt("div",{style:Tt.body,children:[bt("div",{style:Tt.label,children:[r("Records in scope"),$e(Je,{ui:e.ui,label:r("Records in scope"),value:a,onChange:(K)=>s(K),options:[{value:"selected",label:r("Selected records ({count})",{count:q.length}),disabled:q.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:te})}]:[]]})]}),bt("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12},children:[$e("input",{type:"checkbox",checked:m,onChange:(K)=>h(K.target.checked)}),r("Only records with empty target cells")]}),bt("fieldset",{style:{...Tt.label,border:0,margin:0,padding:0},children:[$e("legend",{style:{padding:0,marginBottom:6},children:r("Fields to fill")}),$e("div",{style:Tt.chips,children:l.map((K)=>bt("button",{type:"button","aria-pressed":u.includes(K.id),style:Kr(u.includes(K.id)),onClick:()=>c(ht(u,K.id)),children:[K.ai?$e(Ce,{name:"sparkles",size:12}):null,K.name]},K.id))})]}),bt("label",{style:Tt.label,children:[r("Instruction"),$e("textarea",{style:Tt.textarea,value:g,placeholder:r("Describe what to fill or change"),onChange:(K)=>p(K.target.value),onKeyDown:(K)=>{if(K.key==="Enter"&&(K.metaKey||K.ctrlKey)&&xe)K.preventDefault(),j()}}),$e("span",{style:Tt.chips,children:Ng.map((K)=>$e("button",{type:"button",style:Kr(!1),onClick:()=>p(r(K.text)),children:r(K.label)},K.id))})]}),x.length>0&&bt("div",{style:Tt.label,children:[r("Model"),$e(Je,{ui:e.ui,label:r("Model"),value:w,onChange:f,options:x.map((K)=>({value:K.id,label:K.label}))})]}),I&&$e("p",{role:"alert",style:{margin:0,color:"var(--destructive, #b42318)"},children:I}),ce&&bt("p",{role:"status",style:{margin:0},children:[r("Applied {count} AI changes",{count:ce.changes.length})," ",$e("button",{type:"button",style:Kr(!1),disabled:T,onClick:()=>void Pt(),children:r("Undo")})]}),R!=="running"&&B&&B.failed.length>0&&bt("p",{role:"alert",style:{margin:0,color:"var(--destructive, #b42318)"},children:[r("{count} records could not be processed: {reason}",{count:B.failed.length,reason:B.error})," ",$e("button",{type:"button",style:Kr(!1),onClick:()=>void v(),children:r("Retry failed")})]}),R==="review"&&A&&bt("section",{"aria-label":r("Suggestions"),style:{display:"grid",gap:10},children:[bt("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:wt.faint},children:[bt("span",{style:{flex:1},children:[r("{count} suggested changes",{count:A.changes.length}),A.skipped?` · ${r("Skipped {count} cells",{count:A.skipped})}`:""]}),A.changes.length>0&&$e("button",{type:"button",style:Kr(!1),onClick:()=>U(M.size===A.changes.length?new Set:new Set(A.changes.map((K)=>K.key))),children:M.size===A.changes.length?r("Select none"):r("Select all")})]}),J&&$e("p",{style:{margin:0,fontSize:12,color:wt.faint,whiteSpace:"pre-wrap"},children:J}),A.changes.length===0&&$e("p",{style:{margin:0},children:r("No changes were suggested.")}),[...rn.entries()].map(([K,ye])=>{let Le=H.find((Ae)=>Ae.id===K);return bt("div",{style:Tt.group,children:[$e("div",{style:Tt.groupHead,children:Le?$t(Le,t.fields):K}),ye.map((Ae)=>{let nt=ve(Ae.fieldId);if(!nt)return null;let St=Mn(Ae.before,nt);return bt("label",{style:Tt.change,children:[$e("input",{type:"checkbox",checked:M.has(Ae.key),"aria-label":`${nt.name} ${K}`,onChange:()=>U(new Set(ht([...M],Ae.key)))}),bt("span",{style:{display:"grid",gap:2},children:[$e("span",{style:{fontSize:12,color:wt.faint},children:nt.name}),St&&$e("span",{style:Tt.before,children:St}),$e("span",{style:Tt.after,children:Mn(Ae.after,nt)||r("(empty)")}),Ae.reason&&$e("span",{title:Ae.reason,style:Tt.reason,children:Ae.reason})]})]},Ae.key)})]},K)})]})]}),$e("div",{style:Tt.foot,children:R==="running"?bt(kd,{children:[$e("span",{role:"status",style:{flex:1,color:wt.faint},children:B&&B.total>1?r("Generating batch {done} of {total}…",{done:Math.min(B.done+1,B.total),total:B.total}):r("Generating suggestions…")}),$e(W,{ui:e.ui,variant:"outline",size:"sm",onClick:X,children:r("Stop")})]}):R==="review"&&A&&A.changes.length>0?bt(kd,{children:[$e(W,{ui:e.ui,variant:"default",size:"sm",disabled:T||M.size===0,onClick:()=>void tt(),children:r("Apply {count} changes",{count:M.size})}),$e(W,{ui:e.ui,variant:"outline",size:"sm",disabled:!xe,onClick:()=>void j(),children:r("Regenerate")})]}):$e(W,{ui:e.ui,variant:"default",size:"sm",disabled:!xe,onClick:()=>void j(),children:r("Generate preview")})})]})}import{useEffect as Pd,useLayoutEffect as Mg,useRef as Lg,useState as Og}from"react";import{jsx as Vg,jsxs as Bg}from"react/jsx-runtime";var bl=380;function Sd(e){let t=Lg(null),[n,o]=Og(null),{container:i,anchorFieldId:r,dirty:l,onCancel:d}=e;return Mg(()=>{let a=()=>{let s=i.current,u=r?`[data-uibot-field="${CSS.escape(r)}"]`:"[data-uibot-add-field]",c=s?.querySelector(u)?.getBoundingClientRect(),g=s?.getBoundingClientRect(),p=document.documentElement.clientWidth||window.innerWidth,m=c?c.bottom+4:(g?.top??0)+48,h=c?c.left:(g?.right??p)-bl-16;o({top:Math.max(8,m),left:Math.max(8,Math.min(h,p-bl-8))})};return a(),window.addEventListener("resize",a),window.addEventListener("scroll",a,!0),()=>{window.removeEventListener("resize",a),window.removeEventListener("scroll",a,!0)}},[i,r]),Pd(()=>{let a=requestAnimationFrame(()=>t.current?.querySelector("input:not([disabled])")?.select());return()=>cancelAnimationFrame(a)},[]),Pd(()=>{let a=(s)=>{let u=s.target;if(!u||t.current?.contains(u))return;if(u instanceof Element&&u.closest("[role=listbox],[role=menu],[data-radix-popper-content-wrapper]"))return;if(!l)d()};return document.addEventListener("pointerdown",a,!0),()=>document.removeEventListener("pointerdown",a,!0)},[l,d]),Bg("div",{ref:t,role:"dialog","aria-label":e.title,"data-uibot-field-editor":"",onKeyDown:(a)=>{if(a.key==="Escape"&&!a.nativeEvent.isComposing)a.stopPropagation(),d()},style:{position:"fixed",top:n?.top??0,left:n?.left??0,visibility:n?"visible":"hidden",width:bl,maxWidth:"calc(100vw - 16px)",maxHeight:`calc(100vh - ${(n?.top??0)+16}px)`,overflowY:"auto",zIndex:50,boxSizing:"border-box",padding:16,display:"grid",gap:12,border:"1px solid var(--uibot-border, var(--border, #d4d4d8))",borderRadius:10,background:"var(--uibot-surface, var(--background, #fff))",color:"var(--uibot-text, inherit)",boxShadow:"0 12px 32px rgb(0 0 0 / 0.14)",fontSize:"var(--uibot-workspace-font-size, 13px)"},children:[Vg("strong",{style:{fontSize:14},children:e.title}),e.children]})}import{jsx as _,jsxs as Ne,Fragment as Gr}from"react/jsx-runtime";var Rd={grid:"New grid view",kanban:"New kanban view",gallery:"New gallery view",calendar:"New calendar view",form:"New form view"},Ug=(e,t)=>{let n=Wl(e,t);return n?.length?{sort:n}:{}},br=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Wr(e,t){let[n,o]=Fe({loading:!0}),[i,r]=Fe(0);return Nt(()=>{let d=e();if(!d){o({loading:!1,scope:t,tick:i});return}let a=!0;return o((s)=>({...s.scope?.length===t.length&&s.scope.every((u,c)=>Object.is(u,t[c]))?s:{},loading:!0,scope:t,tick:i})),d.then((s)=>{if(!a)return;o(s.ok?{data:s.data,loading:!1,scope:t,tick:i}:{error:s.error.message,errorCode:s.error.code,loading:!1,scope:t,tick:i})}).catch((s)=>{if(a)o({error:s instanceof Error?s.message:String(s),loading:!1,scope:t,tick:i})}),()=>{a=!1}},[...t,i]),{...n.tick===i&&n.scope?.length===t.length&&n.scope.every((d,a)=>Object.is(d,t[a]))?n:{loading:!0,data:void 0,error:void 0,errorCode:void 0},reload:()=>r((d)=>d+1)}}function yx(e){let{client:t,requestApproval:n}=e,o=on(()=>{}),i=Qn(()=>{let y=Xs(t,n);return il(y,async(O,ee)=>{let ie=await y.mutate(O,ee);if(ie.ok&&!ie.data.replayed&&ee.items.some((de)=>de.op==="insert")){let de=new Set(ee.items.flatMap((Ge)=>Ge.op==="insert"?[]:[Ge.id])),je=ie.data.items.filter((Ge)=>!de.has(Ge.id));if(je.length)o.current(O,je)}return ie})},[t,n]),r=Qn(()=>{if(e.aggregateClient)return e.aggregateClient;let y=t.aggregate;if(!y)return;return{async aggregate(O,ee){let ie=await y.call(t,O,{...ee.filter?{filter:ee.filter}:{},...ee.search!==void 0?{search:ee.search}:{},groupBy:ee.groupBy,aggregates:ee.aggregates.map((de)=>({fn:de.fn,...de.fieldId?{field:de.fieldId}:{},as:de.as}))});return ie.ok?{ok:!0,data:Ll(ee,ie.data)}:ie}}},[e.aggregateClient,t]),l=on([]),d=Qn(()=>e.getRelationOptions??od(i,()=>l.current),[e.getRelationOptions,i]),a=se(e.locale),s=Qn(()=>Dt({preset:"full",...e.features}),[e.features]),u=e.pageSize??50,c=Wr(()=>i.list(),[i]);l.current=c.data??[];let[g,p]=Fe(e.tableId),m=e.tableId??g??c.data?.[0]?.id,h=on(e);h.current=e;let x=on(null),C=hl((y)=>{if(h.current.onBeforeNavigate?.(y)!==!1)return!0;let O=x.current;return requestAnimationFrame(()=>O?.isConnected&&O.focus({preventScroll:!0})),!1},[]),w=e.onTableChange,f=hl((y)=>{if(!C({tableId:y}))return!1;return p(y),w?.(y),!0},[w,C]),R=Wr(()=>e.capabilities||!i.capabilities?void 0:i.capabilities(m),[i,m,e.capabilities]),S=e.capabilities??R.data??{read:!0,write:!0,schema:!0},A=S.schema&&s.schemaEditor,L=S.write&&s.rowCreate,M=S.write&&s.rowUpdate,U=S.write&&s.rowDelete,J=(S.views??S.schema)&&s.viewManagement,P=Boolean(m&&c.data?.some((y)=>y.id===m)),I=Wr(()=>m&&P?i.describe(m):void 0,[i,m,P]),k=!I.loading&&I.data?.id===m?I.data:void 0,T=Wr(()=>m&&k?i.views(m):void 0,[i,m,Boolean(k)]),[D,B]=Fe([]),[F,H]=Fe(""),z=e.viewId??F,ce=on({client:t,tableId:m,id:z});if(ce.current.client!==t||ce.current.tableId!==m||ce.current.id!==z)ce.current={client:t,tableId:m,id:z};let[Z,fe]=Fe(),Q=Z?.client===t&&Z.tableId===m,q=Q&&Z.snapshot===T.data,[te,le]=Fe({});Nt(()=>{if(!T.data||T.loading)return;fe({client:t,tableId:m,snapshot:T.data}),B(T.data),le({}),H((y)=>{let O=T.data??[];if(Q&&O.some((ee)=>ee.id===y))return y;return O.find((ee)=>ee.id===e.initialViewId)?.id??O[0]?.id??""})},[T.data,T.loading,e.initialViewId,t,m]);let ve=on({client:t,ids:new Map});if(ve.current.client!==t)ve.current={client:t,ids:new Map};let xe=ve.current.ids;Nt(()=>{if(m&&T.data?.length)xe.delete(m)},[xe,m,T.data]);let ae=T.data?.length===0?k?.id:void 0,Te=se(e.locale)("All records"),pe=Qn(()=>{if(!ae)return;let y=xe.get(ae);if(!y)y=e.createViewId?.(ae)??`default-${ae}`,xe.set(ae,y);return{id:y,name:Te,version:0,type:"grid",columnOrder:[],hiddenColumns:[],columnWidths:{}}},[xe,ae,Te,e.createViewId]);Nt(()=>{if(!pe||!T.data||T.data.length>0)return;if(T.loading||I.data?.id!==m)return;le((y)=>y[pe.id]?y:{...y,[pe.id]:pe}),H(pe.id)},[pe,T.data,T.loading,I.data?.id,m]);let Me=e.inlineViewControls===!0,j=D.find((y)=>y.id===z),v=q&&k&&!T.loading&&!T.error?te[z]??j:void 0,X=on(void 0);Nt(()=>{if(!v)return;let y=X.current;if(y?.client===t&&y.tableId===m)return;X.current={client:t,tableId:m},h.current.onViewChange?.(v,"initialize")},[t,m,v]);let[oe,tt]=Fe({recordIds:[],fieldIds:[]}),[Pt,rn]=Fe(!1),[ht,K]=Fe(!1),[ye,Le]=Fe(null);Nt(()=>{if(!ye||!v||m!==ye.tableId)return;if(I.data?.id!==ye.tableId||T.loading||D!==T.data)return;le((y)=>({...y,[v.id]:{...v,filter:ye.filter}})),Le(null)},[ye,v,m,I.data?.id,T.loading,T.data,D]),Nt(()=>{tt({recordIds:[],fieldIds:[]}),rn(!1)},[m]);let Ae=Qn(()=>{if(!k)return[];let y=c.data??[],O=k.fields.flatMap((ie)=>{let de=ie.relation&&y.find((je)=>je.id===ie.relation?.collectionId);return de?[{key:`to:${ie.id}`,label:a("Open {name}",{name:de.name}),needsRecord:!1,open:()=>f(de.id)}]:[]}),ee=y.flatMap((ie)=>ie.id===k.id?[]:ie.fields.filter((de)=>de.relation?.collectionId===k.id).map((de)=>({key:`from:${ie.id}:${de.id}`,label:a("{name} · inverse records",{name:ie.name}),needsRecord:!0,open:()=>{let je=oe.recordIds[0];if(!je)return;if(!f(ie.id))return;Le({tableId:ie.id,filter:{conjunction:"and",filterSet:[{fieldId:de.id,operator:"is",value:je}]}})}})));return[...O,...ee]},[k,c.data,oe.recordIds,a,f]),nt=Boolean(v&&pe&&v.id===pe.id&&br(v,pe)),St=Boolean(v&&!nt&&(!j||!br(j,v))),Ct=[...D,...Object.values(te).filter((y)=>!D.some((O)=>O.id===y.id)&&!(y.id===pe?.id&&D.length>0))],[We,mn]=Fe(null),[Oe,an]=Fe(!1),st=(y,O=!1)=>{if(y&&!O&&e.onNotify){e.onNotify(y),mn(null);return}mn(y?{text:y,error:O}:null)},Rt=on(!1),Vt=on(0),Bt=on(m);Bt.current=m,Nt(()=>{Vt.current+=1},[t]);async function ln(y,O){if(Rt.current)return;Rt.current=!0;let ee={client:Vt.current,table:Bt.current};an(!0),st("");try{let ie=await y();if(ee.client!==Vt.current)return;if(ie.ok)O(ie.data,ee.table===Bt.current);else st(ie.error.message,!0)}catch(ie){if(ee.client!==Vt.current)return;st(ie instanceof Error?ie.message:a("Saving failed. Your edit has been kept."),!0)}finally{Rt.current=!1,an(!1)}}let dt=(y)=>{le((O)=>({...O,[y.id]:y})),mn((O)=>O?.error?null:O)},ot=(y)=>{if(y===z)return;let O=te[y]??D.find((ee)=>ee.id===y);if(!O||!m||!C({tableId:m,viewId:y}))return;if(e.viewId===void 0)H(y);h.current.onViewChange?.(O,"select")},Ho=(y)=>{if(!m||!C({tableId:m,viewId:y.id}))return;if(le((O)=>({...O,[y.id]:y})),e.viewId===void 0)H(y.id);h.current.onViewChange?.(y,"create")},we=(y,O)=>{if(!m)return;let ee=D.find((de)=>de.id===y.id),ie=ce.current;if(y.id!==ie.id&&!C({tableId:m,viewId:y.id}))return;ln(async()=>{let de={expectedVersion:ee?.version??0,view:y};return i.saveView(m,{...de,idempotencyKey:zn(`view:${y.id}`,de)})},(de,je)=>{if(ko(`view:${y.id}`),!je)return;if(B((Ge)=>Ge.some((dn)=>dn.id===de.id)?Ge.map((dn)=>dn.id===de.id?de:dn):[...Ge,de]),le((Ge)=>{let{[de.id]:dn,...At}=Ge;return At}),ce.current===ie){if(h.current.viewId===void 0)H(de.id);h.current.onViewChange?.(de,"save")}if(!Me)st(a("View saved"));O?.(de)})},Xn=Me&&St&&J&&!Oe&&!We?.error&&!!v?.name.trim();Nt(()=>{if(!Xn||!v)return;let y=setTimeout(()=>we(v),600);return()=>clearTimeout(y)},[Xn,v]);let[Ut,_n]=Fe(""),$o=()=>{let y=Ct.find((Ge)=>Ge.id===Ut),O=i.deleteView;if(!y||!m)return;let ie=Ct.filter((Ge)=>Ge.id!==y.id)[0],de=ce.current;if(z===y.id&&(!ie||!C({tableId:m,viewId:ie.id})))return;_n("");let je=()=>{if(B((Ge)=>Ge.filter((dn)=>dn.id!==y.id)),le((Ge)=>{let{[y.id]:dn,...At}=Ge;return At}),de===ce.current&&z===y.id&&ie){if(h.current.viewId===void 0)H(ie.id);h.current.onViewChange?.(ie,"delete")}};if(!D.some((Ge)=>Ge.id===y.id))return je();if(!O)return;ln(()=>O.call(i,m,{viewId:y.id,expectedVersion:y.version,idempotencyKey:zn(`delete:${y.id}`,y)}),(Ge,dn)=>{if(ko(`delete:${y.id}`),!dn)return;st(a("View deleted")),je()})},[eo,vt]=Fe(0),[Co,vo]=Fe(null),to=Me&&Co&&Co.viewId===v?.id?Co.text:v?.search??"",hr=(y)=>{if(Me&&v)vo({viewId:v.id,text:y});else if(v)dt({...v,search:y})},jo=Qn(()=>({limit:u,search:to,...v?.filter?{filter:v.filter}:{},...Ug(v,k?.fields)}),[v,to,k?.fields,u]),Ko=JSON.stringify(jo),Rn=JSON.stringify([m,z,Ko]),[qt,no]=Fe({client:i,scope:Rn,cursor:void 0,history:[]}),Wt=qt.client===i&&qt.scope===Rn,Gt=Wt?qt.cursor:void 0,Yt=Wt?qt.history:[];Nt(()=>{no({client:i,scope:Rn,cursor:void 0,history:[]})},[i,Rn]);let oo=(y)=>no((O)=>({client:i,scope:Rn,cursor:y,history:O.client===i&&O.scope===Rn?O.history:[]})),Wo=(y)=>no((O)=>({client:i,scope:Rn,history:y,cursor:O.client===i&&O.scope===Rn?O.cursor:void 0})),Go=(v?.type??"grid")==="grid",It=Wr(()=>m&&k&&v&&Go?i.query(m,{...jo,...Gt?{cursor:Gt}:{}}):void 0,[i,m,k?.schemaVersion,Boolean(v),Ko,Gt,Go,eo]),Ht=()=>{if(m&&!C({tableId:m,...v?{viewId:v.id}:{}}))return;I.reload(),T.reload(),vt((y)=>y+1)},fn=hl(()=>vt((y)=>y+1),[]);o.current=(y,O)=>{let ee=e.aiFillClient;if(!ee||e.schemaSettings?.ai===!1||y!==k?.id)return;let ie=k.fields;if(!yl(ie,O).length)return;let de=Vt.current;Cd({tableId:y,fields:ie,records:O,fill:(je)=>ee.fill(je),mutate:(je)=>i.mutate(y,{idempotencyKey:crypto.randomUUID(),items:je})}).then((je)=>{if(de!==Vt.current)return;if(je.filled)fn();if(je.error&&Bt.current===y)st(a("AI auto-fill stopped: {message}",{message:je.error}),!0)})};let[Be,In]=Fe("");Nt(()=>{In(""),K(!1)},[t,m,z]);let Yo={...e.schemaSettings,ai:Boolean(e.aiFillClient)&&e.schemaSettings?.ai!==!1},[Jt,An]=Fe(!1),[Cr,sn]=Fe(""),[vr,Yr]=Fe(""),[Mt,xr]=Fe(""),xo=on({}),zn=(y,O)=>{let ee=JSON.stringify(O),ie=xo.current[y];if(ie?.fingerprint===ee)return ie.key;let de=crypto.randomUUID();return xo.current[y]={fingerprint:ee,key:de},de},ko=(y)=>{delete xo.current[y]},[wo,kr]=Fe(""),[yn,Jo]=Fe([]),ro=Qn(()=>[{fn:"count",as:"records"},...Mt?[{fn:"sum",fieldId:Mt,as:"sum"}]:[]],[Mt]),$i=Qn(()=>{let y=se(e.locale),O=k?.fields.find((ee)=>ee.id===Mt);return{records:y("Records"),...O?{sum:y("Sum of {name}",{name:O.name})}:{}}},[e.locale,k,Mt]);Nt(()=>xr(""),[m]);let[Po,wr]=Fe([]),[So,b]=Fe(""),[E,N]=Fe(),re=(y)=>{N(y),wr(structuredClone(k?.fields??[])),b(k?.name??""),Dn("schema")},G=Be==="schema"&&(!br(Po,k?.fields)||So!==(k?.name??"")),V=Be==="create"&&(wo.trim()!==""||!br(yn,[{id:"name",name:a("Name"),type:"singleLineText",required:!0}])),[ne,Pe]=Fe(!1),[be,Re]=Fe(!1),he=on(null),Ue=on(null),Dn=(y)=>{if(document.activeElement instanceof HTMLElement)Ue.current=document.activeElement;In(y)},En=()=>{K(!1),In("");let y=Ue.current;if(Ue.current=null,y)requestAnimationFrame(()=>y.isConnected&&y.focus())};Nt(()=>{if(!Be)return;let y=document.activeElement,O=requestAnimationFrame(()=>{if(document.activeElement!==y)return;he.current?.querySelector("[data-uibot-panel] input:not([disabled]), [data-uibot-panel] textarea:not([disabled])")?.focus()});return()=>cancelAnimationFrame(O)},[Be]),Nt(()=>{if(Be!=="add"&&Be!=="record")Pe(!1),Re(!1)},[Be]);let io=()=>{if(G||V||(Be==="add"||Be==="record")&&ne)K(!0);else En()},Jr=(y)=>(O)=>{if(O.nativeEvent.isComposing)return;if(O.key==="Escape"){if(O.stopPropagation(),!Oe&&!be)io()}else if(y&&O.key==="Enter"&&(O.ctrlKey||O.metaKey)&&!Oe)O.preventDefault(),y()},ji=El(),Ad=(Be==="add"||Be==="record")&&ne,Dd=(Be==="add"||Be==="record")&&be,Ed=St||G||V||ji.dirty||Ad,Fd=Oe||ji.busy||Dd;Fn({dirty:Ed,busy:Fd},e);let Cl=()=>{if(!wo.trim()||yn.length===0)return;ln(()=>{let y={name:wo.trim(),fields:yn};return i.create({...y,idempotencyKey:zn("create",y)})},(y,O)=>{if(ko("create"),c.reload(),!O)return;En(),f(y.id)})},vl=()=>void Zo({fields:Po,name:So.trim()}).then(()=>{En(),st(a("Fields saved"))}).catch((y)=>st(y instanceof Error?y.message:String(y),!0)),Zo=(y)=>new Promise((O,ee)=>{if(!m||!k)return ee(Error(a("Choose a table first.")));an(!0);let ie={client:Vt.current,table:Bt.current};i.updateSchema(m,{expectedSchemaVersion:k.schemaVersion,name:y.name??k.name,fields:y.fields??k.fields,...y.icon??k.icon?{icon:y.icon??k.icon}:{},idempotencyKey:zn("schema",{version:k.schemaVersion,name:y.name??k.name,fields:y.fields??k.fields,icon:y.icon??k.icon})}).then((de)=>{if(ie.client!==Vt.current||ie.table!==Bt.current)return O();if(!de.ok)return ee(Error(de.error.message));ko("schema"),T.reload(),I.reload(),c.reload(),oo(void 0),Wo([]),O()}).catch(ee).finally(()=>an(!1))}),[Ki,Wi]=Fe(""),[ao,Gi]=Fe("");Nt(()=>Gi(""),[m,v?.id]);let xl=()=>{let y=k?.fields??[],O=(v?.columnOrder??[]).filter((ee)=>y.some((ie)=>ie.id===ee));return[...O,...y.map((ee)=>ee.id).filter((ee)=>!O.includes(ee))]},[rt,Ro]=Fe(null),[kl,Zr]=Fe(""),[Qr,wl]=Fe(null);Nt(()=>{if(!Qr||!v||T.loading)return;if(!k?.fields.some((y)=>y.id===Qr.fieldId))return;wl(null),dt({...v,columnOrder:Qr.order})},[Qr,k,v,T.loading]),Nt(()=>Ro(null),[m]);let Pl=(y)=>{let O=k?.fields.find((ee)=>ee.id===y);if(!O)return;Zr(""),Ro({draft:structuredClone(O),initial:O,isNew:!1})},Xr=(y)=>{let O={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:a("New field"),type:"singleLineText"};Zr(""),Ro({draft:O,initial:O,isNew:!0,...y?{insert:y}:{}})},Sl=()=>{if(!rt||!k||!v)return;let y={...rt.draft,name:rt.draft.name.trim()};if(!y.name)return Zr(a("Field name is required."));let O=k.fields.map((de)=>de.id===y.id?y:de),ee;if(rt.isNew){if(O=[...k.fields,y],rt.insert){let{beside:de,side:je}=rt.insert;O=[...k.fields],O.splice(k.fields.findIndex((Ge)=>Ge.id===de)+(je==="right"?1:0),0,y),ee=xl(),ee.splice(Math.max(0,ee.indexOf(de)+(je==="right"?1:0)),0,y.id)}}let ie=rt.isNew;Zo({fields:O}).then(()=>{if(ee)wl({fieldId:y.id,order:ee});Ro(null),st(a(ie?"Field added":"Field saved"))}).catch((de)=>Zr(de instanceof Error?de.message:String(de)))},Td=(y)=>{if(!k)return;let O={...structuredClone(y),id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:a("{name} copy",{name:y.name})};delete O.required;let ee=[...k.fields];ee.splice(k.fields.findIndex((ie)=>ie.id===y.id)+1,0,O),Zo({fields:ee}).then(()=>st(a("Field duplicated"))).catch((ie)=>st(ie instanceof Error?ie.message:String(ie),!0))},Nd=()=>{let y=Ki;if(Wi(""),!k||!y)return;Zo({fields:k.fields.filter((O)=>O.id!==y)}).then(()=>st(a("Field deleted"))).catch((O)=>st(O instanceof Error?O.message:String(O),!0))},Md=(y)=>{if(!k||!v)return[];let O=k.fields[0]?.id===y.id,ee=cn(y)&&y.type!=="linkedRecord",ie=y.type==="singleSelect"||y.type==="checkbox",de=(v.type??"grid")==="grid"&&s.groupBy&&ie,je=v.groupByFieldId===y.id,Ge=J&&s.viewTypes.includes("kanban")&&ie,dn=!["relation","lookup","rollup"].includes(y.type),At=[];if(A){if((e.schemaFieldTypes??Ka).includes(y.type))At.push({id:"edit",icon:_(Ce,{name:"pencil"}),label:a("Edit field"),onSelect:()=>Pl(y.id)});if(dn)At.push({id:"duplicate",icon:_(Ce,{name:"copy"}),label:a("Duplicate field"),onSelect:()=>Td(y)})}if(s.columns)At.push({id:"hide",icon:_(Ce,{name:"eyeOff"}),label:a("Hide field"),disabled:O||v.type==="form"&&y.required===!0,onSelect:()=>dt({...v,hiddenColumns:[...v.hiddenColumns,y.id]})});if(J&&s.columnColors&&(v.type??"grid")==="grid")At.push({id:"column-color",icon:_(Ce,{name:"palette"}),label:a("Column color"),separatorBefore:!0,onSelect:()=>Gi(y.id)});let ti=xl().filter((xt)=>!v.hiddenColumns.includes(xt)).indexOf(y.id)+1,Al=s.columnFreezing&&(v.type??"grid")==="grid"&&ti>0&&ti<=4;if(Al){let xt=v.frozenColumnCount===ti;At.push({id:"freeze",icon:_(Ce,{name:"freeze"}),label:a(xt?"Unfreeze columns":"Freeze up to this field"),separatorBefore:!0,onSelect:()=>{let qn={...v};if(xt)delete qn.frozenColumnCount;else qn.frozenColumnCount=ti;dt(qn)}})}if(A)At.push({id:"insert-left",icon:_(Ce,{name:"arrowLeft"}),label:a("Insert field left"),separatorBefore:!Al,onSelect:()=>Xr({beside:y.id,side:"left"})},{id:"insert-right",icon:_(Ce,{name:"arrowRight"}),label:a("Insert field right"),onSelect:()=>Xr({beside:y.id,side:"right"})});if(ee&&s.sorting){let xt=v.sort?.length===1?v.sort[0]:void 0,qn=xt?.fieldId===y.id?xt.direction:void 0;At.push({id:"sort-asc",icon:_(Ce,{name:"sortAsc"}),label:a("Sort {name} ascending",{name:y.name}),separatorBefore:!0,disabled:qn==="asc",onSelect:()=>dt({...v,sort:[{fieldId:y.id,direction:"asc"}]})},{id:"sort-desc",icon:_(Ce,{name:"sortDesc"}),label:a("Sort {name} descending",{name:y.name}),disabled:qn==="desc",onSelect:()=>dt({...v,sort:[{fieldId:y.id,direction:"desc"}]})})}if(s.filter&&cn(y)&&y.type!=="linkedRecord")At.push({id:"filter",icon:_(Ce,{name:"filter"}),label:a("Filter by {name}",{name:y.name}),separatorBefore:!de&&!Ge&&!(ee&&s.sorting),onSelect:()=>{let xt=v.filter,qn={fieldId:y.id,operator:"isNotEmpty"};dt({...v,filter:xt?{...xt,filterSet:[...xt.filterSet,qn]}:{conjunction:"and",filterSet:[qn]}})}});if(de)At.push({id:"group",icon:_(Ce,{name:"group"}),label:a(je?"Ungroup by {name}":"Group by {name}",{name:y.name}),separatorBefore:!0,onSelect:()=>{let xt={...v};if(je)delete xt.groupByFieldId;else xt.groupByFieldId=y.id;dt(xt)}});if(Ge)At.push({id:"kanban",icon:_(Ce,{name:"kanban"}),label:a("Create kanban by {name}",{name:y.name}),separatorBefore:!de,onSelect:()=>{let xt={...v,id:e.createViewId?.(k.id)??crypto.randomUUID(),name:a(Rd.kanban),version:0,type:"kanban",columnOrder:v.columnOrder,hiddenColumns:[],groupByFieldId:y.id};delete xt.dateFieldId,Ho(xt)}});if(y.ai&&e.aiFillClient&&M)At.push({id:"ai-generate",icon:_(Ce,{name:"sparkles"}),label:a("Generate {name} with AI",{name:y.name}),separatorBefore:!0,onSelect:()=>{sn(y.id),An(!0)}});if(A&&!e.addOnlySchema&&!O)At.push({id:"delete",icon:_(Ce,{name:"trash"}),label:a("Delete field"),destructive:!0,separatorBefore:!0,onSelect:()=>Wi(y.id)});return At};if(c.error){let y={code:c.errorCode,message:c.error};return Ne("div",{"data-uibot-workspace":"","data-uibot":"collection-workspace",style:ge.main,children:[e.renderListError?e.renderListError(y,c.reload):_("p",{role:"alert",children:c.error}),Ne("div",{style:ge.actions,children:[_(W,{ui:e.ui,style:ge.button,onClick:c.reload,children:a("Reload records")}),e.toolbarActions]})]})}let Ld=v&&k&&Be==="settings"&&Ne("fieldset",{disabled:Oe,style:ge.fieldset,"data-uibot-panel":"settings",onKeyDown:Jr(),children:[Ne("label",{children:[a("View name")," ",_("input",{"aria-label":a("View name"),value:v.name,onChange:(y)=>dt({...v,name:y.currentTarget.value})})]}),_(rl,{fields:k.fields,view:v,onChange:dt,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},features:e.features??{preset:"full"},sections:e.inlineViewControls?{}:{filter:s.filter,columns:s.columns,sort:s.sorting},grouping:!e.inlineViewControls,filterEditor:{advanced:e.advancedFilters!==!1,...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},getRelationOptions:d}}),Ne("div",{style:ge.actions,children:[_(W,{ui:e.ui,style:ge.button,variant:"default",disabled:!St||!v.name.trim()||!J,onClick:()=>we(v),children:a("Save view")}),_(W,{ui:e.ui,style:ge.button,onClick:En,children:a("Done")})]})]}),Od=k&&Be==="schema"&&Ne("fieldset",{disabled:Oe,style:ge.fieldset,"data-uibot-panel":"schema",onKeyDown:Jr(vl),children:[Ne("label",{children:[a("Table title")," ",_("input",{"aria-label":a("Table title"),value:So,onChange:(y)=>b(y.currentTarget.value)})]}),_(qr,{fields:Po,...E?{focusFieldId:E}:{},onChange:wr,disabled:Oe,...e.schemaFieldTypes?{fieldTypes:e.schemaFieldTypes}:{},settings:Yo,relationTargets:c.data??[],lockedFieldIds:e.addOnlySchema?(k?.fields??[]).map((y)=>y.id):[],...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}),Ne("div",{style:e.renderPanel?ge.stickyFooter:ge.actions,children:[_(W,{ui:e.ui,style:ge.button,variant:"default",disabled:!G||Po.length===0||!So.trim(),onClick:vl,children:a("Save fields")}),e.renderPanel?null:_(W,{ui:e.ui,style:ge.button,onClick:io,children:a("Cancel field settings")})]})]}),ei=(y,O,ee)=>ee?e.renderPanel?e.renderPanel({kind:y,title:O,content:ee,dirty:y==="schema"?G:y==="add"||y==="record"?ne:!1,busy:Oe||(y==="add"||y==="record")&&be,onClose:En}):ee:null,Yi=It.data?.items.find((y)=>y.id===vr),Ji=k&&v?{descriptor:k,rows:It.data?.items??[],total:It.data?.total??0,reloadKey:eo,serverFooterStats:e.serverFooterStats??!0,...r?{aggregate:{client:r,aggregates:ro}}:{},view:v,onViewChange:dt,onSelectionChange:tt,onMutate:(y)=>i.mutate(k.id,y),relationClient:i,...e.renderRecordContextMenu?{renderRecordContextMenu:e.renderRecordContextMenu}:{},onCommitted:fn,readOnly:Oe||!S.write,features:s,display:{keyboardHints:!1,fill:!0,...s.footerStats?{summary:!1}:{}},...e.inlineViewControls||s.columnFreezing?{fieldMenu:Md}:{},...e.inlineViewControls&&L?{onAddRecord:()=>Dn("add")}:{},...e.inlineViewControls&&A?{onAddField:()=>Xr()}:{},onExpandRecord:(y)=>{Yr(y.id),Dn("record")},...e.onNotify?{onNotify:e.onNotify}:{},...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},getRelationOptions:d}:void 0,Io=k&&v?{descriptor:k,view:v,client:i,onCommitted:fn,reloadKey:eo,readOnly:!S.write,features:s,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},...r?{aggregate:{client:r,aggregates:ro}}:{}}:void 0,Rl=_(Gr,{children:e.toolbarActions}),Vd=!c.loading&&(c.data?.length??0)===0,Il=(e.showTableList??s.tableList)!==!1,Bd=Ne("div",{ref:he,onFocusCapture:(y)=>{if(y.target instanceof HTMLElement&&y.target.matches("input, textarea, select, [contenteditable=true]"))x.current=y.target},"data-uibot-workspace":"","data-uibot":"collection-workspace",style:{...ge.root,gridTemplateColumns:[Il?"auto":"","minmax(0, 1fr)",e.sidePanel||e.renderSidePanel?"auto":""].filter(Boolean).join(" ")},children:[Il&&_(Va,{tables:c.data??[],activeId:m,onSelect:f,...A&&(e.allowCreateTable??!0)?{onCreate:()=>{kr(""),Jo([{id:"name",name:a("Name"),type:"singleLineText",required:!0}]),Dn("create")}}:{},createDisabled:Oe,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}),Ne("main",{style:ge.main,children:[ao&&v&&k?.fields.some((y)=>y.id===ao)&&J&&_("div",{style:{justifySelf:"start",alignSelf:"start"},children:_(Bn,{ui:e.ui,defaultOpen:!0,icon:"palette",label:a("Column color for {name}",{name:k.fields.find((y)=>y.id===ao)?.name??""}),children:(y)=>_("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[null,...Tn].map((O,ee)=>_("button",{type:"button","aria-label":O?a("Column color {number}",{number:ee}):a("No color"),title:O?a("Column color {number}",{number:ee}):a("No color"),"aria-pressed":O?v.columnColors?.[ao]===O:!v.columnColors?.[ao],style:{...ge.button,...O?kn(ee-1):{},width:O?28:void 0,height:28,padding:O?0:"0 8px"},onClick:()=>{let ie={...v.columnColors};if(O)ie[ao]=O;else delete ie[ao];let{columnColors:de,...je}=v;dt(Object.keys(ie).length?{...je,columnColors:ie}:je),y(),Gi("")},children:O?"":a("No color")},O??"clear"))})},ao)}),Vd||e.hideHeader?_("div",{style:ge.actions,children:Rl}):_(Ba,{table:k,canManage:A,canWrite:L||M||U,onRename:(y)=>Zo({name:y}),onIconChange:(y)=>Zo({icon:y}),...e.locale?{locale:e.locale}:{},actions:Rl}),ht&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:!0,title:a("Discard unsaved changes?"),confirmLabel:a("Discard"),cancelLabel:a("Keep editing"),onConfirm:En,onCancel:()=>K(!1)}):null,ht&&!e.ui?.ConfirmDialog&&Ne("div",{role:"alertdialog","aria-label":a("Discard unsaved changes?"),style:ge.confirm,children:[a("Discard unsaved changes?"),_(W,{ui:e.ui,style:ge.button,onClick:En,children:a("Discard")}),_(W,{ui:e.ui,style:ge.button,onClick:()=>K(!1),children:a("Keep editing")})]}),Be==="create"?Ne("fieldset",{disabled:Oe,style:ge.fieldset,"data-uibot-panel":"create",onKeyDown:Jr(Cl),children:[Ne("label",{children:[a("Table name")," ",_("input",{"aria-label":a("Table name"),value:wo,onChange:(y)=>kr(y.currentTarget.value)})]}),_(qr,{fields:yn,onChange:Jo,disabled:Oe,...e.schemaFieldTypes?{fieldTypes:e.schemaFieldTypes}:{},settings:Yo,relationTargets:c.data??[],...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}),We?.error?_("p",{role:"alert",style:ge.error,children:We.text}):null,Ne("div",{style:ge.actions,children:[_(W,{ui:e.ui,style:ge.button,variant:"default",disabled:!wo.trim()||yn.length===0,onClick:Cl,children:a("Create table")}),_(W,{ui:e.ui,style:ge.button,onClick:io,children:a("Cancel")})]})]}):k&&v?Ne(Gr,{children:[Ne("div",{style:e.inlineViewControls?{display:"grid",gridTemplateColumns:"minmax(0, 1fr)",gap:8,minWidth:0}:ge.bar,children:[_(Qa,{views:Ct,activeId:v.id,dirty:St&&!Me,disabled:Oe,onSelect:ot,viewTypes:s.viewTypes,disabledViewTypes:[...k.fields.some((y)=>y.type==="singleSelect"||y.type==="checkbox")?[]:["kanban"],...k.fields.some((y)=>y.type==="date")?[]:["calendar"]],...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},...J?{onAdd:(y)=>{let O={...v,id:e.createViewId?.(k.id)??crypto.randomUUID(),name:a(Rd[y]),version:0,type:y,columnOrder:v.columnOrder,hiddenColumns:[]};delete O.groupByFieldId,delete O.dateFieldId;let ee=k.fields.find((de)=>de.type==="singleSelect"||de.type==="checkbox"),ie=k.fields.find((de)=>de.type==="date");if(y==="kanban"&&ee)O.groupByFieldId=ee.id;if(y==="calendar"&&ie)O.dateFieldId=ie.id;Ho(O)},onRename:(y,O)=>{let ee=Ct.find((ie)=>ie.id===y);if(ee&&O.trim()&&O!==ee.name)we({...ee,name:O.trim()})},onDuplicate:(y)=>{let O=Ct.find((ee)=>ee.id===y);if(O)we({...O,id:e.createViewId?.(k.id)??crypto.randomUUID(),name:a("{name} copy",{name:O.name}),version:0})},...i.deleteView&&Ct.length>1?{onDelete:(y)=>_n(y)}:{},...i.reorderViews&&m&&D.length>1?{onReorder:(y)=>{let O=y.filter((ie)=>D.some((de)=>de.id===ie)),ee=i.reorderViews;if(!ee||O.length<2)return;ln(()=>ee.call(i,m,{viewIds:O,idempotencyKey:zn("reorder",O)}),(ie,de)=>{if(ko("reorder"),de)B(ie)})}}:{}}:{}}),e.inlineViewControls?_(Ga.Provider,{value:Oe||e.viewControlsDisabled===!0,children:Ne("div",{style:{...ge.actions,justifyContent:"space-between"},children:[Ne("div",{style:ge.actions,children:[L&&_(W,{ui:e.ui,style:ge.button,icon:"plus",ariaLabel:a("Add record"),onClick:()=>Be==="add"?io():Dn("add"),children:a("Add record")}),e.aiFillClient&&M&&_(W,{ui:e.ui,style:ge.button,icon:"sparkles",ariaLabel:a("AI fill"),onClick:()=>{sn(""),An(!Jt)},children:a("AI fill")}),_(Id,{part:"main",fields:k.fields,view:v,onChange:dt,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},groupable:s.groupBy,filter:s.filter,sort:s.sorting,filterEditor:{advanced:e.advancedFilters!==!1,...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},getRelationOptions:d}})]}),Ne("div",{style:ge.actions,children:[_("span",{role:"status","aria-live":"polite",style:e.onNotify?_g:ge.status,children:Oe?a("Saving…"):""}),s.search?_("input",{type:"search","aria-label":a("Search records"),placeholder:a("Search"),style:ge.search,value:to,onChange:(y)=>hr(y.currentTarget.value)}):null,s.columns?_(Bn,{ui:e.ui,icon:"fields",label:a("Field config"),active:v.hiddenColumns.length>0,children:(y)=>_(fd,{fields:k.fields,view:v,onChange:dt,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},...A?{onEditField:(O)=>{y(),Pl(O)},onAddField:()=>{y(),Xr()},onEditAllFields:()=>{y(),re()}}:{}})}):null,s.columns?_(Id,{part:"extra",fields:k.fields,view:v,onChange:dt,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},groupable:s.groupBy,filter:s.filter,sort:s.sorting,filterEditor:{advanced:e.advancedFilters!==!1,...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},getRelationOptions:d}}):null,_(Bn,{ui:e.ui,icon:"sliders",label:a("View config"),children:Ne("div",{"data-uibot-view-config":"",style:{display:"grid",gap:10,minWidth:0},children:[Ne("label",{style:{display:"grid",gap:4},children:[a("View name"),_("input",{"aria-label":a("View name"),value:v.name,style:ge.search,onChange:(y)=>dt({...v,name:y.currentTarget.value})})]}),_(rl,{fields:k.fields,view:v,onChange:dt,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},features:e.features??{preset:"full"},sections:{},grouping:!1,rowHeight:!1})]})}),_(W,{ui:e.ui,style:ge.button,icon:"refresh",iconOnly:!0,variant:"ghost",ariaLabel:a("Refresh"),onClick:Ht})]})]})}):Ne("div",{style:ge.actions,children:[s.search?_("input",{type:"search","aria-label":a("Search records"),placeholder:a("Search"),style:ge.search,value:to,onChange:(y)=>hr(y.currentTarget.value)}):null,_(W,{ui:e.ui,style:ge.button,icon:"refresh",iconOnly:!0,variant:"ghost",ariaLabel:a("Refresh"),onClick:Ht}),(J||s.filter||s.columns)&&_(W,{ui:e.ui,style:ge.button,icon:"sliders",iconOnly:!0,variant:"ghost",ariaLabel:a("View settings"),onClick:()=>Be==="settings"?En():Dn("settings")}),J?_(W,{ui:e.ui,style:ge.button,icon:"save",iconOnly:!0,variant:"ghost",badge:St,ariaLabel:a("Save view"),disabled:!St||!v.name.trim()||Oe,onClick:()=>we(v)}):null,!e.inlineViewControls&&s.filter&&v.filter?.filterSet.length?_(W,{ui:e.ui,style:ge.button,icon:"filter",ariaLabel:a("Clear current filter"),onClick:()=>{let{filter:y,...O}=v;dt(O)},children:a("{count} filters",{count:v.filter.filterSet.length})}):null,A&&_(W,{ui:e.ui,style:ge.button,icon:"fields",iconOnly:!0,variant:"ghost",ariaLabel:a("Configure fields"),onClick:()=>Be==="schema"?io():re()}),L&&_(W,{ui:e.ui,style:ge.button,icon:"plus",ariaLabel:a("Add record"),onClick:()=>Be==="add"?io():Dn("add"),children:a("Add record")}),e.aiFillClient&&M&&_(W,{ui:e.ui,style:ge.button,icon:"sparkles",ariaLabel:a("AI fill"),onClick:()=>{sn(""),An(!Jt)},children:a("AI fill")}),_("span",{role:"status","aria-live":"polite",style:ge.status,children:Oe?a("Saving…"):""})]})]}),e.relationNavigation!==!1&&Ae.length>0?Ne("div",{style:ge.actions,children:[_(W,{ui:e.ui,style:ge.button,onClick:()=>rn(!Pt),children:a("Relations")}),Pt?Ae.map((y)=>_(W,{ui:e.ui,style:ge.button,disabled:y.needsRecord&&oe.recordIds.length!==1,onClick:y.open,children:y.label},y.key)):null]}):null,Ki&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:!0,title:a("Delete field “{name}”?",{name:k.fields.find((y)=>y.id===Ki)?.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:Oe,onConfirm:Nd,onCancel:()=>Wi("")}):null,Ut&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:!0,title:a("Delete view “{name}”?",{name:Ct.find((y)=>y.id===Ut)?.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:Oe,onConfirm:$o,onCancel:()=>_n("")}):null,Ut&&!e.ui?.ConfirmDialog&&Ne("div",{role:"alertdialog","aria-label":a("Delete view"),style:ge.confirm,children:[a("Delete view “{name}”?",{name:Ct.find((y)=>y.id===Ut)?.name??""}),_("small",{style:ge.status,children:a("Only this view's filters, sort and layout are removed; no records are deleted.")}),_(W,{ui:e.ui,style:ge.button,disabled:Oe,onClick:$o,children:a("Delete view")}),_(W,{ui:e.ui,style:ge.button,onClick:()=>_n(""),children:a("Cancel")})]}),We&&_("p",{role:We.error?"alert":"status",style:We.error?ge.error:ge.status,children:We.text}),e.transferClient&&s.export?_(ha,{descriptor:k,fieldIds:k.fields.filter((y)=>!v.hiddenColumns.includes(y.id)).map((y)=>y.id),query:{search:to,...v.filter?{filter:v.filter}:{},...v.sort?.length?{sort:v.sort}:{}},client:e.transferClient,readOnly:!L,reloadKey:eo,onImported:fn,onRefreshSchema:async()=>{let y=await i.describe(k.id);return I.reload(),y.ok?y.data:null}}):null,ei("settings",a("View settings"),Ld),ei("schema",a("Fields"),Od),ei("add",a("Add record"),Be==="add"&&Ji?_("fieldset",{"aria-label":a("Add record"),"data-uibot-panel":"add",style:{margin:0,padding:0,border:0,minWidth:0},onKeyDown:Jr(),children:_(Ha,{descriptor:k,client:i,readOnly:!L,autoFocus:!0,onDirtyChange:Pe,onBusyChange:Re,onCommitted:()=>fn(),onSaved:(y)=>{En();let O=qa(k,y.items[0]);st(`${a("Record saved")}${O?`:${O}`:""}`)},onCancel:io,stickyActions:Boolean(e.renderPanel),...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}})}):null),ei("record",a("Record details"),Be==="record"&&Io&&Yi?_(Wn,{...Io,row:Yi,onClose:En,onCancel:io,onDirtyChange:Pe,onBusyChange:Re,stickyActions:Boolean(e.renderPanel)},Yi.id):null),Go&&Ji?It.error?Ne("p",{role:"alert",children:[It.error," ",_(W,{ui:e.ui,style:ge.button,onClick:It.reload,children:a("Reload records")})]}):Ne(Gr,{children:[It.loading&&_("p",{role:"status",children:a("Loading records…")}),_(gd,{...Ji},`${m}:${z}:${k.schemaVersion}:${Ko}:${Gt??""}`),r&&!s.footerStats?Ne("div",{style:ge.actions,children:[_(Je,{ui:e.ui,label:a("Sum field"),style:ge.button,value:Mt,options:[{value:"",label:a("No sum")},...k.fields.filter((y)=>y.type==="number").map((y)=>({value:y.id,label:y.name}))],onChange:xr}),_(Bo,{collectionId:k.id,descriptor:k,view:v,aggregates:ro,client:r,labels:$i,reloadKey:eo,...e.locale?{locale:e.locale}:{}})]}):null,_("div",{style:ge.actions,children:_(Ra,{hasPrevious:Yt.length>0,hasNext:Boolean(It.data?.nextCursor),loading:It.loading,onPrevious:()=>{oo(Yt.at(-1)),Wo(Yt.slice(0,-1))},onNext:()=>{Wo([...Yt,Gt]),oo(It.data?.nextCursor??void 0)},page:Yt.length+1,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}})})]}):Io?v.type==="kanban"?_(Xa,{...Io},v.id):v.type==="gallery"?_(tl,{...Io},v.id):v.type==="calendar"?_(ol,{...Io},v.id):_(Da,{...Io,...Ct.some((y)=>y.type!=="form")?{onShowRecords:()=>{let y=Ct.find((O)=>O.type!=="form");if(y)ot(y.id)}}:{}},v.id):null]}):!c.loading&&m&&!P?_("p",{role:"alert",children:a("Table not found")}):I.data&&I.data.id!==m?_("p",{role:"alert",children:a("Table not found")}):T.error?_("p",{role:"alert",children:T.error}):k&&q&&!T.loading&&e.viewId!==void 0&&!v?_("p",{role:"alert",children:a("View not found")}):I.error?_("p",{role:"alert",children:I.error}):c.loading||I.loading?_("p",{role:"status",children:a("Loading…")}):Ne("div",{style:ge.empty,children:[_("p",{style:{margin:0},children:a("No tables yet")}),A&&(e.allowCreateTable??!0)?_(W,{ui:e.ui,style:ge.button,onClick:()=>{kr(""),Jo([{id:"name",name:a("Name"),type:"singleLineText",required:!0}]),Dn("create")},children:a("New table")}):null]})]}),Jt&&e.aiFillClient&&k&&M?_(wd,{table:k,rows:It.data?.items??[],selection:oe,aiFillClient:e.aiFillClient,client:i,query:jo,...It.data?{total:It.data.total}:{},onCommitted:()=>fn(),onClose:()=>An(!1),...Cr?{presetFieldId:Cr}:{},...e.onNotify?{onNotify:e.onNotify}:{},...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}},Cr):null,rt&&k?_(Sd,{container:he,anchorFieldId:rt.isNew?rt.insert?.beside:rt.draft.id,title:a(rt.isNew?"Add field":"Edit field"),dirty:!br(rt.draft,rt.initial),onCancel:()=>Ro(null),children:Ne("fieldset",{disabled:Oe,style:{border:0,padding:0,margin:0,minWidth:0,display:"grid",gap:12},onKeyDown:(y)=>{if(y.key==="Enter"&&(y.ctrlKey||y.metaKey)&&!Oe)y.preventDefault(),Sl()},children:[_(qr,{single:!0,fields:[rt.draft],contextFields:k.fields.filter((y)=>y.id!==rt.draft.id),onChange:(y)=>{let O=y[0];if(O)Ro((ee)=>ee?{...ee,draft:O}:ee)},disabled:Oe,...e.schemaFieldTypes?{fieldTypes:e.schemaFieldTypes}:{},settings:Yo,relationTargets:c.data??[],lockedFieldIds:e.addOnlySchema&&!rt.isNew?[rt.draft.id]:[],...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}),kl?_("p",{role:"alert",style:{margin:0,color:"var(--destructive, #b42318)"},children:kl}):null,Ne("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[_(W,{ui:e.ui,style:ge.button,onClick:()=>Ro(null),children:a("Cancel")}),_(W,{ui:e.ui,style:ge.button,variant:"default",disabled:Oe||!rt.draft.name.trim()||!rt.isNew&&br(rt.draft,rt.initial),onClick:Sl,children:a(rt.isNew?"Add field":"Save field")})]})]})}):null,e.renderOverlay?.({table:k,view:v,selection:oe,rows:It.data?.items??[],reload:fn}),e.sidePanel||e.renderSidePanel?Ne("aside",{style:ge.side,children:[e.sidePanel,e.renderSidePanel?.({table:k,view:v,selection:oe,rows:It.data?.items??[],reload:fn})]}):null]});return _(Qi.Provider,{value:ji.report,children:_(pa,{client:e.linkClient,children:Bd})})}var ge={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 Id({fields:e,view:t,onChange:n,locale:o,ui:i,groupable:r,filter:l=!0,sort:d=!0,filterEditor:a,part:s}){let u=se(o),c={fields:e,view:t,onChange:n,locale:o,ui:i},g=t.filter?.filterSet.length??0,p=t.sort?.length??0,m=r&&(t.type??"grid")==="grid"&&e.some((h)=>h.type==="singleSelect"||h.type==="checkbox");return Ne(Gr,{children:[s==="main"&&Ne(Gr,{children:[l?_(Bn,{ui:i,icon:"filter",active:g>0,label:g?u("{count} filters",{count:g}):u("Filter"),children:_("div",{style:{width:"100%",maxWidth:520,minWidth:0},children:_(Ni,{...c,editor:a})})}):null,m&&_(Bn,{ui:i,icon:"group",active:Boolean(t.groupByFieldId),label:u("Group"),children:_("div",{style:{width:"100%",maxWidth:360,minWidth:0},children:_(Li,{...c})})}),d?_(Bn,{ui:i,icon:"sort",active:p>0,label:p?u("{count} sorts",{count:p}):u("Sort"),children:_("div",{style:{width:"100%",maxWidth:440,minWidth:0},children:_(Mi,{...c})})}):null]}),s==="extra"&&(t.type??"grid")==="grid"&&_(Bn,{ui:i,icon:"rows",label:u("Row height"),active:Boolean(t.rowHeight),children:_("div",{style:{display:"grid",gap:2,minWidth:140},children:ri.map((h)=>_(W,{ui:i,variant:(t.rowHeight??"short")===h?"outline":"ghost",size:"sm",onClick:()=>{let x={...t};if(h==="short")delete x.rowHeight;else x.rowHeight=h;n(x)},children:u(`Row height ${h}`)},h))})})]})}var _g={position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)"};export{yx as PagedCollectionWorkspace};
25
+ `}),Z("div",{style:{position:"relative",width:u,height:"100%",transform:"translateX(calc(var(--uibot-sx, 0px) * -1))"},children:d.map((w)=>{let y=a[w.index];if(!y)return null;let E=w.index===0,S=c.footerStats?.[y.id],k=S!==void 0?S==="none"?void 0:S:E?"count":void 0,O=k?kd(l,y,k):null,L=(N)=>N===null?"":typeof N==="number"&&k!=="count"&&k!=="filled"&&k!=="empty"?sn(Math.round(N*100)/100,y):typeof N==="number"?N.toLocaleString(r):sn(N,y),z=L(O),G=!t?O:k==="count"?s:h.values[`footer${w.index}`]??null,P=!k?"":!t||k==="count"?L(G):h.status==="loading"?"…":h.status==="error"||G===null?"—":L(G),R=k?k==="count"&&E?i("Footer record count",{count:P}):`${i(`Footer ${k}`)} ${P}`.trim():i("Auto summary"),M=w.index<f;return Z("div",{"data-uibot-footer-cell":"",style:{position:"absolute",left:M?p(w.index):w.start,width:w.size,height:"100%",boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"flex-end",padding:"0 4px",background:Zi(c.columnColors?.[y.id])?.background??"var(--background, white)",zIndex:M?2:void 0,transform:M?"translateX(var(--uibot-sx, 0px))":void 0,opacity:k?1:0,transition:"opacity 120ms"},children:Z(zn,{ui:o,chevron:!0,quiet:!0,active:!1,label:R,children:(N)=>mt("div",{style:{display:"grid",gap:2,minWidth:150},children:[Z(Y,{ui:o,variant:k?"ghost":"outline",size:"sm",onClick:()=>{g(y.id,null,E),N()},children:i("No summary")}),wd(y).map((I)=>Z(Y,{ui:o,variant:k===I?"outline":"ghost",size:"sm",onClick:()=>{g(y.id,I,E),N()},children:i(`Footer ${I}`)},I)),t&&h.status==="error"&&k&&k!=="count"?Z("small",{style:{opacity:0.7,padding:"4px 6px"},children:i("Loaded records fallback: {value}",{value:z||"—"})}):null,(!t||h.status==="error")&&s>l.length?Z("small",{style:{opacity:0.7,padding:"4px 6px"},children:i("Summaries cover the {count} loaded records.",{count:l.length})}):null]})})},y.id)})})]})}var bl=44,hl=36;import{DndContext as Tp,KeyboardSensor as Fp,PointerSensor as Np,closestCenter as Mp,useSensor as Rd,useSensors as Op}from"@dnd-kit/core";import{SortableContext as Lp,arrayMove as Bp,sortableKeyboardCoordinates as Vp,useSortable as Up,verticalListSortingStrategy as _p}from"@dnd-kit/sortable";import{CSS as zp}from"@dnd-kit/utilities";import{useState as qp}from"react";import{jsx as Nt,jsxs as ko}from"react/jsx-runtime";var Cl="1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",Hp=({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 Ad({fields:e,view:t,onChange:n,locale:o,ui:r,onEditField:i,onAddField:l,onEditAllFields:s}){let a=oe(o),[d,u]=qp(""),f=Op(Rd(Np,{activationConstraint:{distance:4}}),Rd(Fp,{coordinateGetter:Vp})),c=[...t.columnOrder.flatMap((y)=>{let E=e.find((S)=>S.id===y);return E?[E]:[]}),...e.filter((y)=>!t.columnOrder.includes(y.id))],C=c.map((y)=>y.id),x=({active:y,over:E})=>{if(!E||y.id===E.id)return;let S=C.indexOf(String(y.id)),k=C.indexOf(String(E.id));if(S<0||k<0)return;n({...t,columnOrder:Bp(C,S,k)})},h=e[0]?.id,g=d.trim().toLowerCase(),w=g?c.filter((y)=>y.name.toLowerCase().includes(g)):c;return ko("div",{"data-uibot-field-config":"",style:{display:"grid",gap:6,minWidth:0},children:[Nt("input",{type:"search","aria-label":a("Search fields"),placeholder:a("Search fields"),value:d,onChange:(y)=>u(y.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"}}),Nt(Tp,{sensors:f,collisionDetection:Mp,modifiers:[Hp],onDragEnd:x,children:Nt(Lp,{items:w.map((y)=>y.id),strategy:_p,disabled:Boolean(g),children:ko("div",{style:{display:"grid",gap:2,maxHeight:320,overflowY:"auto"},children:[w.map((y)=>{let E=!t.hiddenColumns.includes(y.id);return ko(jp,{id:y.id,label:a("Reorder {name}",{name:y.name}),disabled:Boolean(g),dimmed:!E,children:[Nt(Wi,{type:y.type}),ko("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[y.name,y.required?" *":""]}),Nt(Y,{ui:r,variant:"ghost",size:"sm",icon:E?"eye":"eyeOff",iconOnly:!0,disabled:t.type==="form"&&y.required===!0||y.id===h,ariaLabel:a(E?"Hide {name}":"Show {name}",{name:y.name}),onClick:()=>n({...t,hiddenColumns:E?[...t.hiddenColumns,y.id]:t.hiddenColumns.filter((S)=>S!==y.id)})}),i&&Nt(Y,{ui:r,variant:"ghost",size:"sm",icon:"more",iconOnly:!0,ariaLabel:a("Edit field {name}",{name:y.name}),onClick:()=>i(y.id)})]},y.id)}),w.length===0&&Nt("span",{style:{opacity:0.7,padding:6},children:a("No matching fields")})]})})}),ko("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"8px 4px 2px",borderTop:Cl},children:[Nt("span",{children:a("Show row numbers")}),Nt(Id,{ui:r,checked:t.showRowNumber!==!1,label:a("Show row numbers"),onChange:(y)=>n({...t,showRowNumber:y})})]}),ko("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"8px 4px 2px",borderTop:Cl},children:[Nt("span",{children:a("Show record IDs")}),Nt(Id,{ui:r,checked:t.showRecordId===!0,label:a("Show record IDs"),onChange:(y)=>n({...t,showRecordId:y})})]}),(l||s)&&ko("div",{style:{borderTop:Cl,paddingTop:6,display:"flex",justifyContent:"space-between",gap:8},children:[l&&Nt(Y,{ui:r,variant:"ghost",size:"sm",icon:"plus",onClick:l,children:a("Add field")}),s&&Nt(Y,{ui:r,variant:"ghost",size:"sm",icon:"fields",onClick:s,children:a("Edit all fields")})]})]})}function jp({id:e,label:t,disabled:n,dimmed:o,children:r}){let{attributes:i,listeners:l,setNodeRef:s,setActivatorNodeRef:a,transform:d,transition:u,isDragging:f}=Up({id:e,disabled:n});return ko("div",{ref:s,style:{display:"flex",alignItems:"center",gap:6,padding:"2px 4px",borderRadius:6,transform:zp.Transform.toString(d),transition:u,position:"relative",zIndex:f?2:void 0,background:f?"var(--accent, color-mix(in srgb, currentColor 8%, transparent))":void 0,opacity:o&&!f?0.55:1},children:[Nt("button",{type:"button",ref:a,"aria-label":t,title:t,disabled:n,...i,...l,style:{display:"inline-flex",padding:0,border:0,background:"transparent",color:"inherit",cursor:n?"default":f?"grabbing":"grab",touchAction:"none"},children:Nt(ve,{name:"grip"})}),r]})}function Id({ui:e,checked:t,label:n,onChange:o}){if(e?.Switch)return e.Switch({checked:t,onChange:o,"aria-label":n});return Nt("input",{type:"checkbox","aria-label":n,checked:t,onChange:(r)=>o(r.currentTarget.checked)})}import{useEffect as Nd,useMemo as Wp,useRef as Md,useState as qt}from"react";var vl=50,Qr=1000,xl=100;function Zr(e,t){let n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}function Ed(e){let t=new Set,n=[],o=0;for(let r of e){o+=r.skipped;for(let i of r.changes){if(t.has(i.key)){o+=1;continue}t.add(i.key),n.push(i)}}return{changes:n,skipped:o}}function Xi(e){return e.filter((t)=>Fr.has(t.type)&&!it(t)&&t.generation!=="autoIncrement")}var Qi=(e)=>e===null||e===void 0||e===""||Array.isArray(e)&&e.length===0,$p=(e,t)=>Qi(e)&&Qi(t)?!0:JSON.stringify(e)===JSON.stringify(t);function Dd(e,t){return e.filter((n)=>t.some((o)=>Qi(n.values[o])))}function wl(e,t){let n=new Set(t);for(let o of t){let r=e.find((i)=>i.id===o)?.ai?.sourceFieldIds;if(!r?.length)return;for(let i of r)n.add(i)}return e.filter((o)=>n.has(o.id)).map((o)=>o.id)}function kl(e,t){if(!t)return e;return e.map((n)=>({...n,values:Object.fromEntries(t.filter((o)=>(o in n.values)).map((o)=>[o,n.values[o]]))}))}function Kp(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=(r)=>e.options?.find((i)=>i.id===r||i.name===r)?.id;if(e.type==="singleSelect")return n(t);if(!Array.isArray(t))return;let o=t.map(n);return o.every((r)=>r!==void 0)?o:void 0}default:return}}function Pl(e,t,n,o){let r=new Map(Xi(e).filter((d)=>n.includes(d.id)).map((d)=>[d.id,d])),i=new Map(t.map((d)=>[d.id,d])),l=[],s=new Set,a=0;for(let d of o){let u=i.get(d.recordId);if(!u){a+=Object.keys(d.values).length;continue}for(let[f,p]of Object.entries(d.values)){let c=r.get(f),C=`${u.id}:${f}`,x=c?Kp(c,p):void 0;if(!c||x===void 0||s.has(C)||$p(u.values[f],x)){a+=1;continue}s.add(C),l.push({key:C,recordId:u.id,expectedVersion:u.version,fieldId:f,before:u.values[f]??null,after:x,...d.reason?{reason:d.reason}:{}})}}return{changes:l,skipped:a}}function Sl(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 Td(e,t){let n=new Map(t.map((r)=>[r.id,r.version])),o=new Map;for(let r of e){let i=n.get(r.recordId);if(i===void 0)continue;let l=o.get(r.recordId)??{op:"update",id:r.recordId,expectedVersion:i,values:{}};l.values[r.fieldId]=r.before,o.set(r.recordId,l)}return[...o.values()]}function Rl(e,t){return Xi(e).filter((n)=>n.ai?.autoFill&&n.ai.prompt.trim()).map((n)=>({field:n,records:t.filter((o)=>Qi(o.values[n.id]))})).filter((n)=>n.records.length>0)}async function Fd(e){let t=new Map(e.records.map((o)=>[o.id,o])),n=0;try{for(let o of Rl(e.fields,e.records)){let r=[o.field.id],i=wl(e.fields,r),l=i?e.fields.filter((s)=>i.includes(s.id)):e.fields;for(let s of Zr(o.records,vl)){let a=s.map((f)=>t.get(f.id)??f),d=await e.fill({tableId:e.tableId,fields:l,instruction:o.field.ai?.prompt.trim()??"",targetFieldIds:r,records:kl(a,i)});if(!d.ok)return{filled:n,error:d.error.message};let{changes:u}=Pl(e.fields,a,r,d.data.suggestions);for(let f of Zr(Sl(u),xl)){let p=await e.mutate(f);if(!p.ok)return{filled:n,error:p.error.message};for(let c of p.data.items)t.set(c.id,c);n+=f.length}}}}catch(o){return{filled:n,error:o instanceof Error?o.message:String(o)}}return{filled:n}}import{jsx as He,jsxs as Ct,Fragment as Od}from"react/jsx-runtime";var Gp=[{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."}],Pt={border:"var(--border, #d5d9df)",background:"var(--background, white)",muted:"var(--muted, #f4f5f7)",faint:"var(--muted-foreground, #6b7280)",primary:"var(--primary, #2563eb)"},At={drawer:{position:"fixed",top:0,right:0,bottom:0,zIndex:80,width:"min(440px, 100vw)",display:"flex",flexDirection:"column",background:Pt.background,color:"inherit",borderLeft:`1px solid ${Pt.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 ${Pt.border}`},body:{flex:1,minHeight:0,overflowY:"auto",padding:14,display:"grid",gap:14,alignContent:"start"},label:{display:"grid",gap:6,fontSize:12,color:Pt.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 ${Pt.border}`,background:Pt.background,color:"inherit",font:"inherit"},foot:{display:"flex",alignItems:"center",gap:8,padding:"10px 14px",borderTop:`1px solid ${Pt.border}`},group:{border:`1px solid ${Pt.border}`,borderRadius:8,overflow:"hidden"},groupHead:{padding:"6px 10px",background:Pt.muted,fontSize:12,fontWeight:600},change:{display:"grid",gridTemplateColumns:"auto 1fr",gap:8,padding:"8px 10px",borderTop:`1px solid ${Pt.border}`,fontSize:13},before:{color:Pt.faint,textDecoration:"line-through",overflowWrap:"anywhere"},after:{fontWeight:500,overflowWrap:"anywhere"},reason:{fontSize:12,color:Pt.faint,display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"}},Xr=(e)=>({display:"inline-flex",alignItems:"center",gap:4,padding:"3px 10px",borderRadius:999,fontSize:12,cursor:"pointer",border:`1px solid ${e?Pt.primary:Pt.border}`,background:e?"color-mix(in srgb, var(--primary, #2563eb) 14%, transparent)":"transparent",color:"inherit"});function Ld(e){let{table:t,rows:n,selection:o,aiFillClient:r}=e,i=oe(e.locale),l=Wp(()=>Xi(t.fields),[t.fields]),s=l.find((Q)=>Q.id===e.presetFieldId&&Q.ai),[a,d]=qt(s?e.query?"view":"page":o.recordIds.length?"selected":"page"),[u,f]=qt(()=>{if(s)return[s.id];let Q=l.filter((ge)=>o.fieldIds.includes(ge.id)).map((ge)=>ge.id);return Q.length?Q:l.map((ge)=>ge.id)}),[p,c]=qt(s?.ai?.prompt??""),[C,x]=qt(Boolean(s)),[h,g]=qt([]),[w,y]=qt(""),[E,S]=qt("idle"),[k,O]=qt(),[L,z]=qt(new Set),[G,P]=qt(""),[R,M]=qt(""),[N,I]=qt(!1),[B,v]=qt(),[K,ce]=qt([]),[fe,_]=qt(),ie=Md(null),ue=Md(null);Nd(()=>{let Q=!0;return r.models?.().then((ge)=>{if(Q&&ge.ok)g(ge.data),y((Pe)=>Pe||ge.data[0]?.id||"")}),()=>{Q=!1,ie.current?.abort()}},[r]),Nd(()=>{ue.current?.focus()},[]);let W=n.filter((Q)=>o.recordIds.includes(Q.id)),q=Math.min(e.total??n.length,Qr),xe=a==="selected"?W.length:a==="page"?n.length:q,ke=(Q)=>t.fields.find((ge)=>ge.id===Q),ye=E!=="running"&&xe>0&&u.length>0&&p.trim()!=="",re=async(Q)=>{if(a==="selected")return W;if(a==="page"||!e.query)return n.slice(0,Qr);let ge=[],Pe;do{let we=await e.client.query(t.id,{...e.query,limit:100,...Pe?{cursor:Pe}:{}});if(!we.ok)throw Error(we.error.message);ge.push(...we.data.items),Pe=we.data.nextCursor??void 0}while(Pe&&ge.length<Qr&&!Q.aborted);return ge.slice(0,Qr)},Ce=wl(t.fields,u),he=Ce?t.fields.filter((Q)=>Ce.includes(Q.id)):t.fields,Ye=async(Q,ge)=>{let Pe=new AbortController;ie.current=Pe,S("running"),M("");let we=[...ge],Je=[],on=[],En="",Mt=Zr(Q,vl);v({done:0,total:Mt.length,failed:Je,error:""});for(let[Ze,gn]of Mt.entries()){if(Pe.signal.aborted)break;let Le=await r.fill({tableId:t.id,fields:he,instruction:p.trim(),targetFieldIds:u,records:kl(gn,Ce),...w?{model:w}:{}},{signal:Pe.signal}).catch((ft)=>({ok:!1,error:{code:"unknown",message:ft instanceof Error?ft.message:typeof ft==="object"&&ft&&("message"in ft)?String(ft.message):String(ft)}}));if(Pe.signal.aborted)break;if(Le.ok){we.push(Pl(t.fields,gn,u,Le.data.suggestions));let ft=[Le.data.summary,Le.data.usage].filter(Boolean).join(" · ");if(ft)on.push(Mt.length>1?`${Ze+1}/${Mt.length} ${ft}`:ft)}else Je.push(...gn),En=Le.error.message;v({done:Ze+1,total:Mt.length,failed:[...Je],error:En})}let Dt=Ed(we);if(!Dt.changes.length&&!we.length){M(En||i("No changes were suggested.")),S("idle");return}O(Dt),z(new Set(Dt.changes.map((Ze)=>Ze.key))),P(on.join(`
26
+ `)),S("review")},j=async()=>{let Q=new AbortController;ie.current=Q,S("running"),M(""),_(void 0),O(void 0),v(void 0);let ge;try{ge=await re(Q.signal)}catch(Pe){M(Pe instanceof Error?Pe.message:String(Pe)),S("idle");return}if(Q.signal.aborted){S("idle");return}if(C)ge=Dd(ge,u);if(!ge.length){M(i("No records have empty target cells.")),S("idle");return}ce(ge),await Ye(ge,[])},D=async()=>{if(!B?.failed.length)return;await Ye(B.failed,k?[k]:[])},te=()=>ie.current?.abort(),T=async(Q)=>{let ge=[];for(let Pe of Zr(Q,xl)){let we=await e.client.mutate(t.id,{idempotencyKey:crypto.randomUUID(),items:Pe});if(!we.ok)return{ok:!1,error:we.error,committedRecords:ge};ge.push(...we.data.items),e.onCommitted(we.data)}return{ok:!0,committedRecords:ge}},Te=async()=>{if(!k)return;let Q=k.changes.filter((Je)=>L.has(Je.key));if(!Q.length)return;I(!0),M("");let ge=await T(Sl(Q));I(!1);let Pe=new Set(ge.committedRecords.map((Je)=>Je.id)),we=Q.filter((Je)=>Pe.has(Je.recordId));if(we.length)_({changes:we,records:ge.committedRecords});if(!ge.ok){let Je=ge.error.code==="version_conflict"?i("Some records changed since the preview. Generate again to review the latest values."):ge.error.message;if(M(we.length?`${i("Applied {count} AI changes",{count:we.length})} · ${Je}`:Je),we.length){let on=k.changes.filter((En)=>!Pe.has(En.recordId));O({changes:on,skipped:k.skipped})}return}e.onNotify?.(i("Applied {count} AI changes",{count:Q.length})),O(void 0),v(void 0),S("idle")},ot=async()=>{if(!fe)return;I(!0);let Q=await T(Td(fe.changes,fe.records));if(I(!1),!Q.ok){M(Q.error.message);return}e.onNotify?.(i("AI changes undone")),_(void 0)},In=new Map;for(let Q of k?.changes??[])In.set(Q.recordId,[...In.get(Q.recordId)??[],Q]);let An=(Q,ge)=>Q.includes(ge)?Q.filter((Pe)=>Pe!==ge):[...Q,ge];return Ct("aside",{ref:ue,tabIndex:-1,"aria-label":i("AI fill"),"data-uibot":"ai-fill-drawer",style:At.drawer,onKeyDown:(Q)=>{if(Q.key==="Escape"&&!Q.nativeEvent.isComposing)Q.stopPropagation(),e.onClose()},children:[Ct("div",{style:At.head,children:[He(ve,{name:"sparkles"}),He("strong",{style:{flex:1},children:i("AI fill")}),He(Y,{ui:e.ui,variant:"ghost",size:"icon",icon:"x",iconOnly:!0,ariaLabel:i("Close"),onClick:e.onClose})]}),Ct("div",{style:At.body,children:[Ct("div",{style:At.label,children:[i("Records in scope"),He(Xe,{ui:e.ui,label:i("Records in scope"),value:a,onChange:(Q)=>d(Q),options:[{value:"selected",label:i("Selected records ({count})",{count:W.length}),disabled:W.length===0},{value:"page",label:i("Loaded records ({count})",{count:n.length})},...e.query?[{value:"view",label:i("All records in this view ({count})",{count:q})}]:[]]})]}),Ct("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:12},children:[He("input",{type:"checkbox",checked:C,onChange:(Q)=>x(Q.target.checked)}),i("Only records with empty target cells")]}),Ct("fieldset",{style:{...At.label,border:0,margin:0,padding:0},children:[He("legend",{style:{padding:0,marginBottom:6},children:i("Fields to fill")}),He("div",{style:At.chips,children:l.map((Q)=>Ct("button",{type:"button","aria-pressed":u.includes(Q.id),style:Xr(u.includes(Q.id)),onClick:()=>f(An(u,Q.id)),children:[Q.ai?He(ve,{name:"sparkles",size:12}):null,Q.name]},Q.id))})]}),Ct("label",{style:At.label,children:[i("Instruction"),He("textarea",{style:At.textarea,value:p,placeholder:i("Describe what to fill or change"),onChange:(Q)=>c(Q.target.value),onKeyDown:(Q)=>{if(Q.key==="Enter"&&(Q.metaKey||Q.ctrlKey)&&ye)Q.preventDefault(),j()}}),He("span",{style:At.chips,children:Gp.map((Q)=>He("button",{type:"button",style:Xr(!1),onClick:()=>c(i(Q.text)),children:i(Q.label)},Q.id))})]}),h.length>0&&Ct("div",{style:At.label,children:[i("Model"),He(Xe,{ui:e.ui,label:i("Model"),value:w,onChange:y,options:h.map((Q)=>({value:Q.id,label:Q.label}))})]}),R&&He("p",{role:"alert",style:{margin:0,color:"var(--destructive, #b42318)"},children:R}),fe&&Ct("p",{role:"status",style:{margin:0},children:[i("Applied {count} AI changes",{count:fe.changes.length})," ",He("button",{type:"button",style:Xr(!1),disabled:N,onClick:()=>void ot(),children:i("Undo")})]}),E!=="running"&&B&&B.failed.length>0&&Ct("p",{role:"alert",style:{margin:0,color:"var(--destructive, #b42318)"},children:[i("{count} records could not be processed: {reason}",{count:B.failed.length,reason:B.error})," ",He("button",{type:"button",style:Xr(!1),onClick:()=>void D(),children:i("Retry failed")})]}),E==="review"&&k&&Ct("section",{"aria-label":i("Suggestions"),style:{display:"grid",gap:10},children:[Ct("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:Pt.faint},children:[Ct("span",{style:{flex:1},children:[i("{count} suggested changes",{count:k.changes.length}),k.skipped?` · ${i("Skipped {count} cells",{count:k.skipped})}`:""]}),k.changes.length>0&&He("button",{type:"button",style:Xr(!1),onClick:()=>z(L.size===k.changes.length?new Set:new Set(k.changes.map((Q)=>Q.key))),children:L.size===k.changes.length?i("Select none"):i("Select all")})]}),G&&He("p",{style:{margin:0,fontSize:12,color:Pt.faint,whiteSpace:"pre-wrap"},children:G}),k.changes.length===0&&He("p",{style:{margin:0},children:i("No changes were suggested.")}),[...In.entries()].map(([Q,ge])=>{let Pe=K.find((we)=>we.id===Q);return Ct("div",{style:At.group,children:[He("div",{style:At.groupHead,children:Pe?jt(Pe,t.fields):Q}),ge.map((we)=>{let Je=ke(we.fieldId);if(!Je)return null;let on=sn(we.before,Je);return Ct("label",{style:At.change,children:[He("input",{type:"checkbox",checked:L.has(we.key),"aria-label":`${Je.name} ${Q}`,onChange:()=>z(new Set(An([...L],we.key)))}),Ct("span",{style:{display:"grid",gap:2},children:[He("span",{style:{fontSize:12,color:Pt.faint},children:Je.name}),on&&He("span",{style:At.before,children:on}),He("span",{style:At.after,children:sn(we.after,Je)||i("(empty)")}),we.reason&&He("span",{title:we.reason,style:At.reason,children:we.reason})]})]},we.key)})]},Q)})]})]}),He("div",{style:At.foot,children:E==="running"?Ct(Od,{children:[He("span",{role:"status",style:{flex:1,color:Pt.faint},children:B&&B.total>1?i("Generating batch {done} of {total}…",{done:Math.min(B.done+1,B.total),total:B.total}):i("Generating suggestions…")}),He(Y,{ui:e.ui,variant:"outline",size:"sm",onClick:te,children:i("Stop")})]}):E==="review"&&k&&k.changes.length>0?Ct(Od,{children:[He(Y,{ui:e.ui,variant:"default",size:"sm",disabled:N||L.size===0,onClick:()=>void Te(),children:i("Apply {count} changes",{count:L.size})}),He(Y,{ui:e.ui,variant:"outline",size:"sm",disabled:!ye,onClick:()=>void j(),children:i("Regenerate")})]}):He(Y,{ui:e.ui,variant:"default",size:"sm",disabled:!ye,onClick:()=>void j(),children:i("Generate preview")})})]})}import{useEffect as Bd,useLayoutEffect as Yp,useRef as Jp,useState as Zp}from"react";import{jsx as Qp,jsxs as Xp}from"react/jsx-runtime";var Il=380;function Vd(e){let t=Jp(null),[n,o]=Zp(null),{container:r,anchorFieldId:i,dirty:l,onCancel:s}=e;return Yp(()=>{let a=()=>{let d=r.current,u=i?`[data-uibot-field="${CSS.escape(i)}"]`:"[data-uibot-add-field]",f=d?.querySelector(u)?.getBoundingClientRect(),p=d?.getBoundingClientRect(),c=document.documentElement.clientWidth||window.innerWidth,C=f?f.bottom+4:(p?.top??0)+48,x=f?f.left:(p?.right??c)-Il-16;o({top:Math.max(8,C),left:Math.max(8,Math.min(x,c-Il-8))})};return a(),window.addEventListener("resize",a),window.addEventListener("scroll",a,!0),()=>{window.removeEventListener("resize",a),window.removeEventListener("scroll",a,!0)}},[r,i]),Bd(()=>{let a=requestAnimationFrame(()=>t.current?.querySelector("input:not([disabled])")?.select());return()=>cancelAnimationFrame(a)},[]),Bd(()=>{let a=(d)=>{let u=d.target;if(!u||t.current?.contains(u))return;if(u instanceof Element&&u.closest("[role=listbox],[role=menu],[data-radix-popper-content-wrapper]"))return;if(!l)s()};return document.addEventListener("pointerdown",a,!0),()=>document.removeEventListener("pointerdown",a,!0)},[l,s]),Xp("div",{ref:t,role:"dialog","aria-label":e.title,"data-uibot-field-editor":"",onKeyDown:(a)=>{if(a.key==="Escape"&&!a.nativeEvent.isComposing)a.stopPropagation(),s()},style:{position:"fixed",top:n?.top??0,left:n?.left??0,visibility:n?"visible":"hidden",width:Il,maxWidth:"calc(100vw - 16px)",maxHeight:`calc(100vh - ${(n?.top??0)+16}px)`,overflowY:"auto",zIndex:50,boxSizing:"border-box",padding:16,display:"grid",gap:12,border:"1px solid var(--uibot-border, var(--border, #d4d4d8))",borderRadius:10,background:"var(--uibot-surface, var(--background, #fff))",color:"var(--uibot-text, inherit)",boxShadow:"0 12px 32px rgb(0 0 0 / 0.14)",fontSize:"var(--uibot-workspace-font-size, 13px)"},children:[Qp("strong",{style:{fontSize:14},children:e.title}),e.children]})}import{jsx as H,jsxs as Oe,Fragment as ti}from"react/jsx-runtime";var Ud={grid:"New grid view",kanban:"New kanban view",gallery:"New gallery view",calendar:"New calendar view",form:"New form view"},eg=(e,t)=>{let n=rs(e,t);return n?.length?{sort:n}:{}},wr=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ei(e,t){let[n,o]=Me({loading:!0}),[r,i]=Me(0);return Et(()=>{let s=e();if(!s){o({loading:!1,scope:t,tick:r});return}let a=!0;return o((d)=>({...d.scope?.length===t.length&&d.scope.every((u,f)=>Object.is(u,t[f]))?d:{},loading:!0,scope:t,tick:r})),s.then((d)=>{if(!a)return;o(d.ok?{data:d.data,loading:!1,scope:t,tick:r}:{error:d.error.message,errorCode:d.error.code,loading:!1,scope:t,tick:r})}).catch((d)=>{if(a)o({error:d instanceof Error?d.message:String(d),loading:!1,scope:t,tick:r})}),()=>{a=!1}},[...t,r]),{...n.tick===r&&n.scope?.length===t.length&&n.scope.every((s,a)=>Object.is(s,t[a]))?n:{loading:!0,data:void 0,error:void 0,errorCode:void 0},reload:()=>i((s)=>s+1)}}function ow(e){let{client:t,requestApproval:n}=e,o=Ht(()=>{}),r=no(()=>{let m=yd(t,n);return fl(m,async(V,J)=>{let ne=await m.mutate(V,J);if(ne.ok&&!ne.data.replayed&&J.items.some((le)=>le.op==="insert")){let le=new Set(J.items.flatMap((We)=>We.op==="insert"?[]:[We.id])),je=ne.data.items.filter((We)=>!le.has(We.id));if(je.length)o.current(V,je)}return ne})},[t,n]),i=no(()=>{if(e.aggregateClient)return e.aggregateClient;let m=t.aggregate;if(!m)return;return{async aggregate(V,J){let ne=await m.call(t,V,{...J.filter?{filter:J.filter}:{},...J.search!==void 0?{search:J.search}:{},groupBy:J.groupBy,aggregates:J.aggregates.map((le)=>({fn:le.fn,...le.fieldId?{field:le.fieldId}:{},as:le.as}))});return ne.ok?{ok:!0,data:$l(J,ne.data)}:ne}}},[e.aggregateClient,t]),l=Ht([]),s=no(()=>e.getRelationOptions??Ri(r,()=>l.current),[e.getRelationOptions,r]),a=oe(e.locale),d=no(()=>wt({preset:"full",...e.features}),[e.features]),u=e.pageSize??50,f=ei(()=>r.list(),[r]);l.current=f.data??[];let[p,c]=Me(e.tableId),C=e.tableId??p??f.data?.[0]?.id,x=Ht(e);x.current=e;let h=Ht(null),g=Al((m)=>{if(x.current.onBeforeNavigate?.(m)!==!1)return!0;let V=h.current;return requestAnimationFrame(()=>V?.isConnected&&V.focus({preventScroll:!0})),!1},[]),w=e.onTableChange,y=Al((m)=>{if(!g({tableId:m}))return!1;return c(m),w?.(m),!0},[w,g]),E=ei(()=>e.capabilities||!r.capabilities?void 0:r.capabilities(C),[r,C,e.capabilities]),S=e.capabilities??E.data??{read:!r.capabilities,write:!r.capabilities,schema:!r.capabilities},k=S.schema&&d.schemaEditor,O=S.write&&d.rowCreate,L=S.write&&d.rowUpdate,z=S.write&&d.rowDelete,G=(S.views??S.schema)&&d.viewManagement,P=k&&(e.allowCreateTable??!0),R=Ht({schema:k,views:G,createTable:P});R.current={schema:k,views:G,createTable:P};let M=Boolean(C&&f.data?.some((m)=>m.id===C)),N=ei(()=>C&&M?r.describe(C):void 0,[r,C,M]),I=!N.loading&&N.data?.id===C?N.data:void 0,B=ei(()=>C&&I?r.views(C):void 0,[r,C,Boolean(I)]),[v,K]=Me([]),[ce,fe]=Me(""),_=e.viewId??ce,ie=Ht({client:t,tableId:C,id:_});if(ie.current.client!==t||ie.current.tableId!==C||ie.current.id!==_)ie.current={client:t,tableId:C,id:_};let[ue,W]=Me(),q=ue?.client===t&&ue.tableId===C,xe=q&&ue.snapshot===B.data,[ke,ye]=Me({});Et(()=>{if(!B.data||B.loading)return;W({client:t,tableId:C,snapshot:B.data}),K(B.data),ye({}),fe((m)=>{let V=B.data??[];if(q&&V.some((J)=>J.id===m))return m;return V.find((J)=>J.id===e.initialViewId)?.id??V[0]?.id??""})},[B.data,B.loading,e.initialViewId,t,C]);let re=Ht({client:t,ids:new Map});if(re.current.client!==t)re.current={client:t,ids:new Map};let Ce=re.current.ids;Et(()=>{if(C&&B.data?.length)Ce.delete(C)},[Ce,C,B.data]);let he=B.data?.length===0?I?.id:void 0,Ye=oe(e.locale)("All records"),j=no(()=>{if(!he)return;let m=Ce.get(he);if(!m)m=e.createViewId?.(he)??`default-${he}`,Ce.set(he,m);return{id:m,name:Ye,version:0,type:"grid",columnOrder:[],hiddenColumns:[],columnWidths:{}}},[Ce,he,Ye,e.createViewId]);Et(()=>{if(!j||!B.data||B.data.length>0)return;if(B.loading||N.data?.id!==C)return;ye((m)=>m[j.id]?m:{...m,[j.id]:j}),fe(j.id)},[j,B.data,B.loading,N.data?.id,C]);let D=e.inlineViewControls===!0,te=v.find((m)=>m.id===_),T=xe&&I&&!B.loading&&!B.error?ke[_]??te:void 0,Te=Ht(void 0);Et(()=>{if(!T)return;let m=Te.current;if(m?.client===t&&m.tableId===C)return;Te.current={client:t,tableId:C},x.current.onViewChange?.(T,"initialize")},[t,C,T]);let[ot,In]=Me({recordIds:[],fieldIds:[]}),[An,Q]=Me(!1),[ge,Pe]=Me(!1),[we,Je]=Me(null);Et(()=>{if(!we||!T||C!==we.tableId)return;if(N.data?.id!==we.tableId||B.loading||v!==B.data)return;ye((m)=>({...m,[T.id]:{...T,filter:we.filter}})),Je(null)},[we,T,C,N.data?.id,B.loading,B.data,v]),Et(()=>{In({recordIds:[],fieldIds:[]}),Q(!1)},[C]);let on=no(()=>{if(!I)return[];let m=f.data??[],V=I.fields.flatMap((ne)=>{let le=ne.relation&&m.find((je)=>je.id===ne.relation?.collectionId);return le?[{key:`to:${ne.id}`,label:a("Open {name}",{name:le.name}),needsRecord:!1,open:()=>y(le.id)}]:[]}),J=m.flatMap((ne)=>ne.id===I.id?[]:ne.fields.filter((le)=>le.relation?.collectionId===I.id).map((le)=>({key:`from:${ne.id}:${le.id}`,label:a("{name} · inverse records",{name:ne.name}),needsRecord:!0,open:()=>{let je=ot.recordIds[0];if(!je)return;if(!y(ne.id))return;Je({tableId:ne.id,filter:{conjunction:"and",filterSet:[{fieldId:le.id,operator:"is",value:je}]}})}})));return[...V,...J]},[I,f.data,ot.recordIds,a,y]),En=Boolean(T&&j&&T.id===j.id&&wr(T,j)),Mt=Boolean(T&&!En&&(!te||!wr(te,T))),Dt=[...v,...Object.values(ke).filter((m)=>!v.some((V)=>V.id===m.id)&&!(m.id===j?.id&&v.length>0))],[Ze,gn]=Me(null),[Le,ft]=Me(!1),Tt=(m,V=!1)=>{if(m&&!V&&e.onNotify){e.onNotify(m),gn(null);return}gn(m?{text:m,error:V}:null)},kr=Ht(!1),Ot=Ht(0),Lt=Ht(C);Lt.current=C,Et(()=>{Ot.current+=1},[t]);async function rn(m,V){if(kr.current)return;kr.current=!0;let J={client:Ot.current,table:Lt.current};ft(!0),Tt("");try{let ne=await m();if(J.client!==Ot.current)return;if(ne.ok)V(ne.data,J.table===Lt.current);else Tt(ne.error.message,!0)}catch(ne){if(J.client!==Ot.current)return;Tt(ne instanceof Error?ne.message:a("Saving failed. Your edit has been kept."),!0)}finally{kr.current=!1,ft(!1)}}let mn=Ht(new Set),Ke=(m)=>JSON.stringify([C,m]);if(!G){for(let m of Object.keys(ke))mn.current.add(Ke(m));if(T)mn.current.add(Ke(T.id))}let st=(m,V=!0)=>{if(V&&R.current.views)mn.current.delete(Ke(m.id));ye((J)=>({...J,[m.id]:m})),gn((J)=>J?.error?null:J)},De=(m)=>{if(m===_)return;let V=ke[m]??v.find((J)=>J.id===m);if(!V||!C||!g({tableId:C,viewId:m}))return;if(e.viewId===void 0)fe(m);x.current.onViewChange?.(V,"select")},oo=(m)=>{if(!R.current.views||!C||!g({tableId:C,viewId:m.id}))return;if(mn.current.delete(Ke(m.id)),ye((V)=>({...V,[m.id]:m})),e.viewId===void 0)fe(m.id);x.current.onViewChange?.(m,"create")},Bt=(m,V)=>{if(!R.current.views||!C)return;let J=v.find((le)=>le.id===m.id),ne=ie.current;if(m.id!==ne.id&&!g({tableId:C,viewId:m.id}))return;rn(async()=>{let le={expectedVersion:J?.version??0,view:m};return r.saveView(C,{...le,idempotencyKey:Io(`view:${m.id}`,le)})},(le,je)=>{if(Ao(`view:${m.id}`),!je)return;if(K((We)=>We.some((an)=>an.id===le.id)?We.map((an)=>an.id===le.id?le:an):[...We,le]),ye((We)=>{let{[le.id]:an,...St}=We;return St}),ie.current===ne){if(x.current.viewId===void 0)fe(le.id);x.current.onViewChange?.(le,"save")}if(!D)Tt(a("View saved"));V?.(le)})},Po=D&&Mt&&G&&!mn.current.has(Ke(T?.id??""))&&!Le&&!Ze?.error&&!!T?.name.trim();Et(()=>{if(!Po||!T)return;let m=setTimeout(()=>{if(!mn.current.has(Ke(T.id)))Bt(T)},600);return()=>clearTimeout(m)},[Po,T]);let[Hn,So]=Me(""),vt=()=>{if(!R.current.views)return;let m=Dt.find((We)=>We.id===Hn),V=r.deleteView;if(!m||!C)return;let ne=Dt.filter((We)=>We.id!==m.id)[0],le=ie.current;if(_===m.id&&(!ne||!g({tableId:C,viewId:ne.id})))return;So("");let je=()=>{if(K((We)=>We.filter((an)=>an.id!==m.id)),ye((We)=>{let{[m.id]:an,...St}=We;return St}),le===ie.current&&_===m.id&&ne){if(x.current.viewId===void 0)fe(ne.id);x.current.onViewChange?.(ne,"delete")}};if(!v.some((We)=>We.id===m.id))return je();if(!V)return;rn(()=>V.call(r,C,{viewId:m.id,expectedVersion:m.version,idempotencyKey:Io(`delete:${m.id}`,m)}),(We,an)=>{if(Ao(`delete:${m.id}`),!an)return;Tt(a("View deleted")),je()})},[jn,ro]=Me(0),[Yo,ni]=Me(null),io=D&&Yo&&Yo.viewId===T?.id?Yo.text:T?.search??"",Pr=(m)=>{if(D&&T)ni({viewId:T.id,text:m});else if(T)st({...T,search:m})},Sr=no(()=>({limit:u,search:io,...T?.filter?{filter:T.filter}:{},...eg(T,I?.fields)}),[T,io,I?.fields,u]),Wt=JSON.stringify(Sr),Gt=JSON.stringify([C,_,Wt]),[Vt,fn]=Me({client:r,scope:Gt,cursor:void 0,history:[]}),Dn=Vt.client===r&&Vt.scope===Gt,Tn=Dn?Vt.cursor:void 0,ao=Dn?Vt.history:[];Et(()=>{fn({client:r,scope:Gt,cursor:void 0,history:[]})},[r,Gt]);let Jo=(m)=>fn((V)=>({client:r,scope:Gt,cursor:m,history:V.client===r&&V.scope===Gt?V.history:[]})),Rr=(m)=>fn((V)=>({client:r,scope:Gt,history:m,cursor:V.client===r&&V.scope===Gt?V.cursor:void 0})),Ut=(T?.type??"grid")==="grid",yt=ei(()=>C&&I&&T&&Ut?r.query(C,{...Sr,...Tn?{cursor:Tn}:{}}):void 0,[r,C,I?.schemaVersion,Boolean(T),Wt,Tn,Ut,jn]),yn=()=>{if(C&&!g({tableId:C,...T?{viewId:T.id}:{}}))return;N.reload(),B.reload(),ro((m)=>m+1)},_t=Al(()=>ro((m)=>m+1),[]);o.current=(m,V)=>{let J=e.aiFillClient;if(!J||e.schemaSettings?.ai===!1||m!==I?.id)return;let ne=I.fields;if(!Rl(ne,V).length)return;let le=Ot.current;Fd({tableId:m,fields:ne,records:V,fill:(je)=>J.fill(je),mutate:(je)=>r.mutate(m,{idempotencyKey:crypto.randomUUID(),items:je})}).then((je)=>{if(le!==Ot.current)return;if(je.filled)_t();if(je.error&&Lt.current===m)Tt(a("AI auto-fill stopped: {message}",{message:je.error}),!0)})};let[Qe,Yt]=Me("");Et(()=>{Yt(""),Pe(!1)},[t,C,_]);let $n={...e.schemaSettings,ai:Boolean(e.aiFillClient)&&e.schemaSettings?.ai!==!1},[Ir,Jt]=Me(!1),[Ro,Zo]=Me(""),[bn,oi]=Me(""),[Fn,Qo]=Me(""),Ar=Ht({}),Io=(m,V)=>{let J=JSON.stringify(V),ne=Ar.current[m];if(ne?.fingerprint===J)return ne.key;let le=crypto.randomUUID();return Ar.current[m]={fingerprint:J,key:le},le},Ao=(m)=>{delete Ar.current[m]},[hn,Xo]=Me(""),[Nn,Er]=Me([]),er=no(()=>[{fn:"count",as:"records"},...Fn?[{fn:"sum",fieldId:Fn,as:"sum"}]:[]],[Fn]),Dr=no(()=>{let m=oe(e.locale),V=I?.fields.find((J)=>J.id===Fn);return{records:m("Records"),...V?{sum:m("Sum of {name}",{name:V.name})}:{}}},[e.locale,I,Fn]);Et(()=>Qo(""),[C]);let[Eo,b]=Me([]),[A,F]=Me(""),[ae,X]=Me(),U=(m)=>{X(m),b(structuredClone(I?.fields??[])),F(I?.name??""),lo("schema")},ee=Qe==="schema"&&(!wr(Eo,I?.fields)||A!==(I?.name??"")),Ie=Qe==="create"&&(hn.trim()!==""||!wr(Nn,[{id:"name",name:a("Name"),type:"singleLineText",required:!0}])),[me,Ae]=Me(!1),[be,Ve]=Me(!1),Tr=Ht(null),ea=Ht(null),lo=(m)=>{if(document.activeElement instanceof HTMLElement)ea.current=document.activeElement;Yt(m)},Mn=()=>{Pe(!1),Yt("");let m=ea.current;if(ea.current=null,m)requestAnimationFrame(()=>m.isConnected&&m.focus())};Et(()=>{if(!Qe)return;let m=document.activeElement,V=requestAnimationFrame(()=>{if(document.activeElement!==m)return;Tr.current?.querySelector("[data-uibot-panel] input:not([disabled]), [data-uibot-panel] textarea:not([disabled])")?.focus()});return()=>cancelAnimationFrame(V)},[Qe]),Et(()=>{if(Qe!=="add"&&Qe!=="record")Ae(!1),Ve(!1)},[Qe]);let so=()=>{if(ee||Ie||(Qe==="add"||Qe==="record")&&me)Pe(!0);else Mn()},ri=(m)=>(V)=>{if(V.nativeEvent.isComposing)return;if(V.key==="Escape"){if(V.stopPropagation(),!Le&&!be)so()}else if(m&&V.key==="Enter"&&(V.ctrlKey||V.metaKey)&&!Le)V.preventDefault(),m()},ta=_l(),zd=(Qe==="add"||Qe==="record")&&me,qd=(Qe==="add"||Qe==="record")&&be,Hd=Mt||ee||Ie||ta.dirty||zd,jd=Le||ta.busy||qd;On({dirty:Hd,busy:jd},e);let El=()=>{if(!R.current.createTable||!hn.trim()||Nn.length===0)return;rn(()=>{let m={name:hn.trim(),fields:Nn};return r.create({...m,idempotencyKey:Io("create",m)})},(m,V)=>{if(Ao("create"),f.reload(),!V)return;Mn(),y(m.id)})},Dl=()=>{if(!R.current.schema)return;tr({fields:Eo,name:A.trim()}).then(()=>{Mn(),Tt(a("Fields saved"))}).catch((m)=>Tt(m instanceof Error?m.message:String(m),!0))},tr=(m)=>new Promise((V,J)=>{if(!R.current.schema)return J(Error(a("Read only")));if(!C||!I)return J(Error(a("Choose a table first.")));ft(!0);let ne={client:Ot.current,table:Lt.current};r.updateSchema(C,{expectedSchemaVersion:I.schemaVersion,name:m.name??I.name,fields:m.fields??I.fields,...m.icon??I.icon?{icon:m.icon??I.icon}:{},idempotencyKey:Io("schema",{version:I.schemaVersion,name:m.name??I.name,fields:m.fields??I.fields,icon:m.icon??I.icon})}).then((le)=>{if(ne.client!==Ot.current||ne.table!==Lt.current)return V();if(!le.ok)return J(Error(le.error.message));Ao("schema"),B.reload(),N.reload(),f.reload(),Jo(void 0),Rr([]),V()}).catch(J).finally(()=>ft(!1))}),[na,oa]=Me(""),[co,ra]=Me("");Et(()=>ra(""),[C,T?.id]);let Tl=()=>{let m=I?.fields??[],V=(T?.columnOrder??[]).filter((J)=>m.some((ne)=>ne.id===J));return[...V,...m.map((J)=>J.id).filter((J)=>!V.includes(J))]},[rt,Do]=Me(null),[Fl,ii]=Me(""),[ai,Nl]=Me(null);Et(()=>{if(!ai||!T||B.loading)return;if(!I?.fields.some((m)=>m.id===ai.fieldId))return;Nl(null),st({...T,columnOrder:ai.order},!1)},[ai,I,T,B.loading]),Et(()=>Do(null),[C]);let Ml=(m)=>{let V=I?.fields.find((J)=>J.id===m);if(!V)return;ii(""),Do({draft:structuredClone(V),initial:V,isNew:!1})},li=(m)=>{let V={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:a("New field"),type:"singleLineText"};ii(""),Do({draft:V,initial:V,isNew:!0,...m?{insert:m}:{}})},Ol=()=>{if(!rt||!I||!T)return;let m={...rt.draft,name:rt.draft.name.trim()};if(!m.name)return ii(a("Field name is required."));let V=I.fields.map((le)=>le.id===m.id?m:le),J;if(rt.isNew){if(V=[...I.fields,m],rt.insert){let{beside:le,side:je}=rt.insert;V=[...I.fields],V.splice(I.fields.findIndex((We)=>We.id===le)+(je==="right"?1:0),0,m),J=Tl(),J.splice(Math.max(0,J.indexOf(le)+(je==="right"?1:0)),0,m.id)}}let ne=rt.isNew;if(J&&R.current.schema&&R.current.views)mn.current.delete(Ke(T.id));tr({fields:V}).then(()=>{if(J)Nl({fieldId:m.id,order:J});Do(null),Tt(a(ne?"Field added":"Field saved"))}).catch((le)=>ii(le instanceof Error?le.message:String(le)))},$d=(m)=>{if(!I)return;let V={...structuredClone(m),id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:a("{name} copy",{name:m.name})};delete V.required;let J=[...I.fields];J.splice(I.fields.findIndex((ne)=>ne.id===m.id)+1,0,V),tr({fields:J}).then(()=>Tt(a("Field duplicated"))).catch((ne)=>Tt(ne instanceof Error?ne.message:String(ne),!0))},Kd=()=>{if(!R.current.schema)return;let m=na;if(oa(""),!I||!m)return;tr({fields:I.fields.filter((V)=>V.id!==m)}).then(()=>Tt(a("Field deleted"))).catch((V)=>Tt(V instanceof Error?V.message:String(V),!0))},Wd=(m)=>{if(!I||!T)return[];let V=I.fields[0]?.id===m.id,J=ln(m)&&m.type!=="linkedRecord",ne=m.type==="singleSelect"||m.type==="checkbox",le=(T.type??"grid")==="grid"&&d.groupBy&&ne,je=T.groupByFieldId===m.id,We=G&&d.viewTypes.includes("kanban")&&ne,an=!["relation","lookup","rollup"].includes(m.type),St=[];if(k){if((e.schemaFieldTypes??nl).includes(m.type))St.push({id:"edit",icon:H(ve,{name:"pencil"}),label:a("Edit field"),onSelect:()=>Ml(m.id)});if(an)St.push({id:"duplicate",icon:H(ve,{name:"copy"}),label:a("Duplicate field"),onSelect:()=>$d(m)})}if(d.columns)St.push({id:"hide",icon:H(ve,{name:"eyeOff"}),label:a("Hide field"),disabled:V||T.type==="form"&&m.required===!0,onSelect:()=>st({...T,hiddenColumns:[...T.hiddenColumns,m.id]})});if(G&&d.columnColors&&(T.type??"grid")==="grid")St.push({id:"column-color",icon:H(ve,{name:"palette"}),label:a("Column color"),separatorBefore:!0,onSelect:()=>ra(m.id)});let di=Tl().filter((xt)=>!T.hiddenColumns.includes(xt)).indexOf(m.id)+1,Vl=d.columnFreezing&&(T.type??"grid")==="grid"&&di>0&&di<=4;if(Vl){let xt=T.frozenColumnCount===di;St.push({id:"freeze",icon:H(ve,{name:"freeze"}),label:a(xt?"Unfreeze columns":"Freeze up to this field"),separatorBefore:!0,onSelect:()=>{let Kn={...T};if(xt)delete Kn.frozenColumnCount;else Kn.frozenColumnCount=di;st(Kn)}})}if(k)St.push({id:"insert-left",icon:H(ve,{name:"arrowLeft"}),label:a("Insert field left"),separatorBefore:!Vl,onSelect:()=>li({beside:m.id,side:"left"})},{id:"insert-right",icon:H(ve,{name:"arrowRight"}),label:a("Insert field right"),onSelect:()=>li({beside:m.id,side:"right"})});if(J&&d.sorting){let xt=T.sort?.length===1?T.sort[0]:void 0,Kn=xt?.fieldId===m.id?xt.direction:void 0;St.push({id:"sort-asc",icon:H(ve,{name:"sortAsc"}),label:a("Sort {name} ascending",{name:m.name}),separatorBefore:!0,disabled:Kn==="asc",onSelect:()=>st({...T,sort:[{fieldId:m.id,direction:"asc"}]})},{id:"sort-desc",icon:H(ve,{name:"sortDesc"}),label:a("Sort {name} descending",{name:m.name}),disabled:Kn==="desc",onSelect:()=>st({...T,sort:[{fieldId:m.id,direction:"desc"}]})})}if(d.filter&&ln(m)&&m.type!=="linkedRecord")St.push({id:"filter",icon:H(ve,{name:"filter"}),label:a("Filter by {name}",{name:m.name}),separatorBefore:!le&&!We&&!(J&&d.sorting),onSelect:()=>{let xt=T.filter,Kn={fieldId:m.id,operator:"isNotEmpty"};st({...T,filter:xt?{...xt,filterSet:[...xt.filterSet,Kn]}:{conjunction:"and",filterSet:[Kn]}})}});if(le)St.push({id:"group",icon:H(ve,{name:"group"}),label:a(je?"Ungroup by {name}":"Group by {name}",{name:m.name}),separatorBefore:!0,onSelect:()=>{let xt={...T};if(je)delete xt.groupByFieldId;else xt.groupByFieldId=m.id;st(xt)}});if(We)St.push({id:"kanban",icon:H(ve,{name:"kanban"}),label:a("Create kanban by {name}",{name:m.name}),separatorBefore:!le,onSelect:()=>{let xt={...T,id:e.createViewId?.(I.id)??crypto.randomUUID(),name:a(Ud.kanban),version:0,type:"kanban",columnOrder:T.columnOrder,hiddenColumns:[],groupByFieldId:m.id};delete xt.dateFieldId,oo(xt)}});if(m.ai&&e.aiFillClient&&L)St.push({id:"ai-generate",icon:H(ve,{name:"sparkles"}),label:a("Generate {name} with AI",{name:m.name}),separatorBefore:!0,onSelect:()=>{Zo(m.id),Jt(!0)}});if(k&&!e.addOnlySchema&&!V)St.push({id:"delete",icon:H(ve,{name:"trash"}),label:a("Delete field"),destructive:!0,separatorBefore:!0,onSelect:()=>oa(m.id)});return St};if(f.error){let m={code:f.errorCode,message:f.error};return Oe("div",{"data-uibot-workspace":"","data-uibot":"collection-workspace",style:de.main,children:[e.renderListError?e.renderListError(m,f.reload):H("p",{role:"alert",children:po(m,e.locale)}),Oe("div",{style:de.actions,children:[H(Y,{ui:e.ui,style:de.button,onClick:f.reload,children:a("Reload records")}),e.toolbarActions]})]})}let Gd=T&&I&&Qe==="settings"&&Oe("fieldset",{disabled:Le,style:de.fieldset,"data-uibot-panel":"settings",onKeyDown:ri(),children:[Oe("label",{children:[a("View name")," ",H("input",{"aria-label":a("View name"),value:T.name,onChange:(m)=>st({...T,name:m.currentTarget.value})})]}),H(ml,{fields:I.fields,view:T,onChange:st,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},features:e.features??{preset:"full"},sections:e.inlineViewControls?{}:{filter:d.filter,columns:d.columns,sort:d.sorting},grouping:!e.inlineViewControls,filterEditor:{advanced:e.advancedFilters!==!1,...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},getRelationOptions:s}}),Oe("div",{style:de.actions,children:[H(Y,{ui:e.ui,style:de.button,variant:"default",disabled:!Mt||!T.name.trim()||!G,onClick:()=>Bt(T),children:a("Save view")}),H(Y,{ui:e.ui,style:de.button,onClick:Mn,children:a("Done")})]})]}),Yd=I&&Qe==="schema"&&Oe("fieldset",{disabled:Le,style:de.fieldset,"data-uibot-panel":"schema",onKeyDown:ri(Dl),children:[Oe("label",{children:[a("Table title")," ",H("input",{"aria-label":a("Table title"),value:A,disabled:!k,onChange:(m)=>F(m.currentTarget.value)})]}),H(Yr,{fields:Eo,...ae?{focusFieldId:ae}:{},onChange:b,disabled:Le||!k,...e.schemaFieldTypes?{fieldTypes:e.schemaFieldTypes}:{},settings:$n,relationTargets:f.data??[],lockedFieldIds:e.addOnlySchema?(I?.fields??[]).map((m)=>m.id):[],...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}),Oe("div",{style:e.renderPanel?de.stickyFooter:de.actions,children:[H(Y,{ui:e.ui,style:de.button,variant:"default",disabled:!k||!ee||Eo.length===0||!A.trim(),onClick:Dl,children:a("Save fields")}),e.renderPanel?null:H(Y,{ui:e.ui,style:de.button,onClick:so,children:a("Cancel field settings")})]})]}),si=(m,V,J)=>J?e.renderPanel?e.renderPanel({kind:m,title:V,content:J,dirty:m==="schema"?ee:m==="add"||m==="record"?me:!1,busy:Le||(m==="add"||m==="record")&&be,onClose:Mn}):J:null,ia=yt.data?.items.find((m)=>m.id===bn),aa=I&&T?{descriptor:I,rows:yt.data?.items??[],total:yt.data?.total??0,reloadKey:jn,serverFooterStats:e.serverFooterStats??!0,...i?{aggregate:{client:i,aggregates:er}}:{},view:T,onViewChange:st,onSelectionChange:In,onMutate:(m)=>r.mutate(I.id,m),relationClient:r,...e.renderRecordContextMenu?{renderRecordContextMenu:e.renderRecordContextMenu}:{},onCommitted:_t,readOnly:Le||!S.write,features:d,display:{keyboardHints:!1,fill:!0,...d.footerStats?{summary:!1}:{}},...e.inlineViewControls||d.columnFreezing?{fieldMenu:Wd}:{},...e.inlineViewControls&&O?{onAddRecord:()=>lo("add")}:{},...e.inlineViewControls&&k?{onAddField:()=>li()}:{},onExpandRecord:(m)=>{oi(m.id),lo("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,To=I&&T?{descriptor:I,view:T,client:r,onCommitted:_t,reloadKey:jn,getRelationOptions:s,readOnly:!S.write,features:d,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},...i?{aggregate:{client:i,aggregates:er,labels:Dr}}:{}}:void 0,Ll=H(ti,{children:e.toolbarActions}),Jd=!f.loading&&(f.data?.length??0)===0,Bl=(e.showTableList??d.tableList)!==!1,Zd=Oe("div",{ref:Tr,onFocusCapture:(m)=>{if(m.target instanceof HTMLElement&&m.target.matches("input, textarea, select, [contenteditable=true]"))h.current=m.target},"data-uibot-workspace":"","data-uibot":"collection-workspace",style:{...de.root,gridTemplateColumns:[Bl?"auto":"","minmax(0, 1fr)",e.sidePanel||e.renderSidePanel?"auto":""].filter(Boolean).join(" ")},children:[Bl&&H(Wa,{tables:f.data??[],activeId:C,onSelect:y,...P?{onCreate:()=>{Xo(""),Er([{id:"name",name:a("Name"),type:"singleLineText",required:!0}]),lo("create")}}:{},createDisabled:Le,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}),Oe("main",{style:de.main,children:[co&&T&&I?.fields.some((m)=>m.id===co)&&G&&H("div",{style:{justifySelf:"start",alignSelf:"start"},children:H(zn,{ui:e.ui,defaultOpen:!0,icon:"palette",label:a("Column color for {name}",{name:I.fields.find((m)=>m.id===co)?.name??""}),children:(m)=>H("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[null,...Ln].map((V,J)=>H("button",{type:"button","aria-label":V?a("Column color {number}",{number:J}):a("No color"),title:V?a("Column color {number}",{number:J}):a("No color"),"aria-pressed":V?T.columnColors?.[co]===V:!T.columnColors?.[co],style:{...de.button,...V?Pn(J-1):{},width:V?28:void 0,height:28,padding:V?0:"0 8px"},onClick:()=>{let ne={...T.columnColors};if(V)ne[co]=V;else delete ne[co];let{columnColors:le,...je}=T;st(Object.keys(ne).length?{...je,columnColors:ne}:je),m(),ra("")},children:V?"":a("No color")},V??"clear"))})},co)}),Jd||e.hideHeader?H("div",{style:de.actions,children:Ll}):H(Ga,{table:I,canManage:k,canWrite:O||L||z,onRename:(m)=>tr({name:m}),onIconChange:(m)=>tr({icon:m}),...e.locale?{locale:e.locale}:{},actions:Ll}),E.error!==void 0?Oe("div",{role:"alert",style:de.actions,children:[po({code:E.errorCode,message:E.error},e.locale),H(Y,{ui:e.ui,style:de.button,disabled:E.loading,onClick:E.reload,children:a("Reload permissions")})]}):null,ge&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:!0,title:a("Discard unsaved changes?"),confirmLabel:a("Discard"),cancelLabel:a("Keep editing"),onConfirm:Mn,onCancel:()=>Pe(!1)}):null,ge&&!e.ui?.ConfirmDialog&&Oe("div",{role:"alertdialog","aria-label":a("Discard unsaved changes?"),style:de.confirm,children:[a("Discard unsaved changes?"),H(Y,{ui:e.ui,style:de.button,onClick:Mn,children:a("Discard")}),H(Y,{ui:e.ui,style:de.button,onClick:()=>Pe(!1),children:a("Keep editing")})]}),Qe==="create"?Oe("fieldset",{disabled:Le,style:de.fieldset,"data-uibot-panel":"create",onKeyDown:ri(El),children:[Oe("label",{children:[a("Table name")," ",H("input",{"aria-label":a("Table name"),value:hn,disabled:!P,onChange:(m)=>Xo(m.currentTarget.value)})]}),H(Yr,{fields:Nn,onChange:Er,disabled:Le||!P,...e.schemaFieldTypes?{fieldTypes:e.schemaFieldTypes}:{},settings:$n,relationTargets:f.data??[],...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}),Ze?.error?H("p",{role:"alert",style:de.error,children:Ze.text}):null,Oe("div",{style:de.actions,children:[H(Y,{ui:e.ui,style:de.button,variant:"default",disabled:!P||!hn.trim()||Nn.length===0,onClick:El,children:a("Create table")}),H(Y,{ui:e.ui,style:de.button,onClick:so,children:a("Cancel")})]})]}):I&&T?Oe(ti,{children:[Oe("div",{style:e.inlineViewControls?{display:"grid",gridTemplateColumns:"minmax(0, 1fr)",gap:8,minWidth:0}:de.bar,children:[H(sl,{views:Dt,activeId:T.id,dirty:Mt&&!D,disabled:Le,onSelect:De,viewTypes:d.viewTypes,disabledViewTypes:[...I.fields.some((m)=>m.type==="singleSelect"||m.type==="checkbox")?[]:["kanban"],...I.fields.some((m)=>m.type==="date")?[]:["calendar"]],...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},...G?{onAdd:(m)=>{let V={...T,id:e.createViewId?.(I.id)??crypto.randomUUID(),name:a(Ud[m]),version:0,type:m,columnOrder:T.columnOrder,hiddenColumns:[]};delete V.groupByFieldId,delete V.dateFieldId;let J=I.fields.find((le)=>le.type==="singleSelect"||le.type==="checkbox"),ne=I.fields.find((le)=>le.type==="date");if(m==="kanban"&&J)V.groupByFieldId=J.id;if(m==="calendar"&&ne)V.dateFieldId=ne.id;oo(V)},onRename:(m,V)=>{let J=Dt.find((ne)=>ne.id===m);if(J&&V.trim()&&V!==J.name)Bt({...J,name:V.trim()})},onDuplicate:(m)=>{let V=Dt.find((J)=>J.id===m);if(V)Bt({...V,id:e.createViewId?.(I.id)??crypto.randomUUID(),name:a("{name} copy",{name:V.name}),version:0})},...r.deleteView&&Dt.length>1?{onDelete:(m)=>So(m)}:{},...r.reorderViews&&C&&v.length>1?{onReorder:(m)=>{if(!R.current.views)return;let V=m.filter((ne)=>v.some((le)=>le.id===ne)),J=r.reorderViews;if(!J||V.length<2)return;rn(()=>J.call(r,C,{viewIds:V,idempotencyKey:Io("reorder",V)}),(ne,le)=>{if(Ao("reorder"),le)K(ne)})}}:{}}:{}}),e.inlineViewControls?H(rl.Provider,{value:Le||e.viewControlsDisabled===!0,children:Oe("div",{style:{...de.actions,justifyContent:"space-between"},children:[Oe("div",{style:de.actions,children:[O&&H(Y,{ui:e.ui,style:de.button,icon:"plus",ariaLabel:a("Add record"),onClick:()=>Qe==="add"?so():lo("add"),children:a("Add record")}),e.aiFillClient&&L&&H(Y,{ui:e.ui,style:de.button,icon:"sparkles",ariaLabel:a("AI fill"),onClick:()=>{Zo(""),Jt(!Ir)},children:a("AI fill")}),H(_d,{part:"main",fields:I.fields,view:T,onChange:st,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},groupable:d.groupBy,filter:d.filter,sort:d.sorting,filterEditor:{advanced:e.advancedFilters!==!1,...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},getRelationOptions:s}})]}),Oe("div",{style:de.actions,children:[H("span",{role:"status","aria-live":"polite",style:e.onNotify?tg:de.status,children:Le?a("Saving…"):""}),d.search?H("input",{type:"search","aria-label":a("Search records"),placeholder:a("Search"),style:de.search,value:io,onChange:(m)=>Pr(m.currentTarget.value)}):null,d.columns?H(zn,{ui:e.ui,icon:"fields",label:a("Field config"),active:T.hiddenColumns.length>0,children:(m)=>H(Ad,{fields:I.fields,view:T,onChange:st,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},...k?{onEditField:(V)=>{m(),Ml(V)},onAddField:()=>{m(),li()},onEditAllFields:()=>{m(),U()}}:{}})}):null,d.columns?H(_d,{part:"extra",fields:I.fields,view:T,onChange:st,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},groupable:d.groupBy,filter:d.filter,sort:d.sorting,filterEditor:{advanced:e.advancedFilters!==!1,...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},getRelationOptions:s}}):null,H(zn,{ui:e.ui,icon:"sliders",label:a("View config"),children:Oe("div",{"data-uibot-view-config":"",style:{display:"grid",gap:10,minWidth:0},children:[Oe("label",{style:{display:"grid",gap:4},children:[a("View name"),H("input",{"aria-label":a("View name"),value:T.name,style:de.search,onChange:(m)=>st({...T,name:m.currentTarget.value})})]}),H(ml,{fields:I.fields,view:T,onChange:st,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},features:e.features??{preset:"full"},sections:{},grouping:!1,rowHeight:!1})]})}),H(Y,{ui:e.ui,style:de.button,icon:"refresh",iconOnly:!0,variant:"ghost",ariaLabel:a("Refresh"),onClick:yn})]})]})}):Oe("div",{style:de.actions,children:[d.search?H("input",{type:"search","aria-label":a("Search records"),placeholder:a("Search"),style:de.search,value:io,onChange:(m)=>Pr(m.currentTarget.value)}):null,H(Y,{ui:e.ui,style:de.button,icon:"refresh",iconOnly:!0,variant:"ghost",ariaLabel:a("Refresh"),onClick:yn}),(G||d.filter||d.columns)&&H(Y,{ui:e.ui,style:de.button,icon:"sliders",iconOnly:!0,variant:"ghost",ariaLabel:a("View settings"),onClick:()=>Qe==="settings"?Mn():lo("settings")}),G?H(Y,{ui:e.ui,style:de.button,icon:"save",iconOnly:!0,variant:"ghost",badge:Mt,ariaLabel:a("Save view"),disabled:!Mt||!T.name.trim()||Le,onClick:()=>Bt(T)}):null,!e.inlineViewControls&&d.filter&&T.filter?.filterSet.length?H(Y,{ui:e.ui,style:de.button,icon:"filter",ariaLabel:a("Clear current filter"),onClick:()=>{let{filter:m,...V}=T;st(V)},children:a("{count} filters",{count:T.filter.filterSet.length})}):null,k&&H(Y,{ui:e.ui,style:de.button,icon:"fields",iconOnly:!0,variant:"ghost",ariaLabel:a("Configure fields"),onClick:()=>Qe==="schema"?so():U()}),O&&H(Y,{ui:e.ui,style:de.button,icon:"plus",ariaLabel:a("Add record"),onClick:()=>Qe==="add"?so():lo("add"),children:a("Add record")}),e.aiFillClient&&L&&H(Y,{ui:e.ui,style:de.button,icon:"sparkles",ariaLabel:a("AI fill"),onClick:()=>{Zo(""),Jt(!Ir)},children:a("AI fill")}),H("span",{role:"status","aria-live":"polite",style:de.status,children:Le?a("Saving…"):""})]})]}),e.relationNavigation!==!1&&on.length>0?Oe("div",{style:de.actions,children:[H(Y,{ui:e.ui,style:de.button,onClick:()=>Q(!An),children:a("Relations")}),An?on.map((m)=>H(Y,{ui:e.ui,style:de.button,disabled:m.needsRecord&&ot.recordIds.length!==1,onClick:m.open,children:m.label},m.key)):null]}):null,na&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:!0,title:a("Delete field “{name}”?",{name:I.fields.find((m)=>m.id===na)?.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:Le,confirmDisabled:!k,onConfirm:Kd,onCancel:()=>oa("")}):null,Hn&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:!0,title:a("Delete view “{name}”?",{name:Dt.find((m)=>m.id===Hn)?.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:Le,confirmDisabled:!G,onConfirm:vt,onCancel:()=>So("")}):null,Hn&&!e.ui?.ConfirmDialog&&Oe("div",{role:"alertdialog","aria-label":a("Delete view"),style:de.confirm,children:[a("Delete view “{name}”?",{name:Dt.find((m)=>m.id===Hn)?.name??""}),H("small",{style:de.status,children:a("Only this view's filters, sort and layout are removed; no records are deleted.")}),H(Y,{ui:e.ui,style:de.button,disabled:Le||!G,onClick:vt,children:a("Delete view")}),H(Y,{ui:e.ui,style:de.button,onClick:()=>So(""),children:a("Cancel")})]}),Ze&&H("p",{role:Ze.error?"alert":"status",style:Ze.error?de.error:de.status,children:Ze.text}),e.transferClient&&d.export?H(Ea,{descriptor:I,fieldIds:I.fields.filter((m)=>!T.hiddenColumns.includes(m.id)).map((m)=>m.id),query:{search:io,...T.filter?{filter:T.filter}:{},...T.sort?.length?{sort:T.sort}:{}},client:e.transferClient,readOnly:!O,reloadKey:jn,onImported:_t,onRefreshSchema:async()=>{let m=await r.describe(I.id);return N.reload(),m.ok?m.data:null}}):null,si("settings",a("View settings"),Gd),si("schema",a("Fields"),Yd),si("add",a("Add record"),Qe==="add"&&aa?H("fieldset",{"aria-label":a("Add record"),"data-uibot-panel":"add",style:{margin:0,padding:0,border:0,minWidth:0},onKeyDown:ri(),children:H(Xa,{descriptor:I,client:r,getRelationOptions:s,readOnly:!O,autoFocus:!0,onDirtyChange:Ae,onBusyChange:Ve,onCommitted:()=>_t(),onSaved:(m)=>{Mn();let V=Qa(I,m.items[0]);Tt(`${a("Record saved")}${V?`:${V}`:""}`)},onCancel:so,stickyActions:Boolean(e.renderPanel),...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}})}):null),si("record",a("Record details"),Qe==="record"&&To&&ia?H(Zn,{...To,row:ia,onClose:Mn,onCancel:so,onDirtyChange:Ae,onBusyChange:Ve,stickyActions:Boolean(e.renderPanel)},ia.id):null),Ut&&aa?yt.error?Oe("p",{role:"alert",children:[po({code:yt.errorCode,message:yt.error},e.locale)," ",H(Y,{ui:e.ui,style:de.button,onClick:yt.reload,children:a("Reload records")})]}):Oe(ti,{children:[yt.loading&&H("p",{role:"status",children:a("Loading records…")}),H(Sd,{...aa},`${C}:${_}:${I.schemaVersion}:${Wt}:${Tn??""}`),i&&!d.footerStats?Oe("div",{style:de.actions,children:[H(Xe,{ui:e.ui,label:a("Sum field"),style:de.button,value:Fn,options:[{value:"",label:a("No sum")},...I.fields.filter((m)=>m.type==="number").map((m)=>({value:m.id,label:m.name}))],onChange:Qo}),H(jo,{collectionId:I.id,descriptor:I,view:T,aggregates:er,client:i,labels:Dr,reloadKey:jn,...e.locale?{locale:e.locale}:{}})]}):null,H("div",{style:de.actions,children:H(Ba,{hasPrevious:ao.length>0,hasNext:Boolean(yt.data?.nextCursor),loading:yt.loading,onPrevious:()=>{Jo(ao.at(-1)),Rr(ao.slice(0,-1))},onNext:()=>{Rr([...ao,Tn]),Jo(yt.data?.nextCursor??void 0)},page:ao.length+1,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}})})]}):To?T.type==="kanban"?H(dl,{...To},T.id):T.type==="gallery"?H(ul,{...To},T.id):T.type==="calendar"?H(gl,{...To},T.id):H(_a,{...To,...Dt.some((m)=>m.type!=="form")?{onShowRecords:()=>{let m=Dt.find((V)=>V.type!=="form");if(m)De(m.id)}}:{}},T.id):null]}):!f.loading&&C&&!M?H("p",{role:"alert",children:a("Table not found")}):N.data&&N.data.id!==C?H("p",{role:"alert",children:a("Table not found")}):B.error?H("p",{role:"alert",children:po({code:B.errorCode,message:B.error},e.locale)}):I&&xe&&!B.loading&&e.viewId!==void 0&&!T?H("p",{role:"alert",children:a("View not found")}):N.error?H("p",{role:"alert",children:po({code:N.errorCode,message:N.error},e.locale)}):f.loading||N.loading?H("p",{role:"status",children:a("Loading…")}):Oe("div",{style:de.empty,children:[H("p",{style:{margin:0},children:a("No tables yet")}),P?H(Y,{ui:e.ui,style:de.button,onClick:()=>{Xo(""),Er([{id:"name",name:a("Name"),type:"singleLineText",required:!0}]),lo("create")},children:a("New table")}):null]})]}),Ir&&e.aiFillClient&&I&&L?H(Ld,{table:I,rows:yt.data?.items??[],selection:ot,aiFillClient:e.aiFillClient,client:r,query:Sr,...yt.data?{total:yt.data.total}:{},onCommitted:()=>_t(),onClose:()=>Jt(!1),...Ro?{presetFieldId:Ro}:{},...e.onNotify?{onNotify:e.onNotify}:{},...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}},Ro):null,rt&&I?H(Vd,{container:Tr,anchorFieldId:rt.isNew?rt.insert?.beside:rt.draft.id,title:a(rt.isNew?"Add field":"Edit field"),dirty:!wr(rt.draft,rt.initial),onCancel:()=>Do(null),children:Oe("fieldset",{disabled:Le,style:{border:0,padding:0,margin:0,minWidth:0,display:"grid",gap:12},onKeyDown:(m)=>{if(m.key==="Enter"&&(m.ctrlKey||m.metaKey)&&!Le)m.preventDefault(),Ol()},children:[H(Yr,{single:!0,fields:[rt.draft],contextFields:I.fields.filter((m)=>m.id!==rt.draft.id),onChange:(m)=>{let V=m[0];if(V)Do((J)=>J?{...J,draft:V}:J)},disabled:Le||!k,...e.schemaFieldTypes?{fieldTypes:e.schemaFieldTypes}:{},settings:$n,relationTargets:f.data??[],lockedFieldIds:e.addOnlySchema&&!rt.isNew?[rt.draft.id]:[],...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{}}),Fl?H("p",{role:"alert",style:{margin:0,color:"var(--destructive, #b42318)"},children:Fl}):null,Oe("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[H(Y,{ui:e.ui,style:de.button,onClick:()=>Do(null),children:a("Cancel")}),H(Y,{ui:e.ui,style:de.button,variant:"default",disabled:Le||!k||!rt.draft.name.trim()||!rt.isNew&&wr(rt.draft,rt.initial),onClick:Ol,children:a(rt.isNew?"Add field":"Save field")})]})]})}):null,e.renderOverlay?.({table:I,view:T,selection:ot,rows:yt.data?.items??[],reload:_t}),e.sidePanel||e.renderSidePanel?Oe("aside",{style:de.side,children:[e.sidePanel,e.renderSidePanel?.({table:I,view:T,selection:ot,rows:yt.data?.items??[],reload:_t})]}):null]});return H(sa.Provider,{value:ta.report,children:H(Pa,{client:e.linkClient,children:Zd})})}var de={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 _d({fields:e,view:t,onChange:n,locale:o,ui:r,groupable:i,filter:l=!0,sort:s=!0,filterEditor:a,part:d}){let u=oe(o),f={fields:e,view:t,onChange:n,locale:o,ui:r},p=t.filter?.filterSet.length??0,c=t.sort?.length??0,C=i&&(t.type??"grid")==="grid"&&e.some((x)=>x.type==="singleSelect"||x.type==="checkbox");return Oe(ti,{children:[d==="main"&&Oe(ti,{children:[l?H(zn,{ui:r,icon:"filter",active:p>0,label:p?u("{count} filters",{count:p}):u("Filter"),children:H("div",{style:{width:"100%",maxWidth:520,minWidth:0},children:H(Hi,{...f,editor:a})})}):null,C&&H(zn,{ui:r,icon:"group",active:Boolean(t.groupByFieldId),label:u("Group"),children:H("div",{style:{width:"100%",maxWidth:360,minWidth:0},children:H($i,{...f})})}),s?H(zn,{ui:r,icon:"sort",active:c>0,label:c?u("{count} sorts",{count:c}):u("Sort"),children:H("div",{style:{width:"100%",maxWidth:440,minWidth:0},children:H(ji,{...f})})}):null]}),d==="extra"&&(t.type??"grid")==="grid"&&H(zn,{ui:r,icon:"rows",label:u("Row height"),active:Boolean(t.rowHeight),children:H("div",{style:{display:"grid",gap:2,minWidth:140},children:pi.map((x)=>H(Y,{ui:r,variant:(t.rowHeight??"short")===x?"outline":"ghost",size:"sm",onClick:()=>{let h={...t};if(x==="short")delete h.rowHeight;else h.rowHeight=x;n(h)},children:u(`Row height ${x}`)},x))})})]})}var tg={position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)"};export{ow as PagedCollectionWorkspace};