@uibot/renderer-react 0.18.1 → 0.19.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 Qi,useMemo as qd,useRef as Dl,useState as Hd}from"react";var Zi=Ud(void 0);function En(e,t={}){let n=zd(Zi),o=Dl({}),{dirty:i,busy:r}=e,{onDirtyChange:l,onBusyChange:d}=t;Qi(()=>{n?.(o.current,{dirty:i,busy:r}),l?.(i),d?.(r)},[n,i,r,l,d]),Qi(()=>()=>{n?.(o.current),l?.(!1),d?.(!1)},[n,l,d])}function Fl(){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 Qi(()=>(n.active=!0,()=>{n.active=!1}),[n]),n}import{useCallback as hl,useEffect as Mt,useMemo as Zn,useRef as on,useState as Ee}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 El(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 Ml(e,t){if(!t)return!0;if(Tl(t)){let n=t.filterSet.map((o)=>Tl(o)?Ml(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 Nl(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)=>Ml(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 P=e.fields.find((L)=>L.id===h.fieldId)?.type,f=(L)=>{if(["number","rating","autoNumber"].includes(P??"")&&typeof L==="number")return L;if(["date","createdTime","lastModifiedTime"].includes(P??"")){let N=Date.parse(String(L));if(Number.isFinite(N))return N}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=El(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:El(m,i.aggregates,e.fields)}});return{view:i,columns:l,rows:r,groups:g,...a.length?{aggregates:a}:{}}}var oi=500,ea=2000,wr=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 Qt(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 Qt("empty");if(t.aggregates.length>8||t.groupBy.length>3)return Qt("too_many");let n=new Set;for(let i of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(i.fn))return Qt("function");if(!Wd.test(i.as)||n.has(i.as)||t.groupBy.includes(i.as))return Qt("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 Qt(i.fn==="sum"?"sum_field":"unknown_field",{alias:i.as,...i.fieldId!==void 0?{fieldId:i.fieldId}:{}});if(i.fn==="sum"&&!Xi(r))return Qt("sum_field",{fieldId:r.id,alias:i.as});if(i.fn==="avg"&&!Xi(r))return Qt("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 Qt("extrema_field",{fieldId:r.id,alias:i.as});if((i.fn==="filled"||i.fn==="empty")&&!cn(r))return Qt("queryable_field",{fieldId:r.id,alias:i.as});if(i.fn==="count"&&!cn(r))return Qt("count_field",{fieldId:r.id,alias:i.as})}let o=new Set;for(let i of t.groupBy){if(o.has(i))return Qt("duplicate_group",{fieldId:i});o.add(i);let r=e.fields.find((l)=>l.id===i);if(!r)return Qt("unknown_field",{fieldId:i});if(!Gd.has(r.type)&&!Yd(r))return Qt("not_groupable",{fieldId:i})}return null}var Ol=(e)=>String(e).padStart(2,"0");function Mn(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=Mn(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=Mn(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 Qd(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 Zo=(e)=>Qd(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 Zo(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=Mn(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}$/,Zd=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function oa(e){if(!Zd(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([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 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 zp(e,t){if(t===e.draft)return e;return{...e,draft:t}}function nc(e){return e.draft!==e.savedContent}function qp(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 Hp(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)),Fo=(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)||!Fo(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)||!Fo(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)=>!Fo(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))||!Fo(e.collectionId,512)||!Fo(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||!Fo(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)||!Fo(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 Qc,useState as wa}from"react";var hn=(e)=>String(e).padStart(2,"0"),uc=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function Ft(e){let t=e.formatting;return uc(e)&&t&&"date"in t?t:void 0}function Eo(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function ua(e){let t=Ft(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=Mn(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=Mn(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 Ql(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(`
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
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
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=Ft(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,N]=S,U=new Date(Date.UTC(Number(A),Number(L)-1,Number(N)));if(U.getUTCMonth()!==Number(L)-1||U.getUTCDate()!==Number(N))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}-${N}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return lo({year:Number(A),month:Number(L),day:Number(N)},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 Zl(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 Mo(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((w)=>typeof w==="string"):[],c=mc(new Set(u));c.current=new Set(u);let[g,p]=er(""),[m,h]=er(),[x,C]=er([]),[P,f]=er(0),[R,S]=er({}),[A,L]=er({rows:[],next:null,error:"",loading:!0}),N=e.link?.collectionId,U=e.link?.displayFieldId;pc(()=>{let w=!0;if(L({rows:[],next:null,error:"",loading:!0}),!o||!N||!U){L({rows:[],next:null,error:s("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return o.query(N,{limit:50,search:g,...m?{cursor:m}:{}}).then((I)=>{if(!w)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(w)L({rows:[],next:null,error:s("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{w=!1}},[o,N,U,g,m,P]);let J=(w)=>R[w]??n.find((I)=>I.id===w)?.label??w;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((w)=>Ar("span",{className:"rounded border px-2 py-1 text-sm",children:[J(w)," ",vn("button",{type:"button","aria-label":s("Remove {name}",{name:J(w)}),onClick:()=>i(u.filter((I)=>I!==w)),children:"×"})]},w))}),vn("input",{"aria-label":s("Search {name} records",{name:e.name}),type:"search",placeholder:s("Search linked records"),value:g,onChange:(w)=>{p(w.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((w)=>w+1),children:s("Retry linked records")})]}),vn("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:A.rows.map((w)=>Ar("label",{className:"flex items-center gap-2 text-sm",children:[vn("input",{type:"checkbox","aria-label":s("Link {name}",{name:J(w.id)}),checked:u.includes(w.id),disabled:!u.includes(w.id)&&u.length>=100,onChange:(I)=>i(I.target.checked?[...u,w.id]:u.filter((k)=>k!==w.id))}),J(w.id)]},w.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((w)=>w.slice(0,-1))},children:s("Previous linked records")}),vn("button",{type:"button",disabled:!A.next||A.loading,onClick:()=>{C((w)=>[...w,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 No(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 Nn(e,t,n){if(t.type==="lookup")return so(e);if(t.type==="hyperlink")return Sr(e);if(t.type==="date"){let o=Ft(t);return o?$n(e,o):pi(e)}if(t.type==="number"){let o=Eo(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 Er=()=>bc(is),rs=(e)=>/^https?:/i.test(e);function bi(e){let t=Er();if(!Zo(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 Fr=(e)=>e?JSON.stringify(e):"",Pc=(e)=>e.trim().startsWith("{")?Ao(e):null;function Tr(e){let t=xc(()=>se(e.locale),[e.locale]),n=Er(),o=Cc(),i=Pc(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 w=new AbortController,I=setTimeout(()=>{g(t("Searching…")),n.search({search:r.trim(),...f?{kinds:f.split(",")}:{},limit:8},{signal:w.signal}).then((k)=>{if(w.signal.aborted)return;u(k.ok?k.data.slice(0,8):[]),g(k.ok?"":k.error.message)}).catch((k)=>{if(!w.signal.aborted)g(k instanceof Error?k.message:String(k))})},200);return()=>{clearTimeout(I),w.abort()}},[n,d,r,f,e.disabled,t]);let R=Ao(r),S=(w)=>n?.kinds?.find((I)=>I.id===w)?.label??w,A=[...R&&!R.ref?[{key:"typed",value:R,title:t("Use link {url}",{url:R.url})}]:[],...s.map((w)=>({key:`${w.kind}:${w.id}`,value:{url:w.url,text:w.title,ref:{kind:w.kind,id:w.id}},title:w.title,subtitle:[S(w.kind),w.subtitle].filter(Boolean).join(" · ")}))],L=Boolean(n&&!c&&!s.length&&r.trim()),N=d&&!e.disabled&&(A.length>0||Boolean(c)||L);vc(()=>{if(!N)return;let w=()=>C(h.current?.getBoundingClientRect()??null);return w(),window.addEventListener("scroll",w,!0),window.addEventListener("resize",w),()=>{window.removeEventListener("scroll",w,!0),window.removeEventListener("resize",w)}},[N]);let U=(w)=>{l(""),m(-1),e.onChange(Fr(w.value))},J=(w)=>{l(w),m(-1),e.onChange(w||Fr(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":N,"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:(w)=>J(w.currentTarget.value),onKeyDown:(w)=>{if(e.onSave||e.onCancel)w.stopPropagation();if(w.key==="ArrowDown"||w.key==="ArrowUp"){if(!A.length)return;w.preventDefault();let I=w.key==="ArrowDown"?1:-1;m((k)=>I>0?(k+1)%A.length:k<=0?A.length-1:k-1)}else if(w.key==="Enter"){w.preventDefault();let I=A[p];if(I)U(I);else e.onSave?.()}else if(w.key==="Tab"&&e.onSave)w.preventDefault(),e.onSave();else if(w.key==="Escape")if(w.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:(w)=>w.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:(w)=>{let I=w.currentTarget.value.slice(0,500),{text:k,...T}=i;e.onChange(Fr(I?{...T,text:I}:T))}})]})]}),N&&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:(w)=>w.preventDefault(),children:[A.map((w,I)=>or("div",{id:`${o}-${I}`,role:"option","aria-selected":I===p,tabIndex:-1,onMouseEnter:()=>m(I),onClick:()=>U(w),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:w.title}),w.subtitle&&un("span",{style:{fontSize:12,opacity:0.65},children:w.subtitle})]},w.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 wc=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function co(e){return wc.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=Mn(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`,[P,f]=ss(t),[R,S]=ss(!1);ls(()=>f(t),[t]);let A=rr(e,P,s),N=Boolean(e.required&&P===""&&A)&&!R&&!u?"":A,U=r??i??e.name,J=e.type==="date"&&co(P),w=J&&!A?as(P):P,I=[c,N?C:void 0].filter(Boolean).join(" "),k={id:x,"aria-label":U,"aria-invalid":Boolean(N),...I?{"aria-describedby":I}:{},disabled:n,onBlur:()=>S(!0),onKeyDown:(E)=>{if(d||a)E.stopPropagation();let H=e.type==="longText"||e.type==="json";if(E.key==="Tab"&&d)E.preventDefault(),d(E.shiftKey?"previous":"next");else if(E.key==="Enter"&&!E.shiftKey&&d&&(!H||E.ctrlKey||E.metaKey))E.preventDefault(),d();else if(E.key==="Escape"&&a)E.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=(E)=>{S(!0),f(E),l(E)},D=(E)=>{if(e.type==="date"&&J&&E){let H=new Date(E);T(Number.isFinite(H.getTime())?H.toISOString():E)}else T(E)},B;if(e.type==="hyperlink")B=uo(Tr,{field:e,text:P,id:x,ariaLabel:U,invalid:Boolean(N),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:P,onChange:(E)=>T(E.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:P,rows:e.type==="json"?4:3,onChange:(E)=>T(E.currentTarget.value)});else{let E=e.type==="date"&&!(A&&P)?J?"datetime-local":"date":"text",H=e.type==="blob";B=uo("input",{...k,type:E,inputMode:e.type==="number"?"decimal":void 0,step:J?"0.001":void 0,value:w,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,N&&uo("span",{id:C,role:"alert",className:"text-xs text-red-600",children:N})]})}import{useEffect as Dc,useRef as Fc}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 Ec}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(Ec,{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=Fc(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 Mr,useState as Ln}from"react";import{jsx as ke,jsxs as _e,Fragment as Nc}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 Mc=(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(""),[P,f]=Ln(!1),[R,S]=Ln(!1),[A,L]=Ln(!0),[N,U]=Ln(null),[J,w]=Ln(!1),I=Mr(!1),k=Mr(!1),T=Mr(!1),D=Mr(null),B=Mr({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 E=(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(E(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)E(q.data),s(null),c(null),D.current=null,H(q.data);else C(q.error.message)}async function Q(){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)E(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 Z(q=!1){if(P||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:P||!t.length,onClick:()=>void Z(),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(Nc,{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:P,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:P,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:P,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:Mc(q.values)}),ke("td",{children:q.error?.code??""})]},q.rowNumber))})]})}),ke("button",{type:"button",className:"self-start",disabled:P||!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:P,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)E(te.data),w(!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:P,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:P,onClick:()=>void Q(),children:g.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(g.status==="ready"||g.status==="schemaChanged")&&ke("button",{type:"button",disabled:P,onClick:()=>w(!0),children:"Cancel import"}),ke("button",{type:"button",disabled:P||!g.failedRows,onClick:()=>void fe(),children:"Show import errors"}),ke("button",{type:"button",disabled:P||!g.failedRows,onClick:()=>void Z(!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:P,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)E(q.data),w(!1);else C(q.error.message)},children:"Confirm cancellation"}),ke("button",{type:"button",onClick:()=>w(!1),children:"Keep import"})]}),N&&_e("div",{className:"max-w-full overflow-x-auto",children:[_e("table",{className:"w-full text-xs",children:[_e("caption",{children:[N.total," failed rows"]}),ke("thead",{children:_e("tr",{children:[ke("th",{children:"Row"}),ke("th",{children:"Field"}),ke("th",{children:"Error"})]})}),ke("tbody",{children:N.items.map((q)=>_e("tr",{children:[ke("td",{children:q.rowNumber}),ke("td",{children:q.fieldId??""}),ke("td",{children:q.code})]},q.rowNumber))})]}),N.nextCursor!==null&&ke("button",{type:"button",onClick:()=>void fe(N.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 Qe,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((E)=>Ci.some((H)=>H.type===E.type)),[i,r]=Oo(o[0]?.id??""),l=o.find((E)=>E.id===i)??o[0],[d,a]=Oo(l?.type??"singleLineText"),[s,u]=Oo(l?.required??!1),[c,g]=Oo(l?.options?.map((E)=>`${E.id}=${E.name}`).join(`
5
- `)??""),[p,m]=Oo(null),[h,x]=Oo(""),[C,P]=Oo(!1),f=Lo(null),R=Lo(null),S=Lo(0),A=Lo(e);A.current=e;let L=f.current?.field??l,N=C||f.current!==null,U=`${e.id}:${e.schemaVersion}:${JSON.stringify(e.fields)}`,J=Lo(e.fields);J.current=e.fields;let w=Lo(U);w.current=U;let I=Lo(!0);ps(()=>(I.current=!0,()=>{I.current=!1,S.current++}),[]),ps(()=>{if(w.current!==U)return;if(f.current&&R.current===e.id)return;S.current++;let E=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(E)r(E.id),a(E.type),u(E.required??!1),g(E.options?.map((H)=>`${H.id}=${H.name}`).join(`
6
- `)??"");m(null),f.current=null,R.current=null,x(""),P(!1)},[U,i,e.id]);let k=()=>{m(null),f.current=null,R.current=null,S.current++,x("")},T=(E)=>{r(E.id),a(E.type),u(E.required??!1),g(E.options?.map((H)=>`${H.id}=${H.name}`).join(`
7
- `)??""),k()};if(!L)return null;let D=()=>{let E={id:L.id,name:L.name,type:d,required:s};if(d==="singleSelect"||d==="multipleSelect")E.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:E}},B=()=>I.current&&w.current===U;return jt("details",{className:"rounded-lg border p-4",children:[Qe("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),jt("div",{className:"mt-4 flex flex-col gap-3",children:[Qe("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:N,onChange:(E)=>{let H=o.find((z)=>z.id===E.target.value);if(H)T(H)},children:[f.current&&!o.some((E)=>E.id===L.id)&&Qe("option",{value:L.id,children:L.name}),o.map((E)=>Qe("option",{value:E.id,children:E.name},E.id))]})]}),jt("label",{children:["Target type"," ",Qe("select",{"aria-label":"Conversion target type",value:d,disabled:N,onChange:(E)=>{a(E.target.value),k()},children:Ci.map((E)=>Qe("option",{value:E.type,children:E.label},E.type))})]}),jt("label",{children:[Qe("input",{type:"checkbox",checked:s,disabled:N,onChange:(E)=>{u(E.target.checked),k()}})," ","Required after conversion"]}),(d==="singleSelect"||d==="multipleSelect")&&jt("label",{children:["Stable option IDs and display names",Qe("textarea",{"aria-label":"Conversion options",className:"block w-full rounded border p-2",disabled:N,value:c,onChange:(E)=>{g(E.target.value),k()},placeholder:`open=Open
9
- done=Done`})]}),h&&Qe("p",{role:"alert",className:"text-sm text-destructive",children:h}),Qe("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:N,onClick:async()=>{let E;try{E=D()}catch(H){x(H instanceof Error?H.message:"Invalid conversion options.");return}P(!0),x(""),m(null),f.current=null;try{let H=await t.previewConversion(e.id,E);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())P(!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."]}),Qe("div",{className:"overflow-x-auto",children:jt("table",{className:"w-full text-sm",children:[Qe("thead",{children:jt("tr",{children:[Qe("th",{children:"Record"}),Qe("th",{children:"Before"}),Qe("th",{children:"After"}),Qe("th",{children:"Error"})]})}),Qe("tbody",{children:p.sample.map((E)=>jt("tr",{children:[Qe("td",{className:"max-w-32 break-all",children:E.id}),Qe("td",{className:"max-w-48 break-words",children:JSON.stringify(E.before)}),Qe("td",{className:"max-w-48 break-words",children:JSON.stringify(E.after)}),Qe("td",{children:E.error})]},E.id))})]})}),p.errors.length>0&&Qe("ul",{children:p.errors.map((E)=>jt("li",{children:[Qe("span",{className:"break-all",children:E.id}),": ",Qe("span",{children:E.code})]},E.id))}),Qe("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 E=f.current,H=S.current,z=()=>I.current&&A.current.id===e.id&&H===S.current;P(!0),x("");try{let ce=await t.convertField(e.id,E);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())P(!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,P=()=>!m&&r.current===i,f=Math.max(50,Math.min(60000,o)),R=async()=>{if(!P()||h)return;h=!0,c(!0);let L=!1;try{let N=x>0;for(let U of g){let J=p.get(U),w=await t.changes(U,{...J!==void 0?{cursor:J}:{},limit:100});if(!P())return;if(!w.ok)throw s(w.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let I=J===void 0;if(I||N||w.data.items.length>0)await l.current(U,w.data,I);if(!P())return;p.set(U,w.data.cursor),L||=w.data.hasMore}x=0,s("live")}catch{if(x++,P())s((N)=>N==="expired"?"expired":"offline")}finally{if(h=!1,P())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 Zt}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 Nr(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]=Zt(null),[a,s]=Zt(null),[u,c]=Zt(null),[g,p]=Zt(),[m,h]=Zt(),[x,C]=Zt([]),[P,f]=Zt([]),[R,S]=Zt(""),[A,L]=Zt(null),[N,U]=Zt(null),[J,w]=Zt(null),[I,k]=Zt(!1),[T,D]=Zt(""),B=po(null),E=po(null),H=po(n);H.current=n;let z=po(!1),ce=po(0),Q=`${e.id}:${t}`,fe=po(Q);fe.current=Q;let Z=po({historyBefore:g,commentBefore:m});Z.current={historyBefore:g,commentBefore:m};let q=po(async()=>{}),te=(v=Q)=>z.current&&fe.current===v&&H.current===n,le=async()=>{let v=Q,X=++ce.current,oe=Z.current,[tt,wt]=await Promise.all([Nr(()=>n.history(e.id,t,{...oe.historyBefore===void 0?{}:{before:oe.historyBefore},limit:20})),Nr(()=>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||!wt.ok)throw D(!tt.ok?tt.error.message:!wt.ok?wt.error.message:xa.message),Error("Activity refresh failed");s(tt.data),c(wt.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!==Q)return;s(null),c(null),d(null),p(void 0),h(void 0),C([]),f([]),Z.current={historyBefore:void 0,commentBefore:void 0},S(""),L(null),U(null),w(null),B.current=null,E.current=null,k(!1),D("")},[Q]),vi(()=>{if(fe.current!==Q||H.current!==n||Z.current.historyBefore!==g||Z.current.commentBefore!==m)return;q.current().catch(()=>{})},[Q,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!==Q)return;let X=v==="delete"?N: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 wt=await Nr(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),!wt.ok){D(wt.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!==Q)return;k(!0),D(""),E.current=null;let X={targetVersion:v,expectedCurrentVersion:a.currentVersion,expectedSchemaVersion:e.schemaVersion},oe=await Nr(()=>n.previewUndo(e.id,t,X));if(!te())return;if(k(!1),oe.ok)w(oe.data);else w(null),D(oe.error.message)},Te=async()=>{if(I||o||l!==Q||!J&&!E.current)return;let v=E.current;if(!v){if(!J)return;v={targetVersion:J.targetVersion,expectedCurrentVersion:J.currentVersion,expectedSchemaVersion:J.schemaVersion,idempotencyKey:crypto.randomUUID()},E.current=v}let X=v;k(!0),D("");let oe=await Nr(()=>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")E.current=null,w(null);D(oe.error.message),await q.current().catch(()=>{});return}E.current=null,w(null),i(oe.data),p(void 0),C([]),await q.current().catch(()=>{})},pe=u?.items.find((v)=>v.id===A?.id),Ne=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!==Q?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||!P.length,onClick:()=>{h(P.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}})]}),Ne&&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"})]})]}),N&&qe("div",{children:[Ie("p",{children:"Delete this comment? A deletion marker will remain."}),Ie("p",{className:"whitespace-pre-wrap break-words",children:N.text}),Ie("button",{type:"button",disabled:I||N.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&&!E.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&&!E.current,onClick:()=>void Te(),children:E.current?"Retry undo":"Confirm restore"}),Ie("button",{type:"button",disabled:I,onClick:()=>{w(null),E.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as xi,useRef as mo,useState as Kn}from"react";import{jsx as Et,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([]),P=mo(m);P.current=m;let[f,R]=Kn(null),[S,A]=Kn(null),L=mo(null),N=mo(null),[U,J]=Kn(!1),[w,I]=Kn(!1),[k,T]=Kn(""),D=()=>d.current&&l.current.identity===r&&l.current.client===n,B=async()=>{let Q=++a.current,fe=await ki(()=>n.list(e,t,{limit:20,...P.current===void 0?{}:{before:P.current}}));if(!D()||Q!==a.current)throw Error("Refresh superseded");if(!fe.ok)throw T(fe.error.message),Error("Attachment refresh failed");p(fe.data),c(r)},E=mo(B);E.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([]),P.current=void 0,++s.current,E.current().catch(()=>{})},[r,n]),xi(()=>{if(P.current===m&&u===r)E.current().catch(()=>{})},[m,r,u]),xi(()=>(i?.(()=>E.current()),()=>i?.(null)),[i]);let H=async()=>{if(U||o||!f||u!==r)return;let Q=f;J(!0),T("");let fe=await ki(()=>n.upload(e,t,Q));if(!D())return;if(J(!1),!fe.ok){T(fe.error.message);return}if(R(null),N.current)N.current.value="";h(void 0),C([]),P.current=void 0,await E.current().catch(()=>{})},z=async()=>{if(U||o||!S||S.authorId!==g?.actorId||u!==r)return;L.current??=crypto.randomUUID();let Q=S,fe=L.current;J(!0),T("");let Z=await ki(()=>n.delete(e,t,Q.id,{expectedVersion:Q.version,idempotencyKey:fe}));if(!D())return;if(J(!1),!Z.ok){T(Z.error.message),await E.current().catch(()=>{});return}A(null),L.current=null,await E.current().catch(()=>{})},ce=async(Q)=>{if(U||u!==r)return;J(!0),T("");let fe=await ki(()=>n.content(e,t,Q.id));if(!D())return;if(J(!1),!fe.ok){T(fe.error.message);return}let Z=Uint8Array.from(atob(fe.data.base64),(le)=>le.charCodeAt(0)),q=URL.createObjectURL(new Blob([Z],{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:[Et("h3",{className:"font-medium",children:"Attachments"}),Et("button",{type:"button",disabled:U,onClick:()=>{T(""),E.current().catch(()=>{})},children:"Refresh attachments"})]}),k&&Et("p",{role:"alert",children:k}),!g||u!==r?Et("p",{role:"status",children:"Loading attachments…"}):Xt(ys,{children:[g.items.length===0&&Et("p",{children:"No attachments yet."}),Et("ol",{className:"flex min-w-0 flex-col gap-2",children:g.items.map((Q)=>Xt("li",{className:"min-w-0 rounded border p-2",children:[Et("p",{className:"break-all",children:Q.name}),Xt("p",{className:"break-all text-xs",children:[Q.size," bytes · version ",Q.version," · ",Q.authorId]}),Q.deletedAt?Et("p",{children:"Attachment deleted"}):Xt("div",{className:"flex flex-wrap gap-3",children:[Et("button",{type:"button",disabled:U,"aria-label":`Download attachment ${Q.name}`,onClick:()=>void ce(Q),children:"Download"}),!o&&Q.authorId===g.actorId&&Et("button",{type:"button",disabled:U,"aria-label":`Delete attachment ${Q.name}`,onClick:()=>{A(Q),L.current=null},children:"Delete"})]})]},Q.id))}),Xt("div",{className:"flex flex-wrap gap-3",children:[Et("button",{type:"button",disabled:U||!x.length,onClick:()=>{h(x.at(-1)),C((Q)=>Q.slice(0,-1))},children:"Newer attachments"}),Et("button",{type:"button",disabled:U||g.nextCursor===null,onClick:()=>{C((Q)=>[...Q,m]),h(g.nextCursor??void 0)},children:"Older attachments"})]}),!o&&Xt(ys,{children:[Et("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",Et("input",{ref:N,"aria-label":"Attachment file",type:"file",disabled:U||w,onChange:async(Q)=>{let fe=Q.target.files?.[0];if(!fe)return;let Z=++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()||Z!==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()&&Z===s.current)T("The selected file could not be read.")}finally{if(D()&&Z===s.current)I(!1)}}},r)]}),f&&Xt("p",{className:"break-all",children:["Selected file: ",f.name]}),Et("button",{type:"button",className:"self-start",disabled:U||w||!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:[Et("button",{type:"button",disabled:U,onClick:()=>void z(),children:"Confirm delete attachment"}),Et("button",{type:"button",disabled:U,onClick:()=>{A(null),L.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as Pi,useRef as ar,useState as en}from"react";import{jsx as Ke,jsxs as ct,Fragment as bs}from"react/jsx-runtime";async function Pa(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([]),[P,f]=en([]),[R,S]=en([]),[A,L]=en(3600),[N,U]=en(null),[J,w]=en(!1),[I,k]=en(""),[T,D]=en(null),B=ar(null),[E,H]=en(!1),[z,ce]=en(""),Q=()=>d.current&&l.current.identity===r&&l.current.client===n,fe=async()=>{let ae=++a.current,Te=await Pa(()=>n.list(r,{limit:20,...h.current===void 0?{}:{before:h.current}}));if(!Q()||ae!==a.current)throw Error("Refresh superseded");if(!Te.ok)throw ce(Te.error.message),Error("Share refresh failed");g(Te.data),u(r)},Z=ar(fe);Z.current=fe,Pi(()=>(d.current=!0,()=>{d.current=!1,++a.current}),[]),Pi(()=>{if(l.current.identity!==r||l.current.client!==n)return;u(null),g(null),f([]),S([]),U(null),w(!1),k(""),D(null),B.current=null,H(!1),ce(""),m(void 0),C([]),h.current=void 0,Z.current().catch(()=>{})},[r,n]),Pi(()=>{if(h.current===p&&s===r)Z.current().catch(()=>{})},[p,s,r]),Pi(()=>(i?.(()=>Z.current()),()=>i?.(null)),[i]);let q=()=>{if(!J)U(null)},te=async()=>{if(E||!N||s!==r)return;let ae=N;H(!0),w(!0),ce("");let Te=await Pa(()=>n.create(r,ae));if(!Q())return;if(H(!1),!Te.ok){ce(Te.error.message);return}k(o(Te.data,ae.key)),U(null),w(!1),m(void 0),C([]),h.current=void 0,await Z.current().catch(()=>{})},le=async()=>{if(E||!T||s!==r)return;let ae=T;B.current??=crypto.randomUUID();let Te=B.current;H(!0),ce("");let pe=await Pa(()=>n.revoke(r,ae.id,{expectedVersion:ae.version,idempotencyKey:Te}));if(!Q())return;if(H(!1),!pe.ok){ce(pe.error.message),await Z.current().catch(()=>{});return}D(null),B.current=null,k(""),await Z.current().catch(()=>{})},ve=e.fields.filter((ae)=>!["linkedRecord","lookup","formula","rollup"].includes(ae.type)),xe=E||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:E,onClick:()=>{ce(""),Z.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:P.includes(ae.id),onChange:(Te)=>{q(),f((pe)=>Te.target.checked?[...pe,ae.id]:pe.filter((Ne)=>Ne!==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((Ne)=>Ne!==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||!P.length||!R.length||R.length>100||P.some((ae)=>!ve.some((Te)=>Te.id===ae)),onClick:()=>{ce("");try{U({expectedSchemaVersion:e.schemaVersion,fieldIds:[...P],recordIds:[...R],expiresInSeconds:A,key:Hc(),idempotencyKey:crypto.randomUUID()})}catch{ce("A secure share key could not be generated.")}},children:"Review read-only share"}),N&&ct("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[ct("p",{className:"break-all",children:["Confirm schema ",N.expectedSchemaVersion,", fields ",N.fieldIds.join(", "),", records ",N.recordIds.join(", ")," for ",N.expiresInSeconds," seconds."]}),N.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:E,onClick:()=>void te(),children:J?"Retry create read link":"Create read link"}),Ke("button",{type:"button",disabled:E,onClick:()=>{U(null),w(!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:E,"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:E||!x.length,onClick:()=>{m(x.at(-1)),C((ae)=>ae.slice(0,-1))},children:"Newer share grants"}),Ke("button",{type:"button",disabled:E||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:E,onClick:()=>void le(),children:"Confirm revoke share"}),Ke("button",{type:"button",disabled:E,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[P,f]=_t(""),[R,S]=_t("record"),[A,L]=_t(60),[N,U]=_t([]),[J,w]=_t([]),[I,k]=_t({}),[T,D]=_t(null),[B,E]=_t(!1),[H,z]=_t(!1),[ce,Q]=_t(""),[fe,Z]=_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){Q(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 Q(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(Q(""),!P.trim()||!N.length||R!=="record"&&!J.length){Q("Choose a name, writable fields, and target records for time or webhook triggers.");return}let j=Object.fromEntries(N.map((X)=>[X,I[X]??null])),v={expectedSchemaVersion:e.schemaVersion,name:P.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}),E(!1)},ae=(j)=>{D(j),E(!1),Q("")},Te=async()=>{if(!T||H)return;let j=T,v=B;E(!0),z(!0),Q("");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)E(!1);Q(`${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)Z(JSON.stringify(o(oe,j.input.webhookKey),null,2));f(""),U([]),w([]),k({})}D(null),E(!1),C.current=void 0,x(void 0),await ve.current()},pe=a.find((j)=>j.id===u),Ne=!!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:Ne,style:{minWidth:0},children:[De("legend",{children:"New automation"}),gt("label",{children:["Name"," ",De("input",{"aria-label":"Automation name",value:P,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:N.includes(j.id),onChange:(v)=>{U(v.target.checked?[...N,j.id]:N.filter((X)=>X!==j.id))}}),j.name]},j.id))]}),De(Vo,{fields:e.fields.filter((j)=>N.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)=>w(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:()=>Z(""),children:"Hide webhook key"})]}),a.length>0&&gt("label",{children:["Automation"," ",De("select",{"aria-label":"Selected automation",disabled:Ne,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:Ne,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:Ne||!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:Ne||!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:Ne||h===void 0,onClick:()=>{C.current=void 0,x(void 0)},children:"Newest runs"}),De("button",{type:"button",disabled:Ne||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(""),[P,f]=Lt([]),[R,S]=Lt([]),[A,L]=Lt([]),[N,U]=Lt(null),[J,w]=Lt(null),[I,k]=Lt(null),[T,D]=Lt(!1),[B,E]=Lt(!1),[H,z]=Lt(""),[ce,Q]=Lt(""),[fe,Z]=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),w(null),k(null),D(!1),z(""),Q(""),Z(""),f([]),S([]),L([]),C("");let v=!0;return c(!1),E(!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:P,sourceFieldIds:R,targetFieldIds:A});w(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(""),Q("")}catch(v){z(v instanceof Error?v.message:"Invalid selection.")}},ve=async()=>{if(!N||B)return;let v=N,X=T;E(!0),D(!0),z("");let oe=await te(()=>n.propose(r,v));if(!q())return;if(E(!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),Z(oe.data.id),D(!1)},xe=async()=>{if(!I||B)return;let v=I,X=T;E(!0),D(!0),z("");let oe=await te(()=>n.confirm(r,v));if(!q())return;if(E(!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}Q(`${oe.data.items.length} records filled${oe.data.replayed?"; original receipt recovered":""}.`),k(null),U(null),w(null),D(!1);try{await o?.()}catch{if(q())z("The fill committed. Refresh the Collection to see its records.")}},ae=async()=>{if(B||N||I)return;E(!0),z("");let v=await te(()=>n.get(r,fe));if(!q())return;if(E(!1),v.ok)k(v.data),D(!1),Q("");else z(v.error.message)},Te=(v,X,oe)=>oe(v.includes(X)?v.filter((tt)=>tt!==X):[...v,X]),pe=B||!!N||!!I,Ne=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"}),Ne.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"}),Ne.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:P.includes(v.id),onChange:()=>Te(P,v.id,f)}),v.id," · version ",v.version]},v.id))]}),He("button",{type:"submit",disabled:!g,children:"Review AI request"})]})}),N&&!I&&pt("section",{"aria-label":"AI data disclosure",children:[pt("p",{children:["Selected service: ",N.resourceId," · model ",N.model," · schema"," ",N.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),He("p",{children:N.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),w(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),w(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)=>Z(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 Fe}from"react/jsx-runtime";var Zc=[{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 by({fields:e,onChange:t,lockedIds:n=[],collections:o=[]}){let i=(r,l)=>t(e.map((d,a)=>a===r?{...d,...l}:d));return Fe("div",{className:"flex flex-col gap-3",children:[e.map((r,l)=>{let d=n.includes(r.id);return Fe("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:Zc.map((a)=>me("option",{value:a.value,children:a.name},a.value))}),Fe("div",{className:"flex items-center gap-2",children:[Fe("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"&&Fe("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Fe("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",Fe("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))]})]}),Fe("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",Fe("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"&&Fe("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Fe("label",{children:["Through linked field"," ",Fe("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))]})]}),Fe("label",{children:["Read target field"," ",Fe("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"&&Fe("div",{className:"flex flex-col gap-1 md:col-span-4",children:[Fe("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."}),Fe("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"&&Fe("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Fe("label",{children:["Through linked field"," ",Fe("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))]})]}),Fe("label",{children:["Aggregate"," ",Fe("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"})]})]}),Fe("label",{children:["Target field"," ",Fe("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(!Zo(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=Qc();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,P=[p,C].filter(Boolean).join(" "),f={...P?{"aria-describedby":P}:{},...x?{"aria-invalid":!0}:{}};return Fe("div",{className:"flex flex-col gap-1 text-sm",children:[Fe("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"?Fe("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:Ft(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]):Fr(Zo(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 hy({fields:e,view:t,onChange:n,onError:o}){let i=e.filter(cn),[r,l]=wa(i[0]?.id??""),d=i.some((C)=>C.id===r)?r:i[0]?.id??"",[a,s]=wa("contains"),u=d?(()=>{let C=e.find((P)=>P.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]=wa(""),x=[...t.columnOrder.flatMap((C)=>{let P=e.find((f)=>f.id===C);return P?[P]:[]}),...e.filter((C)=>!t.columnOrder.includes(C.id))];return Fe("div",{className:"flex flex-wrap items-end gap-3",children:[Fe("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})})]}),Fe("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(C)=>{C.preventDefault();let P=e.find((R)=>R.id===d);if(!P)return;let f;try{f=eu(P,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:[Fe("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"})]}),Fe("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,P)=>Fe("div",{className:"flex items-center gap-2 text-sm",children:[Fe("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:P===0,onClick:()=>{let f=x.map((S)=>S.id),R=f[P-1];if(R!==void 0)[f[P-1],f[P]]=[C.id,R];n({...t,columnOrder:f})},children:"←"}),me("button",{type:"button","aria-label":`Move ${C.name} right`,disabled:P===x.length-1,onClick:()=>{let f=x.map((S)=>S.id),R=f[P+1];if(R!==void 0)[f[P],f[P+1]]=[R,C.id];n({...t,columnOrder:f})},children:"→"})]},C.id))})]})]})}import{useEffect as tu,useMemo as ks,useState as Ps}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 ws(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:ws(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]=Ps(u("Loading summary…")),[p,m]=Ps(!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 P=ws(t,s,C.data,d??{},{unassigned:u("Unassigned"),checked:u("Checked"),unchecked:u("Unchecked"),none:u("none")});g(P.length?P.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 Fa}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)"},wi={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:wi,loading:n,error:""});Si(()=>{let h=!0;if(!n){p({key:s,page:wi,loading:!1,error:""});return}p((P)=>({key:s,page:P.key===s?P.page:wi,loading:!0,error:""}));let[x,,C]=JSON.parse(i);return e.client.query(x,{...C,...d?{cursor:d}:{}}).then((P)=>{if(!h)return;if(P.ok)p({key:s,page:P.data,loading:!1,error:""});else p((f)=>({...f,loading:!1,error:P.error.message}))}).catch(()=>{if(h)p((P)=>({...P,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:wi;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(Fa,{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);En({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(Fa,{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);En({dirty:JSON.stringify(g)!==JSON.stringify(c.current),busy:!1});let x=Or(null),[C,P]=tn(!1);Si(()=>{x.current?.focus()},[]);let f=Ia(l),R=No(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(N=!1)=>{h(!0);try{let U=N?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 w=Lr(J,g,d,l.locale);U={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:e.id,expectedVersion:e.version,values:w}]}}if(await f.commit(U))t()}catch(U){f.setError(U instanceof Error?U.message:d("Invalid value"))}},L=async()=>{let N=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(N))t()};return Kt("div",{ref:x,tabIndex:-1,onKeyDown:(N)=>{if(N.key==="Escape"&&!f.saving)N.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:(N)=>{N.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:(N)=>{p(N),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:()=>P(!0),children:d("Delete record")})}):null]})]}),s&&!r&&Se("button",{type:"button",style:ze,disabled:f.saving,onClick:()=>P(!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(P(!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(P(!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(P(!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=No(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);En({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(Fa,{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 Ea,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:P,value:f}=e;Ea(()=>{c((A)=>Ai(A,e.labels))},[e.labels]),Ea(()=>{let A=!1;if(!x||!P)return;return h(!0),p(""),P({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 N=L.data.items.slice(0,50);c((U)=>Ai(U,N)),s((U)=>{let J=i?[...U,...N]:N;return[...new Map(J.map((w)=>[w.id,w])).values()]}),d(L.data.nextCursor)}).catch(()=>{if(!A)p(t("Relation options unavailable."))}).finally(()=>{if(!A)h(!1)}),()=>{A=!0}},[x,C,n,i,P,t]),Ea(()=>{if(!f||!x||!P)return;if(e.labels?.some((L)=>L.id===f&&L.label.trim()))return;let A=!1;return P({collectionId:x,...C?{labelFieldId:C}:{},ids:[f],limit:50}).then((L)=>{if(A||!L.ok)return;let N=L.data.items.find((U)=>U.id===f);if(N)c((U)=>Ai(U,[N]))}).catch(()=>{}),()=>{A=!0}},[f,x,C,P,e.labels]);let R=!x||!P,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((N)=>N.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},Fi=(e,t="en")=>su[t][e]??e;function Ta(e,t){if(!t)return"";let n=e?Ft(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=Fi(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 Es}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 Ei=()=>`row_${Math.random().toString(36).slice(2,10)}`,pu=(e)=>("filterSet"in e),mu=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}};function Ma(e,t){if(t)return _l(e);let n=bn(e);return n?gu[n]??[]:[]}function Na(e,t,n){if(Xo.has(t))return;let o=bn(e);if(o==="date"&&n)return{mode:"today",timeZone:Ft(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:Ei(),node:o});else t.push({key:Ei(),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=Ma(h,o)[0]??"";u({...d,rows:[...d.rows,{key:Ei(),fieldId:h.id,operator:x,value:x?Na(h,x,o):void 0}]})},p=()=>u({...d,groups:[...d.groups,{key:Ei(),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),P=C?bn(C):null,f=C?Ma(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=Ma(S,o),L=A.includes(h.operator)?h.operator:A[0]??"",N=bn(S)===P;c(h.key,{fieldId:R,operator:L,value:L&&!(N&&L===h.operator)?Na(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:Na(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((P)=>P.key===h.key?{...P,node:C}:P):d.groups.filter((P)=>P.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(Es,{children:[Ve(gr,{ui:o.ui,label:n("Date mode"),style:Ye.control,value:l.mode,options:na.map((u)=>({value:u,label:Fi(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(Es,{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:Ft(e)?.timeZone??l.timeZone??""})]})}var Fs="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 ${Fs}`,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 ${Fs}`,borderRadius:6,background:"transparent",color:"inherit",font:"inherit"},hint:{margin:0,fontSize:12,opacity:0.7}};import{jsx as Ze,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 Mi({fields:e,view:t,onChange:n,locale:o,ui:i,editor:r}){return Ze("div",{"data-uibot-view-filter":"",children:Ze(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 Ni({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:[Ze("span",{style:{flex:"1 1 120px",minWidth:110,display:"flex"},children:Ze(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))})}),Ze("span",{style:{flex:"0 1 110px",minWidth:90,display:"flex"},children:Ze(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))})}),Ze(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:" "}),Ze(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:" "}),Ze(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:[Ze(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?Ze(W,{ui:i,variant:"ghost",size:"sm",onClick:()=>s([]),children:r("Clear sort")}):Ze("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:[Ze("input",{type:"checkbox",checked:t.showRowNumber!==!1,onChange:(c)=>n({...t,showRowNumber:c.currentTarget.checked})})," ",l("Show row numbers")]}),Gn("label",{children:[Ze("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:[Ze(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)})}),Ze("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:p?1:0.5},children:m}),Ze(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)}),Ze(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 Ze("div",{"data-uibot-view-columns":"",children:u});return Gn("details",{"data-uibot-view-columns":"",children:[Ze("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 Ze("div",{style:{display:"flex",gap:6,alignItems:"center"},children:t.groupByFieldId?Gn(hu,{children:[Ze(Ce,{name:"group"}),Ze(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})}),Ze(W,{ui:i,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove grouping"),onClick:()=>{let d={...t};delete d.groupByFieldId,n(d)}})]}):Ze(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"}},Ns="table";function Oi({icon:e,size:t=15,icons:n=_r}){let o=(e?n[e]:void 0)??n[Ns]??_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 P=(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??Ns)===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:P,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 Ms="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 ${Ms}`,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 ${Ms}`,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((E)=>({scope:a,targets:{...E?.scope===a?E.targets:{},[D]:B}}))};return{query:async(...D)=>{let B=D[0],E=(k.get(B)??0)+1;k.set(B,E),T(B,!1);try{let H=await e.client.query(...D);if(k.get(B)===E)T(B,H.ok);return H}catch(H){if(k.get(B)===E)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),P=zo(!1),f=zo(null),R=zo(null),{autoFocus:S}=e;Ua(()=>{if(h?.error)R.current?.focus()},[h]);let[A,L]=pr(!1),[N,U]=pr(!1),J=JSON.stringify(i)!==JSON.stringify(o.current)||A;En({dirty:J,busy:l},e);let w=()=>f.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled])")?.focus();Ua(()=>{if(S)w()},[S]);async function I(k){if(P.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}P.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 E=qa(e.descriptor,B.data.items[0]);if(x({text:`${k?t("Record saved, keep adding"):t("Record saved")}${E?`:${E}`:""}`,error:!1,clearable:!1}),k)requestAnimationFrame(w);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{P.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:N,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],Pu={date:"YYYY-MM-DD",time:"none"},wu={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=Ft(e)??Pu,m=(x)=>{let{timeZone:C,...P}=p,f={...P,...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=Eo(e)??wu,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 P=C.currentTarget.checked?[...h,x.id]:h.filter((f)=>f!==x.id);if(P.length)u({defaultValue:{kind:"value",value:P}});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(!wr.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((P)=>P!==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=Er()?.kinds??[],h=(w)=>l.includes(w.type),x=zr(new Map),C=zr(new Map),P=zr(null),f=zr(new Map),R=zr(null);function S(w,I){let k={fields:w,target:I};R.current=k,t(w),queueMicrotask(()=>{if(R.current===k)R.current=null})}Ru(()=>{let w=R.current;if(!w||w.fields!==e)return;if(R.current=null,n)return;let{target:I}=w,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"?P.current:I.type==="add-option"?f.current.get(I.fieldId):null)?.querySelector("button")?.focus()},[n,e]),Su(()=>{if(!o)return;let w=window.setTimeout(()=>{let I=x.current.get(o);I?.scrollIntoView({block:"center"}),I?.focus(),I?.select()},200);return()=>window.clearTimeout(w)},[o]);let A=(w,I)=>{if(!n)t(e.map((k)=>k.id===w?I(k):k))};function L(){if(n)return;let w={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:g("New field"),type:"singleLineText"};S([...e,w],{type:"field-name",fieldId:w.id})}function N(w){if(n)return;let I=e.filter(h),k=I.findIndex((B)=>B.id===w),T=I.filter((B)=>B.id!==w),D=T[k]??T[k-1];S(e.filter((B)=>B.id!==w),D?{type:"field-name",fieldId:D.id}:{type:"add-field"})}function U(w){if(n)return;let I={id:crypto.randomUUID(),name:g("New option")};S(e.map((k)=>k.id===w.id?{...k,options:[...k.options??[],I]}:k),{type:"option-name",fieldId:w.id,optionId:I.id})}function J(w,I){if(n)return;let k=w.options??[],T=k.findIndex((E)=>E.id===I),D=k.filter((E)=>E.id!==I),B=D[T]??D[T-1];S(e.map((E)=>{if(E.id!==w.id)return E;let H=E.defaultValue;if(!(H?.kind==="value"&&(Array.isArray(H.value)?H.value.includes(I):H.value===I)))return{...E,options:D};let{defaultValue:ce,...Q}=E;return{...Q,options:D}}),B?{type:"option-name",fieldId:w.id,optionId:B.id}:{type:"add-option",fieldId:w.id})}return pn("section",{"aria-label":g("Collection fields"),"data-uibot-schema-editor":"",style:ue.root,children:[e.filter(h).map((w)=>pn("fieldset",{"aria-label":g("Field {name}",{name:w.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(w.id,I);else x.current.delete(w.id)},style:ue.input,value:w.name,disabled:n,onChange:(I)=>{let k=I.currentTarget.value;A(w.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(w.id),value:w.type,options:l.map((I)=>({value:I,label:p[I]})),onChange:(I)=>A(w.id,(k)=>{let{options:T,relation:D,hyperlink:B,formatting:E,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(w.required),disabled:n,onChange:(I)=>{let k=I.currentTarget.checked;A(w.id,(T)=>({...T,required:k}))}}),g("Required")]}),u?null:Xe(W,{ui:r,style:{...ue.button,...ue.danger},disabled:n||a.includes(w.id),icon:"trash",iconOnly:!0,ariaLabel:g("Delete field"),title:g("Delete field {name}",{name:w.name}),onClick:()=>N(w.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:w.description??"",disabled:n,onChange:(I)=>{let k=I.currentTarget.value;A(w.id,(T)=>Iu(T,k))}})]}),w.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(w.id),value:w.relation?.collectionId??"",options:[{value:"",label:g("Choose a related table")},...d.map((I)=>({value:I.id,label:I.name}))],onChange:(I)=>A(w.id,(k)=>({...k,relation:{collectionId:I}}))})]}):null,w.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=w.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(w.id,(B)=>{let E=B.hyperlink?.kinds??[],H=D?[...E,I.id]:E.filter((Q)=>Q!==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(w.type)?pn("fieldset",{style:ue.options,"aria-label":g("Options of field {name}",{name:w.name}),children:[Xe("strong",{style:{fontSize:13},children:g("Options")}),(w.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=`${w.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(w.id,(B)=>({...B,options:(B.options??[]).map((E)=>E.id===I.id?{...E,name:D}:E)}))}}),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(w.id,(E)=>({...E,options:(E.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(w,I.id)})]},I.id)),Xe("div",{ref:(I)=>{if(I)f.current.set(w.id,I);else f.current.delete(w.id)},children:Xe(W,{ui:r,style:ue.button,icon:"plus",disabled:n,onClick:()=>U(w),children:g("Add option")})})]}):null,Xe(Bs,{field:w,...s?{settings:s}:{},dateFormatLocked:a.includes(w.id),disabled:n,locale:i,ui:r,onChange:(I)=>A(w.id,I)}),s?.ai?Xe(Us,{field:w,fields:u&&c?[...c,w]:e,disabled:n,locale:i,onChange:(I)=>A(w.id,I)}):null]},w.id)),u?null:Xe("div",{ref:P,children:Xe(W,{ui:r,style:ue.button,icon:"plus",disabled:n,onClick:L,children:g("Add field")})})]})}import{useEffect as Js,useRef as Qs,useState as Qa}from"react";import{useCallback as Mu,useEffect as Ws,useLayoutEffect as Nu,useRef as Ja,useState as Gs}from"react";import{createContext as Au,useContext as Du,useCallback as Fu,useEffect as zs,useId as Eu,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=Eu();zs(()=>{let h=(x)=>{let C=x.detail,P=u.current;if(!C||!P||C===P)return;let f=P.closest("[data-uibot-workspace]")??P.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=Fu(()=>{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((P)=>P.left===C.left&&P.top===C.top?P: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),P=h.key==="Home"?0:h.key==="End"?x.length-1:(C+(h.key==="ArrowUp"?-1:1)+x.length)%x.length;x[P]?.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=Mu(()=>{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]);Nu(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 Zs}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 Za(e){let t=se(e.locale),[n,o]=Qa(null),[i,r]=Qa(""),[l,d]=Qa(null),a=Qs(null),s=Qs(null),u=Boolean(e.onReorder)&&!e.disabled&&e.views.length>1,c=e.views.map((S)=>S.id),g=(S,A,L)=>{let N=Ou(c,S,A,L);if(N.join("\x00")!==c.join("\x00"))e.onReorder?.(N)};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((N)=>N.id===A.id);if(S.altKey&&(S.key==="ArrowRight"||S.key==="ArrowLeft")){S.preventDefault();let N=e.views[L+(S.key==="ArrowRight"?1:-1)];if(u&&N)a.current=A.id,g(A.id,N.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 N=e.views[L+(S.key==="ArrowRight"?1:-1)];if(N)e.onSelect(N.id),S.currentTarget.parentElement?.parentElement?.querySelectorAll('[role="tab"]')?.[L+(S.key==="ArrowRight"?1:-1)]?.focus()}},P=(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 Zs("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),N=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)}}):Zs("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(),w=(U.clientX||0)>J.left+J.width/2;if(l.over!==S.id||l.after!==w)d({id:l.id,over:S.id,after:w})},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:N},S.id)})}),e.onAdd&&(R?nn(R,{label:t("Add view"),items:P,disabled:e.disabled}):nn(_i,{label:t("Add view"),items:P,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=No(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 P=$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:P}),onClick:()=>i(C),children:P}),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:P}),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:P}),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"?Mo(e,o):Nn(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=No(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"?Mo(a,s):Nn(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!Mo(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))},P=(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"))P(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:(N)=>{g.current=L,N.dataTransfer.setData("application/x-uibot-record",L.id),N.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:P})]},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((P)=>P.type==="singleSelect"||P.type==="checkbox"),p=e.filter((P)=>P.type==="date"),m=(P)=>{let f={...t,type:P};if(delete f.groupByFieldId,delete f.dateFieldId,P==="kanban"&&g[0])f.groupByFieldId=g[0].id;if(P==="calendar"&&p[0])f.dateFieldId=p[0].id;if(P==="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((P)=>({value:P,label:h[P],disabled:P==="kanban"&&!g.length||P==="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:(P)=>m(P)})]}),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((P)=>({value:P,label:u(`Row height ${P}`)})),onChange:(P)=>{let f={...t};if(P==="short")delete f.rowHeight;else f.rowHeight=P;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((P)=>({value:P.id,label:P.name})),onChange:(P)=>n({...t,groupByFieldId:P})})]}),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((P)=>({value:P.id,label:P.name})),onChange:(P)=>n({...t,dateFieldId:P})})]}),(l?.filter||l?.columns||l?.sort)&&yr("div",{style:{display:"grid",gap:12,flexBasis:"100%"},children:[l?.filter&&Jn(Mi,{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(Ni,{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 Pn,useRef as wn,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]),P=C.map((S)=>p.type==="date"?typeof S==="string"&&S!==""?Date.parse(S)/86400000:Number.NaN:typeof S==="number"?S:Number.NaN),f=P[0]??Number.NaN,R=(P[1]??Number.NaN)-f;if(P.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 Qu,useMemo as Zu,useState as Xu}from"react";function ld(e,t,n,o,i,r){let l=Zu(()=>{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 Qu(()=>{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],P=u.fields.find((R)=>R.id===x.fieldId),f=P?.type==="date"||P?.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 Qn={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=Pn(()=>Dt(e.features),[e.features]),r=!e.readOnly&&i.rowDelete,l=!e.readOnly&&i.rowCreate,d=!e.readOnly&&i.rowUpdate,[a,s]=yt({}),u=wn(new Set),[c,g]=yt(()=>new Set),p=wn(new Set);Sn(()=>{if(!u.current.size)return;let b=u.current;u.current=new Set,s((F)=>Object.fromEntries(Object.entries(F).filter(([M])=>!b.has(M))))},[e.rows]);let m=Pn(()=>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=Pn(()=>[...n.columnOrder,...t.fields.map((F)=>F.id).filter((F)=>!n.columnOrder.includes(F))].filter((F)=>!n.hiddenColumns.includes(F)).flatMap((F)=>{let M=t.fields.find((re)=>re.id===F);return M?[M]:[]}),[t.fields,n.columnOrder,n.hiddenColumns]),x=Pn(()=>JSON.stringify([m.map((b)=>b.id),h.map((b)=>b.id)]),[m,h]),[C,P]=yt(x),f=wn(null),[R,S]=yt({row:0,column:0}),[A,L]=yt(!1),[N,U]=yt(()=>new Set),[J,w]=yt(()=>new Set),I=JSON.stringify([t.id,n.filter,n.search,n.sort,e.rowOffset]);Sn(()=>{U(new Set),w(new Set)},[e.rows,I]);let[k,T]=yt({row:0,column:0}),[D,B]=yt(null),E=wn(!1),H=wn(!1),[z,ce]=yt(null),[Q,fe]=yt(!1),[Z,q]=yt(!1);En({dirty:Boolean(z||Q||D&&D.text!==D.originalText),busy:Z||c.size>0},e);let[te,le]=yt(""),[ve,xe]=yt(null),ae=wn(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}),P(x)},[x]);let pe=Pn(()=>{if(!i.groupBy||(n.type??"grid")!=="grid")return;let b=t.fields.find((F)=>F.id===n.groupByFieldId);return ia(b)?b:void 0},[i.groupBy,n.type,n.groupByFieldId,t.fields]),[Ne,j]=yt(()=>new Set),v=pe?.id;Sn(()=>j(new Set),[v]);let X=Pn(()=>$l(m,pe,Ne),[m,pe,Ne]),oe=(b)=>Boolean(pe)&&X.rowItem[b]===void 0,tt=jl(n.rowHeight),wt=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 F=()=>Ae(b.clientWidth);if(F(),typeof ResizeObserver>"u")return window.addEventListener("resize",F),()=>window.removeEventListener("resize",F);let M=new ResizeObserver(F);return M.observe(b),()=>M.disconnect()},[]);let nt=Math.min(Math.max(0,n.frozenColumnCount??0),h.length),St=Pn(()=>{let b=[ye];for(let F of h)b.push((b.at(-1)??ye)+Hr(n.columnWidths[F.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=wn(null),an=Boolean(e.onAddRecord)&&l,st=ig(rg(ng,{activationConstraint:{distance:6}})),Rt=({active:b,delta:F})=>{let M=h.findIndex((Ue)=>Ue.id===b.id),re=Bt.getVirtualItems().find((Ue)=>Ue.index===M);if(M<0||!re)return;let G=re.start+re.size/2+F.x,V=Bt.getVirtualItems().find((Ue)=>G>=Ue.start&&G<Ue.start+Ue.size)?.index;if(V===void 0||V===M)return;if(M<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))],we=String(b.id),be=h[V]?.id;if(!be)return;let Re=ne.filter((Ue)=>Ue!==we),he=Re.indexOf(be)+(V>M?1:0);Re.splice(he,0,we),e.onViewChange({...n,columnOrder:Re})},Vt=(b,F)=>({position:"sticky",float:"left",left:b,zIndex:2,...F?{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 F=new Set(ag(b));for(let M=0;M<We;M+=1)F.add(M);return[...F].sort((M,re)=>M-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,F)=>{Bt.resizeItem(F,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=Pn(()=>A&&C===x?m.slice(ot.firstRow,ot.lastRow+1):[],[A,C,x,m,ot.firstRow,ot.lastRow]),Pe=Pn(()=>{let b=new Set(m.filter((F,M)=>!pe||X.rowItem[M]!==void 0).map((F)=>F.id));return rd(Ho,N,m,J).filter((F)=>b.has(F.id))},[Ho,N,m,J,pe,X]),Xn=Pn(()=>Pe.map((b)=>b.id),[Pe]),Ut=Pn(()=>new Set(Xn),[Xn]),_n=A?{first:ot.firstColumn,last:ot.lastColumn}:{first:0,last:h.length-1},$o=()=>Pe.length?Ql(Pe,h,{row:0,column:_n.first},{row:Pe.length-1,column:_n.last}):"",eo=(b)=>{if(D||Z||Q||z)return;let F=m[b];if(!F)return;if(P(x),Ho.some((M)=>M.id===F.id))w((M)=>al(M,F.id));else U((M)=>al(M,F.id));if(!A)S({row:b,column:0}),T({row:b,column:h.length-1})},[vt,Co]=yt(null),vo=wn(null),to=!N.size&&!J.size&&A&&d&&!Z&&!D&&!Q&&!z&&!Ne.size,hr=(b,F)=>{if(!to)return;let M=ad(b,F,m,h),re=(V)=>{le(V),e.onNotify?.(V)};if(M.limitExceeded){re(o("Fill at most 100 rows at once."));return}let G=M.skipped?o("Skipped {count} cells",{count:M.skipped}):"";if(!M.mutations.length){if(G)re(G);return}Ht({idempotencyKey:crypto.randomUUID(),items:M.mutations},()=>{re([o("Filled {count} cells",{count:M.count}),G].filter(Boolean).join("; "))})};Sn(()=>{if(!vt)return;let b=()=>{let M=vo.current;if(Co(null),vo.current=null,M)hr(vt,M)},F=()=>{Co(null),vo.current=null};return window.addEventListener("mouseup",b),window.addEventListener("blur",F),()=>{window.removeEventListener("mouseup",b),window.removeEventListener("blur",F)}});let jo=JSON.stringify({recordIds:C===x?Xn:[],fieldIds:Pe.length?h.slice(_n.first,_n.last+1).map((b)=>b.id):[]}),Ko=wn(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),F=b>=0?b:ui(X,k.row,1,m.length);if(F>=0)T({...k,row:F}),S({...k,row:F})},[X]);let Rn=(b)=>{let F=new Set(Ne);if(F.has(b))F.delete(b);else F.add(b);j(F),L(!1),U(new Set),w(new Set),S(k)},qt=(b,F=!1)=>{if(Ne.size)F=!1;if(L(!0),P(x),T(b),!F)S(b),U(new Set),w(new Set);rn.scrollToIndex(X.rowItem[b.row]??b.row,{align:"auto"}),Bt.scrollToIndex(b.column,{align:"auto"})},no=(b=k,F)=>{if(!d||Z||D||Q||z||h[b.column]?.generation==="autoIncrement")return;let M=m[b.row],re=h[b.column];if(!M||!re||re.type==="blob"||it(re))return;if(c.has(M.id))return;L(!0),P(x),E.current=!1;let G=re.type==="linkedRecord"?JSON.stringify(M.values[re.id]??[]):re.type==="relation"?Xl(M,re):re.type==="json"&&M.values[re.id]!=null?JSON.stringify(M.values[re.id]):et(M.values[re.id]);B({rowId:M.id,expectedVersion:M.version,field:re,originalText:G,text:re.type==="linkedRecord"||re.type==="relation"?G:F??G}),le(i.optimisticEdit?"":o("Unsaved changes")),ce(null),xe(null)},Wt=wn([]),Gt=wn([]),[Yt,oo]=yt(null),Wo=(b,F)=>{for(let M of b.items){if(M.op!=="update")continue;let re=F.items.find((G)=>G.id===M.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===M.id&&ne.expectedVersion===M.expectedVersion?{...ne,expectedVersion:re.version}:ne)}))}},Go=(b,F,M)=>{let re=b.items;if(!re.length)return null;let G=new Map(M.map((ne)=>[ne.id,ne])),V=[];if(re.every((ne)=>ne.op==="update")){let ne=new Map(F.items.map((we)=>[we.id,we]));for(let we of re){if(we.op!=="update")continue;let be=G.get(we.id);if(!be)return null;V.push({op:"update",id:we.id,expectedVersion:ne.get(we.id)?.version??we.expectedVersion+1,values:Object.fromEntries(Object.keys(we.values).map((Re)=>[Re,be.values[Re]??null]))})}}else if(re.every((ne)=>ne.op==="insert")){if(F.items.length!==re.length)return null;for(let ne of F.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 we=G.get(ne.id);if(!we)return null;V.push({op:"insert",values:Object.fromEntries(t.fields.filter((be)=>be.type!=="blob"&&be.type!=="linkedRecord"&&!it(be)&&be.generation!=="autoIncrement"&&we.values[be.id]!==void 0).map((be)=>[be.id,we.values[be.id]]))})}else return null;return{idempotencyKey:crypto.randomUUID(),items:V}},It=(b)=>{if(Z||e.readOnly||D||Q||z)return;let M=(b==="undo"?Wt:Gt).current.at(-1);if(!M)return;Ht({...M,idempotencyKey:crypto.randomUUID()},void 0,b)};async function Ht(b,F,M){if(Z||H.current||e.readOnly)return;let re=M&&Yt?Yt.before:m;if(M)oo({direction:M,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(M)(M==="undo"?Wt:Gt).current.pop();if(Wo(b,G.data),oo(null),V)if(M==="undo")Gt.current.push(V);else{if(Wt.current.push(V),Wt.current.length>30)Wt.current.shift();if(!M)Gt.current=[]}e.onCommitted(G.data),ce(null),B(null),fe(!1),xe(null);let ne=b.items.filter((be)=>be.op==="delete").length,we=M?o(M==="undo"?"Undone":"Redone"):ne>0&&ne===b.items.length?o("Deleted {count} records",{count:ne}):o("Saved");if(e.onNotify)le(""),e.onNotify(we);else le(we);f.current?.focus({preventScroll:!0}),F?.()}else{if(M){let ne=G.error.status;oo({direction:M,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,F,M,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:F,text:et(M),originalText:et(b.values[F.id])},V={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:b.id,expectedVersion:b.version,values:{[F.id]:M}}]};s((be)=>({...be,[b.id]:{...be[b.id],[F.id]:M}})),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}),E.current=!1,B(G),ce(V),le(ne.error.message);let we=ne.error.details;if(we?.current)xe(we.current)}async function Be(b){if(!D||E.current)return;let{field:F,rowId:M,expectedVersion:re}=D;if(F.generation==="autoIncrement"||t.fields.find((G)=>G.id===F.id)?.generation==="autoIncrement"){le(o("{name} is auto-generated and cannot be edited.",{name:F.name})),B(null);return}try{let G=F.type==="linkedRecord"?JSON.parse(D.text):F.type==="relation"?D.text||null:Cn(D.text,F);if(F.type==="linkedRecord"&&F.required&&Array.isArray(G)&&!G.length)throw Error(`${F.name} is required.`);if(i.optimisticEdit&&F.type==="linkedRecord"&&!z&&D.text===D.originalText){Jt();return}if(i.optimisticEdit&&F.type!=="linkedRecord"&&!z){let we=m.find((be)=>be.id===M);if(!we){B(null);return}if(JSON.stringify(G??null)===JSON.stringify(we.values[F.id]??null)){Jt();return}await fn(we,F,G,()=>{if(b)qt(gi(k,"Tab",m.length,h.length,b==="previous"))});return}let V={[F.id]:G},ne=z??{idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:M,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(F,D.text,"zh-CN"):null)||(G instanceof Error?G.message:o("Invalid value")))}}let In=Boolean(e.readOnly||Z||D||Q||z||Xn.length===0),Yo=()=>{if(In||!r)return;zn()},Jt=()=>{E.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,F,M)=>{if(!d||Z||D||Q||z)return;if(i.optimisticEdit){fn(b,F,M);return}B({rowId:b.id,expectedVersion:b.version,field:F,text:String(M),originalText:et(b.values[F.id])}),Ht({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:b.id,expectedVersion:b.version,values:{[F.id]:M}}]})},sn=i.optionChips,vr=Boolean(e.renderRecordContextMenu)||i.recordContextMenu,Yr=i.optimisticEdit&&!z?{onBlur:(b)=>{if(!b.currentTarget.contains(b.relatedTarget))Be()}}:{},Nt=D?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:D.field,text:D.text,disabled:Z||Boolean(e.readOnly),autoOpen:!0,onChange:An,onSave:(b)=>void Be(b),onCancel:Jt}):void 0,xr=i.optimisticEdit&&D?.field.type==="linkedRecord"&&(Nt===void 0||Nt===null)&&!z&&!Z?{onBlur:(b)=>{let F=b.relatedTarget;if(!F||ae.current?.contains(F)||F.closest('[role="gridcell"]')?.id===`wb-${D.rowId}-${D.field.id}`)return;Be()}}:{},xo=D&&(D.field.type==="singleSelect"||D.field.type==="multipleSelect")?Nt??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:Z,onChange:(b)=>An(D.field.type==="multipleSelect"?Array.from(b.currentTarget.selectedOptions,(F)=>F.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((F)=>F.id===b)).map((b)=>Y("option",{value:b,disabled:!0,children:o("{id} (unavailable)",{id:b})},b))]}):void 0,zn=()=>{if(!r||Z||D||Q||z||Pe.length===0)return;if(Pe.length>100){le(o("Select at most 100 rows per delete."));return}ce({idempotencyKey:crypto.randomUUID(),items:Pe.map((b)=>({op:"delete",id:b.id,expectedVersion:b.version}))}),fe(!0),le(""),xe(null)},ko=(b,F,M,re,G)=>{G.setPointerCapture(re);let V=(we)=>e.onViewChange({...n,columnWidths:{...n.columnWidths,[b]:Hr(M+we.clientX-F)}}),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)},[Po,kr]=yt(480);eg(()=>{if(!e.display?.fill)return;let b=()=>{let F=f.current?.getBoundingClientRect().top??0;kr(Math.max(240,Math.round(window.innerHeight-F-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 F=X.items[b.index];return F?.kind==="row"&&m[F.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&&Pe.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:Qn,variant:"outline",size:"sm",disabled:Z||Pe.length!==1,onClick:()=>{let b=Pe[0];if(b)e.onInspectRecord?.(b.id)},children:o("Open record activity")}),r&&Pe.length>0&&!e.renderRecordContextMenu&&!i.recordContextMenu&&Y(W,{ui:e.ui,style:Qn,variant:"outline",size:"sm",icon:"trash",disabled:In,onClick:zn,children:o("Delete selected rows")})]}),Y("style",{children:`
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:`
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&&Qe("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?Po: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||Q||z||!d||Z)return;if(b.preventDefault(),Ne.size){le(o("Expand all groups before pasting."));return}let F=Zl(b.clipboardData.getData("text/plain"),m,h,{row:ot.firstRow,column:ot.firstColumn},e.locale);if(!F.ok){le(F.message);return}ce({idempotencyKey:crypto.randomUUID(),items:F.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 F=b.key.toLowerCase();if(F==="d"||F==="r"){b.preventDefault();let M=F==="d"?{...ot,lastRow:ot.firstRow}:{...ot,lastColumn:ot.firstColumn};hr(M,ot);return}if(F==="z"||F==="y"){b.preventDefault(),It(F==="y"||b.shiftKey?"redo":"undo");return}}if(!D&&b.key==="Escape"){U(new Set),w(new Set);return}if(D||!m.length||!h.length||Z)return;if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End"].includes(b.key)){b.preventDefault();let F=b.key==="Tab"&&b.shiftKey,M=gi(k,b.key,m.length,h.length,F);if(oe(M.row)){let re=b.key==="ArrowUp"||F||M.row<k.row,G=ui(X,M.row,re?-1:1,m.length);if(G<0)return;M={...M,row:G}}qt(M,b.shiftKey&&b.key!=="Tab")}else if(oe(k.row))b.preventDefault();else if(b.key==="Delete"&&Pe.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:Pe.length}),style:{position:"relative",display:"flex",alignItems:"center"},children:[Pe.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=Pe.length>0&&Pe.length<m.filter((F,M)=>!oe(M)).length},style:Pe.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:Pe.length>0&&Pe.length===m.filter((b,F)=>!oe(F)).length,disabled:Boolean(D||Z||Q||z),onChange:(b)=>{L(!1),P(x),w(new Set),U(b.currentTarget.checked?new Set(m.filter((F,M)=>!oe(M)).map((F)=>F.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 F=h[b.index];if(!F)return null;let M=zi(n.columnColors?.[F.id]),re=n.sort?.find((be)=>be.fieldId===F.id),G=i.sorting&&F.type!=="linkedRecord"&&cn(F),V=e.fieldMenu?.(F)??[],ne=V.length?e.ui?.DropdownMenu?e.ui.DropdownMenu({label:o("Field menu {name}",{name:F.name}),icon:Y(Ce,{name:"chevronDown"}),items:V}):Y(_i,{label:o("Field menu {name}",{name:F.name}),icon:Y(Ce,{name:"chevronDown"}),items:V},F.id):null,we=Y(mg,{id:F.id,disabled:!i.columnReorder,children:(be)=>lt("div",{ref:be.setNodeRef,...be.listeners,role:"columnheader","data-uibot-field":F.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:M?.background??"var(--muted, #f4f6f8)",borderTopWidth:M?3:void 0,borderTopStyle:M?"solid":void 0,borderTopColor:M?.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??[],F.id)}),children:[i.fieldTypeIcons&&Y(Vi,{type:F.type}),i.fieldTypeIcons?Y("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:F.name}):F.name,F.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:F.name}),style:{border:0,background:"transparent",position:"absolute",top:0,bottom:0,right:-3,width:7,padding:0,cursor:"col-resize",zIndex:2},onPointerDown:(Re)=>{Re.stopPropagation(),ko(F.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,[F.id]:Hr(b.size+(Re.key==="ArrowRight"?20:-20))}})}})]})},F.id);return V.length&&e.ui?.ContextMenu?Y(e.ui.ContextMenu,{items:V,"aria-label":o("Field menu {name}",{name:F.name}),children:we},F.id):we}),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 F=X.items[b.index];if(F?.kind==="group"){let G=F.label===null?o("Not set"):F.label==="true"?o("Checked"):F.label==="false"?o("Unchecked"):F.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":!F.collapsed,"aria-label":o(F.collapsed?"Expand group {name}":"Collapse group {name}",{name:G}),disabled:!i.groupCollapse,onClick:()=>Rn(F.raw),style:{position:"sticky",left:10,display:"inline-flex",alignItems:"center",gap:8,height:"100%",padding:0,border:0,background:"transparent",color:"inherit",fontSize:12,cursor:i.groupCollapse?"pointer":"default"},children:[i.groupCollapse&&Y("span",{"aria-hidden":"true",style:{width:10,fontSize:10,opacity:0.6},children:F.collapsed?"▸":"▾"}),Y($a,{index:F.colorIndex,children:G}),Y("span",{style:{opacity:0.6},children:o("{count} records",{count:F.count})})]})},F.key)}let M=F?m[F.index]:void 0;if(F?.kind!=="row"||!M)return null;let re=F.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(M.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(M.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(M.id))qt({row:re,column:0})},children:[Y("span",{"data-uibot-row-number":"",style:{opacity:Ut.has(M.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(M.id)?1:0},children:[Y("input",{type:"checkbox","aria-label":o("Select row"),checked:Ut.has(M.id),disabled:Boolean(D||Z||Q||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?.(M),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(M.id))qt({row:re,column:0})},children:Y("input",{"aria-label":o("Record ID {id}",{id:M.id}),readOnly:!0,value:M.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},we=Ut.has(M.id)&&(N.has(M.id)||A&&ne.column>=ot.firstColumn&&ne.column<=ot.lastColumn),be=D?.rowId===M.id&&D.field.id===V.id,Re=!be&&V.type==="checkbox"?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:V,text:et(M.values[V.id]),disabled:Boolean(!d||Z||D||Q||z),mode:"inline",autoOpen:!1,onChange:(he)=>{if(!d||Z||D||Q||z)return;try{let Ue=Cn(he,V);B({rowId:M.id,expectedVersion:M.version,field:V,text:he,originalText:et(M.values[V.id])}),Ht({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:M.id,expectedVersion:M.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-${M.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":we,"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}:{},...wt>1&&!be&&(V.type==="singleLineText"||V.type==="longText")?{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:wt,whiteSpace:"normal",wordBreak:"break-word",padding:sn?"6px 10px":7}:{},background:we?"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(M.id)&&(N.has(M.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&&Nt!==void 0&&Nt!==null?Nt: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:M.linkedRecords?.[V.id],disabled:Z,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:Z||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"?Mo(M,V):V.type==="lookup"?so(M.values[V.id]):V.type==="formula"||V.type==="rollup"?tr(M.values[V.id],M.computedErrors?.[V.id]):V.type==="checkbox"&&Re!==void 0&&Re!==null?Re:V.type==="checkbox"&&sn?Y(Vs,{checked:M.values[V.id]===!0,label:o("Edit {name}",{name:V.name}),onToggle:!d||Z||D||Q||z||V.generation==="autoIncrement"?void 0:()=>Cr(M,V,M.values[V.id]!==!0)}):V.type==="checkbox"?Y("input",{type:"checkbox","aria-label":o("Edit {name}",{name:V.name}),checked:M.values[V.id]===!0,ref:(he)=>{if(he)he.indeterminate=M.values[V.id]==null},disabled:!d||Z||Boolean(D)||Boolean(Q)||Boolean(z)||V.generation==="autoIncrement",onMouseDown:(he)=>he.stopPropagation(),onKeyDown:(he)=>he.stopPropagation(),onChange:(he)=>{if(!d||Z||D||Q||z)return;let Ue=he.currentTarget.checked;B({rowId:M.id,expectedVersion:M.version,field:V,text:String(Ue),originalText:et(M.values[V.id])}),Ht({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:M.id,expectedVersion:M.version,values:{[V.id]:Ue}}]})}}):V.type==="date"?Y("span",{title:et(M.values[V.id]),style:sn?{opacity:0.75,fontVariantNumeric:"tabular-nums"}:void 0,children:(()=>{let he=Ft(V);return he?$n(M.values[V.id],he):pi(M.values[V.id])})()}):V.type==="number"&&sn?Y("span",{style:{display:"block",width:"100%",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:(()=>{let he=Eo(V);return he?To(M.values[V.id],he):et(M.values[V.id])})()}):sn&&V.type==="singleSelect"&&M.values[V.id]!=null?Y(qo,{ids:[M.values[V.id]],field:V,wrap:wt>1}):sn&&V.type==="multipleSelect"&&Array.isArray(M.values[V.id])?Y(qo,{ids:M.values[V.id],field:V,wrap:wt>1}):V.type==="hyperlink"?Y(bi,{value:M.values[V.id]}):V.type==="singleSelect"?V.options?.find((he)=>he.id===M.values[V.id])?.name??et(M.values[V.id]):V.type==="multipleSelect"&&Array.isArray(M.values[V.id])?M.values[V.id].map((he)=>V.options?.find((Ue)=>Ue.id===he)?.name??String(he)).join(", "):et(M.values[V.id])]},V.id)})]},M.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&&Nt!==void 0&&Nt!==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"&&!Z)b.preventDefault(),b.stopPropagation(),Jt()},children:[!Jo&&D.field.type!=="linkedRecord"&&(Nt??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:Z,onChange:An}):Y(ba,{field:D.field,text:D.text,disabled:Z||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:Z,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:Qn,variant:"outline",size:"sm",disabled:Z,onClick:()=>void Be(),children:Z?o("Saving…"):o("Save edit")}),Y(W,{ui:e.ui,style:Qn,variant:"outline",size:"sm",disabled:Z,onClick:Jt,children:o("Cancel edit")})]}),Q&&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:Z?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:Z,onConfirm:()=>void Ht(z),onCancel:()=>{fe(!1),ce(null),xe(null)}}):null,Q&&z&&!e.ui?.ConfirmDialog&&lt(hi,{label:o("Confirm bulk change"),busy:Z,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:Qn,variant:"outline",size:"sm",disabled:Z,onClick:()=>void Ht(z),children:Z?o("Saving…"):o("Confirm changes")})," ",Y(W,{ui:e.ui,style:Qn,variant:"outline",size:"sm",disabled:Z,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:[!Z&&te&&Y("p",{role:"alert",children:te}),Y(W,{ui:e.ui,style:Qn,variant:"outline",size:"sm",disabled:Z||Boolean(e.readOnly),onClick:()=>void Ht(z,void 0,Yt.direction),children:o("Retry undo/redo")})," ",Yt.rejected&&Y(W,{ui:e.ui,style:Qn,variant:"outline",size:"sm",disabled:Z,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(([F,M])=>{let re=t.fields.find((V)=>V.id===F),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??F}),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(M)}),Y("dt",{children:o("Server value")}),Y("dd",{style:{margin:0,whiteSpace:"pre-wrap"},children:G(ve.values[F])})]})]},F)}):[])}),Y(W,{ui:e.ui,style:Qn,variant:"outline",size:"sm",disabled:Z,onClick:()=>{if(!z)return;let b=z.items.map((F)=>F.op!=="insert"&&F.id===ve.id?{...F,expectedVersion:ve.version}:F);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||Z?8:0},children:Z?o("Saving…"):Yt?"":te})]}),$i=t.fields.filter((b)=>b.type!=="blob"&&b.type!=="linkedRecord"&&!it(b)&&b.generation!=="autoIncrement"),wo=()=>{if(!l||In||Pe.length===0||Pe.length>100)return;Ht({idempotencyKey:crypto.randomUUID(),items:Pe.map((b)=>({op:"insert",values:Object.fromEntries($i.flatMap((F)=>b.values[F.id]===void 0?[]:[[F.id,b.values[F.id]]]))}))})};if(e.renderRecordContextMenu){let b=Pe.length===1?Pe[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:wo}:{}})}if(!i.recordContextMenu)return ro;let Pr=[...e.onExpandRecord&&Pe.length===1?[{id:"expand",icon:Y(Ce,{name:"expand"}),label:o("Expand record"),onSelect:()=>{let b=Pe[0];if(b)e.onExpandRecord?.(b)}}]:[],...l?[{id:"duplicate",icon:Y(Ce,{name:"copy"}),label:o("Duplicate {count} selected records",{count:Pe.length}),disabled:In||Pe.length===0,onSelect:wo}]:[],{id:"copy",separatorBefore:!0,icon:Y(Ce,{name:"copy"}),label:o("Copy cells"),disabled:Pe.length===0,onSelect:()=>{navigator.clipboard?.writeText($o())}},...r?[{id:"delete",icon:Y(Ce,{name:"trash"}),label:o("Delete {count} selected records",{count:Pe.length}),separatorBefore:!0,destructive:!0,disabled:In,onSelect:Yo}]:[]],So=e.ui?.ContextMenu;return So?Y(So,{items:Pr,"aria-label":o("Record actions"),children:ro}):Y(Ui,{block:!0,items:Pr,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=(P,f,R)=>{let S={...p.footerStats??{}};if(f)S[P]=f;else if(R)S[P]="none";else delete S[P];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
+ `}),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:`
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((P)=>{let f=a[P.index];if(!f)return null;let R=P.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,N=(T)=>T===null?"":typeof T==="number"&&A!=="count"&&A!=="filled"&&A!=="empty"?Nn(Math.round(T*100)/100,f):typeof T==="number"?T.toLocaleString(i):Nn(T,f),U=N(L),J=!t?L:A==="count"?d:x.values[`footer${P.index}`]??null,w=!A?"":!t||A==="count"?N(J):x.status==="loading"?"…":x.status==="error"||J===null?"—":N(J),I=A?A==="count"&&R?r("Footer record count",{count:w}):`${r(`Footer ${A}`)} ${w}`.trim():r("Auto summary"),k=P.index<c;return Y("div",{"data-uibot-footer-cell":"",style:{position:"absolute",left:k?g(P.index):P.start,width:P.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 Pg,useSortable as wg,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:Pg})),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(),P=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:P.map((f)=>f.id),strategy:Sg,disabled:Boolean(C),children:ho("div",{style:{display:"grid",gap:2,maxHeight:320,overflowY:"auto"},children:[P.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)}),P.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}=wg({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)=>wr.has(t.type)&&!it(t)&&t.generation!=="autoIncrement")}var qi=(e)=>e===null||e===void 0||e===""||Array.isArray(e)&&e.length===0,Fg=(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 Eg(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?Eg(p,g):void 0;if(!p||h===void 0||d.has(m)||Fg(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 Mg=[{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)"},Tt={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"}},Kr=(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 Pd(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([]),[P,f]=zt(""),[R,S]=zt("idle"),[A,L]=zt(),[N,U]=zt(new Set),[J,w]=zt(""),[I,k]=zt(""),[T,D]=zt(!1),[B,E]=zt(),[H,z]=zt([]),[ce,Q]=zt(),fe=xd(null),Z=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(()=>{Z.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,Ne=async(K,ye)=>{let Le=new AbortController;fe.current=Le,S("running"),k("");let Ae=[...ye],nt=[],St=[],Ct="",We=$r(K,cl);E({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),...P?{model:P}:{}},{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;E({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))),w(St.join(`
26
- `)),S("review")},j=async()=>{let K=new AbortController;fe.current=K,S("running"),k(""),Q(void 0),L(void 0),E(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 Ne(ye,[])},v=async()=>{if(!B?.failed.length)return;await Ne(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)=>N.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)Q({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),E(void 0),S("idle")},wt=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")),Q(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:Z,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:Mg.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:P,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 wt(),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:Pt.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(N.size===A.changes.length?new Set:new Set(A.changes.map((K)=>K.key))),children:N.size===A.changes.length?r("Select none"):r("Select all")})]}),J&&$e("p",{style:{margin:0,fontSize:12,color:Pt.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=Nn(Ae.before,nt);return bt("label",{style:Tt.change,children:[$e("input",{type:"checkbox",checked:N.has(Ae.key),"aria-label":`${nt.name} ${K}`,onChange:()=>U(new Set(ht([...N],Ae.key)))}),bt("span",{style:{display:"grid",gap:2},children:[$e("span",{style:{fontSize:12,color:Pt.faint},children:nt.name}),St&&$e("span",{style:Tt.before,children:St}),$e("span",{style:Tt.after,children:Nn(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:Pt.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||N.size===0,onClick:()=>void tt(),children:r("Apply {count} changes",{count:N.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 wd,useLayoutEffect as Ng,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 Ng(()=>{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]),wd(()=>{let a=requestAnimationFrame(()=>t.current?.querySelector("input:not([disabled])")?.select());return()=>cancelAnimationFrame(a)},[]),wd(()=>{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 Me,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]=Ee({loading:!0}),[i,r]=Ee(0);return Mt(()=>{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 Kv(e){let{client:t,requestApproval:n}=e,o=on(()=>{}),i=Zn(()=>{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=Zn(()=>{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=Zn(()=>e.getRelationOptions??od(i,()=>l.current),[e.getRelationOptions,i]),a=se(e.locale),s=Zn(()=>Dt({preset:"full",...e.features}),[e.features]),u=e.pageSize??50,c=Wr(()=>i.list(),[i]);l.current=c.data??[];let[g,p]=Ee(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},[]),P=e.onTableChange,f=hl((y)=>{if(!C({tableId:y}))return!1;return p(y),P?.(y),!0},[P,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,N=S.write&&s.rowUpdate,U=S.write&&s.rowDelete,J=(S.views??S.schema)&&s.viewManagement,w=Boolean(m&&c.data?.some((y)=>y.id===m)),I=Wr(()=>m&&w?i.describe(m):void 0,[i,m,w]),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]=Ee([]),[E,H]=Ee(""),z=e.viewId??E,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[Q,fe]=Ee(),Z=Q?.client===t&&Q.tableId===m,q=Z&&Q.snapshot===T.data,[te,le]=Ee({});Mt(()=>{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(Z&&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;Mt(()=>{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=Zn(()=>{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]);Mt(()=>{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 Ne=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);Mt(()=>{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]=Ee({recordIds:[],fieldIds:[]}),[wt,rn]=Ee(!1),[ht,K]=Ee(!1),[ye,Le]=Ee(null);Mt(()=>{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]),Mt(()=>{tt({recordIds:[],fieldIds:[]}),rn(!1)},[m]);let Ae=Zn(()=>{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]=Ee(null),[Oe,an]=Ee(!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,Mt(()=>{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")},Pe=(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(!Ne)st(a("View saved"));O?.(de)})},Xn=Ne&&St&&J&&!Oe&&!We?.error&&!!v?.name.trim();Mt(()=>{if(!Xn||!v)return;let y=setTimeout(()=>Pe(v),600);return()=>clearTimeout(y)},[Xn,v]);let[Ut,_n]=Ee(""),$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]=Ee(0),[Co,vo]=Ee(null),to=Ne&&Co&&Co.viewId===v?.id?Co.text:v?.search??"",hr=(y)=>{if(Ne&&v)vo({viewId:v.id,text:y});else if(v)dt({...v,search:y})},jo=Zn(()=>({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]=Ee({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:[];Mt(()=>{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]=Ee("");Mt(()=>{In(""),K(!1)},[t,m,z]);let Yo={...e.schemaSettings,ai:Boolean(e.aiFillClient)&&e.schemaSettings?.ai!==!1},[Jt,An]=Ee(!1),[Cr,sn]=Ee(""),[vr,Yr]=Ee(""),[Nt,xr]=Ee(""),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]},[Po,kr]=Ee(""),[yn,Jo]=Ee([]),ro=Zn(()=>[{fn:"count",as:"records"},...Nt?[{fn:"sum",fieldId:Nt,as:"sum"}]:[]],[Nt]),$i=Zn(()=>{let y=se(e.locale),O=k?.fields.find((ee)=>ee.id===Nt);return{records:y("Records"),...O?{sum:y("Sum of {name}",{name:O.name})}:{}}},[e.locale,k,Nt]);Mt(()=>xr(""),[m]);let[wo,Pr]=Ee([]),[So,b]=Ee(""),[F,M]=Ee(),re=(y)=>{M(y),Pr(structuredClone(k?.fields??[])),b(k?.name??""),Dn("schema")},G=Be==="schema"&&(!br(wo,k?.fields)||So!==(k?.name??"")),V=Be==="create"&&(Po.trim()!==""||!br(yn,[{id:"name",name:a("Name"),type:"singleLineText",required:!0}])),[ne,we]=Ee(!1),[be,Re]=Ee(!1),he=on(null),Ue=on(null),Dn=(y)=>{if(document.activeElement instanceof HTMLElement)Ue.current=document.activeElement;In(y)},Fn=()=>{K(!1),In("");let y=Ue.current;if(Ue.current=null,y)requestAnimationFrame(()=>y.isConnected&&y.focus())};Mt(()=>{if(!Be)return;let y=requestAnimationFrame(()=>he.current?.querySelector("[data-uibot-panel] input:not([disabled]), [data-uibot-panel] textarea:not([disabled])")?.focus());return()=>cancelAnimationFrame(y)},[Be]),Mt(()=>{if(Be!=="add"&&Be!=="record")we(!1),Re(!1)},[Be]);let io=()=>{if(G||V||(Be==="add"||Be==="record")&&ne)K(!0);else Fn()},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=Fl(),Ad=(Be==="add"||Be==="record")&&ne,Dd=(Be==="add"||Be==="record")&&be,Fd=St||G||V||ji.dirty||Ad,Ed=Oe||ji.busy||Dd;En({dirty:Fd,busy:Ed},e);let Cl=()=>{if(!Po.trim()||yn.length===0)return;ln(()=>{let y={name:Po.trim(),fields:yn};return i.create({...y,idempotencyKey:zn("create",y)})},(y,O)=>{if(ko("create"),c.reload(),!O)return;Fn(),f(y.id)})},vl=()=>void Qo({fields:wo,name:So.trim()}).then(()=>{Fn(),st(a("Fields saved"))}).catch((y)=>st(y instanceof Error?y.message:String(y),!0)),Qo=(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]=Ee(""),[ao,Gi]=Ee("");Mt(()=>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]=Ee(null),[kl,Qr]=Ee(""),[Zr,Pl]=Ee(null);Mt(()=>{if(!Zr||!v||T.loading)return;if(!k?.fields.some((y)=>y.id===Zr.fieldId))return;Pl(null),dt({...v,columnOrder:Zr.order})},[Zr,k,v,T.loading]),Mt(()=>Ro(null),[m]);let wl=(y)=>{let O=k?.fields.find((ee)=>ee.id===y);if(!O)return;Qr(""),Ro({draft:structuredClone(O),initial:O,isNew:!1})},Xr=(y)=>{let O={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:a("New field"),type:"singleLineText"};Qr(""),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 Qr(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;Qo({fields:O}).then(()=>{if(ee)Pl({fieldId:y.id,order:ee});Ro(null),st(a(ie?"Field added":"Field saved"))}).catch((de)=>Qr(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),Qo({fields:ee}).then(()=>st(a("Field duplicated"))).catch((ie)=>st(ie instanceof Error?ie.message:String(ie),!0))},Md=()=>{let y=Ki;if(Wi(""),!k||!y)return;Qo({fields:k.fields.filter((O)=>O.id!==y)}).then(()=>st(a("Field deleted"))).catch((O)=>st(O instanceof Error?O.message:String(O),!0))},Nd=(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:()=>wl(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&&N)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 Me("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}),Me("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"&&Me("fieldset",{disabled:Oe,style:ge.fieldset,"data-uibot-panel":"settings",onKeyDown:Jr(),children:[Me("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}}),Me("div",{style:ge.actions,children:[_(W,{ui:e.ui,style:ge.button,variant:"default",disabled:!St||!v.name.trim()||!J,onClick:()=>Pe(v),children:a("Save view")}),_(W,{ui:e.ui,style:ge.button,onClick:Fn,children:a("Done")})]})]}),Od=k&&Be==="schema"&&Me("fieldset",{disabled:Oe,style:ge.fieldset,"data-uibot-panel":"schema",onKeyDown:Jr(vl),children:[Me("label",{children:[a("Table title")," ",_("input",{"aria-label":a("Table title"),value:So,onChange:(y)=>b(y.currentTarget.value)})]}),_(qr,{fields:wo,...F?{focusFieldId:F}:{},onChange:Pr,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}:{}}),Me("div",{style:e.renderPanel?ge.stickyFooter:ge.actions,children:[_(W,{ui:e.ui,style:ge.button,variant:"default",disabled:!G||wo.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:Fn}):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:Nd}:{},...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=Me("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}:{}}),Me("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||N||U,onRename:(y)=>Qo({name:y}),onIconChange:(y)=>Qo({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:Fn,onCancel:()=>K(!1)}):null,ht&&!e.ui?.ConfirmDialog&&Me("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:Fn,children:a("Discard")}),_(W,{ui:e.ui,style:ge.button,onClick:()=>K(!1),children:a("Keep editing")})]}),Be==="create"?Me("fieldset",{disabled:Oe,style:ge.fieldset,"data-uibot-panel":"create",onKeyDown:Jr(Cl),children:[Me("label",{children:[a("Table name")," ",_("input",{"aria-label":a("Table name"),value:Po,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,Me("div",{style:ge.actions,children:[_(W,{ui:e.ui,style:ge.button,variant:"default",disabled:!Po.trim()||yn.length===0,onClick:Cl,children:a("Create table")}),_(W,{ui:e.ui,style:ge.button,onClick:io,children:a("Cancel")})]})]}):k&&v?Me(Gr,{children:[Me("div",{style:e.inlineViewControls?{display:"grid",gridTemplateColumns:"minmax(0, 1fr)",gap:8,minWidth:0}:ge.bar,children:[_(Za,{views:Ct,activeId:v.id,dirty:St&&!Ne,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)Pe({...ee,name:O.trim()})},onDuplicate:(y)=>{let O=Ct.find((ee)=>ee.id===y);if(O)Pe({...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:Me("div",{style:{...ge.actions,justifyContent:"space-between"},children:[Me("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&&N&&_(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}})]}),Me("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(),wl(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:Me("div",{"data-uibot-view-config":"",style:{display:"grid",gap:10,minWidth:0},children:[Me("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})]})]})}):Me("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"?Fn():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:()=>Pe(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&&N&&_(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?Me("div",{style:ge.actions,children:[_(W,{ui:e.ui,style:ge.button,onClick:()=>rn(!wt),children:a("Relations")}),wt?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:Md,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&&Me("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:we,onBusyChange:Re,onCommitted:()=>fn(),onSaved:(y)=>{Fn();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:Fn,onCancel:io,onDirtyChange:we,onBusyChange:Re,stickyActions:Boolean(e.renderPanel)},Yi.id):null),Go&&Ji?It.error?Me("p",{role:"alert",children:[It.error," ",_(W,{ui:e.ui,style:ge.button,onClick:It.reload,children:a("Reload records")})]}):Me(Gr,{children:[It.loading&&_("p",{role:"status",children:a("Loading records…")}),_(gd,{...Ji},`${m}:${z}:${k.schemaVersion}:${Ko}:${Gt??""}`),r&&!s.footerStats?Me("div",{style:ge.actions,children:[_(Je,{ui:e.ui,label:a("Sum field"),style:ge.button,value:Nt,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&&!w?_("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…")}):Me("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&&N?_(Pd,{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:Me("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,Me("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?Me("aside",{style:ge.side,children:[e.sidePanel,e.renderSidePanel?.({table:k,view:v,selection:oe,rows:It.data?.items??[],reload:fn})]}):null]});return _(Zi.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 Me(Gr,{children:[s==="main"&&Me(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:_(Mi,{...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:_(Ni,{...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{Kv as PagedCollectionWorkspace};
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};