@uibot/renderer-react 0.19.0 → 0.20.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 Hi,useCallback as Ki,useContext as Gi,useLayoutEffect as ir,useMemo as Wi,useRef as go,useState as Yi}from"react";var Ji=Hi(void 0);function $t(e,t={}){let n=Gi(Ji),r=go({}),{dirty:o,busy:i}=e,{onDirtyChange:a,onBusyChange:d}=t;ir(()=>{n?.(r.current,{dirty:o,busy:i}),a?.(o),d?.(i)},[n,o,i,a,d]),ir(()=>()=>{n?.(r.current),a?.(!1),d?.(!1)},[n,a,d])}function Qs(){let e=go(new Map),[t,n]=Yi({dirty:!1,busy:!1}),r=Ki((o,i)=>{if(i)e.current.set(o,i);else e.current.delete(o);let a=[...e.current.values()],d=a.some((p)=>p.dirty),l=a.some((p)=>p.busy);n((p)=>p.dirty===d&&p.busy===l?p:{dirty:d,busy:l})},[]);return{...t,report:r}}function mo(e,t){let n=Wi(()=>({active:!0,client:e,id:t}),[e,t]);return ir(()=>(n.active=!0,()=>{n.active=!1}),[n]),n}import{useEffect as it,useLayoutEffect as Ls,useMemo as rt,useRef as ot,useState as Le}from"react";import{DndContext as Os,PointerSensor as Vs,useDraggable as Bs,useSensor as _s,useSensors as Us}from"@dnd-kit/core";import{defaultRangeExtractor as qs,useVirtualizer as Ni}from"@tanstack/react-virtual";function el(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var Pn=["blue","green","red","orange","gray","teal","purple"];function Zi(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 fo(e,t,n){if(!t?.length)return[];return t.map((r)=>{if(r.fn==="count")return{fieldId:r.fieldId,fn:"count",value:e.length};let o=n.find((d)=>d.id===r.fieldId),a=o?.type==="number"||o?.type==="rating"||o?.type==="autoNumber"?e.reduce((d,l)=>d+(Zi(l.values[r.fieldId])??0),0):0;return{fieldId:r.fieldId,fn:"sum",value:a}})}function yo(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function Qi(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function Xi(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 bo(e,t){if(!t)return!0;if(yo(t)){let n=t.filterSet.map((r)=>yo(r)?bo(e,r):Qi(r)?Xi(e,r):!1);return t.conjunction==="or"?n.some(Boolean):n.every(Boolean)}return Object.entries(t).every(([n,r])=>{if(n==="conjunction"||n==="filterSet")return!0;return e.values[n]===r})}function ho(e,t,n,r){let o=e.views.find((C)=>C.id===n)??e.views[0];if(!o)return{view:{id:n,name:n,kind:"table"},columns:e.fields,rows:[...t]};let i=[...t];if(o.filter)i=i.filter((C)=>bo(C,o.filter));if(o.sort?.length)i.sort((C,b)=>{for(let x of o.sort??[]){let P=C.values[x.fieldId],m=b.values[x.fieldId];if(P===m)continue;if(P==null)return 1;if(m==null)return-1;let k=e.fields.find((O)=>O.id===x.fieldId)?.type,y=(O)=>{if(["number","rating","autoNumber"].includes(k??"")&&typeof O==="number")return O;if(["date","createdTime","lastModifiedTime"].includes(k??"")){let T=Date.parse(String(O));if(Number.isFinite(T))return T}return String(O)},I=y(P),F=y(m);if(I===F)continue;let E=I<F?-1:1;return x.direction==="desc"?-E:E}return C.id<b.id?-1:C.id===b.id?0:1});let a=o.projection?.length?e.fields.filter((C)=>o.projection?.includes(C.id)):e.fields,d=r?.search?.trim().toLowerCase();if(d)i=i.filter((C)=>a.some((b)=>String(C.values[b.id]??"").toLowerCase().includes(d)));let l=fo(i,o.aggregates,e.fields),p=o.group?.fieldId;if(!p)return{view:o,columns:a,rows:i,...l.length?{aggregates:l}:{}};let u=[],c=new Map;for(let C of i){let b=String(C.values[p]??"");if(!c.has(b))c.set(b,[]),u.push(b);c.get(b)?.push(C)}let g=u.map((C)=>{let b=c.get(C)??[];return{key:C,fieldId:p,rows:b,aggregates:fo(b,o.aggregates,e.fields)}});return{view:o,columns:a,rows:i,groups:g,...l.length?{aggregates:l}:{}}}var ea=500,ta=2000,na=new Set(["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"]);function Fe(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function Ft(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 cl=["short","medium","tall","extra"];function ul(e,t){return t.map((n)=>{let r={},o={};for(let i of e.groupBy){let a=n[i];if(!(i in n)||a!==null&&typeof a!=="string"&&typeof a!=="number"&&typeof a!=="boolean")throw Error(`Invalid aggregate group ${i}.`);r[i]=a}for(let{as:i,fn:a}of e.aggregates){let d=n[i];if(!(i in n)||d!==null&&!(typeof d==="number"&&Number.isFinite(d))&&!((a==="min"||a==="max")&&typeof d==="string"&&Number.isFinite(Date.parse(d))))throw Error(`Invalid aggregate value ${i}.`);o[i]=d}return{groups:r,values:o}})}var ra=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,oa=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function Rn(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function $e(e,t){return{code:e,...t}}function ia(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function ar(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function Sn(e,t){if(t.aggregates.length===0)return $e("empty");if(t.aggregates.length>8||t.groupBy.length>3)return $e("too_many");let n=new Set;for(let o of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(o.fn))return $e("function");if(!ra.test(o.as)||n.has(o.as)||t.groupBy.includes(o.as))return $e("alias",{alias:o.as,...o.fieldId!==void 0?{fieldId:o.fieldId}:{}});if(n.add(o.as),o.fn==="count"&&o.fieldId===void 0)continue;let i=e.fields.find((a)=>a.id===o.fieldId);if(!i)return $e(o.fn==="sum"?"sum_field":"unknown_field",{alias:o.as,...o.fieldId!==void 0?{fieldId:o.fieldId}:{}});if(o.fn==="sum"&&!ar(i))return $e("sum_field",{fieldId:i.id,alias:o.as});if(o.fn==="avg"&&!ar(i))return $e("numeric_field",{fieldId:i.id,alias:o.as});if((o.fn==="min"||o.fn==="max")&&!ar(i)&&i.type!=="date"&&!((i.type==="formula"||i.type==="rollup")&&i.resultType==="date"))return $e("extrema_field",{fieldId:i.id,alias:o.as});if((o.fn==="filled"||o.fn==="empty")&&!Ft(i))return $e("queryable_field",{fieldId:i.id,alias:o.as});if(o.fn==="count"&&!Ft(i))return $e("count_field",{fieldId:i.id,alias:o.as})}let r=new Set;for(let o of t.groupBy){if(r.has(o))return $e("duplicate_group",{fieldId:o});r.add(o);let i=e.fields.find((a)=>a.id===o);if(!i)return $e("unknown_field",{fieldId:o});if(!oa.has(i.type)&&!ia(i))return $e("not_groupable",{fieldId:o})}return null}var Co=(e)=>String(e).padStart(2,"0");function lt(e,t){let n=new Intl.DateTimeFormat("en-CA",{...t?{timeZone:t}:{},year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(e),r=(o)=>Number(n.find((i)=>i.type===o)?.value??0);return{year:r("year"),month:r("month"),day:r("day"),hour:r("hour"),minute:r("minute"),second:r("second")}}function wt(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 r=n;for(let o=0;o<2;o++){let i=lt(new Date(r),t),a=Date.UTC(i.year,i.month-1,i.day,i.hour,i.minute,i.second);r+=n-a}return new Date(r)}function In(e,t){let n=lt(e,t??"UTC");return`${n.year}-${Co(n.month)}-${Co(n.day)}`}var aa=/^[a-z][a-z0-9_-]{0,31}$/,An=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function xo(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 sa(e){if(!An(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"||!xo(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(!An(t)||Object.keys(t).length!==2||typeof t.kind!=="string"||!aa.test(t.kind)||typeof t.id!=="string"||!t.id||t.id.length>200)return"hyperlink reference is invalid"}return null}var Ht=(e)=>sa(e)===null;function sn(e){if(!An(e)||typeof e.url!=="string")return"";return typeof e.text==="string"&&e.text.trim()?e.text:e.url}function vo(e){if(!An(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 Mt(e){let t=e.trim();if(!t)return null;if(t.startsWith("{"))try{let i=JSON.parse(t);return Ht(i)?i:null}catch{return null}let n=/^\[([^\]]*)\]\((\S+)\)$/.exec(t)??/^(.*?)\s*<(\S+)>$/.exec(t),r=n?.[1]?.trim().slice(0,500)??"",o=n?.[2]??t;if(!/^[a-z][a-z0-9+.-]*:/i.test(o)&&!o.startsWith("/")){if(/^[\w-]+(\.[\w-]+)+(:\d+)?([/?#]\S*)?$/.test(o))o=`https://${o}`;else if(/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(o))o=`mailto:${o}`}if(!xo(o))return null;return r&&r!==o?{url:o,text:r}:{url:o}}function ko(e,t=new Date,n){let r={};for(let o of e){let i=o.defaultValue;if(!i)continue;if(i.kind==="value")r[o.id]=Array.isArray(i.value)?[...i.value]:i.value;else if(o.type==="date"){let a=o.formatting;if(a&&"time"in a&&a.time==="none"){let d=lt(t,n);r[o.id]=`${d.year}-${String(d.month).padStart(2,"0")}-${String(d.day).padStart(2,"0")}`}else r[o.id]=t.toISOString()}}return r}var la=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],da=new Set(["pastDays","nextDays","daysAgo","daysFromNow"]),wo={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"]},ca=new Set(["isEmpty","isNotEmpty"]);function Po(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 vl(e){let t=Po(e);return t?wo[t]:[]}var sr=/^\d{4}-\d{2}-\d{2}$/,ua=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function pa(e){if(!ua(e))return!1;let t=e.mode;if(!la.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&&sr.test(e.date);if(t==="dateRange")return typeof e.date==="string"&&sr.test(e.date)&&typeof e.to==="string"&&sr.test(e.to)&&e.date<=e.to;if(da.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function kl(e,t){if(!e)return"unknown field";let n=Po(e),r=t.operator==="contains"&&(n==="number"||n==="checkbox"||n==="date"||n==="singleSelect");if(!n||!(wo[n].includes(t.operator)||r))return"operator not allowed";if(ca.has(t.operator))return null;let o=t.value;if(r)return n==="number"?typeof o==="number"&&Number.isFinite(o)?null:"number required":n==="checkbox"?typeof o==="boolean"?null:"boolean required":typeof o==="string"?null:"text required";switch(n){case"text":return typeof o==="string"?null:"text value required";case"number":return typeof o==="number"&&Number.isFinite(o)?null:"number required";case"checkbox":return typeof o==="boolean"?null:"boolean required";case"singleSelect":return typeof o==="string"?null:"option required";case"relation":return typeof o==="string"&&o!==""?null:"record required";case"multipleSelect":return typeof o==="string"||Array.isArray(o)&&o.every((i)=>typeof i==="string")?null:"options required";case"date":return pa(o)||typeof o==="string"&&Number.isFinite(Date.parse(o))?null:"date required"}}var ga={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},Kl=Array.from(new Set(Object.values(ga).flat()));var Yl=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 ma=["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"],Ql=[...ma,"radius","font-display","font-body","font-mono"];function fa(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function ad(e,t){if(t===e.draft)return e;return{...e,draft:t}}function ya(e){return e.draft!==e.savedContent}function sd(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 ld(e,t){if(ya(e))return e;let n=fa(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 ft=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),Lt=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),Ot=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,Ro=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,En=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),So=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every(En)&&new Set(e).size===e.length;function ba(e){if(!ft(e)||!Lt(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!En(e.id)||!Ot(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)=>!ft(t)||!Lt(t,["id","name"])||!En(t.id)||!Ot(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,r]of[["linkedRecord","link",["collectionId","displayFieldId"]],["lookup","lookup",["linkFieldId","targetFieldId"]],["formula","formula",["expression"]],["rollup","rollup",["linkFieldId","targetFieldId","function"]]]){let o=e[n];if(e.type===t!==(o!==void 0))return!1;if(o!==void 0&&(!ft(o)||!Lt(o,[...r])||r.some((i)=>!Ot(o[i],i==="expression"?2048:512))))return!1}return!0}function cd(e){if(!ft(e)||!Lt(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))||!Ot(e.collectionId,512)||!Ot(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(!ft(t)||!Lt(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!Ot(t.name,200)||!Ro(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(ba)||new Set(t.fields.map((i)=>i.id)).size!==t.fields.length)return!1;if(!ft(n)||!Lt(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!En(n.id)||!Ot(n.name,200)||!Ro(n.version)||!So(n.columnOrder)||!So(n.hiddenColumns)||!ft(n.columnWidths)||Object.values(n.columnWidths).some((i)=>typeof i!=="number"||!Number.isInteger(i)||i<72||i>800))return!1;let r=t.fields,o=(i)=>r.some((a)=>ft(a)&&a.id===i);if([...n.columnOrder,...n.hiddenColumns,...Object.keys(n.columnWidths)].some((i)=>!o(i)))return!1;if(n.type!==void 0&&!["grid","kanban","gallery","calendar","form"].includes(String(n.type)))return!1;if(n.type==="kanban"&&!t.fields.some((i)=>i.id===n.groupByFieldId&&["singleSelect","checkbox"].includes(i.type)))return!1;if(n.type==="calendar"&&!t.fields.some((i)=>i.id===n.dateFieldId&&i.type==="date"))return!1;if(n.search!==void 0&&(typeof n.search!=="string"||n.search.length>200))return!1;if(n.sort!==void 0&&(!Array.isArray(n.sort)||n.sort.length>4||n.sort.some((i)=>!ft(i)||!Lt(i,["fieldId","direction"])||!o(i.fieldId)||!["asc","desc"].includes(String(i.direction)))))return!1;return!0}var et=(e)=>String(e).padStart(2,"0"),ha=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function dt(e){let t=e.formatting;return ha(e)&&t&&"date"in t?t:void 0}function ln(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function dr(e){let t=dt(e);return!t?"auto":t.time==="none"?"date":"datetime"}function lr(e,t,n,r){switch(r){case"YYYY/MM/DD":return`${e}/${et(t)}/${et(n)}`;case"MM/DD/YYYY":return`${et(t)}/${et(n)}/${e}`;case"DD/MM/YYYY":return`${et(n)}/${et(t)}/${e}`;case"YYYY年M月D日":return`${e}年${t}月${n}日`;default:return`${e}-${et(t)}-${et(n)}`}}function dn(e,t){let n=e==null?"":String(e);if(!n)return"";let r=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n);if(t.time==="none"){if(r)return lr(Number(r[1]),Number(r[2]),Number(r[3]),t.date);let d=new Date(n);if(!Number.isFinite(d.getTime()))return n;let l=lt(d,t.timeZone??"UTC");return lr(l.year,l.month,l.day,t.date)}let o=r?wt({year:Number(r[1]),month:Number(r[2]),day:Number(r[3])},t.timeZone):new Date(n);if(!Number.isFinite(o.getTime()))return n;let i=lt(o,t.timeZone),a=lr(i.year,i.month,i.day,t.date);if(t.time==="12h"){let d=i.hour%12||12;return`${a} ${d}:${et(i.minute)} ${i.hour<12?"AM":"PM"}`}return`${a} ${et(i.hour)}:${et(i.minute)}`}function cn(e,t){if(e==null||e==="")return"";let n=typeof e==="number"?e:Number(e);if(!Number.isFinite(n))return String(e);let r=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:r,maximumFractionDigits:r,useGrouping:t.grouping!==!1}).format(n)}function un(e,t){let n=e?.findIndex((i)=>i.id===t)??-1,r=n>=0?e?.[n]?.color:void 0,o=Pn.findIndex((i)=>i===r);return o>=0?o:n}var Ca={"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 he(e="en"){return(t,n={})=>(e==="zh-CN"?Ca[t]??t:t).replace(/\{(\w+)\}/g,(r,o)=>String(n[o]??r))}function Dn(e,t,n,r,o=!1){let{row:i,column:a}=e;if(t==="ArrowUp")i--;if(t==="ArrowDown")i++;if(t==="ArrowLeft")a--;if(t==="ArrowRight")a++;if(t==="Home")a=0;if(t==="End")a=r-1;if(t==="Tab"){let d=Math.max(0,Math.min(n*r-1,i*r+a+(o?-1:1)));i=Math.floor(d/r),a=d%r}return{row:Math.max(0,Math.min(n-1,i)),column:Math.max(0,Math.min(r-1,a))}}function cr(e,t){return{firstRow:Math.min(e.row,t.row),lastRow:Math.max(e.row,t.row),firstColumn:Math.min(e.column,t.column),lastColumn:Math.max(e.column,t.column)}}function Re(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function Io(e,t,n,r){let o=cr(n,r),i=[];for(let a=o.firstRow;a<=o.lastRow;a++){let d=[];for(let l=o.firstColumn;l<=o.lastColumn;l++){let p=t[l],u=e[a]?.values[p?.id??""],c=p?.type==="json"&&u!=null?JSON.stringify(u):p?.type==="hyperlink"?vo(u):Re(u);d.push(/[\t\r\n"]/.test(c)?`"${c.replaceAll('"','""')}"`:c)}i.push(d.join("\t"))}return i.join(`
2
- `)}function xa(e,t="en"){let n=he(t),r=[],o=[],i="",a=!1;for(let d=0;d<e.length;d++){let l=e[d];if(l==='"'&&(a||i===""))if(a&&e[d+1]==='"')i+='"',d++;else a=!a;else if(!a&&(l==="\t"||l===`
3
- `||l==="\r")){if(o.push(i),i="",l!=="\t"){if(r.push(o),o=[],l==="\r"&&e[d+1]===`
4
- `)d++}}else i+=l}if(a)throw Error(n("Unclosed quoted cell."));if(i||o.length||r.length===0)o.push(i),r.push(o);return r}function tt(e,t,n="en"){let r=he(n);if(t.type==="blob")throw Error(r("{name} is read-only; its original bytes are preserved.",{name:t.name}));if(t.type==="relation")throw Error(r("{name} needs a server-provided option.",{name:t.name}));if(t.type==="lookup"||t.type==="formula"||t.type==="rollup")throw Error(r("{name} is read only.",{name:t.name}));if(t.type==="linkedRecord")throw Error(r("Use the {name} record picker.",{name:t.name}));if(e===""){if(t.required)throw Error(r("{name} is required.",{name:t.name}));return null}if(t.type==="number"){let i=Number(e);if(!e.trim()||!Number.isFinite(i))throw Error(r("{name} needs a number.",{name:t.name}));return i}if(t.type==="hyperlink"){let i=Mt(e);if(!i)throw Error(r("{name} needs a link.",{name:t.name}));return i}if(t.type==="json")try{return JSON.parse(e)}catch{throw Error(r("{name} needs valid JSON.",{name:t.name}))}if(t.type==="bigint"){if(!/^-?\d+$/.test(e))throw Error(r("{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(r("{name} needs true or false.",{name:t.name}))}if(t.type==="date"){let i=dt(t);if(i){let F=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!F)throw Error(r("{name} needs a date.",{name:t.name}));let[,E,O,T]=F,U=new Date(Date.UTC(Number(E),Number(O)-1,Number(T)));if(U.getUTCMonth()!==Number(O)-1||U.getUTCDate()!==Number(T))throw Error(r("{name} needs a valid calendar date.",{name:t.name}));if(i.time==="none"){if(/T.*(?:Z|[+-]\d{2}:\d{2})$/i.test(e)&&Number.isFinite(Date.parse(e)))return In(new Date(e),i.timeZone);return`${E}-${O}-${T}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return wt({year:Number(E),month:Number(O),day:Number(T)},i.timeZone).toISOString()}let a=/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-](\d{2}):(\d{2})))?$/i.exec(e);if(!a)throw Error(r("{name} needs a date.",{name:t.name}));let[,d,l,p,u,c,g,C,b]=a,x=Number(d),P=Number(l),m=Number(p),y=[31,x%4===0&&(x%100!==0||x%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(P<1||P>12||m<1||m>(y[P-1]??0)||Number(u??0)>23||Number(c??0)>59||Number(g??0)>59||Number(C??0)>23||Number(b??0)>59)throw Error(r("{name} needs a valid calendar date.",{name:t.name}));let I=new Date(e);if(!Number.isFinite(I.getTime()))throw Error(r("{name} needs a date.",{name:t.name}));return I.toISOString()}let o=(i)=>{let a=t.options?.find((d)=>d.id===i||d.name===i);if(!a)throw Error(r("{name} has no option '{option}'.",{name:t.name,option:i}));return a.id};if(t.type==="singleSelect")return o(e);if(t.type==="multipleSelect")return[...new Set(e.split(",").map((i)=>o(i.trim())))];return e}function Ao(e,t,n,r,o="en"){let i=he(o);try{if(e.length>1048576)throw Error(i("Paste is too large."));let a=xa(e,o);if(a.length>100||r.row+a.length>t.length)throw Error(i("Paste must fit within the loaded page and contain at most 100 rows."));return{ok:!0,items:a.map((l,p)=>{if(r.column+l.length>n.length)throw Error(i("Paste extends beyond the visible columns."));let u=t[r.row+p];if(!u)throw Error(i("Row is not loaded."));let c={};return l.forEach((g,C)=>{let b=n[r.column+C];if(b?.generation==="autoIncrement")throw Error(i("{name} is auto-generated and cannot be edited.",{name:b.name}));if(b)c[b.id]=tt(g,b,o)}),{op:"update",id:u.id,expectedVersion:u.version,values:c}})}}catch(a){return{ok:!1,message:a instanceof Error?a.message:i("Invalid paste.")}}}function Tn(e,t){let n=Re(e);if(!/^\d{4}-\d{2}-\d{2}T/.test(n))return n;let r=new Date(n);if(!Number.isFinite(r.getTime()))return n;let o=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(r),i=(p)=>o.find((u)=>u.type===p)?.value??"",a=r.getUTCMilliseconds(),d=i("second"),l=d!=="00"||a?`:${d}${a?`.${String(a).padStart(3,"0")}`:""}`:"";return`${i("year")}-${i("month")}-${i("day")} ${i("hour")}:${i("minute")}${l}`}function Eo(e,t,n,r=new Set){let o=new Set([...e.map((i)=>i.id),...t]);return n.filter((i)=>o.has(i.id)&&!r.has(i.id))}function ur(e,t){let n=new Set(e);if(n.has(t))n.delete(t);else n.add(t);return n}import{jsx as Kt}from"react/jsx-runtime";var Do=[["#e8f0fe","#1a56c4"],["#e6f4ea","#1e7a3c"],["#fdecea","#b3261e"],["#fff1e0","#a05a00"],["#e8eaed","#3c4043"],["#e0f2f1","#00695c"],["#f3e8fd","#6a1b9a"]];function pr(e){let t=Math.max(e,0)%Do.length,[n,r]=Do[t]??["#e8eaed","#3c4043"];return{background:`var(--uibot-chip-${t}-bg, ${n})`,color:`var(--uibot-chip-${t}-fg, ${r})`}}function gr({index:e,children:t}){return Kt("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",...pr(e)},children:t})}function mr({ids:e,field:t,wrap:n}){let r=t.options??[];return Kt("span",{style:{display:"inline-flex",gap:4,alignItems:"center",maxWidth:"100%",overflow:"hidden",...n?{flexWrap:"wrap"}:{}},children:e.map((o)=>{let i=r.findIndex((a)=>a.id===o);return Kt(gr,{index:un(r,o),children:r[i]?.name??String(o)},String(o))})})}function No({checked:e,label:t,onToggle:n}){return Kt("input",{type:"checkbox","aria-label":t,checked:e,disabled:!n,style:{width:16,height:16,margin:0,accentColor:"var(--primary, #1a56c4)"},onMouseDown:(r)=>r.stopPropagation(),onKeyDown:(r)=>r.stopPropagation(),onChange:()=>n?.()})}var To={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 Fo({type:e}){return Kt("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:Kt("path",{d:To[e]??To.singleLineText})})}function Nn(e){let t=Pn.findIndex((r)=>r===e);if(t<0)return;let n=pr(t);return{background:`color-mix(in srgb, ${n.background} 55%, var(--background, white))`,marker:String(n.color)}}var Mo=(e,t)=>(e%t+t)%t;function Lo(e,t,n,r){let o=[],i=0,a=0,d=e.lastRow-e.firstRow+1,l=e.lastColumn-e.firstColumn+1;if(d<1||l<1||t.lastRow-t.firstRow+1>100)return{mutations:o,skipped:i,count:a,limitExceeded:!0};for(let p=t.firstRow;p<=t.lastRow;p++){let u=n[p];if(!u)continue;let c={};for(let g=t.firstColumn;g<=t.lastColumn;g++){if(p>=e.firstRow&&p<=e.lastRow&&g>=e.firstColumn&&g<=e.lastColumn)continue;let C=r[g];if(!C)continue;if(Fe(C)||C.generation==="autoIncrement"||["blob","linkedRecord","relation"].includes(C.type)){i++;continue}let b=e.firstColumn+Mo(g-e.firstColumn,l),x=r[b];if(!x||x.type!==C.type){i++;continue}let P=n[e.firstRow+Mo(p-e.firstRow,d)]?.values[x.id]??null;if(l===1&&d>=2&&(C.type==="number"||C.type==="date")&&g===e.firstColumn){let m=n.slice(e.firstRow,e.lastRow+1).map((F)=>F.values[x.id]),k=m.map((F)=>C.type==="date"?typeof F==="string"&&F!==""?Date.parse(F)/86400000:Number.NaN:typeof F==="number"?F:Number.NaN),y=k[0]??Number.NaN,I=(k[1]??Number.NaN)-y;if(k.every((F,E)=>Number.isFinite(F)&&Math.abs(F-(y+I*E))<0.00000001)){let F=y+I*(p-e.firstRow);if(Number.isFinite(F))P=C.type==="date"?String(m[0]).length===10?new Date(F*86400000).toISOString().slice(0,10):new Date(F*86400000).toISOString():F}}c[C.id]=structuredClone(P),a++}if(Object.keys(c).length)o.push({op:"update",id:u.id,expectedVersion:u.version,values:c})}return{mutations:o,skipped:i,count:a,limitExceeded:!1}}import{useEffect as _o,useId as Ta,useMemo as Na,useRef as Fa,useState as Uo}from"react";var va=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function Pt(e){return va.test(e)}var yt=(e)=>String(e).padStart(2,"0");function Oo(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${yt(t.getMonth()+1)}-${yt(t.getDate())}T${yt(t.getHours())}:${yt(t.getMinutes())}:${yt(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var fr=(e,t)=>{let n=lt(e,t);return`${n.year}-${yt(n.month)}-${yt(n.day)}T${yt(n.hour)}:${yt(n.minute)}`};function yr(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!Pt(e))return e.slice(0,10);return fr(new Date(e),t.timeZone??"UTC").slice(0,10)}if(Pt(e))return fr(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function br(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||Pt(t)))return e;let o=e.length>10?e.slice(11,16):t&&Pt(t)?fr(new Date(t),n.timeZone).slice(11,16):"00:00",[i,a,d]=e.slice(0,10).split("-").map(Number),[l,p]=o.split(":").map(Number),u=wt({year:i??0,month:a??1,day:d??1,hour:l??0,minute:p??0},n.timeZone);return Number.isFinite(u.getTime())?u.toISOString():e}import{createContext as ka,useContext as wa,useEffect as Pa,useId as Ra,useLayoutEffect as Sa,useMemo as Ia,useRef as Aa,useState as Gt}from"react";import{jsx as Qe,jsxs as Wt}from"react/jsx-runtime";var Bo=ka(void 0);function Ea(e){return Qe(Bo.Provider,{value:e.client,children:e.children})}var hr=()=>wa(Bo),Vo=(e)=>/^https?:/i.test(e);function Fn(e){let t=hr();if(!Ht(e.value))return null;let n=e.value,r=t?.href?.(n)??n.url;return Qe("a",{href:r,title:n.url,"data-uibot-link":n.ref?.kind??(Vo(r)?"external":"internal"),...Vo(r)?{target:"_blank",rel:"noopener noreferrer"}:{},style:{color:"var(--uibot-link, currentColor)",textDecoration:"underline",textUnderlineOffset:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...e.style},onMouseDown:(o)=>o.stopPropagation(),onDoubleClick:(o)=>o.stopPropagation(),onClick:(o)=>{if(o.stopPropagation(),!(o.button!==0||o.metaKey||o.ctrlKey||o.shiftKey||o.altKey)&&t?.open?.(n))o.preventDefault()},children:sn(n)})}var pn=(e)=>e?JSON.stringify(e):"",Da=(e)=>e.trim().startsWith("{")?Mt(e):null;function gn(e){let t=Ia(()=>he(e.locale),[e.locale]),n=hr(),r=Ra(),o=Da(e.text),[i,a]=Gt(()=>o?"":e.text),[d,l]=Gt(!1),[p,u]=Gt([]),[c,g]=Gt(""),[C,b]=Gt(-1),x=Aa(null),[P,m]=Gt(null),y=e.field.hyperlink?.kinds?.join(",")??"";Pa(()=>{if(!n||!d||e.disabled)return;let R=new AbortController,D=setTimeout(()=>{g(t("Searching…")),n.search({search:i.trim(),...y?{kinds:y.split(",")}:{},limit:8},{signal:R.signal}).then((q)=>{if(R.signal.aborted)return;u(q.ok?q.data.slice(0,8):[]),g(q.ok?"":q.error.message)}).catch((q)=>{if(!R.signal.aborted)g(q instanceof Error?q.message:String(q))})},200);return()=>{clearTimeout(D),R.abort()}},[n,d,i,y,e.disabled,t]);let I=Mt(i),F=(R)=>n?.kinds?.find((D)=>D.id===R)?.label??R,E=[...I&&!I.ref?[{key:"typed",value:I,title:t("Use link {url}",{url:I.url})}]:[],...p.map((R)=>({key:`${R.kind}:${R.id}`,value:{url:R.url,text:R.title,ref:{kind:R.kind,id:R.id}},title:R.title,subtitle:[F(R.kind),R.subtitle].filter(Boolean).join(" · ")}))],O=Boolean(n&&!c&&!p.length&&i.trim()),T=d&&!e.disabled&&(E.length>0||Boolean(c)||O);Sa(()=>{if(!T)return;let R=()=>m(x.current?.getBoundingClientRect()??null);return R(),window.addEventListener("scroll",R,!0),window.addEventListener("resize",R),()=>{window.removeEventListener("scroll",R,!0),window.removeEventListener("resize",R)}},[T]);let U=(R)=>{a(""),b(-1),e.onChange(pn(R.value))},K=(R)=>{a(R),b(-1),e.onChange(R||pn(o))};return Wt("div",{style:{display:"grid",gap:4,minWidth:0,height:"100%"},children:[Qe("input",{ref:x,id:e.id,role:"combobox","aria-label":e.ariaLabel,"aria-expanded":T,"aria-controls":r,"aria-autocomplete":"list","aria-invalid":e.invalid,...e.describedBy?{"aria-describedby":e.describedBy}:{},...C>=0?{"aria-activedescendant":`${r}-${C}`}:{},disabled:e.disabled,placeholder:o?sn(o):t("Search or paste a link"),value:i,style:e.inputStyle,className:e.inputClassName,onFocus:()=>l(!0),onBlur:()=>l(!1),onChange:(R)=>K(R.currentTarget.value),onKeyDown:(R)=>{if(e.onSave||e.onCancel)R.stopPropagation();if(R.key==="ArrowDown"||R.key==="ArrowUp"){if(!E.length)return;R.preventDefault();let D=R.key==="ArrowDown"?1:-1;b((q)=>D>0?(q+1)%E.length:q<=0?E.length-1:q-1)}else if(R.key==="Enter"){R.preventDefault();let D=E[C];if(D)U(D);else e.onSave?.()}else if(R.key==="Tab"&&e.onSave)R.preventDefault(),e.onSave();else if(R.key==="Escape")if(R.preventDefault(),i)K("");else e.onCancel?.()}}),o&&!i&&!e.onSave&&Wt("div",{style:{display:"grid",gap:4,minWidth:0,fontSize:12},children:[Wt("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[Qe(Fn,{value:o,style:{flex:"0 1 auto"}}),Qe("span",{style:{flex:"1 1 0",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:0.6},children:o.url}),Qe("button",{type:"button","aria-label":t("Remove link"),title:t("Remove link"),disabled:e.disabled,onMouseDown:(R)=>R.preventDefault(),onClick:()=>e.onChange(""),style:{border:0,background:"none",color:"inherit",cursor:"pointer",opacity:0.6},children:"×"})]}),Wt("label",{style:{display:"grid",gap:2},children:[Qe("span",{style:{opacity:0.7},children:t("Display text")}),Qe("input",{"aria-label":t("Display text"),placeholder:o.url,value:o.text??"",disabled:e.disabled,className:e.inputClassName,onChange:(R)=>{let D=R.currentTarget.value.slice(0,500),{text:q,...N}=o;e.onChange(pn(D?{...N,text:D}:N))}})]})]}),T&&P&&Wt("div",{id:r,role:"listbox","aria-label":t("Link suggestions"),style:{position:"fixed",top:P.bottom+4,left:P.left,width:Math.max(P.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:(R)=>R.preventDefault(),children:[E.map((R,D)=>Wt("div",{id:`${r}-${D}`,role:"option","aria-selected":D===C,tabIndex:-1,onMouseEnter:()=>b(D),onClick:()=>U(R),onKeyDown:()=>{},style:{display:"grid",gap:2,padding:"6px 8px",borderRadius:6,cursor:"pointer",background:D===C?"var(--uibot-hover, rgb(0 0 0 / 0.06))":void 0},children:[Qe("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:R.title}),R.subtitle&&Qe("span",{style:{fontSize:12,opacity:0.65},children:R.subtitle})]},R.key)),c&&Qe("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:c}),O&&Qe("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:t("No matching resources")})]})]})}import{jsx as Rt,jsxs as qo}from"react/jsx-runtime";function Yt(e,t,n){if(e.type==="blob")return"";try{return tt(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 he(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 Cr({field:e,text:t,disabled:n,id:r,label:o,ariaLabel:i,onChange:a,onSave:d,onCancel:l,locale:p="en",submitted:u=!1,describedBy:c}){let g=Na(()=>he(p),[p]),C=Ta(),b=Fa(null),x=Boolean(d);_o(()=>{if(x)b.current?.querySelector("input,textarea,select")?.focus()},[x]);let P=r??C,m=`${P}-error`,[k,y]=Uo(t),[I,F]=Uo(!1);_o(()=>y(t),[t]);let E=Yt(e,k,p),T=Boolean(e.required&&k===""&&E)&&!I&&!u?"":E,U=i??o??e.name,K=e.type==="date"&&Pt(k),R=K&&!E?Oo(k):k,D=[c,T?m:void 0].filter(Boolean).join(" "),q={id:P,"aria-label":U,"aria-invalid":Boolean(T),...D?{"aria-describedby":D}:{},disabled:n,onBlur:()=>F(!0),onKeyDown:(S)=>{if(d||l)S.stopPropagation();let J=e.type==="longText"||e.type==="json";if(S.key==="Tab"&&d)S.preventDefault(),d(S.shiftKey?"previous":"next");else if(S.key==="Enter"&&!S.shiftKey&&d&&(!J||S.ctrlKey||S.metaKey))S.preventDefault(),d();else if(S.key==="Escape"&&l)S.preventDefault(),l()},style:{width:"100%",...x?{height:"100%",border:0,borderRadius:0,outline:"none",boxShadow:"none",padding:"0 7px",boxSizing:"border-box",font:"inherit"}:{},background:"var(--background, white)",color:"inherit"},className:"min-w-0 rounded-md border border-[var(--uibot-border,#d4d4d8)] bg-[var(--uibot-surface,#fff)] px-2 py-1 text-sm text-[var(--uibot-text,#18181b)] disabled:cursor-not-allowed disabled:opacity-60"},N=(S)=>{F(!0),y(S),a(S)},w=(S)=>{if(e.type==="date"&&K&&S){let J=new Date(S);N(Number.isFinite(J.getTime())?J.toISOString():S)}else N(S)},Z;if(e.type==="hyperlink")Z=Rt(gn,{field:e,text:k,id:P,ariaLabel:U,invalid:Boolean(T),describedBy:D||void 0,disabled:n,locale:p,inputStyle:q.style,inputClassName:q.className,onChange:N,onSave:d,onCancel:l});else if(e.type==="checkbox")Z=qo("select",{...q,value:k,onChange:(S)=>N(S.currentTarget.value),children:[!e.required&&Rt("option",{value:"",children:g("No value")}),Rt("option",{value:"true",children:g("Yes")}),Rt("option",{value:"false",children:g("No")})]});else if(e.type==="longText"||e.type==="json")Z=Rt("textarea",{...q,value:k,rows:e.type==="json"?4:3,onChange:(S)=>N(S.currentTarget.value)});else{let S=e.type==="date"&&!(E&&k)?K?"datetime-local":"date":"text",J=e.type==="blob";Z=Rt("input",{...q,type:S,inputMode:e.type==="number"?"decimal":void 0,step:K?"0.001":void 0,value:R,readOnly:J,onInput:e.type==="date"?(V)=>w(V.currentTarget.value):void 0,onChange:(V)=>w(V.currentTarget.value)})}return qo("div",{ref:b,className:"grid min-w-0 gap-1",style:x?{height:"100%"}:void 0,children:[o&&Rt("label",{className:"text-xs font-medium",htmlFor:P,children:o}),Z,T&&Rt("span",{id:m,role:"alert",className:"text-xs text-red-600",children:T})]})}import{useEffect as xr,useMemo as Ma,useState as Vt}from"react";import{jsx as Jt,jsxs as zo}from"react/jsx-runtime";function Mn(e,t){if(!t?.length)return e;let n=!1,r={...e};for(let o of t){let i=o.label.trim();if(!i||r[o.id]===i)continue;r[o.id]=i,n=!0}return n?r:e}function vr(e){let t=Ma(()=>he(e.locale),[e.locale]),[n,r]=Vt(""),[o,i]=Vt(),[a,d]=Vt(null),[l,p]=Vt([]),[u,c]=Vt(()=>Mn({},e.labels)),[g,C]=Vt(""),[b,x]=Vt(!1),P=e.field.relation?.collectionId,m=e.field.relation?.labelFieldId,{getOptions:k,value:y}=e;xr(()=>{c((E)=>Mn(E,e.labels))},[e.labels]),xr(()=>{let E=!1;if(!P||!k)return;return x(!0),C(""),k({collectionId:P,...m?{labelFieldId:m}:{},search:n,...o?{cursor:o}:{},limit:50}).then((O)=>{if(E)return;if(!O.ok){C(O.error.message),d(null);return}let T=O.data.items.slice(0,50);c((U)=>Mn(U,T)),p((U)=>{let K=o?[...U,...T]:T;return[...new Map(K.map((R)=>[R.id,R])).values()]}),d(O.data.nextCursor)}).catch(()=>{if(!E)C(t("Relation options unavailable."))}).finally(()=>{if(!E)x(!1)}),()=>{E=!0}},[P,m,n,o,k,t]),xr(()=>{if(!y||!P||!k)return;if(e.labels?.some((O)=>O.id===y&&O.label.trim()))return;let E=!1;return k({collectionId:P,...m?{labelFieldId:m}:{},ids:[y],limit:50}).then((O)=>{if(E||!O.ok)return;let T=O.data.items.find((U)=>U.id===y);if(T)c((U)=>Mn(U,[T]))}).catch(()=>{}),()=>{E=!0}},[y,P,m,k,e.labels]);let I=!P||!k,F=y?u[y]??l.find((E)=>E.id===y)?.label??y:"";return zo("div",{children:[Jt("input",{"aria-label":t("Search {name}",{name:e.field.name}),value:n,disabled:e.disabled||I,onChange:(E)=>{r(E.currentTarget.value),i(void 0),p([]),d(null)}}),zo("select",{"aria-label":e.label??e.field.name,value:e.value,disabled:e.disabled||I||b,onChange:(E)=>{let O=E.currentTarget.value;if(!O||l.some((T)=>T.id===O))e.onChange(O)},children:[Jt("option",{value:"",children:t("No relation")}),y&&!l.some((E)=>E.id===y)&&Jt("option",{value:y,children:F}),l.map((E)=>Jt("option",{value:E.id,children:E.label},E.id))]}),a&&Jt("button",{type:"button",disabled:b||e.disabled,onClick:()=>i(a),children:t("More {name} options",{name:e.field.name})}),(g||I)&&Jt("span",{role:"status",children:g||t("Relation option provider unavailable.")})]})}import{jsx as jo}from"react/jsx-runtime";var La={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 Me({name:e,size:t=15,style:n}){return jo("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:jo("path",{d:La[e]})})}import{createContext as Oa,useContext as Va,useCallback as Ba,useEffect as $o,useId as _a,useLayoutEffect as Ho,useRef as Ko,useState as Go}from"react";import{createPortal as Ua}from"react-dom";import{jsx as bt,jsxs as Jo,Fragment as Yo}from"react/jsx-runtime";var qa=Oa(!1),kr="uibot:collection-popover-open";function wr({label:e,trigger:t,defaultOpen:n=!1,disabled:r,menu:o,children:i}){let[a,d]=Go(n),[l,p]=Go({left:8,top:8}),u=Ko(null),c=Ko(null),g=_a();$o(()=>{let x=(P)=>{let m=P.detail,k=u.current;if(!m||!k||m===k)return;let y=k.closest("[data-uibot-workspace]")??k.parentElement,I=m.closest("[data-uibot-workspace]")??m.parentElement;if(y===I)d(!1)};return document.addEventListener(kr,x),()=>document.removeEventListener(kr,x)},[]);let C=()=>{d(!1),u.current?.focus({preventScroll:!0})},b=Ba(()=>{if(!a)return;let x=u.current?.getBoundingClientRect(),P=c.current?.getBoundingClientRect();if(x&&P){let m={left:Math.max(8,Math.min(x.left,window.innerWidth-P.width-8)),top:Math.max(8,x.bottom+P.height+8<=window.innerHeight?x.bottom+4:x.top-P.height-4)};p((k)=>k.left===m.left&&k.top===m.top?k:m)}},[a]);return Ho(b),Ho(()=>{if(!a)return;if(u.current)document.dispatchEvent(new CustomEvent(kr,{detail:u.current}));(c.current?.querySelector("button:not(:disabled), input, select, textarea")??c.current)?.focus({preventScroll:!0})},[a]),$o(()=>{if(!a)return;let x=(m)=>{if(m.target instanceof Node&&!c.current?.contains(m.target)&&!u.current?.contains(m.target))d(!1)},P=(m)=>{if(m.key!=="Escape")return;m.preventDefault(),m.stopPropagation(),d(!1),u.current?.focus({preventScroll:!0})};return window.addEventListener("resize",b),window.addEventListener("scroll",b,!0),document.addEventListener("pointerdown",x),document.addEventListener("keydown",P),()=>{window.removeEventListener("resize",b),window.removeEventListener("scroll",b,!0),document.removeEventListener("pointerdown",x),document.removeEventListener("keydown",P)}},[a,b]),Jo(Yo,{children:[bt("button",{ref:u,type:"button","aria-label":e,"aria-haspopup":o?"menu":"dialog","aria-expanded":a,"aria-controls":a?g:void 0,disabled:r,style:{display:"inline-flex",alignItems:"center",gap:6,border:0,background:"transparent",color:"inherit",font:"inherit",padding:"4px 6px",cursor:"pointer"},onPointerDown:(x)=>x.stopPropagation(),onClick:()=>a?C():d(!0),children:t}),a&&Ua(bt("div",{ref:c,id:g,role:o?"menu":"dialog","aria-label":e,tabIndex:-1,style:{position:"fixed",...l,zIndex:80,padding:o?4:12,minWidth:160,maxWidth:"calc(100vw - 16px)",maxHeight:"min(70vh, 600px)",overflow:"auto",boxSizing:"border-box",border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"var(--foreground, inherit)",fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},onKeyDown:(x)=>{if(!o||!["ArrowDown","ArrowUp","Home","End"].includes(x.key))return;x.preventDefault();let P=[...x.currentTarget.querySelectorAll('button[role="menuitem"]:not(:disabled)')],m=P.indexOf(document.activeElement),k=x.key==="Home"?0:x.key==="End"?P.length-1:(m+(x.key==="ArrowUp"?-1:1)+P.length)%P.length;P[k]?.focus()},children:i(C)}),document.body)]})}function Wo({ui:e,label:t,defaultOpen:n,icon:r,chevron:o,quiet:i,active:a,children:d}){let l=Va(qa),p=(u)=>bt("div",{style:{fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},children:bt("fieldset",{disabled:l,style:{border:0,padding:0,margin:0,minWidth:0},children:u})});if(e?.Popover)return e.Popover({label:t,defaultOpen:n,...r?{icon:bt(Me,{name:r})}:{},...o?{iconEnd:bt(Me,{name:"chevronDown",size:13})}:{},...i?{quiet:i}:{},active:a,children:typeof d==="function"?(u)=>p(d(u)):p(d)});return bt(wr,{label:t,defaultOpen:n,trigger:Jo(Yo,{children:[r?bt(Me,{name:r}):null,t,o?bt(Me,{name:"chevronDown",size:13}):null]}),children:(u)=>p(typeof d==="function"?d(u):d)})}import{useEffect as za,useMemo as ja,useState as $a}from"react";function Zo(e,t,n,r,o,i){let a=ja(()=>{let p=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,Rn(t,{aggregates:p}),r.map((u)=>[u.id,u.version]),i])},[e,n,t,r,i]),[d,l]=$a({key:"",status:"ready",values:{}});return za(()=>{if(!o)return;let p=!0,[u,c]=JSON.parse(a);return(async()=>{let g={};for(let C=0;C<c.aggregates.length;C+=8){let b={...c,aggregates:c.aggregates.slice(C,C+8)};if(Sn(u,b))throw Error("Invalid summary");let x=await o.aggregate(u.id,b);if(!p)return;if(!x.ok||x.data.length!==1)throw Error("Summary unavailable");for(let P of b.aggregates){let m=x.data[0]?.values[P.as],k=u.fields.find((I)=>I.id===P.fieldId),y=k?.type==="date"||k?.resultType==="date";if(m!==null&&!(typeof m==="number"&&Number.isFinite(m))&&!(y&&(P.fn==="min"||P.fn==="max")&&typeof m==="string"&&Number.isFinite(Date.parse(m))))throw Error("Invalid summary result");g[P.as]=m}}if(p)l({key:a,client:o,status:"ready",values:g})})().catch(()=>{if(p)l({key:a,client:o,status:"error",values:{}})}),()=>{p=!1}},[o,a]),{status:!o?"local":d.key!==a||d.client!==o?"loading":d.status,values:d.key===a&&d.client===o?d.values:{}}}function Xo(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 Qo=(e)=>e!==null&&e!==void 0&&e!==""&&!(Array.isArray(e)&&e.length===0)&&e!==!1;function ei(e,t,n){let r=e.map((i)=>i.values[t.id]);if(n==="none")return null;if(n==="count")return e.length;if(n==="filled")return r.filter(Qo).length;if(n==="empty")return r.filter((i)=>!Qo(i)).length;if(t.type==="date"){let i=r.filter((a)=>typeof a==="string"&&a!=="").sort();if(!i.length)return null;return n==="min"?i[0]??null:i[i.length-1]??null}let o=r.filter((i)=>typeof i==="number"&&Number.isFinite(i));if(!o.length)return null;if(n==="sum")return o.reduce((i,a)=>i+a,0);if(n==="avg")return o.reduce((i,a)=>i+a,0)/o.length;if(n==="min")return Math.min(...o);return Math.max(...o)}import{useEffect as Ha,useRef as Ka,useState as Zt}from"react";import{jsx as nt,jsxs as mn}from"react/jsx-runtime";function St(e){if(e==null)return"—";if(Array.isArray(e))return e.map(St).join(", ");return String(e)}function ti(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((r)=>r.label||r.id).join(", "):void 0)??St(e.values[t.id])}function ni(e,t){return Re(e.values[t.id])}function Ln({field:e,value:t,labels:n=[],client:r,onChange:o,disabled:i=!1,locale:a,"aria-describedby":d,"aria-invalid":l}){let p=he(a),u=Array.isArray(t)?t.filter((R)=>typeof R==="string"):[],c=Ka(new Set(u));c.current=new Set(u);let[g,C]=Zt(""),[b,x]=Zt(),[P,m]=Zt([]),[k,y]=Zt(0),[I,F]=Zt({}),[E,O]=Zt({rows:[],next:null,error:"",loading:!0}),T=e.link?.collectionId,U=e.link?.displayFieldId;Ha(()=>{let R=!0;if(O({rows:[],next:null,error:"",loading:!0}),!r||!T||!U){O({rows:[],next:null,error:p("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return r.query(T,{limit:50,search:g,...b?{cursor:b}:{}}).then((D)=>{if(!R)return;if(!D.ok){O({rows:[],next:null,error:D.error.message,loading:!1});return}F((q)=>({...Object.fromEntries(Object.entries(q).filter(([N])=>c.current.has(N))),...Object.fromEntries(D.data.items.map((N)=>{let w=String(N.values[U]??"");return[N.id,w.trim()?w.slice(0,256):N.id]}))})),O({rows:D.data.items,next:D.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(R)O({rows:[],next:null,error:p("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{R=!1}},[r,T,U,g,b,k]);let K=(R)=>I[R]??n.find((D)=>D.id===R)?.label??R;return mn("fieldset",{disabled:i,"aria-label":p("{name} linked records",{name:e.name}),...d?{"aria-describedby":d}:{},...l?{"aria-invalid":!0}:{},className:"flex min-w-0 flex-col gap-2 rounded-md border p-2",children:[nt("div",{className:"flex flex-wrap gap-1",children:u.map((R)=>mn("span",{className:"rounded border px-2 py-1 text-sm",children:[K(R)," ",nt("button",{type:"button","aria-label":p("Remove {name}",{name:K(R)}),onClick:()=>o(u.filter((D)=>D!==R)),children:"×"})]},R))}),nt("input",{"aria-label":p("Search {name} records",{name:e.name}),type:"search",placeholder:p("Search linked records"),value:g,onChange:(R)=>{C(R.target.value),x(void 0),m([])}}),E.loading&&nt("p",{role:"status",children:p("Loading linked records…")}),E.error&&mn("div",{role:"alert",children:[E.error," ",nt("button",{type:"button",onClick:()=>y((R)=>R+1),children:p("Retry linked records")})]}),nt("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:E.rows.map((R)=>mn("label",{className:"flex items-center gap-2 text-sm",children:[nt("input",{type:"checkbox","aria-label":p("Link {name}",{name:K(R.id)}),checked:u.includes(R.id),disabled:!u.includes(R.id)&&u.length>=100,onChange:(D)=>o(D.target.checked?[...u,R.id]:u.filter((q)=>q!==R.id))}),K(R.id)]},R.id))}),!E.loading&&!E.error&&!E.rows.length&&nt("p",{children:p("No matching records.")}),mn("div",{className:"flex gap-2",children:[nt("button",{type:"button",disabled:!P.length||E.loading,onClick:()=>{x(P.at(-1)),m((R)=>R.slice(0,-1))},children:p("Previous linked records")}),nt("button",{type:"button",disabled:!E.next||E.loading,onClick:()=>{m((R)=>[...R,b]),x(E.next??void 0)},children:p("Next linked records")})]}),nt("small",{children:p("{count} selected · up to 100 per record across all link fields",{count:u.length})})]})}var Ga={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function Qt(e,t,n){return t?he(n)(Ga[t]):e==null?"—":String(e)}function Tu(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((r)=>({id:`option:${r.id}`,name:r.name,value:r.id})):[],{id:"null",name:t("Unassigned"),value:null}]}function ri(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function oi(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function Nu(e,t,n){let r=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...oi(e),filter:ri(e.filter,r)}}function Wa(e,t=(n)=>n){if(!/^\d{4}-\d{2}$/.test(e))throw Error(t("Choose a valid month."));let[n,r]=e.split("-").map(Number);if(!n||n>9998||!r||r>12)throw Error(t("Choose a valid month."));let o=new Date(`${e}-01T00:00:00.000Z`),i=new Date(o);return i.setUTCMonth(i.getUTCMonth()+1),{start:o.toISOString(),end:i.toISOString(),days:Math.round((i.getTime()-o.getTime())/86400000),weekday:o.getUTCDay()}}function Fu(e,t,n){let{start:r,end:o}=Wa(n);return{...oi(e),filter:ri(e.filter,{fieldId:t,operator:"onOrAfter",value:r},{fieldId:t,operator:"before",value:o})}}function ii(e,t){let n={id:"date",name:"Date",type:"date"},r=String(tt(t,n)),o=String(tt(String(e),n));return`${r.slice(0,10)}${o.slice(10)}`}function Pr(e,t){return[...t.columnOrder,...e.map((r)=>r.id).filter((r)=>!t.columnOrder.includes(r))].filter((r)=>!t.hiddenColumns.includes(r)).flatMap((r)=>e.filter((o)=>o.id===r))}function Rr(e,t){let n=t.find((r)=>r.type==="singleLineText"||r.type==="longText");return(n?Re(e.values[n.id]):"")||e.id}function Sr(e,t,n){if(t.type==="lookup")return St(e);if(t.type==="hyperlink")return sn(e);if(t.type==="date"){let r=dt(t);return r?dn(e,r):Tn(e)}if(t.type==="number"){let r=ln(t);return r?cn(e,r):Re(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return Qt(e,n);if(t.type==="singleSelect"||t.type==="multipleSelect")return(Array.isArray(e)?e:e==null?[]:[e]).map((o)=>t.options?.find((i)=>i.id===o)?.name??String(o)).join(", ");return Re(e)}import{useEffect as Ya,useRef as Ja}from"react";import{jsx as It,jsxs as ai,Fragment as Za}from"react/jsx-runtime";var On={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function Ae({ui:e,style:t,variant:n,size:r,children:o,disabled:i,onClick:a,title:d,ariaLabel:l,icon:p,iconOnly:u,badge:c}){let g=e?.Button,C=p?ai("span",{style:{position:"relative",display:"inline-flex"},children:[It(Me,{name:p}),c?It("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,b=u?C:ai(Za,{children:[C,o]}),x=l,P=d??(u?x:void 0),m=u?"icon":r;if(g)return It(g,{...n?{variant:n}:{},...m?{size:m}:{},disabled:i,onClick:a,title:P,"aria-label":x,children:b});return It("button",{type:"button",style:{...p?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?On:{},...u?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:i,onClick:a,title:P,"aria-label":x,children:b})}function si({ui:e,value:t,options:n,onChange:r,disabled:o,label:i,style:a,"aria-describedby":d,"aria-invalid":l}){let p=e?.Select,u={...d?{"aria-describedby":d}:{},...l?{"aria-invalid":!0}:{}};if(p)return It(p,{value:t,options:n,onChange:r,disabled:o,"aria-label":i,...u});return It("select",{"aria-label":i,...u,style:a,disabled:o,value:t,onChange:(c)=>r(c.target.value),children:n.map((c)=>It("option",{value:c.value,disabled:c.disabled,children:c.label},c.value))})}function Vn({label:e,busy:t,onCancel:n,children:r,alert:o=!1}){let i=Ja(null);return Ya(()=>{let a=i.current,d=document.activeElement;if(a?.showModal)a.showModal();else a?.setAttribute("open","");return()=>{if(a?.close?.(),d instanceof HTMLElement&&d.isConnected)d.focus({preventScroll:!0})}},[]),It("dialog",{ref:i,role:o?"alertdialog":"dialog","aria-modal":"true","aria-label":e,style:{position:"fixed",inset:0,margin:"auto",maxWidth:"min(440px, calc(100vw - 32px))",maxHeight:"80vh",overflow:"auto",boxSizing:"border-box",padding:20,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"inherit",font:"inherit"},onKeyDown:(a)=>{if(a.key!=="Tab")return;let d=a.currentTarget,l=[...d.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter((c)=>!c.hidden),p=l[0],u=l.at(-1);if(!p||(a.shiftKey?document.activeElement===p:document.activeElement===u)||!d.contains(document.activeElement)){if(a.preventDefault(),(a.shiftKey?u:p)?.focus(),!p)d.focus()}},tabIndex:-1,onCancel:(a)=>{if(a.preventDefault(),!t)n()},children:r})}import{useEffect as Hn,useRef as hn,useState as We}from"react";import{useId as hs,useState as Nr}from"react";import{useEffect as li,useRef as fn,useState as ct}from"react";import{jsx as se,jsxs as be,Fragment as ts}from"react/jsx-runtime";function Qa(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 Xa=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function es({descriptor:e,fieldIds:t,query:n,client:r,readOnly:o=!1,reloadKey:i=0,onImported:a,onRefreshSchema:d}){let[l,p]=ct(null),[u,c]=ct(null),[g,C]=ct(null),[b,x]=ct([]),[P,m]=ct(""),[k,y]=ct(!1),[I,F]=ct(!1),[E,O]=ct(!0),[T,U]=ct(null),[K,R]=ct(!1),D=fn(!1),q=fn(!1),N=fn(!1),w=fn(null),Z=fn({client:r,onImported:a,descriptor:e});Z.current={client:r,onImported:a,descriptor:e},li(()=>(D.current=!0,()=>{D.current=!1,q.current=!1}),[]),li(()=>{let M=!0;if(!o)r.imports(e.id).then((W)=>{if(!M||!D.current||!W.ok)return;if(x((ee)=>W.data.map((de)=>{let me=ee.find((X)=>X.id===de.id);return me&&me.version>de.version?me:de})),!N.current)C((ee)=>{let de=W.data.find((me)=>me.id===ee?.id);return ee&&de&&de.version>ee.version?de:ee})});return()=>{M=!1}},[r,e.id,o,i]);let S=(M)=>{C(M),x((W)=>[M,...W.filter((ee)=>ee.id!==M.id)].slice(0,50)),U(null)};async function J(M){if(N.current||o)return;N.current=!0,q.current=!0,y(!0),F(!0),m("");let W=M;try{while(D.current&&q.current&&W.status==="ready"){let ee=await Z.current.client.advanceImport(e.id,W.id,W.version);if(!D.current)break;if(!ee.ok){m(ee.error.message);break}let de=ee.data;if(S(de),de.importedRows>W.importedRows)Z.current.onImported();if(de.version===W.version&&de.status==="ready"){m("Import paused. Refresh the saved progress before retrying.");break}W=de}}finally{if(N.current=!1,q.current=!1,D.current)y(!1),F(!1)}}async function V(){if(!l||N.current)return;N.current=!0,y(!0),m("");let M=await r.previewImport(e.id,{...l,expectedSchemaVersion:e.schemaVersion});if(N.current=!1,!D.current)return;if(y(!1),M.ok)c(M.data),p({...l,expectedSchemaVersion:M.data.schemaVersion,mapping:M.data.mapping});else m(M.error.message)}async function ie(){if(!l||!u||u.missingRequiredFieldIds.length||!u.totalRows||N.current||o)return;N.current=!0,y(!0),m(""),w.current??=crypto.randomUUID();let M=await r.createImport(e.id,{...l,idempotencyKey:w.current});if(N.current=!1,!D.current)return;if(y(!1),M.ok)S(M.data),p(null),c(null),w.current=null,J(M.data);else m(M.error.message)}async function j(){if(!g||N.current||o)return;if(g.status==="ready"){J(g);return}N.current=!0,y(!0),m("");let M=d?await d():Z.current.descriptor;if(!M){N.current=!1,y(!1),m("Refresh the collection schema and try again.");return}let W=await r.resumeImport(e.id,g.id,g.version,M.schemaVersion);if(N.current=!1,!D.current)return;if(y(!1),W.ok)S(W.data),J(W.data);else m(W.error.message)}async function oe(M){if(!g)return;let W=await r.importErrors(e.id,g.id,{limit:100,...M===void 0?{}:{cursor:M},expectedVersion:g.version});if(!D.current)return;if(W.ok)U(W.data);else m(W.error.message)}async function H(M=!1){if(k||N.current)return;N.current=!0,y(!0),m("");let W=M&&g?await r.exportImportErrors(e.id,g.id):await r.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:E});if(N.current=!1,!D.current)return;if(y(!1),W.ok)Qa(W.data),m(`${W.data.rowCount} rows downloaded${W.data.protectedCells?`; ${W.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else m(W.error.message)}return be("details",{className:"min-w-0 rounded-lg border p-4",children:[se("summary",{className:"cursor-pointer text-sm font-medium",children:"CSV import and export"}),be("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[be("div",{className:"flex flex-wrap items-center gap-3",children:[se("button",{type:"button",disabled:k||!t.length,onClick:()=>void H(),children:"Export CSV"}),be("label",{className:"flex items-center gap-2 text-sm",children:[se("input",{type:"checkbox",checked:E,onChange:(M)=>O(M.target.checked)}),"Spreadsheet view"]})]}),se("p",{className:"text-xs text-muted-foreground",children:"Export all matching records and visible columns from the active query. Spreadsheet view prefixes potentially active text with a tab and changes those values; application support varies. Turn it off for exact text. Limit: 100,000 rows or 20 MiB."}),!o&&be(ts,{children:[be("label",{className:"flex min-w-0 flex-col gap-2 text-sm",children:["CSV file",se("input",{"aria-label":"CSV file",className:"max-w-full",type:"file",accept:".csv,text/csv",disabled:k,onChange:async(M)=>{let W=M.target.files?.[0];if(!W)return;if(m(""),c(null),p(null),w.current=null,W.size>20971520){m("Choose a UTF-8 CSV file no larger than 20 MiB.");return}y(!0),N.current=!0;try{let ee=new TextDecoder("utf-8",{fatal:!0}).decode(await W.arrayBuffer());if(D.current)p({fileName:W.name,csv:ee,expectedSchemaVersion:e.schemaVersion})}catch{if(D.current)m("The file must be valid UTF-8 text.")}finally{if(N.current=!1,D.current)y(!1)}}})]}),l&&be("div",{className:"flex flex-wrap gap-3",children:[se("span",{className:"break-all text-sm",children:l.fileName}),se("button",{type:"button",disabled:k,onClick:()=>void V(),children:"Preview CSV"})]}),se("p",{className:"text-xs text-muted-foreground",children:"Insert into this collection. Existing records and options stay unchanged. Dates: ISO or YYYY-MM-DD; selections: IDs or names; multi-select: JSON array or semicolon list; linked records: JSON IDs. Blank non-text cells become null. Computed columns are skipped. Invalid rows are skipped with downloadable errors."}),u&&l&&be("div",{className:"flex min-w-0 flex-col gap-3",children:[be("p",{className:"text-sm",children:[u.totalRows," rows · ",u.validRows," valid · ",u.invalidRows," ","invalid · ",u.ignoredColumns.length," skipped columns"]}),u.headers.map((M,W)=>be("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[be("span",{className:"max-w-64 break-all",children:["Column ",W+1,": ",M||"(empty)"]}),be("select",{"aria-label":`Column ${W+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:l.mapping?.[W]??"",disabled:k,onChange:(ee)=>{let de=[...l.mapping??u.mapping];de[W]=ee.target.value||null,p({...l,mapping:de}),c(null),w.current=null},children:[se("option",{value:"",children:"Skip column"}),e.fields.filter((ee)=>!Fe(ee)).map((ee)=>be("option",{value:ee.id,children:[ee.name," (",ee.id,")",ee.required?" · required":""]},ee.id))]})]},`${W}:${M}`)),u.missingRequiredFieldIds.length>0&&be("p",{role:"alert",children:["Map required fields: ",u.missingRequiredFieldIds.join(", ")]}),se("div",{className:"max-w-full overflow-x-auto",children:be("table",{className:"w-full text-xs",children:[be("caption",{children:["First ",u.sample.length," normalized rows; row numbers include the header."]}),se("thead",{children:be("tr",{children:[se("th",{children:"Row"}),se("th",{children:"Normalized values"}),se("th",{children:"Error"})]})}),se("tbody",{children:u.sample.map((M)=>be("tr",{children:[se("td",{children:M.rowNumber}),se("td",{className:"max-w-96 break-all",children:Xa(M.values)}),se("td",{children:M.error?.code??""})]},M.rowNumber))})]})}),se("button",{type:"button",className:"self-start",disabled:k||!u.totalRows||u.missingRequiredFieldIds.length>0,onClick:()=>void ie(),children:"Confirm import"})]}),be("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",be("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:g?.id??"",disabled:k,onChange:async(M)=>{if(!M.target.value){C(null);return}let W=await r.importJob(e.id,M.target.value);if(D.current)if(W.ok)S(W.data),R(!1);else m(W.error.message)},children:[se("option",{value:"",children:"Choose saved progress…"}),b.map((M)=>be("option",{value:M.id,children:[M.fileName," · ",M.processedRows,"/",M.totalRows," · ",M.status]},M.id))]})]}),se("button",{type:"button",className:"self-start",disabled:k,onClick:async()=>{let M=await r.imports(e.id);if(D.current)if(M.ok)x(M.data);else m(M.error.message)},children:"Refresh saved imports"}),g&&be("div",{className:"flex flex-col gap-3",children:[be("p",{role:"status",children:[I?"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"]}),se("progress",{"aria-label":"Import progress",max:g.totalRows,value:g.processedRows,className:"max-w-full"}),se("p",{className:"text-xs text-muted-foreground",children:"Closing this page pauses new batches. An in-flight batch may finish. Resume saved progress after signing in with the same credential. Imported records remain if you cancel."}),be("div",{className:"flex flex-wrap gap-3",children:[I&&se("button",{type:"button",onClick:()=>{q.current=!1,F(!1)},children:"Pause import"}),!I&&(g.status==="ready"||g.status==="schemaChanged")&&se("button",{type:"button",disabled:k,onClick:()=>void j(),children:g.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(g.status==="ready"||g.status==="schemaChanged")&&se("button",{type:"button",disabled:k,onClick:()=>R(!0),children:"Cancel import"}),se("button",{type:"button",disabled:k||!g.failedRows,onClick:()=>void oe(),children:"Show import errors"}),se("button",{type:"button",disabled:k||!g.failedRows,onClick:()=>void H(!0),children:"Download all import errors"})]}),K&&be("div",{children:[be("p",{children:["Stop remaining rows? The ",g.importedRows," imported records will remain."]}),se("button",{type:"button",disabled:k,onClick:async()=>{N.current=!0,y(!0);let M=await r.cancelImport(e.id,g.id);if(N.current=!1,!D.current)return;if(y(!1),M.ok)S(M.data),R(!1);else m(M.error.message)},children:"Confirm cancellation"}),se("button",{type:"button",onClick:()=>R(!1),children:"Keep import"})]}),T&&be("div",{className:"max-w-full overflow-x-auto",children:[be("table",{className:"w-full text-xs",children:[be("caption",{children:[T.total," failed rows"]}),se("thead",{children:be("tr",{children:[se("th",{children:"Row"}),se("th",{children:"Field"}),se("th",{children:"Error"})]})}),se("tbody",{children:T.items.map((M)=>be("tr",{children:[se("td",{children:M.rowNumber}),se("td",{children:M.fieldId??""}),se("td",{children:M.code})]},M.rowNumber))})]}),T.nextCursor!==null&&se("button",{type:"button",onClick:()=>void oe(T.nextCursor??void 0),children:"Next errors"})]})]})]}),P&&se("p",{role:"alert",className:"break-words text-sm",children:P})]})]})}import{useEffect as di,useRef as Bt,useState as _t}from"react";import{jsx as Pe,jsxs as qe,Fragment as rs}from"react/jsx-runtime";var Bn=[{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 ns({descriptor:e,client:t,onConverted:n}){let r=e.fields.filter((S)=>Bn.some((J)=>J.type===S.type)),[o,i]=_t(r[0]?.id??""),a=r.find((S)=>S.id===o)??r[0],[d,l]=_t(a?.type??"singleLineText"),[p,u]=_t(a?.required??!1),[c,g]=_t(a?.options?.map((S)=>`${S.id}=${S.name}`).join(`
5
- `)??""),[C,b]=_t(null),[x,P]=_t(""),[m,k]=_t(!1),y=Bt(null),I=Bt(null),F=Bt(0),E=Bt(e);E.current=e;let O=y.current?.field??a,T=m||y.current!==null,U=`${e.id}:${e.schemaVersion}:${JSON.stringify(e.fields)}`,K=Bt(e.fields);K.current=e.fields;let R=Bt(U);R.current=U;let D=Bt(!0);di(()=>(D.current=!0,()=>{D.current=!1,F.current++}),[]),di(()=>{if(R.current!==U)return;if(y.current&&I.current===e.id)return;F.current++;let S=K.current.find((J)=>J.id===o&&Bn.some((V)=>V.type===J.type))??K.current.find((J)=>Bn.some((V)=>V.type===J.type));if(S)i(S.id),l(S.type),u(S.required??!1),g(S.options?.map((J)=>`${J.id}=${J.name}`).join(`
6
- `)??"");b(null),y.current=null,I.current=null,P(""),k(!1)},[U,o,e.id]);let q=()=>{b(null),y.current=null,I.current=null,F.current++,P("")},N=(S)=>{i(S.id),l(S.type),u(S.required??!1),g(S.options?.map((J)=>`${J.id}=${J.name}`).join(`
7
- `)??""),q()};if(!O)return null;let w=()=>{let S={id:O.id,name:O.name,type:d,required:p};if(d==="singleSelect"||d==="multipleSelect")S.options=c.split(`
8
- `).filter((J)=>J.trim()).map((J)=>{let V=J.indexOf("=");if(V<1)throw Error("Each option must use stable_id=Display name.");return{id:J.slice(0,V).trim(),name:J.slice(V+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:S}},Z=()=>D.current&&R.current===U;return qe("details",{className:"rounded-lg border p-4",children:[Pe("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),qe("div",{className:"mt-4 flex flex-col gap-3",children:[Pe("p",{className:"text-sm",children:"Preview every existing record before changing the field. Invalid values or a changed preview block confirmation. All record versions advance together."}),qe("label",{children:["Field"," ",qe("select",{"aria-label":"Conversion field",value:O.id,disabled:T,onChange:(S)=>{let J=r.find((V)=>V.id===S.target.value);if(J)N(J)},children:[y.current&&!r.some((S)=>S.id===O.id)&&Pe("option",{value:O.id,children:O.name}),r.map((S)=>Pe("option",{value:S.id,children:S.name},S.id))]})]}),qe("label",{children:["Target type"," ",Pe("select",{"aria-label":"Conversion target type",value:d,disabled:T,onChange:(S)=>{l(S.target.value),q()},children:Bn.map((S)=>Pe("option",{value:S.type,children:S.label},S.type))})]}),qe("label",{children:[Pe("input",{type:"checkbox",checked:p,disabled:T,onChange:(S)=>{u(S.target.checked),q()}})," ","Required after conversion"]}),(d==="singleSelect"||d==="multipleSelect")&&qe("label",{children:["Stable option IDs and display names",Pe("textarea",{"aria-label":"Conversion options",className:"block w-full rounded border p-2",disabled:T,value:c,onChange:(S)=>{g(S.target.value),q()},placeholder:`open=Open
9
- done=Done`})]}),x&&Pe("p",{role:"alert",className:"text-sm text-destructive",children:x}),Pe("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:T,onClick:async()=>{let S;try{S=w()}catch(J){P(J instanceof Error?J.message:"Invalid conversion options.");return}k(!0),P(""),b(null),y.current=null;try{let J=await t.previewConversion(e.id,S);if(!Z())return;if(J.ok)b(J.data);else P(J.error.message)}catch{if(Z())P("Preview unavailable. Your draft is kept.")}finally{if(Z())k(!1)}},children:m?"Working…":"Preview conversion"}),C&&qe(rs,{children:[qe("p",{role:"status",children:[C.validRows," valid · ",C.invalidRows," invalid"]}),qe("p",{className:"text-xs",children:["Preview covers ",C.totalRows," records. Samples and errors show at most 20 records."]}),Pe("div",{className:"overflow-x-auto",children:qe("table",{className:"w-full text-sm",children:[Pe("thead",{children:qe("tr",{children:[Pe("th",{children:"Record"}),Pe("th",{children:"Before"}),Pe("th",{children:"After"}),Pe("th",{children:"Error"})]})}),Pe("tbody",{children:C.sample.map((S)=>qe("tr",{children:[Pe("td",{className:"max-w-32 break-all",children:S.id}),Pe("td",{className:"max-w-48 break-words",children:JSON.stringify(S.before)}),Pe("td",{className:"max-w-48 break-words",children:JSON.stringify(S.after)}),Pe("td",{children:S.error})]},S.id))})]})}),C.errors.length>0&&Pe("ul",{children:C.errors.map((S)=>qe("li",{children:[Pe("span",{className:"break-all",children:S.id}),": ",Pe("span",{children:S.code})]},S.id))}),Pe("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:m||C.invalidRows>0,onClick:async()=>{if(!y.current)I.current=e.id,F.current++;y.current??={expectedSchemaVersion:C.schemaVersion,field:C.field,previewToken:C.previewToken,idempotencyKey:crypto.randomUUID()};let S=y.current,J=F.current,V=()=>D.current&&E.current.id===e.id&&J===F.current;k(!0),P("");try{let ie=await t.convertField(e.id,S);if(!V())return;if(ie.ok){if(b(null),y.current=null,I.current=null,ie.data.descriptor.schemaVersion>=E.current.schemaVersion)n(ie.data.descriptor)}else if(P(ie.error.message),ie.error.status===409)b(null),y.current=null,I.current=null}catch{if(V())P("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(V())k(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as os,useRef as Ir,useState as ci}from"react";import{jsx as ui,jsxs as as}from"react/jsx-runtime";function is({collectionIds:e,client:t,onChanges:n,pollIntervalMs:r=2000}){let o=JSON.stringify([...new Set(e)].sort()),i=Ir(o);i.current=o;let a=Ir(n);a.current=n;let d=Ir(()=>{}),[l,p]=ci("connecting"),[u,c]=ci(!1);return os(()=>{let g=JSON.parse(o),C=new Map,b=!1,x=!1,P=0,m,k=()=>!b&&i.current===o,y=Math.max(50,Math.min(60000,r)),I=async()=>{if(!k()||x)return;x=!0,c(!0);let O=!1;try{let T=P>0;for(let U of g){let K=C.get(U),R=await t.changes(U,{...K!==void 0?{cursor:K}:{},limit:100});if(!k())return;if(!R.ok)throw p(R.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let D=K===void 0;if(D||T||R.data.items.length>0)await a.current(U,R.data,D);if(!k())return;C.set(U,R.data.cursor),O||=R.data.hasMore}P=0,p("live")}catch{if(P++,k())p((T)=>T==="expired"?"expired":"offline")}finally{if(x=!1,k())c(!1),m=setTimeout(()=>{I()},O&&P===0?0:Math.min(30000,y*2**Math.min(P,8)))}},F=()=>{if(m!==void 0)clearTimeout(m);I()};d.current=F,p("connecting"),I();let E=()=>{if(document.visibilityState==="visible")F()};return window.addEventListener("online",F),document.addEventListener("visibilitychange",E),()=>{if(b=!0,m!==void 0)clearTimeout(m);window.removeEventListener("online",F),document.removeEventListener("visibilitychange",E)}},[o,t,r]),as("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[ui("p",{role:"status",children:l==="live"?"Live updates":l==="connecting"?"Connecting live updates…":l==="expired"?"Session expired. Renew your session; drafts are kept.":"Connection interrupted. Drafts are kept."}),(l==="offline"||l==="expired")&&ui("button",{type:"button",className:"rounded border px-2 py-1",disabled:u,onClick:()=>d.current(),children:"Reconnect now"})]})}import{useEffect as _n,useRef as At,useState as He}from"react";import{jsx as ce,jsxs as Ce,Fragment as Dr}from"react/jsx-runtime";var Er={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function yn(e){try{return await e()}catch{return{ok:!1,error:Er}}}function Ar({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return Ce("div",{className:"min-w-0",children:[ce("strong",{children:t}),ce("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-words rounded border p-2 text-xs",children:n.slice(0,16000)}),n.length>16000&&Ce(Dr,{children:[ce("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),ce("button",{type:"button",onClick:()=>{let r=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),o=document.createElement("a");o.href=r,o.download=`record-${e?.id}-${e?.version}.json`,o.click(),setTimeout(()=>URL.revokeObjectURL(r),1000)},children:"Download snapshot"})]})]})}function ss({descriptor:e,recordId:t,client:n,readOnly:r=!1,onCommitted:o,registerRefresh:i}){let[a,d]=He(null),[l,p]=He(null),[u,c]=He(null),[g,C]=He(),[b,x]=He(),[P,m]=He([]),[k,y]=He([]),[I,F]=He(""),[E,O]=He(null),[T,U]=He(null),[K,R]=He(null),[D,q]=He(!1),[N,w]=He(""),Z=At(null),S=At(null),J=At(n);J.current=n;let V=At(!1),ie=At(0),j=`${e.id}:${t}`,oe=At(j);oe.current=j;let H=At({historyBefore:g,commentBefore:b});H.current={historyBefore:g,commentBefore:b};let M=At(async()=>{}),W=(h=j)=>V.current&&oe.current===h&&J.current===n,ee=async()=>{let h=j,z=++ie.current,Q=H.current,[Oe,Ye]=await Promise.all([yn(()=>n.history(e.id,t,{...Q.historyBefore===void 0?{}:{before:Q.historyBefore},limit:20})),yn(()=>n.comments(e.id,t,{...Q.commentBefore===void 0?{}:{before:Q.commentBefore},limit:50}))]);if(!W(h)||z!==ie.current)throw Error("Refresh superseded");if(!Oe.ok||!Ye.ok)throw w(!Oe.ok?Oe.error.message:!Ye.ok?Ye.error.message:Er.message),Error("Activity refresh failed");p(Oe.data),c(Ye.data),d(h)};M.current=ee,_n(()=>(V.current=!0,()=>{V.current=!1,ie.current++}),[]),_n(()=>(i?.(()=>M.current()),()=>i?.(null)),[i]),_n(()=>{if(oe.current!==j)return;p(null),c(null),d(null),C(void 0),x(void 0),m([]),y([]),H.current={historyBefore:void 0,commentBefore:void 0},F(""),O(null),U(null),R(null),Z.current=null,S.current=null,q(!1),w("")},[j]),_n(()=>{if(oe.current!==j||J.current!==n||H.current.historyBefore!==g||H.current.commentBefore!==b)return;M.current().catch(()=>{})},[j,n,g,b]);let de=(h)=>{let z=Z.current;if(z?.signature===h)return z.key;let Q={signature:h,key:crypto.randomUUID()};return Z.current=Q,Q.key},me=async(h)=>{if(D||r||!u||a!==j)return;let z=h==="delete"?T:E;if(h!=="create"&&(!z||z.authorId!==u.actorId))return;let Q=h==="create"?I:E?.draft??"";if(h!=="delete"&&(!Q.trim()||Q.length>4000||Q.includes("\x00"))){w("Comments require 1–4,000 characters.");return}let Oe=de(JSON.stringify([h,z?.id,z?.version,Q]));q(!0),w("");let Ye=await yn(async()=>{if(h==="create")return n.createComment(e.id,t,{text:Q,idempotencyKey:Oe});if(!z)return{ok:!1,error:Er};if(h==="edit")return n.editComment(e.id,t,z.id,{text:Q,expectedVersion:z.version,idempotencyKey:Oe});return n.deleteComment(e.id,t,z.id,{expectedVersion:z.version,idempotencyKey:Oe})});if(!W())return;if(q(!1),!Ye.ok){w(Ye.error.message);return}if(Z.current=null,h==="create")F("");else if(h==="edit")O(null);else U(null);if(h==="create"&&b!==void 0)x(void 0),y([]);else await M.current().catch(()=>{})},X=async(h)=>{if(D||r||!l||a!==j)return;q(!0),w(""),S.current=null;let z={targetVersion:h,expectedCurrentVersion:l.currentVersion,expectedSchemaVersion:e.schemaVersion},Q=await yn(()=>n.previewUndo(e.id,t,z));if(!W())return;if(q(!1),Q.ok)R(Q.data);else R(null),w(Q.error.message)},we=async()=>{if(D||r||a!==j||!K&&!S.current)return;let h=S.current;if(!h){if(!K)return;h={targetVersion:K.targetVersion,expectedCurrentVersion:K.currentVersion,expectedSchemaVersion:K.schemaVersion,idempotencyKey:crypto.randomUUID()},S.current=h}let z=h;q(!0),w("");let Q=await yn(()=>n.undo(e.id,t,z));if(!W())return;if(q(!1),!Q.ok){if(Q.error.code==="version_conflict"||Q.error.code==="reference_conflict"||Q.error.code==="validation")S.current=null,R(null);w(Q.error.message),await M.current().catch(()=>{});return}S.current=null,R(null),o(Q.data),C(void 0),m([]),await M.current().catch(()=>{})},ae=u?.items.find((h)=>h.id===E?.id),Se=E&&ae&&ae.version!==E.version,B=K&&(K.currentVersion!==l?.currentVersion||K.schemaVersion!==e.schemaVersion);return Ce("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[Ce("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ce("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),ce("button",{type:"button",disabled:D,onClick:()=>{w(""),M.current().catch(()=>{})},children:"Refresh activity"})]}),N&&ce("p",{role:"alert",className:"text-sm text-destructive",children:N}),!l||!u||a!==j?ce("p",{role:"status",children:"Loading record activity…"}):Ce(Dr,{children:[Ce("p",{role:"status",children:["Current version ",l.currentVersion,l.currentDeleted?" · Deleted record":""]}),ce("h3",{className:"font-medium",children:"Comments"}),u.items.length===0&&ce("p",{className:"text-sm",children:"No comments yet."}),ce("ol",{className:"flex flex-col gap-3",children:u.items.map((h)=>Ce("li",{className:"min-w-0 rounded border p-3",children:[Ce("p",{className:"break-all text-xs",children:[h.authorId," · ",h.updatedAt," · version ",h.version]}),ce("p",{className:"whitespace-pre-wrap break-words text-sm",children:h.text??"Comment deleted"}),!r&&h.text!==null&&h.authorId===u.actorId&&Ce("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:D,onClick:()=>{O({...h,draft:h.text??""}),U(null),Z.current=null},children:"Edit comment"}),ce("button",{type:"button",disabled:D,onClick:()=>{U(h),O(null),Z.current=null},children:"Delete comment"})]})]},h.id))}),Ce("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:D||!k.length,onClick:()=>{x(k.at(-1)),y((h)=>h.slice(0,-1))},children:"Newer comments"}),ce("button",{type:"button",disabled:D||u.nextCursor===null,onClick:()=>{y((h)=>[...h,b]),x(u.nextCursor??void 0)},children:"Older comments"})]}),!r&&Ce(Dr,{children:[E&&Ce("div",{className:"flex flex-col gap-2",children:[Ce("label",{children:["Edit comment text",ce("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:D,maxLength:4000,value:E.draft,onChange:(h)=>{O({...E,draft:h.target.value}),Z.current=null}})]}),Se&&Ce("div",{role:"status",children:[ce("p",{children:"This comment changed. Your draft and original version are kept."}),Ce("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",ae.text??"Comment deleted"]}),ae.text!==null&&ae.authorId===u.actorId&&ce("button",{type:"button",disabled:D,onClick:()=>{O({...ae,draft:E.draft}),Z.current=null},children:"Use current comment version"})]}),Ce("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:D||E.authorId!==u.actorId,onClick:()=>void me("edit"),children:"Save comment"}),ce("button",{type:"button",disabled:D,onClick:()=>{O(null),Z.current=null},children:"Cancel comment edit"})]})]}),T&&Ce("div",{children:[ce("p",{children:"Delete this comment? A deletion marker will remain."}),ce("p",{className:"whitespace-pre-wrap break-words",children:T.text}),ce("button",{type:"button",disabled:D||T.authorId!==u.actorId,onClick:()=>void me("delete"),children:"Confirm delete comment"}),ce("button",{type:"button",disabled:D,onClick:()=>U(null),children:"Cancel delete comment"})]}),Ce("label",{children:["New comment",ce("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:D,maxLength:4000,value:I,onChange:(h)=>{F(h.target.value),Z.current=null}})]}),ce("button",{type:"button",className:"self-start",disabled:D||!I.trim(),onClick:()=>void me("create"),children:"Add comment"})]}),ce("h3",{className:"font-medium",children:"Record history"}),ce("p",{className:"text-xs",children:"Stored writable values at each version. Live computed values are excluded. A legacy baseline has an unknown author; earlier versions cannot be recovered."}),ce("ol",{className:"flex flex-col gap-3",children:l.items.map((h)=>Ce("li",{className:"min-w-0 rounded border p-3",children:[Ce("p",{className:"break-all text-xs",children:["Version ",h.version," · ",h.operation," · schema ",h.schemaVersion," · ",h.actorId," ·"," ",h.createdAt]}),Ce("details",{children:[Ce("summary",{children:["Stored values at version ",h.version]}),ce(Ar,{record:h.snapshot,label:`Version ${h.version}`})]}),!r&&h.version<l.currentVersion&&Ce("button",{type:"button",disabled:D,onClick:()=>void X(h.version),children:["Preview restore version ",h.version]})]},h.id))}),Ce("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:D||!P.length,onClick:()=>{C(P.at(-1)),m((h)=>h.slice(0,-1))},children:"Newer history"}),ce("button",{type:"button",disabled:D||l.nextCursor===null,onClick:()=>{m((h)=>[...h,g]),C(l.nextCursor??void 0)},children:"Older history"})]}),!r&&K&&Ce("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[Ce("h3",{children:["Restore version ",K.targetVersion," as a new version"]}),Ce("p",{children:["Current version ",K.currentVersion," · schema ",K.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),Ce("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[ce(Ar,{record:K.before,label:"Current stored values"}),ce(Ar,{record:K.target,label:"Values to restore"})]}),B&&!S.current&&ce("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),Ce("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:D||!!B&&!S.current,onClick:()=>void we(),children:S.current?"Retry undo":"Confirm restore"}),ce("button",{type:"button",disabled:D,onClick:()=>{R(null),S.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as Un,useRef as Et,useState as ht}from"react";import{jsx as Ve,jsxs as Ke,Fragment as pi}from"react/jsx-runtime";async function qn(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 ls(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function ds({collectionId:e,recordId:t,client:n,readOnly:r=!1,registerRefresh:o}){let i=`${e}:${t}`,a=Et({identity:i,client:n});a.current={identity:i,client:n};let d=Et(!1),l=Et(0),p=Et(0),[u,c]=ht(null),[g,C]=ht(null),[b,x]=ht(),[P,m]=ht([]),k=Et(b);k.current=b;let[y,I]=ht(null),[F,E]=ht(null),O=Et(null),T=Et(null),[U,K]=ht(!1),[R,D]=ht(!1),[q,N]=ht(""),w=()=>d.current&&a.current.identity===i&&a.current.client===n,Z=async()=>{let j=++l.current,oe=await qn(()=>n.list(e,t,{limit:20,...k.current===void 0?{}:{before:k.current}}));if(!w()||j!==l.current)throw Error("Refresh superseded");if(!oe.ok)throw N(oe.error.message),Error("Attachment refresh failed");C(oe.data),c(i)},S=Et(Z);S.current=Z,Un(()=>(d.current=!0,()=>{d.current=!1,++l.current,++p.current}),[]),Un(()=>{if(a.current.identity!==i||a.current.client!==n)return;c(null),C(null),I(null),E(null),O.current=null,K(!1),D(!1),N(""),x(void 0),m([]),k.current=void 0,++p.current,S.current().catch(()=>{})},[i,n]),Un(()=>{if(k.current===b&&u===i)S.current().catch(()=>{})},[b,i,u]),Un(()=>(o?.(()=>S.current()),()=>o?.(null)),[o]);let J=async()=>{if(U||r||!y||u!==i)return;let j=y;K(!0),N("");let oe=await qn(()=>n.upload(e,t,j));if(!w())return;if(K(!1),!oe.ok){N(oe.error.message);return}if(I(null),T.current)T.current.value="";x(void 0),m([]),k.current=void 0,await S.current().catch(()=>{})},V=async()=>{if(U||r||!F||F.authorId!==g?.actorId||u!==i)return;O.current??=crypto.randomUUID();let j=F,oe=O.current;K(!0),N("");let H=await qn(()=>n.delete(e,t,j.id,{expectedVersion:j.version,idempotencyKey:oe}));if(!w())return;if(K(!1),!H.ok){N(H.error.message),await S.current().catch(()=>{});return}E(null),O.current=null,await S.current().catch(()=>{})},ie=async(j)=>{if(U||u!==i)return;K(!0),N("");let oe=await qn(()=>n.content(e,t,j.id));if(!w())return;if(K(!1),!oe.ok){N(oe.error.message);return}let H=Uint8Array.from(atob(oe.data.base64),(ee)=>ee.charCodeAt(0)),M=URL.createObjectURL(new Blob([H],{type:"application/octet-stream"})),W=document.createElement("a");W.href=M,W.download=oe.data.attachment.name,W.click(),setTimeout(()=>URL.revokeObjectURL(M),1000)};return Ke("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Ke("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ve("h3",{className:"font-medium",children:"Attachments"}),Ve("button",{type:"button",disabled:U,onClick:()=>{N(""),S.current().catch(()=>{})},children:"Refresh attachments"})]}),q&&Ve("p",{role:"alert",children:q}),!g||u!==i?Ve("p",{role:"status",children:"Loading attachments…"}):Ke(pi,{children:[g.items.length===0&&Ve("p",{children:"No attachments yet."}),Ve("ol",{className:"flex min-w-0 flex-col gap-2",children:g.items.map((j)=>Ke("li",{className:"min-w-0 rounded border p-2",children:[Ve("p",{className:"break-all",children:j.name}),Ke("p",{className:"break-all text-xs",children:[j.size," bytes · version ",j.version," · ",j.authorId]}),j.deletedAt?Ve("p",{children:"Attachment deleted"}):Ke("div",{className:"flex flex-wrap gap-3",children:[Ve("button",{type:"button",disabled:U,"aria-label":`Download attachment ${j.name}`,onClick:()=>void ie(j),children:"Download"}),!r&&j.authorId===g.actorId&&Ve("button",{type:"button",disabled:U,"aria-label":`Delete attachment ${j.name}`,onClick:()=>{E(j),O.current=null},children:"Delete"})]})]},j.id))}),Ke("div",{className:"flex flex-wrap gap-3",children:[Ve("button",{type:"button",disabled:U||!P.length,onClick:()=>{x(P.at(-1)),m((j)=>j.slice(0,-1))},children:"Newer attachments"}),Ve("button",{type:"button",disabled:U||g.nextCursor===null,onClick:()=>{m((j)=>[...j,b]),x(g.nextCursor??void 0)},children:"Older attachments"})]}),!r&&Ke(pi,{children:[Ve("p",{className:"text-xs",children:"Up to 1 MiB per file, 20 active files and 5 MiB per record. Files have independent versions; restoring record values does not restore deleted files."}),Ke("label",{children:["Attachment file",Ve("input",{ref:T,"aria-label":"Attachment file",type:"file",disabled:U||R,onChange:async(j)=>{let oe=j.target.files?.[0];if(!oe)return;let H=++p.current;if(I(null),N(""),!oe.size||oe.size>1048576){N("Choose a nonempty file up to 1 MiB.");return}D(!0);try{let M=await ls(oe);if(!w()||H!==p.current)return;let W=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(oe.type)?oe.type:"application/octet-stream";I({name:oe.name,contentType:W,base64:M,idempotencyKey:crypto.randomUUID()})}catch{if(w()&&H===p.current)N("The selected file could not be read.")}finally{if(w()&&H===p.current)D(!1)}}},i)]}),y&&Ke("p",{className:"break-all",children:["Selected file: ",y.name]}),Ve("button",{type:"button",className:"self-start",disabled:U||R||!y,onClick:()=>void J(),children:"Upload attachment"}),F&&Ke("div",{children:[Ke("p",{className:"break-all",children:["Delete ",F.name,"? This permanently removes its bytes and keeps a deletion marker."]}),Ke("div",{className:"flex flex-wrap gap-3",children:[Ve("button",{type:"button",disabled:U,onClick:()=>void V(),children:"Confirm delete attachment"}),Ve("button",{type:"button",disabled:U,onClick:()=>{E(null),O.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as zn,useRef as Xt,useState as Ge}from"react";import{jsx as ve,jsxs as Ee,Fragment as gi}from"react/jsx-runtime";async function Tr(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function cs(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function us({descriptor:e,recordIds:t,client:n,linkForGrant:r,registerRefresh:o}){let i=e.id,a=Xt({identity:i,client:n});a.current={identity:i,client:n};let d=Xt(!1),l=Xt(0),[p,u]=Ge(null),[c,g]=Ge(null),[C,b]=Ge(),x=Xt(C);x.current=C;let[P,m]=Ge([]),[k,y]=Ge([]),[I,F]=Ge([]),[E,O]=Ge(3600),[T,U]=Ge(null),[K,R]=Ge(!1),[D,q]=Ge(""),[N,w]=Ge(null),Z=Xt(null),[S,J]=Ge(!1),[V,ie]=Ge(""),j=()=>d.current&&a.current.identity===i&&a.current.client===n,oe=async()=>{let X=++l.current,we=await Tr(()=>n.list(i,{limit:20,...x.current===void 0?{}:{before:x.current}}));if(!j()||X!==l.current)throw Error("Refresh superseded");if(!we.ok)throw ie(we.error.message),Error("Share refresh failed");g(we.data),u(i)},H=Xt(oe);H.current=oe,zn(()=>(d.current=!0,()=>{d.current=!1,++l.current}),[]),zn(()=>{if(a.current.identity!==i||a.current.client!==n)return;u(null),g(null),y([]),F([]),U(null),R(!1),q(""),w(null),Z.current=null,J(!1),ie(""),b(void 0),m([]),x.current=void 0,H.current().catch(()=>{})},[i,n]),zn(()=>{if(x.current===C&&p===i)H.current().catch(()=>{})},[C,p,i]),zn(()=>(o?.(()=>H.current()),()=>o?.(null)),[o]);let M=()=>{if(!K)U(null)},W=async()=>{if(S||!T||p!==i)return;let X=T;J(!0),R(!0),ie("");let we=await Tr(()=>n.create(i,X));if(!j())return;if(J(!1),!we.ok){ie(we.error.message);return}q(r(we.data,X.key)),U(null),R(!1),b(void 0),m([]),x.current=void 0,await H.current().catch(()=>{})},ee=async()=>{if(S||!N||p!==i)return;let X=N;Z.current??=crypto.randomUUID();let we=Z.current;J(!0),ie("");let ae=await Tr(()=>n.revoke(i,X.id,{expectedVersion:X.version,idempotencyKey:we}));if(!j())return;if(J(!1),!ae.ok){ie(ae.error.message),await H.current().catch(()=>{});return}w(null),Z.current=null,q(""),await H.current().catch(()=>{})},de=e.fields.filter((X)=>!["linkedRecord","lookup","formula","rollup"].includes(X.type)),me=S||K;return Ee("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Ee("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[ve("h3",{className:"font-medium",children:"Read-only sharing"}),ve("button",{type:"button",disabled:S,onClick:()=>{ie(""),H.current().catch(()=>{})},children:"Refresh share grants"})]}),ve("p",{className:"text-sm",children:"Select the exact basic fields and stable record IDs. Links expose current selected values until expiry or revocation. Schema changes close access."}),ve("p",{className:"text-xs",children:"Relations, computed fields, attachments, discussions, history and writes are excluded. Up to 100 records, 20 active grants and 24 hours per grant. Keys are shown only when created."}),V&&ve("p",{role:"alert",children:V}),Ee("fieldset",{disabled:me,className:"flex min-w-0 flex-col gap-2",children:[ve("legend",{children:"Fields to share"}),de.map((X)=>Ee("label",{className:"break-all",children:[ve("input",{type:"checkbox","aria-label":`Share field ${X.name}`,checked:k.includes(X.id),onChange:(we)=>{M(),y((ae)=>we.target.checked?[...ae,X.id]:ae.filter((Se)=>Se!==X.id))}})," ",X.name]},X.id))]}),Ee("fieldset",{disabled:me,className:"flex min-w-0 flex-col gap-2",children:[ve("legend",{children:"Records on the current page"}),t.slice(0,100).map((X)=>Ee("label",{className:"break-all",children:[ve("input",{type:"checkbox","aria-label":`Share record ${X}`,checked:I.includes(X),onChange:(we)=>{M(),F((ae)=>we.target.checked?[...ae,X]:ae.filter((Se)=>Se!==X))}})," ",X]},X)),t.length===0&&ve("p",{children:"Load records in Grid to choose a share scope."})]}),Ee("p",{className:"break-all text-xs",children:["Selected record IDs: ",I.join(", ")||"none"]}),Ee("label",{children:["Link lifetime"," ",Ee("select",{"aria-label":"Share link lifetime",disabled:me,value:E,onChange:(X)=>{M(),O(Number(X.target.value))},children:[ve("option",{value:60,children:"1 minute"}),ve("option",{value:3600,children:"1 hour"}),ve("option",{value:86400,children:"24 hours"})]})]}),ve("button",{type:"button",className:"self-start",disabled:me||p!==i||!k.length||!I.length||I.length>100||k.some((X)=>!de.some((we)=>we.id===X)),onClick:()=>{ie("");try{U({expectedSchemaVersion:e.schemaVersion,fieldIds:[...k],recordIds:[...I],expiresInSeconds:E,key:cs(),idempotencyKey:crypto.randomUUID()})}catch{ie("A secure share key could not be generated.")}},children:"Review read-only share"}),T&&Ee("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[Ee("p",{className:"break-all",children:["Confirm schema ",T.expectedSchemaVersion,", fields ",T.fieldIds.join(", "),", records ",T.recordIds.join(", ")," for ",T.expiresInSeconds," seconds."]}),T.expectedSchemaVersion!==e.schemaVersion&&ve("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),Ee("div",{className:"flex flex-wrap gap-3",children:[ve("button",{type:"button",disabled:S,onClick:()=>void W(),children:K?"Retry create read link":"Create read link"}),ve("button",{type:"button",disabled:S,onClick:()=>{U(null),R(!1),ie("")},children:"Discard share confirmation"})]}),K&&ve("p",{className:"text-xs",children:"If the response was lost, retry returns the same grant. A discarded committed grant remains in the directory and can be revoked."})]}),D&&Ee("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",ve("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:D,onFocus:(X)=>X.target.select()})]}),!c||p!==i?ve("p",{role:"status",children:"Loading share grants…"}):Ee(gi,{children:[c.items.length===0&&ve("p",{children:"No share grants yet."}),ve("ol",{className:"flex min-w-0 flex-col gap-2",children:c.items.map((X)=>Ee("li",{className:"min-w-0 rounded border p-2",children:[Ee("p",{className:"break-all",children:["Grant ",X.id," · version ",X.version," · schema ",X.schemaVersion]}),Ee("p",{className:"break-all text-xs",children:["Fields: ",X.fieldIds.join(", ")," · Records: ",X.recordIds.join(", ")," · Expires:"," ",X.expiresAt]}),X.revokedAt?ve("p",{children:"Share revoked"}):Ee(gi,{children:[ve("p",{children:X.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(X.expiresAt)<=Date.now()?"Share expired":"Share active"}),ve("button",{type:"button",disabled:S,"aria-label":`Revoke share ${X.id}`,onClick:()=>{w(X),Z.current=null},children:"Revoke"})]})]},X.id))}),Ee("div",{className:"flex flex-wrap gap-3",children:[ve("button",{type:"button",disabled:S||!P.length,onClick:()=>{b(P.at(-1)),m((X)=>X.slice(0,-1))},children:"Newer share grants"}),ve("button",{type:"button",disabled:S||c.nextCursor===null,onClick:()=>{m((X)=>[...X,C]),b(c.nextCursor??void 0)},children:"Older share grants"})]})]}),N&&Ee("div",{children:[Ee("p",{className:"break-all",children:["Revoke grant ",N.id," at version ",N.version,"? Every existing share session will lose access."]}),Ee("div",{className:"flex flex-wrap gap-3",children:[ve("button",{type:"button",disabled:S,onClick:()=>void ee(),children:"Confirm revoke share"}),ve("button",{type:"button",disabled:S,onClick:()=>{w(null),Z.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as mi,useRef as en,useState as Ue}from"react";import{jsx as pe,jsxs as De}from"react/jsx-runtime";var fi=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],ps=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function gs({descriptor:e,recordIds:t,client:n,webhookRequest:r}){let o=e.id,i=en({id:o,client:n});i.current={id:o,client:n};let a=en(!0),d=en(0),[l,p]=Ue([]),[u,c]=Ue(""),g=en(u);g.current=u;let[C,b]=Ue(null),[x,P]=Ue(),m=en(x);m.current=x;let[k,y]=Ue(""),[I,F]=Ue("record"),[E,O]=Ue(60),[T,U]=Ue([]),[K,R]=Ue([]),[D,q]=Ue({}),[N,w]=Ue(null),[Z,S]=Ue(!1),[J,V]=Ue(!1),[ie,j]=Ue(""),[oe,H]=Ue(""),M=()=>a.current&&i.current.id===o&&i.current.client===n,W=async(B)=>{try{return await B()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},ee=async()=>{let B=++d.current,h=await W(()=>n.list(o));if(!M()||B!==d.current)return;if(!h.ok){j(h.error.message);return}p(h.data);let z=h.data.find((Oe)=>Oe.id===g.current)?.id??h.data[0]?.id??"";if(g.current=z,c(z),!z){b(null);return}let Q=await W(()=>n.runs(o,z,{limit:20,...m.current?{before:m.current}:{}}));if(!M()||B!==d.current||g.current!==z)return;if(Q.ok)b(Q.data);else j(Q.error.message)},de=en(ee);de.current=ee,mi(()=>{if(i.current.id!==o||i.current.client!==n)return;a.current=!0,de.current();let B=setInterval(()=>void de.current(),5000);return()=>{a.current=!1,++d.current,clearInterval(B)}},[o,n]),mi(()=>{if(g.current!==u||m.current!==x)return;de.current()},[u,x]);let me=()=>{if(j(""),!k.trim()||!T.length||I!=="record"&&!K.length){j("Choose a name, writable fields, and target records for time or webhook triggers.");return}let B=Object.fromEntries(T.map((z)=>[z,D[z]??null])),h={expectedSchemaVersion:e.schemaVersion,name:k.trim(),trigger:I==="time"?{kind:I,intervalSeconds:E}:{kind:I},targetRecordIds:K,values:B,idempotencyKey:crypto.randomUUID(),...I==="webhook"?{webhookKey:ps()}:{}};w({kind:"create",input:h}),S(!1)},X=(B)=>{w(B),S(!1),j("")},we=async()=>{if(!N||J)return;let B=N,h=Z;S(!0),V(!0),j("");let z=await W(()=>B.kind==="create"?n.create(o,B.input):B.kind==="toggle"?n.toggle(o,B.a.id,B.input):B.kind==="run"?n.runNow(o,B.a.id,B.input):n.retry(o,B.a.id,B.run.id,B.input));if(!M())return;if(V(!1),!z.ok){if(!h&&z.error.status>=400&&z.error.status<500)S(!1);j(`${z.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(B.kind==="create"){let Q=z.data;if(g.current=Q.id,c(Q.id),B.input.webhookKey&&r)H(JSON.stringify(r(Q,B.input.webhookKey),null,2));y(""),U([]),R([]),q({})}w(null),S(!1),m.current=void 0,P(void 0),await de.current()},ae=l.find((B)=>B.id===u),Se=!!N||J;return De("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[pe("p",{children:"Update chosen fields through record changes, a timed interval or a private webhook. Runs keep their original schema and record versions. Automatic changes do not trigger another automation."}),pe("button",{type:"button",onClick:()=>void de.current(),children:"Refresh automation"}),ie&&pe("p",{role:"alert",children:ie}),pe("form",{onSubmit:(B)=>{B.preventDefault(),me()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:De("fieldset",{disabled:Se,style:{minWidth:0},children:[pe("legend",{children:"New automation"}),De("label",{children:["Name"," ",pe("input",{"aria-label":"Automation name",value:k,maxLength:200,onChange:(B)=>y(B.target.value)})]}),De("label",{children:["Trigger"," ",De("select",{"aria-label":"Automation trigger",value:I,onChange:(B)=>F(B.target.value),children:[pe("option",{value:"record",children:"Record changes"}),pe("option",{value:"time",children:"Timed interval"}),pe("option",{value:"webhook",children:"Private webhook"})]})]}),I==="time"&&De("label",{children:["Interval in seconds"," ",pe("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:E,onChange:(B)=>O(Number(B.target.value))})]}),De("fieldset",{children:[pe("legend",{children:"Fields to update"}),e.fields.filter((B)=>fi.includes(B.type)).map((B)=>De("label",{style:{display:"block"},children:[pe("input",{type:"checkbox",checked:T.includes(B.id),onChange:(h)=>{U(h.target.checked?[...T,B.id]:T.filter((z)=>z!==B.id))}}),B.name]},B.id))]}),pe(bn,{fields:e.fields.filter((B)=>T.includes(B.id)&&fi.includes(B.type)),values:D,onChange:q}),De("fieldset",{children:[pe("legend",{children:"Target records from this page"}),I==="record"&&pe("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&pe("p",{children:"Open a grid page to choose fixed records."}),t.map((B)=>De("label",{style:{display:"block",overflowWrap:"anywhere"},children:[pe("input",{type:"checkbox","aria-label":`Automation target ${B}`,checked:K.includes(B),onChange:(h)=>R(h.target.checked?[...K,B]:K.filter((z)=>z!==B))}),B]},B))]}),pe("button",{type:"submit",children:"Review automation"})]})}),N&&De("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[pe("p",{children:N.kind==="create"?`Create ${N.input.name} using schema ${N.input.expectedSchemaVersion}; ${N.input.targetRecordIds.length||"event"} targets.`:N.kind==="toggle"?`${N.input.enabled?"Enable":"Disable"} ${N.a.name}. Disabling fences queued and running work.`:N.kind==="run"?`Run ${N.a.name} for ${N.input.recordIds.length} explicitly selected records.`:`Retry ${N.a.name}, run ${N.run.sequence}, using its original record versions.`}),N.kind==="create"&&pe("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(N.input.values,null,2)}),pe("button",{type:"button",disabled:J,onClick:()=>void we(),children:J?"Confirming…":Z?"Retry automation confirmation":"Confirm automation"}),pe("button",{type:"button",disabled:Z||J,onClick:()=>w(null),children:"Cancel automation review"}),Z&&pe("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),oe&&De("div",{children:[pe("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),pe("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:oe}),pe("button",{type:"button",onClick:()=>H(""),children:"Hide webhook key"})]}),l.length>0&&De("label",{children:["Automation"," ",pe("select",{"aria-label":"Selected automation",disabled:Se,value:u,onChange:(B)=>{g.current=B.target.value,m.current=void 0,P(void 0),c(B.target.value),b(null)},children:l.map((B)=>pe("option",{value:B.id,children:B.name},B.id))})]}),ae&&De("div",{children:[De("p",{children:[ae.enabled?"Enabled":"Disabled"," · ",ae.trigger.kind," · schema ",ae.schemaVersion," · configuration ",ae.version]}),pe("button",{type:"button",disabled:Se,onClick:()=>X({kind:"toggle",a:ae,input:{expectedVersion:ae.version,enabled:!ae.enabled,idempotencyKey:crypto.randomUUID()}}),children:ae.enabled?"Review disable automation":"Review enable automation"}),pe("button",{type:"button",disabled:Se||!ae.enabled||!(ae.targetRecordIds.length||t.length),onClick:()=>X({kind:"run",a:ae,input:{recordIds:ae.targetRecordIds.length?ae.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),C&&De("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!C.items.length&&pe("p",{children:"No runs yet."}),C.items.map((B)=>De("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[De("p",{children:["Run ",B.sequence," · ",B.triggerKind," · ",B.status," · step ",B.step]}),De("p",{children:["Attempts: evaluate ",B.stepAttempts.evaluate,", apply ",B.stepAttempts.apply," · original versions: ",B.expectedRows.map((h)=>`${h.id}: ${h.version}`).join(", ")]}),B.errorCode&&pe("p",{role:"status",children:B.errorCode}),B.leaseUntil&&De("p",{children:["Lease expires ",B.leaseUntil]}),ae&&B.status==="failed"&&De("button",{type:"button",disabled:Se||!ae.enabled,onClick:()=>X({kind:"retry",a:ae,run:B,input:{expectedVersion:B.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",B.sequence]})]},B.id)),pe("button",{type:"button",disabled:Se||x===void 0,onClick:()=>{m.current=void 0,P(void 0)},children:"Newest runs"}),pe("button",{type:"button",disabled:Se||C.nextCursor===null,onClick:()=>{m.current=C.nextCursor??void 0,P(m.current)},children:"Older runs"})]})]})}import{useEffect as ms,useId as fs,useRef as yi,useState as Be}from"react";import{jsx as xe,jsxs as Te}from"react/jsx-runtime";var bi=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function ys(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 o of[n.sourceFieldIds,n.targetFieldIds])if(o.length<1||o.length>10||new Set(o).size!==o.length||o.some((i)=>!e.fields.some((a)=>a.id===i&&bi.includes(a.type))))throw Error("Choose up to ten basic source and target fields.");let r=n.recordIds.map((o)=>{let i=t.find((a)=>a.id===o);if(!i)throw Error("A selected record is no longer on this page.");return{id:o,expectedVersion:i.version}});return structuredClone({expectedSchemaVersion:e.schemaVersion,resourceId:n.resourceId,model:n.model.trim(),instruction:n.instruction,records:r,sourceFieldIds:n.sourceFieldIds,targetFieldIds:n.targetFieldIds,idempotencyKey:crypto.randomUUID()})}function bs({descriptor:e,records:t,client:n,onApplied:r}){let o=fs(),i=e.id,a=yi({id:i,client:n}),d=yi(!0);a.current={id:i,client:n};let[l,p]=Be([]),[u,c]=Be(!1),[g,C]=Be(""),[b,x]=Be(""),[P,m]=Be(""),[k,y]=Be([]),[I,F]=Be([]),[E,O]=Be([]),[T,U]=Be(null),[K,R]=Be(null),[D,q]=Be(null),[N,w]=Be(!1),[Z,S]=Be(!1),[J,V]=Be(""),[ie,j]=Be(""),[oe,H]=Be(""),M=()=>d.current&&a.current.id===i&&a.current.client===n,W=async(h)=>{try{return await h()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};ms(()=>{d.current=!0,U(null),R(null),q(null),w(!1),V(""),j(""),H(""),y([]),F([]),O([]),m("");let h=!0;return c(!1),S(!1),p([]),C(""),x(""),n.providers(i).then((z)=>{if(!h||a.current.id!==i||a.current.client!==n)return;if(c(!0),z.ok)p(z.data),C(z.data[0]?.resourceId??""),x(z.data[0]?.allowedModels[0]??"");else V(z.error.message)}).catch(()=>{if(h)c(!0),V("AI configuration is unavailable.")}),()=>{h=!1,d.current=!1}},[i,n]);let ee=()=>{try{let h=ys(e,t,{resourceId:g,model:b,instruction:P,recordIds:k,sourceFieldIds:I,targetFieldIds:E});R(structuredClone(h.records.map((z)=>({id:z.id,version:z.expectedVersion,values:Object.fromEntries(h.sourceFieldIds.map((Q)=>[Q,t.find((Oe)=>Oe.id===z.id)?.values[Q]??null]))})))),U(h),w(!1),V(""),j("")}catch(h){V(h instanceof Error?h.message:"Invalid selection.")}},de=async()=>{if(!T||Z)return;let h=T,z=N;S(!0),w(!0),V("");let Q=await W(()=>n.propose(i,h));if(!M())return;if(S(!1),!Q.ok){if(!z&&Q.error.status>=400&&Q.error.status<500)w(!1);V(`${Q.error.message} Retry keeps the original selection and versions.`);return}q(Q.data),H(Q.data.id),w(!1)},me=async()=>{if(!D||Z)return;let h=D,z=N;S(!0),w(!0),V("");let Q=await W(()=>n.confirm(i,h));if(!M())return;if(S(!1),!Q.ok){if(!z&&Q.error.status>=400&&Q.error.status<500)w(!1);V(`${Q.error.message} The reviewed proposal keeps its original versions.`);return}j(`${Q.data.items.length} records filled${Q.data.replayed?"; original receipt recovered":""}.`),q(null),U(null),R(null),w(!1);try{await r?.()}catch{if(M())V("The fill committed. Refresh the Collection to see its records.")}},X=async()=>{if(Z||T||D)return;S(!0),V("");let h=await W(()=>n.get(i,oe));if(!M())return;if(S(!1),h.ok)q(h.data),w(!1),j("");else V(h.error.message)},we=(h,z,Q)=>Q(h.includes(z)?h.filter((Oe)=>Oe!==z):[...h,z]),ae=Z||!!T||!!D,Se=e.fields.filter((h)=>bi.includes(h.type)),B=l.find((h)=>h.resourceId===g);return Te("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[xe("p",{children:"Choose the records and fields to send to your configured AI service. Review suggested values before writing. Conflicts keep the original record versions."}),J&&xe("p",{role:"alert",children:J}),ie&&xe("p",{role:"status",children:ie}),u&&l.length===0&&xe("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),xe("form",{onSubmit:(h)=>{h.preventDefault(),ee()},children:Te("fieldset",{disabled:ae,style:{minWidth:0},children:[xe("legend",{children:"AI fill request"}),Te("label",{children:["AI resource"," ",Te("select",{"aria-label":"AI resource",value:g,onChange:(h)=>{C(h.target.value),x(l.find((z)=>z.resourceId===h.target.value)?.allowedModels[0]??"")},children:[xe("option",{value:"",children:"Choose resource"}),l.map((h)=>xe("option",{value:h.resourceId,children:h.name},h.resourceId))]})]}),Te("label",{htmlFor:o,children:["Model"," ",B?.allowedModels.length?xe("select",{id:o,"aria-label":"AI model",value:b,onChange:(h)=>x(h.target.value),children:B.allowedModels.map((h)=>xe("option",{value:h,children:h},h))}):xe("input",{id:o,"aria-label":"AI model",maxLength:200,value:b,onChange:(h)=>x(h.target.value)})]}),Te("label",{children:["Instructions"," ",xe("textarea",{"aria-label":"AI instructions",maxLength:2000,value:P,onChange:(h)=>m(h.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),Te("fieldset",{children:[xe("legend",{children:"Source fields to send"}),Se.map((h)=>Te("label",{style:{display:"block"},children:[xe("input",{type:"checkbox","aria-label":`Send ${h.name}`,checked:I.includes(h.id),onChange:()=>we(I,h.id,F)}),h.name]},h.id))]}),Te("fieldset",{children:[xe("legend",{children:"Fields to fill"}),Se.map((h)=>Te("label",{style:{display:"block"},children:[xe("input",{type:"checkbox","aria-label":`Fill ${h.name}`,checked:E.includes(h.id),onChange:()=>we(E,h.id,O)}),h.name]},h.id))]}),Te("fieldset",{children:[xe("legend",{children:"Target records from this page"}),t.map((h)=>Te("label",{style:{display:"block",overflowWrap:"anywhere"},children:[xe("input",{type:"checkbox","aria-label":`AI record ${h.id}`,checked:k.includes(h.id),onChange:()=>we(k,h.id,y)}),h.id," · version ",h.version]},h.id))]}),xe("button",{type:"submit",disabled:!g,children:"Review AI request"})]})}),T&&!D&&Te("section",{"aria-label":"AI data disclosure",children:[Te("p",{children:["Selected service: ",T.resourceId," · model ",T.model," · schema"," ",T.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),xe("p",{children:T.instruction}),xe("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(K,null,2)}),xe("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),xe("button",{type:"button",disabled:Z,onClick:()=>void de(),children:N?"Retry original AI request":"Generate proposal"}),xe("button",{type:"button",disabled:Z||N,onClick:()=>{U(null),R(null),V("")},children:"Cancel AI request"})]}),D&&Te("section",{"aria-label":"AI fill confirmation",children:[Te("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",D.id," · ",D.provider," · schema ",D.schemaVersion]}),D.schemaVersion!==e.schemaVersion&&xe("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),D.rows.map((h)=>Te("div",{style:{overflowWrap:"anywhere"},children:[Te("p",{children:[h.id," · original version ",h.expectedVersion]}),Object.keys(h.values).map((z)=>Te("div",{children:[xe("strong",{children:e.fields.find((Q)=>Q.id===z)?.name??z}),Te("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(h.before[z]),`
10
- `,"Suggested: ",JSON.stringify(h.values[z])]})]},z))]},h.id)),xe("button",{type:"button",disabled:Z,onClick:()=>void me(),children:N?"Retry original AI fill":"Confirm fill"}),xe("button",{type:"button",disabled:Z||N,onClick:()=>{q(null),U(null),R(null),V("")},children:"Dismiss proposal"})]}),Te("label",{children:["Recover a saved proposal"," ",xe("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:oe,onChange:(h)=>H(h.target.value),disabled:ae,style:{width:"100%",boxSizing:"border-box"}})]}),xe("button",{type:"button",disabled:ae||!/^[a-f0-9]{64}$/.test(oe),onClick:()=>void X(),children:"Load saved proposal"})]})}import{jsx as te,jsxs as ge}from"react/jsx-runtime";var Cs=[{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 wp({fields:e,onChange:t,lockedIds:n=[],collections:r=[]}){let o=(i,a)=>t(e.map((d,l)=>l===i?{...d,...a}:d));return ge("div",{className:"flex flex-col gap-3",children:[e.map((i,a)=>{let d=n.includes(i.id);return ge("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)] gap-2 rounded-md border p-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_150px_auto]",children:[te("input",{"aria-label":`Field ${a+1} name`,placeholder:"Display name",value:i.name,onChange:(l)=>o(a,{name:l.target.value})}),te("input",{"aria-label":`Field ${a+1} ID`,placeholder:"field_id",value:i.id,disabled:d,onChange:(l)=>o(a,{id:l.target.value})}),te("select",{"aria-label":`Field ${a+1} type`,className:"rounded-md border bg-background px-2 text-sm",value:i.type,disabled:d,onChange:(l)=>{let p=l.target.value,u={id:i.id,name:i.name,type:p,required:Fe({type:p})?!1:i.required??!1};if(p==="formula")u.formula={expression:""};if(p==="rollup")u.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(p==="singleSelect"||p==="multipleSelect")u.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((c,g)=>g===a?u:c))},children:Cs.map((l)=>te("option",{value:l.value,children:l.name},l.value))}),ge("div",{className:"flex items-center gap-2",children:[ge("label",{className:"flex items-center gap-1 text-xs",children:[te("input",{type:"checkbox",checked:i.required??!1,disabled:d||n.length>0||Fe(i),onChange:(l)=>o(a,{required:l.target.checked})}),"Required"]}),!d&&te("button",{type:"button",onClick:()=>t(e.filter((l,p)=>p!==a)),children:"Remove"})]}),(i.type==="singleSelect"||i.type==="multipleSelect")&&te("input",{className:"md:col-span-4","aria-label":`Field ${a+1} options`,placeholder:"Open, Done",value:i.options?.map((l)=>l.name).join(", ")??"",disabled:d,onChange:(l)=>o(a,{options:l.target.value.split(",").map((p,u)=>({id:p.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${u}`,name:p.trim()})).filter((p)=>p.name)})}),i.type==="linkedRecord"&&ge("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ge("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",ge("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} linked collection`,value:i.link?.collectionId??"",disabled:d,onChange:(l)=>{let p=r.find((u)=>u.id===l.target.value);o(a,{link:{collectionId:l.target.value,displayFieldId:p?.fields.find((u)=>u.type==="singleLineText"||u.type==="longText")?.id??""}})},children:[te("option",{value:"",children:"Choose collection…"}),r.map((l)=>te("option",{value:l.id,children:l.name},l.id))]})]}),ge("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",ge("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} record label`,value:i.link?.displayFieldId??"",disabled:d||!i.link?.collectionId,onChange:(l)=>o(a,{link:{collectionId:i.link?.collectionId??"",displayFieldId:l.target.value}}),children:[te("option",{value:"",children:"Choose text field…"}),r.find((l)=>l.id===i.link?.collectionId)?.fields.filter((l)=>l.type==="singleLineText"||l.type==="longText").map((l)=>te("option",{value:l.id,children:l.name},l.id))]})]})]}),i.type==="lookup"&&ge("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ge("label",{children:["Through linked field"," ",ge("select",{"aria-label":`Field ${a+1} lookup link`,value:i.lookup?.linkFieldId??"",disabled:d,onChange:(l)=>o(a,{lookup:{linkFieldId:l.target.value,targetFieldId:""}}),children:[te("option",{value:"",children:"Choose linked field…"}),e.filter((l)=>l.type==="linkedRecord"&&l.link).map((l)=>te("option",{value:l.id,children:l.name},l.id))]})]}),ge("label",{children:["Read target field"," ",ge("select",{"aria-label":`Field ${a+1} lookup target`,value:i.lookup?.targetFieldId??"",disabled:d||!i.lookup?.linkFieldId,onChange:(l)=>o(a,{lookup:{linkFieldId:i.lookup?.linkFieldId??"",targetFieldId:l.target.value}}),children:[te("option",{value:"",children:"Choose target field…"}),r.find((l)=>l.id===e.find((p)=>p.id===i.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((l)=>!Fe(l)&&l.type!=="linkedRecord").map((l)=>te("option",{value:l.id,children:l.name},l.id))]})]}),te("small",{children:"Computed from linked records. Values cannot be edited."})]}),i.type==="formula"&&ge("div",{className:"flex flex-col gap-1 md:col-span-4",children:[ge("label",{children:["Formula",te("textarea",{"aria-label":`Field ${a+1} formula`,maxLength:2048,className:"min-h-16 w-full rounded-md border bg-background p-2",placeholder:"{quantity} * {price}",value:i.formula?.expression??"",onChange:(l)=>o(a,{formula:{expression:l.target.value}})})]}),te("small",{children:"Use numbers, stable field references, + - * / and parentheses. Text and date functions: CONCAT, UPPER, LOWER, TRIM, DATE_ADD_DAYS, DATE_DIFF_DAYS. Empty inputs produce an empty result."}),ge("small",{children:["References:"," ",e.filter((l)=>l.id!==i.id&&(l.type==="singleLineText"||l.type==="longText"||l.type==="date"||l.type==="number"||l.type==="formula"||l.type==="rollup")).map((l)=>`{${l.id}}`).join(", ")||"None yet"]})]}),i.type==="rollup"&&ge("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ge("label",{children:["Through linked field"," ",ge("select",{"aria-label":`Field ${a+1} rollup link`,value:i.rollup?.linkFieldId??"",onChange:(l)=>o(a,{rollup:{linkFieldId:l.target.value,targetFieldId:"",function:i.rollup?.function??"sum"}}),children:[te("option",{value:"",children:"Choose linked field…"}),e.filter((l)=>l.type==="linkedRecord"&&l.link).map((l)=>te("option",{value:l.id,children:l.name},l.id))]})]}),ge("label",{children:["Aggregate"," ",ge("select",{"aria-label":`Field ${a+1} rollup function`,value:i.rollup?.function??"sum",onChange:(l)=>{let p=l.target.value,u=r.find((c)=>c.id===e.find((g)=>g.id===i.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((c)=>c.id===i.rollup?.targetFieldId);o(a,{rollup:{linkFieldId:i.rollup?.linkFieldId??"",targetFieldId:p==="count"||u?.type==="number"?i.rollup?.targetFieldId??"":"",function:p}})},children:[te("option",{value:"sum",children:"Sum"}),te("option",{value:"average",children:"Average"}),te("option",{value:"min",children:"Minimum"}),te("option",{value:"max",children:"Maximum"}),te("option",{value:"count",children:"Count values"})]})]}),ge("label",{children:["Target field"," ",ge("select",{"aria-label":`Field ${a+1} rollup target`,value:i.rollup?.targetFieldId??"",disabled:!i.rollup?.linkFieldId,onChange:(l)=>o(a,{rollup:{linkFieldId:i.rollup?.linkFieldId??"",targetFieldId:l.target.value,function:i.rollup?.function??"sum"}}),children:[te("option",{value:"",children:"Choose target field…"}),r.find((l)=>l.id===e.find((p)=>p.id===i.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((l)=>!Fe(l)&&l.type!=="linkedRecord"&&(i.rollup?.function==="count"||l.type==="number")).map((l)=>te("option",{value:l.id,children:l.name},l.id))]})]}),te("small",{className:"w-full",children:"Null targets are skipped. Count counts values; empty sum/count are zero. Other empty aggregates have no result."})]})]},a)}),te("button",{type:"button",className:"self-start",onClick:()=>t([...e,{id:`field_${crypto.randomUUID().replaceAll("-","").slice(0,8)}`,name:"New field",type:"singleLineText",required:!1}]),children:"Add field"})]})}function xs(e,t,n){if(Fe(e)||e.type==="blob")return"";if(e.type==="linkedRecord"||e.type==="relation"){let r=t==null||t===""||Array.isArray(t)&&t.length===0;if(e.required&&r)return n==="zh-CN"?`请填写${e.name}。`:`${e.name} is required.`;return""}return Yt(e,Re(t),n)}function Fr(e,t,n,r){let o=Object.create(null);for(let i of e){if(i.type==="lookup"||i.type==="formula"||i.type==="rollup"||i.type==="blob"||i.generation==="autoIncrement")continue;if(!Object.hasOwn(t,i.id)){if(i.required)throw Error(n("{name} is required.",{name:i.name}));continue}let a=t[i.id];if(i.type==="linkedRecord"){if(!Array.isArray(a)||a.some((d)=>typeof d!=="string")||a.length>100||new Set(a).size!==a.length)throw Error(n("{name} needs unique linked records.",{name:i.name}));if(i.required&&!a.length)throw Error(n("{name} is required.",{name:i.name}));o[i.id]=a;continue}if(i.type==="relation"){if(a==null||a===""){if(i.required)throw Error(n("{name} is required.",{name:i.name}));o[i.id]=null;continue}if(typeof a!=="string")throw Error(n("{name} needs a server-provided option.",{name:i.name}));o[i.id]=a;continue}if(i.type==="hyperlink"&&a!==null&&typeof a==="object"){if(!Ht(a))throw Error(n("{name} needs a link.",{name:i.name}));o[i.id]=a;continue}if(i.required&&typeof a==="string"&&!a.trim())throw Error(n("{name} is required.",{name:i.name}));o[i.id]=tt(Array.isArray(a)?a.join(","):String(a??""),i,r)}return o}function bn({fields:e,values:t,onChange:n,relationClient:r,linkedRecords:o,computedErrors:i,locale:a,ui:d,submitted:l=!1}){let p=he(a),u=hs();return te("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((c)=>{let g=c.description?.trim()??"",C=g?`${u}-${c.id}-hint`:void 0,b=xs(c,t[c.id],a??"en"),P=Boolean(c.required&&Re(t[c.id])===""&&b)&&!l?"":b,m=P?`${u}-${c.id}-error`:void 0,k=[C,m].filter(Boolean).join(" "),y={...k?{"aria-describedby":k}:{},...P?{"aria-invalid":!0}:{}};return ge("div",{className:"flex flex-col gap-1 text-sm",children:[ge("label",{htmlFor:`${u}-${c.id}`,children:[c.name,c.required?" *":""]}),g?te("p",{id:C,className:"m-0 text-xs opacity-70",children:g}):null,Fe(c)?te("output",{id:`${u}-${c.id}`,"aria-label":p("{name} (read only)",{name:c.name}),...y,children:c.type==="lookup"?St(t[c.id]):Qt(t[c.id],i?.[c.id],a)}):c.type==="linkedRecord"?te(Ln,{...a?{locale:a}:{},field:c,value:t[c.id],labels:o?.[c.id],client:r,onChange:(I)=>n({...t,[c.id]:I}),...y}):c.type==="checkbox"?te("input",{id:`${u}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,type:"checkbox",checked:t[c.id]===!0,onChange:(I)=>n({...t,[c.id]:I.target.checked}),...y}):c.type==="singleSelect"&&d?.Select?te(si,{ui:d,label:`${c.name}${c.required?" *":""}`,...y,value:String(t[c.id]??""),options:[{value:"",label:p("Choose…")},...(c.options??[]).map((I)=>({value:I.id,label:I.name}))],onChange:(I)=>n({...t,[c.id]:I||null})}):c.type==="multipleSelect"&&d?.MultiSelect?te(d.MultiSelect,{"aria-label":`${c.name}${c.required?" *":""}`,...y,options:(c.options??[]).map((I)=>({value:I.id,label:I.name,slot:un(c.options,I.id)})),values:Array.isArray(t[c.id])?t[c.id]:[],placeholder:p("Choose…"),onChange:(I)=>n({...t,[c.id]:I})}):c.type==="singleSelect"||c.type==="multipleSelect"?ge("select",{id:`${u}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...y,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:(I)=>n({...t,[c.id]:c.type==="multipleSelect"?Array.from(I.target.selectedOptions,(F)=>F.value):I.target.value||null}),children:[c.type==="singleSelect"&&te("option",{value:"",children:p("Choose…")}),c.options?.map((I)=>te("option",{value:I.id,children:I.name},I.id))]}):c.type==="date"&&d?.DatePicker?(()=>{let I={kind:dr(c),timeZone:dt(c)?.timeZone},F=String(t[c.id]??"");return te(d.DatePicker,{id:`${u}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...y,value:yr(F,I),withTime:I.kind==="auto"?Pt(F):I.kind==="datetime",fixedKind:I.kind!=="auto",clearable:!c.required,onChange:(E)=>n({...t,[c.id]:E?br(E,F,I):null})})})():c.type==="hyperlink"?te(gn,{field:c,id:`${u}-${c.id}`,ariaLabel:`${c.name}${c.required?" *":""}`,describedBy:y["aria-describedby"],invalid:Boolean(P),locale:a,inputClassName:"min-h-9 min-w-0 rounded-md border bg-background p-2",text:typeof t[c.id]==="string"?String(t[c.id]):pn(Ht(t[c.id])?t[c.id]:null),onChange:(I)=>{let F=I.trim().startsWith("{")?Mt(I):null;n({...t,[c.id]:F??(I||null)})}}):c.type==="longText"?te("textarea",{id:`${u}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...y,className:"rounded-md border bg-background p-2",value:String(t[c.id]??""),onChange:(I)=>n({...t,[c.id]:I.target.value||null})}):te("input",{id:`${u}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...y,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:(I)=>n({...t,[c.id]:I.target.value===""?null:c.type==="number"?Number(I.target.value):c.type==="date"&&t[c.id]?ii(t[c.id],I.target.value):I.target.value})}),P?te("span",{id:m,className:"text-xs text-red-600",children:P}):null]},c.id)})})}function vs(e,t,n){if(t==="isEmpty")return;let r=Fe(e)?e.resultType:e.type;if(r==="number"){if(t!=="is"&&t!=="isNot")throw Error("Number filters support is, is not, or is empty.");let o=Number(n);if(!n.trim()||!Number.isFinite(o))throw Error("Filter needs a number.");return o}if(r==="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(r==="checkbox"){if(!["true","false"].includes(n))throw Error("Filter needs true or false.");return n==="true"}if(Fe(e)&&!Ft(e))throw Error("Computed filters are not available for this field.");if((e.type==="multipleSelect"||e.type==="linkedRecord")&&t!=="contains")return n.split(",").map((o)=>o.trim());return n}function Pp({fields:e,view:t,onChange:n,onError:r}){let o=e.filter(Ft),[i,a]=Nr(o[0]?.id??""),d=o.some((m)=>m.id===i)?i:o[0]?.id??"",[l,p]=Nr("contains"),u=d?(()=>{let m=e.find((k)=>k.id===d);return m&&Fe(m)?m.resultType:m?.type})():void 0,c=u==="number"?["is","isNot","isEmpty"]:u==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],g=c.includes(l)?l:u==="number"||u==="date"?"is":"contains",[C,b]=Nr(""),P=[...t.columnOrder.flatMap((m)=>{let k=e.find((y)=>y.id===m);return k?[k]:[]}),...e.filter((m)=>!t.columnOrder.includes(m.id))];return ge("div",{className:"flex flex-wrap items-end gap-3",children:[ge("label",{className:"flex min-w-52 flex-col gap-1 text-sm",children:["Search",te("input",{type:"search",className:"min-h-9 min-w-0 rounded-md border bg-background p-2",value:t.search??"",onChange:(m)=>n({...t,search:m.target.value})})]}),ge("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(m)=>{m.preventDefault();let k=e.find((I)=>I.id===d);if(!k)return;let y;try{y=vs(k,g,C)}catch(I){r(I instanceof Error?I.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:d,operator:g,...g==="isEmpty"?{}:{value:y}}]}})},children:[ge("label",{className:"flex flex-col gap-1 text-sm",children:["Filter field",te("select",{className:"h-9 rounded-md border bg-background px-2",value:d,onChange:(m)=>a(m.target.value),children:o.map((m)=>te("option",{value:m.id,children:m.name},m.id))})]}),te("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:g,onChange:(m)=>p(m.target.value),children:c.map((m)=>te("option",{value:m,children:m==="isNot"?"is not":m==="isEmpty"?"is empty":m==="onOrAfter"?"on or after":m},m))}),g!=="isEmpty"&&te("input",{type:u==="number"?"number":u==="date"?"date":"text",step:u==="number"?"any":void 0,className:"min-h-9 max-w-40 rounded-md border bg-background p-2","aria-label":"Filter value",value:C,onChange:(m)=>b(m.target.value)}),te("button",{type:"submit",disabled:!d,children:"Apply filter"}),te("button",{type:"button",onClick:()=>{let m={...t};delete m.filter,n(m)},children:"Clear filter"})]}),ge("details",{className:"relative",children:[te("summary",{className:"cursor-pointer rounded-md border px-3 py-2 text-sm",children:"Columns"}),te("div",{className:"absolute right-0 top-full z-10 mt-1 flex max-h-96 min-w-64 flex-col gap-2 overflow-auto rounded-md border bg-background p-3 shadow-md",children:P.map((m,k)=>ge("div",{className:"flex items-center gap-2 text-sm",children:[ge("label",{className:"flex flex-1 items-center gap-2",children:[te("input",{type:"checkbox",checked:!t.hiddenColumns.includes(m.id),disabled:t.type==="form"&&m.required===!0,onChange:(y)=>n({...t,hiddenColumns:y.target.checked?t.hiddenColumns.filter((I)=>I!==m.id):[...t.hiddenColumns,m.id]})}),m.name]}),te("button",{type:"button","aria-label":`Move ${m.name} left`,disabled:k===0,onClick:()=>{let y=P.map((F)=>F.id),I=y[k-1];if(I!==void 0)[y[k-1],y[k]]=[m.id,I];n({...t,columnOrder:y})},children:"←"}),te("button",{type:"button","aria-label":`Move ${m.name} right`,disabled:k===P.length-1,onClick:()=>{let y=P.map((F)=>F.id),I=y[k+1];if(I!==void 0)[y[k],y[k+1]]=[I,m.id];n({...t,columnOrder:y})},children:"→"})]},m.id))})]})]})}import{useEffect as ks,useMemo as hi,useState as Ci}from"react";import{jsx as Mr}from"react/jsx-runtime";function ws(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 Ps(e,t,n){let r=n.unassigned??"Unassigned";if(t===null||t===void 0)return r;if(e?.type==="singleSelect")return e.options?.find((o)=>o.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):r}function xi(e,t,n,r={},o={}){return n.map((i)=>{let a=t.groupBy.map((l)=>{let p=e.fields.find((u)=>u.id===l);return`${p?.name??l} ${Ps(p,i.groups[l],o)}`}),d=t.aggregates.map((l)=>{let p=i.values[l.as];return`${r[l.as]??l.as}: ${typeof p==="number"||typeof p==="string"?String(p):o.none??"none"}`});return[...a,...d].join(" · ")})}function Bp({descriptor:e,query:t,rows:n}){return Mr("ul",{"data-uibot":"collection-aggregate",children:xi(e,t,n).map((r)=>Mr("li",{children:r},r))})}function jn({collectionId:e,descriptor:t,view:n,groupBy:r,aggregates:o,client:i,locale:a,labels:d,reloadKey:l=0}){let p=hi(()=>Rn(n,{aggregates:o,...r?{groupBy:r}:{}}),[n,r,o]),u=hi(()=>he(a),[a]),[c,g]=Ci(u("Loading summary…")),[C,b]=Ci(!1);return ks(()=>{let x=Sn(t,p);if(x){g(u(ws(x))),b(!0);return}let P=!0;return g(u("Loading summary…")),b(!1),i.aggregate(e,p).then((m)=>{if(!P)return;if(!m.ok){g(m.error.message),b(!0);return}let k=xi(t,p,m.data,d??{},{unassigned:u("Unassigned"),checked:u("Checked"),unchecked:u("Unchecked"),none:u("none")});g(k.length?k.join(" · "):u("No summary rows.")),b(!1)}).catch(()=>{if(!P)return;g(u("The collection service is unavailable.")),b(!0)}),()=>{P=!1}},[i,e,t,p,d,u,l]),Mr("p",{role:C?"alert":"status","data-uibot":"collection-aggregate",children:c})}var ki=["grid","kanban","gallery","calendar","form"],Rs=["grid","form"],Lr={search:!0,filter:!0,columns:!0,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!0,tableList:!0,viewManagement:!0,export:!0},Ss={search:!0,filter:!1,columns:!1,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!1,tableList:!1,viewManagement:!1,export:!1},Is={search:!0,filter:!0,columns:!0,rowCreate:!1,rowUpdate:!1,rowDelete:!1,schemaEditor:!1,tableList:!0,viewManagement:!1,export:!0},vi={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:ki},Or={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:ki},wi={basic:{...vi,...Lr},full:{...Or,...Lr},simple:{...vi,...Ss,viewTypes:Rs},workbench:{...Or,...Lr},readonly:{...Or,...Is,recordContextMenu:!1,optimisticEdit:!1}};function Ut(e){let{preset:t="basic",...n}=e??{},r={...wi[t],...As(n)};return r.groupBy?r:{...r,groupCollapse:!1}}function As(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}import{jsx as le,jsxs as je,Fragment as Ur}from"react/jsx-runtime";function Zp(e){if(!e.aggregate)return null;return le(jn,{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"},Kn={padding:12,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)"},$n={items:[],total:0,nextCursor:null,limit:50};function Qp(e,t,n=!0){let r=he(e.locale),o=JSON.stringify([e.descriptor.id,e.descriptor.schemaVersion,t]),[i,a]=We({key:o,history:[]}),d=i.key===o?i.cursor:void 0,l=i.key===o?i.history:[],p=JSON.stringify([o,d]),[u,c]=We(0),[g,C]=We({key:p,page:$n,loading:n,error:""});Hn(()=>{let x=!0;if(!n){C({key:p,page:$n,loading:!1,error:""});return}C((k)=>({key:p,page:k.key===p?k.page:$n,loading:!0,error:""}));let[P,,m]=JSON.parse(o);return e.client.query(P,{...m,...d?{cursor:d}:{}}).then((k)=>{if(!x)return;if(k.ok)C({key:p,page:k.data,loading:!1,error:""});else C((y)=>({...y,loading:!1,error:k.error.message}))}).catch(()=>{if(x)C((k)=>({...k,loading:!1,error:r("Collection query failed. Retry to load records.")}))}),()=>{x=!1}},[p,o,d,e.client,e.reloadKey,n,u]);let b=g.key===p?g.page:$n;return{page:b,loading:n&&(g.key!==p||g.loading),error:g.key===p?g.error:"",previous:l.length?()=>a({key:o,cursor:l.at(-1),history:l.slice(0,-1)}):void 0,next:b.nextCursor?()=>a({key:o,cursor:b.nextCursor??void 0,history:[...l,d]}):void 0,retry:()=>c((x)=>x+1),pageNumber:l.length+1}}function Vr(e,t,n,r){return n>=t?e("{count} records total",{count:t.toLocaleString(r)}):e("{total} records · {loaded} loaded",{total:t.toLocaleString(r),loaded:n})}function Es({hasPrevious:e,hasNext:t,onPrevious:n,onNext:r,loading:o,page:i,locale:a,ui:d}){let l=he(a);if(!e&&!t)return null;return je("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[le(Ae,{ui:d,style:ze,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:l("Previous page"),disabled:!e||o,onClick:n}),i?le("span",{style:{fontSize:12},children:l("Page {page}",{page:i})}):null,le(Ae,{ui:d,style:ze,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:l("Next page"),disabled:!t||o,onClick:r})]})}function Xp({state:e,locale:t,ui:n,hideCount:r}){let o=he(t);return je("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[r?null:le("span",{children:Vr(o,e.page.total,e.page.items.length,t)}),le(Es,{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&&le("span",{role:"status",children:o("Loading records…")}),e.error&&je(Ur,{children:[le("span",{role:"alert",children:e.error}),le(Ae,{ui:n,style:ze,variant:"outline",size:"sm",disabled:e.loading,onClick:e.retry,children:o("Retry query")})]})]})}function Br(e){let t=mo(e.client,e.descriptor.id),n=he(e.locale),[r,o]=We(!1),[i,a]=We(""),[d,l]=We(null),p=hn(null);$t({dirty:Boolean(p.current),busy:r});let u=()=>{p.current=null,a(""),l(null)};return{saving:r,error:i,setError:a,remote:d,pending:p,reset:u,commit:async(C)=>{if(r||e.readOnly)return!1;p.current=C,o(!0),a(""),l(null);let b=await e.client.mutate(e.descriptor.id,C).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:n("Saving failed. Your change has been kept.")}}));if(!t.active)return!1;if(o(!1),b.ok)return u(),e.onCommitted(b.data),!0;a(b.error.message);let x=b.error.details?.current;if(x&&typeof x.id==="string"&&Number.isSafeInteger(x.version)&&x.version>0)l(x);return!1},retryRequest:()=>p.current&&d?{idempotencyKey:crypto.randomUUID(),items:p.current.items.map((C)=>C.op!=="insert"&&C.id===d.id?{...C,expectedVersion:d.version}:C)}:p.current}}function _r({mutation:e,onRetry:t,locale:n,ui:r}){let o=he(n);return je(Ur,{children:[e.error&&le("p",{role:"alert",children:e.error}),e.remote&&je("div",{style:Kn,children:[le("strong",{children:o("Current server version {version}",{version:e.remote.version})}),le("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(e.remote.values,null,2)}),le(Ae,{ui:r,style:ze,variant:"outline",size:"sm",disabled:e.saving,onClick:t,children:o("Retry against current version")})]})]})}function eg({row:e,onClose:t,onCancel:n,onDirtyChange:r,onBusyChange:o,stickyActions:i,...a}){let d=he(a.locale),l=Ut(a.features),p=!a.readOnly&&l.rowDelete,u=!a.readOnly&&l.rowUpdate,c=hn(e.values),[g,C]=We(()=>({...c.current})),[b,x]=We(!1);$t({dirty:JSON.stringify(g)!==JSON.stringify(c.current),busy:!1});let P=hn(null),[m,k]=We(!1);Hn(()=>{P.current?.focus()},[]);let y=Br(a),I=Pr(a.descriptor.fields,a.view),F=JSON.stringify(g)!==JSON.stringify(e.values);Hn(()=>{r?.(F)},[F,r]),Hn(()=>{o?.(y.saving)},[y.saving,o]);let E=async(T=!1)=>{x(!0);try{let U=T?y.retryRequest():y.pending.current;if(!U){let K=I.filter((D)=>D.type!=="lookup"&&D.type!=="formula"&&D.type!=="rollup"&&JSON.stringify(g[D.id])!==JSON.stringify(e.values[D.id]));if(!K.length){y.setError(d("Change a field before saving."));return}let R=Fr(K,g,d,a.locale);U={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:e.id,expectedVersion:e.version,values:R}]}}if(await y.commit(U))t()}catch(U){y.setError(U instanceof Error?U.message:d("Invalid value"))}},O=async()=>{let T=y.pending.current?.items[0]?.op==="delete"?y.pending.current:{idempotencyKey:crypto.randomUUID(),items:[{op:"delete",id:e.id,expectedVersion:e.version}]};if(await y.commit(T))t()};return je("div",{ref:P,tabIndex:-1,onKeyDown:(T)=>{if(T.key==="Escape"&&!y.saving)T.stopPropagation(),(n??t)()},role:"dialog","aria-label":d("{name} record",{name:Rr(e,a.descriptor.fields)}),style:{...Kn,marginTop:12},children:[le("h3",{children:Rr(e,a.descriptor.fields)}),a.onInspectRecord&&le(Ae,{ui:a.ui,style:ze,variant:"outline",size:"sm",disabled:y.saving,onClick:()=>a.onInspectRecord?.(e.id),children:d("Open record activity")}),je("form",{onSubmit:(T)=>{T.preventDefault(),E()},children:[le("fieldset",{disabled:y.saving||m||!u,style:{border:0,padding:0},children:le(bn,{fields:I,values:g,submitted:b,...a.locale?{locale:a.locale}:{},...a.ui?{ui:a.ui}:{},relationClient:a.client,linkedRecords:e.linkedRecords,computedErrors:e.computedErrors,onChange:(T)=>{C(T),y.reset()}})}),je("div",{"data-uibot":"record-editor-actions",style:i?{position:"sticky",bottom:0,zIndex:1,display:"flex",gap:8,alignItems:"center",padding:"12px 0",borderTop:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",background:"var(--background, white)"}:void 0,children:[u&&le("button",{type:"submit",style:{...ze,...On},disabled:y.saving||m,children:y.saving?d("Saving…"):d("Save record")}),i?null:le("button",{type:"button",style:ze,disabled:y.saving,onClick:n??t,children:d("Close record")}),i&&p?le("span",{style:{marginLeft:"auto"},children:le(Ae,{ui:a.ui,variant:"ghost",size:"sm",icon:"trash",disabled:y.saving,onClick:()=>k(!0),children:d("Delete record")})}):null]})]}),p&&!i&&le("button",{type:"button",style:ze,disabled:y.saving,onClick:()=>k(!0),children:d("Delete record")}),m&&a.ui?.ConfirmDialog?a.ui.ConfirmDialog({open:!0,destructive:!0,title:d("Delete this record?"),description:d("Delete this record? Your unsaved changes will be discarded after deletion."),confirmLabel:d("Delete"),cancelLabel:d("Cancel"),busy:y.saving,onConfirm:()=>void O(),onCancel:()=>{if(k(!1),y.pending.current?.items[0]?.op==="delete")y.reset()}}):null,m&&!a.ui?.ConfirmDialog&&je(Vn,{alert:!0,label:d("Confirm record deletion"),busy:y.saving,onCancel:()=>{if(k(!1),y.pending.current?.items[0]?.op==="delete")y.reset()},children:[le("p",{children:d("Delete this record? Your unsaved changes will be discarded after deletion.")}),le("button",{type:"button",style:ze,disabled:y.saving,onClick:()=>void O(),children:d("Confirm deletion")}),le("button",{type:"button",style:ze,disabled:y.saving,onClick:()=>{if(k(!1),y.pending.current?.items[0]?.op==="delete")y.reset()},children:d("Cancel deletion")})]}),le(_r,{mutation:y,onRetry:()=>void E(!0),locale:a.locale,ui:a.ui})]})}function tg(e){let t=he(e.locale),n=!e.readOnly&&Ut(e.features).rowCreate,r=hn(null),o=Pr(e.descriptor.fields,{...e.view,hiddenColumns:e.view.hiddenColumns.filter((P)=>!e.descriptor.fields.find((m)=>m.id===P)?.required)}),i=()=>({...Object.fromEntries(o.filter((P)=>P.type==="checkbox").map((P)=>[P.id,!1])),...ko(o)}),a=hn(i()),[d,l]=We(a.current),[p,u]=We(!1),[c,g]=We(!1);$t({dirty:JSON.stringify(d)!==JSON.stringify(a.current),busy:!1});let C=Br(e),b=()=>r.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")?.focus(),x=async()=>{if(!n)return;g(!0);try{let P=C.pending.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:Fr(o,d,t,e.locale)}]};if(await C.commit(P))a.current=i(),l(a.current),u(!0),g(!1),requestAnimationFrame(b)}catch(P){C.setError(P instanceof Error?P.message:t("Invalid value"))}};return je("section",{"data-uibot":"collection-form",style:Kn,children:[le("h3",{children:e.view.name}),e.readOnly&&le("p",{children:t("Record creation requires editor permission.")}),je("form",{ref:r,onSubmit:(P)=>{P.preventDefault(),x()},children:[le("fieldset",{disabled:C.saving||!n,style:{border:0,padding:0},children:le(bn,{fields:o,values:d,submitted:c,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},relationClient:e.client,onChange:(P)=>{l(P),u(!1),C.reset()}})}),n&&le("button",{type:"submit",style:{...ze,...On},disabled:C.saving,children:C.saving?t("Creating…"):t("Create record")})]}),le(_r,{mutation:C,onRetry:()=>void x(),locale:e.locale,ui:e.ui}),p?je("p",{role:"status",children:[t("Record created. Add another below."),e.onShowRecords?je(Ur,{children:[" ",le(Ae,{ui:e.ui,style:ze,variant:"outline",size:"sm",onClick:e.onShowRecords,children:t("Show records")})]}):null]}):null]})}function ng(e){let[t,n]=We(null),r=Br(e),o=!e.readOnly&&Ut(e.features).rowUpdate;return{intent:t,mutation:r,move:async(d,l)=>{if(!o||r.saving||t)return;n({row:d,values:l});let p={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:d.id,expectedVersion:d.version,values:l}]};if(await r.commit(p))n(null)},retry:async()=>{let d=r.retryRequest();if(d&&await r.commit(d))n(null)},cancel:()=>{n(null),r.reset()},blocked:r.saving||!!t}}function rg({state:e,locale:t,ui:n}){let r=he(t);if(!e.intent)return null;return je("div",{role:"dialog","aria-label":r("Pending record move"),style:Kn,children:[le("p",{children:e.mutation.saving?r("Moving record…"):r("The move has been kept for retry.")}),le("pre",{children:JSON.stringify(e.intent.values,null,2)}),le(_r,{mutation:e.mutation,onRetry:()=>void e.retry(),locale:t,ui:n}),!e.mutation.remote&&le(Ae,{ui:n,style:ze,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:()=>void e.retry(),children:r("Retry move")}),le(Ae,{ui:n,style:ze,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:e.cancel,children:r("Cancel move")})]})}import{useCallback as Ds,useEffect as Pi,useLayoutEffect as Ts,useRef as qr,useState as Ri}from"react";import{jsx as Gn,jsxs as Ai,Fragment as Ns}from"react/jsx-runtime";function Si({items:e,label:t,children:n,block:r=!1}){let[o,i]=Ri(null),a=qr(null),d=qr(null),[l,p]=Ri({x:0,y:0}),u=Ds(()=>{if(!o||!d.current)return;let g=Math.max(12,Math.min(o.x,window.innerWidth-12-d.current.offsetWidth)),C=Math.max(12,Math.min(o.y,window.innerHeight-12-d.current.offsetHeight));p((b)=>b.x===g&&b.y===C?b:{x:g,y:C})},[o]);Ts(u),Pi(()=>{if(!o)return;return window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[o,u]);let c=qr(null);return Pi(()=>{if(!o)return;c.current=document.activeElement instanceof HTMLElement?document.activeElement:null,d.current?.querySelector("button:not(:disabled)")?.focus();let g=()=>i(null),C=(b)=>{if(b.key==="Escape")b.preventDefault(),b.stopPropagation(),i(null),c.current?.focus({preventScroll:!0})};return window.addEventListener("keydown",C),window.addEventListener("pointerdown",g),window.addEventListener("blur",g),()=>{window.removeEventListener("keydown",C),window.removeEventListener("pointerdown",g),window.removeEventListener("blur",g)}},[o]),Ai("span",{ref:a,style:{display:r?"block":"inline-flex"},onKeyDown:(g)=>{if(g.shiftKey&&g.key==="F10"||g.key==="ContextMenu"){g.preventDefault(),g.stopPropagation();let C=g.target.getBoundingClientRect();i({x:Math.max(8,Math.min(C.left,window.innerWidth-240)),y:Math.max(8,Math.min(C.bottom,window.innerHeight-280))})}},onContextMenu:(g)=>{g.preventDefault(),g.stopPropagation(),i({x:Math.max(8,Math.min(g.clientX,window.innerWidth-240)),y:Math.max(8,Math.min(g.clientY,window.innerHeight-280))})},children:[n,o&&Gn("div",{ref:d,role:"menu","aria-label":t,style:{position:"fixed",left:l.x,top:l.y,boxSizing:"border-box",maxWidth:"calc(100vw - 24px)",maxHeight:"min(70vh, calc(100vh - 24px))",overflow:"auto",zIndex:60,minWidth:140,font:"inherit",padding:4,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",boxShadow:"0 4px 16px rgb(0 0 0 / 0.12)"},onPointerDown:(g)=>g.stopPropagation(),onKeyDown:(g)=>{if(!["ArrowDown","ArrowUp"].includes(g.key))return;g.preventDefault();let C=[...g.currentTarget.querySelectorAll("button:not(:disabled)")],b=C.indexOf(document.activeElement);C[(b+(g.key==="ArrowUp"?-1:1)+C.length)%C.length]?.focus()},children:e.map((g)=>Gn("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:()=>{i(null),g.onSelect()},children:g.label},g.id))})]})}function Ii({label:e,items:t,disabled:n,icon:r}){return Gn(wr,{label:e,disabled:n,menu:!0,trigger:r??"+",children:(o)=>Gn(Ns,{children:t.map((i)=>Ai("button",{type:"button",role:"menuitem",disabled:i.disabled,style:{display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderTop:i.separatorBefore?"1px solid var(--border, #d5d9df)":void 0,background:"transparent",color:i.destructive?"var(--destructive, #b3261e)":"inherit",opacity:i.disabled?0.5:1,font:"inherit"},onClick:()=>{o(),i.onSelect()},children:[i.icon,i.label]},i.id))})})}function jr(e){return e?.type==="singleSelect"||e?.type==="checkbox"}var Fs="\x00none";function Ei(e,t,n=new Set){if(!t)return{items:e.map((a,d)=>({kind:"row",index:d,key:a.id})),rowItem:e.map((a,d)=>d)};let r=[],o=[],i;return e.forEach((a,d)=>{let l=a.values[t.id],p=l==null?Fs:String(l);if(!i||i.raw!==p){let u=t.options?.findIndex((c)=>c.id===l)??-1;i={kind:"group",key:`group:${r.length}:${p}`,raw:p,label:l==null?null:t.type==="checkbox"?l===!0?"true":"false":t.options?.[u]?.name??String(l),colorIndex:u,count:0,collapsed:n.has(p)},r.push(i)}if(i.count+=1,i.collapsed)return;o[d]=r.length,r.push({kind:"row",index:d,key:a.id})}),{items:r,rowItem:o}}function Wn(e,t,n,r){for(let o=t;o>=0&&o<r;o+=n)if(e.rowItem[o]!==void 0)return o;return-1}var $r=34,zr=38,Ms={short:1,medium:2,tall:3,extra:4},Hr=(e)=>Ms[e??"short"],Di=(e)=>zr+(Hr(e)-1)*22;function Ti(e,t=zr){return zr+e.items.reduce((n,r)=>n+(r.kind==="group"?$r:t),0)}function cg(e,t){let n=e?.groupByFieldId;if(!e||!n||(e.type??"grid")!=="grid")return e?.sort;if(!t?.some((r)=>r.id===n&&jr(r)))return e.sort;return[{fieldId:n,direction:"asc"},...(e.sort??[]).filter((r)=>r.fieldId!==n)]}import{jsx as L,jsxs as Ie}from"react/jsx-runtime";function zs(e,t){let n=e.find((r)=>r.fieldId===t);if(n?.direction==="desc")return[];return[{fieldId:t,direction:n?"desc":"asc"}]}var Ct={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},js={padding:5,width:"100%",border:"1px solid #6688bb",background:"var(--background, white)",color:"inherit"};function qg(e){let{descriptor:t,view:n}=e,r=he(e.locale),o=rt(()=>Ut(e.features),[e.features]),i=!e.readOnly&&o.rowDelete,a=!e.readOnly&&o.rowCreate,d=!e.readOnly&&o.rowUpdate,[l,p]=Le({}),u=ot(new Set),[c,g]=Le(()=>new Set),C=ot(new Set);it(()=>{if(!u.current.size)return;let s=u.current;u.current=new Set,p((f)=>Object.fromEntries(Object.entries(f).filter(([v])=>!s.has(v))))},[e.rows]);let b=rt(()=>Object.keys(l).length?e.rows.map((s)=>l[s.id]?{...s,values:{...s.values,...l[s.id]}}:s):e.rows,[e.rows,l]),x=rt(()=>[...n.columnOrder,...t.fields.map((f)=>f.id).filter((f)=>!n.columnOrder.includes(f))].filter((f)=>!n.hiddenColumns.includes(f)).flatMap((f)=>{let v=t.fields.find((Y)=>Y.id===f);return v?[v]:[]}),[t.fields,n.columnOrder,n.hiddenColumns]),P=rt(()=>JSON.stringify([b.map((s)=>s.id),x.map((s)=>s.id)]),[b,x]),[m,k]=Le(P),y=ot(null),[I,F]=Le({row:0,column:0}),[E,O]=Le(!1),[T,U]=Le(()=>new Set),[K,R]=Le(()=>new Set),D=JSON.stringify([t.id,n.filter,n.search,n.sort,e.rowOffset]);it(()=>{U(new Set),R(new Set)},[e.rows,D]);let[q,N]=Le({row:0,column:0}),[w,Z]=Le(null),S=ot(!1),J=ot(!1),[V,ie]=Le(null),[j,oe]=Le(!1),[H,M]=Le(!1);$t({dirty:Boolean(V||j||w&&w.text!==w.originalText),busy:H||c.size>0},e);let[W,ee]=Le(""),[de,me]=Le(null),X=ot(null),we=w?.field.type==="linkedRecord"?JSON.stringify([w.rowId,w.field.id]):null;it(()=>{if(we)X.current?.querySelector('input[type="search"]')?.focus({preventScroll:!0})},[we]),it(()=>{O(!1),F({row:0,column:0}),N({row:0,column:0}),k(P)},[P]);let ae=rt(()=>{if(!o.groupBy||(n.type??"grid")!=="grid")return;let s=t.fields.find((f)=>f.id===n.groupByFieldId);return jr(s)?s:void 0},[o.groupBy,n.type,n.groupByFieldId,t.fields]),[Se,B]=Le(()=>new Set),h=ae?.id;it(()=>B(new Set),[h]);let z=rt(()=>Ei(b,ae,Se),[b,ae,Se]),Q=(s)=>Boolean(ae)&&z.rowItem[s]===void 0,Oe=Di(n.rowHeight),Ye=Hr(n.rowHeight),tn=Ni({count:z.items.length,getScrollElement:()=>y.current,estimateSize:(s)=>z.items[s]?.kind==="group"?$r:Oe,overscan:5,scrollMargin:38,getItemKey:(s)=>`${Oe}:${z.items[s]?.key??s}`}),Je=n.showRowNumber===!1?0:56,at=n.showRecordId?220:0,qt=Je+at,[Yn,Fi]=Le(0);it(()=>{let s=y.current;if(!s)return;let f=()=>Fi(s.clientWidth);if(f(),typeof ResizeObserver>"u")return window.addEventListener("resize",f),()=>window.removeEventListener("resize",f);let v=new ResizeObserver(f);return v.observe(s),()=>v.disconnect()},[]);let Wr=Math.min(Math.max(0,n.frozenColumnCount??0),x.length),Yr=rt(()=>{let s=[qt];for(let f of x)s.push((s.at(-1)??qt)+Cn(n.columnWidths[f.id]??180));return s},[qt,x,n.columnWidths]),Mi=Yr[Wr]??qt,Ze=Yn>0&&Yn<=768&&Mi>Yn*0.6?0:Wr,Jn=(s)=>Yr[s]??qt,Jr=ot(null),Zn=Boolean(e.onAddRecord)&&a,Li=Us(_s(Vs,{activationConstraint:{distance:6}})),Oi=({active:s,delta:f})=>{let v=x.findIndex((ke)=>ke.id===s.id),Y=xt.getVirtualItems().find((ke)=>ke.index===v);if(v<0||!Y)return;let _=Y.start+Y.size/2+f.x,A=xt.getVirtualItems().find((ke)=>_>=ke.start&&_<ke.start+ke.size)?.index;if(A===void 0||A===v)return;if(v<Ze!==A<Ze)return;let G=[...n.columnOrder.filter((ke)=>t.fields.some(($i)=>$i.id===ke)),...t.fields.map((ke)=>ke.id).filter((ke)=>!n.columnOrder.includes(ke))],ue=String(s.id),ne=x[A]?.id;if(!ne)return;let fe=G.filter((ke)=>ke!==ue),re=fe.indexOf(ne)+(A>v?1:0);fe.splice(re,0,ue),e.onViewChange({...n,columnOrder:fe})},zt=(s,f)=>({position:"sticky",float:"left",left:s,zIndex:2,...f?{boxShadow:"2px 0 4px -2px color-mix(in srgb, currentColor 28%, transparent)"}:{}}),xt=Ni({paddingStart:qt,paddingEnd:e.onAddField?Kr:0,horizontal:!0,count:x.length,rangeExtractor:(s)=>{let f=new Set(qs(s));for(let v=0;v<Ze;v+=1)f.add(v);return[...f].sort((v,Y)=>v-Y)},getScrollElement:()=>y.current,estimateSize:(s)=>Cn(n.columnWidths[x[s]?.id??""]??180),overscan:2,getItemKey:(s)=>x[s]?.id??s});it(()=>{x.forEach((s,f)=>{xt.resizeItem(f,Cn(n.columnWidths[s.id]??180))})},[xt,n.columnWidths,x]);let Dt=Math.max(1,xt.getTotalSize()),Qn=xt.getVirtualItems(),Ne=cr(I,q),Xn=rt(()=>E&&m===P?b.slice(Ne.firstRow,Ne.lastRow+1):[],[E,m,P,b,Ne.firstRow,Ne.lastRow]),ye=rt(()=>{let s=new Set(b.filter((f,v)=>!ae||z.rowItem[v]!==void 0).map((f)=>f.id));return Eo(Xn,T,b,K).filter((f)=>s.has(f.id))},[Xn,T,b,K,ae,z]),nn=rt(()=>ye.map((s)=>s.id),[ye]),ut=rt(()=>new Set(nn),[nn]),xn=E?{first:Ne.firstColumn,last:Ne.lastColumn}:{first:0,last:x.length-1},er=()=>ye.length?Io(ye,x,{row:0,column:xn.first},{row:ye.length-1,column:xn.last}):"",Zr=(s)=>{if(w||H||j||V)return;let f=b[s];if(!f)return;if(k(P),Xn.some((v)=>v.id===f.id))R((v)=>ur(v,f.id));else U((v)=>ur(v,f.id));if(!E)F({row:s,column:0}),N({row:s,column:x.length-1})},[_e,tr]=Le(null),rn=ot(null),Qr=!T.size&&!K.size&&E&&d&&!H&&!w&&!j&&!V&&!Se.size,Xr=(s,f)=>{if(!Qr)return;let v=Lo(s,f,b,x),Y=(A)=>{ee(A),e.onNotify?.(A)};if(v.limitExceeded){Y(r("Fill at most 100 rows at once."));return}let _=v.skipped?r("Skipped {count} cells",{count:v.skipped}):"";if(!v.mutations.length){if(_)Y(_);return}Xe({idempotencyKey:crypto.randomUUID(),items:v.mutations},()=>{Y([r("Filled {count} cells",{count:v.count}),_].filter(Boolean).join("; "))})};it(()=>{if(!_e)return;let s=()=>{let v=rn.current;if(tr(null),rn.current=null,v)Xr(_e,v)},f=()=>{tr(null),rn.current=null};return window.addEventListener("mouseup",s),window.addEventListener("blur",f),()=>{window.removeEventListener("mouseup",s),window.removeEventListener("blur",f)}});let eo=JSON.stringify({recordIds:m===P?nn:[],fieldIds:ye.length?x.slice(xn.first,xn.last+1).map((s)=>s.id):[]}),to=ot(e.onSelectionChange);to.current=e.onSelectionChange,it(()=>{to.current?.(JSON.parse(eo))},[eo]),it(()=>{if(!ae||!Q(q.row))return;let s=Wn(z,q.row,-1,b.length),f=s>=0?s:Wn(z,q.row,1,b.length);if(f>=0)N({...q,row:f}),F({...q,row:f})},[z]);let Vi=(s)=>{let f=new Set(Se);if(f.has(s))f.delete(s);else f.add(s);B(f),O(!1),U(new Set),R(new Set),F(q)},pt=(s,f=!1)=>{if(Se.size)f=!1;if(O(!0),k(P),N(s),!f)F(s),U(new Set),R(new Set);tn.scrollToIndex(z.rowItem[s.row]??s.row,{align:"auto"}),xt.scrollToIndex(s.column,{align:"auto"})},vn=(s=q,f)=>{if(!d||H||w||j||V||x[s.column]?.generation==="autoIncrement")return;let v=b[s.row],Y=x[s.column];if(!v||!Y||Y.type==="blob"||Fe(Y))return;if(c.has(v.id))return;O(!0),k(P),S.current=!1;let _=Y.type==="linkedRecord"?JSON.stringify(v.values[Y.id]??[]):Y.type==="relation"?ni(v,Y):Y.type==="json"&&v.values[Y.id]!=null?JSON.stringify(v.values[Y.id]):Re(v.values[Y.id]);Z({rowId:v.id,expectedVersion:v.version,field:Y,originalText:_,text:Y.type==="linkedRecord"||Y.type==="relation"?_:f??_}),ee(o.optimisticEdit?"":r("Unsaved changes")),ie(null),me(null)},st=ot([]),Tt=ot([]),[Nt,kn]=Le(null),no=(s,f)=>{for(let v of s.items){if(v.op!=="update")continue;let Y=f.items.find((_)=>_.id===v.id);if(!Y)continue;for(let _ of[st,Tt])_.current=_.current.map((A)=>({...A,items:A.items.map((G)=>G.op!=="insert"&&G.id===v.id&&G.expectedVersion===v.expectedVersion?{...G,expectedVersion:Y.version}:G)}))}},ro=(s,f,v)=>{let Y=s.items;if(!Y.length)return null;let _=new Map(v.map((G)=>[G.id,G])),A=[];if(Y.every((G)=>G.op==="update")){let G=new Map(f.items.map((ue)=>[ue.id,ue]));for(let ue of Y){if(ue.op!=="update")continue;let ne=_.get(ue.id);if(!ne)return null;A.push({op:"update",id:ue.id,expectedVersion:G.get(ue.id)?.version??ue.expectedVersion+1,values:Object.fromEntries(Object.keys(ue.values).map((fe)=>[fe,ne.values[fe]??null]))})}}else if(Y.every((G)=>G.op==="insert")){if(f.items.length!==Y.length)return null;for(let G of f.items)A.push({op:"delete",id:G.id,expectedVersion:G.version})}else if(Y.every((G)=>G.op==="delete"))for(let G of Y){if(G.op!=="delete")continue;let ue=_.get(G.id);if(!ue)return null;A.push({op:"insert",values:Object.fromEntries(t.fields.filter((ne)=>ne.type!=="blob"&&ne.type!=="linkedRecord"&&!Fe(ne)&&ne.generation!=="autoIncrement"&&ue.values[ne.id]!==void 0).map((ne)=>[ne.id,ue.values[ne.id]]))})}else return null;return{idempotencyKey:crypto.randomUUID(),items:A}},Bi=(s)=>{if(H||e.readOnly||w||j||V)return;let v=(s==="undo"?st:Tt).current.at(-1);if(!v)return;Xe({...v,idempotencyKey:crypto.randomUUID()},void 0,s)};async function Xe(s,f,v){if(H||J.current||e.readOnly)return;let Y=v&&Nt?Nt.before:b;if(v)kn({direction:v,before:Y,rejected:!1});J.current=!0,M(!0),ie(s),ee("");let _=await e.onMutate(s).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:r("Saving failed. Your edit has been kept.")}}));if(J.current=!1,M(!1),_.ok){let A=ro(s,_.data,Y);if(v)(v==="undo"?st:Tt).current.pop();if(no(s,_.data),kn(null),A)if(v==="undo")Tt.current.push(A);else{if(st.current.push(A),st.current.length>30)st.current.shift();if(!v)Tt.current=[]}e.onCommitted(_.data),ie(null),Z(null),oe(!1),me(null);let G=s.items.filter((ne)=>ne.op==="delete").length,ue=v?r(v==="undo"?"Undone":"Redone"):G>0&&G===s.items.length?r("Deleted {count} records",{count:G}):r("Saved");if(e.onNotify)ee(""),e.onNotify(ue);else ee(ue);y.current?.focus({preventScroll:!0}),f?.()}else{if(v){let G=_.error.status;kn({direction:v,before:Y,rejected:G>=400&&G<500&&G!==408})}ee(_.error.message);let A=_.error.details;if(A?.current)me(A.current)}}async function oo(s,f,v,Y){if(C.current.has(s.id))return;C.current.add(s.id),M(!0);let _=w??{rowId:s.id,expectedVersion:s.version,field:f,text:Re(v),originalText:Re(s.values[f.id])},A={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:s.id,expectedVersion:s.version,values:{[f.id]:v}}]};p((ne)=>({...ne,[s.id]:{...ne[s.id],[f.id]:v}})),g((ne)=>new Set(ne).add(s.id)),Z(null),ee(""),y.current?.focus({preventScroll:!0});let G=await e.onMutate(A).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:r("Saving failed. Your edit has been kept.")}}));if(C.current.delete(s.id),M(!1),g((ne)=>{let fe=new Set(ne);return fe.delete(s.id),fe}),G.ok){u.current.add(s.id);let ne=ro(A,G.data,[s]);if(no(A,G.data),ne){if(st.current.push(ne),st.current.length>30)st.current.shift();Tt.current=[]}e.onCommitted(G.data),Y?.();return}p((ne)=>{let fe={...ne};return delete fe[s.id],fe}),S.current=!1,Z(_),ie(A),ee(G.error.message);let ue=G.error.details;if(ue?.current)me(ue.current)}async function vt(s){if(!w||S.current)return;let{field:f,rowId:v,expectedVersion:Y}=w;if(f.generation==="autoIncrement"||t.fields.find((_)=>_.id===f.id)?.generation==="autoIncrement"){ee(r("{name} is auto-generated and cannot be edited.",{name:f.name})),Z(null);return}try{let _=f.type==="linkedRecord"?JSON.parse(w.text):f.type==="relation"?w.text||null:tt(w.text,f);if(f.type==="linkedRecord"&&f.required&&Array.isArray(_)&&!_.length)throw Error(`${f.name} is required.`);if(o.optimisticEdit&&f.type==="linkedRecord"&&!V&&w.text===w.originalText){gt();return}if(o.optimisticEdit&&f.type!=="linkedRecord"&&!V){let ue=b.find((ne)=>ne.id===v);if(!ue){Z(null);return}if(JSON.stringify(_??null)===JSON.stringify(ue.values[f.id]??null)){gt();return}await oo(ue,f,_,()=>{if(s)pt(Dn(q,"Tab",b.length,x.length,s==="previous"))});return}let A={[f.id]:_},G=V??{idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:v,expectedVersion:Y,values:A}]};await Xe(G,s?()=>pt(Dn(q,"Tab",b.length,x.length,s==="previous")):void 0)}catch(_){ee((e.locale==="zh-CN"?Yt(f,w.text,"zh-CN"):null)||(_ instanceof Error?_.message:r("Invalid value")))}}let jt=Boolean(e.readOnly||H||w||j||V||nn.length===0),io=()=>{if(jt||!i)return;or()},gt=()=>{S.current=!0,ee(""),Z(null),ie(null),me(null),y.current?.focus({preventScroll:!0})},on=(s)=>{if(!w||s===w.text)return;ee(o.optimisticEdit?"":r("Unsaved changes")),Z({...w,text:s}),ie(null),me(null)},_i=(s,f,v)=>{if(!d||H||w||j||V)return;if(o.optimisticEdit){oo(s,f,v);return}Z({rowId:s.id,expectedVersion:s.version,field:f,text:String(v),originalText:Re(s.values[f.id])}),Xe({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:s.id,expectedVersion:s.version,values:{[f.id]:v}}]})},kt=o.optionChips,nr=Boolean(e.renderRecordContextMenu)||o.recordContextMenu,ao=o.optimisticEdit&&!V?{onBlur:(s)=>{if(!s.currentTarget.contains(s.relatedTarget))vt()}}:{},mt=w?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:w.field,text:w.text,disabled:H||Boolean(e.readOnly),autoOpen:!0,onChange:on,onSave:(s)=>void vt(s),onCancel:gt}):void 0,so=o.optimisticEdit&&w?.field.type==="linkedRecord"&&(mt===void 0||mt===null)&&!V&&!H?{onBlur:(s)=>{let f=s.relatedTarget;if(!f||X.current?.contains(f)||f.closest('[role="gridcell"]')?.id===`wb-${w.rowId}-${w.field.id}`)return;vt()}}:{},rr=w&&(w.field.type==="singleSelect"||w.field.type==="multipleSelect")?mt??Ie("select",{"aria-label":r("Edit {name}",{name:w.field.name}),ref:(s)=>s?.focus(),style:js,multiple:w.field.type==="multipleSelect",value:w.field.type==="multipleSelect"?w.text.split(",").filter(Boolean):w.text,disabled:H,onChange:(s)=>on(w.field.type==="multipleSelect"?Array.from(s.currentTarget.selectedOptions,(f)=>f.value).join(","):s.currentTarget.value),onKeyDown:(s)=>{if(s.stopPropagation(),s.key==="Escape")s.preventDefault(),gt();if(s.key==="Tab")s.preventDefault(),vt(s.shiftKey?"previous":"next");if(s.key==="Enter")s.preventDefault(),vt()},children:[w.field.type==="singleSelect"&&L("option",{value:"",disabled:w.field.required,children:r("Clear selection")}),(w.field.options??[]).map((s)=>L("option",{value:s.id,children:s.name},s.id)),w.text.split(",").filter((s)=>s&&!w.field.options?.some((f)=>f.id===s)).map((s)=>L("option",{value:s,disabled:!0,children:r("{id} (unavailable)",{id:s})},s))]}):void 0,or=()=>{if(!i||H||w||j||V||ye.length===0)return;if(ye.length>100){ee(r("Select at most 100 rows per delete."));return}ie({idempotencyKey:crypto.randomUUID(),items:ye.map((s)=>({op:"delete",id:s.id,expectedVersion:s.version}))}),oe(!0),ee(""),me(null)},Ui=(s,f,v,Y,_)=>{_.setPointerCapture(Y);let A=(ue)=>e.onViewChange({...n,columnWidths:{...n.columnWidths,[s]:Cn(v+ue.clientX-f)}}),G=()=>{_.removeEventListener("pointermove",A),_.removeEventListener("pointerup",G),_.removeEventListener("pointercancel",G)};_.addEventListener("pointermove",A),_.addEventListener("pointerup",G),_.addEventListener("pointercancel",G)},[qi,zi]=Le(480);Ls(()=>{if(!e.display?.fill)return;let s=()=>{let f=y.current?.getBoundingClientRect().top??0;zi(Math.max(240,Math.round(window.innerHeight-f-64-(o.footerStats?34:0))))};return s(),window.addEventListener("resize",s),()=>window.removeEventListener("resize",s)},[e.display?.fill,o.footerStats]);let an=e.display?.summary===!1&&e.display?.keyboardHints===!1,lo=!!w&&tn.getVirtualItems().some((s)=>{let f=z.items[s.index];return f?.kind==="row"&&b[f.index]?.id===w.rowId})&&xt.getVirtualItems().some((s)=>x[s.index]?.id===w.field.id),wn=Ie("section",{"data-uibot":"paged-collection-grid",style:{display:an?"grid":"flex",flexDirection:an?void 0:"column",border:"1px solid var(--border, #d5d9df)",borderRadius:8,overflow:"hidden"},children:[(e.display?.summary!==!1||e.display?.keyboardHints!==!1||e.aggregate&&!o.footerStats||e.onInspectRecord||!e.readOnly&&ye.length>0&&!e.renderRecordContextMenu&&!o.recordContextMenu)&&Ie("div",{"data-uibot":"paged-collection-toolbar",style:{display:"flex",gap:8,padding:8,alignItems:"center",flexWrap:"wrap",...an?{}:{order:1,padding:"4px 10px",fontSize:12,borderTop:"1px solid var(--border, #d5d9df)"},...an?{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&&L("span",{children:Vr(r,e.total,b.length,e.locale)}),e.aggregate&&!o.footerStats&&L(jn,{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}:{}}),L("span",{style:{flex:1}}),e.display?.keyboardHints!==!1&&L("span",{style:{fontSize:12},children:r(d?"Arrows · Shift select · Enter edit · Copy / paste":"Arrows · Shift select · Copy")}),e.onInspectRecord&&L(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:H||ye.length!==1,onClick:()=>{let s=ye[0];if(s)e.onInspectRecord?.(s.id)},children:r("Open record activity")}),i&&ye.length>0&&!e.renderRecordContextMenu&&!o.recordContextMenu&&L(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",icon:"trash",disabled:jt,onClick:or,children:r("Delete selected rows")})]}),L("style",{children:`
1
+ import{createContext as ia,useCallback as aa,useContext as sa,useLayoutEffect as mr,useMemo as la,useRef as Co,useState as da}from"react";var ca=ia(void 0);function Ht(e,t={}){let n=sa(ca),r=Co({}),{dirty:i,busy:o}=e,{onDirtyChange:a,onBusyChange:d}=t;mr(()=>{n?.(r.current,{dirty:i,busy:o}),a?.(i),d?.(o)},[n,i,o,a,d]),mr(()=>()=>{n?.(r.current),a?.(!1),d?.(!1)},[n,a,d])}function yl(){let e=Co(new Map),[t,n]=da({dirty:!1,busy:!1}),r=aa((i,o)=>{if(o)e.current.set(i,o);else e.current.delete(i);let a=[...e.current.values()],d=a.some((g)=>g.dirty),s=a.some((g)=>g.busy);n((g)=>g.dirty===d&&g.busy===s?g:{dirty:d,busy:s})},[]);return{...t,report:r}}function xo(e,t){let n=la(()=>({active:!0,client:e,id:t}),[e,t]);return mr(()=>(n.active=!0,()=>{n.active=!1}),[n]),n}import{useEffect as it,useLayoutEffect as Xs,useMemo as ot,useRef as Xe,useState as Le}from"react";import{DndContext as el,PointerSensor as tl,useDraggable as nl,useSensor as rl,useSensors as ol}from"@dnd-kit/core";import{defaultRangeExtractor as il,useVirtualizer as Ki}from"@tanstack/react-virtual";function hl(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var Dn=["blue","green","red","orange","gray","teal","purple"];function ua(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 vo(e,t,n){if(!t?.length)return[];return t.map((r)=>{if(r.fn==="count")return{fieldId:r.fieldId,fn:"count",value:e.length};let i=n.find((d)=>d.id===r.fieldId),a=i?.type==="number"||i?.type==="rating"||i?.type==="autoNumber"?e.reduce((d,s)=>d+(ua(s.values[r.fieldId])??0),0):0;return{fieldId:r.fieldId,fn:"sum",value:a}})}function ko(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function pa(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function ga(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 wo(e,t){if(!t)return!0;if(ko(t)){let n=t.filterSet.map((r)=>ko(r)?wo(e,r):pa(r)?ga(e,r):!1);return t.conjunction==="or"?n.some(Boolean):n.every(Boolean)}return Object.entries(t).every(([n,r])=>{if(n==="conjunction"||n==="filterSet")return!0;return e.values[n]===r})}function Po(e,t,n,r){let i=e.views.find((c)=>c.id===n)??e.views[0];if(!i)return{view:{id:n,name:n,kind:"table"},columns:e.fields,rows:[...t]};let o=[...t];if(i.filter)o=o.filter((c)=>wo(c,i.filter));if(i.sort?.length)o.sort((c,S)=>{for(let R of i.sort??[]){let b=c.values[R.fieldId],u=S.values[R.fieldId];if(b===u)continue;if(b==null)return 1;if(u==null)return-1;let v=e.fields.find((L)=>L.id===R.fieldId)?.type,k=(L)=>{if(["number","rating","autoNumber"].includes(v??"")&&typeof L==="number")return L;if(["date","createdTime","lastModifiedTime"].includes(v??"")){let D=Date.parse(String(L));if(Number.isFinite(D))return D}return String(L)},N=k(b),T=k(u);if(N===T)continue;let C=N<T?-1:1;return R.direction==="desc"?-C:C}return c.id<S.id?-1:c.id===S.id?0:1});let a=i.projection?.length?e.fields.filter((c)=>i.projection?.includes(c.id)):e.fields,d=r?.search?.trim().toLowerCase();if(d)o=o.filter((c)=>a.some((S)=>String(c.values[S.id]??"").toLowerCase().includes(d)));let s=vo(o,i.aggregates,e.fields),g=i.group?.fieldId;if(!g)return{view:i,columns:a,rows:o,...s.length?{aggregates:s}:{}};let m=[],P=new Map;for(let c of o){let S=String(c.values[g]??"");if(!P.has(S))P.set(S,[]),m.push(S);P.get(S)?.push(c)}let f=m.map((c)=>{let S=P.get(c)??[];return{key:c,fieldId:g,rows:S,aggregates:vo(S,i.aggregates,e.fields)}});return{view:i,columns:a,rows:o,groups:f,...s.length?{aggregates:s}:{}}}var ma=500,fa=2000,ya=new Set(["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"]);function Me(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function Mt(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 Al=["short","medium","tall","extra"];function El(e,t){return t.map((n)=>{let r={},i={};for(let o of e.groupBy){let a=n[o];if(!(o in n)||a!==null&&typeof a!=="string"&&typeof a!=="number"&&typeof a!=="boolean")throw Error(`Invalid aggregate group ${o}.`);r[o]=a}for(let{as:o,fn:a}of e.aggregates){let d=n[o];if(!(o in n)||d!==null&&!(typeof d==="number"&&Number.isFinite(d))&&!((a==="min"||a==="max")&&typeof d==="string"&&Number.isFinite(Date.parse(d))))throw Error(`Invalid aggregate value ${o}.`);i[o]=d}return{groups:r,values:i}})}var ba=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,ha=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function Tn(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function He(e,t){return{code:e,...t}}function Ca(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function fr(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function Fn(e,t){if(t.aggregates.length===0)return He("empty");if(t.aggregates.length>8||t.groupBy.length>3)return He("too_many");let n=new Set;for(let i of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(i.fn))return He("function");if(!ba.test(i.as)||n.has(i.as)||t.groupBy.includes(i.as))return He("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 o=e.fields.find((a)=>a.id===i.fieldId);if(!o)return He(i.fn==="sum"?"sum_field":"unknown_field",{alias:i.as,...i.fieldId!==void 0?{fieldId:i.fieldId}:{}});if(i.fn==="sum"&&!fr(o))return He("sum_field",{fieldId:o.id,alias:i.as});if(i.fn==="avg"&&!fr(o))return He("numeric_field",{fieldId:o.id,alias:i.as});if((i.fn==="min"||i.fn==="max")&&!fr(o)&&o.type!=="date"&&!((o.type==="formula"||o.type==="rollup")&&o.resultType==="date"))return He("extrema_field",{fieldId:o.id,alias:i.as});if((i.fn==="filled"||i.fn==="empty")&&!Mt(o))return He("queryable_field",{fieldId:o.id,alias:i.as});if(i.fn==="count"&&!Mt(o))return He("count_field",{fieldId:o.id,alias:i.as})}let r=new Set;for(let i of t.groupBy){if(r.has(i))return He("duplicate_group",{fieldId:i});r.add(i);let o=e.fields.find((a)=>a.id===i);if(!o)return He("unknown_field",{fieldId:i});if(!ha.has(o.type)&&!Ca(o))return He("not_groupable",{fieldId:i})}return null}var Ro=(e)=>String(e).padStart(2,"0");function lt(e,t){let n=new Intl.DateTimeFormat("en-CA",{...t?{timeZone:t}:{},year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(e),r=(i)=>Number(n.find((o)=>o.type===i)?.value??0);return{year:r("year"),month:r("month"),day:r("day"),hour:r("hour"),minute:r("minute"),second:r("second")}}function wt(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 r=n;for(let i=0;i<2;i++){let o=lt(new Date(r),t),a=Date.UTC(o.year,o.month-1,o.day,o.hour,o.minute,o.second);r+=n-a}return new Date(r)}function Nn(e,t){let n=lt(e,t??"UTC");return`${n.year}-${Ro(n.month)}-${Ro(n.day)}`}var xa=/^[a-z][a-z0-9_-]{0,31}$/,Mn=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function So(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 va(e){if(!Mn(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"||!So(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(!Mn(t)||Object.keys(t).length!==2||typeof t.kind!=="string"||!xa.test(t.kind)||typeof t.id!=="string"||!t.id||t.id.length>200)return"hyperlink reference is invalid"}return null}var Kt=(e)=>va(e)===null;function dn(e){if(!Mn(e)||typeof e.url!=="string")return"";return typeof e.text==="string"&&e.text.trim()?e.text:e.url}function Io(e){if(!Mn(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 Ot(e){let t=e.trim();if(!t)return null;if(t.startsWith("{"))try{let o=JSON.parse(t);return Kt(o)?o:null}catch{return null}let n=/^\[([^\]]*)\]\((\S+)\)$/.exec(t)??/^(.*?)\s*<(\S+)>$/.exec(t),r=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(!So(i))return null;return r&&r!==i?{url:i,text:r}:{url:i}}function Ao(e,t=new Date,n){let r={};for(let i of e){let o=i.defaultValue;if(!o)continue;if(o.kind==="value")r[i.id]=Array.isArray(o.value)?[...o.value]:o.value;else if(i.type==="date"){let a=i.formatting;if(a&&"time"in a&&a.time==="none"){let d=lt(t,n);r[i.id]=`${d.year}-${String(d.month).padStart(2,"0")}-${String(d.day).padStart(2,"0")}`}else r[i.id]=t.toISOString()}}return r}var ka=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],wa=new Set(["pastDays","nextDays","daysAgo","daysFromNow"]),Eo={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"]},Pa=new Set(["isEmpty","isNotEmpty"]);function Do(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 Bl(e){let t=Do(e);return t?Eo[t]:[]}var yr=/^\d{4}-\d{2}-\d{2}$/,Ra=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function Sa(e){if(!Ra(e))return!1;let t=e.mode;if(!ka.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&&yr.test(e.date);if(t==="dateRange")return typeof e.date==="string"&&yr.test(e.date)&&typeof e.to==="string"&&yr.test(e.to)&&e.date<=e.to;if(wa.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function Ul(e,t){if(!e)return"unknown field";let n=Do(e),r=t.operator==="contains"&&(n==="number"||n==="checkbox"||n==="date"||n==="singleSelect");if(!n||!(Eo[n].includes(t.operator)||r))return"operator not allowed";if(Pa.has(t.operator))return null;let i=t.value;if(r)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((o)=>typeof o==="string")?null:"options required";case"date":return Sa(i)||typeof i==="string"&&Number.isFinite(Date.parse(i))?null:"date required"}}var Ia={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},cd=Array.from(new Set(Object.values(Ia).flat()));var gd=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 Aa=["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"],yd=[...Aa,"radius","font-display","font-body","font-mono"];function Ea(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function Pd(e,t){if(t===e.draft)return e;return{...e,draft:t}}function Da(e){return e.draft!==e.savedContent}function Rd(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 Sd(e,t){if(Da(e))return e;let n=Ea(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 ft=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),Lt=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),Vt=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,To=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,On=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),Fo=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every(On)&&new Set(e).size===e.length;function Ta(e){if(!ft(e)||!Lt(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!On(e.id)||!Vt(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)=>!ft(t)||!Lt(t,["id","name"])||!On(t.id)||!Vt(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,r]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&&(!ft(i)||!Lt(i,[...r])||r.some((o)=>!Vt(i[o],o==="expression"?2048:512))))return!1}return!0}function Ad(e){if(!ft(e)||!Lt(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))||!Vt(e.collectionId,512)||!Vt(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(!ft(t)||!Lt(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!Vt(t.name,200)||!To(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(Ta)||new Set(t.fields.map((o)=>o.id)).size!==t.fields.length)return!1;if(!ft(n)||!Lt(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!On(n.id)||!Vt(n.name,200)||!To(n.version)||!Fo(n.columnOrder)||!Fo(n.hiddenColumns)||!ft(n.columnWidths)||Object.values(n.columnWidths).some((o)=>typeof o!=="number"||!Number.isInteger(o)||o<72||o>800))return!1;let r=t.fields,i=(o)=>r.some((a)=>ft(a)&&a.id===o);if([...n.columnOrder,...n.hiddenColumns,...Object.keys(n.columnWidths)].some((o)=>!i(o)))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((o)=>o.id===n.groupByFieldId&&["singleSelect","checkbox"].includes(o.type)))return!1;if(n.type==="calendar"&&!t.fields.some((o)=>o.id===n.dateFieldId&&o.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((o)=>!ft(o)||!Lt(o,["fieldId","direction"])||!i(o.fieldId)||!["asc","desc"].includes(String(o.direction)))))return!1;return!0}var tt=(e)=>String(e).padStart(2,"0"),Na=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function dt(e){let t=e.formatting;return Na(e)&&t&&"date"in t?t:void 0}function cn(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function hr(e){let t=dt(e);return!t?"auto":t.time==="none"?"date":"datetime"}function br(e,t,n,r){switch(r){case"YYYY/MM/DD":return`${e}/${tt(t)}/${tt(n)}`;case"MM/DD/YYYY":return`${tt(t)}/${tt(n)}/${e}`;case"DD/MM/YYYY":return`${tt(n)}/${tt(t)}/${e}`;case"YYYY年M月D日":return`${e}年${t}月${n}日`;default:return`${e}-${tt(t)}-${tt(n)}`}}function un(e,t){let n=e==null?"":String(e);if(!n)return"";let r=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n);if(t.time==="none"){if(r)return br(Number(r[1]),Number(r[2]),Number(r[3]),t.date);let d=new Date(n);if(!Number.isFinite(d.getTime()))return n;let s=lt(d,t.timeZone??"UTC");return br(s.year,s.month,s.day,t.date)}let i=r?wt({year:Number(r[1]),month:Number(r[2]),day:Number(r[3])},t.timeZone):new Date(n);if(!Number.isFinite(i.getTime()))return n;let o=lt(i,t.timeZone),a=br(o.year,o.month,o.day,t.date);if(t.time==="12h"){let d=o.hour%12||12;return`${a} ${d}:${tt(o.minute)} ${o.hour<12?"AM":"PM"}`}return`${a} ${tt(o.hour)}:${tt(o.minute)}`}function pn(e,t){if(e==null||e==="")return"";let n=typeof e==="number"?e:Number(e);if(!Number.isFinite(n))return String(e);let r=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:r,maximumFractionDigits:r,useGrouping:t.grouping!==!1}).format(n)}function gn(e,t){let n=e?.findIndex((o)=>o.id===t)??-1,r=n>=0?e?.[n]?.color:void 0,i=Dn.findIndex((o)=>o===r);return i>=0?i:n}var No={"Footer record count":"{count} records","Footer count":"Count","Footer filled":"Filled","Footer empty":"Empty","Footer sum":"Sum","Footer avg":"Average","Footer min":"Minimum","Footer max":"Maximum"},Ma={"AI fill":"AI 填充","AI field":"AI 字段","Generate {name} with AI":"AI 生成「{name}」","Only records with empty target cells":"只处理目标为空的记录","No records have empty target cells.":"没有目标为空的记录。","AI settings of field {name}":"字段 {name} 的 AI 设置","Generate this field with AI":"用 AI 生成此字段","Generate when a record is created":"新建记录时自动生成","AI auto-fill stopped: {message}":"AI 自动生成中断:{message}",Hyperlink:"超链接","Search or paste a link":"搜索文档或粘贴链接","Use link {url}":"使用链接 {url}","Display text":"显示文字","Remove link":"移除链接","Link suggestions":"链接建议","Searching…":"搜索中…","No matching resources":"没有匹配的内容","{name} needs a link.":"{name}需要有效链接(http(s)、邮箱或站内路径)。","Link targets":"可选的链接目标","None chosen offers every kind.":"都不选则提供全部类型。","AI prompt":"AI 提示词","e.g. Summarize the description in one sentence":"例如:用一句话概括描述","Fields the AI reads (none = all)":"AI 读取的字段(不选则读取全部)","AI reads {name}":"AI 读取 {name}","All records in this view ({count})":"当前视图全部记录({count})","Generating batch {done} of {total}…":"正在生成第 {done}/{total} 批…","{count} records could not be processed: {reason}":"{count} 条记录处理失败:{reason}","Retry failed":"重试失败批次",Close:"关闭","Records in scope":"记录范围","Selected records ({count})":"已选记录({count})","Loaded records ({count})":"已载入记录({count})","Fields to fill":"要填充的字段",Instruction:"指令","Describe what to fill or change":"描述要填写或修改的内容","Fill empty cells":"补全空白","Fill the empty target cells using the other fields of the same record.":"根据同一条记录的其他字段,补全目标字段中的空白单元格。","Translate to English":"翻译成英文","Translate the target fields into English and keep proper nouns.":"把目标字段翻译成英文,专有名词保持原样。",Summarize:"生成摘要","Write a one-sentence summary of each record for the target fields.":"为每条记录在目标字段中写一句话摘要。",Classify:"自动归类","Pick the best matching option for each record from the allowed options.":"为每条记录从可选项中选择最匹配的一项。",Model:"模型",Suggestions:"建议","{count} suggested changes":"{count} 处建议修改","Select all":"全选","Select none":"全不选","No changes were suggested.":"没有需要修改的内容。","(empty)":"(空)","Generating suggestions…":"正在生成建议…",Stop:"停止","Apply {count} changes":"应用 {count} 处修改",Regenerate:"重新生成","Generate preview":"生成预览","Applied {count} AI changes":"已应用 {count} 处 AI 修改","AI changes undone":"已撤销 AI 修改",Undo:"撤销","Some records changed since the preview. Generate again to review the latest values.":"部分记录在预览后已被修改,请重新生成以查看最新内容。","Loaded records fallback: {value}":"已载入记录兜底:{value}","That summary function is not supported.":"不支持该汇总函数。","Average only a number field.":"只能对数字字段求平均值。","Minimum and maximum need a number or date field.":"最大值和最小值需要数字或日期字段。","Summarize a queryable field.":"请选择可查询字段汇总。","Select row":"选择行","Select all loaded records":"全选已载入记录","{count} selected":"已选择 {count} 条","Column color":"整列填色","Column color for {name}":"{name}整列填色","Column color {number}":"列色 {number}","No color":"无色","Fill selection":"拖拽填充","Fill at most 100 rows at once.":"一次最多 100 行","Filled {count} cells":"已填充 {count} 个单元格","Skipped {count} cells":"已跳过 {count} 个不可填充单元格","Table not found":"数据表不存在或不可访问","View not found":"视图不存在或不可访问","{count} records total":"共 {count} 条","Row height":"行高","Row height short":"紧凑","Row height medium":"中等","Row height tall":"较高","Row height extra":"超高","Sort {index}":"排序 {index}","Move sort {index} up":"上移排序 {index}","Move sort {index} down":"下移排序 {index}","Remove sort {index}":"删除排序 {index}","Add sort":"添加排序","Clear sort":"清除排序","Default order":"默认顺序",Match:"满足","all conditions":"全部条件","any condition":"任一条件","Filter conjunction":"条件关系","Condition {index}":"条件 {index}","Remove condition {index}":"删除条件 {index}","{count} grouped conditions are kept.":"另有 {count} 组嵌套条件保持不变。",Remove:"移除","Finish the highlighted condition to apply it.":"补全未完成的条件后才会生效。","Add condition":"添加条件","Add group":"添加条件组","Condition group {index}":"条件组 {index}","Remove group {index}":"删除条件组 {index}","Clear filter":"清除筛选","Filter value":"筛选值","Filter field":"筛选字段","Filter operator":"筛选条件","Date mode":"日期方式","From date":"起始日期","To date":"结束日期","Number of days":"天数","Choose option":"选择选项",Format:"格式","Format of field {name}":"字段{name}的格式","Defaults of field {name}":"字段{name}的默认值","Date format":"日期格式","Time format":"时间格式","Time zone":"时区","Viewer's time zone":"跟随查看者","No time (date only)":"不含时间(仅日期)","24-hour":"24 小时制","12-hour":"12 小时制",Preview:"预览","Default value":"默认值",Empty:"空","Current date and time":"当前日期和时间","Number style":"数字样式",Percent:"百分比",Currency:"货币","Decimal places":"小数位数","Thousands separator":"千分位分隔","Checked by default":"默认勾选","Default option {name}":"默认选中{name}","Colour of option {index}":"选项 {index} 的颜色","Colour blue":"蓝","Colour green":"绿","Colour red":"红","Colour orange":"橙","Colour gray":"灰","Colour teal":"青","Colour purple":"紫","Unsaved changes":"修改未保存","Your edit":"我的修改","Server value":"服务端当前值","Record ID":"记录 ID","Record ID {id}":"记录 ID {id}",Row:"序号","Generated automatically":"自动生成","{name} is auto-generated and cannot be edited.":"{name}由系统自动生成,不能手动修改。","Saving failed. Your edit has been kept.":"保存失败,修改已保留。",Saved:"已保存","Invalid value":"输入值无效","{name} is read-only; its original bytes are preserved.":"{name}为只读字段,原始文件内容保持不变。","{name} needs a server-provided option.":"{name}需要由服务端提供可选项。","{name} is read only.":"{name}为只读字段。","Use the {name} record picker.":"请使用{name}记录选择器。","{name} needs a number.":"{name}需要有效数字。","{name} needs valid JSON.":"{name}必须是有效 JSON。","{name} needs an integer.":"{name}必须是整数。","{name} needs true or false.":"{name}请选择是或否。","{name} needs a date.":"{name}需要有效日期。","{name} needs a valid calendar date.":"{name}需要有效日期。","{name} has no option '{option}'.":"{name}没有名为“{option}”的选项。","Paste is too large.":"粘贴内容过大。","Paste must fit within the loaded page and contain at most 100 rows.":"粘贴内容必须位于当前已加载页内,且最多包含 100 行。","Paste extends beyond the visible columns.":"粘贴内容超出可见列范围。","Row is not loaded.":"目标行尚未加载。","Unclosed quoted cell.":"粘贴内容中的引号没有闭合。","Invalid paste.":"粘贴内容无效。","Edit {name}":"编辑 {name}","{name} editor":"{name}编辑器","Sorting is unavailable for this field":"此字段暂不支持排序","Clear selection":"清空选择","{id} (unavailable)":"{id}(选项已移除)","Select at most 100 rows per delete.":"每次最多删除 100 条记录。","{total} records · {loaded} loaded":"共 {total} 条 · 已载入 {loaded} 条","Arrows · Shift select · Enter edit · Copy / paste":"方向键移动 · Shift 多选 · Enter 编辑 · 复制 / 粘贴","Arrows · Shift select · Copy":"方向键移动 · Shift 多选 · 复制","Delete selected rows":"删除所选记录","{name} records":"{name} 数据表","Resize {name}":"调整 {name} 列宽","Saving…":"保存中…","Save edit":"保存修改","Cancel edit":"取消修改","Confirm bulk change":"确认批量修改","Apply {count} row changes in one transaction?":"确认一次性提交 {count} 条记录的修改?","If any record changed or any value is invalid, all changes are rejected.":"如有记录版本冲突或输入值无效,整批修改将不提交。","Confirm changes":"确认修改","Cancel changes":"取消修改","Current server version {version}":"服务端当前版本 {version}","Retry against current version":"按当前版本重试","Saving failed. Your draft has been kept.":"保存失败,草稿已保留。","Choose a text, checkbox or single select grouping field.":"请选择文本、复选框或单选字段作为看板分组。",Ungrouped:"未分组","Invalid grouping value":"分组值无效","Move {name}":"移动 {name}","Retry change":"重试修改","{name} is required.":"请填写 {name}。","No changes":"没有修改","{name} record":"{name} 记录","No value":"未选择",Yes:"是",No:"否","Save record":"保存记录","Create record":"新建记录","Search {name}":"搜索 {name}","No relation":"未关联","More {name} options":"加载更多 {name} 选项","Relation options unavailable.":"关联选项加载失败,请重试。","Relation option provider unavailable.":"暂时无法选择关联记录。","Collection query failed. Retry to load records.":"记录加载失败,请重试。","Previous page":"上一页","Next page":"下一页","Page {page}":"第 {page} 页","Loading records…":"正在加载记录…","Retry query":"重新加载","Saving failed. Your change has been kept.":"保存失败,已保留当前修改。","{name} needs unique linked records.":"{name}需要不重复的关联记录。","Change a field before saving.":"请先修改字段再保存。","Close record":"关闭记录","Delete record":"删除记录","Confirm record deletion":"确认删除记录","Delete this record? Your unsaved changes will be discarded after deletion.":"确定删除此记录?删除后将丢弃尚未保存的修改。","Confirm deletion":"确认删除","Cancel deletion":"取消删除","Record creation requires editor permission.":"新建记录需要编辑权限。","Creating…":"正在创建…","Record created.":"记录已创建。","Record created. Add another below.":"记录已创建,可继续新增。","Show records":"查看记录","Pending record move":"待处理的记录移动","Moving record…":"正在移动记录…","The move has been kept for retry.":"已保留移动请求,可重试。","Retry move":"重试移动","Cancel move":"取消移动","Choose a single-select or boolean grouping field.":"请选择单选或复选框分组字段。","Lane {name}":"分组{name}","Open {name}":"打开{name}","Move to":"移动至","No records in this lane.":"此分组暂无记录。","No records match this view.":"此视图暂无匹配记录。",Unassigned:"未分组","Choose a valid month.":"请选择有效月份。","Invalid initial month. Showing the current UTC month.":"初始月份无效,已显示当前月份。","Choose a valid month between years 1 and 9998.":"请选择 1 至 9998 年之间的有效月份。","Invalid date":"日期无效","Choose a date field for this calendar.":"请为日历选择日期字段。","Previous month":"上个月","Next month":"下个月",Today:"今天","Calendar month":"日历月份",Month:"月份","{year}-{month}":"{year} 年 {month} 月",Sun:"周日",Mon:"周一",Tue:"周二",Wed:"周三",Thu:"周四",Fri:"周五",Sat:"周六","Day {day}":"日期 {day}","No dated records match this month.":"本月暂无匹配的日期记录。","Move {name} to date":"将 {name} 移动至日期",Move:"移动",Grid:"表格",Kanban:"看板",Gallery:"画廊",Calendar:"日历",Form:"表单","View type":"视图类型","Group by":"分组依据","Grid grouping field":"表格分组字段","No grouping":"不分组","Hide fields":"隐藏字段","Field menu {name}":"{name} 字段菜单","Edit field":"修改字段","Field saved":"字段已保存","Field added":"字段已添加","Edit all fields":"批量编辑字段","Save field":"保存","Field name is required.":"请填写字段名。","Duplicate field":"复制字段","Hide field":"隐藏字段","Undo/redo recovery":"撤销/重做恢复","Retry undo/redo":"重试撤销/重做","Clear undo/redo history":"清除撤销/重做历史",Undone:"已撤销",Redone:"已重做","Duplicate {count} selected records":"复制所选 {count} 条记录","Add record below the table":"在表格末尾新增记录","Move to {name}":"移至 {name}","Delete this record?":"删除这条记录?","Filter by {name}":"按 {name} 筛选","Record details":"记录详情","Expand record":"展开记录","Select all rows":"全选记录",Summary:"统计","Auto summary":"自动计算","Footer record count":"{count} 条记录","No summary":"不统计","Footer count":"记录数","Footer filled":"已填写","Footer empty":"未填写","Footer sum":"求和","Footer avg":"平均值","Footer min":"最小值","Footer max":"最大值","Summaries cover the {count} loaded records.":"统计范围为已载入的 {count} 条记录。","Freeze up to this field":"冻结至此字段","Unfreeze columns":"取消冻结","Insert field left":"向左插入字段","Insert field right":"向右插入字段","Sort {name} ascending":"按 {name} 升序","Sort {name} descending":"按 {name} 降序","Group by {name}":"按 {name} 分组","Ungroup by {name}":"取消按 {name} 分组","Create kanban by {name}":"按 {name} 创建看板","Delete field “{name}”?":"删除字段“{name}”?","The field and its values in every record are removed. This cannot be undone.":"该字段及其在所有记录中的值都会被删除,且无法恢复。","Field duplicated":"已复制字段","Field deleted":"已删除字段","Deleted {count} records":"已删除 {count} 条记录","Delete {count} records?":"删除 {count} 条记录?","The selected records will be deleted. If any of them changed meanwhile, nothing is deleted.":"所选记录将被删除。若其中任一条记录已被他人修改,则整体取消、不会删除任何记录。","Search fields":"搜索字段","Reorder {name}":"拖动或按上下方向键调整 {name} 的顺序","No matching fields":"没有匹配的字段","Edit field {name}":"编辑字段 {name}","Field config":"字段配置","View config":"视图配置","{count} hidden fields":"已隐藏 {count} 个字段",Filter:"筛选",Group:"分组",Sort:"排序","{count} sorts":"{count} 项排序","Add grouping":"添加分组","Remove grouping":"移除分组","Hide {name}":"隐藏{name}","Show {name}":"显示{name}","Kanban grouping field":"看板分组字段","Date field":"日期字段","Calendar date field":"日历日期字段","Linked records are unavailable. Ask the host to connect this collection.":"关联记录不可用,请确认表格已连接。","Linked records could not be loaded. Retry to keep editing.":"关联记录加载失败,请重试后继续编辑。","{name} linked records":"{name}关联记录","Remove {name}":"移除 {name}","Search {name} records":"搜索 {name} 记录","Search linked records":"搜索关联记录","Loading linked records…":"加载关联记录…","Retry linked records":"重试加载关联记录","Link {name}":"关联 {name}","No matching records.":"没有匹配记录。","Previous linked records":"上一页关联记录","Next linked records":"下一页关联记录","{count} selected · up to 100 per record across all link fields":"已选择 {count} 项 · 每条记录的所有关联字段合计最多 100 项","{name} (read only)":"{name}(只读)","Choose…":"请选择…","Division by zero":"除数不能为零","Invalid computed value":"计算值无效","Computed value overflow":"计算值超出范围","Dependency failed":"依赖字段计算失败",Views:"视图","Add view":"添加视图","Rename view":"重命名视图","Duplicate view":"复制视图","Delete view":"删除视图","View name":"视图名称","View actions":"视图操作","Double click to rename":"双击重命名","Record actions":"记录操作","Copy cells":"复制所选单元格","Delete {count} selected records":"删除所选 {count} 条记录","Not set":"未设置",Checked:"已勾选",Unchecked:"未勾选","Expand group {name}":"展开分组 {name}","Collapse group {name}":"折叠分组 {name}","{count} records":"{count} 条","Collection fields":"表格字段","Field {name}":"字段 {name}","Field name":"字段名","Field description":"字段说明","Field type":"字段类型",Required:"必填","Delete field":"删除字段","Delete field {name}":"删除字段「{name}」","Options of field {name}":"字段 {name} 的选项",Options:"选项","Option name {index}":"选项名称 {index}","Delete option {index}":"删除选项 {index}",Delete:"删除","Add option":"新增选项","Add field":"新增字段","New field":"新字段","New option":"新选项","Single line text":"单行文本","Long text":"长文本",Number:"数字",Checkbox:"复选框",Date:"日期","Single select":"单选","Multiple select":"多选","Filter applied":"已应用筛选","Sort field":"排序字段","Sort direction":"排序方向",Default:"默认",Ascending:"升序",Descending:"降序",Columns:"列设置","Show row numbers":"显示行号","Show record IDs":"显示记录 ID","Move {name} left":"移动{name}到左侧","Move {name} right":"移动{name}到右侧",Tables:"数据表","New table":"新建数据表","Change table icon":"修改数据表图标","Table icon":"数据表图标","Double click to change the icon":"双击修改图标","Schema permission required":"需要数据结构管理权限","Table name":"数据表名称","Rename table {name}":"重命名数据表 {name}","Start with a table":"从一张数据表开始","{count} fields · {mode}":"{count} 个字段 · {mode}",Editable:"可编辑","Read only":"只读",Table:"表格",People:"人员",Business:"业务",List:"清单",Schedule:"日程",Inventory:"库存","Choose a table first.":"请先选择数据表。","Save view":"保存视图",Done:"完成","View settings":"视图设置","Save fields":"保存字段",Cancel:"取消",Refresh:"刷新","Search records":"搜索记录",Search:"搜索",Fields:"字段","Add record":"新增记录","Unsaved view changes":"视图设置未保存","Delete view “{name}”?":"删除视图「{name}」?","Reload records":"重新加载记录","Reload permissions":"重新加载权限","Loading…":"加载中…","{name} copy":"{name} 副本",Name:"名称","New grid view":"新网格视图","New kanban view":"新看板视图","New gallery view":"新画廊视图","New calendar view":"新日历视图","New form view":"新表单视图","Create table":"创建数据表","Sum field":"求和字段","No sum":"不求和","Linked record":"关联记录","Related table":"关联数据表","Choose a related table":"选择关联表",Relations:"关联","{name} · inverse records":"{name} · 反向记录","No tables yet":"还没有数据表","All records":"全部记录","Loading summary…":"正在汇总…","No summary rows.":"没有汇总数据","The collection service is unavailable.":"数据服务暂不可用","You do not have permission to make this change.":"你没有权限进行此修改。","You do not have permission to view this data.":"你没有权限查看此数据。","Sign in to view this data.":"请登录后查看此数据。","This data is missing or inaccessible.":"此数据不存在或无法访问。","This record has changed. Review the current version.":"记录已被修改,请核对当前版本。",none:"无","Choose a count or sum.":"请选择计数或求和。","Use at most three groups and eight summaries.":"最多使用三个分组和八项汇总。","That field is not in this collection.":"该字段不在此数据表中。","Group by a text, number, date, checkbox, or single select field.":"请按文本、数字、日期、复选框或单选字段分组。","Sum only a number field.":"只能对数字字段求和。","Count a queryable field, or omit the field to count records.":"请统计可查询字段,或不选字段以统计记录数。","Each summary needs its own name, different from the group fields.":"每项汇总需要独立名称,且不能与分组字段重名。","Each group field can be used once.":"每个分组字段只能使用一次。",Records:"记录数","Sum of {name}":"{name}合计","Discard unsaved changes?":"放弃未保存的更改?",Discard:"放弃更改","Keep editing":"继续编辑","View deleted":"视图已删除","View saved":"视图已保存","Fields saved":"字段已保存","Record saved":"记录已保存","Record saved, keep adding":"记录已保存,可继续新增","New record form":"新增记录表单",Save:"保存","Save new record":"保存新记录","Save and continue":"保存并继续","Cancel adding":"取消新增","Clear current filter":"清除当前筛选","Configure fields":"配置字段","Table title":"表格标题","{count} filters":"{count} 项筛选","Cancel field settings":"取消字段设置","Only this view's filters, sort and layout are removed; no records are deleted.":"只删除这个视图的筛选、排序和布局设置,不会删除任何记录。","Expand all groups before pasting.":"请先展开所有分组再粘贴。"};function me(e="en"){return(t,n={})=>(e==="zh-CN"?Ma[t]??t:Object.hasOwn(No,t)?No[t]??t:t).replace(/\{(\w+)\}/g,(r,i)=>String(n[i]??r))}var Mo={permission_denied:"You do not have permission to make this change.",version_conflict:"This record has changed. Review the current version.",unavailable:"The collection service is unavailable."};function mn(e,t="en"){if(t!=="zh-CN"||!Object.hasOwn(Mo,e.code))return e.message;let n=Mo[e.code];return n?me(t)(n):e.message}function Oo({code:e,message:t},n="en"){if(n!=="zh-CN")return t;let r=me(n);switch(e){case"permission_denied":return r("You do not have permission to view this data.");case"unauthorized":return r("Sign in to view this data.");case"not_found":return r("This data is missing or inaccessible.");case"unavailable":return r("The collection service is unavailable.");default:return t}}function Ln(e,t,n,r,i=!1){let{row:o,column:a}=e;if(t==="ArrowUp")o--;if(t==="ArrowDown")o++;if(t==="ArrowLeft")a--;if(t==="ArrowRight")a++;if(t==="Home")a=0;if(t==="End")a=r-1;if(t==="Tab"){let d=Math.max(0,Math.min(n*r-1,o*r+a+(i?-1:1)));o=Math.floor(d/r),a=d%r}return{row:Math.max(0,Math.min(n-1,o)),column:Math.max(0,Math.min(r-1,a))}}function Cr(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 Se(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function Lo(e,t,n,r){let i=Cr(n,r),o=[];for(let a=i.firstRow;a<=i.lastRow;a++){let d=[];for(let s=i.firstColumn;s<=i.lastColumn;s++){let g=t[s],m=e[a]?.values[g?.id??""],P=g?.type==="json"&&m!=null?JSON.stringify(m):g?.type==="hyperlink"?Io(m):Se(m);d.push(/[\t\r\n"]/.test(P)?`"${P.replaceAll('"','""')}"`:P)}o.push(d.join("\t"))}return o.join(`
2
+ `)}function Oa(e,t="en"){let n=me(t),r=[],i=[],o="",a=!1;for(let d=0;d<e.length;d++){let s=e[d];if(s==='"'&&(a||o===""))if(a&&e[d+1]==='"')o+='"',d++;else a=!a;else if(!a&&(s==="\t"||s===`
3
+ `||s==="\r")){if(i.push(o),o="",s!=="\t"){if(r.push(i),i=[],s==="\r"&&e[d+1]===`
4
+ `)d++}}else o+=s}if(a)throw Error(n("Unclosed quoted cell."));if(o||i.length||r.length===0)i.push(o),r.push(i);return r}function nt(e,t,n="en"){let r=me(n);if(t.type==="blob")throw Error(r("{name} is read-only; its original bytes are preserved.",{name:t.name}));if(t.type==="relation")throw Error(r("{name} needs a server-provided option.",{name:t.name}));if(t.type==="lookup"||t.type==="formula"||t.type==="rollup")throw Error(r("{name} is read only.",{name:t.name}));if(t.type==="linkedRecord")throw Error(r("Use the {name} record picker.",{name:t.name}));if(e===""){if(t.required)throw Error(r("{name} is required.",{name:t.name}));return null}if(t.type==="number"){let o=Number(e);if(!e.trim()||!Number.isFinite(o))throw Error(r("{name} needs a number.",{name:t.name}));return o}if(t.type==="hyperlink"){let o=Ot(e);if(!o)throw Error(r("{name} needs a link.",{name:t.name}));return o}if(t.type==="json")try{return JSON.parse(e)}catch{throw Error(r("{name} needs valid JSON.",{name:t.name}))}if(t.type==="bigint"){if(!/^-?\d+$/.test(e))throw Error(r("{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(r("{name} needs true or false.",{name:t.name}))}if(t.type==="date"){let o=dt(t);if(o){let T=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!T)throw Error(r("{name} needs a date.",{name:t.name}));let[,C,L,D]=T,B=new Date(Date.UTC(Number(C),Number(L)-1,Number(D)));if(B.getUTCMonth()!==Number(L)-1||B.getUTCDate()!==Number(D))throw Error(r("{name} needs a valid calendar date.",{name:t.name}));if(o.time==="none"){if(/T.*(?:Z|[+-]\d{2}:\d{2})$/i.test(e)&&Number.isFinite(Date.parse(e)))return Nn(new Date(e),o.timeZone);return`${C}-${L}-${D}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return wt({year:Number(C),month:Number(L),day:Number(D)},o.timeZone).toISOString()}let a=/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-](\d{2}):(\d{2})))?$/i.exec(e);if(!a)throw Error(r("{name} needs a date.",{name:t.name}));let[,d,s,g,m,P,f,c,S]=a,R=Number(d),b=Number(s),u=Number(g),k=[31,R%4===0&&(R%100!==0||R%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(b<1||b>12||u<1||u>(k[b-1]??0)||Number(m??0)>23||Number(P??0)>59||Number(f??0)>59||Number(c??0)>23||Number(S??0)>59)throw Error(r("{name} needs a valid calendar date.",{name:t.name}));let N=new Date(e);if(!Number.isFinite(N.getTime()))throw Error(r("{name} needs a date.",{name:t.name}));return N.toISOString()}let i=(o)=>{let a=t.options?.find((d)=>d.id===o||d.name===o);if(!a)throw Error(r("{name} has no option '{option}'.",{name:t.name,option:o}));return a.id};if(t.type==="singleSelect")return i(e);if(t.type==="multipleSelect")return[...new Set(e.split(",").map((o)=>i(o.trim())))];return e}function Vo(e,t,n,r,i="en"){let o=me(i);try{if(e.length>1048576)throw Error(o("Paste is too large."));let a=Oa(e,i);if(a.length>100||r.row+a.length>t.length)throw Error(o("Paste must fit within the loaded page and contain at most 100 rows."));return{ok:!0,items:a.map((s,g)=>{if(r.column+s.length>n.length)throw Error(o("Paste extends beyond the visible columns."));let m=t[r.row+g];if(!m)throw Error(o("Row is not loaded."));let P={};return s.forEach((f,c)=>{let S=n[r.column+c];if(S?.generation==="autoIncrement")throw Error(o("{name} is auto-generated and cannot be edited.",{name:S.name}));if(S)P[S.id]=nt(f,S,i)}),{op:"update",id:m.id,expectedVersion:m.version,values:P}})}}catch(a){return{ok:!1,message:a instanceof Error?a.message:o("Invalid paste.")}}}function Vn(e,t){let n=Se(e);if(!/^\d{4}-\d{2}-\d{2}T/.test(n))return n;let r=new Date(n);if(!Number.isFinite(r.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(r),o=(g)=>i.find((m)=>m.type===g)?.value??"",a=r.getUTCMilliseconds(),d=o("second"),s=d!=="00"||a?`:${d}${a?`.${String(a).padStart(3,"0")}`:""}`:"";return`${o("year")}-${o("month")}-${o("day")} ${o("hour")}:${o("minute")}${s}`}function _o(e,t,n,r=new Set){let i=new Set([...e.map((o)=>o.id),...t]);return n.filter((o)=>i.has(o.id)&&!r.has(o.id))}function xr(e,t){let n=new Set(e);if(n.has(t))n.delete(t);else n.add(t);return n}import{useEffect as La,useRef as Va,useState as Gt}from"react";import{jsx as rt,jsxs as fn}from"react/jsx-runtime";function Pt(e){if(e==null)return"—";if(Array.isArray(e))return e.map(Pt).join(", ");return String(e)}function Bo(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((r)=>r.label||r.id).join(", "):void 0)??Pt(e.values[t.id])}function Uo(e,t){return Se(e.values[t.id])}function _n({field:e,value:t,labels:n=[],client:r,onChange:i,disabled:o=!1,locale:a,"aria-describedby":d,"aria-invalid":s}){let g=me(a),m=Array.isArray(t)?t.filter((w)=>typeof w==="string"):[],P=Va(new Set(m));P.current=new Set(m);let[f,c]=Gt(""),[S,R]=Gt(),[b,u]=Gt([]),[v,k]=Gt(0),[N,T]=Gt({}),[C,L]=Gt({rows:[],next:null,error:"",loading:!0}),D=e.link?.collectionId,B=e.link?.displayFieldId;La(()=>{let w=!0;if(L({rows:[],next:null,error:"",loading:!0}),!r||!D||!B){L({rows:[],next:null,error:g("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return r.query(D,{limit:50,search:f,...S?{cursor:S}:{}}).then((A)=>{if(!w)return;if(!A.ok){L({rows:[],next:null,error:A.error.message,loading:!1});return}T((H)=>({...Object.fromEntries(Object.entries(H).filter(([M])=>P.current.has(M))),...Object.fromEntries(A.data.items.map((M)=>{let q=String(M.values[B]??"");return[M.id,q.trim()?q.slice(0,256):M.id]}))})),L({rows:A.data.items,next:A.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(w)L({rows:[],next:null,error:g("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{w=!1}},[r,D,B,f,S,v]);let j=(w)=>N[w]??n.find((A)=>A.id===w)?.label??w;return fn("fieldset",{disabled:o,"aria-label":g("{name} linked records",{name:e.name}),...d?{"aria-describedby":d}:{},...s?{"aria-invalid":!0}:{},className:"flex min-w-0 flex-col gap-2 rounded-md border p-2",children:[rt("div",{className:"flex flex-wrap gap-1",children:m.map((w)=>fn("span",{className:"rounded border px-2 py-1 text-sm",children:[j(w)," ",rt("button",{type:"button","aria-label":g("Remove {name}",{name:j(w)}),onClick:()=>i(m.filter((A)=>A!==w)),children:"×"})]},w))}),rt("input",{"aria-label":g("Search {name} records",{name:e.name}),type:"search",placeholder:g("Search linked records"),value:f,onChange:(w)=>{c(w.target.value),R(void 0),u([])}}),C.loading&&rt("p",{role:"status",children:g("Loading linked records…")}),C.error&&fn("div",{role:"alert",children:[C.error," ",rt("button",{type:"button",onClick:()=>k((w)=>w+1),children:g("Retry linked records")})]}),rt("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:C.rows.map((w)=>fn("label",{className:"flex items-center gap-2 text-sm",children:[rt("input",{type:"checkbox","aria-label":g("Link {name}",{name:j(w.id)}),checked:m.includes(w.id),disabled:!m.includes(w.id)&&m.length>=100,onChange:(A)=>i(A.target.checked?[...m,w.id]:m.filter((H)=>H!==w.id))}),j(w.id)]},w.id))}),!C.loading&&!C.error&&!C.rows.length&&rt("p",{children:g("No matching records.")}),fn("div",{className:"flex gap-2",children:[rt("button",{type:"button",disabled:!b.length||C.loading,onClick:()=>{R(b.at(-1)),u((w)=>w.slice(0,-1))},children:g("Previous linked records")}),rt("button",{type:"button",disabled:!C.next||C.loading,onClick:()=>{u((w)=>[...w,S]),R(C.next??void 0)},children:g("Next linked records")})]}),rt("small",{children:g("{count} selected · up to 100 per record across all link fields",{count:m.length})})]})}var _a={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function Wt(e,t,n){return t?me(n)(_a[t]):e==null?"—":String(e)}function mu(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((r)=>({id:`option:${r.id}`,name:r.name,value:r.id})):[],{id:"null",name:t("Unassigned"),value:null}]}function qo(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function zo(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function fu(e,t,n){let r=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...zo(e),filter:qo(e.filter,r)}}function Ba(e,t=(n)=>n){if(!/^\d{4}-\d{2}$/.test(e))throw Error(t("Choose a valid month."));let[n,r]=e.split("-").map(Number);if(!n||n>9998||!r||r>12)throw Error(t("Choose a valid month."));let i=new Date(`${e}-01T00:00:00.000Z`),o=new Date(i);return o.setUTCMonth(o.getUTCMonth()+1),{start:i.toISOString(),end:o.toISOString(),days:Math.round((o.getTime()-i.getTime())/86400000),weekday:i.getUTCDay()}}function yu(e,t,n){let{start:r,end:i}=Ba(n);return{...zo(e),filter:qo(e.filter,{fieldId:t,operator:"onOrAfter",value:r},{fieldId:t,operator:"before",value:i})}}function jo(e,t){let n={id:"date",name:"Date",type:"date"},r=String(nt(t,n)),i=String(nt(String(e),n));return`${r.slice(0,10)}${i.slice(10)}`}function Bn(e,t){return[...t.columnOrder,...e.map((r)=>r.id).filter((r)=>!t.columnOrder.includes(r))].filter((r)=>!t.hiddenColumns.includes(r)).flatMap((r)=>e.filter((i)=>i.id===r))}function vr(e,t){let n=t.find((r)=>r.type==="singleLineText"||r.type==="longText");return(n?Se(e.values[n.id]):"")||e.id}function yn(e,t,n){if(t.type==="lookup")return Pt(e);if(t.type==="hyperlink")return dn(e);if(t.type==="date"){let r=dt(t);return r?un(e,r):Vn(e)}if(t.type==="number"){let r=cn(t);return r?pn(e,r):Se(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return Wt(e,n);if(t.type==="singleSelect"||t.type==="multipleSelect")return(Array.isArray(e)?e:e==null?[]:[e]).map((i)=>t.options?.find((o)=>o.id===i)?.name??String(i)).join(", ");return Se(e)}import{jsx as _t,jsxs as $o}from"react/jsx-runtime";function Un(e,t){return Object.fromEntries(e?.items.flatMap((n)=>n.op==="update"&&n.id===t?Object.entries(n.values):[])??[])}function bn({fields:e,values:t,serverValues:n,locale:r}){let i=me(r);return _t("div",{"data-uibot":"collection-field-changes",style:{display:"grid",gap:8,margin:"8px 0"},children:Object.entries(t).flatMap(([o,a])=>{let d=e.find((g)=>g.id===o);if(!d)return[];let s=(g)=>d.type==="checkbox"&&typeof g==="boolean"?i(g?"Checked":"Unchecked"):yn(g,d)||"—";return $o("div",{style:{border:"1px solid var(--border,#d5d9df)",borderRadius:6,padding:8},children:[_t("strong",{children:d.name}),n?$o("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"minmax(90px,auto) minmax(0,1fr)",gap:4},children:[_t("dt",{children:i("Your edit")}),_t("dd",{style:{margin:0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:s(a)}),_t("dt",{children:i("Server value")}),_t("dd",{style:{margin:0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:s(n[o])})]}):_t("p",{style:{margin:0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:s(a)})]},o)})})}import{jsx as Yt}from"react/jsx-runtime";var Ho=[["#e8f0fe","#1a56c4"],["#e6f4ea","#1e7a3c"],["#fdecea","#b3261e"],["#fff1e0","#a05a00"],["#e8eaed","#3c4043"],["#e0f2f1","#00695c"],["#f3e8fd","#6a1b9a"]];function kr(e){let t=Math.max(e,0)%Ho.length,[n,r]=Ho[t]??["#e8eaed","#3c4043"];return{background:`var(--uibot-chip-${t}-bg, ${n})`,color:`var(--uibot-chip-${t}-fg, ${r})`}}function wr({index:e,children:t}){return Yt("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",...kr(e)},children:t})}function Pr({ids:e,field:t,wrap:n}){let r=t.options??[];return Yt("span",{style:{display:"inline-flex",gap:4,alignItems:"center",maxWidth:"100%",overflow:"hidden",...n?{flexWrap:"wrap"}:{}},children:e.map((i)=>{let o=r.findIndex((a)=>a.id===i);return Yt(wr,{index:gn(r,i),children:r[o]?.name??String(i)},String(i))})})}function Go({checked:e,label:t,onToggle:n}){return Yt("input",{type:"checkbox","aria-label":t,checked:e,disabled:!n,style:{width:16,height:16,margin:0,accentColor:"var(--primary, #1a56c4)"},onMouseDown:(r)=>r.stopPropagation(),onKeyDown:(r)=>r.stopPropagation(),onChange:()=>n?.()})}var Ko={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 Wo({type:e}){return Yt("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:Yt("path",{d:Ko[e]??Ko.singleLineText})})}function qn(e){let t=Dn.findIndex((r)=>r===e);if(t<0)return;let n=kr(t);return{background:`color-mix(in srgb, ${n.background} 55%, var(--background, white))`,marker:String(n.color)}}var Yo=(e,t)=>(e%t+t)%t;function Jo(e,t,n,r){let i=[],o=0,a=0,d=e.lastRow-e.firstRow+1,s=e.lastColumn-e.firstColumn+1;if(d<1||s<1||t.lastRow-t.firstRow+1>100)return{mutations:i,skipped:o,count:a,limitExceeded:!0};for(let g=t.firstRow;g<=t.lastRow;g++){let m=n[g];if(!m)continue;let P={};for(let f=t.firstColumn;f<=t.lastColumn;f++){if(g>=e.firstRow&&g<=e.lastRow&&f>=e.firstColumn&&f<=e.lastColumn)continue;let c=r[f];if(!c)continue;if(Me(c)||c.generation==="autoIncrement"||["blob","linkedRecord","relation"].includes(c.type)){o++;continue}let S=e.firstColumn+Yo(f-e.firstColumn,s),R=r[S];if(!R||R.type!==c.type){o++;continue}let b=n[e.firstRow+Yo(g-e.firstRow,d)]?.values[R.id]??null;if(s===1&&d>=2&&(c.type==="number"||c.type==="date")&&f===e.firstColumn){let u=n.slice(e.firstRow,e.lastRow+1).map((T)=>T.values[R.id]),v=u.map((T)=>c.type==="date"?typeof T==="string"&&T!==""?Date.parse(T)/86400000:Number.NaN:typeof T==="number"?T:Number.NaN),k=v[0]??Number.NaN,N=(v[1]??Number.NaN)-k;if(v.every((T,C)=>Number.isFinite(T)&&Math.abs(T-(k+N*C))<0.00000001)){let T=k+N*(g-e.firstRow);if(Number.isFinite(T))b=c.type==="date"?String(u[0]).length===10?new Date(T*86400000).toISOString().slice(0,10):new Date(T*86400000).toISOString():T}}P[c.id]=structuredClone(b),a++}if(Object.keys(P).length)i.push({op:"update",id:m.id,expectedVersion:m.version,values:P})}return{mutations:i,skipped:o,count:a,limitExceeded:!1}}import{useEffect as ei,useId as Ja,useMemo as Za,useRef as Qa,useState as ti}from"react";var Ua=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function Rt(e){return Ua.test(e)}var yt=(e)=>String(e).padStart(2,"0");function Zo(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${yt(t.getMonth()+1)}-${yt(t.getDate())}T${yt(t.getHours())}:${yt(t.getMinutes())}:${yt(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var Rr=(e,t)=>{let n=lt(e,t);return`${n.year}-${yt(n.month)}-${yt(n.day)}T${yt(n.hour)}:${yt(n.minute)}`};function Sr(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!Rt(e))return e.slice(0,10);return Rr(new Date(e),t.timeZone??"UTC").slice(0,10)}if(Rt(e))return Rr(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function Ir(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||Rt(t)))return e;let i=e.length>10?e.slice(11,16):t&&Rt(t)?Rr(new Date(t),n.timeZone).slice(11,16):"00:00",[o,a,d]=e.slice(0,10).split("-").map(Number),[s,g]=i.split(":").map(Number),m=wt({year:o??0,month:a??1,day:d??1,hour:s??0,minute:g??0},n.timeZone);return Number.isFinite(m.getTime())?m.toISOString():e}import{createContext as qa,useContext as za,useEffect as ja,useId as $a,useLayoutEffect as Ha,useMemo as Ka,useRef as Ga,useState as Jt}from"react";import{jsx as Qe,jsxs as Zt}from"react/jsx-runtime";var Xo=qa(void 0);function Wa(e){return Qe(Xo.Provider,{value:e.client,children:e.children})}var Ar=()=>za(Xo),Qo=(e)=>/^https?:/i.test(e);function zn(e){let t=Ar();if(!Kt(e.value))return null;let n=e.value,r=t?.href?.(n)??n.url;return Qe("a",{href:r,title:n.url,"data-uibot-link":n.ref?.kind??(Qo(r)?"external":"internal"),...Qo(r)?{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:dn(n)})}var hn=(e)=>e?JSON.stringify(e):"",Ya=(e)=>e.trim().startsWith("{")?Ot(e):null;function Cn(e){let t=Ka(()=>me(e.locale),[e.locale]),n=Ar(),r=$a(),i=Ya(e.text),[o,a]=Jt(()=>i?"":e.text),[d,s]=Jt(!1),[g,m]=Jt([]),[P,f]=Jt(""),[c,S]=Jt(-1),R=Ga(null),[b,u]=Jt(null),k=e.field.hyperlink?.kinds?.join(",")??"";ja(()=>{if(!n||!d||e.disabled)return;let w=new AbortController,A=setTimeout(()=>{f(t("Searching…")),n.search({search:o.trim(),...k?{kinds:k.split(",")}:{},limit:8},{signal:w.signal}).then((H)=>{if(w.signal.aborted)return;m(H.ok?H.data.slice(0,8):[]),f(H.ok?"":H.error.message)}).catch((H)=>{if(!w.signal.aborted)f(H instanceof Error?H.message:String(H))})},200);return()=>{clearTimeout(A),w.abort()}},[n,d,o,k,e.disabled,t]);let N=Ot(o),T=(w)=>n?.kinds?.find((A)=>A.id===w)?.label??w,C=[...N&&!N.ref?[{key:"typed",value:N,title:t("Use link {url}",{url:N.url})}]:[],...g.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:[T(w.kind),w.subtitle].filter(Boolean).join(" · ")}))],L=Boolean(n&&!P&&!g.length&&o.trim()),D=d&&!e.disabled&&(C.length>0||Boolean(P)||L);Ha(()=>{if(!D)return;let w=()=>u(R.current?.getBoundingClientRect()??null);return w(),window.addEventListener("scroll",w,!0),window.addEventListener("resize",w),()=>{window.removeEventListener("scroll",w,!0),window.removeEventListener("resize",w)}},[D]);let B=(w)=>{a(""),S(-1),e.onChange(hn(w.value))},j=(w)=>{a(w),S(-1),e.onChange(w||hn(i))};return Zt("div",{style:{display:"grid",gap:4,minWidth:0,height:"100%"},children:[Qe("input",{ref:R,id:e.id,role:"combobox","aria-label":e.ariaLabel,"aria-expanded":D,"aria-controls":r,"aria-autocomplete":"list","aria-invalid":e.invalid,...e.describedBy?{"aria-describedby":e.describedBy}:{},...c>=0?{"aria-activedescendant":`${r}-${c}`}:{},disabled:e.disabled,placeholder:i?dn(i):t("Search or paste a link"),value:o,style:e.inputStyle,className:e.inputClassName,onFocus:()=>s(!0),onBlur:()=>s(!1),onChange:(w)=>j(w.currentTarget.value),onKeyDown:(w)=>{if(e.onSave||e.onCancel)w.stopPropagation();if(w.key==="ArrowDown"||w.key==="ArrowUp"){if(!C.length)return;w.preventDefault();let A=w.key==="ArrowDown"?1:-1;S((H)=>A>0?(H+1)%C.length:H<=0?C.length-1:H-1)}else if(w.key==="Enter"){w.preventDefault();let A=C[c];if(A)B(A);else e.onSave?.()}else if(w.key==="Tab"&&e.onSave)w.preventDefault(),e.onSave();else if(w.key==="Escape")if(w.preventDefault(),o)j("");else e.onCancel?.()}}),i&&!o&&!e.onSave&&Zt("div",{style:{display:"grid",gap:4,minWidth:0,fontSize:12},children:[Zt("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[Qe(zn,{value:i,style:{flex:"0 1 auto"}}),Qe("span",{style:{flex:"1 1 0",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:0.6},children:i.url}),Qe("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:"×"})]}),Zt("label",{style:{display:"grid",gap:2},children:[Qe("span",{style:{opacity:0.7},children:t("Display text")}),Qe("input",{"aria-label":t("Display text"),placeholder:i.url,value:i.text??"",disabled:e.disabled,className:e.inputClassName,onChange:(w)=>{let A=w.currentTarget.value.slice(0,500),{text:H,...M}=i;e.onChange(hn(A?{...M,text:A}:M))}})]})]}),D&&b&&Zt("div",{id:r,role:"listbox","aria-label":t("Link suggestions"),style:{position:"fixed",top:b.bottom+4,left:b.left,width:Math.max(b.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:[C.map((w,A)=>Zt("div",{id:`${r}-${A}`,role:"option","aria-selected":A===c,tabIndex:-1,onMouseEnter:()=>S(A),onClick:()=>B(w),onKeyDown:()=>{},style:{display:"grid",gap:2,padding:"6px 8px",borderRadius:6,cursor:"pointer",background:A===c?"var(--uibot-hover, rgb(0 0 0 / 0.06))":void 0},children:[Qe("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w.title}),w.subtitle&&Qe("span",{style:{fontSize:12,opacity:0.65},children:w.subtitle})]},w.key)),P&&Qe("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:P}),L&&Qe("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:t("No matching resources")})]})]})}import{jsx as St,jsxs as ni}from"react/jsx-runtime";function Qt(e,t,n){if(e.type==="blob")return"";try{return nt(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 me(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 Er({field:e,text:t,disabled:n,id:r,label:i,ariaLabel:o,onChange:a,onSave:d,onCancel:s,locale:g="en",submitted:m=!1,describedBy:P}){let f=Za(()=>me(g),[g]),c=Ja(),S=Qa(null),R=Boolean(d);ei(()=>{if(R)S.current?.querySelector("input,textarea,select")?.focus()},[R]);let b=r??c,u=`${b}-error`,[v,k]=ti(t),[N,T]=ti(!1);ei(()=>k(t),[t]);let C=Qt(e,v,g),D=Boolean(e.required&&v===""&&C)&&!N&&!m?"":C,B=o??i??e.name,j=e.type==="date"&&Rt(v),w=j&&!C?Zo(v):v,A=[P,D?u:void 0].filter(Boolean).join(" "),H={id:b,"aria-label":B,"aria-invalid":Boolean(D),...A?{"aria-describedby":A}:{},disabled:n,onBlur:()=>T(!0),onKeyDown:(p)=>{if(d||s)p.stopPropagation();let z=e.type==="longText"||e.type==="json";if(p.key==="Tab"&&d)p.preventDefault(),d(p.shiftKey?"previous":"next");else if(p.key==="Enter"&&!p.shiftKey&&d&&(!z||p.ctrlKey||p.metaKey))p.preventDefault(),d();else if(p.key==="Escape"&&s)p.preventDefault(),s()},style:{width:"100%",...R?{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"},M=(p)=>{T(!0),k(p),a(p)},q=(p)=>{if(e.type==="date"&&j&&p){let z=new Date(p);M(Number.isFinite(z.getTime())?z.toISOString():p)}else M(p)},Q;if(e.type==="hyperlink")Q=St(Cn,{field:e,text:v,id:b,ariaLabel:B,invalid:Boolean(D),describedBy:A||void 0,disabled:n,locale:g,inputStyle:H.style,inputClassName:H.className,onChange:M,onSave:d,onCancel:s});else if(e.type==="checkbox")Q=ni("select",{...H,value:v,onChange:(p)=>M(p.currentTarget.value),children:[!e.required&&St("option",{value:"",children:f("No value")}),St("option",{value:"true",children:f("Yes")}),St("option",{value:"false",children:f("No")})]});else if(e.type==="longText"||e.type==="json")Q=St("textarea",{...H,value:v,rows:e.type==="json"?4:3,onChange:(p)=>M(p.currentTarget.value)});else{let p=e.type==="date"&&!(C&&v)?j?"datetime-local":"date":"text",z=e.type==="blob";Q=St("input",{...H,type:p,inputMode:e.type==="number"?"decimal":void 0,step:j?"0.001":void 0,value:w,readOnly:z,onInput:e.type==="date"?(te)=>q(te.currentTarget.value):void 0,onChange:(te)=>q(te.currentTarget.value)})}return ni("div",{ref:S,className:"grid min-w-0 gap-1",style:R?{height:"100%"}:void 0,children:[i&&St("label",{className:"text-xs font-medium",htmlFor:b,children:i}),Q,D&&St("span",{id:u,role:"alert",className:"text-xs text-red-600",children:D})]})}import{useEffect as Dr,useMemo as Xa,useState as Bt}from"react";import{jsx as Xt,jsxs as ri}from"react/jsx-runtime";function jn(e,t){if(!t?.length)return e;let n=!1,r={...e};for(let i of t){let o=i.label.trim();if(!o||r[i.id]===o)continue;r[i.id]=o,n=!0}return n?r:e}function xn(e){let t=Xa(()=>me(e.locale),[e.locale]),[n,r]=Bt(""),[i,o]=Bt(),[a,d]=Bt(null),[s,g]=Bt([]),[m,P]=Bt(()=>jn({},e.labels)),[f,c]=Bt(""),[S,R]=Bt(!1),b=e.field.relation?.collectionId,u=e.field.relation?.labelFieldId,{getOptions:v,value:k}=e;Dr(()=>{P((C)=>jn(C,e.labels))},[e.labels]),Dr(()=>{let C=!1;if(!b||!v)return;return R(!0),c(""),v({collectionId:b,...u?{labelFieldId:u}:{},search:n,...i?{cursor:i}:{},limit:50}).then((L)=>{if(C)return;if(!L.ok){c(L.error.message),d(null);return}let D=L.data.items.slice(0,50);P((B)=>jn(B,D)),g((B)=>{let j=i?[...B,...D]:D;return[...new Map(j.map((w)=>[w.id,w])).values()]}),d(L.data.nextCursor)}).catch(()=>{if(!C)c(t("Relation options unavailable."))}).finally(()=>{if(!C)R(!1)}),()=>{C=!0}},[b,u,n,i,v,t]),Dr(()=>{if(!k||!b||!v)return;if(e.labels?.some((L)=>L.id===k&&L.label.trim()))return;let C=!1;return v({collectionId:b,...u?{labelFieldId:u}:{},ids:[k],limit:50}).then((L)=>{if(C||!L.ok)return;let D=L.data.items.find((B)=>B.id===k);if(D)P((B)=>jn(B,[D]))}).catch(()=>{}),()=>{C=!0}},[k,b,u,v,e.labels]);let N=!b||!v,T=k?m[k]??s.find((C)=>C.id===k)?.label??k:"";return ri("div",{children:[Xt("input",{"aria-label":t("Search {name}",{name:e.field.name}),value:n,disabled:e.disabled||N,onKeyDown:(C)=>{if(C.key==="Enter"&&!C.ctrlKey&&!C.metaKey)C.preventDefault()},onChange:(C)=>{r(C.currentTarget.value),o(void 0),g([]),d(null)}}),ri("select",{id:e.id,"aria-describedby":e["aria-describedby"],"aria-invalid":e["aria-invalid"],"aria-label":e.label??e.field.name,value:e.value,disabled:e.disabled||N||S,onChange:(C)=>{let L=C.currentTarget.value;if(!L||s.some((D)=>D.id===L))e.onChange(L)},children:[Xt("option",{value:"",children:t("No relation")}),k&&!s.some((C)=>C.id===k)&&Xt("option",{value:k,children:T}),s.map((C)=>Xt("option",{value:C.id,children:C.label},C.id))]}),a&&Xt("button",{type:"button",disabled:S||e.disabled,onClick:()=>o(a),children:t("More {name} options",{name:e.field.name})}),(f||N)&&Xt("span",{role:"status",children:f||t("Relation option provider unavailable.")})]})}import{jsx as oi}from"react/jsx-runtime";var es={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 Oe({name:e,size:t=15,style:n}){return oi("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:oi("path",{d:es[e]})})}import{createContext as ts,useContext as ns,useCallback as rs,useEffect as ii,useId as os,useLayoutEffect as ai,useRef as si,useState as li}from"react";import{createPortal as is}from"react-dom";import{jsx as bt,jsxs as ui,Fragment as ci}from"react/jsx-runtime";var as=ts(!1),Tr="uibot:collection-popover-open";function Fr({label:e,trigger:t,defaultOpen:n=!1,disabled:r,menu:i,children:o}){let[a,d]=li(n),[s,g]=li({left:8,top:8}),m=si(null),P=si(null),f=os();ii(()=>{let R=(b)=>{let u=b.detail,v=m.current;if(!u||!v||u===v)return;let k=v.closest("[data-uibot-workspace]")??v.parentElement,N=u.closest("[data-uibot-workspace]")??u.parentElement;if(k===N)d(!1)};return document.addEventListener(Tr,R),()=>document.removeEventListener(Tr,R)},[]);let c=()=>{d(!1),m.current?.focus({preventScroll:!0})},S=rs(()=>{if(!a)return;let R=m.current?.getBoundingClientRect(),b=P.current?.getBoundingClientRect();if(R&&b){let u={left:Math.max(8,Math.min(R.left,window.innerWidth-b.width-8)),top:Math.max(8,R.bottom+b.height+8<=window.innerHeight?R.bottom+4:R.top-b.height-4)};g((v)=>v.left===u.left&&v.top===u.top?v:u)}},[a]);return ai(S),ai(()=>{if(!a)return;if(m.current)document.dispatchEvent(new CustomEvent(Tr,{detail:m.current}));(P.current?.querySelector("button:not(:disabled), input, select, textarea")??P.current)?.focus({preventScroll:!0})},[a]),ii(()=>{if(!a)return;let R=(u)=>{if(u.target instanceof Node&&!P.current?.contains(u.target)&&!m.current?.contains(u.target))d(!1)},b=(u)=>{if(u.key!=="Escape")return;u.preventDefault(),u.stopPropagation(),d(!1),m.current?.focus({preventScroll:!0})};return window.addEventListener("resize",S),window.addEventListener("scroll",S,!0),document.addEventListener("pointerdown",R),document.addEventListener("keydown",b),()=>{window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0),document.removeEventListener("pointerdown",R),document.removeEventListener("keydown",b)}},[a,S]),ui(ci,{children:[bt("button",{ref:m,type:"button","aria-label":e,"aria-haspopup":i?"menu":"dialog","aria-expanded":a,"aria-controls":a?f:void 0,disabled:r,style:{display:"inline-flex",alignItems:"center",gap:6,border:0,background:"transparent",color:"inherit",font:"inherit",padding:"4px 6px",cursor:"pointer"},onPointerDown:(R)=>R.stopPropagation(),onClick:()=>a?c():d(!0),children:t}),a&&is(bt("div",{ref:P,id:f,role:i?"menu":"dialog","aria-label":e,tabIndex:-1,style:{position:"fixed",...s,zIndex:80,padding:i?4:12,minWidth:160,maxWidth:"calc(100vw - 16px)",maxHeight:"min(70vh, 600px)",overflow:"auto",boxSizing:"border-box",border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"var(--foreground, inherit)",fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},onKeyDown:(R)=>{if(!i||!["ArrowDown","ArrowUp","Home","End"].includes(R.key))return;R.preventDefault();let b=[...R.currentTarget.querySelectorAll('button[role="menuitem"]:not(:disabled)')],u=b.indexOf(document.activeElement),v=R.key==="Home"?0:R.key==="End"?b.length-1:(u+(R.key==="ArrowUp"?-1:1)+b.length)%b.length;b[v]?.focus()},children:o(c)}),document.body)]})}function di({ui:e,label:t,defaultOpen:n,icon:r,chevron:i,quiet:o,active:a,children:d}){let s=ns(as),g=(m)=>bt("div",{style:{fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},children:bt("fieldset",{disabled:s,style:{border:0,padding:0,margin:0,minWidth:0},children:m})});if(e?.Popover)return e.Popover({label:t,defaultOpen:n,...r?{icon:bt(Oe,{name:r})}:{},...i?{iconEnd:bt(Oe,{name:"chevronDown",size:13})}:{},...o?{quiet:o}:{},active:a,children:typeof d==="function"?(m)=>g(d(m)):g(d)});return bt(Fr,{label:t,defaultOpen:n,trigger:ui(ci,{children:[r?bt(Oe,{name:r}):null,t,i?bt(Oe,{name:"chevronDown",size:13}):null]}),children:(m)=>g(typeof d==="function"?d(m):d)})}import{useEffect as ss,useMemo as ls,useState as ds}from"react";function pi(e,t,n,r,i,o){let a=ls(()=>{let g=n.flatMap((m,P)=>{let f=t.footerStats?.[m.id];return f&&f!=="none"&&f!=="count"?[{fn:f,fieldId:m.id,as:`footer${P}`}]:[]});return JSON.stringify([e,Tn(t,{aggregates:g}),r.map((m)=>[m.id,m.version]),o])},[e,n,t,r,o]),[d,s]=ds({key:"",status:"ready",values:{}});return ss(()=>{if(!i)return;let g=!0,[m,P]=JSON.parse(a);return(async()=>{let f={};for(let c=0;c<P.aggregates.length;c+=8){let S={...P,aggregates:P.aggregates.slice(c,c+8)};if(Fn(m,S))throw Error("Invalid summary");let R=await i.aggregate(m.id,S);if(!g)return;if(!R.ok||R.data.length!==1)throw Error("Summary unavailable");for(let b of S.aggregates){let u=R.data[0]?.values[b.as],v=m.fields.find((N)=>N.id===b.fieldId),k=v?.type==="date"||v?.resultType==="date";if(u!==null&&!(typeof u==="number"&&Number.isFinite(u))&&!(k&&(b.fn==="min"||b.fn==="max")&&typeof u==="string"&&Number.isFinite(Date.parse(u))))throw Error("Invalid summary result");f[b.as]=u}}if(g)s({key:a,client:i,status:"ready",values:f})})().catch(()=>{if(g)s({key:a,client:i,status:"error",values:{}})}),()=>{g=!1}},[i,a]),{status:!i?"local":d.key!==a||d.client!==i?"loading":d.status,values:d.key===a&&d.client===i?d.values:{}}}function mi(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 gi=(e)=>e!==null&&e!==void 0&&e!==""&&!(Array.isArray(e)&&e.length===0)&&e!==!1;function fi(e,t,n){let r=e.map((o)=>o.values[t.id]);if(n==="none")return null;if(n==="count")return e.length;if(n==="filled")return r.filter(gi).length;if(n==="empty")return r.filter((o)=>!gi(o)).length;if(t.type==="date"){let o=r.filter((a)=>typeof a==="string"&&a!=="").sort();if(!o.length)return null;return n==="min"?o[0]??null:o[o.length-1]??null}let i=r.filter((o)=>typeof o==="number"&&Number.isFinite(o));if(!i.length)return null;if(n==="sum")return i.reduce((o,a)=>o+a,0);if(n==="avg")return i.reduce((o,a)=>o+a,0)/i.length;if(n==="min")return Math.min(...i);return Math.max(...i)}import{useEffect as cs,useRef as us}from"react";import{jsx as It,jsxs as yi,Fragment as ps}from"react/jsx-runtime";var $n={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function Ie({ui:e,style:t,variant:n,size:r,children:i,disabled:o,onClick:a,title:d,ariaLabel:s,icon:g,iconOnly:m,badge:P}){let f=e?.Button,c=g?yi("span",{style:{position:"relative",display:"inline-flex"},children:[It(Oe,{name:g}),P?It("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,S=m?c:yi(ps,{children:[c,i]}),R=s,b=d??(m?R:void 0),u=m?"icon":r;if(f)return It(f,{...n?{variant:n}:{},...u?{size:u}:{},disabled:o,onClick:a,title:b,"aria-label":R,children:S});return It("button",{type:"button",style:{...g?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?$n:{},...m?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:o,onClick:a,title:b,"aria-label":R,children:S})}function bi({ui:e,value:t,options:n,onChange:r,disabled:i,label:o,style:a,"aria-describedby":d,"aria-invalid":s}){let g=e?.Select,m={...d?{"aria-describedby":d}:{},...s?{"aria-invalid":!0}:{}};if(g)return It(g,{value:t,options:n,onChange:r,disabled:i,"aria-label":o,...m});return It("select",{"aria-label":o,...m,style:a,disabled:i,value:t,onChange:(P)=>r(P.target.value),children:n.map((P)=>It("option",{value:P.value,disabled:P.disabled,children:P.label},P.value))})}function Hn({label:e,busy:t,onCancel:n,children:r,alert:i=!1}){let o=us(null);return cs(()=>{let a=o.current,d=document.activeElement;if(a?.showModal)a.showModal();else a?.setAttribute("open","");return()=>{if(a?.close?.(),d instanceof HTMLElement&&d.isConnected)d.focus({preventScroll:!0})}},[]),It("dialog",{ref:o,role:i?"alertdialog":"dialog","aria-modal":"true","aria-label":e,style:{position:"fixed",inset:0,margin:"auto",maxWidth:"min(440px, calc(100vw - 32px))",maxHeight:"80vh",overflow:"auto",boxSizing:"border-box",padding:20,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"inherit",font:"inherit"},onKeyDown:(a)=>{if(a.key!=="Tab")return;let d=a.currentTarget,s=[...d.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter((P)=>!P.hidden),g=s[0],m=s.at(-1);if(!g||(a.shiftKey?document.activeElement===g:document.activeElement===m)||!d.contains(document.activeElement)){if(a.preventDefault(),(a.shiftKey?m:g)?.focus(),!g)d.focus()}},tabIndex:-1,onCancel:(a)=>{if(a.preventDefault(),!t)n()},children:r})}import{useEffect as Xn,useRef as nn,useState as Ye}from"react";import{useId as Os,useMemo as Ls,useState as _r}from"react";var hi=(e)=>e.type==="singleLineText"||e.type==="longText",Ci=(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"},xi=(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 gs(e,t){let n=e?.fields??[],r=n.find((o)=>o.id===t),i=n.filter((o)=>hi(o)&&!Ci(o)).sort((o,a)=>xi(o.name)-xi(a.name));return[...r&&hi(r)&&!Ci(r)?[r]:[],...i].filter((o,a,d)=>d.findIndex((s)=>s.id===o.id)===a)}function ms(e){if(!e?.length)return;let t=[...new Set(e.filter((n)=>n!==""))].slice(0,50);return t.length?t:void 0}function vi(e,t){return async(n)=>{let r=ms(n.ids),i=await e.query(n.collectionId,{...r?{ids:r}:n.search?{search:n.search}:{},...!r&&n.cursor?{cursor:n.cursor}:{},limit:Math.min(50,n.limit)});if(!i.ok)return i;let o=gs((typeof t==="function"?t():t).find((a)=>a.id===n.collectionId),n.labelFieldId);return{ok:!0,data:{items:i.data.items.map((a)=>{let d=o.map((s)=>a.values[s.id]).find((s)=>s!==null&&s!==void 0&&String(s).trim()!=="");return{id:a.id,label:d===void 0?a.id:String(d)}}),nextCursor:i.data.nextCursor}}}}import{useEffect as ki,useRef as vn,useState as ct}from"react";import{jsx as ae,jsxs as Ce,Fragment as hs}from"react/jsx-runtime";function fs(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 ys=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function bs({descriptor:e,fieldIds:t,query:n,client:r,readOnly:i=!1,reloadKey:o=0,onImported:a,onRefreshSchema:d}){let[s,g]=ct(null),[m,P]=ct(null),[f,c]=ct(null),[S,R]=ct([]),[b,u]=ct(""),[v,k]=ct(!1),[N,T]=ct(!1),[C,L]=ct(!0),[D,B]=ct(null),[j,w]=ct(!1),A=vn(!1),H=vn(!1),M=vn(!1),q=vn(null),Q=vn({client:r,onImported:a,descriptor:e});Q.current={client:r,onImported:a,descriptor:e},ki(()=>(A.current=!0,()=>{A.current=!1,H.current=!1}),[]),ki(()=>{let O=!0;if(!i)r.imports(e.id).then((E)=>{if(!O||!A.current||!E.ok)return;if(R((ie)=>E.data.map((ue)=>{let le=ie.find((Y)=>Y.id===ue.id);return le&&le.version>ue.version?le:ue})),!M.current)c((ie)=>{let ue=E.data.find((le)=>le.id===ie?.id);return ie&&ue&&ue.version>ie.version?ue:ie})});return()=>{O=!1}},[r,e.id,i,o]);let p=(O)=>{c(O),R((E)=>[O,...E.filter((ie)=>ie.id!==O.id)].slice(0,50)),B(null)};async function z(O){if(M.current||i)return;M.current=!0,H.current=!0,k(!0),T(!0),u("");let E=O;try{while(A.current&&H.current&&E.status==="ready"){let ie=await Q.current.client.advanceImport(e.id,E.id,E.version);if(!A.current)break;if(!ie.ok){u(ie.error.message);break}let ue=ie.data;if(p(ue),ue.importedRows>E.importedRows)Q.current.onImported();if(ue.version===E.version&&ue.status==="ready"){u("Import paused. Refresh the saved progress before retrying.");break}E=ue}}finally{if(M.current=!1,H.current=!1,A.current)k(!1),T(!1)}}async function te(){if(!s||M.current)return;M.current=!0,k(!0),u("");let O=await r.previewImport(e.id,{...s,expectedSchemaVersion:e.schemaVersion});if(M.current=!1,!A.current)return;if(k(!1),O.ok)P(O.data),g({...s,expectedSchemaVersion:O.data.schemaVersion,mapping:O.data.mapping});else u(O.error.message)}async function pe(){if(!s||!m||m.missingRequiredFieldIds.length||!m.totalRows||M.current||i)return;M.current=!0,k(!0),u(""),q.current??=crypto.randomUUID();let O=await r.createImport(e.id,{...s,idempotencyKey:q.current});if(M.current=!1,!A.current)return;if(k(!1),O.ok)p(O.data),g(null),P(null),q.current=null,z(O.data);else u(O.error.message)}async function F(){if(!f||M.current||i)return;if(f.status==="ready"){z(f);return}M.current=!0,k(!0),u("");let O=d?await d():Q.current.descriptor;if(!O){M.current=!1,k(!1),u("Refresh the collection schema and try again.");return}let E=await r.resumeImport(e.id,f.id,f.version,O.schemaVersion);if(M.current=!1,!A.current)return;if(k(!1),E.ok)p(E.data),z(E.data);else u(E.error.message)}async function X(O){if(!f)return;let E=await r.importErrors(e.id,f.id,{limit:100,...O===void 0?{}:{cursor:O},expectedVersion:f.version});if(!A.current)return;if(E.ok)B(E.data);else u(E.error.message)}async function ee(O=!1){if(v||M.current)return;M.current=!0,k(!0),u("");let E=O&&f?await r.exportImportErrors(e.id,f.id):await r.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:C});if(M.current=!1,!A.current)return;if(k(!1),E.ok)fs(E.data),u(`${E.data.rowCount} rows downloaded${E.data.protectedCells?`; ${E.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else u(E.error.message)}return Ce("details",{className:"min-w-0 rounded-lg border p-4",children:[ae("summary",{className:"cursor-pointer text-sm font-medium",children:"CSV import and export"}),Ce("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[Ce("div",{className:"flex flex-wrap items-center gap-3",children:[ae("button",{type:"button",disabled:v||!t.length,onClick:()=>void ee(),children:"Export CSV"}),Ce("label",{className:"flex items-center gap-2 text-sm",children:[ae("input",{type:"checkbox",checked:C,onChange:(O)=>L(O.target.checked)}),"Spreadsheet view"]})]}),ae("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&&Ce(hs,{children:[Ce("label",{className:"flex min-w-0 flex-col gap-2 text-sm",children:["CSV file",ae("input",{"aria-label":"CSV file",className:"max-w-full",type:"file",accept:".csv,text/csv",disabled:v,onChange:async(O)=>{let E=O.target.files?.[0];if(!E)return;if(u(""),P(null),g(null),q.current=null,E.size>20971520){u("Choose a UTF-8 CSV file no larger than 20 MiB.");return}k(!0),M.current=!0;try{let ie=new TextDecoder("utf-8",{fatal:!0}).decode(await E.arrayBuffer());if(A.current)g({fileName:E.name,csv:ie,expectedSchemaVersion:e.schemaVersion})}catch{if(A.current)u("The file must be valid UTF-8 text.")}finally{if(M.current=!1,A.current)k(!1)}}})]}),s&&Ce("div",{className:"flex flex-wrap gap-3",children:[ae("span",{className:"break-all text-sm",children:s.fileName}),ae("button",{type:"button",disabled:v,onClick:()=>void te(),children:"Preview CSV"})]}),ae("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."}),m&&s&&Ce("div",{className:"flex min-w-0 flex-col gap-3",children:[Ce("p",{className:"text-sm",children:[m.totalRows," rows · ",m.validRows," valid · ",m.invalidRows," ","invalid · ",m.ignoredColumns.length," skipped columns"]}),m.headers.map((O,E)=>Ce("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[Ce("span",{className:"max-w-64 break-all",children:["Column ",E+1,": ",O||"(empty)"]}),Ce("select",{"aria-label":`Column ${E+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:s.mapping?.[E]??"",disabled:v,onChange:(ie)=>{let ue=[...s.mapping??m.mapping];ue[E]=ie.target.value||null,g({...s,mapping:ue}),P(null),q.current=null},children:[ae("option",{value:"",children:"Skip column"}),e.fields.filter((ie)=>!Me(ie)).map((ie)=>Ce("option",{value:ie.id,children:[ie.name," (",ie.id,")",ie.required?" · required":""]},ie.id))]})]},`${E}:${O}`)),m.missingRequiredFieldIds.length>0&&Ce("p",{role:"alert",children:["Map required fields: ",m.missingRequiredFieldIds.join(", ")]}),ae("div",{className:"max-w-full overflow-x-auto",children:Ce("table",{className:"w-full text-xs",children:[Ce("caption",{children:["First ",m.sample.length," normalized rows; row numbers include the header."]}),ae("thead",{children:Ce("tr",{children:[ae("th",{children:"Row"}),ae("th",{children:"Normalized values"}),ae("th",{children:"Error"})]})}),ae("tbody",{children:m.sample.map((O)=>Ce("tr",{children:[ae("td",{children:O.rowNumber}),ae("td",{className:"max-w-96 break-all",children:ys(O.values)}),ae("td",{children:O.error?.code??""})]},O.rowNumber))})]})}),ae("button",{type:"button",className:"self-start",disabled:v||!m.totalRows||m.missingRequiredFieldIds.length>0,onClick:()=>void pe(),children:"Confirm import"})]}),Ce("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",Ce("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:f?.id??"",disabled:v,onChange:async(O)=>{if(!O.target.value){c(null);return}let E=await r.importJob(e.id,O.target.value);if(A.current)if(E.ok)p(E.data),w(!1);else u(E.error.message)},children:[ae("option",{value:"",children:"Choose saved progress…"}),S.map((O)=>Ce("option",{value:O.id,children:[O.fileName," · ",O.processedRows,"/",O.totalRows," · ",O.status]},O.id))]})]}),ae("button",{type:"button",className:"self-start",disabled:v,onClick:async()=>{let O=await r.imports(e.id);if(A.current)if(O.ok)R(O.data);else u(O.error.message)},children:"Refresh saved imports"}),f&&Ce("div",{className:"flex flex-col gap-3",children:[Ce("p",{role:"status",children:[N?"Importing":f.status==="ready"?"Paused":f.status==="schemaChanged"?"Schema changed — confirm before continuing":f.status==="completed"?"Completed":"Cancelled"," ","· ",f.processedRows," of ",f.totalRows," processed · ",f.importedRows," imported ·"," ",f.failedRows," failed"]}),ae("progress",{"aria-label":"Import progress",max:f.totalRows,value:f.processedRows,className:"max-w-full"}),ae("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."}),Ce("div",{className:"flex flex-wrap gap-3",children:[N&&ae("button",{type:"button",onClick:()=>{H.current=!1,T(!1)},children:"Pause import"}),!N&&(f.status==="ready"||f.status==="schemaChanged")&&ae("button",{type:"button",disabled:v,onClick:()=>void F(),children:f.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(f.status==="ready"||f.status==="schemaChanged")&&ae("button",{type:"button",disabled:v,onClick:()=>w(!0),children:"Cancel import"}),ae("button",{type:"button",disabled:v||!f.failedRows,onClick:()=>void X(),children:"Show import errors"}),ae("button",{type:"button",disabled:v||!f.failedRows,onClick:()=>void ee(!0),children:"Download all import errors"})]}),j&&Ce("div",{children:[Ce("p",{children:["Stop remaining rows? The ",f.importedRows," imported records will remain."]}),ae("button",{type:"button",disabled:v,onClick:async()=>{M.current=!0,k(!0);let O=await r.cancelImport(e.id,f.id);if(M.current=!1,!A.current)return;if(k(!1),O.ok)p(O.data),w(!1);else u(O.error.message)},children:"Confirm cancellation"}),ae("button",{type:"button",onClick:()=>w(!1),children:"Keep import"})]}),D&&Ce("div",{className:"max-w-full overflow-x-auto",children:[Ce("table",{className:"w-full text-xs",children:[Ce("caption",{children:[D.total," failed rows"]}),ae("thead",{children:Ce("tr",{children:[ae("th",{children:"Row"}),ae("th",{children:"Field"}),ae("th",{children:"Error"})]})}),ae("tbody",{children:D.items.map((O)=>Ce("tr",{children:[ae("td",{children:O.rowNumber}),ae("td",{children:O.fieldId??""}),ae("td",{children:O.code})]},O.rowNumber))})]}),D.nextCursor!==null&&ae("button",{type:"button",onClick:()=>void X(D.nextCursor??void 0),children:"Next errors"})]})]})]}),b&&ae("p",{role:"alert",className:"break-words text-sm",children:b})]})]})}import{useEffect as wi,useRef as Ut,useState as qt}from"react";import{jsx as Re,jsxs as ze,Fragment as xs}from"react/jsx-runtime";var Kn=[{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 Cs({descriptor:e,client:t,onConverted:n}){let r=e.fields.filter((p)=>Kn.some((z)=>z.type===p.type)),[i,o]=qt(r[0]?.id??""),a=r.find((p)=>p.id===i)??r[0],[d,s]=qt(a?.type??"singleLineText"),[g,m]=qt(a?.required??!1),[P,f]=qt(a?.options?.map((p)=>`${p.id}=${p.name}`).join(`
5
+ `)??""),[c,S]=qt(null),[R,b]=qt(""),[u,v]=qt(!1),k=Ut(null),N=Ut(null),T=Ut(0),C=Ut(e);C.current=e;let L=k.current?.field??a,D=u||k.current!==null,B=`${e.id}:${e.schemaVersion}:${JSON.stringify(e.fields)}`,j=Ut(e.fields);j.current=e.fields;let w=Ut(B);w.current=B;let A=Ut(!0);wi(()=>(A.current=!0,()=>{A.current=!1,T.current++}),[]),wi(()=>{if(w.current!==B)return;if(k.current&&N.current===e.id)return;T.current++;let p=j.current.find((z)=>z.id===i&&Kn.some((te)=>te.type===z.type))??j.current.find((z)=>Kn.some((te)=>te.type===z.type));if(p)o(p.id),s(p.type),m(p.required??!1),f(p.options?.map((z)=>`${z.id}=${z.name}`).join(`
6
+ `)??"");S(null),k.current=null,N.current=null,b(""),v(!1)},[B,i,e.id]);let H=()=>{S(null),k.current=null,N.current=null,T.current++,b("")},M=(p)=>{o(p.id),s(p.type),m(p.required??!1),f(p.options?.map((z)=>`${z.id}=${z.name}`).join(`
7
+ `)??""),H()};if(!L)return null;let q=()=>{let p={id:L.id,name:L.name,type:d,required:g};if(d==="singleSelect"||d==="multipleSelect")p.options=P.split(`
8
+ `).filter((z)=>z.trim()).map((z)=>{let te=z.indexOf("=");if(te<1)throw Error("Each option must use stable_id=Display name.");return{id:z.slice(0,te).trim(),name:z.slice(te+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:p}},Q=()=>A.current&&w.current===B;return ze("details",{className:"rounded-lg border p-4",children:[Re("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),ze("div",{className:"mt-4 flex flex-col gap-3",children:[Re("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."}),ze("label",{children:["Field"," ",ze("select",{"aria-label":"Conversion field",value:L.id,disabled:D,onChange:(p)=>{let z=r.find((te)=>te.id===p.target.value);if(z)M(z)},children:[k.current&&!r.some((p)=>p.id===L.id)&&Re("option",{value:L.id,children:L.name}),r.map((p)=>Re("option",{value:p.id,children:p.name},p.id))]})]}),ze("label",{children:["Target type"," ",Re("select",{"aria-label":"Conversion target type",value:d,disabled:D,onChange:(p)=>{s(p.target.value),H()},children:Kn.map((p)=>Re("option",{value:p.type,children:p.label},p.type))})]}),ze("label",{children:[Re("input",{type:"checkbox",checked:g,disabled:D,onChange:(p)=>{m(p.target.checked),H()}})," ","Required after conversion"]}),(d==="singleSelect"||d==="multipleSelect")&&ze("label",{children:["Stable option IDs and display names",Re("textarea",{"aria-label":"Conversion options",className:"block w-full rounded border p-2",disabled:D,value:P,onChange:(p)=>{f(p.target.value),H()},placeholder:`open=Open
9
+ done=Done`})]}),R&&Re("p",{role:"alert",className:"text-sm text-destructive",children:R}),Re("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:D,onClick:async()=>{let p;try{p=q()}catch(z){b(z instanceof Error?z.message:"Invalid conversion options.");return}v(!0),b(""),S(null),k.current=null;try{let z=await t.previewConversion(e.id,p);if(!Q())return;if(z.ok)S(z.data);else b(z.error.message)}catch{if(Q())b("Preview unavailable. Your draft is kept.")}finally{if(Q())v(!1)}},children:u?"Working…":"Preview conversion"}),c&&ze(xs,{children:[ze("p",{role:"status",children:[c.validRows," valid · ",c.invalidRows," invalid"]}),ze("p",{className:"text-xs",children:["Preview covers ",c.totalRows," records. Samples and errors show at most 20 records."]}),Re("div",{className:"overflow-x-auto",children:ze("table",{className:"w-full text-sm",children:[Re("thead",{children:ze("tr",{children:[Re("th",{children:"Record"}),Re("th",{children:"Before"}),Re("th",{children:"After"}),Re("th",{children:"Error"})]})}),Re("tbody",{children:c.sample.map((p)=>ze("tr",{children:[Re("td",{className:"max-w-32 break-all",children:p.id}),Re("td",{className:"max-w-48 break-words",children:JSON.stringify(p.before)}),Re("td",{className:"max-w-48 break-words",children:JSON.stringify(p.after)}),Re("td",{children:p.error})]},p.id))})]})}),c.errors.length>0&&Re("ul",{children:c.errors.map((p)=>ze("li",{children:[Re("span",{className:"break-all",children:p.id}),": ",Re("span",{children:p.code})]},p.id))}),Re("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:u||c.invalidRows>0,onClick:async()=>{if(!k.current)N.current=e.id,T.current++;k.current??={expectedSchemaVersion:c.schemaVersion,field:c.field,previewToken:c.previewToken,idempotencyKey:crypto.randomUUID()};let p=k.current,z=T.current,te=()=>A.current&&C.current.id===e.id&&z===T.current;v(!0),b("");try{let pe=await t.convertField(e.id,p);if(!te())return;if(pe.ok){if(S(null),k.current=null,N.current=null,pe.data.descriptor.schemaVersion>=C.current.schemaVersion)n(pe.data.descriptor)}else if(b(pe.error.message),pe.error.status===409)S(null),k.current=null,N.current=null}catch{if(te())b("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(te())v(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as vs,useRef as Nr,useState as Pi}from"react";import{jsx as Ri,jsxs as ws}from"react/jsx-runtime";function ks({collectionIds:e,client:t,onChanges:n,pollIntervalMs:r=2000}){let i=JSON.stringify([...new Set(e)].sort()),o=Nr(i);o.current=i;let a=Nr(n);a.current=n;let d=Nr(()=>{}),[s,g]=Pi("connecting"),[m,P]=Pi(!1);return vs(()=>{let f=JSON.parse(i),c=new Map,S=!1,R=!1,b=0,u,v=()=>!S&&o.current===i,k=Math.max(50,Math.min(60000,r)),N=async()=>{if(!v()||R)return;R=!0,P(!0);let L=!1;try{let D=b>0;for(let B of f){let j=c.get(B),w=await t.changes(B,{...j!==void 0?{cursor:j}:{},limit:100});if(!v())return;if(!w.ok)throw g(w.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let A=j===void 0;if(A||D||w.data.items.length>0)await a.current(B,w.data,A);if(!v())return;c.set(B,w.data.cursor),L||=w.data.hasMore}b=0,g("live")}catch{if(b++,v())g((D)=>D==="expired"?"expired":"offline")}finally{if(R=!1,v())P(!1),u=setTimeout(()=>{N()},L&&b===0?0:Math.min(30000,k*2**Math.min(b,8)))}},T=()=>{if(u!==void 0)clearTimeout(u);N()};d.current=T,g("connecting"),N();let C=()=>{if(document.visibilityState==="visible")T()};return window.addEventListener("online",T),document.addEventListener("visibilitychange",C),()=>{if(S=!0,u!==void 0)clearTimeout(u);window.removeEventListener("online",T),document.removeEventListener("visibilitychange",C)}},[i,t,r]),ws("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[Ri("p",{role:"status",children:s==="live"?"Live updates":s==="connecting"?"Connecting live updates…":s==="expired"?"Session expired. Renew your session; drafts are kept.":"Connection interrupted. Drafts are kept."}),(s==="offline"||s==="expired")&&Ri("button",{type:"button",className:"rounded border px-2 py-1",disabled:m,onClick:()=>d.current(),children:"Reconnect now"})]})}import{useEffect as Gn,useRef as At,useState as Ke}from"react";import{jsx as ce,jsxs as xe,Fragment as Lr}from"react/jsx-runtime";var Or={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function kn(e){try{return await e()}catch{return{ok:!1,error:Or}}}function Mr({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return xe("div",{className:"min-w-0",children:[ce("strong",{children:t}),ce("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-words rounded border p-2 text-xs",children:n.slice(0,16000)}),n.length>16000&&xe(Lr,{children:[ce("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),ce("button",{type:"button",onClick:()=>{let r=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),i=document.createElement("a");i.href=r,i.download=`record-${e?.id}-${e?.version}.json`,i.click(),setTimeout(()=>URL.revokeObjectURL(r),1000)},children:"Download snapshot"})]})]})}function Ps({descriptor:e,recordId:t,client:n,readOnly:r=!1,onCommitted:i,registerRefresh:o}){let[a,d]=Ke(null),[s,g]=Ke(null),[m,P]=Ke(null),[f,c]=Ke(),[S,R]=Ke(),[b,u]=Ke([]),[v,k]=Ke([]),[N,T]=Ke(""),[C,L]=Ke(null),[D,B]=Ke(null),[j,w]=Ke(null),[A,H]=Ke(!1),[M,q]=Ke(""),Q=At(null),p=At(null),z=At(n);z.current=n;let te=At(!1),pe=At(0),F=`${e.id}:${t}`,X=At(F);X.current=F;let ee=At({historyBefore:f,commentBefore:S});ee.current={historyBefore:f,commentBefore:S};let O=At(async()=>{}),E=(h=F)=>te.current&&X.current===h&&z.current===n,ie=async()=>{let h=F,G=++pe.current,Z=ee.current,[ke,qe]=await Promise.all([kn(()=>n.history(e.id,t,{...Z.historyBefore===void 0?{}:{before:Z.historyBefore},limit:20})),kn(()=>n.comments(e.id,t,{...Z.commentBefore===void 0?{}:{before:Z.commentBefore},limit:50}))]);if(!E(h)||G!==pe.current)throw Error("Refresh superseded");if(!ke.ok||!qe.ok)throw q(!ke.ok?ke.error.message:!qe.ok?qe.error.message:Or.message),Error("Activity refresh failed");g(ke.data),P(qe.data),d(h)};O.current=ie,Gn(()=>(te.current=!0,()=>{te.current=!1,pe.current++}),[]),Gn(()=>(o?.(()=>O.current()),()=>o?.(null)),[o]),Gn(()=>{if(X.current!==F)return;g(null),P(null),d(null),c(void 0),R(void 0),u([]),k([]),ee.current={historyBefore:void 0,commentBefore:void 0},T(""),L(null),B(null),w(null),Q.current=null,p.current=null,H(!1),q("")},[F]),Gn(()=>{if(X.current!==F||z.current!==n||ee.current.historyBefore!==f||ee.current.commentBefore!==S)return;O.current().catch(()=>{})},[F,n,f,S]);let ue=(h)=>{let G=Q.current;if(G?.signature===h)return G.key;let Z={signature:h,key:crypto.randomUUID()};return Q.current=Z,Z.key},le=async(h)=>{if(A||r||!m||a!==F)return;let G=h==="delete"?D:C;if(h!=="create"&&(!G||G.authorId!==m.actorId))return;let Z=h==="create"?N:C?.draft??"";if(h!=="delete"&&(!Z.trim()||Z.length>4000||Z.includes("\x00"))){q("Comments require 1–4,000 characters.");return}let ke=ue(JSON.stringify([h,G?.id,G?.version,Z]));H(!0),q("");let qe=await kn(async()=>{if(h==="create")return n.createComment(e.id,t,{text:Z,idempotencyKey:ke});if(!G)return{ok:!1,error:Or};if(h==="edit")return n.editComment(e.id,t,G.id,{text:Z,expectedVersion:G.version,idempotencyKey:ke});return n.deleteComment(e.id,t,G.id,{expectedVersion:G.version,idempotencyKey:ke})});if(!E())return;if(H(!1),!qe.ok){q(qe.error.message);return}if(Q.current=null,h==="create")T("");else if(h==="edit")L(null);else B(null);if(h==="create"&&S!==void 0)R(void 0),k([]);else await O.current().catch(()=>{})},Y=async(h)=>{if(A||r||!s||a!==F)return;H(!0),q(""),p.current=null;let G={targetVersion:h,expectedCurrentVersion:s.currentVersion,expectedSchemaVersion:e.schemaVersion},Z=await kn(()=>n.previewUndo(e.id,t,G));if(!E())return;if(H(!1),Z.ok)w(Z.data);else w(null),q(Z.error.message)},de=async()=>{if(A||r||a!==F||!j&&!p.current)return;let h=p.current;if(!h){if(!j)return;h={targetVersion:j.targetVersion,expectedCurrentVersion:j.currentVersion,expectedSchemaVersion:j.schemaVersion,idempotencyKey:crypto.randomUUID()},p.current=h}let G=h;H(!0),q("");let Z=await kn(()=>n.undo(e.id,t,G));if(!E())return;if(H(!1),!Z.ok){if(Z.error.code==="version_conflict"||Z.error.code==="reference_conflict"||Z.error.code==="validation")p.current=null,w(null);q(Z.error.message),await O.current().catch(()=>{});return}p.current=null,w(null),i(Z.data),c(void 0),u([]),await O.current().catch(()=>{})},oe=m?.items.find((h)=>h.id===C?.id),Ne=C&&oe&&oe.version!==C.version,V=j&&(j.currentVersion!==s?.currentVersion||j.schemaVersion!==e.schemaVersion);return xe("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[xe("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[xe("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),ce("button",{type:"button",disabled:A,onClick:()=>{q(""),O.current().catch(()=>{})},children:"Refresh activity"})]}),M&&ce("p",{role:"alert",className:"text-sm text-destructive",children:M}),!s||!m||a!==F?ce("p",{role:"status",children:"Loading record activity…"}):xe(Lr,{children:[xe("p",{role:"status",children:["Current version ",s.currentVersion,s.currentDeleted?" · Deleted record":""]}),ce("h3",{className:"font-medium",children:"Comments"}),m.items.length===0&&ce("p",{className:"text-sm",children:"No comments yet."}),ce("ol",{className:"flex flex-col gap-3",children:m.items.map((h)=>xe("li",{className:"min-w-0 rounded border p-3",children:[xe("p",{className:"break-all text-xs",children:[h.authorId," · ",h.updatedAt," · version ",h.version]}),ce("p",{className:"whitespace-pre-wrap break-words text-sm",children:h.text??"Comment deleted"}),!r&&h.text!==null&&h.authorId===m.actorId&&xe("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:A,onClick:()=>{L({...h,draft:h.text??""}),B(null),Q.current=null},children:"Edit comment"}),ce("button",{type:"button",disabled:A,onClick:()=>{B(h),L(null),Q.current=null},children:"Delete comment"})]})]},h.id))}),xe("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:A||!v.length,onClick:()=>{R(v.at(-1)),k((h)=>h.slice(0,-1))},children:"Newer comments"}),ce("button",{type:"button",disabled:A||m.nextCursor===null,onClick:()=>{k((h)=>[...h,S]),R(m.nextCursor??void 0)},children:"Older comments"})]}),!r&&xe(Lr,{children:[C&&xe("div",{className:"flex flex-col gap-2",children:[xe("label",{children:["Edit comment text",ce("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:A,maxLength:4000,value:C.draft,onChange:(h)=>{L({...C,draft:h.target.value}),Q.current=null}})]}),Ne&&xe("div",{role:"status",children:[ce("p",{children:"This comment changed. Your draft and original version are kept."}),xe("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",oe.text??"Comment deleted"]}),oe.text!==null&&oe.authorId===m.actorId&&ce("button",{type:"button",disabled:A,onClick:()=>{L({...oe,draft:C.draft}),Q.current=null},children:"Use current comment version"})]}),xe("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:A||C.authorId!==m.actorId,onClick:()=>void le("edit"),children:"Save comment"}),ce("button",{type:"button",disabled:A,onClick:()=>{L(null),Q.current=null},children:"Cancel comment edit"})]})]}),D&&xe("div",{children:[ce("p",{children:"Delete this comment? A deletion marker will remain."}),ce("p",{className:"whitespace-pre-wrap break-words",children:D.text}),ce("button",{type:"button",disabled:A||D.authorId!==m.actorId,onClick:()=>void le("delete"),children:"Confirm delete comment"}),ce("button",{type:"button",disabled:A,onClick:()=>B(null),children:"Cancel delete comment"})]}),xe("label",{children:["New comment",ce("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:A,maxLength:4000,value:N,onChange:(h)=>{T(h.target.value),Q.current=null}})]}),ce("button",{type:"button",className:"self-start",disabled:A||!N.trim(),onClick:()=>void le("create"),children:"Add comment"})]}),ce("h3",{className:"font-medium",children:"Record history"}),ce("p",{className:"text-xs",children:"Stored writable values at each version. Live computed values are excluded. A legacy baseline has an unknown author; earlier versions cannot be recovered."}),ce("ol",{className:"flex flex-col gap-3",children:s.items.map((h)=>xe("li",{className:"min-w-0 rounded border p-3",children:[xe("p",{className:"break-all text-xs",children:["Version ",h.version," · ",h.operation," · schema ",h.schemaVersion," · ",h.actorId," ·"," ",h.createdAt]}),xe("details",{children:[xe("summary",{children:["Stored values at version ",h.version]}),ce(Mr,{record:h.snapshot,label:`Version ${h.version}`})]}),!r&&h.version<s.currentVersion&&xe("button",{type:"button",disabled:A,onClick:()=>void Y(h.version),children:["Preview restore version ",h.version]})]},h.id))}),xe("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:A||!b.length,onClick:()=>{c(b.at(-1)),u((h)=>h.slice(0,-1))},children:"Newer history"}),ce("button",{type:"button",disabled:A||s.nextCursor===null,onClick:()=>{u((h)=>[...h,f]),c(s.nextCursor??void 0)},children:"Older history"})]}),!r&&j&&xe("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[xe("h3",{children:["Restore version ",j.targetVersion," as a new version"]}),xe("p",{children:["Current version ",j.currentVersion," · schema ",j.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),xe("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[ce(Mr,{record:j.before,label:"Current stored values"}),ce(Mr,{record:j.target,label:"Values to restore"})]}),V&&!p.current&&ce("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),xe("div",{className:"flex gap-3",children:[ce("button",{type:"button",disabled:A||!!V&&!p.current,onClick:()=>void de(),children:p.current?"Retry undo":"Confirm restore"}),ce("button",{type:"button",disabled:A,onClick:()=>{w(null),p.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as Wn,useRef as Et,useState as ht}from"react";import{jsx as Ve,jsxs as Ge,Fragment as Si}from"react/jsx-runtime";async function Yn(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 Rs(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function Ss({collectionId:e,recordId:t,client:n,readOnly:r=!1,registerRefresh:i}){let o=`${e}:${t}`,a=Et({identity:o,client:n});a.current={identity:o,client:n};let d=Et(!1),s=Et(0),g=Et(0),[m,P]=ht(null),[f,c]=ht(null),[S,R]=ht(),[b,u]=ht([]),v=Et(S);v.current=S;let[k,N]=ht(null),[T,C]=ht(null),L=Et(null),D=Et(null),[B,j]=ht(!1),[w,A]=ht(!1),[H,M]=ht(""),q=()=>d.current&&a.current.identity===o&&a.current.client===n,Q=async()=>{let F=++s.current,X=await Yn(()=>n.list(e,t,{limit:20,...v.current===void 0?{}:{before:v.current}}));if(!q()||F!==s.current)throw Error("Refresh superseded");if(!X.ok)throw M(X.error.message),Error("Attachment refresh failed");c(X.data),P(o)},p=Et(Q);p.current=Q,Wn(()=>(d.current=!0,()=>{d.current=!1,++s.current,++g.current}),[]),Wn(()=>{if(a.current.identity!==o||a.current.client!==n)return;P(null),c(null),N(null),C(null),L.current=null,j(!1),A(!1),M(""),R(void 0),u([]),v.current=void 0,++g.current,p.current().catch(()=>{})},[o,n]),Wn(()=>{if(v.current===S&&m===o)p.current().catch(()=>{})},[S,o,m]),Wn(()=>(i?.(()=>p.current()),()=>i?.(null)),[i]);let z=async()=>{if(B||r||!k||m!==o)return;let F=k;j(!0),M("");let X=await Yn(()=>n.upload(e,t,F));if(!q())return;if(j(!1),!X.ok){M(X.error.message);return}if(N(null),D.current)D.current.value="";R(void 0),u([]),v.current=void 0,await p.current().catch(()=>{})},te=async()=>{if(B||r||!T||T.authorId!==f?.actorId||m!==o)return;L.current??=crypto.randomUUID();let F=T,X=L.current;j(!0),M("");let ee=await Yn(()=>n.delete(e,t,F.id,{expectedVersion:F.version,idempotencyKey:X}));if(!q())return;if(j(!1),!ee.ok){M(ee.error.message),await p.current().catch(()=>{});return}C(null),L.current=null,await p.current().catch(()=>{})},pe=async(F)=>{if(B||m!==o)return;j(!0),M("");let X=await Yn(()=>n.content(e,t,F.id));if(!q())return;if(j(!1),!X.ok){M(X.error.message);return}let ee=Uint8Array.from(atob(X.data.base64),(ie)=>ie.charCodeAt(0)),O=URL.createObjectURL(new Blob([ee],{type:"application/octet-stream"})),E=document.createElement("a");E.href=O,E.download=X.data.attachment.name,E.click(),setTimeout(()=>URL.revokeObjectURL(O),1000)};return Ge("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Ge("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ve("h3",{className:"font-medium",children:"Attachments"}),Ve("button",{type:"button",disabled:B,onClick:()=>{M(""),p.current().catch(()=>{})},children:"Refresh attachments"})]}),H&&Ve("p",{role:"alert",children:H}),!f||m!==o?Ve("p",{role:"status",children:"Loading attachments…"}):Ge(Si,{children:[f.items.length===0&&Ve("p",{children:"No attachments yet."}),Ve("ol",{className:"flex min-w-0 flex-col gap-2",children:f.items.map((F)=>Ge("li",{className:"min-w-0 rounded border p-2",children:[Ve("p",{className:"break-all",children:F.name}),Ge("p",{className:"break-all text-xs",children:[F.size," bytes · version ",F.version," · ",F.authorId]}),F.deletedAt?Ve("p",{children:"Attachment deleted"}):Ge("div",{className:"flex flex-wrap gap-3",children:[Ve("button",{type:"button",disabled:B,"aria-label":`Download attachment ${F.name}`,onClick:()=>void pe(F),children:"Download"}),!r&&F.authorId===f.actorId&&Ve("button",{type:"button",disabled:B,"aria-label":`Delete attachment ${F.name}`,onClick:()=>{C(F),L.current=null},children:"Delete"})]})]},F.id))}),Ge("div",{className:"flex flex-wrap gap-3",children:[Ve("button",{type:"button",disabled:B||!b.length,onClick:()=>{R(b.at(-1)),u((F)=>F.slice(0,-1))},children:"Newer attachments"}),Ve("button",{type:"button",disabled:B||f.nextCursor===null,onClick:()=>{u((F)=>[...F,S]),R(f.nextCursor??void 0)},children:"Older attachments"})]}),!r&&Ge(Si,{children:[Ve("p",{className:"text-xs",children:"Up to 1 MiB per file, 20 active files and 5 MiB per record. Files have independent versions; restoring record values does not restore deleted files."}),Ge("label",{children:["Attachment file",Ve("input",{ref:D,"aria-label":"Attachment file",type:"file",disabled:B||w,onChange:async(F)=>{let X=F.target.files?.[0];if(!X)return;let ee=++g.current;if(N(null),M(""),!X.size||X.size>1048576){M("Choose a nonempty file up to 1 MiB.");return}A(!0);try{let O=await Rs(X);if(!q()||ee!==g.current)return;let E=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(X.type)?X.type:"application/octet-stream";N({name:X.name,contentType:E,base64:O,idempotencyKey:crypto.randomUUID()})}catch{if(q()&&ee===g.current)M("The selected file could not be read.")}finally{if(q()&&ee===g.current)A(!1)}}},o)]}),k&&Ge("p",{className:"break-all",children:["Selected file: ",k.name]}),Ve("button",{type:"button",className:"self-start",disabled:B||w||!k,onClick:()=>void z(),children:"Upload attachment"}),T&&Ge("div",{children:[Ge("p",{className:"break-all",children:["Delete ",T.name,"? This permanently removes its bytes and keeps a deletion marker."]}),Ge("div",{className:"flex flex-wrap gap-3",children:[Ve("button",{type:"button",disabled:B,onClick:()=>void te(),children:"Confirm delete attachment"}),Ve("button",{type:"button",disabled:B,onClick:()=>{C(null),L.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as Jn,useRef as en,useState as We}from"react";import{jsx as we,jsxs as Ae,Fragment as Ii}from"react/jsx-runtime";async function Vr(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function Is(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function As({descriptor:e,recordIds:t,client:n,linkForGrant:r,registerRefresh:i}){let o=e.id,a=en({identity:o,client:n});a.current={identity:o,client:n};let d=en(!1),s=en(0),[g,m]=We(null),[P,f]=We(null),[c,S]=We(),R=en(c);R.current=c;let[b,u]=We([]),[v,k]=We([]),[N,T]=We([]),[C,L]=We(3600),[D,B]=We(null),[j,w]=We(!1),[A,H]=We(""),[M,q]=We(null),Q=en(null),[p,z]=We(!1),[te,pe]=We(""),F=()=>d.current&&a.current.identity===o&&a.current.client===n,X=async()=>{let Y=++s.current,de=await Vr(()=>n.list(o,{limit:20,...R.current===void 0?{}:{before:R.current}}));if(!F()||Y!==s.current)throw Error("Refresh superseded");if(!de.ok)throw pe(de.error.message),Error("Share refresh failed");f(de.data),m(o)},ee=en(X);ee.current=X,Jn(()=>(d.current=!0,()=>{d.current=!1,++s.current}),[]),Jn(()=>{if(a.current.identity!==o||a.current.client!==n)return;m(null),f(null),k([]),T([]),B(null),w(!1),H(""),q(null),Q.current=null,z(!1),pe(""),S(void 0),u([]),R.current=void 0,ee.current().catch(()=>{})},[o,n]),Jn(()=>{if(R.current===c&&g===o)ee.current().catch(()=>{})},[c,g,o]),Jn(()=>(i?.(()=>ee.current()),()=>i?.(null)),[i]);let O=()=>{if(!j)B(null)},E=async()=>{if(p||!D||g!==o)return;let Y=D;z(!0),w(!0),pe("");let de=await Vr(()=>n.create(o,Y));if(!F())return;if(z(!1),!de.ok){pe(de.error.message);return}H(r(de.data,Y.key)),B(null),w(!1),S(void 0),u([]),R.current=void 0,await ee.current().catch(()=>{})},ie=async()=>{if(p||!M||g!==o)return;let Y=M;Q.current??=crypto.randomUUID();let de=Q.current;z(!0),pe("");let oe=await Vr(()=>n.revoke(o,Y.id,{expectedVersion:Y.version,idempotencyKey:de}));if(!F())return;if(z(!1),!oe.ok){pe(oe.error.message),await ee.current().catch(()=>{});return}q(null),Q.current=null,H(""),await ee.current().catch(()=>{})},ue=e.fields.filter((Y)=>!["linkedRecord","lookup","formula","rollup"].includes(Y.type)),le=p||j;return Ae("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Ae("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[we("h3",{className:"font-medium",children:"Read-only sharing"}),we("button",{type:"button",disabled:p,onClick:()=>{pe(""),ee.current().catch(()=>{})},children:"Refresh share grants"})]}),we("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."}),we("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."}),te&&we("p",{role:"alert",children:te}),Ae("fieldset",{disabled:le,className:"flex min-w-0 flex-col gap-2",children:[we("legend",{children:"Fields to share"}),ue.map((Y)=>Ae("label",{className:"break-all",children:[we("input",{type:"checkbox","aria-label":`Share field ${Y.name}`,checked:v.includes(Y.id),onChange:(de)=>{O(),k((oe)=>de.target.checked?[...oe,Y.id]:oe.filter((Ne)=>Ne!==Y.id))}})," ",Y.name]},Y.id))]}),Ae("fieldset",{disabled:le,className:"flex min-w-0 flex-col gap-2",children:[we("legend",{children:"Records on the current page"}),t.slice(0,100).map((Y)=>Ae("label",{className:"break-all",children:[we("input",{type:"checkbox","aria-label":`Share record ${Y}`,checked:N.includes(Y),onChange:(de)=>{O(),T((oe)=>de.target.checked?[...oe,Y]:oe.filter((Ne)=>Ne!==Y))}})," ",Y]},Y)),t.length===0&&we("p",{children:"Load records in Grid to choose a share scope."})]}),Ae("p",{className:"break-all text-xs",children:["Selected record IDs: ",N.join(", ")||"none"]}),Ae("label",{children:["Link lifetime"," ",Ae("select",{"aria-label":"Share link lifetime",disabled:le,value:C,onChange:(Y)=>{O(),L(Number(Y.target.value))},children:[we("option",{value:60,children:"1 minute"}),we("option",{value:3600,children:"1 hour"}),we("option",{value:86400,children:"24 hours"})]})]}),we("button",{type:"button",className:"self-start",disabled:le||g!==o||!v.length||!N.length||N.length>100||v.some((Y)=>!ue.some((de)=>de.id===Y)),onClick:()=>{pe("");try{B({expectedSchemaVersion:e.schemaVersion,fieldIds:[...v],recordIds:[...N],expiresInSeconds:C,key:Is(),idempotencyKey:crypto.randomUUID()})}catch{pe("A secure share key could not be generated.")}},children:"Review read-only share"}),D&&Ae("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[Ae("p",{className:"break-all",children:["Confirm schema ",D.expectedSchemaVersion,", fields ",D.fieldIds.join(", "),", records ",D.recordIds.join(", ")," for ",D.expiresInSeconds," seconds."]}),D.expectedSchemaVersion!==e.schemaVersion&&we("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),Ae("div",{className:"flex flex-wrap gap-3",children:[we("button",{type:"button",disabled:p,onClick:()=>void E(),children:j?"Retry create read link":"Create read link"}),we("button",{type:"button",disabled:p,onClick:()=>{B(null),w(!1),pe("")},children:"Discard share confirmation"})]}),j&&we("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."})]}),A&&Ae("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",we("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:A,onFocus:(Y)=>Y.target.select()})]}),!P||g!==o?we("p",{role:"status",children:"Loading share grants…"}):Ae(Ii,{children:[P.items.length===0&&we("p",{children:"No share grants yet."}),we("ol",{className:"flex min-w-0 flex-col gap-2",children:P.items.map((Y)=>Ae("li",{className:"min-w-0 rounded border p-2",children:[Ae("p",{className:"break-all",children:["Grant ",Y.id," · version ",Y.version," · schema ",Y.schemaVersion]}),Ae("p",{className:"break-all text-xs",children:["Fields: ",Y.fieldIds.join(", ")," · Records: ",Y.recordIds.join(", ")," · Expires:"," ",Y.expiresAt]}),Y.revokedAt?we("p",{children:"Share revoked"}):Ae(Ii,{children:[we("p",{children:Y.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(Y.expiresAt)<=Date.now()?"Share expired":"Share active"}),we("button",{type:"button",disabled:p,"aria-label":`Revoke share ${Y.id}`,onClick:()=>{q(Y),Q.current=null},children:"Revoke"})]})]},Y.id))}),Ae("div",{className:"flex flex-wrap gap-3",children:[we("button",{type:"button",disabled:p||!b.length,onClick:()=>{S(b.at(-1)),u((Y)=>Y.slice(0,-1))},children:"Newer share grants"}),we("button",{type:"button",disabled:p||P.nextCursor===null,onClick:()=>{u((Y)=>[...Y,c]),S(P.nextCursor??void 0)},children:"Older share grants"})]})]}),M&&Ae("div",{children:[Ae("p",{className:"break-all",children:["Revoke grant ",M.id," at version ",M.version,"? Every existing share session will lose access."]}),Ae("div",{className:"flex flex-wrap gap-3",children:[we("button",{type:"button",disabled:p,onClick:()=>void ie(),children:"Confirm revoke share"}),we("button",{type:"button",disabled:p,onClick:()=>{q(null),Q.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as Ai,useRef as tn,useState as Ue}from"react";import{jsx as fe,jsxs as Ee}from"react/jsx-runtime";var Ei=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],Es=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function Ds({descriptor:e,recordIds:t,client:n,webhookRequest:r}){let i=e.id,o=tn({id:i,client:n});o.current={id:i,client:n};let a=tn(!0),d=tn(0),[s,g]=Ue([]),[m,P]=Ue(""),f=tn(m);f.current=m;let[c,S]=Ue(null),[R,b]=Ue(),u=tn(R);u.current=R;let[v,k]=Ue(""),[N,T]=Ue("record"),[C,L]=Ue(60),[D,B]=Ue([]),[j,w]=Ue([]),[A,H]=Ue({}),[M,q]=Ue(null),[Q,p]=Ue(!1),[z,te]=Ue(!1),[pe,F]=Ue(""),[X,ee]=Ue(""),O=()=>a.current&&o.current.id===i&&o.current.client===n,E=async(V)=>{try{return await V()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},ie=async()=>{let V=++d.current,h=await E(()=>n.list(i));if(!O()||V!==d.current)return;if(!h.ok){F(h.error.message);return}g(h.data);let G=h.data.find((ke)=>ke.id===f.current)?.id??h.data[0]?.id??"";if(f.current=G,P(G),!G){S(null);return}let Z=await E(()=>n.runs(i,G,{limit:20,...u.current?{before:u.current}:{}}));if(!O()||V!==d.current||f.current!==G)return;if(Z.ok)S(Z.data);else F(Z.error.message)},ue=tn(ie);ue.current=ie,Ai(()=>{if(o.current.id!==i||o.current.client!==n)return;a.current=!0,ue.current();let V=setInterval(()=>void ue.current(),5000);return()=>{a.current=!1,++d.current,clearInterval(V)}},[i,n]),Ai(()=>{if(f.current!==m||u.current!==R)return;ue.current()},[m,R]);let le=()=>{if(F(""),!v.trim()||!D.length||N!=="record"&&!j.length){F("Choose a name, writable fields, and target records for time or webhook triggers.");return}let V=Object.fromEntries(D.map((G)=>[G,A[G]??null])),h={expectedSchemaVersion:e.schemaVersion,name:v.trim(),trigger:N==="time"?{kind:N,intervalSeconds:C}:{kind:N},targetRecordIds:j,values:V,idempotencyKey:crypto.randomUUID(),...N==="webhook"?{webhookKey:Es()}:{}};q({kind:"create",input:h}),p(!1)},Y=(V)=>{q(V),p(!1),F("")},de=async()=>{if(!M||z)return;let V=M,h=Q;p(!0),te(!0),F("");let G=await E(()=>V.kind==="create"?n.create(i,V.input):V.kind==="toggle"?n.toggle(i,V.a.id,V.input):V.kind==="run"?n.runNow(i,V.a.id,V.input):n.retry(i,V.a.id,V.run.id,V.input));if(!O())return;if(te(!1),!G.ok){if(!h&&G.error.status>=400&&G.error.status<500)p(!1);F(`${G.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(V.kind==="create"){let Z=G.data;if(f.current=Z.id,P(Z.id),V.input.webhookKey&&r)ee(JSON.stringify(r(Z,V.input.webhookKey),null,2));k(""),B([]),w([]),H({})}q(null),p(!1),u.current=void 0,b(void 0),await ue.current()},oe=s.find((V)=>V.id===m),Ne=!!M||z;return Ee("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[fe("p",{children:"Update chosen fields through record changes, a timed interval or a private webhook. Runs keep their original schema and record versions. Automatic changes do not trigger another automation."}),fe("button",{type:"button",onClick:()=>void ue.current(),children:"Refresh automation"}),pe&&fe("p",{role:"alert",children:pe}),fe("form",{onSubmit:(V)=>{V.preventDefault(),le()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:Ee("fieldset",{disabled:Ne,style:{minWidth:0},children:[fe("legend",{children:"New automation"}),Ee("label",{children:["Name"," ",fe("input",{"aria-label":"Automation name",value:v,maxLength:200,onChange:(V)=>k(V.target.value)})]}),Ee("label",{children:["Trigger"," ",Ee("select",{"aria-label":"Automation trigger",value:N,onChange:(V)=>T(V.target.value),children:[fe("option",{value:"record",children:"Record changes"}),fe("option",{value:"time",children:"Timed interval"}),fe("option",{value:"webhook",children:"Private webhook"})]})]}),N==="time"&&Ee("label",{children:["Interval in seconds"," ",fe("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:C,onChange:(V)=>L(Number(V.target.value))})]}),Ee("fieldset",{children:[fe("legend",{children:"Fields to update"}),e.fields.filter((V)=>Ei.includes(V.type)).map((V)=>Ee("label",{style:{display:"block"},children:[fe("input",{type:"checkbox",checked:D.includes(V.id),onChange:(h)=>{B(h.target.checked?[...D,V.id]:D.filter((G)=>G!==V.id))}}),V.name]},V.id))]}),fe(wn,{fields:e.fields.filter((V)=>D.includes(V.id)&&Ei.includes(V.type)),values:A,onChange:H}),Ee("fieldset",{children:[fe("legend",{children:"Target records from this page"}),N==="record"&&fe("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&fe("p",{children:"Open a grid page to choose fixed records."}),t.map((V)=>Ee("label",{style:{display:"block",overflowWrap:"anywhere"},children:[fe("input",{type:"checkbox","aria-label":`Automation target ${V}`,checked:j.includes(V),onChange:(h)=>w(h.target.checked?[...j,V]:j.filter((G)=>G!==V))}),V]},V))]}),fe("button",{type:"submit",children:"Review automation"})]})}),M&&Ee("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[fe("p",{children:M.kind==="create"?`Create ${M.input.name} using schema ${M.input.expectedSchemaVersion}; ${M.input.targetRecordIds.length||"event"} targets.`:M.kind==="toggle"?`${M.input.enabled?"Enable":"Disable"} ${M.a.name}. Disabling fences queued and running work.`:M.kind==="run"?`Run ${M.a.name} for ${M.input.recordIds.length} explicitly selected records.`:`Retry ${M.a.name}, run ${M.run.sequence}, using its original record versions.`}),M.kind==="create"&&fe("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(M.input.values,null,2)}),fe("button",{type:"button",disabled:z,onClick:()=>void de(),children:z?"Confirming…":Q?"Retry automation confirmation":"Confirm automation"}),fe("button",{type:"button",disabled:Q||z,onClick:()=>q(null),children:"Cancel automation review"}),Q&&fe("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),X&&Ee("div",{children:[fe("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),fe("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:X}),fe("button",{type:"button",onClick:()=>ee(""),children:"Hide webhook key"})]}),s.length>0&&Ee("label",{children:["Automation"," ",fe("select",{"aria-label":"Selected automation",disabled:Ne,value:m,onChange:(V)=>{f.current=V.target.value,u.current=void 0,b(void 0),P(V.target.value),S(null)},children:s.map((V)=>fe("option",{value:V.id,children:V.name},V.id))})]}),oe&&Ee("div",{children:[Ee("p",{children:[oe.enabled?"Enabled":"Disabled"," · ",oe.trigger.kind," · schema ",oe.schemaVersion," · configuration ",oe.version]}),fe("button",{type:"button",disabled:Ne,onClick:()=>Y({kind:"toggle",a:oe,input:{expectedVersion:oe.version,enabled:!oe.enabled,idempotencyKey:crypto.randomUUID()}}),children:oe.enabled?"Review disable automation":"Review enable automation"}),fe("button",{type:"button",disabled:Ne||!oe.enabled||!(oe.targetRecordIds.length||t.length),onClick:()=>Y({kind:"run",a:oe,input:{recordIds:oe.targetRecordIds.length?oe.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),c&&Ee("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!c.items.length&&fe("p",{children:"No runs yet."}),c.items.map((V)=>Ee("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[Ee("p",{children:["Run ",V.sequence," · ",V.triggerKind," · ",V.status," · step ",V.step]}),Ee("p",{children:["Attempts: evaluate ",V.stepAttempts.evaluate,", apply ",V.stepAttempts.apply," · original versions: ",V.expectedRows.map((h)=>`${h.id}: ${h.version}`).join(", ")]}),V.errorCode&&fe("p",{role:"status",children:V.errorCode}),V.leaseUntil&&Ee("p",{children:["Lease expires ",V.leaseUntil]}),oe&&V.status==="failed"&&Ee("button",{type:"button",disabled:Ne||!oe.enabled,onClick:()=>Y({kind:"retry",a:oe,run:V,input:{expectedVersion:V.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",V.sequence]})]},V.id)),fe("button",{type:"button",disabled:Ne||R===void 0,onClick:()=>{u.current=void 0,b(void 0)},children:"Newest runs"}),fe("button",{type:"button",disabled:Ne||c.nextCursor===null,onClick:()=>{u.current=c.nextCursor??void 0,b(u.current)},children:"Older runs"})]})]})}import{useEffect as Ts,useId as Fs,useRef as Di,useState as _e}from"react";import{jsx as ve,jsxs as De}from"react/jsx-runtime";var Ti=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function Ns(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((o)=>!e.fields.some((a)=>a.id===o&&Ti.includes(a.type))))throw Error("Choose up to ten basic source and target fields.");let r=n.recordIds.map((i)=>{let o=t.find((a)=>a.id===i);if(!o)throw Error("A selected record is no longer on this page.");return{id:i,expectedVersion:o.version}});return structuredClone({expectedSchemaVersion:e.schemaVersion,resourceId:n.resourceId,model:n.model.trim(),instruction:n.instruction,records:r,sourceFieldIds:n.sourceFieldIds,targetFieldIds:n.targetFieldIds,idempotencyKey:crypto.randomUUID()})}function Ms({descriptor:e,records:t,client:n,onApplied:r}){let i=Fs(),o=e.id,a=Di({id:o,client:n}),d=Di(!0);a.current={id:o,client:n};let[s,g]=_e([]),[m,P]=_e(!1),[f,c]=_e(""),[S,R]=_e(""),[b,u]=_e(""),[v,k]=_e([]),[N,T]=_e([]),[C,L]=_e([]),[D,B]=_e(null),[j,w]=_e(null),[A,H]=_e(null),[M,q]=_e(!1),[Q,p]=_e(!1),[z,te]=_e(""),[pe,F]=_e(""),[X,ee]=_e(""),O=()=>d.current&&a.current.id===o&&a.current.client===n,E=async(h)=>{try{return await h()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};Ts(()=>{d.current=!0,B(null),w(null),H(null),q(!1),te(""),F(""),ee(""),k([]),T([]),L([]),u("");let h=!0;return P(!1),p(!1),g([]),c(""),R(""),n.providers(o).then((G)=>{if(!h||a.current.id!==o||a.current.client!==n)return;if(P(!0),G.ok)g(G.data),c(G.data[0]?.resourceId??""),R(G.data[0]?.allowedModels[0]??"");else te(G.error.message)}).catch(()=>{if(h)P(!0),te("AI configuration is unavailable.")}),()=>{h=!1,d.current=!1}},[o,n]);let ie=()=>{try{let h=Ns(e,t,{resourceId:f,model:S,instruction:b,recordIds:v,sourceFieldIds:N,targetFieldIds:C});w(structuredClone(h.records.map((G)=>({id:G.id,version:G.expectedVersion,values:Object.fromEntries(h.sourceFieldIds.map((Z)=>[Z,t.find((ke)=>ke.id===G.id)?.values[Z]??null]))})))),B(h),q(!1),te(""),F("")}catch(h){te(h instanceof Error?h.message:"Invalid selection.")}},ue=async()=>{if(!D||Q)return;let h=D,G=M;p(!0),q(!0),te("");let Z=await E(()=>n.propose(o,h));if(!O())return;if(p(!1),!Z.ok){if(!G&&Z.error.status>=400&&Z.error.status<500)q(!1);te(`${Z.error.message} Retry keeps the original selection and versions.`);return}H(Z.data),ee(Z.data.id),q(!1)},le=async()=>{if(!A||Q)return;let h=A,G=M;p(!0),q(!0),te("");let Z=await E(()=>n.confirm(o,h));if(!O())return;if(p(!1),!Z.ok){if(!G&&Z.error.status>=400&&Z.error.status<500)q(!1);te(`${Z.error.message} The reviewed proposal keeps its original versions.`);return}F(`${Z.data.items.length} records filled${Z.data.replayed?"; original receipt recovered":""}.`),H(null),B(null),w(null),q(!1);try{await r?.()}catch{if(O())te("The fill committed. Refresh the Collection to see its records.")}},Y=async()=>{if(Q||D||A)return;p(!0),te("");let h=await E(()=>n.get(o,X));if(!O())return;if(p(!1),h.ok)H(h.data),q(!1),F("");else te(h.error.message)},de=(h,G,Z)=>Z(h.includes(G)?h.filter((ke)=>ke!==G):[...h,G]),oe=Q||!!D||!!A,Ne=e.fields.filter((h)=>Ti.includes(h.type)),V=s.find((h)=>h.resourceId===f);return De("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[ve("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."}),z&&ve("p",{role:"alert",children:z}),pe&&ve("p",{role:"status",children:pe}),m&&s.length===0&&ve("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),ve("form",{onSubmit:(h)=>{h.preventDefault(),ie()},children:De("fieldset",{disabled:oe,style:{minWidth:0},children:[ve("legend",{children:"AI fill request"}),De("label",{children:["AI resource"," ",De("select",{"aria-label":"AI resource",value:f,onChange:(h)=>{c(h.target.value),R(s.find((G)=>G.resourceId===h.target.value)?.allowedModels[0]??"")},children:[ve("option",{value:"",children:"Choose resource"}),s.map((h)=>ve("option",{value:h.resourceId,children:h.name},h.resourceId))]})]}),De("label",{htmlFor:i,children:["Model"," ",V?.allowedModels.length?ve("select",{id:i,"aria-label":"AI model",value:S,onChange:(h)=>R(h.target.value),children:V.allowedModels.map((h)=>ve("option",{value:h,children:h},h))}):ve("input",{id:i,"aria-label":"AI model",maxLength:200,value:S,onChange:(h)=>R(h.target.value)})]}),De("label",{children:["Instructions"," ",ve("textarea",{"aria-label":"AI instructions",maxLength:2000,value:b,onChange:(h)=>u(h.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),De("fieldset",{children:[ve("legend",{children:"Source fields to send"}),Ne.map((h)=>De("label",{style:{display:"block"},children:[ve("input",{type:"checkbox","aria-label":`Send ${h.name}`,checked:N.includes(h.id),onChange:()=>de(N,h.id,T)}),h.name]},h.id))]}),De("fieldset",{children:[ve("legend",{children:"Fields to fill"}),Ne.map((h)=>De("label",{style:{display:"block"},children:[ve("input",{type:"checkbox","aria-label":`Fill ${h.name}`,checked:C.includes(h.id),onChange:()=>de(C,h.id,L)}),h.name]},h.id))]}),De("fieldset",{children:[ve("legend",{children:"Target records from this page"}),t.map((h)=>De("label",{style:{display:"block",overflowWrap:"anywhere"},children:[ve("input",{type:"checkbox","aria-label":`AI record ${h.id}`,checked:v.includes(h.id),onChange:()=>de(v,h.id,k)}),h.id," · version ",h.version]},h.id))]}),ve("button",{type:"submit",disabled:!f,children:"Review AI request"})]})}),D&&!A&&De("section",{"aria-label":"AI data disclosure",children:[De("p",{children:["Selected service: ",D.resourceId," · model ",D.model," · schema"," ",D.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),ve("p",{children:D.instruction}),ve("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(j,null,2)}),ve("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),ve("button",{type:"button",disabled:Q,onClick:()=>void ue(),children:M?"Retry original AI request":"Generate proposal"}),ve("button",{type:"button",disabled:Q||M,onClick:()=>{B(null),w(null),te("")},children:"Cancel AI request"})]}),A&&De("section",{"aria-label":"AI fill confirmation",children:[De("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",A.id," · ",A.provider," · schema ",A.schemaVersion]}),A.schemaVersion!==e.schemaVersion&&ve("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),A.rows.map((h)=>De("div",{style:{overflowWrap:"anywhere"},children:[De("p",{children:[h.id," · original version ",h.expectedVersion]}),Object.keys(h.values).map((G)=>De("div",{children:[ve("strong",{children:e.fields.find((Z)=>Z.id===G)?.name??G}),De("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(h.before[G]),`
10
+ `,"Suggested: ",JSON.stringify(h.values[G])]})]},G))]},h.id)),ve("button",{type:"button",disabled:Q,onClick:()=>void le(),children:M?"Retry original AI fill":"Confirm fill"}),ve("button",{type:"button",disabled:Q||M,onClick:()=>{H(null),B(null),w(null),te("")},children:"Dismiss proposal"})]}),De("label",{children:["Recover a saved proposal"," ",ve("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:X,onChange:(h)=>ee(h.target.value),disabled:oe,style:{width:"100%",boxSizing:"border-box"}})]}),ve("button",{type:"button",disabled:oe||!/^[a-f0-9]{64}$/.test(X),onClick:()=>void Y(),children:"Load saved proposal"})]})}import{jsx as J,jsxs as ye}from"react/jsx-runtime";var Vs=[{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 Jp({fields:e,onChange:t,lockedIds:n=[],collections:r=[]}){let i=(o,a)=>t(e.map((d,s)=>s===o?{...d,...a}:d));return ye("div",{className:"flex flex-col gap-3",children:[e.map((o,a)=>{let d=n.includes(o.id);return ye("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:[J("input",{"aria-label":`Field ${a+1} name`,placeholder:"Display name",value:o.name,onChange:(s)=>i(a,{name:s.target.value})}),J("input",{"aria-label":`Field ${a+1} ID`,placeholder:"field_id",value:o.id,disabled:d,onChange:(s)=>i(a,{id:s.target.value})}),J("select",{"aria-label":`Field ${a+1} type`,className:"rounded-md border bg-background px-2 text-sm",value:o.type,disabled:d,onChange:(s)=>{let g=s.target.value,m={id:o.id,name:o.name,type:g,required:Me({type:g})?!1:o.required??!1};if(g==="formula")m.formula={expression:""};if(g==="rollup")m.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(g==="singleSelect"||g==="multipleSelect")m.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((P,f)=>f===a?m:P))},children:Vs.map((s)=>J("option",{value:s.value,children:s.name},s.value))}),ye("div",{className:"flex items-center gap-2",children:[ye("label",{className:"flex items-center gap-1 text-xs",children:[J("input",{type:"checkbox",checked:o.required??!1,disabled:d||n.length>0||Me(o),onChange:(s)=>i(a,{required:s.target.checked})}),"Required"]}),!d&&J("button",{type:"button",onClick:()=>t(e.filter((s,g)=>g!==a)),children:"Remove"})]}),(o.type==="singleSelect"||o.type==="multipleSelect")&&J("input",{className:"md:col-span-4","aria-label":`Field ${a+1} options`,placeholder:"Open, Done",value:o.options?.map((s)=>s.name).join(", ")??"",disabled:d,onChange:(s)=>i(a,{options:s.target.value.split(",").map((g,m)=>({id:g.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${m}`,name:g.trim()})).filter((g)=>g.name)})}),o.type==="linkedRecord"&&ye("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ye("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",ye("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} linked collection`,value:o.link?.collectionId??"",disabled:d,onChange:(s)=>{let g=r.find((m)=>m.id===s.target.value);i(a,{link:{collectionId:s.target.value,displayFieldId:g?.fields.find((m)=>m.type==="singleLineText"||m.type==="longText")?.id??""}})},children:[J("option",{value:"",children:"Choose collection…"}),r.map((s)=>J("option",{value:s.id,children:s.name},s.id))]})]}),ye("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",ye("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} record label`,value:o.link?.displayFieldId??"",disabled:d||!o.link?.collectionId,onChange:(s)=>i(a,{link:{collectionId:o.link?.collectionId??"",displayFieldId:s.target.value}}),children:[J("option",{value:"",children:"Choose text field…"}),r.find((s)=>s.id===o.link?.collectionId)?.fields.filter((s)=>s.type==="singleLineText"||s.type==="longText").map((s)=>J("option",{value:s.id,children:s.name},s.id))]})]})]}),o.type==="lookup"&&ye("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ye("label",{children:["Through linked field"," ",ye("select",{"aria-label":`Field ${a+1} lookup link`,value:o.lookup?.linkFieldId??"",disabled:d,onChange:(s)=>i(a,{lookup:{linkFieldId:s.target.value,targetFieldId:""}}),children:[J("option",{value:"",children:"Choose linked field…"}),e.filter((s)=>s.type==="linkedRecord"&&s.link).map((s)=>J("option",{value:s.id,children:s.name},s.id))]})]}),ye("label",{children:["Read target field"," ",ye("select",{"aria-label":`Field ${a+1} lookup target`,value:o.lookup?.targetFieldId??"",disabled:d||!o.lookup?.linkFieldId,onChange:(s)=>i(a,{lookup:{linkFieldId:o.lookup?.linkFieldId??"",targetFieldId:s.target.value}}),children:[J("option",{value:"",children:"Choose target field…"}),r.find((s)=>s.id===e.find((g)=>g.id===o.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((s)=>!Me(s)&&s.type!=="linkedRecord").map((s)=>J("option",{value:s.id,children:s.name},s.id))]})]}),J("small",{children:"Computed from linked records. Values cannot be edited."})]}),o.type==="formula"&&ye("div",{className:"flex flex-col gap-1 md:col-span-4",children:[ye("label",{children:["Formula",J("textarea",{"aria-label":`Field ${a+1} formula`,maxLength:2048,className:"min-h-16 w-full rounded-md border bg-background p-2",placeholder:"{quantity} * {price}",value:o.formula?.expression??"",onChange:(s)=>i(a,{formula:{expression:s.target.value}})})]}),J("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."}),ye("small",{children:["References:"," ",e.filter((s)=>s.id!==o.id&&(s.type==="singleLineText"||s.type==="longText"||s.type==="date"||s.type==="number"||s.type==="formula"||s.type==="rollup")).map((s)=>`{${s.id}}`).join(", ")||"None yet"]})]}),o.type==="rollup"&&ye("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ye("label",{children:["Through linked field"," ",ye("select",{"aria-label":`Field ${a+1} rollup link`,value:o.rollup?.linkFieldId??"",onChange:(s)=>i(a,{rollup:{linkFieldId:s.target.value,targetFieldId:"",function:o.rollup?.function??"sum"}}),children:[J("option",{value:"",children:"Choose linked field…"}),e.filter((s)=>s.type==="linkedRecord"&&s.link).map((s)=>J("option",{value:s.id,children:s.name},s.id))]})]}),ye("label",{children:["Aggregate"," ",ye("select",{"aria-label":`Field ${a+1} rollup function`,value:o.rollup?.function??"sum",onChange:(s)=>{let g=s.target.value,m=r.find((P)=>P.id===e.find((f)=>f.id===o.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((P)=>P.id===o.rollup?.targetFieldId);i(a,{rollup:{linkFieldId:o.rollup?.linkFieldId??"",targetFieldId:g==="count"||m?.type==="number"?o.rollup?.targetFieldId??"":"",function:g}})},children:[J("option",{value:"sum",children:"Sum"}),J("option",{value:"average",children:"Average"}),J("option",{value:"min",children:"Minimum"}),J("option",{value:"max",children:"Maximum"}),J("option",{value:"count",children:"Count values"})]})]}),ye("label",{children:["Target field"," ",ye("select",{"aria-label":`Field ${a+1} rollup target`,value:o.rollup?.targetFieldId??"",disabled:!o.rollup?.linkFieldId,onChange:(s)=>i(a,{rollup:{linkFieldId:o.rollup?.linkFieldId??"",targetFieldId:s.target.value,function:o.rollup?.function??"sum"}}),children:[J("option",{value:"",children:"Choose target field…"}),r.find((s)=>s.id===e.find((g)=>g.id===o.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((s)=>!Me(s)&&s.type!=="linkedRecord"&&(o.rollup?.function==="count"||s.type==="number")).map((s)=>J("option",{value:s.id,children:s.name},s.id))]})]}),J("small",{className:"w-full",children:"Null targets are skipped. Count counts values; empty sum/count are zero. Other empty aggregates have no result."})]})]},a)}),J("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 _s(e,t,n){if(Me(e)||e.type==="blob")return"";if(e.type==="linkedRecord"||e.type==="relation"){let r=t==null||t===""||Array.isArray(t)&&t.length===0;if(e.required&&r)return n==="zh-CN"?`请填写${e.name}。`:`${e.name} is required.`;return""}return Qt(e,Se(t),n)}function Br(e,t,n,r){let i=Object.create(null);for(let o of e){if(o.type==="lookup"||o.type==="formula"||o.type==="rollup"||o.type==="blob"||o.generation==="autoIncrement")continue;if(!Object.hasOwn(t,o.id)){if(o.required)throw Error(n("{name} is required.",{name:o.name}));continue}let a=t[o.id];if(o.type==="linkedRecord"){if(!Array.isArray(a)||a.some((d)=>typeof d!=="string")||a.length>100||new Set(a).size!==a.length)throw Error(n("{name} needs unique linked records.",{name:o.name}));if(o.required&&!a.length)throw Error(n("{name} is required.",{name:o.name}));i[o.id]=a;continue}if(o.type==="relation"){if(a==null||a===""){if(o.required)throw Error(n("{name} is required.",{name:o.name}));i[o.id]=null;continue}if(typeof a!=="string")throw Error(n("{name} needs a server-provided option.",{name:o.name}));i[o.id]=a;continue}if(o.type==="hyperlink"&&a!==null&&typeof a==="object"){if(!Kt(a))throw Error(n("{name} needs a link.",{name:o.name}));i[o.id]=a;continue}if(o.required&&typeof a==="string"&&!a.trim())throw Error(n("{name} is required.",{name:o.name}));i[o.id]=nt(Array.isArray(a)?a.join(","):String(a??""),o,r)}return i}function wn({fields:e,values:t,onChange:n,relationClient:r,getRelationOptions:i,linkedRecords:o,computedErrors:a,locale:d,ui:s,submitted:g=!1}){let m=me(d),P=Os(),f=Ls(()=>i??(r?vi(r,[]):void 0),[i,r]);return J("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((c)=>{let S=c.description?.trim()??"",R=S?`${P}-${c.id}-hint`:void 0,b=_s(c,t[c.id],d??"en"),v=Boolean(c.required&&Se(t[c.id])===""&&b)&&!g?"":b,k=v?`${P}-${c.id}-error`:void 0,N=[R,k].filter(Boolean).join(" "),T={...N?{"aria-describedby":N}:{},...v?{"aria-invalid":!0}:{}};return ye("div",{className:"flex flex-col gap-1 text-sm",children:[ye("label",{htmlFor:`${P}-${c.id}`,children:[c.name,c.required?" *":""]}),S?J("p",{id:R,className:"m-0 text-xs opacity-70",children:S}):null,Me(c)?J("output",{id:`${P}-${c.id}`,"aria-label":m("{name} (read only)",{name:c.name}),...T,children:c.type==="lookup"?Pt(t[c.id]):Wt(t[c.id],a?.[c.id],d)}):c.type==="relation"?J(xn,{field:c,id:`${P}-${c.id}`,label:`${c.name}${c.required?" *":""}`,value:typeof t[c.id]==="string"?String(t[c.id]):"",labels:o?.[c.id],getOptions:f,locale:d,onChange:(C)=>n({...t,[c.id]:C||null}),...T}):c.type==="linkedRecord"?J(_n,{...d?{locale:d}:{},field:c,value:t[c.id],labels:o?.[c.id],client:r,onChange:(C)=>n({...t,[c.id]:C}),...T}):c.type==="checkbox"?J("input",{id:`${P}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,type:"checkbox",checked:t[c.id]===!0,onChange:(C)=>n({...t,[c.id]:C.target.checked}),...T}):c.type==="singleSelect"&&s?.Select?J(bi,{ui:s,label:`${c.name}${c.required?" *":""}`,...T,value:String(t[c.id]??""),options:[{value:"",label:m("Choose…")},...(c.options??[]).map((C)=>({value:C.id,label:C.name}))],onChange:(C)=>n({...t,[c.id]:C||null})}):c.type==="multipleSelect"&&s?.MultiSelect?J(s.MultiSelect,{"aria-label":`${c.name}${c.required?" *":""}`,...T,options:(c.options??[]).map((C)=>({value:C.id,label:C.name,slot:gn(c.options,C.id)})),values:Array.isArray(t[c.id])?t[c.id]:[],placeholder:m("Choose…"),onChange:(C)=>n({...t,[c.id]:C})}):c.type==="singleSelect"||c.type==="multipleSelect"?ye("select",{id:`${P}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...T,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:(C)=>n({...t,[c.id]:c.type==="multipleSelect"?Array.from(C.target.selectedOptions,(L)=>L.value):C.target.value||null}),children:[c.type==="singleSelect"&&J("option",{value:"",children:m("Choose…")}),c.options?.map((C)=>J("option",{value:C.id,children:C.name},C.id))]}):c.type==="date"&&s?.DatePicker?(()=>{let C={kind:hr(c),timeZone:dt(c)?.timeZone},L=String(t[c.id]??"");return J(s.DatePicker,{id:`${P}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...T,value:Sr(L,C),withTime:C.kind==="auto"?Rt(L):C.kind==="datetime",fixedKind:C.kind!=="auto",clearable:!c.required,onChange:(D)=>n({...t,[c.id]:D?Ir(D,L,C):null})})})():c.type==="hyperlink"?J(Cn,{field:c,id:`${P}-${c.id}`,ariaLabel:`${c.name}${c.required?" *":""}`,describedBy:T["aria-describedby"],invalid:Boolean(v),locale:d,inputClassName:"min-h-9 min-w-0 rounded-md border bg-background p-2",text:typeof t[c.id]==="string"?String(t[c.id]):hn(Kt(t[c.id])?t[c.id]:null),onChange:(C)=>{let L=C.trim().startsWith("{")?Ot(C):null;n({...t,[c.id]:L??(C||null)})}}):c.type==="longText"?J("textarea",{id:`${P}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...T,className:"rounded-md border bg-background p-2",value:String(t[c.id]??""),onChange:(C)=>n({...t,[c.id]:C.target.value||null})}):J("input",{id:`${P}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...T,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:(C)=>n({...t,[c.id]:C.target.value===""?null:c.type==="number"?Number(C.target.value):c.type==="date"&&t[c.id]?jo(t[c.id],C.target.value):C.target.value})}),v?J("span",{id:k,className:"text-xs text-red-600",children:v}):null]},c.id)})})}function Bs(e,t,n){if(t==="isEmpty")return;let r=Me(e)?e.resultType:e.type;if(r==="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(r==="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(r==="checkbox"){if(!["true","false"].includes(n))throw Error("Filter needs true or false.");return n==="true"}if(Me(e)&&!Mt(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 Zp({fields:e,view:t,onChange:n,onError:r}){let i=e.filter(Mt),[o,a]=_r(i[0]?.id??""),d=i.some((u)=>u.id===o)?o:i[0]?.id??"",[s,g]=_r("contains"),m=d?(()=>{let u=e.find((v)=>v.id===d);return u&&Me(u)?u.resultType:u?.type})():void 0,P=m==="number"?["is","isNot","isEmpty"]:m==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],f=P.includes(s)?s:m==="number"||m==="date"?"is":"contains",[c,S]=_r(""),b=[...t.columnOrder.flatMap((u)=>{let v=e.find((k)=>k.id===u);return v?[v]:[]}),...e.filter((u)=>!t.columnOrder.includes(u.id))];return ye("div",{className:"flex flex-wrap items-end gap-3",children:[ye("label",{className:"flex min-w-52 flex-col gap-1 text-sm",children:["Search",J("input",{type:"search",className:"min-h-9 min-w-0 rounded-md border bg-background p-2",value:t.search??"",onChange:(u)=>n({...t,search:u.target.value})})]}),ye("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(u)=>{u.preventDefault();let v=e.find((N)=>N.id===d);if(!v)return;let k;try{k=Bs(v,f,c)}catch(N){r(N instanceof Error?N.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:d,operator:f,...f==="isEmpty"?{}:{value:k}}]}})},children:[ye("label",{className:"flex flex-col gap-1 text-sm",children:["Filter field",J("select",{className:"h-9 rounded-md border bg-background px-2",value:d,onChange:(u)=>a(u.target.value),children:i.map((u)=>J("option",{value:u.id,children:u.name},u.id))})]}),J("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:f,onChange:(u)=>g(u.target.value),children:P.map((u)=>J("option",{value:u,children:u==="isNot"?"is not":u==="isEmpty"?"is empty":u==="onOrAfter"?"on or after":u},u))}),f!=="isEmpty"&&J("input",{type:m==="number"?"number":m==="date"?"date":"text",step:m==="number"?"any":void 0,className:"min-h-9 max-w-40 rounded-md border bg-background p-2","aria-label":"Filter value",value:c,onChange:(u)=>S(u.target.value)}),J("button",{type:"submit",disabled:!d,children:"Apply filter"}),J("button",{type:"button",onClick:()=>{let u={...t};delete u.filter,n(u)},children:"Clear filter"})]}),ye("details",{className:"relative",children:[J("summary",{className:"cursor-pointer rounded-md border px-3 py-2 text-sm",children:"Columns"}),J("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:b.map((u,v)=>ye("div",{className:"flex items-center gap-2 text-sm",children:[ye("label",{className:"flex flex-1 items-center gap-2",children:[J("input",{type:"checkbox",checked:!t.hiddenColumns.includes(u.id),disabled:t.type==="form"&&u.required===!0,onChange:(k)=>n({...t,hiddenColumns:k.target.checked?t.hiddenColumns.filter((N)=>N!==u.id):[...t.hiddenColumns,u.id]})}),u.name]}),J("button",{type:"button","aria-label":`Move ${u.name} left`,disabled:v===0,onClick:()=>{let k=b.map((T)=>T.id),N=k[v-1];if(N!==void 0)[k[v-1],k[v]]=[u.id,N];n({...t,columnOrder:k})},children:"←"}),J("button",{type:"button","aria-label":`Move ${u.name} right`,disabled:v===b.length-1,onClick:()=>{let k=b.map((T)=>T.id),N=k[v+1];if(N!==void 0)[k[v],k[v+1]]=[N,u.id];n({...t,columnOrder:k})},children:"→"})]},u.id))})]})]})}import{useEffect as Us,useMemo as Fi,useState as Ni}from"react";import{jsx as Ur}from"react/jsx-runtime";function qs(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 zs(e,t,n){let r=n.unassigned??"Unassigned";if(t===null||t===void 0)return r;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):r}function Mi(e,t,n,r={},i={}){return n.map((o)=>{let a=t.groupBy.map((s)=>{let g=e.fields.find((m)=>m.id===s);return`${g?.name??s} ${zs(g,o.groups[s],i)}`}),d=t.aggregates.map((s)=>{let g=o.values[s.as];return`${r[s.as]??s.as}: ${typeof g==="number"||typeof g==="string"?String(g):i.none??"none"}`});return[...a,...d].join(" · ")})}function ug({descriptor:e,query:t,rows:n}){return Ur("ul",{"data-uibot":"collection-aggregate",children:Mi(e,t,n).map((r)=>Ur("li",{children:r},r))})}function Zn({collectionId:e,descriptor:t,view:n,groupBy:r,aggregates:i,client:o,locale:a,labels:d,reloadKey:s=0}){let g=Fi(()=>Tn(n,{aggregates:i,...r?{groupBy:r}:{}}),[n,r,i]),m=Fi(()=>me(a),[a]),[P,f]=Ni(m("Loading summary…")),[c,S]=Ni(!1);return Us(()=>{let R=Fn(t,g);if(R){f(m(qs(R))),S(!0);return}let b=!0;return f(m("Loading summary…")),S(!1),o.aggregate(e,g).then((u)=>{if(!b)return;if(!u.ok){f(u.error.message),S(!0);return}let v=Mi(t,g,u.data,d??{},{unassigned:m("Unassigned"),checked:m("Checked"),unchecked:m("Unchecked"),none:m("none")});f(v.length?v.join(" · "):m("No summary rows.")),S(!1)}).catch(()=>{if(!b)return;f(m("The collection service is unavailable.")),S(!0)}),()=>{b=!1}},[o,e,t,g,d,m,s]),Ur("p",{role:c?"alert":"status","data-uibot":"collection-aggregate",children:P})}var Li=["grid","kanban","gallery","calendar","form"],js=["grid","form"],qr={search:!0,filter:!0,columns:!0,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!0,tableList:!0,viewManagement:!0,export:!0},$s={search:!0,filter:!1,columns:!1,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!1,tableList:!1,viewManagement:!1,export:!1},Hs={search:!0,filter:!0,columns:!0,rowCreate:!1,rowUpdate:!1,rowDelete:!1,schemaEditor:!1,tableList:!0,viewManagement:!1,export:!0},Oi={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:Li},zr={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:Li},Vi={basic:{...Oi,...qr},full:{...zr,...qr},simple:{...Oi,...$s,viewTypes:js},workbench:{...zr,...qr},readonly:{...zr,...Hs,recordContextMenu:!1,optimisticEdit:!1}};function Dt(e){let{preset:t="basic",...n}=e??{},r={...Vi[t],...Ks(n)};return r.groupBy?r:{...r,groupCollapse:!1}}function Ks(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}import{jsx as se,jsxs as $e,Fragment as Kr}from"react/jsx-runtime";function Rg(e){if(!e.aggregate)return null;return se(Zn,{collectionId:e.descriptor.id,descriptor:e.descriptor,view:e.view,...e.aggregate.groupBy?{groupBy:e.aggregate.groupBy}:{},aggregates:e.aggregate.aggregates,client:e.aggregate.client,...e.aggregate.labels?{labels:e.aggregate.labels}:{},...e.locale?{locale:e.locale}:{},...e.reloadKey!==void 0?{reloadKey:e.reloadKey}:{}})}var je={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},er={padding:12,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)"},Qn={items:[],total:0,nextCursor:null,limit:50};function Sg(e,t,n=!0){let r=JSON.stringify([e.descriptor.id,e.descriptor.schemaVersion,t]),[i,o]=Ye({key:r,history:[]}),a=i.key===r?i.cursor:void 0,d=i.key===r?i.history:[],s=JSON.stringify([r,a]),[g,m]=Ye(0),[P,f]=Ye({key:s,page:Qn,loading:n,error:null});Xn(()=>{let R=!0;if(!n){f({key:s,page:Qn,loading:!1,error:null});return}f((v)=>({key:s,page:v.key===s?v.page:Qn,loading:!0,error:null}));let[b,,u]=JSON.parse(r);return e.client.query(b,{...u,...a?{cursor:a}:{}}).then((v)=>{if(!R)return;if(v.ok)f({key:s,page:v.data,loading:!1,error:null});else f((k)=>({...k,loading:!1,error:v.error}))}).catch(()=>{if(R)f((v)=>({...v,loading:!1,error:{message:"Collection query failed. Retry to load records."}}))}),()=>{R=!1}},[s,r,a,e.client,e.reloadKey,n,g]);let c=P.key===s?P.page:Qn,S=P.key===s?P.error:null;return{page:c,loading:n&&(P.key!==s||P.loading),error:S?S.code?Oo(S,e.locale):me(e.locale)(S.message):"",previous:d.length?()=>o({key:r,cursor:d.at(-1),history:d.slice(0,-1)}):void 0,next:c.nextCursor?()=>o({key:r,cursor:c.nextCursor??void 0,history:[...d,a]}):void 0,retry:()=>m((R)=>R+1),pageNumber:d.length+1}}function jr(e,t,n,r){return n>=t?e("{count} records total",{count:t.toLocaleString(r)}):e("{total} records · {loaded} loaded",{total:t.toLocaleString(r),loaded:n})}function Gs({hasPrevious:e,hasNext:t,onPrevious:n,onNext:r,loading:i,page:o,locale:a,ui:d}){let s=me(a);if(!e&&!t)return null;return $e("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[se(Ie,{ui:d,style:je,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:s("Previous page"),disabled:!e||i,onClick:n}),o?se("span",{style:{fontSize:12},children:s("Page {page}",{page:o})}):null,se(Ie,{ui:d,style:je,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:s("Next page"),disabled:!t||i,onClick:r})]})}function Ig({state:e,locale:t,ui:n,hideCount:r}){let i=me(t);return $e("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[r?null:se("span",{children:jr(i,e.page.total,e.page.items.length,t)}),se(Gs,{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&&$e(Kr,{children:[se("span",{role:"alert",children:e.error}),se(Ie,{ui:n,style:je,variant:"outline",size:"sm",disabled:e.loading,onClick:e.retry,children:i("Retry query")})]})]})}function $r(e){let t=xo(e.client,e.descriptor.id),n=me(e.locale),[r,i]=Ye(!1),[o,a]=Ye(""),[d,s]=Ye(null),g=nn(null),m=nn(e);m.current=e;let P=(R)=>{if(!R||m.current.readOnly)return!1;let b=Dt(m.current.features),u={insert:b.rowCreate,update:b.rowUpdate,delete:b.rowDelete};return R.items.every((v)=>u[v.op])};Ht({dirty:Boolean(g.current),busy:r});let f=()=>{g.current=null,a(""),s(null)};return{saving:r,error:o,setError:a,remote:d,pending:g,reset:f,commit:async(R)=>{if(r||!t.active||!P(R))return!1;g.current=R,i(!0),a(""),s(null);let b=await e.client.mutate(e.descriptor.id,R).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),b.ok)return f(),e.onCommitted(b.data),!0;a(mn(b.error,e.locale));let u=b.error.details?.current;if(u&&typeof u.id==="string"&&Number.isSafeInteger(u.version)&&u.version>0)s(u);return!1},retryRequest:()=>g.current&&d?{idempotencyKey:crypto.randomUUID(),items:g.current.items.map((R)=>R.op!=="insert"&&R.id===d.id?{...R,expectedVersion:d.version}:R)}:g.current,canRetry:P(g.current),fields:Bn(e.descriptor.fields,e.view)}}function Hr({mutation:e,onRetry:t,locale:n,ui:r}){let i=me(n);return $e(Kr,{children:[e.error&&se("p",{role:"alert",children:e.error}),e.pending.current&&!e.canRetry&&se("p",{role:"status",children:i("You do not have permission to make this change.")}),e.remote&&$e("div",{style:er,children:[se("strong",{children:i("Current server version {version}",{version:e.remote.version})}),se(bn,{fields:e.fields,values:Un(e.pending.current,e.remote.id),serverValues:e.remote.values,locale:n}),se(Ie,{ui:r,style:je,variant:"outline",size:"sm",disabled:e.saving||!e.canRetry,onClick:t,children:i("Retry against current version")})]})]})}function Ag({row:e,onClose:t,onCancel:n,onDirtyChange:r,onBusyChange:i,stickyActions:o,...a}){let d=me(a.locale),s=Dt(a.features),g=!a.readOnly&&s.rowDelete,m=!a.readOnly&&s.rowUpdate,P=nn(e.values),[f,c]=Ye(()=>({...P.current})),[S,R]=Ye(!1);Ht({dirty:JSON.stringify(f)!==JSON.stringify(P.current),busy:!1});let b=nn(null),[u,v]=Ye(!1);Xn(()=>{b.current?.focus()},[]);let k=$r(a),N=Bn(a.descriptor.fields,a.view),T=JSON.stringify(f)!==JSON.stringify(e.values);Xn(()=>{r?.(T)},[T,r]),Xn(()=>{i?.(k.saving)},[k.saving,i]);let C=async(D=!1)=>{R(!0);try{let B=D?k.retryRequest():k.pending.current;if(!B){let j=N.filter((A)=>A.type!=="lookup"&&A.type!=="formula"&&A.type!=="rollup"&&JSON.stringify(f[A.id])!==JSON.stringify(e.values[A.id]));if(!j.length){k.setError(d("Change a field before saving."));return}let w=Br(j,f,d,a.locale);B={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:e.id,expectedVersion:e.version,values:w}]}}if(await k.commit(B))t()}catch(B){k.setError(B instanceof Error?B.message:d("Invalid value"))}},L=async()=>{let D=k.pending.current?.items[0]?.op==="delete"?k.pending.current:{idempotencyKey:crypto.randomUUID(),items:[{op:"delete",id:e.id,expectedVersion:e.version}]};if(await k.commit(D))t()};return $e("div",{ref:b,tabIndex:-1,onKeyDown:(D)=>{if(D.key==="Escape"&&!k.saving)D.stopPropagation(),(n??t)()},role:"dialog","aria-label":d("{name} record",{name:vr(e,a.descriptor.fields)}),style:{...er,marginTop:12},children:[se("h3",{children:vr(e,a.descriptor.fields)}),a.onInspectRecord&&se(Ie,{ui:a.ui,style:je,variant:"outline",size:"sm",disabled:k.saving,onClick:()=>a.onInspectRecord?.(e.id),children:d("Open record activity")}),$e("form",{onSubmit:(D)=>{D.preventDefault(),C()},children:[se("fieldset",{disabled:k.saving||u||!m,style:{border:0,padding:0},children:se(wn,{fields:N,values:f,submitted:S,...a.locale?{locale:a.locale}:{},...a.ui?{ui:a.ui}:{},relationClient:a.client,getRelationOptions:a.getRelationOptions,linkedRecords:e.linkedRecords,computedErrors:e.computedErrors,onChange:(D)=>{c(D),k.reset()}})}),$e("div",{"data-uibot":"record-editor-actions",style:o?{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:[m&&se("button",{type:"submit",style:{...je,...$n},disabled:k.saving||u,children:k.saving?d("Saving…"):d("Save record")}),o?null:se("button",{type:"button",style:je,disabled:k.saving,onClick:n??t,children:d("Close record")}),o&&g?se("span",{style:{marginLeft:"auto"},children:se(Ie,{ui:a.ui,variant:"ghost",size:"sm",icon:"trash",disabled:k.saving,onClick:()=>v(!0),children:d("Delete record")})}):null]})]}),g&&!o&&se("button",{type:"button",style:je,disabled:k.saving,onClick:()=>v(!0),children:d("Delete record")}),u&&a.ui?.ConfirmDialog?a.ui.ConfirmDialog({open:!0,destructive:!0,title:d("Delete this record?"),description:d(g?"Delete this record? Your unsaved changes will be discarded after deletion.":"You do not have permission to make this change."),confirmLabel:d("Delete"),cancelLabel:d("Cancel"),busy:k.saving,confirmDisabled:!g,onConfirm:()=>void L(),onCancel:()=>{if(v(!1),k.pending.current?.items[0]?.op==="delete")k.reset()}}):null,u&&!a.ui?.ConfirmDialog&&$e(Hn,{alert:!0,label:d("Confirm record deletion"),busy:k.saving,onCancel:()=>{if(v(!1),k.pending.current?.items[0]?.op==="delete")k.reset()},children:[se("p",{children:d("Delete this record? Your unsaved changes will be discarded after deletion.")}),!g&&se("p",{role:"status",children:d("You do not have permission to make this change.")}),se("button",{type:"button",style:je,disabled:k.saving||!g,onClick:()=>void L(),children:d("Confirm deletion")}),se("button",{type:"button",style:je,disabled:k.saving,onClick:()=>{if(v(!1),k.pending.current?.items[0]?.op==="delete")k.reset()},children:d("Cancel deletion")})]}),se(Hr,{mutation:k,onRetry:()=>void C(!0),locale:a.locale,ui:a.ui})]})}function Eg(e){let t=me(e.locale),n=!e.readOnly&&Dt(e.features).rowCreate,r=nn(null),i=Bn(e.descriptor.fields,{...e.view,hiddenColumns:e.view.hiddenColumns.filter((b)=>!e.descriptor.fields.find((u)=>u.id===b)?.required)}),o=()=>({...Object.fromEntries(i.filter((b)=>b.type==="checkbox").map((b)=>[b.id,!1])),...Ao(i)}),a=nn(o()),[d,s]=Ye(a.current),[g,m]=Ye(!1),[P,f]=Ye(!1);Ht({dirty:JSON.stringify(d)!==JSON.stringify(a.current),busy:!1});let c=$r(e),S=()=>r.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")?.focus(),R=async()=>{if(!n)return;f(!0);try{let b=c.pending.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:Br(i,d,t,e.locale)}]};if(await c.commit(b))a.current=o(),s(a.current),m(!0),f(!1),requestAnimationFrame(S)}catch(b){c.setError(b instanceof Error?b.message:t("Invalid value"))}};return $e("section",{"data-uibot":"collection-form",style:er,children:[se("h3",{children:e.view.name}),e.readOnly&&se("p",{children:t("Record creation requires editor permission.")}),$e("form",{ref:r,onSubmit:(b)=>{b.preventDefault(),R()},children:[se("fieldset",{disabled:c.saving||!n,style:{border:0,padding:0},children:se(wn,{fields:i,values:d,submitted:P,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},relationClient:e.client,getRelationOptions:e.getRelationOptions,onChange:(b)=>{s(b),m(!1),c.reset()}})}),n&&se("button",{type:"submit",style:{...je,...$n},disabled:c.saving,children:c.saving?t("Creating…"):t("Create record")})]}),se(Hr,{mutation:c,onRetry:()=>void R(),locale:e.locale,ui:e.ui}),g?$e("p",{role:"status",children:[t("Record created. Add another below."),e.onShowRecords?$e(Kr,{children:[" ",se(Ie,{ui:e.ui,style:je,variant:"outline",size:"sm",onClick:e.onShowRecords,children:t("Show records")})]}):null]}):null]})}function Dg(e){let[t,n]=Ye(null),r=$r(e),i=!e.readOnly&&Dt(e.features).rowUpdate;return{intent:t,mutation:r,move:async(d,s)=>{if(!i||r.saving||t)return;n({row:d,values:s});let g={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:d.id,expectedVersion:d.version,values:s}]};if(await r.commit(g))n(null)},retry:async()=>{let d=r.retryRequest();if(d&&await r.commit(d))n(null)},cancel:()=>{n(null),r.reset()},blocked:r.saving||!!t}}function Tg({state:e,locale:t,ui:n}){let r=me(t);if(!e.intent)return null;return $e("div",{role:"dialog","aria-label":r("Pending record move"),style:er,children:[se("p",{children:e.mutation.saving?r("Moving record…"):r("The move has been kept for retry.")}),!e.mutation.remote&&se(bn,{fields:e.mutation.fields,values:e.intent.values,locale:t}),se(Hr,{mutation:e.mutation,onRetry:()=>void e.retry(),locale:t,ui:n}),!e.mutation.remote&&se(Ie,{ui:n,style:je,variant:"outline",size:"sm",disabled:e.mutation.saving||!e.mutation.canRetry,onClick:()=>void e.retry(),children:r("Retry move")}),se(Ie,{ui:n,style:je,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:e.cancel,children:r("Cancel move")})]})}import{useCallback as Ws,useEffect as _i,useLayoutEffect as Ys,useRef as Gr,useState as Bi}from"react";import{jsx as tr,jsxs as zi,Fragment as Js}from"react/jsx-runtime";function Ui({items:e,label:t,children:n,block:r=!1}){let[i,o]=Bi(null),a=Gr(null),d=Gr(null),[s,g]=Bi({x:0,y:0}),m=Ws(()=>{if(!i||!d.current)return;let f=Math.max(12,Math.min(i.x,window.innerWidth-12-d.current.offsetWidth)),c=Math.max(12,Math.min(i.y,window.innerHeight-12-d.current.offsetHeight));g((S)=>S.x===f&&S.y===c?S:{x:f,y:c})},[i]);Ys(m),_i(()=>{if(!i)return;return window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[i,m]);let P=Gr(null);return _i(()=>{if(!i)return;P.current=document.activeElement instanceof HTMLElement?document.activeElement:null,d.current?.querySelector("button:not(:disabled)")?.focus();let f=()=>o(null),c=(S)=>{if(S.key==="Escape")S.preventDefault(),S.stopPropagation(),o(null),P.current?.focus({preventScroll:!0})};return window.addEventListener("keydown",c),window.addEventListener("pointerdown",f),window.addEventListener("blur",f),()=>{window.removeEventListener("keydown",c),window.removeEventListener("pointerdown",f),window.removeEventListener("blur",f)}},[i]),zi("span",{ref:a,style:{display:r?"block":"inline-flex"},onKeyDown:(f)=>{if(f.shiftKey&&f.key==="F10"||f.key==="ContextMenu"){f.preventDefault(),f.stopPropagation();let c=f.target.getBoundingClientRect();o({x:Math.max(8,Math.min(c.left,window.innerWidth-240)),y:Math.max(8,Math.min(c.bottom,window.innerHeight-280))})}},onContextMenu:(f)=>{f.preventDefault(),f.stopPropagation(),o({x:Math.max(8,Math.min(f.clientX,window.innerWidth-240)),y:Math.max(8,Math.min(f.clientY,window.innerHeight-280))})},children:[n,i&&tr("div",{ref:d,role:"menu","aria-label":t,style:{position:"fixed",left:s.x,top:s.y,boxSizing:"border-box",maxWidth:"calc(100vw - 24px)",maxHeight:"min(70vh, calc(100vh - 24px))",overflow:"auto",zIndex:60,minWidth:140,font:"inherit",padding:4,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",boxShadow:"0 4px 16px rgb(0 0 0 / 0.12)"},onPointerDown:(f)=>f.stopPropagation(),onKeyDown:(f)=>{if(!["ArrowDown","ArrowUp"].includes(f.key))return;f.preventDefault();let c=[...f.currentTarget.querySelectorAll("button:not(:disabled)")],S=c.indexOf(document.activeElement);c[(S+(f.key==="ArrowUp"?-1:1)+c.length)%c.length]?.focus()},children:e.map((f)=>tr("button",{type:"button",role:"menuitem",disabled:f.disabled,style:{display:"block",width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderRadius:6,background:"transparent",color:f.destructive?"var(--destructive, #b3261e)":"inherit",cursor:f.disabled?"default":"pointer",opacity:f.disabled?0.5:1},onClick:()=>{o(null),f.onSelect()},children:f.label},f.id))})]})}function qi({label:e,items:t,disabled:n,icon:r}){return tr(Fr,{label:e,disabled:n,menu:!0,trigger:r??"+",children:(i)=>tr(Js,{children:t.map((o)=>zi("button",{type:"button",role:"menuitem",disabled:o.disabled,style:{display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderTop:o.separatorBefore?"1px solid var(--border, #d5d9df)":void 0,background:"transparent",color:o.destructive?"var(--destructive, #b3261e)":"inherit",opacity:o.disabled?0.5:1,font:"inherit"},onClick:()=>{i(),o.onSelect()},children:[o.icon,o.label]},o.id))})})}function Yr(e){return e?.type==="singleSelect"||e?.type==="checkbox"}var Zs="\x00none";function ji(e,t,n=new Set){if(!t)return{items:e.map((a,d)=>({kind:"row",index:d,key:a.id})),rowItem:e.map((a,d)=>d)};let r=[],i=[],o;return e.forEach((a,d)=>{let s=a.values[t.id],g=s==null?Zs:String(s);if(!o||o.raw!==g){let m=t.options?.findIndex((P)=>P.id===s)??-1;o={kind:"group",key:`group:${r.length}:${g}`,raw:g,label:s==null?null:t.type==="checkbox"?s===!0?"true":"false":t.options?.[m]?.name??String(s),colorIndex:m,count:0,collapsed:n.has(g)},r.push(o)}if(o.count+=1,o.collapsed)return;i[d]=r.length,r.push({kind:"row",index:d,key:a.id})}),{items:r,rowItem:i}}function nr(e,t,n,r){for(let i=t;i>=0&&i<r;i+=n)if(e.rowItem[i]!==void 0)return i;return-1}var Jr=34,Wr=38,Qs={short:1,medium:2,tall:3,extra:4},Zr=(e)=>Qs[e??"short"],$i=(e)=>Wr+(Zr(e)-1)*22;function Hi(e,t=Wr){return Wr+e.items.reduce((n,r)=>n+(r.kind==="group"?Jr:t),0)}function _g(e,t){let n=e?.groupByFieldId;if(!e||!n||(e.type??"grid")!=="grid")return e?.sort;if(!t?.some((r)=>r.id===n&&Yr(r)))return e.sort;return[{fieldId:n,direction:"asc"},...(e.sort??[]).filter((r)=>r.fieldId!==n)]}import{jsx as _,jsxs as Te}from"react/jsx-runtime";function al(e,t){let n=e.find((r)=>r.fieldId===t);if(n?.direction==="desc")return[];return[{fieldId:t,direction:n?"desc":"asc"}]}var Ct={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},sl={padding:5,width:"100%",border:"1px solid #6688bb",background:"var(--background, white)",color:"inherit"};function ym(e){let{descriptor:t,view:n}=e,r=me(e.locale),i=ot(()=>Dt(e.features),[e.features]),o=!e.readOnly&&i.rowDelete,a=!e.readOnly&&i.rowCreate,d=!e.readOnly&&i.rowUpdate,s=Xe({readOnly:e.readOnly,features:i});s.current={readOnly:e.readOnly,features:i};let g=(l)=>{if(!l||s.current.readOnly)return!1;let y={insert:s.current.features.rowCreate,update:s.current.features.rowUpdate,delete:s.current.features.rowDelete};return l.items.every((x)=>y[x.op])},[m,P]=Le({}),f=Xe(new Set),[c,S]=Le(()=>new Set),R=Xe(new Set);it(()=>{if(!f.current.size)return;let l=f.current;f.current=new Set,P((y)=>Object.fromEntries(Object.entries(y).filter(([x])=>!l.has(x))))},[e.rows]);let b=ot(()=>Object.keys(m).length?e.rows.map((l)=>m[l.id]?{...l,values:{...l.values,...m[l.id]}}:l):e.rows,[e.rows,m]),u=ot(()=>[...n.columnOrder,...t.fields.map((y)=>y.id).filter((y)=>!n.columnOrder.includes(y))].filter((y)=>!n.hiddenColumns.includes(y)).flatMap((y)=>{let x=t.fields.find((W)=>W.id===y);return x?[x]:[]}),[t.fields,n.columnOrder,n.hiddenColumns]),v=ot(()=>JSON.stringify([b.map((l)=>l.id),u.map((l)=>l.id)]),[b,u]),[k,N]=Le(v),T=Xe(null),[C,L]=Le({row:0,column:0}),[D,B]=Le(!1),[j,w]=Le(()=>new Set),[A,H]=Le(()=>new Set),M=JSON.stringify([t.id,n.filter,n.search,n.sort,e.rowOffset]);it(()=>{w(new Set),H(new Set)},[e.rows,M]);let[q,Q]=Le({row:0,column:0}),[p,z]=Le(null),te=Xe(!1),pe=Xe(!1),[F,X]=Le(null),[ee,O]=Le(!1),[E,ie]=Le(!1);Ht({dirty:Boolean(F||ee||p&&p.text!==p.originalText),busy:E||c.size>0},e);let[ue,le]=Le(""),[Y,de]=Le(null),oe=Xe(null),Ne=p?.field.type==="linkedRecord"?JSON.stringify([p.rowId,p.field.id]):null;it(()=>{if(Ne)oe.current?.querySelector('input[type="search"]')?.focus({preventScroll:!0})},[Ne]),it(()=>{B(!1),L({row:0,column:0}),Q({row:0,column:0}),N(v)},[v]);let V=ot(()=>{if(!i.groupBy||(n.type??"grid")!=="grid")return;let l=t.fields.find((y)=>y.id===n.groupByFieldId);return Yr(l)?l:void 0},[i.groupBy,n.type,n.groupByFieldId,t.fields]),[h,G]=Le(()=>new Set),Z=V?.id;it(()=>G(new Set),[Z]);let ke=ot(()=>ji(b,V,h),[b,V,h]),qe=(l)=>Boolean(V)&&ke.rowItem[l]===void 0,rr=$i(n.rowHeight),Rn=Zr(n.rowHeight),rn=Ki({count:ke.items.length,getScrollElement:()=>T.current,estimateSize:(l)=>ke.items[l]?.kind==="group"?Jr:rr,overscan:5,scrollMargin:38,getItemKey:(l)=>`${rr}:${ke.items[l]?.key??l}`}),Je=n.showRowNumber===!1?0:56,at=n.showRecordId?220:0,zt=Je+at,[or,Gi]=Le(0);it(()=>{let l=T.current;if(!l)return;let y=()=>Gi(l.clientWidth);if(y(),typeof ResizeObserver>"u")return window.addEventListener("resize",y),()=>window.removeEventListener("resize",y);let x=new ResizeObserver(y);return x.observe(l),()=>x.disconnect()},[]);let eo=Math.min(Math.max(0,n.frozenColumnCount??0),u.length),to=ot(()=>{let l=[zt];for(let y of u)l.push((l.at(-1)??zt)+Pn(n.columnWidths[y.id]??180));return l},[zt,u,n.columnWidths]),Wi=to[eo]??zt,Ze=or>0&&or<=768&&Wi>or*0.6?0:eo,ir=(l)=>to[l]??zt,no=Xe(null),ar=Boolean(e.onAddRecord)&&a,Yi=ol(rl(tl,{activationConstraint:{distance:6}})),Ji=({active:l,delta:y})=>{let x=u.findIndex((Pe)=>Pe.id===l.id),W=xt.getVirtualItems().find((Pe)=>Pe.index===x);if(x<0||!W)return;let U=W.start+W.size/2+y.x,I=xt.getVirtualItems().find((Pe)=>U>=Pe.start&&U<Pe.start+Pe.size)?.index;if(I===void 0||I===x)return;if(x<Ze!==I<Ze)return;let K=[...n.columnOrder.filter((Pe)=>t.fields.some((oa)=>oa.id===Pe)),...t.fields.map((Pe)=>Pe.id).filter((Pe)=>!n.columnOrder.includes(Pe))],ge=String(l.id),ne=u[I]?.id;if(!ne)return;let be=K.filter((Pe)=>Pe!==ge),re=be.indexOf(ne)+(I>x?1:0);be.splice(re,0,ge),e.onViewChange({...n,columnOrder:be})},jt=(l,y)=>({position:"sticky",float:"left",left:l,zIndex:2,...y?{boxShadow:"2px 0 4px -2px color-mix(in srgb, currentColor 28%, transparent)"}:{}}),xt=Ki({paddingStart:zt,paddingEnd:e.onAddField?Qr:0,horizontal:!0,count:u.length,rangeExtractor:(l)=>{let y=new Set(il(l));for(let x=0;x<Ze;x+=1)y.add(x);return[...y].sort((x,W)=>x-W)},getScrollElement:()=>T.current,estimateSize:(l)=>Pn(n.columnWidths[u[l]?.id??""]??180),overscan:2,getItemKey:(l)=>u[l]?.id??l});it(()=>{u.forEach((l,y)=>{xt.resizeItem(y,Pn(n.columnWidths[l.id]??180))})},[xt,n.columnWidths,u]);let Tt=Math.max(1,xt.getTotalSize()),sr=xt.getVirtualItems(),Fe=Cr(C,q),lr=ot(()=>D&&k===v?b.slice(Fe.firstRow,Fe.lastRow+1):[],[D,k,v,b,Fe.firstRow,Fe.lastRow]),he=ot(()=>{let l=new Set(b.filter((y,x)=>!V||ke.rowItem[x]!==void 0).map((y)=>y.id));return _o(lr,j,b,A).filter((y)=>l.has(y.id))},[lr,j,b,A,V,ke]),on=ot(()=>he.map((l)=>l.id),[he]),ut=ot(()=>new Set(on),[on]),Sn=D?{first:Fe.firstColumn,last:Fe.lastColumn}:{first:0,last:u.length-1},dr=()=>he.length?Lo(he,u,{row:0,column:Sn.first},{row:he.length-1,column:Sn.last}):"",ro=(l)=>{if(p||E||ee||F)return;let y=b[l];if(!y)return;if(N(v),lr.some((x)=>x.id===y.id))H((x)=>xr(x,y.id));else w((x)=>xr(x,y.id));if(!D)L({row:l,column:0}),Q({row:l,column:u.length-1})},[Be,cr]=Le(null),an=Xe(null),oo=!j.size&&!A.size&&D&&d&&!E&&!p&&!ee&&!F&&!h.size,io=(l,y)=>{if(!oo)return;let x=Jo(l,y,b,u),W=(I)=>{le(I),e.onNotify?.(I)};if(x.limitExceeded){W(r("Fill at most 100 rows at once."));return}let U=x.skipped?r("Skipped {count} cells",{count:x.skipped}):"";if(!x.mutations.length){if(U)W(U);return}et({idempotencyKey:crypto.randomUUID(),items:x.mutations},()=>{W([r("Filled {count} cells",{count:x.count}),U].filter(Boolean).join("; "))})};it(()=>{if(!Be)return;let l=()=>{let x=an.current;if(cr(null),an.current=null,x)io(Be,x)},y=()=>{cr(null),an.current=null};return window.addEventListener("mouseup",l),window.addEventListener("blur",y),()=>{window.removeEventListener("mouseup",l),window.removeEventListener("blur",y)}});let ao=JSON.stringify({recordIds:k===v?on:[],fieldIds:he.length?u.slice(Sn.first,Sn.last+1).map((l)=>l.id):[]}),so=Xe(e.onSelectionChange);so.current=e.onSelectionChange,it(()=>{so.current?.(JSON.parse(ao))},[ao]),it(()=>{if(!V||!qe(q.row))return;let l=nr(ke,q.row,-1,b.length),y=l>=0?l:nr(ke,q.row,1,b.length);if(y>=0)Q({...q,row:y}),L({...q,row:y})},[ke]);let Zi=(l)=>{let y=new Set(h);if(y.has(l))y.delete(l);else y.add(l);G(y),B(!1),w(new Set),H(new Set),L(q)},pt=(l,y=!1)=>{if(h.size)y=!1;if(B(!0),N(v),Q(l),!y)L(l),w(new Set),H(new Set);rn.scrollToIndex(ke.rowItem[l.row]??l.row,{align:"auto"}),xt.scrollToIndex(l.column,{align:"auto"})},In=(l=q,y)=>{if(!d||E||p||ee||F||u[l.column]?.generation==="autoIncrement")return;let x=b[l.row],W=u[l.column];if(!x||!W||W.type==="blob"||Me(W))return;if(c.has(x.id))return;B(!0),N(v),te.current=!1;let U=W.type==="linkedRecord"?JSON.stringify(x.values[W.id]??[]):W.type==="relation"?Uo(x,W):W.type==="json"&&x.values[W.id]!=null?JSON.stringify(x.values[W.id]):Se(x.values[W.id]);z({rowId:x.id,expectedVersion:x.version,field:W,originalText:U,text:W.type==="linkedRecord"||W.type==="relation"?U:y??U}),le(i.optimisticEdit?"":r("Unsaved changes")),X(null),de(null)},st=Xe([]),Ft=Xe([]),[Nt,An]=Le(null),lo=(l,y)=>{for(let x of l.items){if(x.op!=="update")continue;let W=y.items.find((U)=>U.id===x.id);if(!W)continue;for(let U of[st,Ft])U.current=U.current.map((I)=>({...I,items:I.items.map((K)=>K.op!=="insert"&&K.id===x.id&&K.expectedVersion===x.expectedVersion?{...K,expectedVersion:W.version}:K)}))}},co=(l,y,x)=>{let W=l.items;if(!W.length)return null;let U=new Map(x.map((K)=>[K.id,K])),I=[];if(W.every((K)=>K.op==="update")){let K=new Map(y.items.map((ge)=>[ge.id,ge]));for(let ge of W){if(ge.op!=="update")continue;let ne=U.get(ge.id);if(!ne)return null;I.push({op:"update",id:ge.id,expectedVersion:K.get(ge.id)?.version??ge.expectedVersion+1,values:Object.fromEntries(Object.keys(ge.values).map((be)=>[be,ne.values[be]??null]))})}}else if(W.every((K)=>K.op==="insert")){if(y.items.length!==W.length)return null;for(let K of y.items)I.push({op:"delete",id:K.id,expectedVersion:K.version})}else if(W.every((K)=>K.op==="delete"))for(let K of W){if(K.op!=="delete")continue;let ge=U.get(K.id);if(!ge)return null;I.push({op:"insert",values:Object.fromEntries(t.fields.filter((ne)=>ne.type!=="blob"&&ne.type!=="linkedRecord"&&!Me(ne)&&ne.generation!=="autoIncrement"&&ge.values[ne.id]!==void 0).map((ne)=>[ne.id,ge.values[ne.id]]))})}else return null;return{idempotencyKey:crypto.randomUUID(),items:I}},Qi=(l)=>{if(E||e.readOnly||p||ee||F)return;let x=(l==="undo"?st:Ft).current.at(-1);if(!x||!g(x))return;et({...x,idempotencyKey:crypto.randomUUID()},void 0,l)};async function et(l,y,x){if(E||pe.current||!g(l))return;let W=x&&Nt?Nt.before:b;if(x)An({direction:x,before:W,rejected:!1});pe.current=!0,ie(!0),X(l),le("");let U=await e.onMutate(l).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:r("Saving failed. Your edit has been kept.")}}));if(pe.current=!1,ie(!1),U.ok){let I=co(l,U.data,W);if(x)(x==="undo"?st:Ft).current.pop();if(lo(l,U.data),An(null),I)if(x==="undo")Ft.current.push(I);else{if(st.current.push(I),st.current.length>30)st.current.shift();if(!x)Ft.current=[]}e.onCommitted(U.data),X(null),z(null),O(!1),de(null);let K=l.items.filter((ne)=>ne.op==="delete").length,ge=x?r(x==="undo"?"Undone":"Redone"):K>0&&K===l.items.length?r("Deleted {count} records",{count:K}):r("Saved");if(e.onNotify)le(""),e.onNotify(ge);else le(ge);T.current?.focus({preventScroll:!0}),y?.()}else{if(x){let K=U.error.status;An({direction:x,before:W,rejected:K>=400&&K<500&&K!==408})}le(mn(U.error,e.locale));let I=U.error.details;if(I?.current)de(I.current)}}async function uo(l,y,x,W){if(R.current.has(l.id)||s.current.readOnly||!s.current.features.rowUpdate)return;R.current.add(l.id),ie(!0);let U=p??{rowId:l.id,expectedVersion:l.version,field:y,text:Se(x),originalText:Se(l.values[y.id])},I={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:l.id,expectedVersion:l.version,values:{[y.id]:x}}]};P((ne)=>({...ne,[l.id]:{...ne[l.id],[y.id]:x}})),S((ne)=>new Set(ne).add(l.id)),z(null),le(""),T.current?.focus({preventScroll:!0});let K=await e.onMutate(I).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:r("Saving failed. Your edit has been kept.")}}));if(R.current.delete(l.id),ie(!1),S((ne)=>{let be=new Set(ne);return be.delete(l.id),be}),K.ok){f.current.add(l.id);let ne=co(I,K.data,[l]);if(lo(I,K.data),ne){if(st.current.push(ne),st.current.length>30)st.current.shift();Ft.current=[]}e.onCommitted(K.data),W?.();return}P((ne)=>{let be={...ne};return delete be[l.id],be}),te.current=!1,z(U),X(I),le(mn(K.error,e.locale));let ge=K.error.details;if(ge?.current)de(ge.current)}async function vt(l){if(!p||te.current||s.current.readOnly||!s.current.features.rowUpdate)return;let{field:y,rowId:x,expectedVersion:W}=p;if(y.generation==="autoIncrement"||t.fields.find((U)=>U.id===y.id)?.generation==="autoIncrement"){le(r("{name} is auto-generated and cannot be edited.",{name:y.name})),z(null);return}try{let U=y.type==="linkedRecord"?JSON.parse(p.text):y.type==="relation"?p.text||null:nt(p.text,y);if(y.type==="linkedRecord"&&y.required&&Array.isArray(U)&&!U.length)throw Error(`${y.name} is required.`);if(i.optimisticEdit&&y.type==="linkedRecord"&&!F&&p.text===p.originalText){gt();return}if(i.optimisticEdit&&y.type!=="linkedRecord"&&!F){let ge=b.find((ne)=>ne.id===x);if(!ge){z(null);return}if(JSON.stringify(U??null)===JSON.stringify(ge.values[y.id]??null)){gt();return}await uo(ge,y,U,()=>{if(l)pt(Ln(q,"Tab",b.length,u.length,l==="previous"))});return}let I={[y.id]:U},K=F??{idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:x,expectedVersion:W,values:I}]};await et(K,l?()=>pt(Ln(q,"Tab",b.length,u.length,l==="previous")):void 0)}catch(U){le((e.locale==="zh-CN"?Qt(y,p.text,"zh-CN"):null)||(U instanceof Error?U.message:r("Invalid value")))}}let $t=Boolean(e.readOnly||E||p||ee||F||on.length===0),po=()=>{if($t||!o)return;gr()},gt=()=>{te.current=!0,le(""),z(null),X(null),de(null),T.current?.focus({preventScroll:!0})},sn=(l)=>{if(!p||l===p.text)return;le(i.optimisticEdit?"":r("Unsaved changes")),z({...p,text:l}),X(null),de(null)},Xi=(l,y,x)=>{if(!d||E||p||ee||F)return;if(i.optimisticEdit){uo(l,y,x);return}z({rowId:l.id,expectedVersion:l.version,field:y,text:String(x),originalText:Se(l.values[y.id])}),et({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:l.id,expectedVersion:l.version,values:{[y.id]:x}}]})},kt=i.optionChips,ur=Boolean(e.renderRecordContextMenu)||i.recordContextMenu,go=i.optimisticEdit&&!F?{onBlur:(l)=>{if(!l.currentTarget.contains(l.relatedTarget))vt()}}:{},mt=p?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:p.field,text:p.text,disabled:E||!d,autoOpen:!0,onChange:sn,onSave:(l)=>void vt(l),onCancel:gt}):void 0,mo=i.optimisticEdit&&p?.field.type==="linkedRecord"&&(mt===void 0||mt===null)&&!F&&!E?{onBlur:(l)=>{let y=l.relatedTarget;if(!y||oe.current?.contains(y)||y.closest('[role="gridcell"]')?.id===`wb-${p.rowId}-${p.field.id}`)return;vt()}}:{},pr=p&&(p.field.type==="singleSelect"||p.field.type==="multipleSelect")?mt??Te("select",{"aria-label":r("Edit {name}",{name:p.field.name}),ref:(l)=>l?.focus(),style:sl,multiple:p.field.type==="multipleSelect",value:p.field.type==="multipleSelect"?p.text.split(",").filter(Boolean):p.text,disabled:E||!d,onChange:(l)=>sn(p.field.type==="multipleSelect"?Array.from(l.currentTarget.selectedOptions,(y)=>y.value).join(","):l.currentTarget.value),onKeyDown:(l)=>{if(l.stopPropagation(),l.key==="Escape")l.preventDefault(),gt();if(l.key==="Tab")l.preventDefault(),vt(l.shiftKey?"previous":"next");if(l.key==="Enter")l.preventDefault(),vt()},children:[p.field.type==="singleSelect"&&_("option",{value:"",disabled:p.field.required,children:r("Clear selection")}),(p.field.options??[]).map((l)=>_("option",{value:l.id,children:l.name},l.id)),p.text.split(",").filter((l)=>l&&!p.field.options?.some((y)=>y.id===l)).map((l)=>_("option",{value:l,disabled:!0,children:r("{id} (unavailable)",{id:l})},l))]}):void 0,gr=()=>{if(!o||E||p||ee||F||he.length===0)return;if(he.length>100){le(r("Select at most 100 rows per delete."));return}X({idempotencyKey:crypto.randomUUID(),items:he.map((l)=>({op:"delete",id:l.id,expectedVersion:l.version}))}),O(!0),le(""),de(null)},ea=(l,y,x,W,U)=>{U.setPointerCapture(W);let I=(ge)=>e.onViewChange({...n,columnWidths:{...n.columnWidths,[l]:Pn(x+ge.clientX-y)}}),K=()=>{U.removeEventListener("pointermove",I),U.removeEventListener("pointerup",K),U.removeEventListener("pointercancel",K)};U.addEventListener("pointermove",I),U.addEventListener("pointerup",K),U.addEventListener("pointercancel",K)},[ta,na]=Le(480);Xs(()=>{if(!e.display?.fill)return;let l=()=>{let y=T.current?.getBoundingClientRect().top??0;na(Math.max(240,Math.round(window.innerHeight-y-64-(i.footerStats?34:0))))};return l(),window.addEventListener("resize",l),()=>window.removeEventListener("resize",l)},[e.display?.fill,i.footerStats]);let ln=e.display?.summary===!1&&e.display?.keyboardHints===!1,fo=!!p&&rn.getVirtualItems().some((l)=>{let y=ke.items[l.index];return y?.kind==="row"&&b[y.index]?.id===p.rowId})&&xt.getVirtualItems().some((l)=>u[l.index]?.id===p.field.id),En=Te("section",{"data-uibot":"paged-collection-grid",style:{display:ln?"grid":"flex",flexDirection:ln?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&&he.length>0&&!e.renderRecordContextMenu&&!i.recordContextMenu)&&Te("div",{"data-uibot":"paged-collection-toolbar",style:{display:"flex",gap:8,padding:8,alignItems:"center",flexWrap:"wrap",...ln?{}:{order:1,padding:"4px 10px",fontSize:12,borderTop:"1px solid var(--border, #d5d9df)"},...ln?{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&&_("span",{children:jr(r,e.total,b.length,e.locale)}),e.aggregate&&!i.footerStats&&_(Zn,{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}:{}}),_("span",{style:{flex:1}}),e.display?.keyboardHints!==!1&&_("span",{style:{fontSize:12},children:r(d?"Arrows · Shift select · Enter edit · Copy / paste":"Arrows · Shift select · Copy")}),e.onInspectRecord&&_(Ie,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:E||he.length!==1,onClick:()=>{let l=he[0];if(l)e.onInspectRecord?.(l.id)},children:r("Open record activity")}),o&&he.length>0&&!e.renderRecordContextMenu&&!i.recordContextMenu&&_(Ie,{ui:e.ui,style:Ct,variant:"outline",size:"sm",icon:"trash",disabled:$t,onClick:gr,children:r("Delete selected rows")})]}),_("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,10 +16,10 @@ done=Done`})]}),x&&Pe("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
- `}),Ie($s,{ui:e.ui,paneRef:y,role:"grid","aria-label":r("{name} records",{name:t.name}),"aria-rowcount":e.total+1,"aria-colcount":x.length+Number(Boolean(Je))+Number(Boolean(at)),"aria-activedescendant":b[q.row]&&x[q.column]?`wb-${b[q.row]?.id}-${x[q.column]?.id}`:void 0,tabIndex:0,style:{gridArea:an?"1 / 1":void 0,overflow:"auto",height:e.display?.fill?qi:o.autoHeight?Math.min(e.display?.maxHeight??560,Math.max(120,Ti(z,Oe)+2+(Zn?Gr:0))):e.display?.maxHeight??480,position:"relative",outlineOffset:-2},onScroll:(s)=>Jr.current?.style.setProperty("--uibot-sx",`${s.currentTarget.scrollLeft}px`),onCopy:(s)=>{if(w)return;s.preventDefault(),s.clipboardData.setData("text/plain",er())},onPaste:(s)=>{if(w||j||V||!d||H)return;if(s.preventDefault(),Se.size){ee(r("Expand all groups before pasting."));return}let f=Ao(s.clipboardData.getData("text/plain"),b,x,{row:Ne.firstRow,column:Ne.firstColumn},e.locale);if(!f.ok){ee(f.message);return}ie({idempotencyKey:crypto.randomUUID(),items:f.items}),oe(!0),ee(""),me(null)},onKeyDown:(s)=>{if(s.target!==s.currentTarget&&s.target.closest("button, input, select, textarea, [contenteditable=true]"))return;if((s.metaKey||s.ctrlKey)&&!s.altKey&&!w){let f=s.key.toLowerCase();if(f==="d"||f==="r"){s.preventDefault();let v=f==="d"?{...Ne,lastRow:Ne.firstRow}:{...Ne,lastColumn:Ne.firstColumn};Xr(v,Ne);return}if(f==="z"||f==="y"){s.preventDefault(),Bi(f==="y"||s.shiftKey?"redo":"undo");return}}if(!w&&s.key==="Escape"){U(new Set),R(new Set);return}if(w||!b.length||!x.length||H)return;if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End"].includes(s.key)){s.preventDefault();let f=s.key==="Tab"&&s.shiftKey,v=Dn(q,s.key,b.length,x.length,f);if(Q(v.row)){let Y=s.key==="ArrowUp"||f||v.row<q.row,_=Wn(z,v.row,Y?-1:1,b.length);if(_<0)return;v={...v,row:_}}pt(v,s.shiftKey&&s.key!=="Tab")}else if(Q(q.row))s.preventDefault();else if(s.key==="Delete"&&ye.length>0&&i)s.preventDefault(),or();else if(d&&["Enter","F2"].includes(s.key))s.preventDefault(),vn();else if(d&&s.key.length===1&&!s.metaKey&&!s.ctrlKey&&!s.altKey)s.preventDefault(),vn(q,s.key)},children:[L(Os,{sensors:Li,modifiers:[Ws],onDragEnd:Oi,children:Ie("div",{role:"row",tabIndex:-1,style:{position:"sticky",top:0,height:38,width:Dt,zIndex:2,background:"var(--muted, #f4f6f8)"},children:[Je>0&&L("div",{role:"columnheader",tabIndex:-1,"aria-colindex":1,"aria-label":r("Row"),style:{...zt(0,!at&&Ze===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:Je,padding:4,display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center",height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:Ie("label",{title:r("{count} selected",{count:ye.length}),style:{position:"relative",display:"flex",alignItems:"center"},children:[ye.length===0&&L("span",{"aria-hidden":"true",children:r("Row")}),L("input",{type:"checkbox","aria-label":r("Select all loaded records"),ref:(s)=>{if(s)s.indeterminate=ye.length>0&&ye.length<b.filter((f,v)=>!Q(v)).length},style:ye.length===0?{position:"absolute",inset:0,width:"100%",height:"100%",margin:0,opacity:0,cursor:"pointer"}:{margin:0,width:16,height:16},onKeyDown:(s)=>s.stopPropagation(),checked:ye.length>0&&ye.length===b.filter((s,f)=>!Q(f)).length,disabled:Boolean(w||H||j||V),onChange:(s)=>{O(!1),k(P),R(new Set),U(s.currentTarget.checked?new Set(b.filter((f,v)=>!Q(v)).map((f)=>f.id)):new Set)},onFocus:(s)=>{s.currentTarget.parentElement?.style.setProperty("outline","2px solid var(--ring, currentColor)")},onBlur:(s)=>{s.currentTarget.parentElement?.style.removeProperty("outline")}})]})}),at>0&&L("div",{role:"columnheader",tabIndex:-1,"aria-colindex":Je>0?2:1,style:{...zt(Je,Ze===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:at,padding:8,height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:r("Record ID")}),Qn.map((s)=>{let f=x[s.index];if(!f)return null;let v=Nn(n.columnColors?.[f.id]),Y=n.sort?.find((ne)=>ne.fieldId===f.id),_=o.sorting&&f.type!=="linkedRecord"&&Ft(f),A=e.fieldMenu?.(f)??[],G=A.length?e.ui?.DropdownMenu?e.ui.DropdownMenu({label:r("Field menu {name}",{name:f.name}),icon:L(Me,{name:"chevronDown"}),items:A}):L(Ii,{label:r("Field menu {name}",{name:f.name}),icon:L(Me,{name:"chevronDown"}),items:A},f.id):null,ue=L(Ys,{id:f.id,disabled:!o.columnReorder,children:(ne)=>Ie("div",{ref:ne.setNodeRef,...ne.listeners,role:"columnheader","data-uibot-field":f.id,tabIndex:-1,"aria-colindex":s.index+1+Number(Boolean(Je))+Number(Boolean(at)),onKeyDown:(fe)=>{if(fe.shiftKey&&fe.key==="F10"||fe.key==="ContextMenu"){fe.preventDefault(),fe.stopPropagation();let re=fe.currentTarget.querySelector('button[aria-haspopup="menu"]');re?.focus({preventScroll:!0}),re?.click(),re?.dispatchEvent(new KeyboardEvent("keydown",{key:"ArrowDown",bubbles:!0}))}},"aria-sort":Y?Y.direction==="asc"?"ascending":"descending":"none",style:{...s.index<Ze?{...zt(Jn(s.index),s.index===Ze-1),background:"var(--muted, #f4f6f8)"}:{position:"absolute",left:s.start},boxSizing:"border-box",background:v?.background??"var(--muted, #f4f6f8)",borderTopWidth:v?3:void 0,borderTopStyle:v?"solid":void 0,borderTopColor:v?.marker,width:s.size,height:38,borderRight:"1px solid var(--border, #d5d9df)",display:"flex",alignItems:"center",...ne.style},children:[Ie("button",{type:"button",disabled:!_,title:_||!o.sorting?void 0:r("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",...o.fieldTypeIcons?{display:"flex",alignItems:"center",gap:6,fontSize:12,fontWeight:600,whiteSpace:"nowrap"}:{}},onClick:()=>e.onViewChange({...n,sort:zs(n.sort??[],f.id)}),children:[o.fieldTypeIcons&&L(Fo,{type:f.type}),o.fieldTypeIcons?L("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:f.name}):f.name,f.ai?L("span",{role:"img","aria-label":r("AI field"),title:r("AI field"),"data-uibot-ai-field":"",style:{display:"inline-flex",flex:"none",opacity:0.7},children:L(Me,{name:"sparkles",size:12})}):null,Y?L(Me,{name:Y.direction==="asc"?"sortAsc":"sortDesc",size:12,style:{marginLeft:"auto",opacity:0.7}}):null]}),G,o.columnResize&&L("button",{type:"button","aria-label":r("Resize {name}",{name:f.name}),style:{border:0,background:"transparent",position:"absolute",top:0,bottom:0,right:-3,width:7,padding:0,cursor:"col-resize",zIndex:2},onPointerDown:(fe)=>{fe.stopPropagation(),Ui(f.id,fe.clientX,s.size,fe.pointerId,fe.currentTarget)},onKeyDown:(fe)=>{if(fe.key==="ArrowLeft"||fe.key==="ArrowRight")fe.preventDefault(),e.onViewChange({...n,columnWidths:{...n.columnWidths,[f.id]:Cn(s.size+(fe.key==="ArrowRight"?20:-20))}})}})]})},f.id);return A.length&&e.ui?.ContextMenu?L(e.ui.ContextMenu,{items:A,"aria-label":r("Field menu {name}",{name:f.name}),children:ue},f.id):ue}),e.onAddField&&L("div",{"data-uibot-add-field":"",style:{position:"absolute",left:Dt-Kr,width:Kr,height:38,boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--muted, #f4f6f8)",borderRight:"1px solid var(--border, #d5d9df)"},children:L("button",{type:"button","aria-label":r("Add field"),title:r("Add field"),onClick:()=>e.onAddField?.(),style:{border:0,background:"transparent",color:"inherit",cursor:"pointer",width:"100%",height:"100%",display:"grid",placeItems:"center"},children:L(Me,{name:"plus"})})})]})}),Ie("div",{style:{position:"relative",width:Dt,height:tn.getTotalSize()+(Zn?Gr:0)},children:[tn.getVirtualItems().map((s)=>{let f=z.items[s.index];if(f?.kind==="group"){let _=f.label===null?r("Not set"):f.label==="true"?r("Checked"):f.label==="false"?r("Unchecked"):f.label;return L("div",{role:"presentation","data-uibot-group":_,style:{position:"absolute",top:s.start-38,height:s.size,width:Dt,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"},children:Ie("button",{type:"button","aria-expanded":!f.collapsed,"aria-label":r(f.collapsed?"Expand group {name}":"Collapse group {name}",{name:_}),disabled:!o.groupCollapse,onClick:()=>Vi(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:o.groupCollapse?"pointer":"default"},children:[o.groupCollapse&&L("span",{"aria-hidden":"true",style:{width:10,fontSize:10,opacity:0.6},children:f.collapsed?"▸":"▾"}),L(gr,{index:f.colorIndex,children:_}),L("span",{style:{opacity:0.6},children:r("{count} records",{count:f.count})})]})},f.key)}let v=f?b[f.index]:void 0;if(f?.kind!=="row"||!v)return null;let Y=f.index;return Ie("div",{role:"row",tabIndex:-1,"aria-rowindex":(e.rowOffset??0)+Y+2,style:{position:"absolute",top:s.start-38,height:s.size,width:Dt},children:[Je>0&&Ie("div",{role:"gridcell",tabIndex:-1,"aria-colindex":1,"aria-label":String((e.rowOffset??0)+Y+1),"aria-readonly":"true","aria-selected":ut.has(v.id),style:{...zt(0,!at&&Ze===0),width:Je,height:s.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(v.id)?"var(--accent, #e8f0fe)":"var(--muted, #f4f6f8)"},onMouseDown:(_)=>{if(w||_.button!==0||x.length===0)return;if(_.target.closest("button, input"))return;if(_.preventDefault(),_.ctrlKey||_.metaKey){Zr(Y),y.current?.focus({preventScroll:!0});return}if(!_.shiftKey)pt({row:Y,column:0});pt({row:Y,column:x.length-1},!0),y.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!nr||x.length===0)return;if(!ut.has(v.id))pt({row:Y,column:0})},children:[L("span",{"data-uibot-row-number":"",style:{opacity:ut.has(v.id)?0:1},children:(e.rowOffset??0)+Y+1}),Ie("span",{"data-uibot-row-actions":"",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",gap:4,opacity:ut.has(v.id)?1:0},children:[L("input",{type:"checkbox","aria-label":r("Select row"),checked:ut.has(v.id),disabled:Boolean(w||H||j||V),onChange:()=>Zr(Y),onClick:(_)=>_.stopPropagation()}),e.onExpandRecord&&L("button",{type:"button","aria-label":r("Expand record"),title:r("Expand record"),style:{display:"inline-flex",padding:0,border:0,background:"transparent",color:"inherit",cursor:"pointer"},onClick:()=>e.onExpandRecord?.(v),children:L(Me,{name:"expand"})})]})]}),at>0&&L("div",{role:"gridcell",tabIndex:-1,"aria-colindex":Je>0?2:1,"aria-readonly":"true",style:{...zt(Je,Ze===0),background:"var(--background, white)",boxSizing:"border-box",width:at,height:s.size,padding:7,borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)"},onContextMenu:()=>{if(!nr)return;if(!ut.has(v.id))pt({row:Y,column:0})},children:L("input",{"aria-label":r("Record ID {id}",{id:v.id}),readOnly:!0,value:v.id,style:{width:"100%",border:0,background:"transparent",color:"inherit",fontSize:12},onCopy:(_)=>_.stopPropagation(),onPaste:(_)=>_.stopPropagation(),onKeyDown:(_)=>_.stopPropagation()})}),Qn.map((_)=>{let A=x[_.index];if(!A)return null;let G={row:Y,column:_.index},ue=ut.has(v.id)&&(T.has(v.id)||E&&G.column>=Ne.firstColumn&&G.column<=Ne.lastColumn),ne=w?.rowId===v.id&&w.field.id===A.id,fe=!ne&&A.type==="checkbox"?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:A,text:Re(v.values[A.id]),disabled:Boolean(!d||H||w||j||V),mode:"inline",autoOpen:!1,onChange:(re)=>{if(!d||H||w||j||V)return;try{let ke=tt(re,A);Z({rowId:v.id,expectedVersion:v.version,field:A,text:re,originalText:Re(v.values[A.id])}),Xe({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:v.id,expectedVersion:v.version,values:{[A.id]:ke}}]})}catch(ke){ee(e.locale==="zh-CN"?Yt(A,re,"zh-CN"):ke instanceof Error?ke.message:r("Invalid value"))}},onSave:()=>{},onCancel:gt}):void 0;return Ie("div",{id:`wb-${v.id}-${A.id}`,role:"gridcell",tabIndex:-1,...ne&&A.type==="linkedRecord"?so:{},"aria-colindex":_.index+1+Number(Boolean(Je))+Number(Boolean(at)),"aria-selected":ue,"aria-readonly":!d||A.generation==="autoIncrement"||A.type==="blob"||Fe(A),style:{..._.index<Ze?zt(Jn(_.index),_.index===Ze-1):{position:"absolute",left:_.start},width:_.size,height:s.size,padding:ne?0:kt?"0 10px":7,boxSizing:"border-box",borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",overflow:ne?"visible":"hidden",...ne?{zIndex:3}:{},whiteSpace:"nowrap",...kt&&!ne?{display:"flex",alignItems:"center",fontSize:13}:{},...Ye>1&&!ne&&(A.type==="singleLineText"||A.type==="longText")?{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:Ye,whiteSpace:"normal",wordBreak:"break-word",padding:kt?"6px 10px":7}:{},background:ue?"var(--accent, #e8f0fe)":Nn(n.columnColors?.[A.id])?.background??"var(--background, white)",outline:q.row===G.row&&q.column===G.column?"2px solid #6488bd":"none",outlineOffset:-2},onMouseEnter:()=>{if(!_e)return;let re=Math.max(_e.firstRow-G.row,G.row-_e.lastRow,0),ke=Math.max(_e.firstColumn-G.column,G.column-_e.lastColumn,0);rn.current=re>=ke?{..._e,firstRow:Math.min(G.row,_e.firstRow),lastRow:Math.max(G.row,_e.lastRow)}:{..._e,firstColumn:Math.min(G.column,_e.firstColumn),lastColumn:Math.max(G.column,_e.lastColumn)}},onMouseDown:(re)=>{if(_e||w)return;if(re.button!==0)return;re.preventDefault(),pt(G,re.shiftKey),y.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!nr)return;if(!(ut.has(v.id)&&(T.has(v.id)||G.column>=Ne.firstColumn&&G.column<=Ne.lastColumn)))pt(G)},onClick:(re)=>{if(!w&&!re.shiftKey&&(A.type==="singleSelect"||A.type==="multipleSelect"))vn(G)},onDoubleClick:()=>vn(G),children:[Qr&&G.row===Ne.lastRow&&G.column===Ne.lastColumn&&L("button",{type:"button","aria-label":r("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:_e?"grabbing":"grab",zIndex:4},onMouseDown:(re)=>{re.preventDefault(),re.stopPropagation(),rn.current=null,tr(Ne)},onClick:(re)=>re.stopPropagation()}),ne&&mt!==void 0&&mt!==null?mt:ne&&A.type==="relation"?L(vr,{locale:e.locale,field:A,value:w.text,label:r("Edit {name}",{name:A.name}),getOptions:e.getRelationOptions,labels:v.linkedRecords?.[A.id],disabled:H,onChange:(re)=>{ee(o.optimisticEdit?"":r("Unsaved changes")),Z({...w,text:re}),ie(null),me(null)}}):ne&&rr!==void 0?L("div",{style:{display:"contents"},...ao,children:rr}):ne&&A.type!=="linkedRecord"?L("div",{style:{display:"contents"},...ao,children:L(Cr,{field:A,text:w.text,disabled:H||Boolean(e.readOnly),locale:e.locale,ariaLabel:r("Edit {name}",{name:A.name}),onChange:on,onSave:(re)=>void vt(re),onCancel:gt})}):A.type==="relation"||A.type==="linkedRecord"?ti(v,A):A.type==="lookup"?St(v.values[A.id]):A.type==="formula"||A.type==="rollup"?Qt(v.values[A.id],v.computedErrors?.[A.id]):A.type==="checkbox"&&fe!==void 0&&fe!==null?fe:A.type==="checkbox"&&kt?L(No,{checked:v.values[A.id]===!0,label:r("Edit {name}",{name:A.name}),onToggle:!d||H||w||j||V||A.generation==="autoIncrement"?void 0:()=>_i(v,A,v.values[A.id]!==!0)}):A.type==="checkbox"?L("input",{type:"checkbox","aria-label":r("Edit {name}",{name:A.name}),checked:v.values[A.id]===!0,ref:(re)=>{if(re)re.indeterminate=v.values[A.id]==null},disabled:!d||H||Boolean(w)||Boolean(j)||Boolean(V)||A.generation==="autoIncrement",onMouseDown:(re)=>re.stopPropagation(),onKeyDown:(re)=>re.stopPropagation(),onChange:(re)=>{if(!d||H||w||j||V)return;let ke=re.currentTarget.checked;Z({rowId:v.id,expectedVersion:v.version,field:A,text:String(ke),originalText:Re(v.values[A.id])}),Xe({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:v.id,expectedVersion:v.version,values:{[A.id]:ke}}]})}}):A.type==="date"?L("span",{title:Re(v.values[A.id]),style:kt?{opacity:0.75,fontVariantNumeric:"tabular-nums"}:void 0,children:(()=>{let re=dt(A);return re?dn(v.values[A.id],re):Tn(v.values[A.id])})()}):A.type==="number"&&kt?L("span",{style:{display:"block",width:"100%",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:(()=>{let re=ln(A);return re?cn(v.values[A.id],re):Re(v.values[A.id])})()}):kt&&A.type==="singleSelect"&&v.values[A.id]!=null?L(mr,{ids:[v.values[A.id]],field:A,wrap:Ye>1}):kt&&A.type==="multipleSelect"&&Array.isArray(v.values[A.id])?L(mr,{ids:v.values[A.id],field:A,wrap:Ye>1}):A.type==="hyperlink"?L(Fn,{value:v.values[A.id]}):A.type==="singleSelect"?A.options?.find((re)=>re.id===v.values[A.id])?.name??Re(v.values[A.id]):A.type==="multipleSelect"&&Array.isArray(v.values[A.id])?v.values[A.id].map((re)=>A.options?.find((ke)=>ke.id===re)?.name??String(re)).join(", "):Re(v.values[A.id])]},A.id)})]},v.id)}),Zn?L("div",{style:{position:"absolute",top:tn.getTotalSize(),left:0,width:Dt,height:Gr,borderBottom:"1px solid var(--border, #d5d9df)"},children:Ie("button",{type:"button","aria-label":r("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:[L(Me,{name:"plus"}),r("Add record")]})}):null]})]}),o.footerStats&&(n.type??"grid")==="grid"&&x.length>0?L(Js,{ui:e.ui,locale:e.locale,t:r,rows:b,total:e.total,descriptor:t,aggregateClient:e.serverFooterStats===!1?void 0:e.aggregate?.client,reloadKey:e.reloadKey,fields:x,columns:Qn,width:Dt,frozenCount:Ze,frozenLeft:Jn,view:n,footerRef:Jr,onChange:e.onViewChange}):null,w&&(V||!(o.optimisticEdit&&w.field.type!=="linkedRecord"))&&!(lo&&mt!==void 0&&mt!==null)&&Ie("div",{ref:X,...so,role:"dialog","aria-label":r("{name} editor",{name:w.field.name}),style:{padding:8,display:"flex",flexWrap:"wrap",gap:8},onKeyDown:(s)=>{if(w.field.type==="linkedRecord"&&s.key==="Escape"&&!H)s.preventDefault(),s.stopPropagation(),gt()},children:[!lo&&w.field.type!=="linkedRecord"&&(mt??rr??(w.field.type==="relation"?L(vr,{locale:e.locale,field:w.field,value:w.text,label:r("Edit {name}",{name:w.field.name}),getOptions:e.getRelationOptions,labels:b.find((s)=>s.id===w.rowId)?.linkedRecords?.[w.field.id],disabled:H,onChange:on}):L(Cr,{field:w.field,text:w.text,disabled:H||Boolean(e.readOnly),locale:e.locale,ariaLabel:r("Edit {name}",{name:w.field.name}),onChange:on,onSave:(s)=>void vt(s),onCancel:gt}))),w.field.type==="linkedRecord"&&L("div",{style:{width:"100%"},children:L(Ln,{disabled:H,field:w.field,value:JSON.parse(w.text),locale:e.locale,labels:b.find((s)=>s.id===w.rowId)?.linkedRecords?.[w.field.id],client:e.relationClient,onChange:(s)=>{Z({...w,text:JSON.stringify(s)}),ie(null),me(null)}})}),L(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:H,onClick:()=>void vt(),children:H?r("Saving…"):r("Save edit")}),L(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:H,onClick:gt,children:r("Cancel edit")})]}),j&&V&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:V.items.every((s)=>s.op==="delete"),title:V.items.every((s)=>s.op==="delete")?r("Delete {count} records?",{count:V.items.length}):r("Apply {count} row changes in one transaction?",{count:V.items.length}),description:V.items.every((s)=>s.op==="delete")?r("The selected records will be deleted. If any of them changed meanwhile, nothing is deleted."):r("If any record changed or any value is invalid, all changes are rejected."),confirmLabel:H?r("Saving…"):V.items.every((s)=>s.op==="delete")?r("Delete"):r("Confirm changes"),cancelLabel:V.items.every((s)=>s.op==="delete")?r("Cancel"):r("Cancel changes"),busy:H,onConfirm:()=>void Xe(V),onCancel:()=>{oe(!1),ie(null),me(null)}}):null,j&&V&&!e.ui?.ConfirmDialog&&Ie(Vn,{label:r("Confirm bulk change"),busy:H,onCancel:()=>{oe(!1),ie(null),me(null)},children:[L("p",{children:r("Apply {count} row changes in one transaction?",{count:V.items.length})}),L("p",{style:{fontSize:12},children:r("If any record changed or any value is invalid, all changes are rejected.")}),L(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:H,onClick:()=>void Xe(V),children:H?r("Saving…"):r("Confirm changes")})," ",L(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:H,onClick:()=>{oe(!1),ie(null),me(null)},children:r("Cancel changes")})]}),Nt&&V&&Ie("div",{role:"group","aria-label":r("Undo/redo recovery"),style:{padding:8},children:[!H&&W&&L("p",{role:"alert",children:W}),L(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:H||Boolean(e.readOnly),onClick:()=>void Xe(V,void 0,Nt.direction),children:r("Retry undo/redo")})," ",Nt.rejected&&L(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:H,onClick:()=>{st.current=[],Tt.current=[],kn(null),ie(null),me(null),ee("")},children:r("Clear undo/redo history")})]}),de&&!Nt&&Ie("div",{style:{padding:12},children:[L("strong",{children:r("Current server version {version}",{version:de.version})}),L("div",{style:{display:"grid",gap:8,margin:"8px 0"},children:V?.items.flatMap((s)=>s.op==="update"&&s.id===de.id?Object.entries(s.values).map(([f,v])=>{let Y=t.fields.find((A)=>A.id===f),_=(A)=>Y?.options?.find((G)=>G.id===A)?.name??Re(A);return Ie("div",{style:{border:"1px solid var(--border,#d5d9df)",borderRadius:6,padding:8},children:[L("strong",{children:Y?.name??f}),Ie("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"minmax(90px,auto) 1fr",gap:4},children:[L("dt",{children:r("Your edit")}),L("dd",{style:{margin:0,whiteSpace:"pre-wrap"},children:_(v)}),L("dt",{children:r("Server value")}),L("dd",{style:{margin:0,whiteSpace:"pre-wrap"},children:_(de.values[f])})]})]},f)}):[])}),L(Ae,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:H,onClick:()=>{if(!V)return;let s=V.items.map((f)=>f.op!=="insert"&&f.id===de.id?{...f,expectedVersion:de.version}:f);Xe({idempotencyKey:crypto.randomUUID(),items:s})},children:r("Retry against current version")})]}),L("p",{role:"status","aria-live":"polite",style:e.onNotify?Hs:{margin:0,padding:W||H?8:0},children:H?r("Saving…"):Nt?"":W})]}),ji=t.fields.filter((s)=>s.type!=="blob"&&s.type!=="linkedRecord"&&!Fe(s)&&s.generation!=="autoIncrement"),co=()=>{if(!a||jt||ye.length===0||ye.length>100)return;Xe({idempotencyKey:crypto.randomUUID(),items:ye.map((s)=>({op:"insert",values:Object.fromEntries(ji.flatMap((f)=>s.values[f.id]===void 0?[]:[[f.id,s.values[f.id]]]))}))})};if(e.renderRecordContextMenu){let s=ye.length===1?ye[0]:void 0;return e.renderRecordContextMenu({children:wn,recordIds:nn,disabled:jt,onDelete:io,...e.onExpandRecord&&s?{onExpand:()=>e.onExpandRecord?.(s)}:{},onCopy:()=>void navigator.clipboard?.writeText(er()),...a?{onDuplicate:co}:{}})}if(!o.recordContextMenu)return wn;let uo=[...e.onExpandRecord&&ye.length===1?[{id:"expand",icon:L(Me,{name:"expand"}),label:r("Expand record"),onSelect:()=>{let s=ye[0];if(s)e.onExpandRecord?.(s)}}]:[],...a?[{id:"duplicate",icon:L(Me,{name:"copy"}),label:r("Duplicate {count} selected records",{count:ye.length}),disabled:jt||ye.length===0,onSelect:co}]:[],{id:"copy",separatorBefore:!0,icon:L(Me,{name:"copy"}),label:r("Copy cells"),disabled:ye.length===0,onSelect:()=>{navigator.clipboard?.writeText(er())}},...i?[{id:"delete",icon:L(Me,{name:"trash"}),label:r("Delete {count} selected records",{count:ye.length}),separatorBefore:!0,destructive:!0,disabled:jt,onSelect:io}]:[]],po=e.ui?.ContextMenu;return po?L(po,{items:uo,"aria-label":r("Record actions"),children:wn}):L(Si,{block:!0,items:uo,label:r("Record actions"),children:wn})}function $s({ui:e,paneRef:t,style:n,children:r,...o}){if(e?.ScrollArea)return e.ScrollArea({viewportRef:t,viewportProps:o,style:n,children:r});return L("div",{ref:t,style:n,...o,children:r})}var Hs={position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:0},Ks=96,Gs=560,Cn=(e)=>Math.max(Ks,Math.min(Gs,Math.round(e))),Ws=({transform:e})=>({...e,y:0});function Ys({id:e,disabled:t,children:n}){let{setNodeRef:r,listeners:o,transform:i,isDragging:a}=Bs({id:e,disabled:t});return it(()=>{if(!a)return;let d=document.body.style.cursor;return document.body.style.cursor="grabbing",()=>{document.body.style.cursor=d}},[a]),n({setNodeRef:r,listeners:t?void 0:o,style:{...i?{transform:`translate3d(${Math.round(i.x)}px, 0, 0)`}:{},...a?{cursor:"grabbing",zIndex:6,opacity:0.9,background:"var(--accent, #e8f0fe)",boxShadow:"0 2px 10px color-mix(in srgb, currentColor 22%, transparent)"}:{}}})}function Js({descriptor:e,aggregateClient:t,reloadKey:n,ui:r,locale:o,t:i,rows:a,total:d,fields:l,columns:p,width:u,frozenCount:c,frozenLeft:g,view:C,footerRef:b,onChange:x}){let P=Zo(e,C,l,a,t,n),m=(k,y,I)=>{let F={...C.footerStats??{}};if(y)F[k]=y;else if(I)F[k]="none";else delete F[k];let{footerStats:E,...O}=C;x(Object.keys(F).length?{...O,footerStats:F}:O)};return Ie("div",{ref:b,"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:[L("style",{children:`
19
+ `}),Te(ll,{ui:e.ui,paneRef:T,role:"grid","aria-label":r("{name} records",{name:t.name}),"aria-rowcount":e.total+1,"aria-colcount":u.length+Number(Boolean(Je))+Number(Boolean(at)),"aria-activedescendant":b[q.row]&&u[q.column]?`wb-${b[q.row]?.id}-${u[q.column]?.id}`:void 0,tabIndex:0,style:{gridArea:ln?"1 / 1":void 0,overflow:"auto",height:e.display?.fill?ta:i.autoHeight?Math.min(e.display?.maxHeight??560,Math.max(120,Hi(ke,rr)+2+(ar?Xr:0))):e.display?.maxHeight??480,position:"relative",outlineOffset:-2},onScroll:(l)=>no.current?.style.setProperty("--uibot-sx",`${l.currentTarget.scrollLeft}px`),onCopy:(l)=>{if(p)return;l.preventDefault(),l.clipboardData.setData("text/plain",dr())},onPaste:(l)=>{if(p||ee||F||!d||E)return;if(l.preventDefault(),h.size){le(r("Expand all groups before pasting."));return}let y=Vo(l.clipboardData.getData("text/plain"),b,u,{row:Fe.firstRow,column:Fe.firstColumn},e.locale);if(!y.ok){le(y.message);return}X({idempotencyKey:crypto.randomUUID(),items:y.items}),O(!0),le(""),de(null)},onKeyDown:(l)=>{if(l.target!==l.currentTarget&&l.target.closest("button, input, select, textarea, [contenteditable=true]"))return;if((l.metaKey||l.ctrlKey)&&!l.altKey&&!p){let y=l.key.toLowerCase();if(y==="d"||y==="r"){l.preventDefault();let x=y==="d"?{...Fe,lastRow:Fe.firstRow}:{...Fe,lastColumn:Fe.firstColumn};io(x,Fe);return}if(y==="z"||y==="y"){l.preventDefault(),Qi(y==="y"||l.shiftKey?"redo":"undo");return}}if(!p&&l.key==="Escape"){w(new Set),H(new Set);return}if(p||!b.length||!u.length||E)return;if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Tab","Home","End"].includes(l.key)){l.preventDefault();let y=l.key==="Tab"&&l.shiftKey,x=Ln(q,l.key,b.length,u.length,y);if(qe(x.row)){let W=l.key==="ArrowUp"||y||x.row<q.row,U=nr(ke,x.row,W?-1:1,b.length);if(U<0)return;x={...x,row:U}}pt(x,l.shiftKey&&l.key!=="Tab")}else if(qe(q.row))l.preventDefault();else if(l.key==="Delete"&&he.length>0&&o)l.preventDefault(),gr();else if(d&&["Enter","F2"].includes(l.key))l.preventDefault(),In();else if(d&&l.key.length===1&&!l.metaKey&&!l.ctrlKey&&!l.altKey)l.preventDefault(),In(q,l.key)},children:[_(el,{sensors:Yi,modifiers:[pl],onDragEnd:Ji,children:Te("div",{role:"row",tabIndex:-1,style:{position:"sticky",top:0,height:38,width:Tt,zIndex:2,background:"var(--muted, #f4f6f8)"},children:[Je>0&&_("div",{role:"columnheader",tabIndex:-1,"aria-colindex":1,"aria-label":r("Row"),style:{...jt(0,!at&&Ze===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:Je,padding:4,display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center",height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:Te("label",{title:r("{count} selected",{count:he.length}),style:{position:"relative",display:"flex",alignItems:"center"},children:[he.length===0&&_("span",{"aria-hidden":"true",children:r("Row")}),_("input",{type:"checkbox","aria-label":r("Select all loaded records"),ref:(l)=>{if(l)l.indeterminate=he.length>0&&he.length<b.filter((y,x)=>!qe(x)).length},style:he.length===0?{position:"absolute",inset:0,width:"100%",height:"100%",margin:0,opacity:0,cursor:"pointer"}:{margin:0,width:16,height:16},onKeyDown:(l)=>l.stopPropagation(),checked:he.length>0&&he.length===b.filter((l,y)=>!qe(y)).length,disabled:Boolean(p||E||ee||F),onChange:(l)=>{B(!1),N(v),H(new Set),w(l.currentTarget.checked?new Set(b.filter((y,x)=>!qe(x)).map((y)=>y.id)):new Set)},onFocus:(l)=>{l.currentTarget.parentElement?.style.setProperty("outline","2px solid var(--ring, currentColor)")},onBlur:(l)=>{l.currentTarget.parentElement?.style.removeProperty("outline")}})]})}),at>0&&_("div",{role:"columnheader",tabIndex:-1,"aria-colindex":Je>0?2:1,style:{...jt(Je,Ze===0),background:"var(--muted, #f4f6f8)",boxSizing:"border-box",width:at,padding:8,height:38,borderRight:"1px solid var(--border, #d5d9df)"},children:r("Record ID")}),sr.map((l)=>{let y=u[l.index];if(!y)return null;let x=qn(n.columnColors?.[y.id]),W=n.sort?.find((ne)=>ne.fieldId===y.id),U=i.sorting&&y.type!=="linkedRecord"&&Mt(y),I=e.fieldMenu?.(y)??[],K=I.length?e.ui?.DropdownMenu?e.ui.DropdownMenu({label:r("Field menu {name}",{name:y.name}),icon:_(Oe,{name:"chevronDown"}),items:I}):_(qi,{label:r("Field menu {name}",{name:y.name}),icon:_(Oe,{name:"chevronDown"}),items:I},y.id):null,ge=_(gl,{id:y.id,disabled:!i.columnReorder,children:(ne)=>Te("div",{ref:ne.setNodeRef,...ne.listeners,role:"columnheader","data-uibot-field":y.id,tabIndex:-1,"aria-colindex":l.index+1+Number(Boolean(Je))+Number(Boolean(at)),onKeyDown:(be)=>{if(be.shiftKey&&be.key==="F10"||be.key==="ContextMenu"){be.preventDefault(),be.stopPropagation();let re=be.currentTarget.querySelector('button[aria-haspopup="menu"]');re?.focus({preventScroll:!0}),re?.click(),re?.dispatchEvent(new KeyboardEvent("keydown",{key:"ArrowDown",bubbles:!0}))}},"aria-sort":W?W.direction==="asc"?"ascending":"descending":"none",style:{...l.index<Ze?{...jt(ir(l.index),l.index===Ze-1),background:"var(--muted, #f4f6f8)"}:{position:"absolute",left:l.start},boxSizing:"border-box",background:x?.background??"var(--muted, #f4f6f8)",borderTopWidth:x?3:void 0,borderTopStyle:x?"solid":void 0,borderTopColor:x?.marker,width:l.size,height:38,borderRight:"1px solid var(--border, #d5d9df)",display:"flex",alignItems:"center",...ne.style},children:[Te("button",{type:"button",disabled:!U,title:U||!i.sorting?void 0:r("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:al(n.sort??[],y.id)}),children:[i.fieldTypeIcons&&_(Wo,{type:y.type}),i.fieldTypeIcons?_("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:y.name}):y.name,y.ai?_("span",{role:"img","aria-label":r("AI field"),title:r("AI field"),"data-uibot-ai-field":"",style:{display:"inline-flex",flex:"none",opacity:0.7},children:_(Oe,{name:"sparkles",size:12})}):null,W?_(Oe,{name:W.direction==="asc"?"sortAsc":"sortDesc",size:12,style:{marginLeft:"auto",opacity:0.7}}):null]}),K,i.columnResize&&_("button",{type:"button","aria-label":r("Resize {name}",{name:y.name}),style:{border:0,background:"transparent",position:"absolute",top:0,bottom:0,right:-3,width:7,padding:0,cursor:"col-resize",zIndex:2},onPointerDown:(be)=>{be.stopPropagation(),ea(y.id,be.clientX,l.size,be.pointerId,be.currentTarget)},onKeyDown:(be)=>{if(be.key==="ArrowLeft"||be.key==="ArrowRight")be.preventDefault(),e.onViewChange({...n,columnWidths:{...n.columnWidths,[y.id]:Pn(l.size+(be.key==="ArrowRight"?20:-20))}})}})]})},y.id);return I.length&&e.ui?.ContextMenu?_(e.ui.ContextMenu,{items:I,"aria-label":r("Field menu {name}",{name:y.name}),children:ge},y.id):ge}),e.onAddField&&_("div",{"data-uibot-add-field":"",style:{position:"absolute",left:Tt-Qr,width:Qr,height:38,boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--muted, #f4f6f8)",borderRight:"1px solid var(--border, #d5d9df)"},children:_("button",{type:"button","aria-label":r("Add field"),title:r("Add field"),onClick:()=>e.onAddField?.(),style:{border:0,background:"transparent",color:"inherit",cursor:"pointer",width:"100%",height:"100%",display:"grid",placeItems:"center"},children:_(Oe,{name:"plus"})})})]})}),Te("div",{style:{position:"relative",width:Tt,height:rn.getTotalSize()+(ar?Xr:0)},children:[rn.getVirtualItems().map((l)=>{let y=ke.items[l.index];if(y?.kind==="group"){let U=y.label===null?r("Not set"):y.label==="true"?r("Checked"):y.label==="false"?r("Unchecked"):y.label;return _("div",{role:"presentation","data-uibot-group":U,style:{position:"absolute",top:l.start-38,height:l.size,width:Tt,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"},children:Te("button",{type:"button","aria-expanded":!y.collapsed,"aria-label":r(y.collapsed?"Expand group {name}":"Collapse group {name}",{name:U}),disabled:!i.groupCollapse,onClick:()=>Zi(y.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&&_("span",{"aria-hidden":"true",style:{width:10,fontSize:10,opacity:0.6},children:y.collapsed?"▸":"▾"}),_(wr,{index:y.colorIndex,children:U}),_("span",{style:{opacity:0.6},children:r("{count} records",{count:y.count})})]})},y.key)}let x=y?b[y.index]:void 0;if(y?.kind!=="row"||!x)return null;let W=y.index;return Te("div",{role:"row",tabIndex:-1,"aria-rowindex":(e.rowOffset??0)+W+2,style:{position:"absolute",top:l.start-38,height:l.size,width:Tt},children:[Je>0&&Te("div",{role:"gridcell",tabIndex:-1,"aria-colindex":1,"aria-label":String((e.rowOffset??0)+W+1),"aria-readonly":"true","aria-selected":ut.has(x.id),style:{...jt(0,!at&&Ze===0),width:Je,height:l.size,padding:7,boxSizing:"border-box",borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",color:"var(--muted-foreground, #71717a)",textAlign:"center",fontVariantNumeric:"tabular-nums",background:ut.has(x.id)?"var(--accent, #e8f0fe)":"var(--muted, #f4f6f8)"},onMouseDown:(U)=>{if(p||U.button!==0||u.length===0)return;if(U.target.closest("button, input"))return;if(U.preventDefault(),U.ctrlKey||U.metaKey){ro(W),T.current?.focus({preventScroll:!0});return}if(!U.shiftKey)pt({row:W,column:0});pt({row:W,column:u.length-1},!0),T.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!ur||u.length===0)return;if(!ut.has(x.id))pt({row:W,column:0})},children:[_("span",{"data-uibot-row-number":"",style:{opacity:ut.has(x.id)?0:1},children:(e.rowOffset??0)+W+1}),Te("span",{"data-uibot-row-actions":"",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",gap:4,opacity:ut.has(x.id)?1:0},children:[_("input",{type:"checkbox","aria-label":r("Select row"),checked:ut.has(x.id),disabled:Boolean(p||E||ee||F),onChange:()=>ro(W),onClick:(U)=>U.stopPropagation()}),e.onExpandRecord&&_("button",{type:"button","aria-label":r("Expand record"),title:r("Expand record"),style:{display:"inline-flex",padding:0,border:0,background:"transparent",color:"inherit",cursor:"pointer"},onClick:()=>e.onExpandRecord?.(x),children:_(Oe,{name:"expand"})})]})]}),at>0&&_("div",{role:"gridcell",tabIndex:-1,"aria-colindex":Je>0?2:1,"aria-readonly":"true",style:{...jt(Je,Ze===0),background:"var(--background, white)",boxSizing:"border-box",width:at,height:l.size,padding:7,borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)"},onContextMenu:()=>{if(!ur)return;if(!ut.has(x.id))pt({row:W,column:0})},children:_("input",{"aria-label":r("Record ID {id}",{id:x.id}),readOnly:!0,value:x.id,style:{width:"100%",border:0,background:"transparent",color:"inherit",fontSize:12},onCopy:(U)=>U.stopPropagation(),onPaste:(U)=>U.stopPropagation(),onKeyDown:(U)=>U.stopPropagation()})}),sr.map((U)=>{let I=u[U.index];if(!I)return null;let K={row:W,column:U.index},ge=ut.has(x.id)&&(j.has(x.id)||D&&K.column>=Fe.firstColumn&&K.column<=Fe.lastColumn),ne=p?.rowId===x.id&&p.field.id===I.id,be=!ne&&I.type==="checkbox"?e.renderCellEditor?.({...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},field:I,text:Se(x.values[I.id]),disabled:Boolean(!d||E||p||ee||F),mode:"inline",autoOpen:!1,onChange:(re)=>{if(!d||E||p||ee||F)return;try{let Pe=nt(re,I);z({rowId:x.id,expectedVersion:x.version,field:I,text:re,originalText:Se(x.values[I.id])}),et({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:x.id,expectedVersion:x.version,values:{[I.id]:Pe}}]})}catch(Pe){le(e.locale==="zh-CN"?Qt(I,re,"zh-CN"):Pe instanceof Error?Pe.message:r("Invalid value"))}},onSave:()=>{},onCancel:gt}):void 0;return Te("div",{id:`wb-${x.id}-${I.id}`,role:"gridcell",tabIndex:-1,...ne&&I.type==="linkedRecord"?mo:{},"aria-colindex":U.index+1+Number(Boolean(Je))+Number(Boolean(at)),"aria-selected":ge,"aria-readonly":!d||I.generation==="autoIncrement"||I.type==="blob"||Me(I),style:{...U.index<Ze?jt(ir(U.index),U.index===Ze-1):{position:"absolute",left:U.start},width:U.size,height:l.size,padding:ne?0:kt?"0 10px":7,boxSizing:"border-box",borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",overflow:ne?"visible":"hidden",...ne?{zIndex:3}:{},whiteSpace:"nowrap",...kt&&!ne?{display:"flex",alignItems:"center",fontSize:13}:{},...Rn>1&&!ne&&(I.type==="singleLineText"||I.type==="longText")?{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:Rn,whiteSpace:"normal",wordBreak:"break-word",padding:kt?"6px 10px":7}:{},background:ge?"var(--accent, #e8f0fe)":qn(n.columnColors?.[I.id])?.background??"var(--background, white)",outline:q.row===K.row&&q.column===K.column?"2px solid #6488bd":"none",outlineOffset:-2},onMouseEnter:()=>{if(!Be)return;let re=Math.max(Be.firstRow-K.row,K.row-Be.lastRow,0),Pe=Math.max(Be.firstColumn-K.column,K.column-Be.lastColumn,0);an.current=re>=Pe?{...Be,firstRow:Math.min(K.row,Be.firstRow),lastRow:Math.max(K.row,Be.lastRow)}:{...Be,firstColumn:Math.min(K.column,Be.firstColumn),lastColumn:Math.max(K.column,Be.lastColumn)}},onMouseDown:(re)=>{if(Be||p)return;if(re.button!==0)return;re.preventDefault(),pt(K,re.shiftKey),T.current?.focus({preventScroll:!0})},onContextMenu:()=>{if(!ur)return;if(!(ut.has(x.id)&&(j.has(x.id)||K.column>=Fe.firstColumn&&K.column<=Fe.lastColumn)))pt(K)},onClick:(re)=>{if(!p&&!re.shiftKey&&(I.type==="singleSelect"||I.type==="multipleSelect"))In(K)},onDoubleClick:()=>In(K),children:[oo&&K.row===Fe.lastRow&&K.column===Fe.lastColumn&&_("button",{type:"button","aria-label":r("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:Be?"grabbing":"grab",zIndex:4},onMouseDown:(re)=>{re.preventDefault(),re.stopPropagation(),an.current=null,cr(Fe)},onClick:(re)=>re.stopPropagation()}),ne&&mt!==void 0&&mt!==null?mt:ne&&I.type==="relation"?_(xn,{locale:e.locale,field:I,value:p.text,label:r("Edit {name}",{name:I.name}),getOptions:e.getRelationOptions,labels:x.linkedRecords?.[I.id],disabled:E||!d,onChange:(re)=>{le(i.optimisticEdit?"":r("Unsaved changes")),z({...p,text:re}),X(null),de(null)}}):ne&&pr!==void 0?_("div",{style:{display:"contents"},...go,children:pr}):ne&&I.type!=="linkedRecord"?_("div",{style:{display:"contents"},...go,children:_(Er,{field:I,text:p.text,disabled:E||!d,locale:e.locale,ariaLabel:r("Edit {name}",{name:I.name}),onChange:sn,onSave:(re)=>void vt(re),onCancel:gt})}):I.type==="relation"||I.type==="linkedRecord"?Bo(x,I):I.type==="lookup"?Pt(x.values[I.id]):I.type==="formula"||I.type==="rollup"?Wt(x.values[I.id],x.computedErrors?.[I.id]):I.type==="checkbox"&&be!==void 0&&be!==null?be:I.type==="checkbox"&&kt?_(Go,{checked:x.values[I.id]===!0,label:r("Edit {name}",{name:I.name}),onToggle:!d||E||p||ee||F||I.generation==="autoIncrement"?void 0:()=>Xi(x,I,x.values[I.id]!==!0)}):I.type==="checkbox"?_("input",{type:"checkbox","aria-label":r("Edit {name}",{name:I.name}),checked:x.values[I.id]===!0,ref:(re)=>{if(re)re.indeterminate=x.values[I.id]==null},disabled:!d||E||Boolean(p)||Boolean(ee)||Boolean(F)||I.generation==="autoIncrement",onMouseDown:(re)=>re.stopPropagation(),onKeyDown:(re)=>re.stopPropagation(),onChange:(re)=>{if(!d||E||p||ee||F)return;let Pe=re.currentTarget.checked;z({rowId:x.id,expectedVersion:x.version,field:I,text:String(Pe),originalText:Se(x.values[I.id])}),et({idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:x.id,expectedVersion:x.version,values:{[I.id]:Pe}}]})}}):I.type==="date"?_("span",{title:Se(x.values[I.id]),style:kt?{opacity:0.75,fontVariantNumeric:"tabular-nums"}:void 0,children:(()=>{let re=dt(I);return re?un(x.values[I.id],re):Vn(x.values[I.id])})()}):I.type==="number"&&kt?_("span",{style:{display:"block",width:"100%",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:(()=>{let re=cn(I);return re?pn(x.values[I.id],re):Se(x.values[I.id])})()}):kt&&I.type==="singleSelect"&&x.values[I.id]!=null?_(Pr,{ids:[x.values[I.id]],field:I,wrap:Rn>1}):kt&&I.type==="multipleSelect"&&Array.isArray(x.values[I.id])?_(Pr,{ids:x.values[I.id],field:I,wrap:Rn>1}):I.type==="hyperlink"?_(zn,{value:x.values[I.id]}):I.type==="singleSelect"?I.options?.find((re)=>re.id===x.values[I.id])?.name??Se(x.values[I.id]):I.type==="multipleSelect"&&Array.isArray(x.values[I.id])?x.values[I.id].map((re)=>I.options?.find((Pe)=>Pe.id===re)?.name??String(re)).join(", "):Se(x.values[I.id])]},I.id)})]},x.id)}),ar?_("div",{style:{position:"absolute",top:rn.getTotalSize(),left:0,width:Tt,height:Xr,borderBottom:"1px solid var(--border, #d5d9df)"},children:Te("button",{type:"button","aria-label":r("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:[_(Oe,{name:"plus"}),r("Add record")]})}):null]})]}),i.footerStats&&(n.type??"grid")==="grid"&&u.length>0?_(ml,{ui:e.ui,locale:e.locale,t:r,rows:b,total:e.total,descriptor:t,aggregateClient:e.serverFooterStats===!1?void 0:e.aggregate?.client,reloadKey:e.reloadKey,fields:u,columns:sr,width:Tt,frozenCount:Ze,frozenLeft:ir,view:n,footerRef:no,onChange:e.onViewChange}):null,p&&(F||!(i.optimisticEdit&&p.field.type!=="linkedRecord"))&&!(fo&&mt!==void 0&&mt!==null)&&Te("div",{ref:oe,...mo,role:"dialog","aria-label":r("{name} editor",{name:p.field.name}),style:{padding:8,display:"flex",flexWrap:"wrap",gap:8},onKeyDown:(l)=>{if(p.field.type==="linkedRecord"&&l.key==="Escape"&&!E)l.preventDefault(),l.stopPropagation(),gt()},children:[!fo&&p.field.type!=="linkedRecord"&&(mt??pr??(p.field.type==="relation"?_(xn,{locale:e.locale,field:p.field,value:p.text,label:r("Edit {name}",{name:p.field.name}),getOptions:e.getRelationOptions,labels:b.find((l)=>l.id===p.rowId)?.linkedRecords?.[p.field.id],disabled:E||!d,onChange:sn}):_(Er,{field:p.field,text:p.text,disabled:E||!d,locale:e.locale,ariaLabel:r("Edit {name}",{name:p.field.name}),onChange:sn,onSave:(l)=>void vt(l),onCancel:gt}))),p.field.type==="linkedRecord"&&_("div",{style:{width:"100%"},children:_(_n,{disabled:E||!d,field:p.field,value:JSON.parse(p.text),locale:e.locale,labels:b.find((l)=>l.id===p.rowId)?.linkedRecords?.[p.field.id],client:e.relationClient,onChange:(l)=>{z({...p,text:JSON.stringify(l)}),X(null),de(null)}})}),_(Ie,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:E||!d,onClick:()=>void vt(),children:E?r("Saving…"):r("Save edit")}),_(Ie,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:E,onClick:gt,children:r("Cancel edit")})]}),ee&&F&&e.ui?.ConfirmDialog?e.ui.ConfirmDialog({open:!0,destructive:F.items.every((l)=>l.op==="delete"),title:F.items.every((l)=>l.op==="delete")?r("Delete {count} records?",{count:F.items.length}):r("Apply {count} row changes in one transaction?",{count:F.items.length}),description:F.items.every((l)=>l.op==="delete")?r("The selected records will be deleted. If any of them changed meanwhile, nothing is deleted."):r("If any record changed or any value is invalid, all changes are rejected."),confirmLabel:E?r("Saving…"):F.items.every((l)=>l.op==="delete")?r("Delete"):r("Confirm changes"),cancelLabel:F.items.every((l)=>l.op==="delete")?r("Cancel"):r("Cancel changes"),busy:E,confirmDisabled:!g(F),onConfirm:()=>void et(F),onCancel:()=>{O(!1),X(null),de(null)}}):null,ee&&F&&!e.ui?.ConfirmDialog&&Te(Hn,{label:r("Confirm bulk change"),busy:E,onCancel:()=>{O(!1),X(null),de(null)},children:[_("p",{children:r("Apply {count} row changes in one transaction?",{count:F.items.length})}),_("p",{style:{fontSize:12},children:r("If any record changed or any value is invalid, all changes are rejected.")}),_(Ie,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:E||!g(F),onClick:()=>void et(F),children:E?r("Saving…"):r("Confirm changes")})," ",_(Ie,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:E,onClick:()=>{O(!1),X(null),de(null)},children:r("Cancel changes")})]}),Nt&&F&&Te("div",{role:"group","aria-label":r("Undo/redo recovery"),style:{padding:8},children:[!E&&ue&&_("p",{role:"alert",children:ue}),_(Ie,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:E||!g(F),onClick:()=>void et(F,void 0,Nt.direction),children:r("Retry undo/redo")})," ",Nt.rejected&&_(Ie,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:E,onClick:()=>{st.current=[],Ft.current=[],An(null),X(null),de(null),le("")},children:r("Clear undo/redo history")})]}),Y&&!Nt&&Te("div",{style:{padding:12},children:[_("strong",{children:r("Current server version {version}",{version:Y.version})}),_(bn,{fields:u,values:Un(F,Y.id),serverValues:Y.values,locale:e.locale}),_(Ie,{ui:e.ui,style:Ct,variant:"outline",size:"sm",disabled:E||!g(F),onClick:()=>{if(!F)return;let l=F.items.map((y)=>y.op!=="insert"&&y.id===Y.id?{...y,expectedVersion:Y.version}:y);et({idempotencyKey:crypto.randomUUID(),items:l})},children:r("Retry against current version")})]}),_("p",{role:"status","aria-live":"polite",style:e.onNotify?dl:{margin:0,padding:ue||E?8:0},children:E?r("Saving…"):Nt?"":ue})]}),ra=t.fields.filter((l)=>l.type!=="blob"&&l.type!=="linkedRecord"&&!Me(l)&&l.generation!=="autoIncrement"),yo=()=>{if(!a||$t||he.length===0||he.length>100)return;et({idempotencyKey:crypto.randomUUID(),items:he.map((l)=>({op:"insert",values:Object.fromEntries(ra.flatMap((y)=>l.values[y.id]===void 0?[]:[[y.id,l.values[y.id]]]))}))})};if(e.renderRecordContextMenu){let l=he.length===1?he[0]:void 0;return e.renderRecordContextMenu({children:En,recordIds:on,disabled:$t,onDelete:po,...e.onExpandRecord&&l?{onExpand:()=>e.onExpandRecord?.(l)}:{},onCopy:()=>void navigator.clipboard?.writeText(dr()),...a?{onDuplicate:yo}:{}})}if(!i.recordContextMenu)return En;let bo=[...e.onExpandRecord&&he.length===1?[{id:"expand",icon:_(Oe,{name:"expand"}),label:r("Expand record"),onSelect:()=>{let l=he[0];if(l)e.onExpandRecord?.(l)}}]:[],...a?[{id:"duplicate",icon:_(Oe,{name:"copy"}),label:r("Duplicate {count} selected records",{count:he.length}),disabled:$t||he.length===0,onSelect:yo}]:[],{id:"copy",separatorBefore:!0,icon:_(Oe,{name:"copy"}),label:r("Copy cells"),disabled:he.length===0,onSelect:()=>{navigator.clipboard?.writeText(dr())}},...o?[{id:"delete",icon:_(Oe,{name:"trash"}),label:r("Delete {count} selected records",{count:he.length}),separatorBefore:!0,destructive:!0,disabled:$t,onSelect:po}]:[]],ho=e.ui?.ContextMenu;return ho?_(ho,{items:bo,"aria-label":r("Record actions"),children:En}):_(Ui,{block:!0,items:bo,label:r("Record actions"),children:En})}function ll({ui:e,paneRef:t,style:n,children:r,...i}){if(e?.ScrollArea)return e.ScrollArea({viewportRef:t,viewportProps:i,style:n,children:r});return _("div",{ref:t,style:n,...i,children:r})}var dl={position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:0},cl=96,ul=560,Pn=(e)=>Math.max(cl,Math.min(ul,Math.round(e))),pl=({transform:e})=>({...e,y:0});function gl({id:e,disabled:t,children:n}){let{setNodeRef:r,listeners:i,transform:o,isDragging:a}=nl({id:e,disabled:t});return it(()=>{if(!a)return;let d=document.body.style.cursor;return document.body.style.cursor="grabbing",()=>{document.body.style.cursor=d}},[a]),n({setNodeRef:r,listeners:t?void 0:i,style:{...o?{transform:`translate3d(${Math.round(o.x)}px, 0, 0)`}:{},...a?{cursor:"grabbing",zIndex:6,opacity:0.9,background:"var(--accent, #e8f0fe)",boxShadow:"0 2px 10px color-mix(in srgb, currentColor 22%, transparent)"}:{}}})}function ml({descriptor:e,aggregateClient:t,reloadKey:n,ui:r,locale:i,t:o,rows:a,total:d,fields:s,columns:g,width:m,frozenCount:P,frozenLeft:f,view:c,footerRef:S,onChange:R}){let b=pi(e,c,s,a,t,n),u=(v,k,N)=>{let T={...c.footerStats??{}};if(k)T[v]=k;else if(N)T[v]="none";else delete T[v];let{footerStats:C,...L}=c;R(Object.keys(T).length?{...L,footerStats:T}:L)};return Te("div",{ref:S,"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:[_("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
- `}),L("div",{style:{position:"relative",width:u,height:"100%",transform:"translateX(calc(var(--uibot-sx, 0px) * -1))"},children:p.map((k)=>{let y=l[k.index];if(!y)return null;let I=k.index===0,F=C.footerStats?.[y.id],E=F!==void 0?F==="none"?void 0:F:I?"count":void 0,O=E?ei(a,y,E):null,T=(N)=>N===null?"":typeof N==="number"&&E!=="count"&&E!=="filled"&&E!=="empty"?Sr(Math.round(N*100)/100,y):typeof N==="number"?N.toLocaleString(o):Sr(N,y),U=T(O),K=!t?O:E==="count"?d:P.values[`footer${k.index}`]??null,R=!E?"":!t||E==="count"?T(K):P.status==="loading"?"…":P.status==="error"||K===null?"—":T(K),D=E?E==="count"&&I?i("Footer record count",{count:R}):`${i(`Footer ${E}`)} ${R}`.trim():i("Auto summary"),q=k.index<c;return L("div",{"data-uibot-footer-cell":"",style:{position:"absolute",left:q?g(k.index):k.start,width:k.size,height:"100%",boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"flex-end",padding:"0 4px",background:Nn(C.columnColors?.[y.id])?.background??"var(--background, white)",zIndex:q?2:void 0,transform:q?"translateX(var(--uibot-sx, 0px))":void 0,opacity:E?1:0,transition:"opacity 120ms"},children:L(Wo,{ui:r,chevron:!0,quiet:!0,active:!1,label:D,children:(N)=>Ie("div",{style:{display:"grid",gap:2,minWidth:150},children:[L(Ae,{ui:r,variant:E?"ghost":"outline",size:"sm",onClick:()=>{m(y.id,null,I),N()},children:i("No summary")}),Xo(y).map((w)=>L(Ae,{ui:r,variant:E===w?"outline":"ghost",size:"sm",onClick:()=>{m(y.id,w,I),N()},children:i(`Footer ${w}`)},w)),t&&P.status==="error"&&E&&E!=="count"?L("small",{style:{opacity:0.7,padding:"4px 6px"},children:i("Loaded records fallback: {value}",{value:U||"—"})}):null,(!t||P.status==="error")&&d>a.length?L("small",{style:{opacity:0.7,padding:"4px 6px"},children:i("Summaries cover the {count} loaded records.",{count:a.length})}):null]})})},y.id)})})]})}var Kr=44,Gr=36;export{wi as PAGED_COLLECTION_GRID_PRESETS,Gs as PAGED_COLUMN_MAX_WIDTH,Ks as PAGED_COLUMN_MIN_WIDTH,qg as PagedCollectionGrid,gn as PagedHyperlinkInput,Fn as PagedHyperlinkView,Ea as PagedLinkClientProvider,dn as formatPagedDate,cn as formatPagedNumber,wt as instantFromZoned,zs as nextPagedCollectionSort,dt as pagedDateFormatting,dr as pagedDateKind,ln as pagedNumberFormatting,un as pagedOptionSlot,yr as pickerValue,Ut as resolvePagedCollectionGridFeatures,br as storedFromPicker,hr as usePagedLinkClient};
25
+ `}),_("div",{style:{position:"relative",width:m,height:"100%",transform:"translateX(calc(var(--uibot-sx, 0px) * -1))"},children:g.map((v)=>{let k=s[v.index];if(!k)return null;let N=v.index===0,T=c.footerStats?.[k.id],C=T!==void 0?T==="none"?void 0:T:N?"count":void 0,L=C?fi(a,k,C):null,D=(M)=>M===null?"":typeof M==="number"&&C!=="count"&&C!=="filled"&&C!=="empty"?yn(Math.round(M*100)/100,k):typeof M==="number"?M.toLocaleString(i):yn(M,k),B=D(L),j=!t?L:C==="count"?d:b.values[`footer${v.index}`]??null,w=!C?"":!t||C==="count"?D(j):b.status==="loading"?"…":b.status==="error"||j===null?"—":D(j),A=C?C==="count"&&N?o("Footer record count",{count:w}):`${o(`Footer ${C}`)} ${w}`.trim():o("Auto summary"),H=v.index<P;return _("div",{"data-uibot-footer-cell":"",style:{position:"absolute",left:H?f(v.index):v.start,width:v.size,height:"100%",boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"flex-end",padding:"0 4px",background:qn(c.columnColors?.[k.id])?.background??"var(--background, white)",zIndex:H?2:void 0,transform:H?"translateX(var(--uibot-sx, 0px))":void 0,opacity:C?1:0,transition:"opacity 120ms"},children:_(di,{ui:r,chevron:!0,quiet:!0,active:!1,label:A,children:(M)=>Te("div",{style:{display:"grid",gap:2,minWidth:150},children:[_(Ie,{ui:r,variant:C?"ghost":"outline",size:"sm",onClick:()=>{u(k.id,null,N),M()},children:o("No summary")}),mi(k).map((q)=>_(Ie,{ui:r,variant:C===q?"outline":"ghost",size:"sm",onClick:()=>{u(k.id,q,N),M()},children:o(`Footer ${q}`)},q)),t&&b.status==="error"&&C&&C!=="count"?_("small",{style:{opacity:0.7,padding:"4px 6px"},children:o("Loaded records fallback: {value}",{value:B||"—"})}):null,(!t||b.status==="error")&&d>a.length?_("small",{style:{opacity:0.7,padding:"4px 6px"},children:o("Summaries cover the {count} loaded records.",{count:a.length})}):null]})})},k.id)})})]})}var Qr=44,Xr=36;export{Vi as PAGED_COLLECTION_GRID_PRESETS,ul as PAGED_COLUMN_MAX_WIDTH,cl as PAGED_COLUMN_MIN_WIDTH,ym as PagedCollectionGrid,Cn as PagedHyperlinkInput,zn as PagedHyperlinkView,Wa as PagedLinkClientProvider,un as formatPagedDate,pn as formatPagedNumber,wt as instantFromZoned,al as nextPagedCollectionSort,dt as pagedDateFormatting,hr as pagedDateKind,cn as pagedNumberFormatting,gn as pagedOptionSlot,Sr as pickerValue,Dt as resolvePagedCollectionGridFeatures,Ir as storedFromPicker,Ar as usePagedLinkClient};