@uibot/renderer-react 0.6.0 → 0.7.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.
- package/dist/collection-application.js +1 -1
- package/dist/collection-approval.d.ts +5 -0
- package/dist/collection-editors.js +1 -1
- package/dist/collection-views/ai-fill-model.d.ts +23 -1
- package/dist/collection-views.js +9 -9
- package/dist/collection-workspace.js +13 -13
- package/dist/index.js +1 -1
- package/dist/paged-collection-grid.js +1 -1
- package/package.json +4 -4
package/dist/collection-views.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
function dl(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var Tt=["blue","green","red","orange","gray","teal","purple"];function Yr(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 wo(e,t,n){if(!t?.length)return[];return t.map((i)=>{if(i.fn==="count")return{fieldId:i.fieldId,fn:"count",value:e.length};let r=n.find((d)=>d.id===i.fieldId),a=r?.type==="number"||r?.type==="rating"||r?.type==="autoNumber"?e.reduce((d,l)=>d+(Yr(l.values[i.fieldId])??0),0):0;return{fieldId:i.fieldId,fn:"sum",value:a}})}function Ro(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function Gr(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function Jr(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 So(e,t){if(!t)return!0;if(Ro(t)){let n=t.filterSet.map((i)=>Ro(i)?So(e,i):Gr(i)?Jr(e,i):!1);return t.conjunction==="or"?n.some(Boolean):n.every(Boolean)}return Object.entries(t).every(([n,i])=>{if(n==="conjunction"||n==="filterSet")return!0;return e.values[n]===i})}function Io(e,t,n,i){let r=e.views.find((p)=>p.id===n)??e.views[0];if(!r)return{view:{id:n,name:n,kind:"table"},columns:e.fields,rows:[...t]};let o=[...t];if(r.filter)o=o.filter((p)=>So(p,r.filter));if(r.sort?.length)o.sort((p,C)=>{for(let b of r.sort??[]){let y=p.values[b.fieldId],m=C.values[b.fieldId];if(y===m)continue;if(y==null)return 1;if(m==null)return-1;let h=e.fields.find((I)=>I.id===b.fieldId)?.type,f=(I)=>{if(["number","rating","autoNumber"].includes(h??"")&&typeof I==="number")return I;if(["date","createdTime","lastModifiedTime"].includes(h??"")){let v=Date.parse(String(I));if(Number.isFinite(v))return v}return String(I)},x=f(y),w=f(m);if(x===w)continue;let S=x<w?-1:1;return b.direction==="desc"?-S:S}return p.id<C.id?-1:p.id===C.id?0:1});let a=r.projection?.length?e.fields.filter((p)=>r.projection?.includes(p.id)):e.fields,d=i?.search?.trim().toLowerCase();if(d)o=o.filter((p)=>a.some((C)=>String(p.values[C.id]??"").toLowerCase().includes(d)));let l=wo(o,r.aggregates,e.fields),c=r.group?.fieldId;if(!c)return{view:r,columns:a,rows:o,...l.length?{aggregates:l}:{}};let s=[],u=new Map;for(let p of o){let C=String(p.values[c]??"");if(!u.has(C))u.set(C,[]),s.push(C);u.get(C)?.push(p)}let g=s.map((p)=>{let C=u.get(p)??[];return{key:p,fieldId:c,rows:C,aggregates:wo(C,r.aggregates,e.fields)}});return{view:r,columns:a,rows:o,groups:g,...l.length?{aggregates:l}:{}}}var sn=500,Bn=2000,Un=new Set(["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"]);function Me(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function Ct(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 Ao=["short","medium","tall","extra"];function hl(e,t){return t.map((n)=>{let i={},r={};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}.`);i[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}.`);r[o]=d}return{groups:i,values:r}})}var Zr=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,Qr=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function Do(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function Ve(e,t){return{code:e,...t}}function Xr(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function Vn(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function Fo(e,t){if(t.aggregates.length===0)return Ve("empty");if(t.aggregates.length>8||t.groupBy.length>3)return Ve("too_many");let n=new Set;for(let r of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(r.fn))return Ve("function");if(!Zr.test(r.as)||n.has(r.as)||t.groupBy.includes(r.as))return Ve("alias",{alias:r.as,...r.fieldId!==void 0?{fieldId:r.fieldId}:{}});if(n.add(r.as),r.fn==="count"&&r.fieldId===void 0)continue;let o=e.fields.find((a)=>a.id===r.fieldId);if(!o)return Ve(r.fn==="sum"?"sum_field":"unknown_field",{alias:r.as,...r.fieldId!==void 0?{fieldId:r.fieldId}:{}});if(r.fn==="sum"&&!Vn(o))return Ve("sum_field",{fieldId:o.id,alias:r.as});if(r.fn==="avg"&&!Vn(o))return Ve("numeric_field",{fieldId:o.id,alias:r.as});if((r.fn==="min"||r.fn==="max")&&!Vn(o)&&o.type!=="date"&&!((o.type==="formula"||o.type==="rollup")&&o.resultType==="date"))return Ve("extrema_field",{fieldId:o.id,alias:r.as});if((r.fn==="filled"||r.fn==="empty")&&!Ct(o))return Ve("queryable_field",{fieldId:o.id,alias:r.as});if(r.fn==="count"&&!Ct(o))return Ve("count_field",{fieldId:o.id,alias:r.as})}let i=new Set;for(let r of t.groupBy){if(i.has(r))return Ve("duplicate_group",{fieldId:r});i.add(r);let o=e.fields.find((a)=>a.id===r);if(!o)return Ve("unknown_field",{fieldId:r});if(!Qr.has(o.type)&&!Xr(o))return Ve("not_groupable",{fieldId:r})}return null}var Eo=(e)=>String(e).padStart(2,"0");function Ze(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),i=(r)=>Number(n.find((o)=>o.type===r)?.value??0);return{year:i("year"),month:i("month"),day:i("day"),hour:i("hour"),minute:i("minute"),second:i("second")}}function ht(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 i=n;for(let r=0;r<2;r++){let o=Ze(new Date(i),t),a=Date.UTC(o.year,o.month-1,o.day,o.hour,o.minute,o.second);i+=n-a}return new Date(i)}function dn(e,t){let n=Ze(e,t??"UTC");return`${n.year}-${Eo(n.month)}-${Eo(n.day)}`}function Jt(e,t=new Date,n){let i={};for(let r of e){let o=r.defaultValue;if(!o)continue;if(o.kind==="value")i[r.id]=Array.isArray(o.value)?[...o.value]:o.value;else if(r.type==="date"){let a=r.formatting;if(a&&"time"in a&&a.time==="none"){let d=Ze(t,n);i[r.id]=`${d.year}-${String(d.month).padStart(2,"0")}-${String(d.day).padStart(2,"0")}`}else i[r.id]=t.toISOString()}}return i}var qn=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],cn=new Set(["pastDays","nextDays","daysAgo","daysFromNow"]),To={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"]},Mt=new Set(["isEmpty","isNotEmpty"]);function Ke(e){switch(e.type){case"singleLineText":case"longText":return"text";case"number":return"number";case"checkbox":return"checkbox";case"date":return"date";case"singleSelect":return"singleSelect";case"multipleSelect":return"multipleSelect";case"relation":return"relation";case"formula":case"rollup":return e.resultType==="text"?"text":e.resultType==="number"?"number":e.resultType==="date"?"date":null;default:return null}}function Mo(e){let t=Ke(e);return t?To[t]:[]}var _n=/^\d{4}-\d{2}-\d{2}$/,ei=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function $n(e){if(!ei(e))return!1;let t=e.mode;if(!qn.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&&_n.test(e.date);if(t==="dateRange")return typeof e.date==="string"&&_n.test(e.date)&&typeof e.to==="string"&&_n.test(e.to)&&e.date<=e.to;if(cn.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function No(e,t){if(!e)return"unknown field";let n=Ke(e),i=t.operator==="contains"&&(n==="number"||n==="checkbox"||n==="date"||n==="singleSelect");if(!n||!(To[n].includes(t.operator)||i))return"operator not allowed";if(Mt.has(t.operator))return null;let r=t.value;if(i)return n==="number"?typeof r==="number"&&Number.isFinite(r)?null:"number required":n==="checkbox"?typeof r==="boolean"?null:"boolean required":typeof r==="string"?null:"text required";switch(n){case"text":return typeof r==="string"?null:"text value required";case"number":return typeof r==="number"&&Number.isFinite(r)?null:"number required";case"checkbox":return typeof r==="boolean"?null:"boolean required";case"singleSelect":return typeof r==="string"?null:"option required";case"relation":return typeof r==="string"&&r!==""?null:"record required";case"multipleSelect":return typeof r==="string"||Array.isArray(r)&&r.every((o)=>typeof o==="string")?null:"options required";case"date":return $n(r)||typeof r==="string"&&Number.isFinite(Date.parse(r))?null:"date required"}}var ti={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},Yl=Array.from(new Set(Object.values(ti).flat()));var Zl=Object.freeze([Object.freeze({name:"manifest",summary:"Describe query operations and list the derived resource index.",positionals:Object.freeze([]),options:Object.freeze([])}),Object.freeze({name:"search",summary:"Search resources with deterministic bilingual ranking and reasons.",positionals:Object.freeze([Object.freeze({name:"text",property:"text",type:"string",required:!1})]),options:Object.freeze([Object.freeze({name:"kind",property:"kinds",type:"resource-kind",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"tag",property:"tags",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"category",property:"categories",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"capability",property:"capabilities",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"maturity",property:"maturities",type:"resource-maturity",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"limit",property:"limit",type:"positive-integer"})])}),Object.freeze({name:"get",summary:"Resolve one canonical resource id or unambiguous alias.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([])}),Object.freeze({name:"build",summary:"Plan dependency closure and gaps without writing or installing.",positionals:Object.freeze([Object.freeze({name:"root",property:"roots",type:"string",required:!0,variadic:!0})]),options:Object.freeze([])})]);function ni(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function ns(e,t){if(t===e.draft)return e;return{...e,draft:t}}function oi(e){return e.draft!==e.savedContent}function os(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 rs(e,t){if(oi(e))return e;let n=ni(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 ot=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),vt=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),xt=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,Lo=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,un=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),Oo=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every(un)&&new Set(e).size===e.length;function ri(e){if(!ot(e)||!vt(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!un(e.id)||!xt(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)=>!ot(t)||!vt(t,["id","name"])||!un(t.id)||!xt(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,i]of[["linkedRecord","link",["collectionId","displayFieldId"]],["lookup","lookup",["linkFieldId","targetFieldId"]],["formula","formula",["expression"]],["rollup","rollup",["linkFieldId","targetFieldId","function"]]]){let r=e[n];if(e.type===t!==(r!==void 0))return!1;if(r!==void 0&&(!ot(r)||!vt(r,[...i])||i.some((o)=>!xt(r[o],o==="expression"?2048:512))))return!1}return!0}function as(e){if(!ot(e)||!vt(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))||!xt(e.collectionId,512)||!xt(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(!ot(t)||!vt(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!xt(t.name,200)||!Lo(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(ri)||new Set(t.fields.map((o)=>o.id)).size!==t.fields.length)return!1;if(!ot(n)||!vt(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!un(n.id)||!xt(n.name,200)||!Lo(n.version)||!Oo(n.columnOrder)||!Oo(n.hiddenColumns)||!ot(n.columnWidths)||Object.values(n.columnWidths).some((o)=>typeof o!=="number"||!Number.isInteger(o)||o<72||o>800))return!1;let i=t.fields,r=(o)=>i.some((a)=>ot(a)&&a.id===o);if([...n.columnOrder,...n.hiddenColumns,...Object.keys(n.columnWidths)].some((o)=>!r(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)=>!ot(o)||!vt(o,["fieldId","direction"])||!r(o.fieldId)||!["asc","desc"].includes(String(o.direction)))))return!1;return!0}import{createContext as ii,useCallback as ai,useContext as li,useLayoutEffect as zn,useMemo as si,useRef as Vo,useState as di}from"react";var ci=ii(void 0);function Nt(e,t={}){let n=li(ci),i=Vo({}),{dirty:r,busy:o}=e,{onDirtyChange:a,onBusyChange:d}=t;zn(()=>{n?.(i.current,{dirty:r,busy:o}),a?.(r),d?.(o)},[n,r,o,a,d]),zn(()=>()=>{n?.(i.current),a?.(!1),d?.(!1)},[n,a,d])}function rd(){let e=Vo(new Map),[t,n]=di({dirty:!1,busy:!1}),i=ai((r,o)=>{if(o)e.current.set(r,o);else e.current.delete(r);let a=[...e.current.values()],d=a.some((c)=>c.dirty),l=a.some((c)=>c.busy);n((c)=>c.dirty===d&&c.busy===l?c:{dirty:d,busy:l})},[]);return{...t,report:i}}function pn(e,t){let n=si(()=>({active:!0,client:e,id:t}),[e,t]);return zn(()=>(n.active=!0,()=>{n.active=!1}),[n]),n}import{useEffect as Sn,useRef as on,useState as qe}from"react";import{useId as Ki,useState as Qn}from"react";var We=(e)=>String(e).padStart(2,"0"),ui=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function Ne(e){let t=e.formatting;return ui(e)&&t&&"date"in t?t:void 0}function gn(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function Bo(e){let t=Ne(e);return!t?"auto":t.time==="none"?"date":"datetime"}function jn(e,t,n,i){switch(i){case"YYYY/MM/DD":return`${e}/${We(t)}/${We(n)}`;case"MM/DD/YYYY":return`${We(t)}/${We(n)}/${e}`;case"DD/MM/YYYY":return`${We(n)}/${We(t)}/${e}`;case"YYYY年M月D日":return`${e}年${t}月${n}日`;default:return`${e}-${We(t)}-${We(n)}`}}function Lt(e,t){let n=e==null?"":String(e);if(!n)return"";let i=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n);if(t.time==="none"){if(i)return jn(Number(i[1]),Number(i[2]),Number(i[3]),t.date);let d=new Date(n);if(!Number.isFinite(d.getTime()))return n;let l=Ze(d,t.timeZone??"UTC");return jn(l.year,l.month,l.day,t.date)}let r=i?ht({year:Number(i[1]),month:Number(i[2]),day:Number(i[3])},t.timeZone):new Date(n);if(!Number.isFinite(r.getTime()))return n;let o=Ze(r,t.timeZone),a=jn(o.year,o.month,o.day,t.date);if(t.time==="12h"){let d=o.hour%12||12;return`${a} ${d}:${We(o.minute)} ${o.hour<12?"AM":"PM"}`}return`${a} ${We(o.hour)}:${We(o.minute)}`}function mn(e,t){if(e==null||e==="")return"";let n=typeof e==="number"?e:Number(e);if(!Number.isFinite(n))return String(e);let i=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:i,maximumFractionDigits:i,useGrouping:t.grouping!==!1}).format(n)}function fn(e,t){let n=e?.findIndex((o)=>o.id===t)??-1,i=n>=0?e?.[n]?.color:void 0,r=Tt.findIndex((o)=>o===i);return r>=0?r:n}var pi={"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 生成此字段","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":"修改字段","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 K(e="en"){return(t,n={})=>(e==="zh-CN"?pi[t]??t:t).replace(/\{(\w+)\}/g,(i,r)=>String(n[r]??i))}function ud(e,t,n,i,r=!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=i-1;if(t==="Tab"){let d=Math.max(0,Math.min(n*i-1,o*i+a+(r?-1:1)));o=Math.floor(d/i),a=d%i}return{row:Math.max(0,Math.min(n-1,o)),column:Math.max(0,Math.min(i-1,a))}}function gi(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 Ye(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function pd(e,t,n,i){let r=gi(n,i),o=[];for(let a=r.firstRow;a<=r.lastRow;a++){let d=[];for(let l=r.firstColumn;l<=r.lastColumn;l++){let c=t[l],s=e[a]?.values[c?.id??""],u=c?.type==="json"&&s!=null?JSON.stringify(s):Ye(s);d.push(/[\t\r\n"]/.test(u)?`"${u.replaceAll('"','""')}"`:u)}o.push(d.join("\t"))}return o.join(`
|
|
2
|
-
`)}function mi(e,t="en"){let n=K(t),
|
|
3
|
-
`||l==="\r")){if(
|
|
4
|
-
`)d++}}else o+=l}if(a)throw Error(n("Unclosed quoted cell."));if(o||r.length||i.length===0)r.push(o),i.push(r);return i}function dt(e,t,n="en"){let i=K(n);if(t.type==="blob")throw Error(i("{name} is read-only; its original bytes are preserved.",{name:t.name}));if(t.type==="relation")throw Error(i("{name} needs a server-provided option.",{name:t.name}));if(t.type==="lookup"||t.type==="formula"||t.type==="rollup")throw Error(i("{name} is read only.",{name:t.name}));if(t.type==="linkedRecord")throw Error(i("Use the {name} record picker.",{name:t.name}));if(e===""){if(t.required)throw Error(i("{name} is required.",{name:t.name}));return null}if(t.type==="number"){let o=Number(e);if(!e.trim()||!Number.isFinite(o))throw Error(i("{name} needs a number.",{name:t.name}));return o}if(t.type==="json")try{return JSON.parse(e)}catch{throw Error(i("{name} needs valid JSON.",{name:t.name}))}if(t.type==="bigint"){if(!/^-?\d+$/.test(e))throw Error(i("{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(i("{name} needs true or false.",{name:t.name}))}if(t.type==="date"){let o=Ne(t);if(o){let w=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!w)throw Error(i("{name} needs a date.",{name:t.name}));let[,S,I,v]=w,P=new Date(Date.UTC(Number(S),Number(I)-1,Number(v)));if(P.getUTCMonth()!==Number(I)-1||P.getUTCDate()!==Number(v))throw Error(i("{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 dn(new Date(e),o.timeZone);return`${S}-${I}-${v}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return ht({year:Number(S),month:Number(I),day:Number(v)},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(i("{name} needs a date.",{name:t.name}));let[,d,l,c,s,u,g,p,C]=a,b=Number(d),y=Number(l),m=Number(c),f=[31,b%4===0&&(b%100!==0||b%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(y<1||y>12||m<1||m>(f[y-1]??0)||Number(s??0)>23||Number(u??0)>59||Number(g??0)>59||Number(p??0)>23||Number(C??0)>59)throw Error(i("{name} needs a valid calendar date.",{name:t.name}));let x=new Date(e);if(!Number.isFinite(x.getTime()))throw Error(i("{name} needs a date.",{name:t.name}));return x.toISOString()}let r=(o)=>{let a=t.options?.find((d)=>d.id===o||d.name===o);if(!a)throw Error(i("{name} has no option '{option}'.",{name:t.name,option:o}));return a.id};if(t.type==="singleSelect")return r(e);if(t.type==="multipleSelect")return[...new Set(e.split(",").map((o)=>r(o.trim())))];return e}function gd(e,t,n,i,r="en"){let o=K(r);try{if(e.length>1048576)throw Error(o("Paste is too large."));let a=mi(e,r);if(a.length>100||i.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((l,c)=>{if(i.column+l.length>n.length)throw Error(o("Paste extends beyond the visible columns."));let s=t[i.row+c];if(!s)throw Error(o("Row is not loaded."));let u={};return l.forEach((g,p)=>{let C=n[i.column+p];if(C?.generation==="autoIncrement")throw Error(o("{name} is auto-generated and cannot be edited.",{name:C.name}));if(C)u[C.id]=dt(g,C,r)}),{op:"update",id:s.id,expectedVersion:s.version,values:u}})}}catch(a){return{ok:!1,message:a instanceof Error?a.message:o("Invalid paste.")}}}function Uo(e,t){let n=Ye(e);if(!/^\d{4}-\d{2}-\d{2}T/.test(n))return n;let i=new Date(n);if(!Number.isFinite(i.getTime()))return n;let r=new Intl.DateTimeFormat("en-CA",{...t?{timeZone:t}:{},year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(i),o=(c)=>r.find((s)=>s.type===c)?.value??"",a=i.getUTCMilliseconds(),d=o("second"),l=d!=="00"||a?`:${d}${a?`.${String(a).padStart(3,"0")}`:""}`:"";return`${o("year")}-${o("month")}-${o("day")} ${o("hour")}:${o("minute")}${l}`}import{useEffect as fi,useRef as yi,useState as Ot}from"react";import{jsx as Ge,jsxs as Zt}from"react/jsx-runtime";function Vt(e){if(e==null)return"—";if(Array.isArray(e))return e.map(Vt).join(", ");return String(e)}function Qt(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((i)=>i.label||i.id).join(", "):void 0)??Vt(e.values[t.id])}function Cd(e,t){return Ye(e.values[t.id])}function _o({field:e,value:t,labels:n=[],client:i,onChange:r,disabled:o=!1,locale:a,"aria-describedby":d,"aria-invalid":l}){let c=K(a),s=Array.isArray(t)?t.filter((F)=>typeof F==="string"):[],u=yi(new Set(s));u.current=new Set(s);let[g,p]=Ot(""),[C,b]=Ot(),[y,m]=Ot([]),[h,f]=Ot(0),[x,w]=Ot({}),[S,I]=Ot({rows:[],next:null,error:"",loading:!0}),v=e.link?.collectionId,P=e.link?.displayFieldId;fi(()=>{let F=!0;if(I({rows:[],next:null,error:"",loading:!0}),!i||!v||!P){I({rows:[],next:null,error:c("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return i.query(v,{limit:50,search:g,...C?{cursor:C}:{}}).then((D)=>{if(!F)return;if(!D.ok){I({rows:[],next:null,error:D.error.message,loading:!1});return}w((N)=>({...Object.fromEntries(Object.entries(N).filter(([A])=>u.current.has(A))),...Object.fromEntries(D.data.items.map((A)=>{let O=String(A.values[P]??"");return[A.id,O.trim()?O.slice(0,256):A.id]}))})),I({rows:D.data.items,next:D.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(F)I({rows:[],next:null,error:c("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{F=!1}},[i,v,P,g,C,h]);let E=(F)=>x[F]??n.find((D)=>D.id===F)?.label??F;return Zt("fieldset",{disabled:o,"aria-label":c("{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:[Ge("div",{className:"flex flex-wrap gap-1",children:s.map((F)=>Zt("span",{className:"rounded border px-2 py-1 text-sm",children:[E(F)," ",Ge("button",{type:"button","aria-label":c("Remove {name}",{name:E(F)}),onClick:()=>r(s.filter((D)=>D!==F)),children:"×"})]},F))}),Ge("input",{"aria-label":c("Search {name} records",{name:e.name}),type:"search",placeholder:c("Search linked records"),value:g,onChange:(F)=>{p(F.target.value),b(void 0),m([])}}),S.loading&&Ge("p",{role:"status",children:c("Loading linked records…")}),S.error&&Zt("div",{role:"alert",children:[S.error," ",Ge("button",{type:"button",onClick:()=>f((F)=>F+1),children:c("Retry linked records")})]}),Ge("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:S.rows.map((F)=>Zt("label",{className:"flex items-center gap-2 text-sm",children:[Ge("input",{type:"checkbox","aria-label":c("Link {name}",{name:E(F.id)}),checked:s.includes(F.id),disabled:!s.includes(F.id)&&s.length>=100,onChange:(D)=>r(D.target.checked?[...s,F.id]:s.filter((N)=>N!==F.id))}),E(F.id)]},F.id))}),!S.loading&&!S.error&&!S.rows.length&&Ge("p",{children:c("No matching records.")}),Zt("div",{className:"flex gap-2",children:[Ge("button",{type:"button",disabled:!y.length||S.loading,onClick:()=>{b(y.at(-1)),m((F)=>F.slice(0,-1))},children:c("Previous linked records")}),Ge("button",{type:"button",disabled:!S.next||S.loading,onClick:()=>{m((F)=>[...F,C]),b(S.next??void 0)},children:c("Next linked records")})]}),Ge("small",{children:c("{count} selected · up to 100 per record across all link fields",{count:s.length})})]})}var bi={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function yn(e,t,n){return t?K(n)(bi[t]):e==null?"—":String(e)}function qo(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((i)=>({id:`option:${i.id}`,name:i.name,value:i.id})):[],{id:"null",name:t("Unassigned"),value:null}]}function $o(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function bn(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function zo(e,t,n){let i=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...bn(e),filter:$o(e.filter,i)}}function Xt(e,t=(n)=>n){if(!/^\d{4}-\d{2}$/.test(e))throw Error(t("Choose a valid month."));let[n,i]=e.split("-").map(Number);if(!n||n>9998||!i||i>12)throw Error(t("Choose a valid month."));let r=new Date(`${e}-01T00:00:00.000Z`),o=new Date(r);return o.setUTCMonth(o.getUTCMonth()+1),{start:r.toISOString(),end:o.toISOString(),days:Math.round((o.getTime()-r.getTime())/86400000),weekday:r.getUTCDay()}}function jo(e,t,n){let{start:i,end:r}=Xt(n);return{...bn(e),filter:$o(e.filter,{fieldId:t,operator:"onOrAfter",value:i},{fieldId:t,operator:"before",value:r})}}function Cn(e,t){let n={id:"date",name:"Date",type:"date"},i=String(dt(t,n)),r=String(dt(String(e),n));return`${i.slice(0,10)}${r.slice(10)}`}function Pt(e,t){return[...t.columnOrder,...e.map((i)=>i.id).filter((i)=>!t.columnOrder.includes(i))].filter((i)=>!t.hiddenColumns.includes(i)).flatMap((i)=>e.filter((r)=>r.id===i))}function ze(e,t){let n=t.find((i)=>i.type==="singleLineText"||i.type==="longText");return(n?Ye(e.values[n.id]):"")||e.id}function hn(e,t,n){if(t.type==="lookup")return Vt(e);if(t.type==="date"){let i=Ne(t);return i?Lt(e,i):Uo(e)}if(t.type==="number"){let i=gn(t);return i?mn(e,i):Ye(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return yn(e,n);if(t.type==="singleSelect"||t.type==="multipleSelect")return(Array.isArray(e)?e:e==null?[]:[e]).map((r)=>t.options?.find((o)=>o.id===r)?.name??String(r)).join(", ");return Ye(e)}import{useEffect as Yo,useId as hi,useMemo as vi,useRef as xi,useState as Go}from"react";var Ci=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function ct(e){return Ci.test(e)}var rt=(e)=>String(e).padStart(2,"0");function Ho(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${rt(t.getMonth()+1)}-${rt(t.getDate())}T${rt(t.getHours())}:${rt(t.getMinutes())}:${rt(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var Hn=(e,t)=>{let n=Ze(e,t);return`${n.year}-${rt(n.month)}-${rt(n.day)}T${rt(n.hour)}:${rt(n.minute)}`};function Ko(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!ct(e))return e.slice(0,10);return Hn(new Date(e),t.timeZone??"UTC").slice(0,10)}if(ct(e))return Hn(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function Wo(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||ct(t)))return e;let r=e.length>10?e.slice(11,16):t&&ct(t)?Hn(new Date(t),n.timeZone).slice(11,16):"00:00",[o,a,d]=e.slice(0,10).split("-").map(Number),[l,c]=r.split(":").map(Number),s=ht({year:o??0,month:a??1,day:d??1,hour:l??0,minute:c??0},n.timeZone);return Number.isFinite(s.getTime())?s.toISOString():e}import{jsx as kt,jsxs as Jo}from"react/jsx-runtime";function Kn(e,t,n){if(e.type==="blob")return"";try{return dt(t,e),""}catch{if(t===""&&e.required)return n==="zh-CN"?`请填写${e.name}。`:`${e.name} is required.`;if(e.type==="number")return n==="zh-CN"?`${e.name}需要有效数字。`:`${e.name} needs a number.`;if(e.type==="bigint")return n==="zh-CN"?`${e.name}必须是整数。`:`${e.name} needs an integer.`;if(e.type==="date")return n==="zh-CN"?`${e.name}需要有效日期。`:`${e.name} needs a valid date.`;if(e.type==="checkbox")return n==="zh-CN"?`${e.name}请选择是或否。`:`${e.name} needs true or false.`;if(e.type==="json")return n==="zh-CN"?`${e.name}必须是有效 JSON。`:`${e.name} needs valid JSON.`;return n==="zh-CN"?"输入值无效":"Invalid value"}}function Nd({field:e,text:t,disabled:n,id:i,label:r,ariaLabel:o,onChange:a,onSave:d,onCancel:l,locale:c="en",submitted:s=!1,describedBy:u}){let g=vi(()=>K(c),[c]),p=hi(),C=xi(null),b=Boolean(d);Yo(()=>{if(b)C.current?.querySelector("input,textarea,select")?.focus()},[b]);let y=i??p,m=`${y}-error`,[h,f]=Go(t),[x,w]=Go(!1);Yo(()=>f(t),[t]);let S=Kn(e,h,c),v=Boolean(e.required&&h===""&&S)&&!x&&!s?"":S,P=o??r??e.name,E=e.type==="date"&&ct(h),F=E&&!S?Ho(h):h,D=[u,v?m:void 0].filter(Boolean).join(" "),N={id:y,"aria-label":P,"aria-invalid":Boolean(v),...D?{"aria-describedby":D}:{},disabled:n,onBlur:()=>w(!0),onKeyDown:(R)=>{if(d||l)R.stopPropagation();let L=e.type==="longText"||e.type==="json";if(R.key==="Tab"&&d)R.preventDefault(),d(R.shiftKey?"previous":"next");else if(R.key==="Enter"&&!R.shiftKey&&d&&(!L||R.ctrlKey||R.metaKey))R.preventDefault(),d();else if(R.key==="Escape"&&l)R.preventDefault(),l()},style:{width:"100%",...b?{height:"100%",border:0,borderRadius:0,outline:"none",boxShadow:"none",padding:"0 7px",boxSizing:"border-box",font:"inherit"}:{},background:"var(--background, white)",color:"inherit"},className:"min-w-0 rounded-md border border-[var(--uibot-border,#d4d4d8)] bg-[var(--uibot-surface,#fff)] px-2 py-1 text-sm text-[var(--uibot-text,#18181b)] disabled:cursor-not-allowed disabled:opacity-60"},A=(R)=>{w(!0),f(R),a(R)},O=(R)=>{if(e.type==="date"&&E&&R){let L=new Date(R);A(Number.isFinite(L.getTime())?L.toISOString():R)}else A(R)},V;if(e.type==="checkbox")V=Jo("select",{...N,value:h,onChange:(R)=>A(R.currentTarget.value),children:[!e.required&&kt("option",{value:"",children:g("No value")}),kt("option",{value:"true",children:g("Yes")}),kt("option",{value:"false",children:g("No")})]});else if(e.type==="longText"||e.type==="json")V=kt("textarea",{...N,value:h,rows:e.type==="json"?4:3,onChange:(R)=>A(R.currentTarget.value)});else{let R=e.type==="date"&&!(S&&h)?E?"datetime-local":"date":"text",L=e.type==="blob";V=kt("input",{...N,type:R,inputMode:e.type==="number"?"decimal":void 0,step:E?"0.001":void 0,value:F,readOnly:L,onInput:e.type==="date"?(W)=>O(W.currentTarget.value):void 0,onChange:(W)=>O(W.currentTarget.value)})}return Jo("div",{ref:C,className:"grid min-w-0 gap-1",style:b?{height:"100%"}:void 0,children:[r&&kt("label",{className:"text-xs font-medium",htmlFor:y,children:r}),V,v&&kt("span",{id:m,role:"alert",className:"text-xs text-red-600",children:v})]})}import{useEffect as ki,useRef as wi}from"react";import{jsx as Zo}from"react/jsx-runtime";var Pi={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 Fe({name:e,size:t=15,style:n}){return Zo("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:Zo("path",{d:Pi[e]})})}import{jsx as ut,jsxs as Qo,Fragment as Ri}from"react/jsx-runtime";var Bt={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function Y({ui:e,style:t,variant:n,size:i,children:r,disabled:o,onClick:a,title:d,ariaLabel:l,icon:c,iconOnly:s,badge:u}){let g=e?.Button,p=c?Qo("span",{style:{position:"relative",display:"inline-flex"},children:[ut(Fe,{name:c}),u?ut("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,C=s?p:Qo(Ri,{children:[p,r]}),b=l,y=d??(s?b:void 0),m=s?"icon":i;if(g)return ut(g,{...n?{variant:n}:{},...m?{size:m}:{},disabled:o,onClick:a,title:y,"aria-label":b,children:C});return ut("button",{type:"button",style:{...c?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?Bt:{},...s?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:o,onClick:a,title:y,"aria-label":b,children:C})}function Pe({ui:e,value:t,options:n,onChange:i,disabled:r,label:o,style:a,"aria-describedby":d,"aria-invalid":l}){let c=e?.Select,s={...d?{"aria-describedby":d}:{},...l?{"aria-invalid":!0}:{}};if(c)return ut(c,{value:t,options:n,onChange:i,disabled:r,"aria-label":o,...s});return ut("select",{"aria-label":o,...s,style:a,disabled:r,value:t,onChange:(u)=>i(u.target.value),children:n.map((u)=>ut("option",{value:u.value,disabled:u.disabled,children:u.label},u.value))})}function Xo({label:e,busy:t,onCancel:n,children:i,alert:r=!1}){let o=wi(null);return ki(()=>{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})}},[]),ut("dialog",{ref:o,role:r?"alertdialog":"dialog","aria-modal":"true","aria-label":e,style:{position:"fixed",inset:0,margin:"auto",maxWidth:"min(440px, calc(100vw - 32px))",maxHeight:"80vh",overflow:"auto",boxSizing:"border-box",padding:20,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"inherit",font:"inherit"},onKeyDown:(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((u)=>!u.hidden),c=l[0],s=l.at(-1);if(!c||(a.shiftKey?document.activeElement===c:document.activeElement===s)||!d.contains(document.activeElement)){if(a.preventDefault(),(a.shiftKey?s:c)?.focus(),!c)d.focus()}},tabIndex:-1,onCancel:(a)=>{if(a.preventDefault(),!t)n()},children:i})}import{useEffect as er,useRef as en,useState as Qe}from"react";import{jsx as G,jsxs as ie,Fragment as Di}from"react/jsx-runtime";function Si(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 Ii=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function Ai({descriptor:e,fieldIds:t,query:n,client:i,readOnly:r=!1,reloadKey:o=0,onImported:a,onRefreshSchema:d}){let[l,c]=Qe(null),[s,u]=Qe(null),[g,p]=Qe(null),[C,b]=Qe([]),[y,m]=Qe(""),[h,f]=Qe(!1),[x,w]=Qe(!1),[S,I]=Qe(!0),[v,P]=Qe(null),[E,F]=Qe(!1),D=en(!1),N=en(!1),A=en(!1),O=en(null),V=en({client:i,onImported:a,descriptor:e});V.current={client:i,onImported:a,descriptor:e},er(()=>(D.current=!0,()=>{D.current=!1,N.current=!1}),[]),er(()=>{let T=!0;if(!r)i.imports(e.id).then((B)=>{if(!T||!D.current||!B.ok)return;if(b((ee)=>B.data.map((se)=>{let Re=ee.find((z)=>z.id===se.id);return Re&&Re.version>se.version?Re:se})),!A.current)p((ee)=>{let se=B.data.find((Re)=>Re.id===ee?.id);return ee&&se&&se.version>ee.version?se:ee})});return()=>{T=!1}},[i,e.id,r,o]);let R=(T)=>{p(T),b((B)=>[T,...B.filter((ee)=>ee.id!==T.id)].slice(0,50)),P(null)};async function L(T){if(A.current||r)return;A.current=!0,N.current=!0,f(!0),w(!0),m("");let B=T;try{while(D.current&&N.current&&B.status==="ready"){let ee=await V.current.client.advanceImport(e.id,B.id,B.version);if(!D.current)break;if(!ee.ok){m(ee.error.message);break}let se=ee.data;if(R(se),se.importedRows>B.importedRows)V.current.onImported();if(se.version===B.version&&se.status==="ready"){m("Import paused. Refresh the saved progress before retrying.");break}B=se}}finally{if(A.current=!1,N.current=!1,D.current)f(!1),w(!1)}}async function W(){if(!l||A.current)return;A.current=!0,f(!0),m("");let T=await i.previewImport(e.id,{...l,expectedSchemaVersion:e.schemaVersion});if(A.current=!1,!D.current)return;if(f(!1),T.ok)u(T.data),c({...l,expectedSchemaVersion:T.data.schemaVersion,mapping:T.data.mapping});else m(T.error.message)}async function le(){if(!l||!s||s.missingRequiredFieldIds.length||!s.totalRows||A.current||r)return;A.current=!0,f(!0),m(""),O.current??=crypto.randomUUID();let T=await i.createImport(e.id,{...l,idempotencyKey:O.current});if(A.current=!1,!D.current)return;if(f(!1),T.ok)R(T.data),c(null),u(null),O.current=null,L(T.data);else m(T.error.message)}async function _(){if(!g||A.current||r)return;if(g.status==="ready"){L(g);return}A.current=!0,f(!0),m("");let T=d?await d():V.current.descriptor;if(!T){A.current=!1,f(!1),m("Refresh the collection schema and try again.");return}let B=await i.resumeImport(e.id,g.id,g.version,T.schemaVersion);if(A.current=!1,!D.current)return;if(f(!1),B.ok)R(B.data),L(B.data);else m(B.error.message)}async function J(T){if(!g)return;let B=await i.importErrors(e.id,g.id,{limit:100,...T===void 0?{}:{cursor:T},expectedVersion:g.version});if(!D.current)return;if(B.ok)P(B.data);else m(B.error.message)}async function oe(T=!1){if(h||A.current)return;A.current=!0,f(!0),m("");let B=T&&g?await i.exportImportErrors(e.id,g.id):await i.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:S});if(A.current=!1,!D.current)return;if(f(!1),B.ok)Si(B.data),m(`${B.data.rowCount} rows downloaded${B.data.protectedCells?`; ${B.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else m(B.error.message)}return ie("details",{className:"min-w-0 rounded-lg border p-4",children:[G("summary",{className:"cursor-pointer text-sm font-medium",children:"CSV import and export"}),ie("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[ie("div",{className:"flex flex-wrap items-center gap-3",children:[G("button",{type:"button",disabled:h||!t.length,onClick:()=>void oe(),children:"Export CSV"}),ie("label",{className:"flex items-center gap-2 text-sm",children:[G("input",{type:"checkbox",checked:S,onChange:(T)=>I(T.target.checked)}),"Spreadsheet view"]})]}),G("p",{className:"text-xs text-muted-foreground",children:"Export all matching records and visible columns from the active query. Spreadsheet view prefixes potentially active text with a tab and changes those values; application support varies. Turn it off for exact text. Limit: 100,000 rows or 20 MiB."}),!r&&ie(Di,{children:[ie("label",{className:"flex min-w-0 flex-col gap-2 text-sm",children:["CSV file",G("input",{"aria-label":"CSV file",className:"max-w-full",type:"file",accept:".csv,text/csv",disabled:h,onChange:async(T)=>{let B=T.target.files?.[0];if(!B)return;if(m(""),u(null),c(null),O.current=null,B.size>20971520){m("Choose a UTF-8 CSV file no larger than 20 MiB.");return}f(!0),A.current=!0;try{let ee=new TextDecoder("utf-8",{fatal:!0}).decode(await B.arrayBuffer());if(D.current)c({fileName:B.name,csv:ee,expectedSchemaVersion:e.schemaVersion})}catch{if(D.current)m("The file must be valid UTF-8 text.")}finally{if(A.current=!1,D.current)f(!1)}}})]}),l&&ie("div",{className:"flex flex-wrap gap-3",children:[G("span",{className:"break-all text-sm",children:l.fileName}),G("button",{type:"button",disabled:h,onClick:()=>void W(),children:"Preview CSV"})]}),G("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."}),s&&l&&ie("div",{className:"flex min-w-0 flex-col gap-3",children:[ie("p",{className:"text-sm",children:[s.totalRows," rows · ",s.validRows," valid · ",s.invalidRows," ","invalid · ",s.ignoredColumns.length," skipped columns"]}),s.headers.map((T,B)=>ie("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[ie("span",{className:"max-w-64 break-all",children:["Column ",B+1,": ",T||"(empty)"]}),ie("select",{"aria-label":`Column ${B+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:l.mapping?.[B]??"",disabled:h,onChange:(ee)=>{let se=[...l.mapping??s.mapping];se[B]=ee.target.value||null,c({...l,mapping:se}),u(null),O.current=null},children:[G("option",{value:"",children:"Skip column"}),e.fields.filter((ee)=>!Me(ee)).map((ee)=>ie("option",{value:ee.id,children:[ee.name," (",ee.id,")",ee.required?" · required":""]},ee.id))]})]},`${B}:${T}`)),s.missingRequiredFieldIds.length>0&&ie("p",{role:"alert",children:["Map required fields: ",s.missingRequiredFieldIds.join(", ")]}),G("div",{className:"max-w-full overflow-x-auto",children:ie("table",{className:"w-full text-xs",children:[ie("caption",{children:["First ",s.sample.length," normalized rows; row numbers include the header."]}),G("thead",{children:ie("tr",{children:[G("th",{children:"Row"}),G("th",{children:"Normalized values"}),G("th",{children:"Error"})]})}),G("tbody",{children:s.sample.map((T)=>ie("tr",{children:[G("td",{children:T.rowNumber}),G("td",{className:"max-w-96 break-all",children:Ii(T.values)}),G("td",{children:T.error?.code??""})]},T.rowNumber))})]})}),G("button",{type:"button",className:"self-start",disabled:h||!s.totalRows||s.missingRequiredFieldIds.length>0,onClick:()=>void le(),children:"Confirm import"})]}),ie("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",ie("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:g?.id??"",disabled:h,onChange:async(T)=>{if(!T.target.value){p(null);return}let B=await i.importJob(e.id,T.target.value);if(D.current)if(B.ok)R(B.data),F(!1);else m(B.error.message)},children:[G("option",{value:"",children:"Choose saved progress…"}),C.map((T)=>ie("option",{value:T.id,children:[T.fileName," · ",T.processedRows,"/",T.totalRows," · ",T.status]},T.id))]})]}),G("button",{type:"button",className:"self-start",disabled:h,onClick:async()=>{let T=await i.imports(e.id);if(D.current)if(T.ok)b(T.data);else m(T.error.message)},children:"Refresh saved imports"}),g&&ie("div",{className:"flex flex-col gap-3",children:[ie("p",{role:"status",children:[x?"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"]}),G("progress",{"aria-label":"Import progress",max:g.totalRows,value:g.processedRows,className:"max-w-full"}),G("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."}),ie("div",{className:"flex flex-wrap gap-3",children:[x&&G("button",{type:"button",onClick:()=>{N.current=!1,w(!1)},children:"Pause import"}),!x&&(g.status==="ready"||g.status==="schemaChanged")&&G("button",{type:"button",disabled:h,onClick:()=>void _(),children:g.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(g.status==="ready"||g.status==="schemaChanged")&&G("button",{type:"button",disabled:h,onClick:()=>F(!0),children:"Cancel import"}),G("button",{type:"button",disabled:h||!g.failedRows,onClick:()=>void J(),children:"Show import errors"}),G("button",{type:"button",disabled:h||!g.failedRows,onClick:()=>void oe(!0),children:"Download all import errors"})]}),E&&ie("div",{children:[ie("p",{children:["Stop remaining rows? The ",g.importedRows," imported records will remain."]}),G("button",{type:"button",disabled:h,onClick:async()=>{A.current=!0,f(!0);let T=await i.cancelImport(e.id,g.id);if(A.current=!1,!D.current)return;if(f(!1),T.ok)R(T.data),F(!1);else m(T.error.message)},children:"Confirm cancellation"}),G("button",{type:"button",onClick:()=>F(!1),children:"Keep import"})]}),v&&ie("div",{className:"max-w-full overflow-x-auto",children:[ie("table",{className:"w-full text-xs",children:[ie("caption",{children:[v.total," failed rows"]}),G("thead",{children:ie("tr",{children:[G("th",{children:"Row"}),G("th",{children:"Field"}),G("th",{children:"Error"})]})}),G("tbody",{children:v.items.map((T)=>ie("tr",{children:[G("td",{children:T.rowNumber}),G("td",{children:T.fieldId??""}),G("td",{children:T.code})]},T.rowNumber))})]}),v.nextCursor!==null&&G("button",{type:"button",onClick:()=>void J(v.nextCursor??void 0),children:"Next errors"})]})]})]}),y&&G("p",{role:"alert",className:"break-words text-sm",children:y})]})]})}import{useEffect as tr,useRef as wt,useState as Rt}from"react";import{jsx as ge,jsxs as Le,Fragment as Ei}from"react/jsx-runtime";var vn=[{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 Fi({descriptor:e,client:t,onConverted:n}){let i=e.fields.filter((R)=>vn.some((L)=>L.type===R.type)),[r,o]=Rt(i[0]?.id??""),a=i.find((R)=>R.id===r)??i[0],[d,l]=Rt(a?.type??"singleLineText"),[c,s]=Rt(a?.required??!1),[u,g]=Rt(a?.options?.map((R)=>`${R.id}=${R.name}`).join(`
|
|
5
|
-
`)??""),[p,C]=Rt(null),[b,y]=Rt(""),[m,h]=Rt(!1),f=wt(null),x=wt(null),w=wt(0),S=wt(e);S.current=e;let I=f.current?.field??a,v=m||f.current!==null,P=`${e.id}:${e.schemaVersion}:${JSON.stringify(e.fields)}`,
|
|
6
|
-
`)??"");C(null),f.current=null,x.current=null,y(""),h(!1)},[P,
|
|
1
|
+
function dl(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var Et=["blue","green","red","orange","gray","teal","purple"];function Yr(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 wo(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,l)=>d+(Yr(l.values[r.fieldId])??0),0):0;return{fieldId:r.fieldId,fn:"sum",value:a}})}function Ro(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function Gr(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function Jr(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 So(e,t){if(!t)return!0;if(Ro(t)){let n=t.filterSet.map((r)=>Ro(r)?So(e,r):Gr(r)?Jr(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 Io(e,t,n,r){let i=e.views.find((p)=>p.id===n)??e.views[0];if(!i)return{view:{id:n,name:n,kind:"table"},columns:e.fields,rows:[...t]};let o=[...t];if(i.filter)o=o.filter((p)=>So(p,i.filter));if(i.sort?.length)o.sort((p,C)=>{for(let b of i.sort??[]){let y=p.values[b.fieldId],m=C.values[b.fieldId];if(y===m)continue;if(y==null)return 1;if(m==null)return-1;let h=e.fields.find((I)=>I.id===b.fieldId)?.type,f=(I)=>{if(["number","rating","autoNumber"].includes(h??"")&&typeof I==="number")return I;if(["date","createdTime","lastModifiedTime"].includes(h??"")){let v=Date.parse(String(I));if(Number.isFinite(v))return v}return String(I)},x=f(y),w=f(m);if(x===w)continue;let S=x<w?-1:1;return b.direction==="desc"?-S:S}return p.id<C.id?-1:p.id===C.id?0:1});let a=i.projection?.length?e.fields.filter((p)=>i.projection?.includes(p.id)):e.fields,d=r?.search?.trim().toLowerCase();if(d)o=o.filter((p)=>a.some((C)=>String(p.values[C.id]??"").toLowerCase().includes(d)));let l=wo(o,i.aggregates,e.fields),c=i.group?.fieldId;if(!c)return{view:i,columns:a,rows:o,...l.length?{aggregates:l}:{}};let s=[],u=new Map;for(let p of o){let C=String(p.values[c]??"");if(!u.has(C))u.set(C,[]),s.push(C);u.get(C)?.push(p)}let g=s.map((p)=>{let C=u.get(p)??[];return{key:p,fieldId:c,rows:C,aggregates:wo(C,i.aggregates,e.fields)}});return{view:i,columns:a,rows:o,groups:g,...l.length?{aggregates:l}:{}}}var sn=500,Bn=2000,Un=new Set(["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"]);function Me(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function Ct(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 Ao=["short","medium","tall","extra"];function hl(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 Zr=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,Qr=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function Do(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function Ve(e,t){return{code:e,...t}}function Xr(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function Vn(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function Fo(e,t){if(t.aggregates.length===0)return Ve("empty");if(t.aggregates.length>8||t.groupBy.length>3)return Ve("too_many");let n=new Set;for(let i of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(i.fn))return Ve("function");if(!Zr.test(i.as)||n.has(i.as)||t.groupBy.includes(i.as))return Ve("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 Ve(i.fn==="sum"?"sum_field":"unknown_field",{alias:i.as,...i.fieldId!==void 0?{fieldId:i.fieldId}:{}});if(i.fn==="sum"&&!Vn(o))return Ve("sum_field",{fieldId:o.id,alias:i.as});if(i.fn==="avg"&&!Vn(o))return Ve("numeric_field",{fieldId:o.id,alias:i.as});if((i.fn==="min"||i.fn==="max")&&!Vn(o)&&o.type!=="date"&&!((o.type==="formula"||o.type==="rollup")&&o.resultType==="date"))return Ve("extrema_field",{fieldId:o.id,alias:i.as});if((i.fn==="filled"||i.fn==="empty")&&!Ct(o))return Ve("queryable_field",{fieldId:o.id,alias:i.as});if(i.fn==="count"&&!Ct(o))return Ve("count_field",{fieldId:o.id,alias:i.as})}let r=new Set;for(let i of t.groupBy){if(r.has(i))return Ve("duplicate_group",{fieldId:i});r.add(i);let o=e.fields.find((a)=>a.id===i);if(!o)return Ve("unknown_field",{fieldId:i});if(!Qr.has(o.type)&&!Xr(o))return Ve("not_groupable",{fieldId:i})}return null}var To=(e)=>String(e).padStart(2,"0");function Ze(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 ht(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=Ze(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 dn(e,t){let n=Ze(e,t??"UTC");return`${n.year}-${To(n.month)}-${To(n.day)}`}function Jt(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=Ze(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 qn=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],cn=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"]},Mt=new Set(["isEmpty","isNotEmpty"]);function Ke(e){switch(e.type){case"singleLineText":case"longText":return"text";case"number":return"number";case"checkbox":return"checkbox";case"date":return"date";case"singleSelect":return"singleSelect";case"multipleSelect":return"multipleSelect";case"relation":return"relation";case"formula":case"rollup":return e.resultType==="text"?"text":e.resultType==="number"?"number":e.resultType==="date"?"date":null;default:return null}}function Mo(e){let t=Ke(e);return t?Eo[t]:[]}var _n=/^\d{4}-\d{2}-\d{2}$/,ei=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function $n(e){if(!ei(e))return!1;let t=e.mode;if(!qn.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&&_n.test(e.date);if(t==="dateRange")return typeof e.date==="string"&&_n.test(e.date)&&typeof e.to==="string"&&_n.test(e.to)&&e.date<=e.to;if(cn.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function No(e,t){if(!e)return"unknown field";let n=Ke(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(Mt.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 $n(i)||typeof i==="string"&&Number.isFinite(Date.parse(i))?null:"date required"}}var ti={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},Yl=Array.from(new Set(Object.values(ti).flat()));var Zl=Object.freeze([Object.freeze({name:"manifest",summary:"Describe query operations and list the derived resource index.",positionals:Object.freeze([]),options:Object.freeze([])}),Object.freeze({name:"search",summary:"Search resources with deterministic bilingual ranking and reasons.",positionals:Object.freeze([Object.freeze({name:"text",property:"text",type:"string",required:!1})]),options:Object.freeze([Object.freeze({name:"kind",property:"kinds",type:"resource-kind",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"tag",property:"tags",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"category",property:"categories",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"capability",property:"capabilities",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"maturity",property:"maturities",type:"resource-maturity",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"limit",property:"limit",type:"positive-integer"})])}),Object.freeze({name:"get",summary:"Resolve one canonical resource id or unambiguous alias.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([])}),Object.freeze({name:"build",summary:"Plan dependency closure and gaps without writing or installing.",positionals:Object.freeze([Object.freeze({name:"root",property:"roots",type:"string",required:!0,variadic:!0})]),options:Object.freeze([])})]);function ni(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function ns(e,t){if(t===e.draft)return e;return{...e,draft:t}}function oi(e){return e.draft!==e.savedContent}function os(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 rs(e,t){if(oi(e))return e;let n=ni(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 ot=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),vt=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),xt=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,Lo=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,un=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),Oo=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every(un)&&new Set(e).size===e.length;function ri(e){if(!ot(e)||!vt(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!un(e.id)||!xt(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)=>!ot(t)||!vt(t,["id","name"])||!un(t.id)||!xt(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&&(!ot(i)||!vt(i,[...r])||r.some((o)=>!xt(i[o],o==="expression"?2048:512))))return!1}return!0}function as(e){if(!ot(e)||!vt(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))||!xt(e.collectionId,512)||!xt(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(!ot(t)||!vt(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!xt(t.name,200)||!Lo(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(ri)||new Set(t.fields.map((o)=>o.id)).size!==t.fields.length)return!1;if(!ot(n)||!vt(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!un(n.id)||!xt(n.name,200)||!Lo(n.version)||!Oo(n.columnOrder)||!Oo(n.hiddenColumns)||!ot(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)=>ot(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)=>!ot(o)||!vt(o,["fieldId","direction"])||!i(o.fieldId)||!["asc","desc"].includes(String(o.direction)))))return!1;return!0}import{createContext as ii,useCallback as ai,useContext as li,useLayoutEffect as zn,useMemo as si,useRef as Vo,useState as di}from"react";var ci=ii(void 0);function Nt(e,t={}){let n=li(ci),r=Vo({}),{dirty:i,busy:o}=e,{onDirtyChange:a,onBusyChange:d}=t;zn(()=>{n?.(r.current,{dirty:i,busy:o}),a?.(i),d?.(o)},[n,i,o,a,d]),zn(()=>()=>{n?.(r.current),a?.(!1),d?.(!1)},[n,a,d])}function rd(){let e=Vo(new Map),[t,n]=di({dirty:!1,busy:!1}),r=ai((i,o)=>{if(o)e.current.set(i,o);else e.current.delete(i);let a=[...e.current.values()],d=a.some((c)=>c.dirty),l=a.some((c)=>c.busy);n((c)=>c.dirty===d&&c.busy===l?c:{dirty:d,busy:l})},[]);return{...t,report:r}}function pn(e,t){let n=si(()=>({active:!0,client:e,id:t}),[e,t]);return zn(()=>(n.active=!0,()=>{n.active=!1}),[n]),n}import{useEffect as Sn,useRef as on,useState as qe}from"react";import{useId as Ki,useState as Qn}from"react";var We=(e)=>String(e).padStart(2,"0"),ui=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function Ne(e){let t=e.formatting;return ui(e)&&t&&"date"in t?t:void 0}function gn(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function Bo(e){let t=Ne(e);return!t?"auto":t.time==="none"?"date":"datetime"}function jn(e,t,n,r){switch(r){case"YYYY/MM/DD":return`${e}/${We(t)}/${We(n)}`;case"MM/DD/YYYY":return`${We(t)}/${We(n)}/${e}`;case"DD/MM/YYYY":return`${We(n)}/${We(t)}/${e}`;case"YYYY年M月D日":return`${e}年${t}月${n}日`;default:return`${e}-${We(t)}-${We(n)}`}}function Lt(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 jn(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=Ze(d,t.timeZone??"UTC");return jn(l.year,l.month,l.day,t.date)}let i=r?ht({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=Ze(i,t.timeZone),a=jn(o.year,o.month,o.day,t.date);if(t.time==="12h"){let d=o.hour%12||12;return`${a} ${d}:${We(o.minute)} ${o.hour<12?"AM":"PM"}`}return`${a} ${We(o.hour)}:${We(o.minute)}`}function mn(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 fn(e,t){let n=e?.findIndex((o)=>o.id===t)??-1,r=n>=0?e?.[n]?.color:void 0,i=Et.findIndex((o)=>o===r);return i>=0?i:n}var pi={"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}","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":"修改字段","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 K(e="en"){return(t,n={})=>(e==="zh-CN"?pi[t]??t:t).replace(/\{(\w+)\}/g,(r,i)=>String(n[i]??r))}function ud(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 gi(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 Ye(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function pd(e,t,n,r){let i=gi(n,r),o=[];for(let a=i.firstRow;a<=i.lastRow;a++){let d=[];for(let l=i.firstColumn;l<=i.lastColumn;l++){let c=t[l],s=e[a]?.values[c?.id??""],u=c?.type==="json"&&s!=null?JSON.stringify(s):Ye(s);d.push(/[\t\r\n"]/.test(u)?`"${u.replaceAll('"','""')}"`:u)}o.push(d.join("\t"))}return o.join(`
|
|
2
|
+
`)}function mi(e,t="en"){let n=K(t),r=[],i=[],o="",a=!1;for(let d=0;d<e.length;d++){let l=e[d];if(l==='"'&&(a||o===""))if(a&&e[d+1]==='"')o+='"',d++;else a=!a;else if(!a&&(l==="\t"||l===`
|
|
3
|
+
`||l==="\r")){if(i.push(o),o="",l!=="\t"){if(r.push(i),i=[],l==="\r"&&e[d+1]===`
|
|
4
|
+
`)d++}}else o+=l}if(a)throw Error(n("Unclosed quoted cell."));if(o||i.length||r.length===0)i.push(o),r.push(i);return r}function dt(e,t,n="en"){let r=K(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==="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=Ne(t);if(o){let w=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!w)throw Error(r("{name} needs a date.",{name:t.name}));let[,S,I,v]=w,P=new Date(Date.UTC(Number(S),Number(I)-1,Number(v)));if(P.getUTCMonth()!==Number(I)-1||P.getUTCDate()!==Number(v))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 dn(new Date(e),o.timeZone);return`${S}-${I}-${v}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return ht({year:Number(S),month:Number(I),day:Number(v)},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,l,c,s,u,g,p,C]=a,b=Number(d),y=Number(l),m=Number(c),f=[31,b%4===0&&(b%100!==0||b%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(y<1||y>12||m<1||m>(f[y-1]??0)||Number(s??0)>23||Number(u??0)>59||Number(g??0)>59||Number(p??0)>23||Number(C??0)>59)throw Error(r("{name} needs a valid calendar date.",{name:t.name}));let x=new Date(e);if(!Number.isFinite(x.getTime()))throw Error(r("{name} needs a date.",{name:t.name}));return x.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 gd(e,t,n,r,i="en"){let o=K(i);try{if(e.length>1048576)throw Error(o("Paste is too large."));let a=mi(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((l,c)=>{if(r.column+l.length>n.length)throw Error(o("Paste extends beyond the visible columns."));let s=t[r.row+c];if(!s)throw Error(o("Row is not loaded."));let u={};return l.forEach((g,p)=>{let C=n[r.column+p];if(C?.generation==="autoIncrement")throw Error(o("{name} is auto-generated and cannot be edited.",{name:C.name}));if(C)u[C.id]=dt(g,C,i)}),{op:"update",id:s.id,expectedVersion:s.version,values:u}})}}catch(a){return{ok:!1,message:a instanceof Error?a.message:o("Invalid paste.")}}}function Uo(e,t){let n=Ye(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=(c)=>i.find((s)=>s.type===c)?.value??"",a=r.getUTCMilliseconds(),d=o("second"),l=d!=="00"||a?`:${d}${a?`.${String(a).padStart(3,"0")}`:""}`:"";return`${o("year")}-${o("month")}-${o("day")} ${o("hour")}:${o("minute")}${l}`}import{useEffect as fi,useRef as yi,useState as Ot}from"react";import{jsx as Ge,jsxs as Zt}from"react/jsx-runtime";function Vt(e){if(e==null)return"—";if(Array.isArray(e))return e.map(Vt).join(", ");return String(e)}function Qt(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((r)=>r.label||r.id).join(", "):void 0)??Vt(e.values[t.id])}function Cd(e,t){return Ye(e.values[t.id])}function _o({field:e,value:t,labels:n=[],client:r,onChange:i,disabled:o=!1,locale:a,"aria-describedby":d,"aria-invalid":l}){let c=K(a),s=Array.isArray(t)?t.filter((F)=>typeof F==="string"):[],u=yi(new Set(s));u.current=new Set(s);let[g,p]=Ot(""),[C,b]=Ot(),[y,m]=Ot([]),[h,f]=Ot(0),[x,w]=Ot({}),[S,I]=Ot({rows:[],next:null,error:"",loading:!0}),v=e.link?.collectionId,P=e.link?.displayFieldId;fi(()=>{let F=!0;if(I({rows:[],next:null,error:"",loading:!0}),!r||!v||!P){I({rows:[],next:null,error:c("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return r.query(v,{limit:50,search:g,...C?{cursor:C}:{}}).then((D)=>{if(!F)return;if(!D.ok){I({rows:[],next:null,error:D.error.message,loading:!1});return}w((N)=>({...Object.fromEntries(Object.entries(N).filter(([A])=>u.current.has(A))),...Object.fromEntries(D.data.items.map((A)=>{let O=String(A.values[P]??"");return[A.id,O.trim()?O.slice(0,256):A.id]}))})),I({rows:D.data.items,next:D.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(F)I({rows:[],next:null,error:c("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{F=!1}},[r,v,P,g,C,h]);let T=(F)=>x[F]??n.find((D)=>D.id===F)?.label??F;return Zt("fieldset",{disabled:o,"aria-label":c("{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:[Ge("div",{className:"flex flex-wrap gap-1",children:s.map((F)=>Zt("span",{className:"rounded border px-2 py-1 text-sm",children:[T(F)," ",Ge("button",{type:"button","aria-label":c("Remove {name}",{name:T(F)}),onClick:()=>i(s.filter((D)=>D!==F)),children:"×"})]},F))}),Ge("input",{"aria-label":c("Search {name} records",{name:e.name}),type:"search",placeholder:c("Search linked records"),value:g,onChange:(F)=>{p(F.target.value),b(void 0),m([])}}),S.loading&&Ge("p",{role:"status",children:c("Loading linked records…")}),S.error&&Zt("div",{role:"alert",children:[S.error," ",Ge("button",{type:"button",onClick:()=>f((F)=>F+1),children:c("Retry linked records")})]}),Ge("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:S.rows.map((F)=>Zt("label",{className:"flex items-center gap-2 text-sm",children:[Ge("input",{type:"checkbox","aria-label":c("Link {name}",{name:T(F.id)}),checked:s.includes(F.id),disabled:!s.includes(F.id)&&s.length>=100,onChange:(D)=>i(D.target.checked?[...s,F.id]:s.filter((N)=>N!==F.id))}),T(F.id)]},F.id))}),!S.loading&&!S.error&&!S.rows.length&&Ge("p",{children:c("No matching records.")}),Zt("div",{className:"flex gap-2",children:[Ge("button",{type:"button",disabled:!y.length||S.loading,onClick:()=>{b(y.at(-1)),m((F)=>F.slice(0,-1))},children:c("Previous linked records")}),Ge("button",{type:"button",disabled:!S.next||S.loading,onClick:()=>{m((F)=>[...F,C]),b(S.next??void 0)},children:c("Next linked records")})]}),Ge("small",{children:c("{count} selected · up to 100 per record across all link fields",{count:s.length})})]})}var bi={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function yn(e,t,n){return t?K(n)(bi[t]):e==null?"—":String(e)}function qo(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 $o(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function bn(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function zo(e,t,n){let r=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...bn(e),filter:$o(e.filter,r)}}function Xt(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 jo(e,t,n){let{start:r,end:i}=Xt(n);return{...bn(e),filter:$o(e.filter,{fieldId:t,operator:"onOrAfter",value:r},{fieldId:t,operator:"before",value:i})}}function Cn(e,t){let n={id:"date",name:"Date",type:"date"},r=String(dt(t,n)),i=String(dt(String(e),n));return`${r.slice(0,10)}${i.slice(10)}`}function Pt(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 ze(e,t){let n=t.find((r)=>r.type==="singleLineText"||r.type==="longText");return(n?Ye(e.values[n.id]):"")||e.id}function hn(e,t,n){if(t.type==="lookup")return Vt(e);if(t.type==="date"){let r=Ne(t);return r?Lt(e,r):Uo(e)}if(t.type==="number"){let r=gn(t);return r?mn(e,r):Ye(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return yn(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 Ye(e)}import{useEffect as Yo,useId as hi,useMemo as vi,useRef as xi,useState as Go}from"react";var Ci=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function ct(e){return Ci.test(e)}var rt=(e)=>String(e).padStart(2,"0");function Ho(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${rt(t.getMonth()+1)}-${rt(t.getDate())}T${rt(t.getHours())}:${rt(t.getMinutes())}:${rt(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var Hn=(e,t)=>{let n=Ze(e,t);return`${n.year}-${rt(n.month)}-${rt(n.day)}T${rt(n.hour)}:${rt(n.minute)}`};function Ko(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!ct(e))return e.slice(0,10);return Hn(new Date(e),t.timeZone??"UTC").slice(0,10)}if(ct(e))return Hn(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function Wo(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||ct(t)))return e;let i=e.length>10?e.slice(11,16):t&&ct(t)?Hn(new Date(t),n.timeZone).slice(11,16):"00:00",[o,a,d]=e.slice(0,10).split("-").map(Number),[l,c]=i.split(":").map(Number),s=ht({year:o??0,month:a??1,day:d??1,hour:l??0,minute:c??0},n.timeZone);return Number.isFinite(s.getTime())?s.toISOString():e}import{jsx as kt,jsxs as Jo}from"react/jsx-runtime";function Kn(e,t,n){if(e.type==="blob")return"";try{return dt(t,e),""}catch{if(t===""&&e.required)return n==="zh-CN"?`请填写${e.name}。`:`${e.name} is required.`;if(e.type==="number")return n==="zh-CN"?`${e.name}需要有效数字。`:`${e.name} needs a number.`;if(e.type==="bigint")return n==="zh-CN"?`${e.name}必须是整数。`:`${e.name} needs an integer.`;if(e.type==="date")return n==="zh-CN"?`${e.name}需要有效日期。`:`${e.name} needs a valid date.`;if(e.type==="checkbox")return n==="zh-CN"?`${e.name}请选择是或否。`:`${e.name} needs true or false.`;if(e.type==="json")return n==="zh-CN"?`${e.name}必须是有效 JSON。`:`${e.name} needs valid JSON.`;return n==="zh-CN"?"输入值无效":"Invalid value"}}function Nd({field:e,text:t,disabled:n,id:r,label:i,ariaLabel:o,onChange:a,onSave:d,onCancel:l,locale:c="en",submitted:s=!1,describedBy:u}){let g=vi(()=>K(c),[c]),p=hi(),C=xi(null),b=Boolean(d);Yo(()=>{if(b)C.current?.querySelector("input,textarea,select")?.focus()},[b]);let y=r??p,m=`${y}-error`,[h,f]=Go(t),[x,w]=Go(!1);Yo(()=>f(t),[t]);let S=Kn(e,h,c),v=Boolean(e.required&&h===""&&S)&&!x&&!s?"":S,P=o??i??e.name,T=e.type==="date"&&ct(h),F=T&&!S?Ho(h):h,D=[u,v?m:void 0].filter(Boolean).join(" "),N={id:y,"aria-label":P,"aria-invalid":Boolean(v),...D?{"aria-describedby":D}:{},disabled:n,onBlur:()=>w(!0),onKeyDown:(R)=>{if(d||l)R.stopPropagation();let L=e.type==="longText"||e.type==="json";if(R.key==="Tab"&&d)R.preventDefault(),d(R.shiftKey?"previous":"next");else if(R.key==="Enter"&&!R.shiftKey&&d&&(!L||R.ctrlKey||R.metaKey))R.preventDefault(),d();else if(R.key==="Escape"&&l)R.preventDefault(),l()},style:{width:"100%",...b?{height:"100%",border:0,borderRadius:0,outline:"none",boxShadow:"none",padding:"0 7px",boxSizing:"border-box",font:"inherit"}:{},background:"var(--background, white)",color:"inherit"},className:"min-w-0 rounded-md border border-[var(--uibot-border,#d4d4d8)] bg-[var(--uibot-surface,#fff)] px-2 py-1 text-sm text-[var(--uibot-text,#18181b)] disabled:cursor-not-allowed disabled:opacity-60"},A=(R)=>{w(!0),f(R),a(R)},O=(R)=>{if(e.type==="date"&&T&&R){let L=new Date(R);A(Number.isFinite(L.getTime())?L.toISOString():R)}else A(R)},V;if(e.type==="checkbox")V=Jo("select",{...N,value:h,onChange:(R)=>A(R.currentTarget.value),children:[!e.required&&kt("option",{value:"",children:g("No value")}),kt("option",{value:"true",children:g("Yes")}),kt("option",{value:"false",children:g("No")})]});else if(e.type==="longText"||e.type==="json")V=kt("textarea",{...N,value:h,rows:e.type==="json"?4:3,onChange:(R)=>A(R.currentTarget.value)});else{let R=e.type==="date"&&!(S&&h)?T?"datetime-local":"date":"text",L=e.type==="blob";V=kt("input",{...N,type:R,inputMode:e.type==="number"?"decimal":void 0,step:T?"0.001":void 0,value:F,readOnly:L,onInput:e.type==="date"?(W)=>O(W.currentTarget.value):void 0,onChange:(W)=>O(W.currentTarget.value)})}return Jo("div",{ref:C,className:"grid min-w-0 gap-1",style:b?{height:"100%"}:void 0,children:[i&&kt("label",{className:"text-xs font-medium",htmlFor:y,children:i}),V,v&&kt("span",{id:m,role:"alert",className:"text-xs text-red-600",children:v})]})}import{useEffect as ki,useRef as wi}from"react";import{jsx as Zo}from"react/jsx-runtime";var Pi={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 Fe({name:e,size:t=15,style:n}){return Zo("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:Zo("path",{d:Pi[e]})})}import{jsx as ut,jsxs as Qo,Fragment as Ri}from"react/jsx-runtime";var Bt={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function Y({ui:e,style:t,variant:n,size:r,children:i,disabled:o,onClick:a,title:d,ariaLabel:l,icon:c,iconOnly:s,badge:u}){let g=e?.Button,p=c?Qo("span",{style:{position:"relative",display:"inline-flex"},children:[ut(Fe,{name:c}),u?ut("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,C=s?p:Qo(Ri,{children:[p,i]}),b=l,y=d??(s?b:void 0),m=s?"icon":r;if(g)return ut(g,{...n?{variant:n}:{},...m?{size:m}:{},disabled:o,onClick:a,title:y,"aria-label":b,children:C});return ut("button",{type:"button",style:{...c?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?Bt:{},...s?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:o,onClick:a,title:y,"aria-label":b,children:C})}function ke({ui:e,value:t,options:n,onChange:r,disabled:i,label:o,style:a,"aria-describedby":d,"aria-invalid":l}){let c=e?.Select,s={...d?{"aria-describedby":d}:{},...l?{"aria-invalid":!0}:{}};if(c)return ut(c,{value:t,options:n,onChange:r,disabled:i,"aria-label":o,...s});return ut("select",{"aria-label":o,...s,style:a,disabled:i,value:t,onChange:(u)=>r(u.target.value),children:n.map((u)=>ut("option",{value:u.value,disabled:u.disabled,children:u.label},u.value))})}function Xo({label:e,busy:t,onCancel:n,children:r,alert:i=!1}){let o=wi(null);return ki(()=>{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})}},[]),ut("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,l=[...d.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter((u)=>!u.hidden),c=l[0],s=l.at(-1);if(!c||(a.shiftKey?document.activeElement===c:document.activeElement===s)||!d.contains(document.activeElement)){if(a.preventDefault(),(a.shiftKey?s:c)?.focus(),!c)d.focus()}},tabIndex:-1,onCancel:(a)=>{if(a.preventDefault(),!t)n()},children:r})}import{useEffect as er,useRef as en,useState as Qe}from"react";import{jsx as G,jsxs as ie,Fragment as Di}from"react/jsx-runtime";function Si(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 Ii=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function Ai({descriptor:e,fieldIds:t,query:n,client:r,readOnly:i=!1,reloadKey:o=0,onImported:a,onRefreshSchema:d}){let[l,c]=Qe(null),[s,u]=Qe(null),[g,p]=Qe(null),[C,b]=Qe([]),[y,m]=Qe(""),[h,f]=Qe(!1),[x,w]=Qe(!1),[S,I]=Qe(!0),[v,P]=Qe(null),[T,F]=Qe(!1),D=en(!1),N=en(!1),A=en(!1),O=en(null),V=en({client:r,onImported:a,descriptor:e});V.current={client:r,onImported:a,descriptor:e},er(()=>(D.current=!0,()=>{D.current=!1,N.current=!1}),[]),er(()=>{let E=!0;if(!i)r.imports(e.id).then((B)=>{if(!E||!D.current||!B.ok)return;if(b((ee)=>B.data.map((se)=>{let Re=ee.find((z)=>z.id===se.id);return Re&&Re.version>se.version?Re:se})),!A.current)p((ee)=>{let se=B.data.find((Re)=>Re.id===ee?.id);return ee&&se&&se.version>ee.version?se:ee})});return()=>{E=!1}},[r,e.id,i,o]);let R=(E)=>{p(E),b((B)=>[E,...B.filter((ee)=>ee.id!==E.id)].slice(0,50)),P(null)};async function L(E){if(A.current||i)return;A.current=!0,N.current=!0,f(!0),w(!0),m("");let B=E;try{while(D.current&&N.current&&B.status==="ready"){let ee=await V.current.client.advanceImport(e.id,B.id,B.version);if(!D.current)break;if(!ee.ok){m(ee.error.message);break}let se=ee.data;if(R(se),se.importedRows>B.importedRows)V.current.onImported();if(se.version===B.version&&se.status==="ready"){m("Import paused. Refresh the saved progress before retrying.");break}B=se}}finally{if(A.current=!1,N.current=!1,D.current)f(!1),w(!1)}}async function W(){if(!l||A.current)return;A.current=!0,f(!0),m("");let E=await r.previewImport(e.id,{...l,expectedSchemaVersion:e.schemaVersion});if(A.current=!1,!D.current)return;if(f(!1),E.ok)u(E.data),c({...l,expectedSchemaVersion:E.data.schemaVersion,mapping:E.data.mapping});else m(E.error.message)}async function le(){if(!l||!s||s.missingRequiredFieldIds.length||!s.totalRows||A.current||i)return;A.current=!0,f(!0),m(""),O.current??=crypto.randomUUID();let E=await r.createImport(e.id,{...l,idempotencyKey:O.current});if(A.current=!1,!D.current)return;if(f(!1),E.ok)R(E.data),c(null),u(null),O.current=null,L(E.data);else m(E.error.message)}async function q(){if(!g||A.current||i)return;if(g.status==="ready"){L(g);return}A.current=!0,f(!0),m("");let E=d?await d():V.current.descriptor;if(!E){A.current=!1,f(!1),m("Refresh the collection schema and try again.");return}let B=await r.resumeImport(e.id,g.id,g.version,E.schemaVersion);if(A.current=!1,!D.current)return;if(f(!1),B.ok)R(B.data),L(B.data);else m(B.error.message)}async function J(E){if(!g)return;let B=await r.importErrors(e.id,g.id,{limit:100,...E===void 0?{}:{cursor:E},expectedVersion:g.version});if(!D.current)return;if(B.ok)P(B.data);else m(B.error.message)}async function oe(E=!1){if(h||A.current)return;A.current=!0,f(!0),m("");let B=E&&g?await r.exportImportErrors(e.id,g.id):await r.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:S});if(A.current=!1,!D.current)return;if(f(!1),B.ok)Si(B.data),m(`${B.data.rowCount} rows downloaded${B.data.protectedCells?`; ${B.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else m(B.error.message)}return ie("details",{className:"min-w-0 rounded-lg border p-4",children:[G("summary",{className:"cursor-pointer text-sm font-medium",children:"CSV import and export"}),ie("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[ie("div",{className:"flex flex-wrap items-center gap-3",children:[G("button",{type:"button",disabled:h||!t.length,onClick:()=>void oe(),children:"Export CSV"}),ie("label",{className:"flex items-center gap-2 text-sm",children:[G("input",{type:"checkbox",checked:S,onChange:(E)=>I(E.target.checked)}),"Spreadsheet view"]})]}),G("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&&ie(Di,{children:[ie("label",{className:"flex min-w-0 flex-col gap-2 text-sm",children:["CSV file",G("input",{"aria-label":"CSV file",className:"max-w-full",type:"file",accept:".csv,text/csv",disabled:h,onChange:async(E)=>{let B=E.target.files?.[0];if(!B)return;if(m(""),u(null),c(null),O.current=null,B.size>20971520){m("Choose a UTF-8 CSV file no larger than 20 MiB.");return}f(!0),A.current=!0;try{let ee=new TextDecoder("utf-8",{fatal:!0}).decode(await B.arrayBuffer());if(D.current)c({fileName:B.name,csv:ee,expectedSchemaVersion:e.schemaVersion})}catch{if(D.current)m("The file must be valid UTF-8 text.")}finally{if(A.current=!1,D.current)f(!1)}}})]}),l&&ie("div",{className:"flex flex-wrap gap-3",children:[G("span",{className:"break-all text-sm",children:l.fileName}),G("button",{type:"button",disabled:h,onClick:()=>void W(),children:"Preview CSV"})]}),G("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."}),s&&l&&ie("div",{className:"flex min-w-0 flex-col gap-3",children:[ie("p",{className:"text-sm",children:[s.totalRows," rows · ",s.validRows," valid · ",s.invalidRows," ","invalid · ",s.ignoredColumns.length," skipped columns"]}),s.headers.map((E,B)=>ie("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[ie("span",{className:"max-w-64 break-all",children:["Column ",B+1,": ",E||"(empty)"]}),ie("select",{"aria-label":`Column ${B+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:l.mapping?.[B]??"",disabled:h,onChange:(ee)=>{let se=[...l.mapping??s.mapping];se[B]=ee.target.value||null,c({...l,mapping:se}),u(null),O.current=null},children:[G("option",{value:"",children:"Skip column"}),e.fields.filter((ee)=>!Me(ee)).map((ee)=>ie("option",{value:ee.id,children:[ee.name," (",ee.id,")",ee.required?" · required":""]},ee.id))]})]},`${B}:${E}`)),s.missingRequiredFieldIds.length>0&&ie("p",{role:"alert",children:["Map required fields: ",s.missingRequiredFieldIds.join(", ")]}),G("div",{className:"max-w-full overflow-x-auto",children:ie("table",{className:"w-full text-xs",children:[ie("caption",{children:["First ",s.sample.length," normalized rows; row numbers include the header."]}),G("thead",{children:ie("tr",{children:[G("th",{children:"Row"}),G("th",{children:"Normalized values"}),G("th",{children:"Error"})]})}),G("tbody",{children:s.sample.map((E)=>ie("tr",{children:[G("td",{children:E.rowNumber}),G("td",{className:"max-w-96 break-all",children:Ii(E.values)}),G("td",{children:E.error?.code??""})]},E.rowNumber))})]})}),G("button",{type:"button",className:"self-start",disabled:h||!s.totalRows||s.missingRequiredFieldIds.length>0,onClick:()=>void le(),children:"Confirm import"})]}),ie("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",ie("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:g?.id??"",disabled:h,onChange:async(E)=>{if(!E.target.value){p(null);return}let B=await r.importJob(e.id,E.target.value);if(D.current)if(B.ok)R(B.data),F(!1);else m(B.error.message)},children:[G("option",{value:"",children:"Choose saved progress…"}),C.map((E)=>ie("option",{value:E.id,children:[E.fileName," · ",E.processedRows,"/",E.totalRows," · ",E.status]},E.id))]})]}),G("button",{type:"button",className:"self-start",disabled:h,onClick:async()=>{let E=await r.imports(e.id);if(D.current)if(E.ok)b(E.data);else m(E.error.message)},children:"Refresh saved imports"}),g&&ie("div",{className:"flex flex-col gap-3",children:[ie("p",{role:"status",children:[x?"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"]}),G("progress",{"aria-label":"Import progress",max:g.totalRows,value:g.processedRows,className:"max-w-full"}),G("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."}),ie("div",{className:"flex flex-wrap gap-3",children:[x&&G("button",{type:"button",onClick:()=>{N.current=!1,w(!1)},children:"Pause import"}),!x&&(g.status==="ready"||g.status==="schemaChanged")&&G("button",{type:"button",disabled:h,onClick:()=>void q(),children:g.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(g.status==="ready"||g.status==="schemaChanged")&&G("button",{type:"button",disabled:h,onClick:()=>F(!0),children:"Cancel import"}),G("button",{type:"button",disabled:h||!g.failedRows,onClick:()=>void J(),children:"Show import errors"}),G("button",{type:"button",disabled:h||!g.failedRows,onClick:()=>void oe(!0),children:"Download all import errors"})]}),T&&ie("div",{children:[ie("p",{children:["Stop remaining rows? The ",g.importedRows," imported records will remain."]}),G("button",{type:"button",disabled:h,onClick:async()=>{A.current=!0,f(!0);let E=await r.cancelImport(e.id,g.id);if(A.current=!1,!D.current)return;if(f(!1),E.ok)R(E.data),F(!1);else m(E.error.message)},children:"Confirm cancellation"}),G("button",{type:"button",onClick:()=>F(!1),children:"Keep import"})]}),v&&ie("div",{className:"max-w-full overflow-x-auto",children:[ie("table",{className:"w-full text-xs",children:[ie("caption",{children:[v.total," failed rows"]}),G("thead",{children:ie("tr",{children:[G("th",{children:"Row"}),G("th",{children:"Field"}),G("th",{children:"Error"})]})}),G("tbody",{children:v.items.map((E)=>ie("tr",{children:[G("td",{children:E.rowNumber}),G("td",{children:E.fieldId??""}),G("td",{children:E.code})]},E.rowNumber))})]}),v.nextCursor!==null&&G("button",{type:"button",onClick:()=>void J(v.nextCursor??void 0),children:"Next errors"})]})]})]}),y&&G("p",{role:"alert",className:"break-words text-sm",children:y})]})]})}import{useEffect as tr,useRef as wt,useState as Rt}from"react";import{jsx as ge,jsxs as Le,Fragment as Ti}from"react/jsx-runtime";var vn=[{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 Fi({descriptor:e,client:t,onConverted:n}){let r=e.fields.filter((R)=>vn.some((L)=>L.type===R.type)),[i,o]=Rt(r[0]?.id??""),a=r.find((R)=>R.id===i)??r[0],[d,l]=Rt(a?.type??"singleLineText"),[c,s]=Rt(a?.required??!1),[u,g]=Rt(a?.options?.map((R)=>`${R.id}=${R.name}`).join(`
|
|
5
|
+
`)??""),[p,C]=Rt(null),[b,y]=Rt(""),[m,h]=Rt(!1),f=wt(null),x=wt(null),w=wt(0),S=wt(e);S.current=e;let I=f.current?.field??a,v=m||f.current!==null,P=`${e.id}:${e.schemaVersion}:${JSON.stringify(e.fields)}`,T=wt(e.fields);T.current=e.fields;let F=wt(P);F.current=P;let D=wt(!0);tr(()=>(D.current=!0,()=>{D.current=!1,w.current++}),[]),tr(()=>{if(F.current!==P)return;if(f.current&&x.current===e.id)return;w.current++;let R=T.current.find((L)=>L.id===i&&vn.some((W)=>W.type===L.type))??T.current.find((L)=>vn.some((W)=>W.type===L.type));if(R)o(R.id),l(R.type),s(R.required??!1),g(R.options?.map((L)=>`${L.id}=${L.name}`).join(`
|
|
6
|
+
`)??"");C(null),f.current=null,x.current=null,y(""),h(!1)},[P,i,e.id]);let N=()=>{C(null),f.current=null,x.current=null,w.current++,y("")},A=(R)=>{o(R.id),l(R.type),s(R.required??!1),g(R.options?.map((L)=>`${L.id}=${L.name}`).join(`
|
|
7
7
|
`)??""),N()};if(!I)return null;let O=()=>{let R={id:I.id,name:I.name,type:d,required:c};if(d==="singleSelect"||d==="multipleSelect")R.options=u.split(`
|
|
8
|
-
`).filter((L)=>L.trim()).map((L)=>{let W=L.indexOf("=");if(W<1)throw Error("Each option must use stable_id=Display name.");return{id:L.slice(0,W).trim(),name:L.slice(W+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:R}},V=()=>D.current&&F.current===P;return Le("details",{className:"rounded-lg border p-4",children:[ge("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),Le("div",{className:"mt-4 flex flex-col gap-3",children:[ge("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."}),Le("label",{children:["Field"," ",Le("select",{"aria-label":"Conversion field",value:I.id,disabled:v,onChange:(R)=>{let L=
|
|
9
|
-
done=Done`})]}),b&&ge("p",{role:"alert",className:"text-sm text-destructive",children:b}),ge("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:v,onClick:async()=>{let R;try{R=O()}catch(L){y(L instanceof Error?L.message:"Invalid conversion options.");return}h(!0),y(""),C(null),f.current=null;try{let L=await t.previewConversion(e.id,R);if(!V())return;if(L.ok)C(L.data);else y(L.error.message)}catch{if(V())y("Preview unavailable. Your draft is kept.")}finally{if(V())h(!1)}},children:m?"Working…":"Preview conversion"}),p&&Le(Ei,{children:[Le("p",{role:"status",children:[p.validRows," valid · ",p.invalidRows," invalid"]}),Le("p",{className:"text-xs",children:["Preview covers ",p.totalRows," records. Samples and errors show at most 20 records."]}),ge("div",{className:"overflow-x-auto",children:Le("table",{className:"w-full text-sm",children:[ge("thead",{children:Le("tr",{children:[ge("th",{children:"Record"}),ge("th",{children:"Before"}),ge("th",{children:"After"}),ge("th",{children:"Error"})]})}),ge("tbody",{children:p.sample.map((R)=>Le("tr",{children:[ge("td",{className:"max-w-32 break-all",children:R.id}),ge("td",{className:"max-w-48 break-words",children:JSON.stringify(R.before)}),ge("td",{className:"max-w-48 break-words",children:JSON.stringify(R.after)}),ge("td",{children:R.error})]},R.id))})]})}),p.errors.length>0&&ge("ul",{children:p.errors.map((R)=>Le("li",{children:[ge("span",{className:"break-all",children:R.id}),": ",ge("span",{children:R.code})]},R.id))}),ge("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:m||p.invalidRows>0,onClick:async()=>{if(!f.current)x.current=e.id,w.current++;f.current??={expectedSchemaVersion:p.schemaVersion,field:p.field,previewToken:p.previewToken,idempotencyKey:crypto.randomUUID()};let R=f.current,L=w.current,W=()=>D.current&&S.current.id===e.id&&L===w.current;h(!0),y("");try{let le=await t.convertField(e.id,R);if(!W())return;if(le.ok){if(C(null),f.current=null,x.current=null,le.data.descriptor.schemaVersion>=S.current.schemaVersion)n(le.data.descriptor)}else if(y(le.error.message),le.error.status===409)C(null),f.current=null,x.current=null}catch{if(W())y("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(W())h(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as Ti,useRef as Wn,useState as nr}from"react";import{jsx as or,jsxs as Ni}from"react/jsx-runtime";function Mi({collectionIds:e,client:t,onChanges:n,pollIntervalMs:i=2000}){let r=JSON.stringify([...new Set(e)].sort()),o=Wn(r);o.current=r;let a=Wn(n);a.current=n;let d=Wn(()=>{}),[l,c]=nr("connecting"),[s,u]=nr(!1);return Ti(()=>{let g=JSON.parse(r),p=new Map,C=!1,b=!1,y=0,m,h=()=>!C&&o.current===r,f=Math.max(50,Math.min(60000,i)),x=async()=>{if(!h()||b)return;b=!0,u(!0);let I=!1;try{let v=y>0;for(let P of g){let E=p.get(P),F=await t.changes(P,{...E!==void 0?{cursor:E}:{},limit:100});if(!h())return;if(!F.ok)throw c(F.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let D=E===void 0;if(D||v||F.data.items.length>0)await a.current(P,F.data,D);if(!h())return;p.set(P,F.data.cursor),I||=F.data.hasMore}y=0,c("live")}catch{if(y++,h())c((v)=>v==="expired"?"expired":"offline")}finally{if(b=!1,h())u(!1),m=setTimeout(()=>{x()},I&&y===0?0:Math.min(30000,f*2**Math.min(y,8)))}},w=()=>{if(m!==void 0)clearTimeout(m);x()};d.current=w,c("connecting"),x();let S=()=>{if(document.visibilityState==="visible")w()};return window.addEventListener("online",w),document.addEventListener("visibilitychange",S),()=>{if(C=!0,m!==void 0)clearTimeout(m);window.removeEventListener("online",w),document.removeEventListener("visibilitychange",S)}},[r,t,i]),Ni("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[or("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")&&or("button",{type:"button",className:"rounded border px-2 py-1",disabled:s,onClick:()=>d.current(),children:"Reconnect now"})]})}import{useEffect as xn,useRef as pt,useState as Be}from"react";import{jsx as X,jsxs as de,Fragment as Jn}from"react/jsx-runtime";var Gn={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function tn(e){try{return await e()}catch{return{ok:!1,error:Gn}}}function Yn({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return de("div",{className:"min-w-0",children:[X("strong",{children:t}),X("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&&de(Jn,{children:[X("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),X("button",{type:"button",onClick:()=>{let i=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),r=document.createElement("a");r.href=i,r.download=`record-${e?.id}-${e?.version}.json`,r.click(),setTimeout(()=>URL.revokeObjectURL(i),1000)},children:"Download snapshot"})]})]})}function Li({descriptor:e,recordId:t,client:n,readOnly:i=!1,onCommitted:r,registerRefresh:o}){let[a,d]=Be(null),[l,c]=Be(null),[s,u]=Be(null),[g,p]=Be(),[C,b]=Be(),[y,m]=Be([]),[h,f]=Be([]),[x,w]=Be(""),[S,I]=Be(null),[v,P]=Be(null),[E,F]=Be(null),[D,N]=Be(!1),[A,O]=Be(""),V=pt(null),R=pt(null),L=pt(n);L.current=n;let W=pt(!1),le=pt(0),_=`${e.id}:${t}`,J=pt(_);J.current=_;let oe=pt({historyBefore:g,commentBefore:C});oe.current={historyBefore:g,commentBefore:C};let T=pt(async()=>{}),B=(k=_)=>W.current&&J.current===k&&L.current===n,ee=async()=>{let k=_,U=++le.current,H=oe.current,[Te,bt]=await Promise.all([tn(()=>n.history(e.id,t,{...H.historyBefore===void 0?{}:{before:H.historyBefore},limit:20})),tn(()=>n.comments(e.id,t,{...H.commentBefore===void 0?{}:{before:H.commentBefore},limit:50}))]);if(!B(k)||U!==le.current)throw Error("Refresh superseded");if(!Te.ok||!bt.ok)throw O(!Te.ok?Te.error.message:!bt.ok?bt.error.message:Gn.message),Error("Activity refresh failed");c(Te.data),u(bt.data),d(k)};T.current=ee,xn(()=>(W.current=!0,()=>{W.current=!1,le.current++}),[]),xn(()=>(o?.(()=>T.current()),()=>o?.(null)),[o]),xn(()=>{if(J.current!==_)return;c(null),u(null),d(null),p(void 0),b(void 0),m([]),f([]),oe.current={historyBefore:void 0,commentBefore:void 0},w(""),I(null),P(null),F(null),V.current=null,R.current=null,N(!1),O("")},[_]),xn(()=>{if(J.current!==_||L.current!==n||oe.current.historyBefore!==g||oe.current.commentBefore!==C)return;T.current().catch(()=>{})},[_,n,g,C]);let se=(k)=>{let U=V.current;if(U?.signature===k)return U.key;let H={signature:k,key:crypto.randomUUID()};return V.current=H,H.key},Re=async(k)=>{if(D||i||!s||a!==_)return;let U=k==="delete"?v:S;if(k!=="create"&&(!U||U.authorId!==s.actorId))return;let H=k==="create"?x:S?.draft??"";if(k!=="delete"&&(!H.trim()||H.length>4000||H.includes("\x00"))){O("Comments require 1–4,000 characters.");return}let Te=se(JSON.stringify([k,U?.id,U?.version,H]));N(!0),O("");let bt=await tn(async()=>{if(k==="create")return n.createComment(e.id,t,{text:H,idempotencyKey:Te});if(!U)return{ok:!1,error:Gn};if(k==="edit")return n.editComment(e.id,t,U.id,{text:H,expectedVersion:U.version,idempotencyKey:Te});return n.deleteComment(e.id,t,U.id,{expectedVersion:U.version,idempotencyKey:Te})});if(!B())return;if(N(!1),!bt.ok){O(bt.error.message);return}if(V.current=null,k==="create")w("");else if(k==="edit")I(null);else P(null);if(k==="create"&&C!==void 0)b(void 0),f([]);else await T.current().catch(()=>{})},z=async(k)=>{if(D||i||!l||a!==_)return;N(!0),O(""),R.current=null;let U={targetVersion:k,expectedCurrentVersion:l.currentVersion,expectedSchemaVersion:e.schemaVersion},H=await tn(()=>n.previewUndo(e.id,t,U));if(!B())return;if(N(!1),H.ok)F(H.data);else F(null),O(H.error.message)},fe=async()=>{if(D||i||a!==_||!E&&!R.current)return;let k=R.current;if(!k){if(!E)return;k={targetVersion:E.targetVersion,expectedCurrentVersion:E.currentVersion,expectedSchemaVersion:E.schemaVersion,idempotencyKey:crypto.randomUUID()},R.current=k}let U=k;N(!0),O("");let H=await tn(()=>n.undo(e.id,t,U));if(!B())return;if(N(!1),!H.ok){if(H.error.code==="version_conflict"||H.error.code==="reference_conflict"||H.error.code==="validation")R.current=null,F(null);O(H.error.message),await T.current().catch(()=>{});return}R.current=null,F(null),r(H.data),p(void 0),m([]),await T.current().catch(()=>{})},Q=s?.items.find((k)=>k.id===S?.id),Ae=S&&Q&&Q.version!==S.version,M=E&&(E.currentVersion!==l?.currentVersion||E.schemaVersion!==e.schemaVersion);return de("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[de("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[de("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),X("button",{type:"button",disabled:D,onClick:()=>{O(""),T.current().catch(()=>{})},children:"Refresh activity"})]}),A&&X("p",{role:"alert",className:"text-sm text-destructive",children:A}),!l||!s||a!==_?X("p",{role:"status",children:"Loading record activity…"}):de(Jn,{children:[de("p",{role:"status",children:["Current version ",l.currentVersion,l.currentDeleted?" · Deleted record":""]}),X("h3",{className:"font-medium",children:"Comments"}),s.items.length===0&&X("p",{className:"text-sm",children:"No comments yet."}),X("ol",{className:"flex flex-col gap-3",children:s.items.map((k)=>de("li",{className:"min-w-0 rounded border p-3",children:[de("p",{className:"break-all text-xs",children:[k.authorId," · ",k.updatedAt," · version ",k.version]}),X("p",{className:"whitespace-pre-wrap break-words text-sm",children:k.text??"Comment deleted"}),!i&&k.text!==null&&k.authorId===s.actorId&&de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:D,onClick:()=>{I({...k,draft:k.text??""}),P(null),V.current=null},children:"Edit comment"}),X("button",{type:"button",disabled:D,onClick:()=>{P(k),I(null),V.current=null},children:"Delete comment"})]})]},k.id))}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:D||!h.length,onClick:()=>{b(h.at(-1)),f((k)=>k.slice(0,-1))},children:"Newer comments"}),X("button",{type:"button",disabled:D||s.nextCursor===null,onClick:()=>{f((k)=>[...k,C]),b(s.nextCursor??void 0)},children:"Older comments"})]}),!i&&de(Jn,{children:[S&&de("div",{className:"flex flex-col gap-2",children:[de("label",{children:["Edit comment text",X("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:D,maxLength:4000,value:S.draft,onChange:(k)=>{I({...S,draft:k.target.value}),V.current=null}})]}),Ae&&de("div",{role:"status",children:[X("p",{children:"This comment changed. Your draft and original version are kept."}),de("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",Q.text??"Comment deleted"]}),Q.text!==null&&Q.authorId===s.actorId&&X("button",{type:"button",disabled:D,onClick:()=>{I({...Q,draft:S.draft}),V.current=null},children:"Use current comment version"})]}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:D||S.authorId!==s.actorId,onClick:()=>void Re("edit"),children:"Save comment"}),X("button",{type:"button",disabled:D,onClick:()=>{I(null),V.current=null},children:"Cancel comment edit"})]})]}),v&&de("div",{children:[X("p",{children:"Delete this comment? A deletion marker will remain."}),X("p",{className:"whitespace-pre-wrap break-words",children:v.text}),X("button",{type:"button",disabled:D||v.authorId!==s.actorId,onClick:()=>void Re("delete"),children:"Confirm delete comment"}),X("button",{type:"button",disabled:D,onClick:()=>P(null),children:"Cancel delete comment"})]}),de("label",{children:["New comment",X("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:D,maxLength:4000,value:x,onChange:(k)=>{w(k.target.value),V.current=null}})]}),X("button",{type:"button",className:"self-start",disabled:D||!x.trim(),onClick:()=>void Re("create"),children:"Add comment"})]}),X("h3",{className:"font-medium",children:"Record history"}),X("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."}),X("ol",{className:"flex flex-col gap-3",children:l.items.map((k)=>de("li",{className:"min-w-0 rounded border p-3",children:[de("p",{className:"break-all text-xs",children:["Version ",k.version," · ",k.operation," · schema ",k.schemaVersion," · ",k.actorId," ·"," ",k.createdAt]}),de("details",{children:[de("summary",{children:["Stored values at version ",k.version]}),X(Yn,{record:k.snapshot,label:`Version ${k.version}`})]}),!i&&k.version<l.currentVersion&&de("button",{type:"button",disabled:D,onClick:()=>void z(k.version),children:["Preview restore version ",k.version]})]},k.id))}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:D||!y.length,onClick:()=>{p(y.at(-1)),m((k)=>k.slice(0,-1))},children:"Newer history"}),X("button",{type:"button",disabled:D||l.nextCursor===null,onClick:()=>{m((k)=>[...k,g]),p(l.nextCursor??void 0)},children:"Older history"})]}),!i&&E&&de("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[de("h3",{children:["Restore version ",E.targetVersion," as a new version"]}),de("p",{children:["Current version ",E.currentVersion," · schema ",E.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),de("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[X(Yn,{record:E.before,label:"Current stored values"}),X(Yn,{record:E.target,label:"Values to restore"})]}),M&&!R.current&&X("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:D||!!M&&!R.current,onClick:()=>void fe(),children:R.current?"Retry undo":"Confirm restore"}),X("button",{type:"button",disabled:D,onClick:()=>{F(null),R.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as Pn,useRef as gt,useState as it}from"react";import{jsx as Ie,jsxs as Ue,Fragment as rr}from"react/jsx-runtime";async function kn(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 Oi(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let i of t)n+=String.fromCharCode(i);return btoa(n)}function Vi({collectionId:e,recordId:t,client:n,readOnly:i=!1,registerRefresh:r}){let o=`${e}:${t}`,a=gt({identity:o,client:n});a.current={identity:o,client:n};let d=gt(!1),l=gt(0),c=gt(0),[s,u]=it(null),[g,p]=it(null),[C,b]=it(),[y,m]=it([]),h=gt(C);h.current=C;let[f,x]=it(null),[w,S]=it(null),I=gt(null),v=gt(null),[P,E]=it(!1),[F,D]=it(!1),[N,A]=it(""),O=()=>d.current&&a.current.identity===o&&a.current.client===n,V=async()=>{let _=++l.current,J=await kn(()=>n.list(e,t,{limit:20,...h.current===void 0?{}:{before:h.current}}));if(!O()||_!==l.current)throw Error("Refresh superseded");if(!J.ok)throw A(J.error.message),Error("Attachment refresh failed");p(J.data),u(o)},R=gt(V);R.current=V,Pn(()=>(d.current=!0,()=>{d.current=!1,++l.current,++c.current}),[]),Pn(()=>{if(a.current.identity!==o||a.current.client!==n)return;u(null),p(null),x(null),S(null),I.current=null,E(!1),D(!1),A(""),b(void 0),m([]),h.current=void 0,++c.current,R.current().catch(()=>{})},[o,n]),Pn(()=>{if(h.current===C&&s===o)R.current().catch(()=>{})},[C,o,s]),Pn(()=>(r?.(()=>R.current()),()=>r?.(null)),[r]);let L=async()=>{if(P||i||!f||s!==o)return;let _=f;E(!0),A("");let J=await kn(()=>n.upload(e,t,_));if(!O())return;if(E(!1),!J.ok){A(J.error.message);return}if(x(null),v.current)v.current.value="";b(void 0),m([]),h.current=void 0,await R.current().catch(()=>{})},W=async()=>{if(P||i||!w||w.authorId!==g?.actorId||s!==o)return;I.current??=crypto.randomUUID();let _=w,J=I.current;E(!0),A("");let oe=await kn(()=>n.delete(e,t,_.id,{expectedVersion:_.version,idempotencyKey:J}));if(!O())return;if(E(!1),!oe.ok){A(oe.error.message),await R.current().catch(()=>{});return}S(null),I.current=null,await R.current().catch(()=>{})},le=async(_)=>{if(P||s!==o)return;E(!0),A("");let J=await kn(()=>n.content(e,t,_.id));if(!O())return;if(E(!1),!J.ok){A(J.error.message);return}let oe=Uint8Array.from(atob(J.data.base64),(ee)=>ee.charCodeAt(0)),T=URL.createObjectURL(new Blob([oe],{type:"application/octet-stream"})),B=document.createElement("a");B.href=T,B.download=J.data.attachment.name,B.click(),setTimeout(()=>URL.revokeObjectURL(T),1000)};return Ue("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Ue("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ie("h3",{className:"font-medium",children:"Attachments"}),Ie("button",{type:"button",disabled:P,onClick:()=>{A(""),R.current().catch(()=>{})},children:"Refresh attachments"})]}),N&&Ie("p",{role:"alert",children:N}),!g||s!==o?Ie("p",{role:"status",children:"Loading attachments…"}):Ue(rr,{children:[g.items.length===0&&Ie("p",{children:"No attachments yet."}),Ie("ol",{className:"flex min-w-0 flex-col gap-2",children:g.items.map((_)=>Ue("li",{className:"min-w-0 rounded border p-2",children:[Ie("p",{className:"break-all",children:_.name}),Ue("p",{className:"break-all text-xs",children:[_.size," bytes · version ",_.version," · ",_.authorId]}),_.deletedAt?Ie("p",{children:"Attachment deleted"}):Ue("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:P,"aria-label":`Download attachment ${_.name}`,onClick:()=>void le(_),children:"Download"}),!i&&_.authorId===g.actorId&&Ie("button",{type:"button",disabled:P,"aria-label":`Delete attachment ${_.name}`,onClick:()=>{S(_),I.current=null},children:"Delete"})]})]},_.id))}),Ue("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:P||!y.length,onClick:()=>{b(y.at(-1)),m((_)=>_.slice(0,-1))},children:"Newer attachments"}),Ie("button",{type:"button",disabled:P||g.nextCursor===null,onClick:()=>{m((_)=>[..._,C]),b(g.nextCursor??void 0)},children:"Older attachments"})]}),!i&&Ue(rr,{children:[Ie("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."}),Ue("label",{children:["Attachment file",Ie("input",{ref:v,"aria-label":"Attachment file",type:"file",disabled:P||F,onChange:async(_)=>{let J=_.target.files?.[0];if(!J)return;let oe=++c.current;if(x(null),A(""),!J.size||J.size>1048576){A("Choose a nonempty file up to 1 MiB.");return}D(!0);try{let T=await Oi(J);if(!O()||oe!==c.current)return;let B=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(J.type)?J.type:"application/octet-stream";x({name:J.name,contentType:B,base64:T,idempotencyKey:crypto.randomUUID()})}catch{if(O()&&oe===c.current)A("The selected file could not be read.")}finally{if(O()&&oe===c.current)D(!1)}}},o)]}),f&&Ue("p",{className:"break-all",children:["Selected file: ",f.name]}),Ie("button",{type:"button",className:"self-start",disabled:P||F||!f,onClick:()=>void L(),children:"Upload attachment"}),w&&Ue("div",{children:[Ue("p",{className:"break-all",children:["Delete ",w.name,"? This permanently removes its bytes and keeps a deletion marker."]}),Ue("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:P,onClick:()=>void W(),children:"Confirm delete attachment"}),Ie("button",{type:"button",disabled:P,onClick:()=>{S(null),I.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as wn,useRef as Ut,useState as _e}from"react";import{jsx as ue,jsxs as be,Fragment as ir}from"react/jsx-runtime";async function Zn(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function Bi(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function Ui({descriptor:e,recordIds:t,client:n,linkForGrant:i,registerRefresh:r}){let o=e.id,a=Ut({identity:o,client:n});a.current={identity:o,client:n};let d=Ut(!1),l=Ut(0),[c,s]=_e(null),[u,g]=_e(null),[p,C]=_e(),b=Ut(p);b.current=p;let[y,m]=_e([]),[h,f]=_e([]),[x,w]=_e([]),[S,I]=_e(3600),[v,P]=_e(null),[E,F]=_e(!1),[D,N]=_e(""),[A,O]=_e(null),V=Ut(null),[R,L]=_e(!1),[W,le]=_e(""),_=()=>d.current&&a.current.identity===o&&a.current.client===n,J=async()=>{let z=++l.current,fe=await Zn(()=>n.list(o,{limit:20,...b.current===void 0?{}:{before:b.current}}));if(!_()||z!==l.current)throw Error("Refresh superseded");if(!fe.ok)throw le(fe.error.message),Error("Share refresh failed");g(fe.data),s(o)},oe=Ut(J);oe.current=J,wn(()=>(d.current=!0,()=>{d.current=!1,++l.current}),[]),wn(()=>{if(a.current.identity!==o||a.current.client!==n)return;s(null),g(null),f([]),w([]),P(null),F(!1),N(""),O(null),V.current=null,L(!1),le(""),C(void 0),m([]),b.current=void 0,oe.current().catch(()=>{})},[o,n]),wn(()=>{if(b.current===p&&c===o)oe.current().catch(()=>{})},[p,c,o]),wn(()=>(r?.(()=>oe.current()),()=>r?.(null)),[r]);let T=()=>{if(!E)P(null)},B=async()=>{if(R||!v||c!==o)return;let z=v;L(!0),F(!0),le("");let fe=await Zn(()=>n.create(o,z));if(!_())return;if(L(!1),!fe.ok){le(fe.error.message);return}N(i(fe.data,z.key)),P(null),F(!1),C(void 0),m([]),b.current=void 0,await oe.current().catch(()=>{})},ee=async()=>{if(R||!A||c!==o)return;let z=A;V.current??=crypto.randomUUID();let fe=V.current;L(!0),le("");let Q=await Zn(()=>n.revoke(o,z.id,{expectedVersion:z.version,idempotencyKey:fe}));if(!_())return;if(L(!1),!Q.ok){le(Q.error.message),await oe.current().catch(()=>{});return}O(null),V.current=null,N(""),await oe.current().catch(()=>{})},se=e.fields.filter((z)=>!["linkedRecord","lookup","formula","rollup"].includes(z.type)),Re=R||E;return be("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[be("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[ue("h3",{className:"font-medium",children:"Read-only sharing"}),ue("button",{type:"button",disabled:R,onClick:()=>{le(""),oe.current().catch(()=>{})},children:"Refresh share grants"})]}),ue("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."}),ue("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."}),W&&ue("p",{role:"alert",children:W}),be("fieldset",{disabled:Re,className:"flex min-w-0 flex-col gap-2",children:[ue("legend",{children:"Fields to share"}),se.map((z)=>be("label",{className:"break-all",children:[ue("input",{type:"checkbox","aria-label":`Share field ${z.name}`,checked:h.includes(z.id),onChange:(fe)=>{T(),f((Q)=>fe.target.checked?[...Q,z.id]:Q.filter((Ae)=>Ae!==z.id))}})," ",z.name]},z.id))]}),be("fieldset",{disabled:Re,className:"flex min-w-0 flex-col gap-2",children:[ue("legend",{children:"Records on the current page"}),t.slice(0,100).map((z)=>be("label",{className:"break-all",children:[ue("input",{type:"checkbox","aria-label":`Share record ${z}`,checked:x.includes(z),onChange:(fe)=>{T(),w((Q)=>fe.target.checked?[...Q,z]:Q.filter((Ae)=>Ae!==z))}})," ",z]},z)),t.length===0&&ue("p",{children:"Load records in Grid to choose a share scope."})]}),be("p",{className:"break-all text-xs",children:["Selected record IDs: ",x.join(", ")||"none"]}),be("label",{children:["Link lifetime"," ",be("select",{"aria-label":"Share link lifetime",disabled:Re,value:S,onChange:(z)=>{T(),I(Number(z.target.value))},children:[ue("option",{value:60,children:"1 minute"}),ue("option",{value:3600,children:"1 hour"}),ue("option",{value:86400,children:"24 hours"})]})]}),ue("button",{type:"button",className:"self-start",disabled:Re||c!==o||!h.length||!x.length||x.length>100||h.some((z)=>!se.some((fe)=>fe.id===z)),onClick:()=>{le("");try{P({expectedSchemaVersion:e.schemaVersion,fieldIds:[...h],recordIds:[...x],expiresInSeconds:S,key:Bi(),idempotencyKey:crypto.randomUUID()})}catch{le("A secure share key could not be generated.")}},children:"Review read-only share"}),v&&be("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[be("p",{className:"break-all",children:["Confirm schema ",v.expectedSchemaVersion,", fields ",v.fieldIds.join(", "),", records ",v.recordIds.join(", ")," for ",v.expiresInSeconds," seconds."]}),v.expectedSchemaVersion!==e.schemaVersion&&ue("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),be("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:R,onClick:()=>void B(),children:E?"Retry create read link":"Create read link"}),ue("button",{type:"button",disabled:R,onClick:()=>{P(null),F(!1),le("")},children:"Discard share confirmation"})]}),E&&ue("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&&be("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",ue("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:D,onFocus:(z)=>z.target.select()})]}),!u||c!==o?ue("p",{role:"status",children:"Loading share grants…"}):be(ir,{children:[u.items.length===0&&ue("p",{children:"No share grants yet."}),ue("ol",{className:"flex min-w-0 flex-col gap-2",children:u.items.map((z)=>be("li",{className:"min-w-0 rounded border p-2",children:[be("p",{className:"break-all",children:["Grant ",z.id," · version ",z.version," · schema ",z.schemaVersion]}),be("p",{className:"break-all text-xs",children:["Fields: ",z.fieldIds.join(", ")," · Records: ",z.recordIds.join(", ")," · Expires:"," ",z.expiresAt]}),z.revokedAt?ue("p",{children:"Share revoked"}):be(ir,{children:[ue("p",{children:z.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(z.expiresAt)<=Date.now()?"Share expired":"Share active"}),ue("button",{type:"button",disabled:R,"aria-label":`Revoke share ${z.id}`,onClick:()=>{O(z),V.current=null},children:"Revoke"})]})]},z.id))}),be("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:R||!y.length,onClick:()=>{C(y.at(-1)),m((z)=>z.slice(0,-1))},children:"Newer share grants"}),ue("button",{type:"button",disabled:R||u.nextCursor===null,onClick:()=>{m((z)=>[...z,p]),C(u.nextCursor??void 0)},children:"Older share grants"})]})]}),A&&be("div",{children:[be("p",{className:"break-all",children:["Revoke grant ",A.id," at version ",A.version,"? Every existing share session will lose access."]}),be("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:R,onClick:()=>void ee(),children:"Confirm revoke share"}),ue("button",{type:"button",disabled:R,onClick:()=>{O(null),V.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as ar,useRef as _t,useState as Ee}from"react";import{jsx as te,jsxs as Ce}from"react/jsx-runtime";var lr=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],_i=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function qi({descriptor:e,recordIds:t,client:n,webhookRequest:i}){let r=e.id,o=_t({id:r,client:n});o.current={id:r,client:n};let a=_t(!0),d=_t(0),[l,c]=Ee([]),[s,u]=Ee(""),g=_t(s);g.current=s;let[p,C]=Ee(null),[b,y]=Ee(),m=_t(b);m.current=b;let[h,f]=Ee(""),[x,w]=Ee("record"),[S,I]=Ee(60),[v,P]=Ee([]),[E,F]=Ee([]),[D,N]=Ee({}),[A,O]=Ee(null),[V,R]=Ee(!1),[L,W]=Ee(!1),[le,_]=Ee(""),[J,oe]=Ee(""),T=()=>a.current&&o.current.id===r&&o.current.client===n,B=async(M)=>{try{return await M()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},ee=async()=>{let M=++d.current,k=await B(()=>n.list(r));if(!T()||M!==d.current)return;if(!k.ok){_(k.error.message);return}c(k.data);let U=k.data.find((Te)=>Te.id===g.current)?.id??k.data[0]?.id??"";if(g.current=U,u(U),!U){C(null);return}let H=await B(()=>n.runs(r,U,{limit:20,...m.current?{before:m.current}:{}}));if(!T()||M!==d.current||g.current!==U)return;if(H.ok)C(H.data);else _(H.error.message)},se=_t(ee);se.current=ee,ar(()=>{if(o.current.id!==r||o.current.client!==n)return;a.current=!0,se.current();let M=setInterval(()=>void se.current(),5000);return()=>{a.current=!1,++d.current,clearInterval(M)}},[r,n]),ar(()=>{if(g.current!==s||m.current!==b)return;se.current()},[s,b]);let Re=()=>{if(_(""),!h.trim()||!v.length||x!=="record"&&!E.length){_("Choose a name, writable fields, and target records for time or webhook triggers.");return}let M=Object.fromEntries(v.map((U)=>[U,D[U]??null])),k={expectedSchemaVersion:e.schemaVersion,name:h.trim(),trigger:x==="time"?{kind:x,intervalSeconds:S}:{kind:x},targetRecordIds:E,values:M,idempotencyKey:crypto.randomUUID(),...x==="webhook"?{webhookKey:_i()}:{}};O({kind:"create",input:k}),R(!1)},z=(M)=>{O(M),R(!1),_("")},fe=async()=>{if(!A||L)return;let M=A,k=V;R(!0),W(!0),_("");let U=await B(()=>M.kind==="create"?n.create(r,M.input):M.kind==="toggle"?n.toggle(r,M.a.id,M.input):M.kind==="run"?n.runNow(r,M.a.id,M.input):n.retry(r,M.a.id,M.run.id,M.input));if(!T())return;if(W(!1),!U.ok){if(!k&&U.error.status>=400&&U.error.status<500)R(!1);_(`${U.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(M.kind==="create"){let H=U.data;if(g.current=H.id,u(H.id),M.input.webhookKey&&i)oe(JSON.stringify(i(H,M.input.webhookKey),null,2));f(""),P([]),F([]),N({})}O(null),R(!1),m.current=void 0,y(void 0),await se.current()},Q=l.find((M)=>M.id===s),Ae=!!A||L;return Ce("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[te("p",{children:"Update chosen fields through record changes, a timed interval or a private webhook. Runs keep their original schema and record versions. Automatic changes do not trigger another automation."}),te("button",{type:"button",onClick:()=>void se.current(),children:"Refresh automation"}),le&&te("p",{role:"alert",children:le}),te("form",{onSubmit:(M)=>{M.preventDefault(),Re()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:Ce("fieldset",{disabled:Ae,style:{minWidth:0},children:[te("legend",{children:"New automation"}),Ce("label",{children:["Name"," ",te("input",{"aria-label":"Automation name",value:h,maxLength:200,onChange:(M)=>f(M.target.value)})]}),Ce("label",{children:["Trigger"," ",Ce("select",{"aria-label":"Automation trigger",value:x,onChange:(M)=>w(M.target.value),children:[te("option",{value:"record",children:"Record changes"}),te("option",{value:"time",children:"Timed interval"}),te("option",{value:"webhook",children:"Private webhook"})]})]}),x==="time"&&Ce("label",{children:["Interval in seconds"," ",te("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:S,onChange:(M)=>I(Number(M.target.value))})]}),Ce("fieldset",{children:[te("legend",{children:"Fields to update"}),e.fields.filter((M)=>lr.includes(M.type)).map((M)=>Ce("label",{style:{display:"block"},children:[te("input",{type:"checkbox",checked:v.includes(M.id),onChange:(k)=>{P(k.target.checked?[...v,M.id]:v.filter((U)=>U!==M.id))}}),M.name]},M.id))]}),te(St,{fields:e.fields.filter((M)=>v.includes(M.id)&&lr.includes(M.type)),values:D,onChange:N}),Ce("fieldset",{children:[te("legend",{children:"Target records from this page"}),x==="record"&&te("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&te("p",{children:"Open a grid page to choose fixed records."}),t.map((M)=>Ce("label",{style:{display:"block",overflowWrap:"anywhere"},children:[te("input",{type:"checkbox","aria-label":`Automation target ${M}`,checked:E.includes(M),onChange:(k)=>F(k.target.checked?[...E,M]:E.filter((U)=>U!==M))}),M]},M))]}),te("button",{type:"submit",children:"Review automation"})]})}),A&&Ce("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[te("p",{children:A.kind==="create"?`Create ${A.input.name} using schema ${A.input.expectedSchemaVersion}; ${A.input.targetRecordIds.length||"event"} targets.`:A.kind==="toggle"?`${A.input.enabled?"Enable":"Disable"} ${A.a.name}. Disabling fences queued and running work.`:A.kind==="run"?`Run ${A.a.name} for ${A.input.recordIds.length} explicitly selected records.`:`Retry ${A.a.name}, run ${A.run.sequence}, using its original record versions.`}),A.kind==="create"&&te("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(A.input.values,null,2)}),te("button",{type:"button",disabled:L,onClick:()=>void fe(),children:L?"Confirming…":V?"Retry automation confirmation":"Confirm automation"}),te("button",{type:"button",disabled:V||L,onClick:()=>O(null),children:"Cancel automation review"}),V&&te("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),J&&Ce("div",{children:[te("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),te("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:J}),te("button",{type:"button",onClick:()=>oe(""),children:"Hide webhook key"})]}),l.length>0&&Ce("label",{children:["Automation"," ",te("select",{"aria-label":"Selected automation",disabled:Ae,value:s,onChange:(M)=>{g.current=M.target.value,m.current=void 0,y(void 0),u(M.target.value),C(null)},children:l.map((M)=>te("option",{value:M.id,children:M.name},M.id))})]}),Q&&Ce("div",{children:[Ce("p",{children:[Q.enabled?"Enabled":"Disabled"," · ",Q.trigger.kind," · schema ",Q.schemaVersion," · configuration ",Q.version]}),te("button",{type:"button",disabled:Ae,onClick:()=>z({kind:"toggle",a:Q,input:{expectedVersion:Q.version,enabled:!Q.enabled,idempotencyKey:crypto.randomUUID()}}),children:Q.enabled?"Review disable automation":"Review enable automation"}),te("button",{type:"button",disabled:Ae||!Q.enabled||!(Q.targetRecordIds.length||t.length),onClick:()=>z({kind:"run",a:Q,input:{recordIds:Q.targetRecordIds.length?Q.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),p&&Ce("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!p.items.length&&te("p",{children:"No runs yet."}),p.items.map((M)=>Ce("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[Ce("p",{children:["Run ",M.sequence," · ",M.triggerKind," · ",M.status," · step ",M.step]}),Ce("p",{children:["Attempts: evaluate ",M.stepAttempts.evaluate,", apply ",M.stepAttempts.apply," · original versions: ",M.expectedRows.map((k)=>`${k.id}: ${k.version}`).join(", ")]}),M.errorCode&&te("p",{role:"status",children:M.errorCode}),M.leaseUntil&&Ce("p",{children:["Lease expires ",M.leaseUntil]}),Q&&M.status==="failed"&&Ce("button",{type:"button",disabled:Ae||!Q.enabled,onClick:()=>z({kind:"retry",a:Q,run:M,input:{expectedVersion:M.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",M.sequence]})]},M.id)),te("button",{type:"button",disabled:Ae||b===void 0,onClick:()=>{m.current=void 0,y(void 0)},children:"Newest runs"}),te("button",{type:"button",disabled:Ae||p.nextCursor===null,onClick:()=>{m.current=p.nextCursor??void 0,y(m.current)},children:"Older runs"})]})]})}import{useEffect as $i,useId as zi,useRef as sr,useState as De}from"react";import{jsx as ce,jsxs as he}from"react/jsx-runtime";var dr=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function ji(e,t,n){if(!n.resourceId||!n.model.trim()||n.model.length>200||!n.instruction.trim()||new TextEncoder().encode(n.instruction).length>2000||n.recordIds.length<1||n.recordIds.length>10||new Set(n.recordIds).size!==n.recordIds.length)throw Error("Choose an AI resource, model, instruction and up to ten records.");for(let r of[n.sourceFieldIds,n.targetFieldIds])if(r.length<1||r.length>10||new Set(r).size!==r.length||r.some((o)=>!e.fields.some((a)=>a.id===o&&dr.includes(a.type))))throw Error("Choose up to ten basic source and target fields.");let i=n.recordIds.map((r)=>{let o=t.find((a)=>a.id===r);if(!o)throw Error("A selected record is no longer on this page.");return{id:r,expectedVersion:o.version}});return structuredClone({expectedSchemaVersion:e.schemaVersion,resourceId:n.resourceId,model:n.model.trim(),instruction:n.instruction,records:i,sourceFieldIds:n.sourceFieldIds,targetFieldIds:n.targetFieldIds,idempotencyKey:crypto.randomUUID()})}function Hi({descriptor:e,records:t,client:n,onApplied:i}){let r=zi(),o=e.id,a=sr({id:o,client:n}),d=sr(!0);a.current={id:o,client:n};let[l,c]=De([]),[s,u]=De(!1),[g,p]=De(""),[C,b]=De(""),[y,m]=De(""),[h,f]=De([]),[x,w]=De([]),[S,I]=De([]),[v,P]=De(null),[E,F]=De(null),[D,N]=De(null),[A,O]=De(!1),[V,R]=De(!1),[L,W]=De(""),[le,_]=De(""),[J,oe]=De(""),T=()=>d.current&&a.current.id===o&&a.current.client===n,B=async(k)=>{try{return await k()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};$i(()=>{d.current=!0,P(null),F(null),N(null),O(!1),W(""),_(""),oe(""),f([]),w([]),I([]),m("");let k=!0;return u(!1),R(!1),c([]),p(""),b(""),n.providers(o).then((U)=>{if(!k||a.current.id!==o||a.current.client!==n)return;if(u(!0),U.ok)c(U.data),p(U.data[0]?.resourceId??""),b(U.data[0]?.allowedModels[0]??"");else W(U.error.message)}).catch(()=>{if(k)u(!0),W("AI configuration is unavailable.")}),()=>{k=!1,d.current=!1}},[o,n]);let ee=()=>{try{let k=ji(e,t,{resourceId:g,model:C,instruction:y,recordIds:h,sourceFieldIds:x,targetFieldIds:S});F(structuredClone(k.records.map((U)=>({id:U.id,version:U.expectedVersion,values:Object.fromEntries(k.sourceFieldIds.map((H)=>[H,t.find((Te)=>Te.id===U.id)?.values[H]??null]))})))),P(k),O(!1),W(""),_("")}catch(k){W(k instanceof Error?k.message:"Invalid selection.")}},se=async()=>{if(!v||V)return;let k=v,U=A;R(!0),O(!0),W("");let H=await B(()=>n.propose(o,k));if(!T())return;if(R(!1),!H.ok){if(!U&&H.error.status>=400&&H.error.status<500)O(!1);W(`${H.error.message} Retry keeps the original selection and versions.`);return}N(H.data),oe(H.data.id),O(!1)},Re=async()=>{if(!D||V)return;let k=D,U=A;R(!0),O(!0),W("");let H=await B(()=>n.confirm(o,k));if(!T())return;if(R(!1),!H.ok){if(!U&&H.error.status>=400&&H.error.status<500)O(!1);W(`${H.error.message} The reviewed proposal keeps its original versions.`);return}_(`${H.data.items.length} records filled${H.data.replayed?"; original receipt recovered":""}.`),N(null),P(null),F(null),O(!1);try{await i?.()}catch{if(T())W("The fill committed. Refresh the Collection to see its records.")}},z=async()=>{if(V||v||D)return;R(!0),W("");let k=await B(()=>n.get(o,J));if(!T())return;if(R(!1),k.ok)N(k.data),O(!1),_("");else W(k.error.message)},fe=(k,U,H)=>H(k.includes(U)?k.filter((Te)=>Te!==U):[...k,U]),Q=V||!!v||!!D,Ae=e.fields.filter((k)=>dr.includes(k.type)),M=l.find((k)=>k.resourceId===g);return he("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[ce("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."}),L&&ce("p",{role:"alert",children:L}),le&&ce("p",{role:"status",children:le}),s&&l.length===0&&ce("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),ce("form",{onSubmit:(k)=>{k.preventDefault(),ee()},children:he("fieldset",{disabled:Q,style:{minWidth:0},children:[ce("legend",{children:"AI fill request"}),he("label",{children:["AI resource"," ",he("select",{"aria-label":"AI resource",value:g,onChange:(k)=>{p(k.target.value),b(l.find((U)=>U.resourceId===k.target.value)?.allowedModels[0]??"")},children:[ce("option",{value:"",children:"Choose resource"}),l.map((k)=>ce("option",{value:k.resourceId,children:k.name},k.resourceId))]})]}),he("label",{htmlFor:r,children:["Model"," ",M?.allowedModels.length?ce("select",{id:r,"aria-label":"AI model",value:C,onChange:(k)=>b(k.target.value),children:M.allowedModels.map((k)=>ce("option",{value:k,children:k},k))}):ce("input",{id:r,"aria-label":"AI model",maxLength:200,value:C,onChange:(k)=>b(k.target.value)})]}),he("label",{children:["Instructions"," ",ce("textarea",{"aria-label":"AI instructions",maxLength:2000,value:y,onChange:(k)=>m(k.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),he("fieldset",{children:[ce("legend",{children:"Source fields to send"}),Ae.map((k)=>he("label",{style:{display:"block"},children:[ce("input",{type:"checkbox","aria-label":`Send ${k.name}`,checked:x.includes(k.id),onChange:()=>fe(x,k.id,w)}),k.name]},k.id))]}),he("fieldset",{children:[ce("legend",{children:"Fields to fill"}),Ae.map((k)=>he("label",{style:{display:"block"},children:[ce("input",{type:"checkbox","aria-label":`Fill ${k.name}`,checked:S.includes(k.id),onChange:()=>fe(S,k.id,I)}),k.name]},k.id))]}),he("fieldset",{children:[ce("legend",{children:"Target records from this page"}),t.map((k)=>he("label",{style:{display:"block",overflowWrap:"anywhere"},children:[ce("input",{type:"checkbox","aria-label":`AI record ${k.id}`,checked:h.includes(k.id),onChange:()=>fe(h,k.id,f)}),k.id," · version ",k.version]},k.id))]}),ce("button",{type:"submit",disabled:!g,children:"Review AI request"})]})}),v&&!D&&he("section",{"aria-label":"AI data disclosure",children:[he("p",{children:["Selected service: ",v.resourceId," · model ",v.model," · schema"," ",v.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),ce("p",{children:v.instruction}),ce("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(E,null,2)}),ce("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),ce("button",{type:"button",disabled:V,onClick:()=>void se(),children:A?"Retry original AI request":"Generate proposal"}),ce("button",{type:"button",disabled:V||A,onClick:()=>{P(null),F(null),W("")},children:"Cancel AI request"})]}),D&&he("section",{"aria-label":"AI fill confirmation",children:[he("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",D.id," · ",D.provider," · schema ",D.schemaVersion]}),D.schemaVersion!==e.schemaVersion&&ce("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),D.rows.map((k)=>he("div",{style:{overflowWrap:"anywhere"},children:[he("p",{children:[k.id," · original version ",k.expectedVersion]}),Object.keys(k.values).map((U)=>he("div",{children:[ce("strong",{children:e.fields.find((H)=>H.id===U)?.name??U}),he("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(k.before[U]),`
|
|
10
|
-
`,"Suggested: ",JSON.stringify(k.values[U])]})]},U))]},k.id)),ce("button",{type:"button",disabled:V,onClick:()=>void Re(),children:A?"Retry original AI fill":"Confirm fill"}),ce("button",{type:"button",disabled:V||A,onClick:()=>{N(null),P(null),F(null),W("")},children:"Dismiss proposal"})]}),he("label",{children:["Recover a saved proposal"," ",ce("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:J,onChange:(k)=>oe(k.target.value),disabled:Q,style:{width:"100%",boxSizing:"border-box"}})]}),ce("button",{type:"button",disabled:Q||!/^[a-f0-9]{64}$/.test(J),onClick:()=>void z(),children:"Load saved proposal"})]})}import{jsx as j,jsxs as ne}from"react/jsx-runtime";var Wi=[{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 Sc({fields:e,onChange:t,lockedIds:n=[],collections:i=[]}){let r=(o,a)=>t(e.map((d,l)=>l===o?{...d,...a}:d));return ne("div",{className:"flex flex-col gap-3",children:[e.map((o,a)=>{let d=n.includes(o.id);return ne("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)] gap-2 rounded-md border p-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_150px_auto]",children:[j("input",{"aria-label":`Field ${a+1} name`,placeholder:"Display name",value:o.name,onChange:(l)=>r(a,{name:l.target.value})}),j("input",{"aria-label":`Field ${a+1} ID`,placeholder:"field_id",value:o.id,disabled:d,onChange:(l)=>r(a,{id:l.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:(l)=>{let c=l.target.value,s={id:o.id,name:o.name,type:c,required:Me({type:c})?!1:o.required??!1};if(c==="formula")s.formula={expression:""};if(c==="rollup")s.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(c==="singleSelect"||c==="multipleSelect")s.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((u,g)=>g===a?s:u))},children:Wi.map((l)=>j("option",{value:l.value,children:l.name},l.value))}),ne("div",{className:"flex items-center gap-2",children:[ne("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:(l)=>r(a,{required:l.target.checked})}),"Required"]}),!d&&j("button",{type:"button",onClick:()=>t(e.filter((l,c)=>c!==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((l)=>l.name).join(", ")??"",disabled:d,onChange:(l)=>r(a,{options:l.target.value.split(",").map((c,s)=>({id:c.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${s}`,name:c.trim()})).filter((c)=>c.name)})}),o.type==="linkedRecord"&&ne("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ne("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",ne("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} linked collection`,value:o.link?.collectionId??"",disabled:d,onChange:(l)=>{let c=i.find((s)=>s.id===l.target.value);r(a,{link:{collectionId:l.target.value,displayFieldId:c?.fields.find((s)=>s.type==="singleLineText"||s.type==="longText")?.id??""}})},children:[j("option",{value:"",children:"Choose collection…"}),i.map((l)=>j("option",{value:l.id,children:l.name},l.id))]})]}),ne("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",ne("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} record label`,value:o.link?.displayFieldId??"",disabled:d||!o.link?.collectionId,onChange:(l)=>r(a,{link:{collectionId:o.link?.collectionId??"",displayFieldId:l.target.value}}),children:[j("option",{value:"",children:"Choose text field…"}),i.find((l)=>l.id===o.link?.collectionId)?.fields.filter((l)=>l.type==="singleLineText"||l.type==="longText").map((l)=>j("option",{value:l.id,children:l.name},l.id))]})]})]}),o.type==="lookup"&&ne("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ne("label",{children:["Through linked field"," ",ne("select",{"aria-label":`Field ${a+1} lookup link`,value:o.lookup?.linkFieldId??"",disabled:d,onChange:(l)=>r(a,{lookup:{linkFieldId:l.target.value,targetFieldId:""}}),children:[j("option",{value:"",children:"Choose linked field…"}),e.filter((l)=>l.type==="linkedRecord"&&l.link).map((l)=>j("option",{value:l.id,children:l.name},l.id))]})]}),ne("label",{children:["Read target field"," ",ne("select",{"aria-label":`Field ${a+1} lookup target`,value:o.lookup?.targetFieldId??"",disabled:d||!o.lookup?.linkFieldId,onChange:(l)=>r(a,{lookup:{linkFieldId:o.lookup?.linkFieldId??"",targetFieldId:l.target.value}}),children:[j("option",{value:"",children:"Choose target field…"}),i.find((l)=>l.id===e.find((c)=>c.id===o.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((l)=>!Me(l)&&l.type!=="linkedRecord").map((l)=>j("option",{value:l.id,children:l.name},l.id))]})]}),j("small",{children:"Computed from linked records. Values cannot be edited."})]}),o.type==="formula"&&ne("div",{className:"flex flex-col gap-1 md:col-span-4",children:[ne("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:(l)=>r(a,{formula:{expression:l.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."}),ne("small",{children:["References:"," ",e.filter((l)=>l.id!==o.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"]})]}),o.type==="rollup"&&ne("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ne("label",{children:["Through linked field"," ",ne("select",{"aria-label":`Field ${a+1} rollup link`,value:o.rollup?.linkFieldId??"",onChange:(l)=>r(a,{rollup:{linkFieldId:l.target.value,targetFieldId:"",function:o.rollup?.function??"sum"}}),children:[j("option",{value:"",children:"Choose linked field…"}),e.filter((l)=>l.type==="linkedRecord"&&l.link).map((l)=>j("option",{value:l.id,children:l.name},l.id))]})]}),ne("label",{children:["Aggregate"," ",ne("select",{"aria-label":`Field ${a+1} rollup function`,value:o.rollup?.function??"sum",onChange:(l)=>{let c=l.target.value,s=i.find((u)=>u.id===e.find((g)=>g.id===o.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((u)=>u.id===o.rollup?.targetFieldId);r(a,{rollup:{linkFieldId:o.rollup?.linkFieldId??"",targetFieldId:c==="count"||s?.type==="number"?o.rollup?.targetFieldId??"":"",function:c}})},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"})]})]}),ne("label",{children:["Target field"," ",ne("select",{"aria-label":`Field ${a+1} rollup target`,value:o.rollup?.targetFieldId??"",disabled:!o.rollup?.linkFieldId,onChange:(l)=>r(a,{rollup:{linkFieldId:o.rollup?.linkFieldId??"",targetFieldId:l.target.value,function:o.rollup?.function??"sum"}}),children:[j("option",{value:"",children:"Choose target field…"}),i.find((l)=>l.id===e.find((c)=>c.id===o.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((l)=>!Me(l)&&l.type!=="linkedRecord"&&(o.rollup?.function==="count"||l.type==="number")).map((l)=>j("option",{value:l.id,children:l.name},l.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 Yi(e,t,n){if(Me(e)||e.type==="blob")return"";if(e.type==="linkedRecord"||e.type==="relation"){let i=t==null||t===""||Array.isArray(t)&&t.length===0;if(e.required&&i)return n==="zh-CN"?`请填写${e.name}。`:`${e.name} is required.`;return""}return Kn(e,Ye(t),n)}function nn(e,t,n,i){let r=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}));r[o.id]=a;continue}if(o.type==="relation"){if(a==null||a===""){if(o.required)throw Error(n("{name} is required.",{name:o.name}));r[o.id]=null;continue}if(typeof a!=="string")throw Error(n("{name} needs a server-provided option.",{name:o.name}));r[o.id]=a;continue}if(o.required&&typeof a==="string"&&!a.trim())throw Error(n("{name} is required.",{name:o.name}));r[o.id]=dt(Array.isArray(a)?a.join(","):String(a??""),o,i)}return r}function St({fields:e,values:t,onChange:n,relationClient:i,linkedRecords:r,computedErrors:o,locale:a,ui:d,submitted:l=!1}){let c=K(a),s=Ki();return j("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((u)=>{let g=u.description?.trim()??"",p=g?`${s}-${u.id}-hint`:void 0,C=Yi(u,t[u.id],a??"en"),y=Boolean(u.required&&Ye(t[u.id])===""&&C)&&!l?"":C,m=y?`${s}-${u.id}-error`:void 0,h=[p,m].filter(Boolean).join(" "),f={...h?{"aria-describedby":h}:{},...y?{"aria-invalid":!0}:{}};return ne("div",{className:"flex flex-col gap-1 text-sm",children:[ne("label",{htmlFor:`${s}-${u.id}`,children:[u.name,u.required?" *":""]}),g?j("p",{id:p,className:"m-0 text-xs opacity-70",children:g}):null,Me(u)?j("output",{id:`${s}-${u.id}`,"aria-label":c("{name} (read only)",{name:u.name}),...f,children:u.type==="lookup"?Vt(t[u.id]):yn(t[u.id],o?.[u.id],a)}):u.type==="linkedRecord"?j(_o,{...a?{locale:a}:{},field:u,value:t[u.id],labels:r?.[u.id],client:i,onChange:(x)=>n({...t,[u.id]:x}),...f}):u.type==="checkbox"?j("input",{id:`${s}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,type:"checkbox",checked:t[u.id]===!0,onChange:(x)=>n({...t,[u.id]:x.target.checked}),...f}):u.type==="singleSelect"&&d?.Select?j(Pe,{ui:d,label:`${u.name}${u.required?" *":""}`,...f,value:String(t[u.id]??""),options:[{value:"",label:c("Choose…")},...(u.options??[]).map((x)=>({value:x.id,label:x.name}))],onChange:(x)=>n({...t,[u.id]:x||null})}):u.type==="multipleSelect"&&d?.MultiSelect?j(d.MultiSelect,{"aria-label":`${u.name}${u.required?" *":""}`,...f,options:(u.options??[]).map((x)=>({value:x.id,label:x.name,slot:fn(u.options,x.id)})),values:Array.isArray(t[u.id])?t[u.id]:[],placeholder:c("Choose…"),onChange:(x)=>n({...t,[u.id]:x})}):u.type==="singleSelect"||u.type==="multipleSelect"?ne("select",{id:`${s}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...f,className:"min-h-9 rounded-md border bg-background p-2",multiple:u.type==="multipleSelect",value:u.type==="multipleSelect"?Array.isArray(t[u.id])?t[u.id]:[]:String(t[u.id]??""),onChange:(x)=>n({...t,[u.id]:u.type==="multipleSelect"?Array.from(x.target.selectedOptions,(w)=>w.value):x.target.value||null}),children:[u.type==="singleSelect"&&j("option",{value:"",children:c("Choose…")}),u.options?.map((x)=>j("option",{value:x.id,children:x.name},x.id))]}):u.type==="date"&&d?.DatePicker?(()=>{let x={kind:Bo(u),timeZone:Ne(u)?.timeZone},w=String(t[u.id]??"");return j(d.DatePicker,{id:`${s}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...f,value:Ko(w,x),withTime:x.kind==="auto"?ct(w):x.kind==="datetime",fixedKind:x.kind!=="auto",clearable:!u.required,onChange:(S)=>n({...t,[u.id]:S?Wo(S,w,x):null})})})():u.type==="longText"?j("textarea",{id:`${s}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...f,className:"rounded-md border bg-background p-2",value:String(t[u.id]??""),onChange:(x)=>n({...t,[u.id]:x.target.value||null})}):j("input",{id:`${s}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...f,className:"min-h-9 min-w-0 rounded-md border bg-background p-2",type:u.type==="number"?"number":u.type==="date"?"date":"text",step:u.type==="number"?"any":void 0,value:u.type==="date"?String(t[u.id]??"").slice(0,10):String(t[u.id]??""),onChange:(x)=>n({...t,[u.id]:x.target.value===""?null:u.type==="number"?Number(x.target.value):u.type==="date"&&t[u.id]?Cn(t[u.id],x.target.value):x.target.value})}),y?j("span",{id:m,className:"text-xs text-red-600",children:y}):null]},u.id)})})}function Gi(e,t,n){if(t==="isEmpty")return;let i=Me(e)?e.resultType:e.type;if(i==="number"){if(t!=="is"&&t!=="isNot")throw Error("Number filters support is, is not, or is empty.");let r=Number(n);if(!n.trim()||!Number.isFinite(r))throw Error("Filter needs a number.");return r}if(i==="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(i==="checkbox"){if(!["true","false"].includes(n))throw Error("Filter needs true or false.");return n==="true"}if(Me(e)&&!Ct(e))throw Error("Computed filters are not available for this field.");if((e.type==="multipleSelect"||e.type==="linkedRecord")&&t!=="contains")return n.split(",").map((r)=>r.trim());return n}function Ic({fields:e,view:t,onChange:n,onError:i}){let r=e.filter(Ct),[o,a]=Qn(r[0]?.id??""),d=r.some((m)=>m.id===o)?o:r[0]?.id??"",[l,c]=Qn("contains"),s=d?(()=>{let m=e.find((h)=>h.id===d);return m&&Me(m)?m.resultType:m?.type})():void 0,u=s==="number"?["is","isNot","isEmpty"]:s==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],g=u.includes(l)?l:s==="number"||s==="date"?"is":"contains",[p,C]=Qn(""),y=[...t.columnOrder.flatMap((m)=>{let h=e.find((f)=>f.id===m);return h?[h]:[]}),...e.filter((m)=>!t.columnOrder.includes(m.id))];return ne("div",{className:"flex flex-wrap items-end gap-3",children:[ne("label",{className:"flex min-w-52 flex-col gap-1 text-sm",children:["Search",j("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})})]}),ne("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(m)=>{m.preventDefault();let h=e.find((x)=>x.id===d);if(!h)return;let f;try{f=Gi(h,g,p)}catch(x){i(x instanceof Error?x.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:d,operator:g,...g==="isEmpty"?{}:{value:f}}]}})},children:[ne("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:(m)=>a(m.target.value),children:r.map((m)=>j("option",{value:m.id,children:m.name},m.id))})]}),j("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:g,onChange:(m)=>c(m.target.value),children:u.map((m)=>j("option",{value:m,children:m==="isNot"?"is not":m==="isEmpty"?"is empty":m==="onOrAfter"?"on or after":m},m))}),g!=="isEmpty"&&j("input",{type:s==="number"?"number":s==="date"?"date":"text",step:s==="number"?"any":void 0,className:"min-h-9 max-w-40 rounded-md border bg-background p-2","aria-label":"Filter value",value:p,onChange:(m)=>C(m.target.value)}),j("button",{type:"submit",disabled:!d,children:"Apply filter"}),j("button",{type:"button",onClick:()=>{let m={...t};delete m.filter,n(m)},children:"Clear filter"})]}),ne("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:y.map((m,h)=>ne("div",{className:"flex items-center gap-2 text-sm",children:[ne("label",{className:"flex flex-1 items-center gap-2",children:[j("input",{type:"checkbox",checked:!t.hiddenColumns.includes(m.id),disabled:t.type==="form"&&m.required===!0,onChange:(f)=>n({...t,hiddenColumns:f.target.checked?t.hiddenColumns.filter((x)=>x!==m.id):[...t.hiddenColumns,m.id]})}),m.name]}),j("button",{type:"button","aria-label":`Move ${m.name} left`,disabled:h===0,onClick:()=>{let f=y.map((w)=>w.id),x=f[h-1];if(x!==void 0)[f[h-1],f[h]]=[m.id,x];n({...t,columnOrder:f})},children:"←"}),j("button",{type:"button","aria-label":`Move ${m.name} right`,disabled:h===y.length-1,onClick:()=>{let f=y.map((w)=>w.id),x=f[h+1];if(x!==void 0)[f[h],f[h+1]]=[x,m.id];n({...t,columnOrder:f})},children:"→"})]},m.id))})]})]})}import{useEffect as Ji,useMemo as cr,useState as ur}from"react";import{jsx as Xn}from"react/jsx-runtime";function Zi(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 Qi(e,t,n){let i=n.unassigned??"Unassigned";if(t===null||t===void 0)return i;if(e?.type==="singleSelect")return e.options?.find((r)=>r.id===t)?.name??String(t);if(e?.type==="checkbox")return t===!0?n.checked??"Checked":n.unchecked??"Unchecked";return typeof t==="string"||typeof t==="number"||typeof t==="boolean"?String(t):i}function pr(e,t,n,i={},r={}){return n.map((o)=>{let a=t.groupBy.map((l)=>{let c=e.fields.find((s)=>s.id===l);return`${c?.name??l} ${Qi(c,o.groups[l],r)}`}),d=t.aggregates.map((l)=>{let c=o.values[l.as];return`${i[l.as]??l.as}: ${typeof c==="number"||typeof c==="string"?String(c):r.none??"none"}`});return[...a,...d].join(" · ")})}function Xi({descriptor:e,query:t,rows:n}){return Xn("ul",{"data-uibot":"collection-aggregate",children:pr(e,t,n).map((i)=>Xn("li",{children:i},i))})}function eo({collectionId:e,descriptor:t,view:n,groupBy:i,aggregates:r,client:o,locale:a,labels:d,reloadKey:l=0}){let c=cr(()=>Do(n,{aggregates:r,...i?{groupBy:i}:{}}),[n,i,r]),s=cr(()=>K(a),[a]),[u,g]=ur(s("Loading summary…")),[p,C]=ur(!1);return Ji(()=>{let b=Fo(t,c);if(b){g(s(Zi(b))),C(!0);return}let y=!0;return g(s("Loading summary…")),C(!1),o.aggregate(e,c).then((m)=>{if(!y)return;if(!m.ok){g(m.error.message),C(!0);return}let h=pr(t,c,m.data,d??{},{unassigned:s("Unassigned"),checked:s("Checked"),unchecked:s("Unchecked"),none:s("none")});g(h.length?h.join(" · "):s("No summary rows.")),C(!1)}).catch(()=>{if(!y)return;g(s("The collection service is unavailable.")),C(!0)}),()=>{y=!1}},[o,e,t,c,d,s,l]),Xn("p",{role:p?"alert":"status","data-uibot":"collection-aggregate",children:u})}var mr=["grid","kanban","gallery","calendar","form"],ea=["grid","form"],to={search:!0,filter:!0,columns:!0,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!0,tableList:!0,viewManagement:!0,export:!0},ta={search:!0,filter:!1,columns:!1,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!1,tableList:!1,viewManagement:!1,export:!1},na={search:!0,filter:!0,columns:!0,rowCreate:!1,rowUpdate:!1,rowDelete:!1,schemaEditor:!1,tableList:!0,viewManagement:!1,export:!0},gr={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:mr},no={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:mr},oa={basic:{...gr,...to},full:{...no,...to},simple:{...gr,...ta,viewTypes:ea},workbench:{...no,...to},readonly:{...no,...na,recordContextMenu:!1,optimisticEdit:!1}};function je(e){let{preset:t="basic",...n}=e??{},i={...oa[t],...ra(n)};return i.groupBy?i:{...i,groupCollapse:!1}}function ra(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}import{jsx as Z,jsxs as Oe,Fragment as ao}from"react/jsx-runtime";function qt(e){if(!e.aggregate)return null;return Z(eo,{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 ae={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},He={padding:12,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)"},Rn={items:[],total:0,nextCursor:null,limit:50};function $t(e,t,n=!0){let i=K(e.locale),r=JSON.stringify([e.descriptor.id,e.descriptor.schemaVersion,t]),[o,a]=qe({key:r,history:[]}),d=o.key===r?o.cursor:void 0,l=o.key===r?o.history:[],c=JSON.stringify([r,d]),[s,u]=qe(0),[g,p]=qe({key:c,page:Rn,loading:n,error:""});Sn(()=>{let b=!0;if(!n){p({key:c,page:Rn,loading:!1,error:""});return}p((h)=>({key:c,page:h.key===c?h.page:Rn,loading:!0,error:""}));let[y,,m]=JSON.parse(r);return e.client.query(y,{...m,...d?{cursor:d}:{}}).then((h)=>{if(!b)return;if(h.ok)p({key:c,page:h.data,loading:!1,error:""});else p((f)=>({...f,loading:!1,error:h.error.message}))}).catch(()=>{if(b)p((h)=>({...h,loading:!1,error:i("Collection query failed. Retry to load records.")}))}),()=>{b=!1}},[c,r,d,e.client,e.reloadKey,n,s]);let C=g.key===c?g.page:Rn;return{page:C,loading:n&&(g.key!==c||g.loading),error:g.key===c?g.error:"",previous:l.length?()=>a({key:r,cursor:l.at(-1),history:l.slice(0,-1)}):void 0,next:C.nextCursor?()=>a({key:r,cursor:C.nextCursor??void 0,history:[...l,d]}):void 0,retry:()=>u((b)=>b+1),pageNumber:l.length+1}}function oo(e,t,n,i){return n>=t?e("{count} records total",{count:t.toLocaleString(i)}):e("{total} records · {loaded} loaded",{total:t.toLocaleString(i),loaded:n})}function ia({hasPrevious:e,hasNext:t,onPrevious:n,onNext:i,loading:r,page:o,locale:a,ui:d}){let l=K(a);if(!e&&!t)return null;return Oe("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[Z(Y,{ui:d,style:ae,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:l("Previous page"),disabled:!e||r,onClick:n}),o?Z("span",{style:{fontSize:12},children:l("Page {page}",{page:o})}):null,Z(Y,{ui:d,style:ae,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:l("Next page"),disabled:!t||r,onClick:i})]})}function zt({state:e,locale:t,ui:n,hideCount:i}){let r=K(t);return Oe("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[i?null:Z("span",{children:oo(r,e.page.total,e.page.items.length,t)}),Z(ia,{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&&Z("span",{role:"status",children:r("Loading records…")}),e.error&&Oe(ao,{children:[Z("span",{role:"alert",children:e.error}),Z(Y,{ui:n,style:ae,variant:"outline",size:"sm",disabled:e.loading,onClick:e.retry,children:r("Retry query")})]})]})}function ro(e){let t=pn(e.client,e.descriptor.id),n=K(e.locale),[i,r]=qe(!1),[o,a]=qe(""),[d,l]=qe(null),c=on(null);Nt({dirty:Boolean(c.current),busy:i});let s=()=>{c.current=null,a(""),l(null)};return{saving:i,error:o,setError:a,remote:d,pending:c,reset:s,commit:async(p)=>{if(i||e.readOnly)return!1;c.current=p,r(!0),a(""),l(null);let C=await e.client.mutate(e.descriptor.id,p).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:n("Saving failed. Your change has been kept.")}}));if(!t.active)return!1;if(r(!1),C.ok)return s(),e.onCommitted(C.data),!0;a(C.error.message);let b=C.error.details?.current;if(b&&typeof b.id==="string"&&Number.isSafeInteger(b.version)&&b.version>0)l(b);return!1},retryRequest:()=>c.current&&d?{idempotencyKey:crypto.randomUUID(),items:c.current.items.map((p)=>p.op!=="insert"&&p.id===d.id?{...p,expectedVersion:d.version}:p)}:c.current}}function io({mutation:e,onRetry:t,locale:n,ui:i}){let r=K(n);return Oe(ao,{children:[e.error&&Z("p",{role:"alert",children:e.error}),e.remote&&Oe("div",{style:He,children:[Z("strong",{children:r("Current server version {version}",{version:e.remote.version})}),Z("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(e.remote.values,null,2)}),Z(Y,{ui:i,style:ae,variant:"outline",size:"sm",disabled:e.saving,onClick:t,children:r("Retry against current version")})]})]})}function It({row:e,onClose:t,onCancel:n,onDirtyChange:i,onBusyChange:r,stickyActions:o,...a}){let d=K(a.locale),l=je(a.features),c=!a.readOnly&&l.rowDelete,s=!a.readOnly&&l.rowUpdate,u=on(e.values),[g,p]=qe(()=>({...u.current})),[C,b]=qe(!1);Nt({dirty:JSON.stringify(g)!==JSON.stringify(u.current),busy:!1});let y=on(null),[m,h]=qe(!1);Sn(()=>{y.current?.focus()},[]);let f=ro(a),x=Pt(a.descriptor.fields,a.view),w=JSON.stringify(g)!==JSON.stringify(e.values);Sn(()=>{i?.(w)},[w,i]),Sn(()=>{r?.(f.saving)},[f.saving,r]);let S=async(v=!1)=>{b(!0);try{let P=v?f.retryRequest():f.pending.current;if(!P){let E=x.filter((D)=>D.type!=="lookup"&&D.type!=="formula"&&D.type!=="rollup"&&JSON.stringify(g[D.id])!==JSON.stringify(e.values[D.id]));if(!E.length){f.setError(d("Change a field before saving."));return}let F=nn(E,g,d,a.locale);P={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:e.id,expectedVersion:e.version,values:F}]}}if(await f.commit(P))t()}catch(P){f.setError(P instanceof Error?P.message:d("Invalid value"))}},I=async()=>{let v=f.pending.current?.items[0]?.op==="delete"?f.pending.current:{idempotencyKey:crypto.randomUUID(),items:[{op:"delete",id:e.id,expectedVersion:e.version}]};if(await f.commit(v))t()};return Oe("div",{ref:y,tabIndex:-1,onKeyDown:(v)=>{if(v.key==="Escape"&&!f.saving)v.stopPropagation(),(n??t)()},role:"dialog","aria-label":d("{name} record",{name:ze(e,a.descriptor.fields)}),style:{...He,marginTop:12},children:[Z("h3",{children:ze(e,a.descriptor.fields)}),a.onInspectRecord&&Z(Y,{ui:a.ui,style:ae,variant:"outline",size:"sm",disabled:f.saving,onClick:()=>a.onInspectRecord?.(e.id),children:d("Open record activity")}),Oe("form",{onSubmit:(v)=>{v.preventDefault(),S()},children:[Z("fieldset",{disabled:f.saving||m||!s,style:{border:0,padding:0},children:Z(St,{fields:x,values:g,submitted:C,...a.locale?{locale:a.locale}:{},...a.ui?{ui:a.ui}:{},relationClient:a.client,linkedRecords:e.linkedRecords,computedErrors:e.computedErrors,onChange:(v)=>{p(v),f.reset()}})}),Oe("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:[s&&Z("button",{type:"submit",style:{...ae,...Bt},disabled:f.saving||m,children:f.saving?d("Saving…"):d("Save record")}),o?null:Z("button",{type:"button",style:ae,disabled:f.saving,onClick:n??t,children:d("Close record")}),o&&c?Z("span",{style:{marginLeft:"auto"},children:Z(Y,{ui:a.ui,variant:"ghost",size:"sm",icon:"trash",disabled:f.saving,onClick:()=>h(!0),children:d("Delete record")})}):null]})]}),c&&!o&&Z("button",{type:"button",style:ae,disabled:f.saving,onClick:()=>h(!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:f.saving,onConfirm:()=>void I(),onCancel:()=>{if(h(!1),f.pending.current?.items[0]?.op==="delete")f.reset()}}):null,m&&!a.ui?.ConfirmDialog&&Oe(Xo,{alert:!0,label:d("Confirm record deletion"),busy:f.saving,onCancel:()=>{if(h(!1),f.pending.current?.items[0]?.op==="delete")f.reset()},children:[Z("p",{children:d("Delete this record? Your unsaved changes will be discarded after deletion.")}),Z("button",{type:"button",style:ae,disabled:f.saving,onClick:()=>void I(),children:d("Confirm deletion")}),Z("button",{type:"button",style:ae,disabled:f.saving,onClick:()=>{if(h(!1),f.pending.current?.items[0]?.op==="delete")f.reset()},children:d("Cancel deletion")})]}),Z(io,{mutation:f,onRetry:()=>void S(!0),locale:a.locale,ui:a.ui})]})}function aa(e){let t=K(e.locale),n=!e.readOnly&&je(e.features).rowCreate,i=on(null),r=Pt(e.descriptor.fields,{...e.view,hiddenColumns:e.view.hiddenColumns.filter((y)=>!e.descriptor.fields.find((m)=>m.id===y)?.required)}),o=()=>({...Object.fromEntries(r.filter((y)=>y.type==="checkbox").map((y)=>[y.id,!1])),...Jt(r)}),a=on(o()),[d,l]=qe(a.current),[c,s]=qe(!1),[u,g]=qe(!1);Nt({dirty:JSON.stringify(d)!==JSON.stringify(a.current),busy:!1});let p=ro(e),C=()=>i.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")?.focus(),b=async()=>{if(!n)return;g(!0);try{let y=p.pending.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:nn(r,d,t,e.locale)}]};if(await p.commit(y))a.current=o(),l(a.current),s(!0),g(!1),requestAnimationFrame(C)}catch(y){p.setError(y instanceof Error?y.message:t("Invalid value"))}};return Oe("section",{"data-uibot":"collection-form",style:He,children:[Z("h3",{children:e.view.name}),e.readOnly&&Z("p",{children:t("Record creation requires editor permission.")}),Oe("form",{ref:i,onSubmit:(y)=>{y.preventDefault(),b()},children:[Z("fieldset",{disabled:p.saving||!n,style:{border:0,padding:0},children:Z(St,{fields:r,values:d,submitted:u,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},relationClient:e.client,onChange:(y)=>{l(y),s(!1),p.reset()}})}),n&&Z("button",{type:"submit",style:{...ae,...Bt},disabled:p.saving,children:p.saving?t("Creating…"):t("Create record")})]}),Z(io,{mutation:p,onRetry:()=>void b(),locale:e.locale,ui:e.ui}),c?Oe("p",{role:"status",children:[t("Record created. Add another below."),e.onShowRecords?Oe(ao,{children:[" ",Z(Y,{ui:e.ui,style:ae,variant:"outline",size:"sm",onClick:e.onShowRecords,children:t("Show records")})]}):null]}):null]})}function In(e){let[t,n]=qe(null),i=ro(e),r=!e.readOnly&&je(e.features).rowUpdate;return{intent:t,mutation:i,move:async(d,l)=>{if(!r||i.saving||t)return;n({row:d,values:l});let c={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:d.id,expectedVersion:d.version,values:l}]};if(await i.commit(c))n(null)},retry:async()=>{let d=i.retryRequest();if(d&&await i.commit(d))n(null)},cancel:()=>{n(null),i.reset()},blocked:i.saving||!!t}}function An({state:e,locale:t,ui:n}){let i=K(t);if(!e.intent)return null;return Oe("div",{role:"dialog","aria-label":i("Pending record move"),style:He,children:[Z("p",{children:e.mutation.saving?i("Moving record…"):i("The move has been kept for retry.")}),Z("pre",{children:JSON.stringify(e.intent.values,null,2)}),Z(io,{mutation:e.mutation,onRetry:()=>void e.retry(),locale:t,ui:n}),!e.mutation.remote&&Z(Y,{ui:n,style:ae,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:()=>void e.retry(),children:i("Retry move")}),Z(Y,{ui:n,style:ae,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:e.cancel,children:i("Cancel move")})]})}import{useEffect as ua,useMemo as Cr,useRef as pa,useState as ga}from"react";import{useEffect as lo,useMemo as la,useState as At}from"react";import{jsx as jt,jsxs as fr}from"react/jsx-runtime";function Dn(e,t){if(!t?.length)return e;let n=!1,i={...e};for(let r of t){let o=r.label.trim();if(!o||i[r.id]===o)continue;i[r.id]=o,n=!0}return n?i:e}function yr(e){let t=la(()=>K(e.locale),[e.locale]),[n,i]=At(""),[r,o]=At(),[a,d]=At(null),[l,c]=At([]),[s,u]=At(()=>Dn({},e.labels)),[g,p]=At(""),[C,b]=At(!1),y=e.field.relation?.collectionId,m=e.field.relation?.labelFieldId,{getOptions:h,value:f}=e;lo(()=>{u((S)=>Dn(S,e.labels))},[e.labels]),lo(()=>{let S=!1;if(!y||!h)return;return b(!0),p(""),h({collectionId:y,...m?{labelFieldId:m}:{},search:n,...r?{cursor:r}:{},limit:50}).then((I)=>{if(S)return;if(!I.ok){p(I.error.message),d(null);return}let v=I.data.items.slice(0,50);u((P)=>Dn(P,v)),c((P)=>{let E=r?[...P,...v]:v;return[...new Map(E.map((F)=>[F.id,F])).values()]}),d(I.data.nextCursor)}).catch(()=>{if(!S)p(t("Relation options unavailable."))}).finally(()=>{if(!S)b(!1)}),()=>{S=!0}},[y,m,n,r,h,t]),lo(()=>{if(!f||!y||!h)return;if(e.labels?.some((I)=>I.id===f&&I.label.trim()))return;let S=!1;return h({collectionId:y,...m?{labelFieldId:m}:{},ids:[f],limit:50}).then((I)=>{if(S||!I.ok)return;let v=I.data.items.find((P)=>P.id===f);if(v)u((P)=>Dn(P,[v]))}).catch(()=>{}),()=>{S=!0}},[f,y,m,h,e.labels]);let x=!y||!h,w=f?s[f]??l.find((S)=>S.id===f)?.label??f:"";return fr("div",{children:[jt("input",{"aria-label":t("Search {name}",{name:e.field.name}),value:n,disabled:e.disabled||x,onChange:(S)=>{i(S.currentTarget.value),o(void 0),c([]),d(null)}}),fr("select",{"aria-label":e.label??e.field.name,value:e.value,disabled:e.disabled||x||C,onChange:(S)=>{let I=S.currentTarget.value;if(!I||l.some((v)=>v.id===I))e.onChange(I)},children:[jt("option",{value:"",children:t("No relation")}),f&&!l.some((S)=>S.id===f)&&jt("option",{value:f,children:w}),l.map((S)=>jt("option",{value:S.id,children:S.label},S.id))]}),a&&jt("button",{type:"button",disabled:C||e.disabled,onClick:()=>o(a),children:t("More {name} options",{name:e.field.name})}),(g||x)&&jt("span",{role:"status",children:g||t("Relation option provider unavailable.")})]})}var sa={"zh-CN":{is:"等于",isNot:"不等于",contains:"包含",notContains:"不包含",isEmpty:"为空",isNotEmpty:"不为空",gt:"大于",gte:"大于等于",lt:"小于",lte:"小于等于",before:"早于",after:"晚于",onOrBefore:"不晚于",onOrAfter:"不早于"},en:{is:"is",isNot:"is not",contains:"contains",notContains:"does not contain",isEmpty:"is empty",isNotEmpty:"is not empty",gt:">",gte:"≥",lt:"<",lte:"≤",before:"is before",after:"is after",onOrBefore:"is on or before",onOrAfter:"is on or after"}},da={"zh-CN":{is:"恰好是",isNot:"不是恰好",contains:"包含任一",notContains:"不包含任一"},en:{is:"is exactly",isNot:"is not exactly",contains:"has any of",notContains:"has none of"}},ca={"zh-CN":{exactDate:"指定日期",dateRange:"日期区间",today:"今天",yesterday:"昨天",tomorrow:"明天",currentWeek:"本周",lastWeek:"上周",nextWeek:"下周",currentMonth:"本月",lastMonth:"上月",nextMonth:"下月",currentYear:"今年",lastYear:"去年",nextYear:"明年",pastDays:"过去 N 天",nextDays:"未来 N 天",daysAgo:"N 天前",daysFromNow:"N 天后"},en:{exactDate:"exact date",dateRange:"date range",today:"today",yesterday:"yesterday",tomorrow:"tomorrow",currentWeek:"this week",lastWeek:"last week",nextWeek:"next week",currentMonth:"this month",lastMonth:"last month",nextMonth:"next month",currentYear:"this year",lastYear:"last year",nextYear:"next year",pastDays:"past N days",nextDays:"next N days",daysAgo:"N days ago",daysFromNow:"N days from now"}},Fn=(e,t="en",n)=>{if(n&&Ke(n)==="multipleSelect"){let i=da[t][e];if(i)return i}return sa[t][e]??e},En=(e,t="en")=>ca[t][e]??e;function so(e,t){if(!t)return"";let n=e?Ne(e):void 0;return n?Lt(t,{...n,time:"none"}):t}function br(e,t,n="en"){let i=n==="zh-CN";return e.filterSet.map((r)=>{if("filterSet"in r)return`(${br(r,t,n)})`;let o=t.find((c)=>c.id===r.fieldId),a=Fn(r.operator,n,o);if(r.operator==="isEmpty"||r.operator==="isNotEmpty")return`${o?.name??r.fieldId} ${a}`;let d=(c)=>o?.options?.find((s)=>s.id===c)?.name??String(c??""),l;if($n(r.value)){let c=r.value,s=En(c.mode,n);l=c.mode==="exactDate"?so(o,c.date):c.mode==="dateRange"?`${so(o,c.date)} ~ ${so(o,c.to)}`:c.days!==void 0?s.replace("N",String(c.days)):s}else l=Array.isArray(r.value)?r.value.map(d).join(i?"、":", "):d(r.value);return`${o?.name??r.fieldId} ${a} ${l}`}).join(e.conjunction==="or"?i?" 或 ":" OR ":i?" 且 ":" AND ")}import{jsx as re,jsxs as Xe,Fragment as Pr}from"react/jsx-runtime";var ma={text:["is","isNot","contains","isEmpty"],number:["is","isNot","gte","lte","isEmpty"],checkbox:["is"],date:["is","isNot","before","onOrAfter","isEmpty"],singleSelect:["is","isNot","isEmpty"],multipleSelect:["is","contains","isEmpty"]};function Ht(e){return re("span",{style:pe.cell,children:re(Pe,{...e})})}var Tn=()=>`row_${Math.random().toString(36).slice(2,10)}`,fa=(e)=>("filterSet"in e),ya=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}};function co(e,t){if(t)return Mo(e);let n=Ke(e);return n?ma[n]??[]:[]}function uo(e,t,n){if(Mt.has(t))return;let i=Ke(e);if(i==="date"&&n)return{mode:"today",timeZone:Ne(e)?.timeZone??ya()};if(i==="checkbox")return!0;if(i==="multipleSelect")return[];return i==="number"?void 0:""}function hr(e){let t=[],n=[];for(let i of e?.filterSet??[])if(fa(i))n.push({key:Tn(),node:i});else t.push({key:Tn(),fieldId:i.fieldId,operator:i.operator,value:i.value});return{rows:t,groups:n,conjunction:e?.conjunction??"and"}}function vr(e,t,n,i){let r=[],o=!0;for(let l of t){let c=e.find((g)=>g.id===l.fieldId);if(!c||!l.operator){o=!1;continue}let s=l.value===""||Array.isArray(l.value)&&l.value.length===0;if(!Mt.has(l.operator)&&s){o=!1;continue}let u={fieldId:l.fieldId,operator:l.operator,...Mt.has(l.operator)?{}:{value:l.value}};if(No(c,u))o=!1;else r.push(u)}let a=n.map((l)=>l.node).filter((l)=>Boolean(l?.filterSet.length)),d=[...r,...a];return{node:d.length?{conjunction:i,filterSet:d}:void 0,complete:o}}function Mn(e){let{ui:t,locale:n}=e,i=e.advanced!==!1,r=e.allowGroups!==!1,o=Cr(()=>K(n),[n]),a=Cr(()=>e.fields.filter((b)=>!Me(b)&&Ke(b)!==null),[e.fields]),[d,l]=ga(()=>hr(e.filter)),c=pa(JSON.stringify(e.filter??null));ua(()=>{let b=JSON.stringify(e.filter??null);if(b!==c.current)c.current=b,l(hr(e.filter))},[e.filter]);let s=(b)=>{l(b);let{node:y}=vr(a,b.rows,b.groups,b.conjunction),m=JSON.stringify(y??null);if(m!==c.current)c.current=m,e.onChange(y)},u=(b,y)=>s({...d,rows:d.rows.map((m)=>m.key===b?{...m,...y}:m)}),g=()=>{let b=a[0];if(!b)return;let y=co(b,i)[0]??"";s({...d,rows:[...d.rows,{key:Tn(),fieldId:b.id,operator:y,value:y?uo(b,y,i):void 0}]})},p=()=>s({...d,groups:[...d.groups,{key:Tn(),node:void 0}]}),C=vr(a,d.rows,d.groups,d.conjunction).complete===!1||d.groups.some((b)=>b.node===void 0);return Xe("div",{"data-uibot-filter-builder":"",style:pe.root,children:[d.rows.length+d.groups.length>1?Xe("div",{style:pe.inline,children:[re("span",{children:o("Match")}),re(Ht,{ui:t,label:o("Filter conjunction"),style:pe.control,value:d.conjunction,options:[{value:"and",label:o("all conditions")},{value:"or",label:o("any condition")}],onChange:(b)=>s({...d,conjunction:b==="or"?"or":"and"})})]}):null,d.rows.map((b,y)=>{let m=a.find((x)=>x.id===b.fieldId),h=m?Ke(m):null,f=m?co(m,i):[];return Xe("fieldset",{"aria-label":o("Condition {index}",{index:y+1}),style:{...pe.condition,margin:0,padding:0,border:0,minWidth:0},children:[re("span",{style:pe.slot,children:re(Ht,{ui:t,label:o("Filter field"),style:pe.control,value:b.fieldId,options:a.map((x)=>({value:x.id,label:x.name})),onChange:(x)=>{let w=a.find((P)=>P.id===x);if(!w)return;let S=co(w,i),I=S.includes(b.operator)?b.operator:S[0]??"",v=Ke(w)===h;u(b.key,{fieldId:x,operator:I,value:I&&!(v&&I===b.operator)?uo(w,I,i):b.value})}})}),re("span",{style:pe.slot,children:re(Ht,{ui:t,label:o("Filter operator"),style:pe.control,value:b.operator,options:f.map((x)=>({value:x,label:Fn(x,n??"en",m)})),onChange:(x)=>{if(!m)return;let w=x;u(b.key,{operator:w,value:uo(m,w,i)})}})}),m&&b.operator&&!Mt.has(b.operator)?re("span",{style:pe.slot,children:re(ba,{field:m,row:b,advanced:i,t:o,props:e,onValue:(x)=>u(b.key,{value:x})})}):null,re(Y,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:o("Remove condition {index}",{index:y+1}),title:o("Remove condition {index}",{index:y+1}),style:{flex:"0 0 auto"},onClick:()=>s({...d,rows:d.rows.filter((x)=>x.key!==b.key)})})]},b.key)}),r?d.groups.map((b,y)=>Xe("fieldset",{"aria-label":o("Condition group {index}",{index:y+1}),style:pe.group,children:[Xe("div",{style:pe.groupHead,children:[re("strong",{style:{fontSize:13},children:o("Condition group {index}",{index:y+1})}),re(Y,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:o("Remove group {index}",{index:y+1}),title:o("Remove group {index}",{index:y+1}),onClick:()=>s({...d,groups:d.groups.filter((m)=>m.key!==b.key)})})]}),re(Mn,{fields:e.fields,filter:b.node,allowGroups:!1,advanced:i,...n?{locale:n}:{},...t?{ui:t}:{},...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},onChange:(m)=>s({...d,groups:m?d.groups.map((h)=>h.key===b.key?{...h,node:m}:h):d.groups.filter((h)=>h.key!==b.key)})})]},b.key)):d.groups.length?Xe("p",{style:pe.hint,children:[o("{count} grouped conditions are kept.",{count:d.groups.length})," ",re(Y,{ui:t,variant:"ghost",size:"sm",onClick:()=>s({...d,groups:[]}),children:o("Remove")})]}):null,C?re("p",{role:"status",style:pe.hint,children:o("Finish the highlighted condition to apply it.")}):null,Xe("div",{style:pe.inline,children:[re(Y,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:a.length===0,onClick:g,children:o("Add condition")}),r?re(Y,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:a.length===0,onClick:p,children:o("Add group")}):null,d.rows.length||d.groups.length?re(Y,{ui:t,variant:"ghost",size:"sm",onClick:()=>s({rows:[],groups:[],conjunction:"and"}),children:o("Clear filter")}):null]})]})}function ba({field:e,row:t,advanced:n,t:i,props:r,onValue:o}){let{ui:a}=r,d=Ke(e),l=i("Filter value"),c=(s,u,g,p)=>r.renderCellEditor?.({...r.getRelationOptions?{getRelationOptions:r.getRelationOptions}:{},field:{...e,...p,required:!1},text:s,disabled:!1,mode:"filter",label:g,autoOpen:!1,onChange:u,onSave:()=>{},onCancel:()=>u("")});if(d==="number")return re("input",{"aria-label":l,type:"number",step:"any",style:pe.control,value:typeof t.value==="number"?String(t.value):"",onChange:(s)=>{let u=s.currentTarget.value;o(u===""||!Number.isFinite(Number(u))?void 0:Number(u))}});if(d==="text")return re("input",{"aria-label":l,style:pe.control,value:typeof t.value==="string"?t.value:"",onChange:(s)=>o(s.currentTarget.value)});if(d==="checkbox")return re(Ht,{ui:a,label:l,style:pe.control,value:t.value===!1?"false":"true",options:[{value:"true",label:i("Yes")},{value:"false",label:i("No")}],onChange:(s)=>o(s==="true")});if(d==="singleSelect"||d==="multipleSelect"){let s=Array.isArray(t.value)?t.value.join(","):typeof t.value==="string"?t.value:"",u=c(s,(p)=>o(d==="multipleSelect"?p.split(",").filter(Boolean):p),l);if(u)return u;if(d==="singleSelect")return re(Ht,{ui:a,label:l,style:pe.control,value:s,options:[{value:"",label:i("Choose option")},...(e.options??[]).map((p)=>({value:p.id,label:p.name}))],onChange:o});let g=new Set(s.split(",").filter(Boolean));return re("fieldset",{"aria-label":l,style:{...pe.inline,margin:0,padding:0,border:0},children:(e.options??[]).map((p)=>Xe("label",{style:pe.inline,children:[re("input",{type:"checkbox",checked:g.has(p.id),onChange:(C)=>{let b=new Set(g);if(C.currentTarget.checked)b.add(p.id);else b.delete(p.id);o([...b])}}),p.name]},p.id))})}if(d==="relation"){let s=typeof t.value==="string"?t.value:"";return c(s,o,l)??re(yr,{field:e,value:s,onChange:o,label:l,getOptions:r.getRelationOptions,locale:r.locale})}if(d==="date"){if(!n||typeof t.value==="string"){let s=typeof t.value==="string"?t.value:"";return c(s,o,l)??re("input",{"aria-label":l,type:"date",style:pe.control,value:s.slice(0,10),onChange:(u)=>o(u.currentTarget.value)})}return re(Ca,{field:e,value:t.value,t:i,props:r,custom:c,onValue:o})}return null}function Ca({field:e,value:t,t:n,props:i,custom:r,onValue:o}){let a=t??{mode:"today"},d=(s)=>o({...a,...s}),l=(s,u,g)=>r(u??"",(p)=>g(p.slice(0,10)),s,{formatting:{date:"YYYY-MM-DD",time:"none"}})??re("input",{"aria-label":s,type:"date",style:pe.control,value:u??"",onChange:(p)=>g(p.currentTarget.value)}),c=(s)=>{let{date:u,to:g,days:p,...C}=a;o({...C,mode:s,...cn.has(s)?{days:7}:{}})};return Xe(Pr,{children:[re(Ht,{ui:i.ui,label:n("Date mode"),style:pe.control,value:a.mode,options:qn.map((s)=>({value:s,label:En(s,i.locale??"en")})),onChange:(s)=>c(s)}),a.mode==="exactDate"?l(n("Filter value"),a.date,(s)=>d({date:s})):null,a.mode==="dateRange"?Xe(Pr,{children:[l(n("From date"),a.date,(s)=>d({date:s})),l(n("To date"),a.to,(s)=>d({to:s}))]}):null,cn.has(a.mode)?re("input",{"aria-label":n("Number of days"),type:"number",min:0,step:1,style:{...pe.control,width:84},value:a.days??"",onChange:(s)=>{let u=s.currentTarget.value;if(u===""){let{days:g,...p}=a;o(p)}else d({days:Number(u)})}}):null,re("span",{style:pe.hint,children:Ne(e)?.timeZone??a.timeZone??""})]})}var xr="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",pe={group:{margin:0,minWidth:0,display:"grid",gap:8,padding:10,border:`1px solid ${xr}`,borderRadius:8},groupHead:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},cell:{flex:"1 1 120px",minWidth:0,display:"flex"},condition:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},slot:{display:"flex",minWidth:0,flex:"1 1 120px"},root:{display:"grid",gap:8},row:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},inline:{display:"inline-flex",flexWrap:"wrap",alignItems:"center",gap:6},control:{width:"100%",minWidth:0,minHeight:30,padding:"0 8px",border:`1px solid ${xr}`,borderRadius:6,background:"transparent",color:"inherit",font:"inherit"},hint:{margin:0,fontSize:12,opacity:0.7}};import{jsx as me,jsxs as at,Fragment as va}from"react/jsx-runtime";var po={display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},go={minHeight:30,padding:"0 8px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit"};function kr({fields:e,view:t,onChange:n,locale:i,ui:r,editor:o}){return me("div",{"data-uibot-view-filter":"",children:me(Mn,{fields:e,filter:t.filter,locale:i,ui:r,renderCellEditor:o?.renderCellEditor,getRelationOptions:o?.getRelationOptions,advanced:o?.advanced,onChange:(a)=>{if(a)n({...t,filter:a});else{let{filter:d,...l}=t;n(l)}}})})}var ha=10;function wr({fields:e,view:t,onChange:n,locale:i,ui:r}){let o=K(i),a=t.sort??[],d=e.filter((u)=>Ct(u)),l=d.filter((u)=>!a.some((g)=>g.fieldId===u.id)),c=(u)=>{if(u.length)n({...t,sort:u});else{let{sort:g,...p}=t;n(p)}},s=(u,g)=>{let p=[...a],[C]=p.splice(u,1);if(C)p.splice(u+g,0,C);c(p)};return at("div",{"data-uibot-view-sort":"",style:{display:"grid",gap:8},children:[a.map((u,g)=>at("fieldset",{"aria-label":o("Sort {index}",{index:g+1}),style:{...po,margin:0,padding:0,border:0,minWidth:0},children:[me("span",{style:{flex:"1 1 120px",minWidth:110,display:"flex"},children:me(Pe,{ui:r,label:o("Sort field"),style:go,value:u.fieldId,options:d.filter((p)=>p.id===u.fieldId||l.includes(p)).map((p)=>({value:p.id,label:p.name})),onChange:(p)=>c(a.map((C,b)=>b===g?{...C,fieldId:p}:C))})}),me("span",{style:{flex:"0 1 110px",minWidth:90,display:"flex"},children:me(Pe,{ui:r,label:o("Sort direction"),style:go,value:u.direction,options:[{value:"asc",label:o("Ascending")},{value:"desc",label:o("Descending")}],onChange:(p)=>c(a.map((C,b)=>b===g?{...C,direction:p}:C))})}),me(Y,{ui:r,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:g===0,ariaLabel:o("Move sort {index} up",{index:g+1}),title:o("Move sort {index} up",{index:g+1}),onClick:()=>s(g,-1),children:" "}),me(Y,{ui:r,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:g===a.length-1,ariaLabel:o("Move sort {index} down",{index:g+1}),title:o("Move sort {index} down",{index:g+1}),onClick:()=>s(g,1),children:" "}),me(Y,{ui:r,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:o("Remove sort {index}",{index:g+1}),title:o("Remove sort {index}",{index:g+1}),onClick:()=>c(a.filter((p,C)=>C!==g)),children:" "})]},u.fieldId)),at("div",{style:po,children:[me(Y,{ui:r,variant:"outline",size:"sm",icon:"plus",disabled:l.length===0||a.length>=ha,onClick:()=>{let u=l[0];if(u)c([...a,{fieldId:u.id,direction:"asc"}])},children:o("Add sort")}),a.length?me(Y,{ui:r,variant:"ghost",size:"sm",onClick:()=>c([]),children:o("Clear sort")}):me("span",{style:{fontSize:12,opacity:0.7},children:o("Default order")})]})]})}function Rr({fields:e,view:t,onChange:n,locale:i,ui:r,bare:o}){let a=K(i),l=[...t.columnOrder.flatMap((u)=>{let g=e.find((p)=>p.id===u);return g?[g]:[]}),...e.filter((u)=>!t.columnOrder.includes(u.id))],c=(u,g)=>{let p=l.map((y)=>y.id),C=p[u],b=p[u+g];if(C===void 0||b===void 0)return;p[u]=b,p[u+g]=C,n({...t,columnOrder:p})},s=at("div",{style:{display:"grid",gap:6,paddingTop:o?0:6,minWidth:0},children:[at("label",{children:[me("input",{type:"checkbox",checked:t.showRowNumber!==!1,onChange:(u)=>n({...t,showRowNumber:u.currentTarget.checked})})," ",a("Show row numbers")]}),at("label",{children:[me("input",{type:"checkbox",checked:t.showRecordId===!0,onChange:(u)=>n({...t,showRecordId:u.currentTarget.checked})})," ",a("Show record IDs")]}),l.map((u,g)=>{let p=!t.hiddenColumns.includes(u.id),C=`${u.name}${u.required?" *":""}`;return at("div",{style:{...po,flexWrap:"nowrap",gap:4},children:[me(Y,{ui:r,variant:"ghost",size:"sm",icon:p?"eye":"eyeOff",iconOnly:!0,disabled:t.type==="form"&&u.required===!0,ariaLabel:C,title:a(p?"Hide {name}":"Show {name}",{name:u.name}),onClick:()=>n({...t,hiddenColumns:p?[...t.hiddenColumns,u.id]:t.hiddenColumns.filter((b)=>b!==u.id)})}),me("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:p?1:0.5},children:C}),me(Y,{ui:r,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:g===0,ariaLabel:a("Move {name} left",{name:u.name}),onClick:()=>c(g,-1)}),me(Y,{ui:r,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:g===l.length-1,ariaLabel:a("Move {name} right",{name:u.name}),onClick:()=>c(g,1)})]},u.id)})]});if(o)return me("div",{"data-uibot-view-columns":"",children:s});return at("details",{"data-uibot-view-columns":"",children:[me("summary",{children:a("Columns")}),s]})}function Sr({fields:e,view:t,onChange:n,locale:i,ui:r}){let o=K(i),a=e.filter((d)=>d.type==="singleSelect"||d.type==="checkbox");return me("div",{style:{display:"flex",gap:6,alignItems:"center"},children:t.groupByFieldId?at(va,{children:[me(Fe,{name:"group"}),me(Pe,{ui:r,label:o("Grid grouping field"),style:go,value:t.groupByFieldId,options:a.map((d)=>({value:d.id,label:d.name})),onChange:(d)=>n({...t,groupByFieldId:d})}),me(Y,{ui:r,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:o("Remove grouping"),onClick:()=>{let d={...t};delete d.groupByFieldId,n(d)}})]}):me(Y,{ui:r,variant:"outline",size:"sm",icon:"plus",onClick:()=>{let d=a[0];if(d)n({...t,groupByFieldId:d.id})},children:o("Add grouping")})})}import{useState as rn}from"react";import{jsx as we,jsxs as mt}from"react/jsx-runtime";var an={table:{label:"Table",path:"M2.5 3.5h11v9h-11zM2.5 7h11M6.5 3.5v9"},users:{label:"People",path:"M6 7.5a2.2 2.2 0 1 0 0-4.4 2.2 2.2 0 0 0 0 4.4zM2 13c0-2.2 1.8-3.6 4-3.6s4 1.4 4 3.6M11 7a1.8 1.8 0 1 0 0-3.6M12 9.6c1.3.3 2.2 1.4 2.2 3"},briefcase:{label:"Business",path:"M2.5 5.5h11v7h-11zM6 5.5v-2h4v2M2.5 9h11"},list:{label:"List",path:"M5.5 4h8M5.5 8h8M5.5 12h8M2.5 4h.01M2.5 8h.01M2.5 12h.01"},calendar:{label:"Schedule",path:"M3 4.5h10V13H3zM3 7.5h10M6 3v3M10 3v3"},package:{label:"Inventory",path:"M8 2.5l5 2.5v6l-5 2.5L3 11V5zM3 5l5 2.5L13 5M8 7.5v6"}},Ar="table";function Nn({icon:e,size:t=15,icons:n=an}){let i=(e?n[e]:void 0)??n[Ar]??an.table;return we("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",width:t,height:t,fill:"none",stroke:"currentColor",strokeWidth:1.4,strokeLinecap:"round",strokeLinejoin:"round",style:{flex:"none"},children:we("path",{d:i?.path??""})})}function xa(e){let t=K(e.locale);return mt("aside",{"data-uibot-table-list":"",style:Dt.root,children:[mt("div",{style:Dt.title,children:[we("span",{children:t("Tables")}),we("span",{children:e.tables.length})]}),we("nav",{"aria-label":t("Tables"),style:Dt.nav,children:e.tables.map((n)=>mt("button",{type:"button","aria-current":n.id===e.activeId?"page":void 0,onClick:()=>e.onSelect(n.id),style:{...Dt.item,...n.id===e.activeId?Dt.active:{}},children:[we(Nn,{icon:n.icon,icons:e.icons??an}),we("span",{style:Dt.name,children:n.name})]},n.id))}),e.onCreate?we(Y,{ui:e.ui,variant:"ghost",style:Dt.create,disabled:e.createDisabled,onClick:e.onCreate,children:t("New table")}):null]})}function Pa(e){let t=K(e.locale),n=e.icons??an,[i,r]=rn(!1),[o,a]=rn(""),[d,l]=rn(!1),[c,s]=rn(!1),[u,g]=rn(""),p=e.table,C=e.canManage&&Boolean(p)&&!c;async function b(f){s(!0),g("");try{return await f(),!0}catch(x){return g(x instanceof Error?x.message:t("Saving failed. Your edit has been kept.")),!1}finally{s(!1)}}let y=()=>{if(!C||!e.onRename)return;a(p?.name??""),g(""),r(!0)};async function m(){let f=o.trim();if(!f||f===p?.name){r(!1);return}if(await b(()=>e.onRename?.(f)))r(!1)}let h=(f)=>{if(f.key==="Enter"||f.key==="F2")f.preventDefault(),y()};return mt("header",{"data-uibot-table-header":"",style:Je.root,children:[mt("div",{style:Je.left,children:[mt("span",{style:{position:"relative"},children:[we("button",{type:"button","aria-label":t("Change table icon"),"aria-haspopup":"menu","aria-expanded":d,title:e.canManage?t("Double click to change the icon"):t("Schema permission required"),disabled:!C||!e.onIconChange,style:Je.iconButton,onDoubleClick:()=>l(!0),onKeyDown:(f)=>{if(f.key==="Enter"||f.key===" ")f.preventDefault(),l(!0)},children:we(Nn,{icon:p?.icon,size:17,icons:n})}),d?we("div",{role:"menu","aria-label":t("Table icon"),style:Je.menu,children:Object.entries(n).map(([f,x])=>mt("button",{type:"button",role:"menuitemradio","aria-checked":(p?.icon??Ar)===f,title:x.label,style:Je.menuItem,onClick:()=>{l(!1),b(()=>e.onIconChange?.(f))},children:[we(Nn,{icon:f,icons:n}),we("span",{children:x.label})]},f))}):null]}),mt("div",{style:{minWidth:0},children:[i?we("input",{"aria-label":t("Table name"),value:o,disabled:c,style:Je.input,autoFocus:!0,onChange:(f)=>a(f.currentTarget.value),onBlur:()=>{if(!u)m()},onKeyDown:(f)=>{if(f.key==="Enter")f.preventDefault(),m();if(f.key==="Escape")f.preventDefault(),r(!1),g("")}}):we("h2",{style:Je.title,children:we("button",{type:"button","aria-label":t("Rename table {name}",{name:p?.name??""}),title:e.canManage?t("Double click to rename"):t("Schema permission required"),disabled:!C||!e.onRename,style:Je.titleButton,onDoubleClick:y,onKeyDown:h,children:p?.name??t("Start with a table")})}),u?we("p",{role:"alert",style:Je.error,children:u}):null,we("p",{style:Je.summary,children:p?t("{count} fields · {mode}",{count:p.fields.length,mode:e.canWrite?t("Editable"):t("Read only")}):t("Start with a table")})]})]}),we("div",{style:Je.actions,children:e.actions})]})}var Ir="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",Dt={root:{display:"grid",gap:8,alignContent:"start",minWidth:180},title:{display:"flex",justifyContent:"space-between",padding:"0 12px",fontSize:12,opacity:0.7},nav:{display:"grid",gap:2},item:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",border:0,borderRadius:6,background:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},active:{background:"var(--uibot-active-bg, color-mix(in srgb, currentColor 10%, transparent))",fontWeight:600},name:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},create:{justifyContent:"flex-start",width:"100%"}},Je={root:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,padding:"12px 20px"},left:{display:"flex",alignItems:"center",gap:12,minWidth:0},iconButton:{width:32,height:32,display:"grid",placeItems:"center",border:0,borderRadius:8,background:"var(--uibot-active-bg, color-mix(in srgb, currentColor 10%, transparent))",color:"inherit",cursor:"pointer"},menu:{position:"absolute",top:"100%",left:0,zIndex:60,display:"grid",minWidth:150,padding:4,border:`1px solid ${Ir}`,borderRadius:8,background:"var(--background, #fff)"},menuItem:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:0,background:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},input:{height:32,width:240,maxWidth:"100%",padding:"0 8px",border:`1px solid ${Ir}`,borderRadius:6,font:"inherit",fontWeight:600},title:{margin:0,fontSize:16,fontWeight:600},titleButton:{maxWidth:"100%",padding:0,border:0,background:"transparent",color:"inherit",font:"inherit",cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},error:{margin:"4px 0 0",fontSize:12,color:"var(--uibot-danger, #b3261e)"},summary:{margin:"2px 0 0",fontSize:12,opacity:0.7},actions:{display:"flex",alignItems:"center",gap:4}};import{useEffect as mo,useMemo as fo,useRef as Ft,useState as Kt}from"react";import{jsx as ft,jsxs as yo}from"react/jsx-runtime";function ka(e,t){if(!t)return"";let n=e.fields.find((r)=>r.id==="title")??e.fields[0],i=n?t.values[n.id]:void 0;return typeof i==="string"?i.trim():""}function wa(e){let t=fo(()=>K(e.locale),[e.locale]),n=pn(e.client,e.descriptor.id),i=Ft(null);if(i.current===null)i.current=Jt(e.descriptor.fields);let[r,o]=Kt(i.current),[a,d]=Kt(!1),l=fo(()=>({client:e.client,descriptor:e.descriptor}),[e.client,e.descriptor]),c=Ft(l);c.current=l;let s=Ft(!0);mo(()=>(s.current=!0,()=>{s.current=!1}),[]);let[u,g]=Kt(),p=fo(()=>{let N=new Map,A=(O,V)=>{if(!s.current||c.current!==l)return;g((R)=>({scope:l,targets:{...R?.scope===l?R.targets:{},[O]:V}}))};return{query:async(...O)=>{let V=O[0],R=(N.get(V)??0)+1;N.set(V,R),A(V,!1);try{let L=await e.client.query(...O);if(N.get(V)===R)A(V,L.ok);return L}catch(L){if(N.get(V)===R)A(V,!1);throw L}}}},[e.client,l]),C=e.descriptor.fields.some((N)=>N.type==="linkedRecord"&&(!N.link||u?.scope!==l||!u.targets[N.link.collectionId])),[b,y]=Kt(null),m=Ft(null),h=Ft(!1),f=Ft(null),x=Ft(null),{autoFocus:w}=e;mo(()=>{if(b?.error)x.current?.focus()},[b]);let[S,I]=Kt(!1),[v,P]=Kt(!1),E=JSON.stringify(r)!==JSON.stringify(i.current)||S;Nt({dirty:E,busy:a},e);let F=()=>f.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled])")?.focus();mo(()=>{if(w)F()},[w]);async function D(N){if(h.current||e.readOnly||C)return;P(!0);let A;try{A=nn(e.descriptor.fields,r,t,e.locale)}catch(V){y({text:V instanceof Error?V.message:t("Invalid value"),error:!0,clearable:!0});return}h.current=!0,d(!0),y(null);let O=m.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:A}]};m.current=O;try{let V=await e.client.mutate(e.descriptor.id,O);if(!n.active)return;if(!V.ok){let L=V.error.code==="validation";I(!L),y({text:V.error.message,error:!0,clearable:L});return}m.current=null,I(!1),P(!1),i.current=Jt(e.descriptor.fields),o(i.current),e.onCommitted(V.data);let R=ka(e.descriptor,V.data.items[0]);if(y({text:`${N?t("Record saved, keep adding"):t("Record saved")}${R?`:${R}`:""}`,error:!1,clearable:!1}),N)requestAnimationFrame(F);else e.onSaved?.(V.data)}catch{if(!n.active)return;I(!0),y({text:t("Saving failed. Your draft has been kept."),error:!0,clearable:!1})}finally{h.current=!1,d(!1)}}return yo("form",{ref:f,noValidate:!0,"aria-label":t("New record form"),"data-uibot":"record-creator",onSubmit:(N)=>{N.preventDefault();let A=N.nativeEvent.submitter;D(A?.getAttribute("data-continue")==="true")},onKeyDown:(N)=>{if(N.key==="Enter"&&(N.ctrlKey||N.metaKey)&&!N.nativeEvent.isComposing&&!a)N.preventDefault(),N.currentTarget.requestSubmit()},children:[ft("fieldset",{disabled:a||e.readOnly,style:et.fields,children:ft(St,{fields:e.descriptor.fields,values:r,submitted:v,relationClient:p,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},onChange:(N)=>{if(o(N),m.current=null,I(!1),b?.clearable)y(null)}})}),b?ft("p",{ref:x,role:b.error?"alert":"status",tabIndex:-1,style:b.error?et.error:et.status,children:b.text}):null,yo("div",{"data-uibot":"record-creator-actions",style:e.stickyActions?{...et.actions,...et.sticky}:et.actions,children:[yo("span",{style:et.hint,children:[ft("kbd",{children:"Ctrl / ⌘"})," + ",ft("kbd",{children:"Enter"})," ",t("Save")]}),ft("button",{type:"submit","aria-label":t("Save new record"),"aria-busy":a,disabled:a||e.readOnly||C,style:{...et.button,...Bt},children:a?t("Saving…"):t("Save new record")}),ft("button",{type:"submit","data-continue":"true",disabled:a||e.readOnly||C,style:et.button,children:t("Save and continue")}),e.onCancel&&!e.stickyActions?ft(Y,{ui:e.ui,style:et.button,disabled:a,onClick:e.onCancel,children:t("Cancel adding")}):null]})]})}var et={sticky:{position:"sticky",bottom:0,zIndex:1,padding:"12px 0",borderTop:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",background:"var(--background, white)"},fields:{margin:0,padding:0,border:0,minWidth:0},actions:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,marginTop:12},button:{padding:"6px 10px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit",cursor:"pointer"},hint:{marginRight:"auto",fontSize:12,opacity:0.7},error:{margin:"8px 0 0",fontSize:13,color:"var(--uibot-danger, #b3261e)"},status:{margin:"8px 0 0",fontSize:12,opacity:0.8}};import{useEffect as Ta,useLayoutEffect as Ma,useRef as ln}from"react";import{jsx as Wt}from"react/jsx-runtime";var Dr=[["#e8f0fe","#1a56c4"],["#e6f4ea","#1e7a3c"],["#fdecea","#b3261e"],["#fff1e0","#a05a00"],["#e8eaed","#3c4043"],["#e0f2f1","#00695c"],["#f3e8fd","#6a1b9a"]];function Et(e){let t=Math.max(e,0)%Dr.length,[n,i]=Dr[t]??["#e8eaed","#3c4043"];return{background:`var(--uibot-chip-${t}-bg, ${n})`,color:`var(--uibot-chip-${t}-fg, ${i})`}}function Ra({index:e,children:t}){return Wt("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",...Et(e)},children:t})}function Ln({ids:e,field:t,wrap:n}){let i=t.options??[];return Wt("span",{style:{display:"inline-flex",gap:4,alignItems:"center",maxWidth:"100%",overflow:"hidden",...n?{flexWrap:"wrap"}:{}},children:e.map((r)=>{let o=i.findIndex((a)=>a.id===r);return Wt(Ra,{index:fn(i,r),children:i[o]?.name??String(r)},String(r))})})}function Bu({checked:e,label:t,onToggle:n}){return Wt("input",{type:"checkbox","aria-label":t,checked:e,disabled:!n,style:{width:16,height:16,margin:0,accentColor:"var(--primary, #1a56c4)"},onMouseDown:(i)=>i.stopPropagation(),onKeyDown:(i)=>i.stopPropagation(),onChange:()=>n?.()})}var Fr={singleLineText:"M3 4.5h10M8 4.5v8",longText:"M3 4h10M3 8h10M3 12h6",number:"M6.5 3 5.5 13M10.5 3l-1 10M3 6h10.5M2.5 10h10.5",bigint:"M6.5 3 5.5 13M10.5 3l-1 10M3 6h10.5M2.5 10h10.5",checkbox:"M3.5 3.5h9v9h-9zM5.6 8.1l1.8 1.8 3-3.6",date:"M3 4.5h10V13H3zM3 7.5h10M6 3v3M10 3v3",singleSelect:"M8 14a6 6 0 1 0 0-12 6 6 0 0 0 0 12zM5.8 7l2.2 2.2L10.2 7",multipleSelect:"M6 4h7M6 8h7M6 12h7M3 4h.01M3 8h.01M3 12h.01",relation:"M7 9a2.5 2.5 0 0 0 3.5 0l2-2A2.5 2.5 0 0 0 9 3.5l-.7.7M9 7a2.5 2.5 0 0 0-3.5 0l-2 2A2.5 2.5 0 0 0 7 12.5l.7-.7",linkedRecord:"M7 9a2.5 2.5 0 0 0 3.5 0l2-2A2.5 2.5 0 0 0 9 3.5l-.7.7M9 7a2.5 2.5 0 0 0-3.5 0l-2 2A2.5 2.5 0 0 0 7 12.5l.7-.7",lookup:"M7 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM10 10l3.5 3.5",formula:"M10.5 3.5c-2 0-2.2 1-2.5 3L7.2 12c-.3 1.6-1 2-2.5 2M5 7.5h5",rollup:"M12 3.5H4.5L8.5 8l-4 4.5H12",json:"M6 3.5C4.5 3.5 4.5 5 4.5 6.5S4 8 3 8c1 0 1.5.5 1.5 1.5S4.5 12.5 6 12.5M10 3.5c1.5 0 1.5 1.5 1.5 3S12 8 13 8c-1 0-1.5.5-1.5 1.5s0 3-1.5 3",blob:"M4 3.5h5l3 3V12.5H4z"};function Uu({type:e}){return Wt("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:Wt("path",{d:Fr[e]??Fr.singleLineText})})}var q={root:{display:"grid",gap:12,color:"var(--uibot-schema-fg, inherit)",fontFamily:"inherit"},field:{margin:0,minWidth:0,display:"grid",gap:12,padding:16,border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:10,background:"var(--uibot-schema-bg, transparent)"},row:{display:"flex",flexWrap:"wrap",alignItems:"end",gap:12},control:{display:"grid",flex:"1 1 180px",gap:5,minWidth:140,fontSize:13},label:{color:"var(--uibot-schema-muted, color-mix(in srgb, currentColor 65%, transparent))",fontWeight:600},input:{boxSizing:"border-box",width:"100%",minHeight:"var(--uibot-schema-control-height, 36px)",padding:"7px 9px",border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"var(--uibot-schema-bg, transparent)",color:"inherit",font:"inherit"},button:{minHeight:36,padding:"7px 12px",border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"var(--uibot-schema-surface, transparent)",color:"inherit",font:"inherit",fontWeight:600,cursor:"pointer"},danger:{borderColor:"var(--uibot-schema-danger-border, color-mix(in srgb, #e5534b 45%, transparent))",background:"var(--uibot-schema-danger-bg, transparent)",color:"var(--uibot-schema-danger, #e5534b)"},checkbox:{display:"flex",alignItems:"center",gap:8,minHeight:"var(--uibot-schema-control-height, 36px)",fontSize:13},options:{display:"grid",gap:8,margin:0,minWidth:0,padding:"10px 0 0",border:0,borderTop:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))"},optionRow:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},settings:{display:"grid",gap:10,margin:0,minWidth:0,padding:"10px 0 0",border:0,borderTop:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))"},swatch:{width:18,height:18,padding:0,borderRadius:999,cursor:"pointer",flex:"none"}};import{jsx as ve,jsxs as ke,Fragment as bo}from"react/jsx-runtime";var Sa=["YYYY-MM-DD","YYYY/MM/DD","MM/DD/YYYY","DD/MM/YYYY","YYYY年M月D日"],Ia=["Asia/Shanghai","Asia/Hong_Kong","Asia/Tokyo","Asia/Singapore","Europe/London","Europe/Paris","America/New_York","America/Los_Angeles","UTC"],Aa=["CNY","USD","EUR","JPY","GBP","HKD"],Da=[0,1,2,3,4,5,6,7,8],Fa={date:"YYYY-MM-DD",time:"none"},Ea={kind:"decimal",precision:0,grouping:!0};function Er({field:e,onChange:t,disabled:n,locale:i,ui:r,settings:o,dateFormatLocked:a}){let d=o?.formatting!==!1,l=o?.defaults!==!1,c=K(i),s=(p)=>t((C)=>({...C,...p})),u=()=>t((p)=>{let{defaultValue:C,...b}=p;return b}),g=(p,C,b,y,m=!1)=>ke("div",{style:q.control,children:[ve("span",{style:q.label,children:p}),ve(Pe,{ui:r,label:p,style:q.input,disabled:n||m,value:C,options:b,onChange:y})]});if(e.type==="date"){let p=Ne(e)??Fa,C=(y)=>{let{timeZone:m,...h}=p,f={...h,...m?{timeZone:m}:{},...y};if(y.timeZone==="")delete f.timeZone;s({formatting:f})},b=p.time!=="none";if(!d&&!l)return null;return ke("fieldset",{style:q.settings,"aria-label":c("Format of field {name}",{name:e.name}),children:[d?ke(bo,{children:[ve("strong",{style:{fontSize:13},children:c("Format")}),ke("div",{style:q.row,children:[g(c("Date format"),p.date,Sa.map((y)=>({value:y,label:y})),(y)=>C({date:y}),Boolean(a)),g(c("Time format"),p.time,[{value:"none",label:c("No time (date only)")},{value:"24h",label:c("24-hour")},{value:"12h",label:c("12-hour")}],(y)=>C({time:y}),Boolean(a)),b?g(c("Time zone"),p.timeZone??"",[{value:"",label:c("Viewer's time zone")},...Ia.map((y)=>({value:y,label:y}))],(y)=>C({timeZone:y}),Boolean(a)):null]}),ke("p",{style:{...q.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[c("Preview"),": ",Lt(new Date().toISOString(),p)]})]}):null,l&&g(c("Default value"),e.defaultValue?.kind==="now"?"now":"",[{value:"",label:c("Empty")},{value:"now",label:b?c("Current date and time"):c("Today")}],(y)=>y==="now"?s({defaultValue:{kind:"now"}}):u())]})}if(e.type==="number"){let p=gn(e)??Ea,C=(y)=>s({formatting:{...p,...y}}),b=e.defaultValue?.kind==="value"?String(e.defaultValue.value):"";if(!d&&!l)return null;return ke("fieldset",{style:q.settings,"aria-label":c("Format of field {name}",{name:e.name}),children:[d?ke(bo,{children:[ve("strong",{style:{fontSize:13},children:c("Format")}),ke("div",{style:q.row,children:[g(c("Number style"),p.kind,[{value:"decimal",label:c("Number")},{value:"percent",label:c("Percent")},{value:"currency",label:c("Currency")}],(y)=>C({kind:y})),g(c("Decimal places"),String(p.precision),Da.map((y)=>({value:String(y),label:String(y)})),(y)=>C({precision:Number(y)})),p.kind==="currency"?g(c("Currency"),p.currency??"CNY",Aa.map((y)=>({value:y,label:y})),(y)=>C({currency:y})):null]}),ke("label",{style:q.checkbox,children:[ve("input",{type:"checkbox","aria-label":c("Thousands separator"),checked:p.grouping!==!1,disabled:n,onChange:(y)=>C({grouping:y.currentTarget.checked})}),c("Thousands separator")]}),ke("p",{style:{...q.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[c("Preview"),":"," ",mn(p.kind==="percent"?0.1234:1234.5678,p)]})]}):null,l&&ke("label",{style:q.control,children:[ve("span",{style:q.label,children:c("Default value")}),ve("input",{"aria-label":c("Default value"),style:q.input,type:"number",step:"any",disabled:n,value:b,onChange:(y)=>{let m=y.currentTarget.value;if(m===""||!Number.isFinite(Number(m)))u();else s({defaultValue:{kind:"value",value:Number(m)}})}})]})]})}if(!l)return null;if(e.type==="singleLineText"||e.type==="longText")return ve("fieldset",{style:q.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:ke("label",{style:q.control,children:[ve("span",{style:q.label,children:c("Default value")}),ve("input",{"aria-label":c("Default value"),style:q.input,disabled:n,value:e.defaultValue?.kind==="value"?String(e.defaultValue.value):"",onChange:(p)=>{let C=p.currentTarget.value;if(C==="")u();else s({defaultValue:{kind:"value",value:C}})}})]})});if(e.type==="checkbox")return ve("fieldset",{style:q.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:ke("label",{style:q.checkbox,children:[ve("input",{type:"checkbox","aria-label":c("Checked by default"),checked:e.defaultValue?.kind==="value"&&e.defaultValue.value===!0,disabled:n,onChange:(p)=>p.currentTarget.checked?s({defaultValue:{kind:"value",value:!0}}):u()}),c("Checked by default")]})});if((e.type==="singleSelect"||e.type==="multipleSelect")&&(e.options?.length??0)>0){let p=e.options??[],C=e.defaultValue?.kind==="value"?e.defaultValue.value:void 0;if(e.type==="singleSelect")return ve("fieldset",{style:q.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:g(c("Default value"),typeof C==="string"?C:"",[{value:"",label:c("Empty")},...p.map((y)=>({value:y.id,label:y.name}))],(y)=>y?s({defaultValue:{kind:"value",value:y}}):u())});let b=Array.isArray(C)?C:[];return ke("fieldset",{style:q.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:[ve("span",{style:q.label,children:c("Default value")}),p.map((y)=>ke("label",{style:q.checkbox,children:[ve("input",{type:"checkbox","aria-label":c("Default option {name}",{name:y.name}),checked:b.includes(y.id),disabled:n,onChange:(m)=>{let h=m.currentTarget.checked?[...b,y.id]:b.filter((f)=>f!==y.id);if(h.length)s({defaultValue:{kind:"value",value:h}});else u()}}),y.name]},y.id))]})}return null}function Tr({field:e,fields:t,onChange:n,disabled:i,locale:r}){let o=K(r);if(!Un.has(e.type))return null;let a=e.ai,d=t.filter((s)=>s.id!==e.id&&s.type!=="blob"&&s.type!=="lookup"),l=a?.sourceFieldIds??[],c=(s)=>n((u)=>{if(s)return{...u,ai:s};let{ai:g,...p}=u;return p});return ke("fieldset",{style:q.settings,"aria-label":o("AI settings of field {name}",{name:e.name}),children:[ke("label",{style:q.checkbox,children:[ve("input",{type:"checkbox",checked:Boolean(a),disabled:i,onChange:(s)=>c(s.currentTarget.checked?{prompt:""}:void 0)}),o("Generate this field with AI")]}),a?ke(bo,{children:[ke("label",{style:q.control,children:[ve("span",{style:q.label,children:o("AI prompt")}),ve("textarea",{"aria-label":o("AI prompt"),style:{...q.input,minHeight:72,resize:"vertical"},rows:3,maxLength:Bn,placeholder:o("e.g. Summarize the description in one sentence"),value:a.prompt,disabled:i,onChange:(s)=>{let u=s.currentTarget.value;n((g)=>({...g,ai:{...g.ai,prompt:u}}))}})]}),ve("span",{style:q.label,children:o("Fields the AI reads (none = all)")}),ve("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px"},children:d.map((s)=>ke("label",{style:q.checkbox,children:[ve("input",{type:"checkbox","aria-label":o("AI reads {name}",{name:s.name}),checked:l.includes(s.id),disabled:i,onChange:(u)=>{let g=u.currentTarget.checked;n((p)=>{let C=p.ai?.sourceFieldIds??[],b=g?[...C,s.id]:C.filter((h)=>h!==s.id),{sourceFieldIds:y,...m}=p.ai??{prompt:""};return{...p,ai:b.length?{...m,sourceFieldIds:b}:m}})}}),s.name]},s.id))})]}):null]})}import{jsx as xe,jsxs as tt}from"react/jsx-runtime";var Na=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],Mr=(e)=>e==="singleSelect"||e==="multipleSelect";function La(e,t){let n=t.slice(0,sn);if(!n.trim()){let{description:i,...r}=e;return r}return{...e,description:n}}function Oa({fields:e,onChange:t,disabled:n=!1,focusFieldId:i,locale:r,ui:o,fieldTypes:a=Na,relationTargets:d=[],lockedFieldIds:l=[],settings:c}){let s=K(r),u={singleLineText:s("Single line text"),longText:s("Long text"),number:s("Number"),checkbox:s("Checkbox"),date:s("Date"),singleSelect:s("Single select"),multipleSelect:s("Multiple select"),relation:s("Linked record")},g=(v)=>a.includes(v.type),p=ln(new Map),C=ln(new Map),b=ln(null),y=ln(new Map),m=ln(null);function h(v,P){let E={fields:v,target:P};m.current=E,t(v),queueMicrotask(()=>{if(m.current===E)m.current=null})}Ma(()=>{let v=m.current;if(!v||v.fields!==e)return;if(m.current=null,n)return;let{target:P}=v,E=P.type==="field-name"?p.current.get(P.fieldId):P.type==="option-name"?C.current.get(`${P.fieldId}:${P.optionId}`):null;if(E){E.focus(),E.select();return}(P.type==="add-field"?b.current:P.type==="add-option"?y.current.get(P.fieldId):null)?.querySelector("button")?.focus()},[n,e]),Ta(()=>{if(!i)return;let v=window.setTimeout(()=>{let P=p.current.get(i);P?.scrollIntoView({block:"center"}),P?.focus(),P?.select()},200);return()=>window.clearTimeout(v)},[i]);let f=(v,P)=>{if(!n)t(e.map((E)=>E.id===v?P(E):E))};function x(){if(n)return;let v={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:s("New field"),type:"singleLineText"};h([...e,v],{type:"field-name",fieldId:v.id})}function w(v){if(n)return;let P=e.filter(g),E=P.findIndex((N)=>N.id===v),F=P.filter((N)=>N.id!==v),D=F[E]??F[E-1];h(e.filter((N)=>N.id!==v),D?{type:"field-name",fieldId:D.id}:{type:"add-field"})}function S(v){if(n)return;let P={id:crypto.randomUUID(),name:s("New option")};h(e.map((E)=>E.id===v.id?{...E,options:[...E.options??[],P]}:E),{type:"option-name",fieldId:v.id,optionId:P.id})}function I(v,P){if(n)return;let E=v.options??[],F=E.findIndex((A)=>A.id===P),D=E.filter((A)=>A.id!==P),N=D[F]??D[F-1];h(e.map((A)=>{if(A.id!==v.id)return A;let O=A.defaultValue;if(!(O?.kind==="value"&&(Array.isArray(O.value)?O.value.includes(P):O.value===P)))return{...A,options:D};let{defaultValue:R,...L}=A;return{...L,options:D}}),N?{type:"option-name",fieldId:v.id,optionId:N.id}:{type:"add-option",fieldId:v.id})}return tt("section",{"aria-label":s("Collection fields"),"data-uibot-schema-editor":"",style:q.root,children:[e.filter(g).map((v)=>tt("fieldset",{"aria-label":s("Field {name}",{name:v.name}),style:q.field,children:[tt("div",{style:q.row,children:[tt("label",{style:q.control,children:[xe("span",{style:q.label,children:s("Field name")}),xe("input",{"aria-label":s("Field name"),ref:(P)=>{if(P)p.current.set(v.id,P);else p.current.delete(v.id)},style:q.input,value:v.name,disabled:n,onChange:(P)=>{let E=P.currentTarget.value;f(v.id,(F)=>({...F,name:E}))}})]}),tt("div",{style:q.control,children:[xe("span",{style:q.label,children:s("Field type")}),xe(Pe,{ui:o,label:s("Field type"),style:q.input,disabled:n||l.includes(v.id),value:v.type,options:a.map((P)=>({value:P,label:u[P]})),onChange:(P)=>f(v.id,(E)=>{let{options:F,relation:D,formatting:N,defaultValue:A,...O}=E;return{...O,type:P,...Mr(P)?{options:E.options??[]}:{},...P==="relation"?{relation:{collectionId:""}}:{}}})})]}),tt("label",{style:q.checkbox,children:[xe("input",{type:"checkbox","aria-label":s("Required"),checked:Boolean(v.required),disabled:n,onChange:(P)=>{let E=P.currentTarget.checked;f(v.id,(F)=>({...F,required:E}))}}),s("Required")]}),xe(Y,{ui:o,style:{...q.button,...q.danger},disabled:n||l.includes(v.id),icon:"trash",iconOnly:!0,ariaLabel:s("Delete field"),title:s("Delete field {name}",{name:v.name}),onClick:()=>w(v.id)})]}),c?.descriptions===!1?null:tt("label",{style:q.control,children:[xe("span",{style:q.label,children:s("Field description")}),xe("textarea",{"aria-label":s("Field description"),style:{...q.input,minHeight:64,resize:"vertical"},rows:2,maxLength:sn,value:v.description??"",disabled:n,onChange:(P)=>{let E=P.currentTarget.value;f(v.id,(F)=>La(F,E))}})]}),v.type==="relation"?tt("div",{style:q.control,children:[xe("span",{style:q.label,children:s("Related table")}),xe(Pe,{ui:o,label:s("Related table"),style:q.input,disabled:n||l.includes(v.id),value:v.relation?.collectionId??"",options:[{value:"",label:s("Choose a related table")},...d.map((P)=>({value:P.id,label:P.name}))],onChange:(P)=>f(v.id,(E)=>({...E,relation:{collectionId:P}}))})]}):null,Mr(v.type)?tt("fieldset",{style:q.options,"aria-label":s("Options of field {name}",{name:v.name}),children:[xe("strong",{style:{fontSize:13},children:s("Options")}),(v.options??[]).map((P,E)=>tt("div",{style:q.optionRow,children:[xe("input",{"aria-label":s("Option name {index}",{index:E+1}),ref:(F)=>{let D=`${v.id}:${P.id}`;if(F)C.current.set(D,F);else C.current.delete(D)},style:{...q.input,flex:"1 1 120px",minWidth:0,width:"auto"},value:P.name,disabled:n,onChange:(F)=>{let D=F.currentTarget.value;f(v.id,(N)=>({...N,options:(N.options??[]).map((A)=>A.id===P.id?{...A,name:D}:A)}))}}),c?.optionColors===!1?null:xe("fieldset",{"aria-label":s("Colour of option {index}",{index:E+1}),style:{display:"inline-flex",flex:"none",gap:4,margin:0,padding:0,border:0,minWidth:0},children:Tt.map((F,D)=>{let N=(P.color??Tt[E%Tt.length])===F;return xe("button",{type:"button","aria-label":s(`Colour ${F}`),"aria-pressed":N,disabled:n,style:{...q.swatch,background:Et(D).color,border:N?"2px solid currentColor":"1px solid transparent"},onClick:()=>f(v.id,(A)=>({...A,options:(A.options??[]).map((O)=>O.id===P.id?{...O,color:F}:O)}))},F)})}),xe(Y,{ui:o,style:{...q.button,...q.danger},disabled:n,icon:"trash",iconOnly:!0,ariaLabel:s("Delete option {index}",{index:E+1}),title:s("Delete option {index}",{index:E+1}),onClick:()=>I(v,P.id)})]},P.id)),xe("div",{ref:(P)=>{if(P)y.current.set(v.id,P);else y.current.delete(v.id)},children:xe(Y,{ui:o,style:q.button,icon:"plus",disabled:n,onClick:()=>S(v),children:s("Add option")})})]}):null,xe(Er,{field:v,...c?{settings:c}:{},dateFormatLocked:l.includes(v.id),disabled:n,locale:r,ui:o,onChange:(P)=>f(v.id,P)}),c?.ai?xe(Tr,{field:v,fields:e,disabled:n,locale:r,onChange:(P)=>f(v.id,P)}):null]},v.id)),xe("div",{ref:b,children:xe(Y,{ui:o,style:q.button,icon:"plus",disabled:n,onClick:x,children:s("Add field")})})]})}import{useEffect as Hr,useRef as Kr,useState as xo}from"react";import{useCallback as za,useEffect as _r,useLayoutEffect as ja,useRef as vo,useState as qr}from"react";import{createContext as Va,useContext as Ba,useCallback as Ua,useEffect as Nr,useId as _a,useLayoutEffect as Lr,useRef as Or,useState as Vr}from"react";import{createPortal as qa}from"react-dom";import{jsx as lt,jsxs as Ur,Fragment as Br}from"react/jsx-runtime";var $a=Va(!1),Co="uibot:collection-popover-open";function ho({label:e,trigger:t,defaultOpen:n=!1,disabled:i,menu:r,children:o}){let[a,d]=Vr(n),[l,c]=Vr({left:8,top:8}),s=Or(null),u=Or(null),g=_a();Nr(()=>{let b=(y)=>{let m=y.detail,h=s.current;if(!m||!h||m===h)return;let f=h.closest("[data-uibot-workspace]")??h.parentElement,x=m.closest("[data-uibot-workspace]")??m.parentElement;if(f===x)d(!1)};return document.addEventListener(Co,b),()=>document.removeEventListener(Co,b)},[]);let p=()=>{d(!1),s.current?.focus({preventScroll:!0})},C=Ua(()=>{if(!a)return;let b=s.current?.getBoundingClientRect(),y=u.current?.getBoundingClientRect();if(b&&y){let m={left:Math.max(8,Math.min(b.left,window.innerWidth-y.width-8)),top:Math.max(8,b.bottom+y.height+8<=window.innerHeight?b.bottom+4:b.top-y.height-4)};c((h)=>h.left===m.left&&h.top===m.top?h:m)}},[a]);return Lr(C),Lr(()=>{if(!a)return;if(s.current)document.dispatchEvent(new CustomEvent(Co,{detail:s.current}));(u.current?.querySelector("button:not(:disabled), input, select, textarea")??u.current)?.focus({preventScroll:!0})},[a]),Nr(()=>{if(!a)return;let b=(m)=>{if(m.target instanceof Node&&!u.current?.contains(m.target)&&!s.current?.contains(m.target))d(!1)},y=(m)=>{if(m.key!=="Escape")return;m.preventDefault(),m.stopPropagation(),d(!1),s.current?.focus({preventScroll:!0})};return window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),document.addEventListener("pointerdown",b),document.addEventListener("keydown",y),()=>{window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0),document.removeEventListener("pointerdown",b),document.removeEventListener("keydown",y)}},[a,C]),Ur(Br,{children:[lt("button",{ref:s,type:"button","aria-label":e,"aria-haspopup":r?"menu":"dialog","aria-expanded":a,"aria-controls":a?g:void 0,disabled:i,style:{display:"inline-flex",alignItems:"center",gap:6,border:0,background:"transparent",color:"inherit",font:"inherit",padding:"4px 6px",cursor:"pointer"},onPointerDown:(b)=>b.stopPropagation(),onClick:()=>a?p():d(!0),children:t}),a&&qa(lt("div",{ref:u,id:g,role:r?"menu":"dialog","aria-label":e,tabIndex:-1,style:{position:"fixed",...l,zIndex:80,padding:r?4:12,minWidth:160,maxWidth:"calc(100vw - 16px)",maxHeight:"min(70vh, 600px)",overflow:"auto",boxSizing:"border-box",border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"var(--foreground, inherit)",fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},onKeyDown:(b)=>{if(!r||!["ArrowDown","ArrowUp","Home","End"].includes(b.key))return;b.preventDefault();let y=[...b.currentTarget.querySelectorAll('button[role="menuitem"]:not(:disabled)')],m=y.indexOf(document.activeElement),h=b.key==="Home"?0:b.key==="End"?y.length-1:(m+(b.key==="ArrowUp"?-1:1)+y.length)%y.length;y[h]?.focus()},children:o(p)}),document.body)]})}function dp({ui:e,label:t,defaultOpen:n,icon:i,chevron:r,quiet:o,active:a,children:d}){let l=Ba($a),c=(s)=>lt("div",{style:{fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},children:lt("fieldset",{disabled:l,style:{border:0,padding:0,margin:0,minWidth:0},children:s})});if(e?.Popover)return e.Popover({label:t,defaultOpen:n,...i?{icon:lt(Fe,{name:i})}:{},...r?{iconEnd:lt(Fe,{name:"chevronDown",size:13})}:{},...o?{quiet:o}:{},active:a,children:typeof d==="function"?(s)=>c(d(s)):c(d)});return lt(ho,{label:t,defaultOpen:n,trigger:Ur(Br,{children:[i?lt(Fe,{name:i}):null,t,r?lt(Fe,{name:"chevronDown",size:13}):null]}),children:(s)=>c(typeof d==="function"?d(s):d)})}import{jsx as On,jsxs as jr,Fragment as Ha}from"react/jsx-runtime";function $r({items:e,label:t,children:n,block:i=!1}){let[r,o]=qr(null),a=vo(null),d=vo(null),[l,c]=qr({x:0,y:0}),s=za(()=>{if(!r||!d.current)return;let g=Math.max(12,Math.min(r.x,window.innerWidth-12-d.current.offsetWidth)),p=Math.max(12,Math.min(r.y,window.innerHeight-12-d.current.offsetHeight));c((C)=>C.x===g&&C.y===p?C:{x:g,y:p})},[r]);ja(s),_r(()=>{if(!r)return;return window.addEventListener("resize",s),()=>window.removeEventListener("resize",s)},[r,s]);let u=vo(null);return _r(()=>{if(!r)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null,d.current?.querySelector("button:not(:disabled)")?.focus();let g=()=>o(null),p=(C)=>{if(C.key==="Escape")C.preventDefault(),C.stopPropagation(),o(null),u.current?.focus({preventScroll:!0})};return window.addEventListener("keydown",p),window.addEventListener("pointerdown",g),window.addEventListener("blur",g),()=>{window.removeEventListener("keydown",p),window.removeEventListener("pointerdown",g),window.removeEventListener("blur",g)}},[r]),jr("span",{ref:a,style:{display:i?"block":"inline-flex"},onKeyDown:(g)=>{if(g.shiftKey&&g.key==="F10"||g.key==="ContextMenu"){g.preventDefault(),g.stopPropagation();let p=g.target.getBoundingClientRect();o({x:Math.max(8,Math.min(p.left,window.innerWidth-240)),y:Math.max(8,Math.min(p.bottom,window.innerHeight-280))})}},onContextMenu:(g)=>{g.preventDefault(),g.stopPropagation(),o({x:Math.max(8,Math.min(g.clientX,window.innerWidth-240)),y:Math.max(8,Math.min(g.clientY,window.innerHeight-280))})},children:[n,r&&On("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 p=[...g.currentTarget.querySelectorAll("button:not(:disabled)")],C=p.indexOf(document.activeElement);p[(C+(g.key==="ArrowUp"?-1:1)+p.length)%p.length]?.focus()},children:e.map((g)=>On("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:()=>{o(null),g.onSelect()},children:g.label},g.id))})]})}function zr({label:e,items:t,disabled:n,icon:i}){return On(ho,{label:e,disabled:n,menu:!0,trigger:i??"+",children:(r)=>On(Ha,{children:t.map((o)=>jr("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:()=>{r(),o.onSelect()},children:[o.icon,o.label]},o.id))})})}import{jsx as $e,jsxs as Wr}from"react/jsx-runtime";function Ka(e,t,n,i){if(t===n)return[...e];let r=e.filter((a)=>a!==t),o=r.indexOf(n);if(o<0||!e.includes(t))return[...e];return r.splice(i?o+1:o,0,t),r}var Wa=["grid","kanban","gallery","calendar","form"];function Ya(e,t){return{grid:e("Grid"),kanban:e("Kanban"),gallery:e("Gallery"),calendar:e("Calendar"),form:e("Form")}[t]}function Ga({slot:e,items:t,label:n,children:i}){if(!t.length)return $e("span",{children:i});if(e)return $e(e,{items:t,"aria-label":n,children:i});return $e($r,{items:t,label:n,children:i})}function Ja(e){let t=K(e.locale),[n,i]=xo(null),[r,o]=xo(""),[a,d]=xo(null),l=Kr(null),c=Kr(null),s=Boolean(e.onReorder)&&!e.disabled&&e.views.length>1,u=e.views.map((w)=>w.id),g=(w,S,I)=>{let v=Ka(u,w,S,I);if(v.join("\x00")!==u.join("\x00"))e.onReorder?.(v)};Hr(()=>{let w=l.current;if(!w)return;l.current=null,document.querySelector(`[data-view-tab="${CSS.escape(w)}"]`)?.focus()}),Hr(()=>{if(n)c.current?.select()},[n]);let p=Boolean(e.onDelete)&&e.views.length>1,C=(w)=>{if(!e.onRename||e.disabled)return;o(w.name),i(w.id)},b=()=>{if(!n)return;let w=e.views.find((I)=>I.id===n),S=r.trim();if(i(null),w&&S&&S!==w.name)e.onRename?.(w.id,S)},y=(w)=>[...e.onRename?[{id:"rename",icon:$e(Fe,{name:"pencil"}),label:t("Rename view"),onSelect:()=>C(w)}]:[],...e.onDuplicate?[{id:"duplicate",icon:$e(Fe,{name:"copy"}),label:t("Duplicate view"),onSelect:()=>e.onDuplicate?.(w.id)}]:[],...e.onDelete?[{id:"delete",icon:$e(Fe,{name:"trash"}),label:t("Delete view"),destructive:!0,disabled:!p,onSelect:()=>e.onDelete?.(w.id)}]:[]],m=(w,S)=>{let I=e.views.findIndex((v)=>v.id===S.id);if(w.altKey&&(w.key==="ArrowRight"||w.key==="ArrowLeft")){w.preventDefault();let v=e.views[I+(w.key==="ArrowRight"?1:-1)];if(s&&v)l.current=S.id,g(S.id,v.id,w.key==="ArrowRight")}else if(w.key==="F2")w.preventDefault(),C(S);else if(w.key==="Delete"&&p&&!e.disabled)w.preventDefault(),e.onDelete?.(S.id);else if(w.key==="ArrowRight"||w.key==="ArrowLeft"){w.preventDefault();let v=e.views[I+(w.key==="ArrowRight"?1:-1)];if(v)e.onSelect(v.id),w.currentTarget.parentElement?.parentElement?.querySelectorAll('[role="tab"]')?.[I+(w.key==="ArrowRight"?1:-1)]?.focus()}},h=(e.viewTypes??Wa).map((w)=>({id:w,label:Ya(t,w),disabled:e.disabledViewTypes?.includes(w)??!1,onSelect:()=>e.onAdd?.(w)})),f=e.ui?.ContextMenu,x=e.ui?.DropdownMenu;return Wr("div",{"data-uibot":"collection-view-tabs",style:{display:"flex",alignItems:"flex-end",gap:2,minWidth:0,maxWidth:"100%",overflowX:"auto"},children:[$e("div",{role:"tablist","aria-label":t("Views"),style:{display:"flex",gap:2},children:e.views.map((w)=>{let S=w.id===e.activeId,I=y(w),v=n===w.id?$e("input",{ref:c,"aria-label":t("View name"),value:r,maxLength:80,style:{height:30,padding:"0 8px",font:"inherit",border:"1px solid var(--primary, #1a56c4)",borderRadius:6,background:"var(--background, white)",color:"inherit"},onChange:(P)=>o(P.target.value),onBlur:b,onKeyDown:(P)=>{if(P.stopPropagation(),P.key==="Enter")P.preventDefault(),b();else if(P.key==="Escape")P.preventDefault(),i(null)}}):Wr("button",{type:"button",role:"tab","aria-selected":S,tabIndex:S?0:-1,disabled:e.disabled,title:e.onRename?t("Double click to rename"):void 0,"data-view-tab":w.id,draggable:s,onDragStart:(P)=>{if(!s)return;P.dataTransfer.effectAllowed="move",P.dataTransfer.setData("text/plain",w.id),d({id:w.id})},onDragOver:(P)=>{if(!a||a.id===w.id)return;P.preventDefault();let E=P.currentTarget.getBoundingClientRect(),F=(P.clientX||0)>E.left+E.width/2;if(a.over!==w.id||a.after!==F)d({id:a.id,over:w.id,after:F})},onDrop:(P)=>{if(!a)return;P.preventDefault(),g(a.id,w.id,Boolean(a.after)),d(null)},onDragEnd:()=>d(null),style:{boxShadow:a?.over===w.id?a.after?"inset -2px 0 0 var(--primary, #1a56c4)":"inset 2px 0 0 var(--primary, #1a56c4)":void 0,opacity:a?.id===w.id?0.5:1,position:"relative",display:"inline-flex",alignItems:"center",gap:6,height:34,padding:"0 12px",border:0,borderBottom:S?"2px solid var(--primary, #1a56c4)":"2px solid transparent",background:"transparent",color:S?"var(--primary, #1a56c4)":"inherit",fontWeight:S?600:400,fontSize:13,whiteSpace:"nowrap",cursor:"pointer"},onClick:()=>e.onSelect(w.id),onDoubleClick:()=>C(w),onKeyDown:(P)=>m(P,w),children:[$e("span",{children:w.name}),e.dirty&&S&&$e("span",{role:"img","aria-label":t("Unsaved changes"),style:{width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}})]});return $e(Ga,{slot:f,items:n===w.id?[]:I,label:t("View actions"),children:v},w.id)})}),e.onAdd&&(x?$e(x,{label:t("Add view"),items:h,disabled:e.disabled}):$e(zr,{label:t("Add view"),items:h,disabled:e.disabled}))]})}import{useRef as Za,useState as Qa}from"react";import{jsx as Se,jsxs as Yt}from"react/jsx-runtime";function Xa(e){let t=K(e.locale),n=e.descriptor.fields.find((l)=>l.id===e.view.groupByFieldId),i=In(e),r=Za(null),[o,a]=Qa(null);if(!n||!["singleSelect","checkbox"].includes(n.type))return Se("p",{role:"status",children:t("Choose a single-select or boolean grouping field.")});let d=qo(n,t);return Yt("section",{"data-uibot":"collection-kanban",children:[Se(qt,{...e}),Se("div",{style:{display:"flex",gap:12,overflowX:"auto",alignItems:"flex-start",paddingBottom:12},children:d.map((l)=>Se(el,{...e,field:n,lane:l,lanes:d,blocked:i.blocked,onOpen:a,onMove:(c,s)=>void i.move(c,{[n.id]:s.value}),onDrag:(c)=>{r.current=c},onDrop:(c)=>{if(r.current?.id===c)i.move(r.current,{[n.id]:l.value});r.current=null}},l.id))}),Se(An,{state:i,locale:e.locale,ui:e.ui}),o&&Se(It,{...e,row:o,onClose:()=>a(null)},o.id)]})}function el({field:e,lane:t,lanes:n,blocked:i,onOpen:r,onMove:o,onDrag:a,onDrop:d,...l}){let c=K(l.locale),s=je(l.features),u=s.optionChips,g=!l.readOnly&&s.rowUpdate,p=$t(l,zo(l.view,e,t)),C=l.descriptor.fields.find((m)=>m.type==="singleLineText"||m.type==="longText")?.id,b=Pt(l.descriptor.fields,l.view).filter((m)=>m.id!==e.id&&m.id!==C).slice(0,3),y=g&&!i&&!(e.required&&t.value===null);return Yt("section",{"aria-label":c("Lane {name}",{name:t.name}),"data-lane-id":t.id,style:{...He,flex:"0 0 290px",minWidth:0,...u?{background:"var(--muted, #f4f6f8)",padding:10}:{}},onDragOver:(m)=>{if(y)m.preventDefault()},onDrop:(m)=>{if(!y)return;m.preventDefault(),d(m.dataTransfer.getData("application/x-uibot-record"))},children:[Yt("h3",{style:u?{display:"flex",alignItems:"center",gap:6,margin:"0 0 6px",fontSize:13}:void 0,children:[u&&Se("span",{"aria-hidden":"true",style:{width:8,height:8,borderRadius:999,...t.id.startsWith("option:")?{background:Et(nl(n,t)).color}:{background:"var(--muted-foreground, #9a9892)"}}}),t.name," · ",oo(c,p.page.total,p.page.items.length,l.locale)]}),Se(zt,{state:p,locale:l.locale,ui:l.ui,hideCount:!0}),Yt("div",{style:{display:"flex",flexDirection:"column",gap:8,marginTop:12,maxHeight:"65vh",overflowY:"auto"},children:[p.page.items.map((m)=>{let h=ze(m,l.descriptor.fields);return Yt("article",{"data-record-id":m.id,style:u?{...He,padding:10,boxShadow:"0 1px 2px rgb(0 0 0 / 0.06)",cursor:"grab",position:"relative"}:He,draggable:g&&!i&&!p.loading,onDragStart:(f)=>{a(m),f.dataTransfer.setData("application/x-uibot-record",m.id),f.dataTransfer.effectAllowed="move"},onDragEnd:()=>a(null),children:[Se("button",{type:"button",style:{...ae,width:"100%",textAlign:"left",overflowWrap:"anywhere",...u?{border:0,padding:"0 28px 0 0",background:"transparent",fontWeight:600}:{}},"aria-label":c("Open {name}",{name:h}),onClick:()=>r(m),children:h}),u&&Se(tl,{row:m,fields:b}),g&&(l.ui?.DropdownMenu?Se("span",{style:{position:"absolute",top:4,right:4},children:l.ui.DropdownMenu({label:c("Move {name}",{name:h}),icon:Se(Fe,{name:"more"}),disabled:i||p.loading,items:n.map((f)=>({id:f.id,label:c("Move to {name}",{name:f.name}),disabled:f.id===t.id||!!e.required&&f.value===null,onSelect:()=>o(m,f)}))})}):Yt("div",{style:{display:"flex",flexDirection:"column",gap:4,marginTop:8},children:[Se("span",{children:c("Move to")}),Se(Pe,{ui:l.ui,label:c("Move {name}",{name:h}),style:ae,disabled:i||p.loading,value:t.id,onChange:(f)=>{let x=n.find((w)=>w.id===f);if(x&&x.id!==t.id)o(m,x)},options:n.map((f)=>({value:f.id,label:f.name,disabled:!!e.required&&f.value===null}))})]}))]},m.id)}),!p.loading&&!p.error&&!p.page.items.length&&Se("p",{children:c("No records in this lane.")})]})]})}function tl({row:e,fields:t}){let n=t.map((i)=>{let r=e.values[i.id],o=i.type==="singleSelect"||i.type==="multipleSelect",a=Array.isArray(r)?r:r==null?[]:[r],d=i.type==="linkedRecord"?Qt(e,i):hn(r,i,e.computedErrors?.[i.id]);return{field:i,chips:o,ids:a,text:d}}).filter((i)=>i.chips?i.ids.length>0:i.text!=="");if(!n.length)return null;return Se("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:6,alignItems:"center",fontSize:12,opacity:0.85},children:n.map((i)=>i.chips?Se(Ln,{ids:i.ids,field:i.field},i.field.id):Se("span",{style:{fontVariantNumeric:"tabular-nums"},children:i.text},i.field.id))})}function nl(e,t){return e.filter((n)=>n.id.startsWith("option:")).findIndex((n)=>n.id===t.id)}import{useState as ol}from"react";import{jsx as nt,jsxs as Po}from"react/jsx-runtime";function rl(e){let t=K(e.locale),n=je(e.features).optionChips,i=$t(e,bn(e.view)),[r,o]=ol(null),a=e.descriptor.fields.find((l)=>l.type==="singleLineText"||l.type==="longText")?.id,d=Pt(e.descriptor.fields,e.view).filter((l)=>!n||l.id!==a);return Po("section",{"data-uibot":"collection-gallery",children:[nt(qt,{...e}),nt(zt,{state:i,locale:e.locale,ui:e.ui}),nt("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 240px), 1fr))",gap:12,marginTop:12},children:i.page.items.map((l)=>Po("article",{"data-record-id":l.id,style:{...He,minWidth:0,...n?{boxShadow:"0 1px 2px rgb(0 0 0 / 0.05)"}:{}},children:[nt("button",{type:"button","aria-label":t("Open {name}",{name:ze(l,e.descriptor.fields)}),style:{...ae,width:"100%",textAlign:"left",overflowWrap:"anywhere",...n?{border:0,padding:0,background:"transparent",fontWeight:600,fontSize:"var(--uibot-workspace-font-size, 13px)"}:{}},onClick:()=>o(l),children:ze(l,e.descriptor.fields)}),nt("dl",{children:d.filter((c)=>!n||!il(l,c)).slice(0,n?5:d.length).map((c)=>Po("div",{children:[nt("dt",{style:{fontSize:12,opacity:0.7},children:c.name}),nt("dd",{style:{margin:"0 0 8px",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n&&(c.type==="singleSelect"||c.type==="multipleSelect")&&l.values[c.id]!=null?nt(Ln,{ids:Array.isArray(l.values[c.id])?l.values[c.id]:[l.values[c.id]],field:c}):(c.type==="linkedRecord"?Qt(l,c):hn(l.values[c.id],c,l.computedErrors?.[c.id]))||"—"})]},c.id))})]},l.id))}),!i.loading&&!i.error&&!i.page.items.length&&nt("p",{children:t("No records match this view.")}),r&&nt(It,{...e,row:r,onClose:()=>o(null)},r.id)]})}function il(e,t){let n=e.values[t.id];if(t.type==="linkedRecord")return!Qt(e,t);return n==null||n===""||Array.isArray(n)&&n.length===0}import{useRef as al,useState as ko}from"react";import{jsx as ye,jsxs as yt}from"react/jsx-runtime";function ll(e){let t=K(e.locale),n=je(e.features),i=n.optionChips,r=!e.readOnly&&n.rowUpdate,[o,a]=ko(()=>{let f=new Date().toISOString().slice(0,7),x=e.initialMonth??f;try{return Xt(x),{month:x,error:""}}catch{return{month:f,error:t("Invalid initial month. Showing the current UTC month.")}}}),{month:d,error:l}=o,[c,s]=ko(null),u=e.descriptor.fields.find((f)=>f.id===e.view.dateFieldId&&f.type==="date"),g=al(null),p=In(e),C=$t(e,u?jo(e.view,u.id,d):{limit:1},!!u),b=Xt(d),y=(f)=>{try{Xt(f),a({month:f,error:""})}catch{a((x)=>({...x,error:t("Choose a valid month between years 1 and 9998.")}))}},m=(f)=>{let x=new Date(b.start);x.setUTCMonth(x.getUTCMonth()+f),y(x.toISOString().slice(0,7))},h=(f,x)=>{if(!u)return;try{p.move(f,{[u.id]:Cn(f.values[u.id],x)})}catch(w){p.mutation.setError(w instanceof Error?w.message:t("Invalid date"))}};if(!u)return ye("p",{role:"status",children:t("Choose a date field for this calendar.")});return yt("section",{"data-uibot":"collection-calendar",children:[ye(qt,{...e}),yt("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginBottom:12},children:[ye(Y,{ui:e.ui,style:ae,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:t("Previous month"),onClick:()=>m(-1)}),e.ui?.MonthPicker?ye(e.ui.MonthPicker,{value:d,onChange:y,"aria-label":t("Calendar month")}):e.ui?.Button?ye("strong",{role:"status","aria-label":t("Calendar month"),style:{minWidth:96,textAlign:"center",fontVariantNumeric:"tabular-nums"},children:t("{year}-{month}",{year:d.slice(0,4),month:d.slice(5,7)})}):yt("label",{children:[t("Month")," ",ye("input",{type:"month","aria-label":t("Calendar month"),min:"0001-01",max:"9998-12",value:d,onChange:(f)=>y(f.target.value),style:ae})]}),ye(Y,{ui:e.ui,style:ae,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:t("Next month"),onClick:()=>m(1)}),ye(Y,{ui:e.ui,style:ae,variant:"outline",size:"sm",onClick:()=>y(new Date().toISOString().slice(0,7)),children:t("Today")})]}),l&&ye("p",{role:"alert",children:l}),ye(zt,{state:C,locale:e.locale,ui:e.ui}),ye("div",{style:{overflowX:"auto",minWidth:0},children:yt("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, minmax(0, 1fr))"},children:[[t("Sun"),t("Mon"),t("Tue"),t("Wed"),t("Thu"),t("Fri"),t("Sat")].map((f)=>ye("strong",{style:i?{padding:"8px 10px",fontSize:12,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"}:{padding:8},children:f},f)),["sun","mon","tue","wed","thu","fri","sat"].slice(0,b.weekday).map((f)=>ye("div",{"aria-hidden":"true",style:i?{borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",background:"var(--muted, #f4f6f8)",opacity:0.5}:void 0},f)),Array.from({length:b.days},(f,x)=>{let w=`${d}-${String(x+1).padStart(2,"0")}`,S=C.page.items.filter((I)=>String(I.values[u.id]??"").slice(0,10)===w);return yt("article",{"aria-label":t("Day {day}",{day:w}),"data-calendar-day":w,style:{...He,minHeight:130,maxHeight:280,overflowY:"auto",minWidth:0,borderRadius:0,...i?{padding:8,border:0,borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",fontSize:12}:{}},onDragOver:(I)=>{if(r&&!p.blocked)I.preventDefault()},onDrop:(I)=>{if(!r||p.blocked)return;if(I.preventDefault(),g.current?.id===I.dataTransfer.getData("application/x-uibot-record"))h(g.current,w);g.current=null},children:[ye("time",{dateTime:w,children:x+1}),S.map((I)=>yt("article",{"data-record-id":I.id,style:{marginTop:8},draggable:r&&!p.blocked&&!C.loading,onDragStart:(v)=>{g.current=I,v.dataTransfer.setData("application/x-uibot-record",I.id),v.dataTransfer.effectAllowed="move"},onDragEnd:()=>{g.current=null},children:[yt("button",{type:"button",style:{...ae,textAlign:"left",width:"100%",overflowWrap:"anywhere",...i?{border:0,padding:"3px 8px",fontSize:12,fontWeight:500,...Et(0)}:{}},"aria-label":t("Open {name}",{name:ze(I,e.descriptor.fields)}),onClick:()=>s(I),children:[ze(I,e.descriptor.fields)," ",ye("small",{children:String(I.values[u.id]).slice(11,16)})]}),r&&ye(sl,{ui:e.ui,t,row:I,fieldId:u.id,title:ze(I,e.descriptor.fields),disabled:p.blocked||C.loading,onMove:h})]},I.id))]},w)})]})}),!C.loading&&!C.error&&!C.page.items.length&&ye("p",{children:t("No dated records match this month.")}),ye(An,{state:p,locale:e.locale,ui:e.ui}),!p.intent&&p.mutation.error&&ye("p",{role:"alert",children:p.mutation.error}),c&&ye(It,{...e,row:c,onClose:()=>s(null)},c.id)]})}function sl({ui:e,t,row:n,fieldId:i,title:r,disabled:o,onMove:a}){let[d,l]=ko({day:String(n.values[i]).slice(0,10)}),c=e?.DateMove;if(c)return ye(c,{label:t("Move {name} to date",{name:r}),value:d.day,disabled:o,onPick:(s)=>a(d.baseline??n,s)});return yt("div",{style:{marginTop:4,display:"flex",gap:4,flexWrap:"wrap"},children:[ye("input",{type:"date","aria-label":t("Move {name} to date",{name:r}),value:d.day,disabled:o,style:{width:"100%",minWidth:0},onChange:(s)=>l({day:s.target.value,baseline:d.baseline??n})}),ye("button",{type:"button",style:ae,"aria-label":t("Move {name}",{name:r}),disabled:o||!d.day,onClick:()=>a(d.baseline??n,d.day),children:t("Move")})]})}import{jsx as st,jsxs as Gt}from"react/jsx-runtime";function og({fields:e,view:t,onChange:n,locale:i,ui:r,features:o,sections:a,filterEditor:d,grouping:l,rowHeight:c}){let s=K(i),u=je(o),g=e.filter((h)=>h.type==="singleSelect"||h.type==="checkbox"),p=e.filter((h)=>h.type==="date"),C=(h)=>{let f={...t,type:h};if(delete f.groupByFieldId,delete f.dateFieldId,h==="kanban"&&g[0])f.groupByFieldId=g[0].id;if(h==="calendar"&&p[0])f.dateFieldId=p[0].id;if(h==="form")f.hiddenColumns=f.hiddenColumns.filter((x)=>!e.find((w)=>w.id===x)?.required);n(f)},b={grid:s("Grid"),kanban:s("Kanban"),gallery:s("Gallery"),calendar:s("Calendar"),form:s("Form")},y=u.viewTypes.map((h)=>({value:h,label:b[h],disabled:h==="kanban"&&!g.length||h==="calendar"&&!p.length})),m=t.type??"grid";return Gt("div",{style:{display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},children:[Gt("div",{children:[s("View type")," ",st(Pe,{ui:r,label:s("View type"),style:ae,value:m,options:y,onChange:(h)=>C(h)})]}),m==="grid"&&u.groupBy&&g.length>0&&l!==!1&&st("div",{style:{flexBasis:"100%"},children:st(Sr,{fields:e,view:t,onChange:n,locale:i,ui:r})}),m==="grid"&&c!==!1&&Gt("div",{children:[s("Row height")," ",st(Pe,{ui:r,label:s("Row height"),style:ae,value:t.rowHeight??"short",options:Ao.map((h)=>({value:h,label:s(`Row height ${h}`)})),onChange:(h)=>{let f={...t};if(h==="short")delete f.rowHeight;else f.rowHeight=h;n(f)}})]}),m==="kanban"&&Gt("div",{children:[s("Group by")," ",st(Pe,{ui:r,label:s("Kanban grouping field"),style:ae,value:t.groupByFieldId??"",options:g.map((h)=>({value:h.id,label:h.name})),onChange:(h)=>n({...t,groupByFieldId:h})})]}),m==="calendar"&&Gt("div",{children:[s("Date field")," ",st(Pe,{ui:r,label:s("Calendar date field"),style:ae,value:t.dateFieldId??"",options:p.map((h)=>({value:h.id,label:h.name})),onChange:(h)=>n({...t,dateFieldId:h})})]}),(a?.filter||a?.columns||a?.sort)&&Gt("div",{style:{display:"grid",gap:12,flexBasis:"100%"},children:[a?.filter&&st(kr,{fields:e,view:t,onChange:n,locale:i,ui:r,editor:d}),a?.columns&&st(Rr,{fields:e,view:t,onChange:n,locale:i,ui:r}),a?.sort&&st(wr,{fields:e,view:t,onChange:n,locale:i,ui:r})]})]})}export{Xi as CollectionAggregateRows,eo as CollectionAggregateSummary,ll as CollectionCalendar,aa as CollectionForm,rl as CollectionGallery,Xa as CollectionKanban,It as CollectionRecordEditor,og as CollectionViewSettings,Ja as CollectionViewTabs,an as PAGED_TABLE_ICONS,Mn as PagedCollectionFilterBuilder,wa as PagedCollectionRecordCreator,Oa as PagedCollectionSchemaEditor,Pa as PagedCollectionTableHeader,xa as PagedCollectionTableList,Nn as PagedTableIcon,En as dateModeLabel,Fn as filterOperatorLabel,br as pagedFilterSummary};
|
|
8
|
+
`).filter((L)=>L.trim()).map((L)=>{let W=L.indexOf("=");if(W<1)throw Error("Each option must use stable_id=Display name.");return{id:L.slice(0,W).trim(),name:L.slice(W+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:R}},V=()=>D.current&&F.current===P;return Le("details",{className:"rounded-lg border p-4",children:[ge("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),Le("div",{className:"mt-4 flex flex-col gap-3",children:[ge("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."}),Le("label",{children:["Field"," ",Le("select",{"aria-label":"Conversion field",value:I.id,disabled:v,onChange:(R)=>{let L=r.find((W)=>W.id===R.target.value);if(L)A(L)},children:[f.current&&!r.some((R)=>R.id===I.id)&&ge("option",{value:I.id,children:I.name}),r.map((R)=>ge("option",{value:R.id,children:R.name},R.id))]})]}),Le("label",{children:["Target type"," ",ge("select",{"aria-label":"Conversion target type",value:d,disabled:v,onChange:(R)=>{l(R.target.value),N()},children:vn.map((R)=>ge("option",{value:R.type,children:R.label},R.type))})]}),Le("label",{children:[ge("input",{type:"checkbox",checked:c,disabled:v,onChange:(R)=>{s(R.target.checked),N()}})," ","Required after conversion"]}),(d==="singleSelect"||d==="multipleSelect")&&Le("label",{children:["Stable option IDs and display names",ge("textarea",{"aria-label":"Conversion options",className:"block w-full rounded border p-2",disabled:v,value:u,onChange:(R)=>{g(R.target.value),N()},placeholder:`open=Open
|
|
9
|
+
done=Done`})]}),b&&ge("p",{role:"alert",className:"text-sm text-destructive",children:b}),ge("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:v,onClick:async()=>{let R;try{R=O()}catch(L){y(L instanceof Error?L.message:"Invalid conversion options.");return}h(!0),y(""),C(null),f.current=null;try{let L=await t.previewConversion(e.id,R);if(!V())return;if(L.ok)C(L.data);else y(L.error.message)}catch{if(V())y("Preview unavailable. Your draft is kept.")}finally{if(V())h(!1)}},children:m?"Working…":"Preview conversion"}),p&&Le(Ti,{children:[Le("p",{role:"status",children:[p.validRows," valid · ",p.invalidRows," invalid"]}),Le("p",{className:"text-xs",children:["Preview covers ",p.totalRows," records. Samples and errors show at most 20 records."]}),ge("div",{className:"overflow-x-auto",children:Le("table",{className:"w-full text-sm",children:[ge("thead",{children:Le("tr",{children:[ge("th",{children:"Record"}),ge("th",{children:"Before"}),ge("th",{children:"After"}),ge("th",{children:"Error"})]})}),ge("tbody",{children:p.sample.map((R)=>Le("tr",{children:[ge("td",{className:"max-w-32 break-all",children:R.id}),ge("td",{className:"max-w-48 break-words",children:JSON.stringify(R.before)}),ge("td",{className:"max-w-48 break-words",children:JSON.stringify(R.after)}),ge("td",{children:R.error})]},R.id))})]})}),p.errors.length>0&&ge("ul",{children:p.errors.map((R)=>Le("li",{children:[ge("span",{className:"break-all",children:R.id}),": ",ge("span",{children:R.code})]},R.id))}),ge("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:m||p.invalidRows>0,onClick:async()=>{if(!f.current)x.current=e.id,w.current++;f.current??={expectedSchemaVersion:p.schemaVersion,field:p.field,previewToken:p.previewToken,idempotencyKey:crypto.randomUUID()};let R=f.current,L=w.current,W=()=>D.current&&S.current.id===e.id&&L===w.current;h(!0),y("");try{let le=await t.convertField(e.id,R);if(!W())return;if(le.ok){if(C(null),f.current=null,x.current=null,le.data.descriptor.schemaVersion>=S.current.schemaVersion)n(le.data.descriptor)}else if(y(le.error.message),le.error.status===409)C(null),f.current=null,x.current=null}catch{if(W())y("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(W())h(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as Ei,useRef as Wn,useState as nr}from"react";import{jsx as or,jsxs as Ni}from"react/jsx-runtime";function Mi({collectionIds:e,client:t,onChanges:n,pollIntervalMs:r=2000}){let i=JSON.stringify([...new Set(e)].sort()),o=Wn(i);o.current=i;let a=Wn(n);a.current=n;let d=Wn(()=>{}),[l,c]=nr("connecting"),[s,u]=nr(!1);return Ei(()=>{let g=JSON.parse(i),p=new Map,C=!1,b=!1,y=0,m,h=()=>!C&&o.current===i,f=Math.max(50,Math.min(60000,r)),x=async()=>{if(!h()||b)return;b=!0,u(!0);let I=!1;try{let v=y>0;for(let P of g){let T=p.get(P),F=await t.changes(P,{...T!==void 0?{cursor:T}:{},limit:100});if(!h())return;if(!F.ok)throw c(F.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let D=T===void 0;if(D||v||F.data.items.length>0)await a.current(P,F.data,D);if(!h())return;p.set(P,F.data.cursor),I||=F.data.hasMore}y=0,c("live")}catch{if(y++,h())c((v)=>v==="expired"?"expired":"offline")}finally{if(b=!1,h())u(!1),m=setTimeout(()=>{x()},I&&y===0?0:Math.min(30000,f*2**Math.min(y,8)))}},w=()=>{if(m!==void 0)clearTimeout(m);x()};d.current=w,c("connecting"),x();let S=()=>{if(document.visibilityState==="visible")w()};return window.addEventListener("online",w),document.addEventListener("visibilitychange",S),()=>{if(C=!0,m!==void 0)clearTimeout(m);window.removeEventListener("online",w),document.removeEventListener("visibilitychange",S)}},[i,t,r]),Ni("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[or("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")&&or("button",{type:"button",className:"rounded border px-2 py-1",disabled:s,onClick:()=>d.current(),children:"Reconnect now"})]})}import{useEffect as xn,useRef as pt,useState as Be}from"react";import{jsx as X,jsxs as de,Fragment as Jn}from"react/jsx-runtime";var Gn={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function tn(e){try{return await e()}catch{return{ok:!1,error:Gn}}}function Yn({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return de("div",{className:"min-w-0",children:[X("strong",{children:t}),X("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&&de(Jn,{children:[X("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),X("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 Li({descriptor:e,recordId:t,client:n,readOnly:r=!1,onCommitted:i,registerRefresh:o}){let[a,d]=Be(null),[l,c]=Be(null),[s,u]=Be(null),[g,p]=Be(),[C,b]=Be(),[y,m]=Be([]),[h,f]=Be([]),[x,w]=Be(""),[S,I]=Be(null),[v,P]=Be(null),[T,F]=Be(null),[D,N]=Be(!1),[A,O]=Be(""),V=pt(null),R=pt(null),L=pt(n);L.current=n;let W=pt(!1),le=pt(0),q=`${e.id}:${t}`,J=pt(q);J.current=q;let oe=pt({historyBefore:g,commentBefore:C});oe.current={historyBefore:g,commentBefore:C};let E=pt(async()=>{}),B=(k=q)=>W.current&&J.current===k&&L.current===n,ee=async()=>{let k=q,U=++le.current,H=oe.current,[Ee,bt]=await Promise.all([tn(()=>n.history(e.id,t,{...H.historyBefore===void 0?{}:{before:H.historyBefore},limit:20})),tn(()=>n.comments(e.id,t,{...H.commentBefore===void 0?{}:{before:H.commentBefore},limit:50}))]);if(!B(k)||U!==le.current)throw Error("Refresh superseded");if(!Ee.ok||!bt.ok)throw O(!Ee.ok?Ee.error.message:!bt.ok?bt.error.message:Gn.message),Error("Activity refresh failed");c(Ee.data),u(bt.data),d(k)};E.current=ee,xn(()=>(W.current=!0,()=>{W.current=!1,le.current++}),[]),xn(()=>(o?.(()=>E.current()),()=>o?.(null)),[o]),xn(()=>{if(J.current!==q)return;c(null),u(null),d(null),p(void 0),b(void 0),m([]),f([]),oe.current={historyBefore:void 0,commentBefore:void 0},w(""),I(null),P(null),F(null),V.current=null,R.current=null,N(!1),O("")},[q]),xn(()=>{if(J.current!==q||L.current!==n||oe.current.historyBefore!==g||oe.current.commentBefore!==C)return;E.current().catch(()=>{})},[q,n,g,C]);let se=(k)=>{let U=V.current;if(U?.signature===k)return U.key;let H={signature:k,key:crypto.randomUUID()};return V.current=H,H.key},Re=async(k)=>{if(D||r||!s||a!==q)return;let U=k==="delete"?v:S;if(k!=="create"&&(!U||U.authorId!==s.actorId))return;let H=k==="create"?x:S?.draft??"";if(k!=="delete"&&(!H.trim()||H.length>4000||H.includes("\x00"))){O("Comments require 1–4,000 characters.");return}let Ee=se(JSON.stringify([k,U?.id,U?.version,H]));N(!0),O("");let bt=await tn(async()=>{if(k==="create")return n.createComment(e.id,t,{text:H,idempotencyKey:Ee});if(!U)return{ok:!1,error:Gn};if(k==="edit")return n.editComment(e.id,t,U.id,{text:H,expectedVersion:U.version,idempotencyKey:Ee});return n.deleteComment(e.id,t,U.id,{expectedVersion:U.version,idempotencyKey:Ee})});if(!B())return;if(N(!1),!bt.ok){O(bt.error.message);return}if(V.current=null,k==="create")w("");else if(k==="edit")I(null);else P(null);if(k==="create"&&C!==void 0)b(void 0),f([]);else await E.current().catch(()=>{})},z=async(k)=>{if(D||r||!l||a!==q)return;N(!0),O(""),R.current=null;let U={targetVersion:k,expectedCurrentVersion:l.currentVersion,expectedSchemaVersion:e.schemaVersion},H=await tn(()=>n.previewUndo(e.id,t,U));if(!B())return;if(N(!1),H.ok)F(H.data);else F(null),O(H.error.message)},fe=async()=>{if(D||r||a!==q||!T&&!R.current)return;let k=R.current;if(!k){if(!T)return;k={targetVersion:T.targetVersion,expectedCurrentVersion:T.currentVersion,expectedSchemaVersion:T.schemaVersion,idempotencyKey:crypto.randomUUID()},R.current=k}let U=k;N(!0),O("");let H=await tn(()=>n.undo(e.id,t,U));if(!B())return;if(N(!1),!H.ok){if(H.error.code==="version_conflict"||H.error.code==="reference_conflict"||H.error.code==="validation")R.current=null,F(null);O(H.error.message),await E.current().catch(()=>{});return}R.current=null,F(null),i(H.data),p(void 0),m([]),await E.current().catch(()=>{})},Q=s?.items.find((k)=>k.id===S?.id),Ae=S&&Q&&Q.version!==S.version,M=T&&(T.currentVersion!==l?.currentVersion||T.schemaVersion!==e.schemaVersion);return de("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[de("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[de("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),X("button",{type:"button",disabled:D,onClick:()=>{O(""),E.current().catch(()=>{})},children:"Refresh activity"})]}),A&&X("p",{role:"alert",className:"text-sm text-destructive",children:A}),!l||!s||a!==q?X("p",{role:"status",children:"Loading record activity…"}):de(Jn,{children:[de("p",{role:"status",children:["Current version ",l.currentVersion,l.currentDeleted?" · Deleted record":""]}),X("h3",{className:"font-medium",children:"Comments"}),s.items.length===0&&X("p",{className:"text-sm",children:"No comments yet."}),X("ol",{className:"flex flex-col gap-3",children:s.items.map((k)=>de("li",{className:"min-w-0 rounded border p-3",children:[de("p",{className:"break-all text-xs",children:[k.authorId," · ",k.updatedAt," · version ",k.version]}),X("p",{className:"whitespace-pre-wrap break-words text-sm",children:k.text??"Comment deleted"}),!r&&k.text!==null&&k.authorId===s.actorId&&de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:D,onClick:()=>{I({...k,draft:k.text??""}),P(null),V.current=null},children:"Edit comment"}),X("button",{type:"button",disabled:D,onClick:()=>{P(k),I(null),V.current=null},children:"Delete comment"})]})]},k.id))}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:D||!h.length,onClick:()=>{b(h.at(-1)),f((k)=>k.slice(0,-1))},children:"Newer comments"}),X("button",{type:"button",disabled:D||s.nextCursor===null,onClick:()=>{f((k)=>[...k,C]),b(s.nextCursor??void 0)},children:"Older comments"})]}),!r&&de(Jn,{children:[S&&de("div",{className:"flex flex-col gap-2",children:[de("label",{children:["Edit comment text",X("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:D,maxLength:4000,value:S.draft,onChange:(k)=>{I({...S,draft:k.target.value}),V.current=null}})]}),Ae&&de("div",{role:"status",children:[X("p",{children:"This comment changed. Your draft and original version are kept."}),de("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",Q.text??"Comment deleted"]}),Q.text!==null&&Q.authorId===s.actorId&&X("button",{type:"button",disabled:D,onClick:()=>{I({...Q,draft:S.draft}),V.current=null},children:"Use current comment version"})]}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:D||S.authorId!==s.actorId,onClick:()=>void Re("edit"),children:"Save comment"}),X("button",{type:"button",disabled:D,onClick:()=>{I(null),V.current=null},children:"Cancel comment edit"})]})]}),v&&de("div",{children:[X("p",{children:"Delete this comment? A deletion marker will remain."}),X("p",{className:"whitespace-pre-wrap break-words",children:v.text}),X("button",{type:"button",disabled:D||v.authorId!==s.actorId,onClick:()=>void Re("delete"),children:"Confirm delete comment"}),X("button",{type:"button",disabled:D,onClick:()=>P(null),children:"Cancel delete comment"})]}),de("label",{children:["New comment",X("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:D,maxLength:4000,value:x,onChange:(k)=>{w(k.target.value),V.current=null}})]}),X("button",{type:"button",className:"self-start",disabled:D||!x.trim(),onClick:()=>void Re("create"),children:"Add comment"})]}),X("h3",{className:"font-medium",children:"Record history"}),X("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."}),X("ol",{className:"flex flex-col gap-3",children:l.items.map((k)=>de("li",{className:"min-w-0 rounded border p-3",children:[de("p",{className:"break-all text-xs",children:["Version ",k.version," · ",k.operation," · schema ",k.schemaVersion," · ",k.actorId," ·"," ",k.createdAt]}),de("details",{children:[de("summary",{children:["Stored values at version ",k.version]}),X(Yn,{record:k.snapshot,label:`Version ${k.version}`})]}),!r&&k.version<l.currentVersion&&de("button",{type:"button",disabled:D,onClick:()=>void z(k.version),children:["Preview restore version ",k.version]})]},k.id))}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:D||!y.length,onClick:()=>{p(y.at(-1)),m((k)=>k.slice(0,-1))},children:"Newer history"}),X("button",{type:"button",disabled:D||l.nextCursor===null,onClick:()=>{m((k)=>[...k,g]),p(l.nextCursor??void 0)},children:"Older history"})]}),!r&&T&&de("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[de("h3",{children:["Restore version ",T.targetVersion," as a new version"]}),de("p",{children:["Current version ",T.currentVersion," · schema ",T.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),de("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[X(Yn,{record:T.before,label:"Current stored values"}),X(Yn,{record:T.target,label:"Values to restore"})]}),M&&!R.current&&X("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:D||!!M&&!R.current,onClick:()=>void fe(),children:R.current?"Retry undo":"Confirm restore"}),X("button",{type:"button",disabled:D,onClick:()=>{F(null),R.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as Pn,useRef as gt,useState as it}from"react";import{jsx as Ie,jsxs as Ue,Fragment as rr}from"react/jsx-runtime";async function kn(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 Oi(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let r of t)n+=String.fromCharCode(r);return btoa(n)}function Vi({collectionId:e,recordId:t,client:n,readOnly:r=!1,registerRefresh:i}){let o=`${e}:${t}`,a=gt({identity:o,client:n});a.current={identity:o,client:n};let d=gt(!1),l=gt(0),c=gt(0),[s,u]=it(null),[g,p]=it(null),[C,b]=it(),[y,m]=it([]),h=gt(C);h.current=C;let[f,x]=it(null),[w,S]=it(null),I=gt(null),v=gt(null),[P,T]=it(!1),[F,D]=it(!1),[N,A]=it(""),O=()=>d.current&&a.current.identity===o&&a.current.client===n,V=async()=>{let q=++l.current,J=await kn(()=>n.list(e,t,{limit:20,...h.current===void 0?{}:{before:h.current}}));if(!O()||q!==l.current)throw Error("Refresh superseded");if(!J.ok)throw A(J.error.message),Error("Attachment refresh failed");p(J.data),u(o)},R=gt(V);R.current=V,Pn(()=>(d.current=!0,()=>{d.current=!1,++l.current,++c.current}),[]),Pn(()=>{if(a.current.identity!==o||a.current.client!==n)return;u(null),p(null),x(null),S(null),I.current=null,T(!1),D(!1),A(""),b(void 0),m([]),h.current=void 0,++c.current,R.current().catch(()=>{})},[o,n]),Pn(()=>{if(h.current===C&&s===o)R.current().catch(()=>{})},[C,o,s]),Pn(()=>(i?.(()=>R.current()),()=>i?.(null)),[i]);let L=async()=>{if(P||r||!f||s!==o)return;let q=f;T(!0),A("");let J=await kn(()=>n.upload(e,t,q));if(!O())return;if(T(!1),!J.ok){A(J.error.message);return}if(x(null),v.current)v.current.value="";b(void 0),m([]),h.current=void 0,await R.current().catch(()=>{})},W=async()=>{if(P||r||!w||w.authorId!==g?.actorId||s!==o)return;I.current??=crypto.randomUUID();let q=w,J=I.current;T(!0),A("");let oe=await kn(()=>n.delete(e,t,q.id,{expectedVersion:q.version,idempotencyKey:J}));if(!O())return;if(T(!1),!oe.ok){A(oe.error.message),await R.current().catch(()=>{});return}S(null),I.current=null,await R.current().catch(()=>{})},le=async(q)=>{if(P||s!==o)return;T(!0),A("");let J=await kn(()=>n.content(e,t,q.id));if(!O())return;if(T(!1),!J.ok){A(J.error.message);return}let oe=Uint8Array.from(atob(J.data.base64),(ee)=>ee.charCodeAt(0)),E=URL.createObjectURL(new Blob([oe],{type:"application/octet-stream"})),B=document.createElement("a");B.href=E,B.download=J.data.attachment.name,B.click(),setTimeout(()=>URL.revokeObjectURL(E),1000)};return Ue("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Ue("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ie("h3",{className:"font-medium",children:"Attachments"}),Ie("button",{type:"button",disabled:P,onClick:()=>{A(""),R.current().catch(()=>{})},children:"Refresh attachments"})]}),N&&Ie("p",{role:"alert",children:N}),!g||s!==o?Ie("p",{role:"status",children:"Loading attachments…"}):Ue(rr,{children:[g.items.length===0&&Ie("p",{children:"No attachments yet."}),Ie("ol",{className:"flex min-w-0 flex-col gap-2",children:g.items.map((q)=>Ue("li",{className:"min-w-0 rounded border p-2",children:[Ie("p",{className:"break-all",children:q.name}),Ue("p",{className:"break-all text-xs",children:[q.size," bytes · version ",q.version," · ",q.authorId]}),q.deletedAt?Ie("p",{children:"Attachment deleted"}):Ue("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:P,"aria-label":`Download attachment ${q.name}`,onClick:()=>void le(q),children:"Download"}),!r&&q.authorId===g.actorId&&Ie("button",{type:"button",disabled:P,"aria-label":`Delete attachment ${q.name}`,onClick:()=>{S(q),I.current=null},children:"Delete"})]})]},q.id))}),Ue("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:P||!y.length,onClick:()=>{b(y.at(-1)),m((q)=>q.slice(0,-1))},children:"Newer attachments"}),Ie("button",{type:"button",disabled:P||g.nextCursor===null,onClick:()=>{m((q)=>[...q,C]),b(g.nextCursor??void 0)},children:"Older attachments"})]}),!r&&Ue(rr,{children:[Ie("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."}),Ue("label",{children:["Attachment file",Ie("input",{ref:v,"aria-label":"Attachment file",type:"file",disabled:P||F,onChange:async(q)=>{let J=q.target.files?.[0];if(!J)return;let oe=++c.current;if(x(null),A(""),!J.size||J.size>1048576){A("Choose a nonempty file up to 1 MiB.");return}D(!0);try{let E=await Oi(J);if(!O()||oe!==c.current)return;let B=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(J.type)?J.type:"application/octet-stream";x({name:J.name,contentType:B,base64:E,idempotencyKey:crypto.randomUUID()})}catch{if(O()&&oe===c.current)A("The selected file could not be read.")}finally{if(O()&&oe===c.current)D(!1)}}},o)]}),f&&Ue("p",{className:"break-all",children:["Selected file: ",f.name]}),Ie("button",{type:"button",className:"self-start",disabled:P||F||!f,onClick:()=>void L(),children:"Upload attachment"}),w&&Ue("div",{children:[Ue("p",{className:"break-all",children:["Delete ",w.name,"? This permanently removes its bytes and keeps a deletion marker."]}),Ue("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:P,onClick:()=>void W(),children:"Confirm delete attachment"}),Ie("button",{type:"button",disabled:P,onClick:()=>{S(null),I.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as wn,useRef as Ut,useState as _e}from"react";import{jsx as ue,jsxs as be,Fragment as ir}from"react/jsx-runtime";async function Zn(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function Bi(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function Ui({descriptor:e,recordIds:t,client:n,linkForGrant:r,registerRefresh:i}){let o=e.id,a=Ut({identity:o,client:n});a.current={identity:o,client:n};let d=Ut(!1),l=Ut(0),[c,s]=_e(null),[u,g]=_e(null),[p,C]=_e(),b=Ut(p);b.current=p;let[y,m]=_e([]),[h,f]=_e([]),[x,w]=_e([]),[S,I]=_e(3600),[v,P]=_e(null),[T,F]=_e(!1),[D,N]=_e(""),[A,O]=_e(null),V=Ut(null),[R,L]=_e(!1),[W,le]=_e(""),q=()=>d.current&&a.current.identity===o&&a.current.client===n,J=async()=>{let z=++l.current,fe=await Zn(()=>n.list(o,{limit:20,...b.current===void 0?{}:{before:b.current}}));if(!q()||z!==l.current)throw Error("Refresh superseded");if(!fe.ok)throw le(fe.error.message),Error("Share refresh failed");g(fe.data),s(o)},oe=Ut(J);oe.current=J,wn(()=>(d.current=!0,()=>{d.current=!1,++l.current}),[]),wn(()=>{if(a.current.identity!==o||a.current.client!==n)return;s(null),g(null),f([]),w([]),P(null),F(!1),N(""),O(null),V.current=null,L(!1),le(""),C(void 0),m([]),b.current=void 0,oe.current().catch(()=>{})},[o,n]),wn(()=>{if(b.current===p&&c===o)oe.current().catch(()=>{})},[p,c,o]),wn(()=>(i?.(()=>oe.current()),()=>i?.(null)),[i]);let E=()=>{if(!T)P(null)},B=async()=>{if(R||!v||c!==o)return;let z=v;L(!0),F(!0),le("");let fe=await Zn(()=>n.create(o,z));if(!q())return;if(L(!1),!fe.ok){le(fe.error.message);return}N(r(fe.data,z.key)),P(null),F(!1),C(void 0),m([]),b.current=void 0,await oe.current().catch(()=>{})},ee=async()=>{if(R||!A||c!==o)return;let z=A;V.current??=crypto.randomUUID();let fe=V.current;L(!0),le("");let Q=await Zn(()=>n.revoke(o,z.id,{expectedVersion:z.version,idempotencyKey:fe}));if(!q())return;if(L(!1),!Q.ok){le(Q.error.message),await oe.current().catch(()=>{});return}O(null),V.current=null,N(""),await oe.current().catch(()=>{})},se=e.fields.filter((z)=>!["linkedRecord","lookup","formula","rollup"].includes(z.type)),Re=R||T;return be("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[be("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[ue("h3",{className:"font-medium",children:"Read-only sharing"}),ue("button",{type:"button",disabled:R,onClick:()=>{le(""),oe.current().catch(()=>{})},children:"Refresh share grants"})]}),ue("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."}),ue("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."}),W&&ue("p",{role:"alert",children:W}),be("fieldset",{disabled:Re,className:"flex min-w-0 flex-col gap-2",children:[ue("legend",{children:"Fields to share"}),se.map((z)=>be("label",{className:"break-all",children:[ue("input",{type:"checkbox","aria-label":`Share field ${z.name}`,checked:h.includes(z.id),onChange:(fe)=>{E(),f((Q)=>fe.target.checked?[...Q,z.id]:Q.filter((Ae)=>Ae!==z.id))}})," ",z.name]},z.id))]}),be("fieldset",{disabled:Re,className:"flex min-w-0 flex-col gap-2",children:[ue("legend",{children:"Records on the current page"}),t.slice(0,100).map((z)=>be("label",{className:"break-all",children:[ue("input",{type:"checkbox","aria-label":`Share record ${z}`,checked:x.includes(z),onChange:(fe)=>{E(),w((Q)=>fe.target.checked?[...Q,z]:Q.filter((Ae)=>Ae!==z))}})," ",z]},z)),t.length===0&&ue("p",{children:"Load records in Grid to choose a share scope."})]}),be("p",{className:"break-all text-xs",children:["Selected record IDs: ",x.join(", ")||"none"]}),be("label",{children:["Link lifetime"," ",be("select",{"aria-label":"Share link lifetime",disabled:Re,value:S,onChange:(z)=>{E(),I(Number(z.target.value))},children:[ue("option",{value:60,children:"1 minute"}),ue("option",{value:3600,children:"1 hour"}),ue("option",{value:86400,children:"24 hours"})]})]}),ue("button",{type:"button",className:"self-start",disabled:Re||c!==o||!h.length||!x.length||x.length>100||h.some((z)=>!se.some((fe)=>fe.id===z)),onClick:()=>{le("");try{P({expectedSchemaVersion:e.schemaVersion,fieldIds:[...h],recordIds:[...x],expiresInSeconds:S,key:Bi(),idempotencyKey:crypto.randomUUID()})}catch{le("A secure share key could not be generated.")}},children:"Review read-only share"}),v&&be("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[be("p",{className:"break-all",children:["Confirm schema ",v.expectedSchemaVersion,", fields ",v.fieldIds.join(", "),", records ",v.recordIds.join(", ")," for ",v.expiresInSeconds," seconds."]}),v.expectedSchemaVersion!==e.schemaVersion&&ue("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),be("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:R,onClick:()=>void B(),children:T?"Retry create read link":"Create read link"}),ue("button",{type:"button",disabled:R,onClick:()=>{P(null),F(!1),le("")},children:"Discard share confirmation"})]}),T&&ue("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&&be("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",ue("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:D,onFocus:(z)=>z.target.select()})]}),!u||c!==o?ue("p",{role:"status",children:"Loading share grants…"}):be(ir,{children:[u.items.length===0&&ue("p",{children:"No share grants yet."}),ue("ol",{className:"flex min-w-0 flex-col gap-2",children:u.items.map((z)=>be("li",{className:"min-w-0 rounded border p-2",children:[be("p",{className:"break-all",children:["Grant ",z.id," · version ",z.version," · schema ",z.schemaVersion]}),be("p",{className:"break-all text-xs",children:["Fields: ",z.fieldIds.join(", ")," · Records: ",z.recordIds.join(", ")," · Expires:"," ",z.expiresAt]}),z.revokedAt?ue("p",{children:"Share revoked"}):be(ir,{children:[ue("p",{children:z.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(z.expiresAt)<=Date.now()?"Share expired":"Share active"}),ue("button",{type:"button",disabled:R,"aria-label":`Revoke share ${z.id}`,onClick:()=>{O(z),V.current=null},children:"Revoke"})]})]},z.id))}),be("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:R||!y.length,onClick:()=>{C(y.at(-1)),m((z)=>z.slice(0,-1))},children:"Newer share grants"}),ue("button",{type:"button",disabled:R||u.nextCursor===null,onClick:()=>{m((z)=>[...z,p]),C(u.nextCursor??void 0)},children:"Older share grants"})]})]}),A&&be("div",{children:[be("p",{className:"break-all",children:["Revoke grant ",A.id," at version ",A.version,"? Every existing share session will lose access."]}),be("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:R,onClick:()=>void ee(),children:"Confirm revoke share"}),ue("button",{type:"button",disabled:R,onClick:()=>{O(null),V.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as ar,useRef as _t,useState as Te}from"react";import{jsx as te,jsxs as he}from"react/jsx-runtime";var lr=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],_i=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function qi({descriptor:e,recordIds:t,client:n,webhookRequest:r}){let i=e.id,o=_t({id:i,client:n});o.current={id:i,client:n};let a=_t(!0),d=_t(0),[l,c]=Te([]),[s,u]=Te(""),g=_t(s);g.current=s;let[p,C]=Te(null),[b,y]=Te(),m=_t(b);m.current=b;let[h,f]=Te(""),[x,w]=Te("record"),[S,I]=Te(60),[v,P]=Te([]),[T,F]=Te([]),[D,N]=Te({}),[A,O]=Te(null),[V,R]=Te(!1),[L,W]=Te(!1),[le,q]=Te(""),[J,oe]=Te(""),E=()=>a.current&&o.current.id===i&&o.current.client===n,B=async(M)=>{try{return await M()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},ee=async()=>{let M=++d.current,k=await B(()=>n.list(i));if(!E()||M!==d.current)return;if(!k.ok){q(k.error.message);return}c(k.data);let U=k.data.find((Ee)=>Ee.id===g.current)?.id??k.data[0]?.id??"";if(g.current=U,u(U),!U){C(null);return}let H=await B(()=>n.runs(i,U,{limit:20,...m.current?{before:m.current}:{}}));if(!E()||M!==d.current||g.current!==U)return;if(H.ok)C(H.data);else q(H.error.message)},se=_t(ee);se.current=ee,ar(()=>{if(o.current.id!==i||o.current.client!==n)return;a.current=!0,se.current();let M=setInterval(()=>void se.current(),5000);return()=>{a.current=!1,++d.current,clearInterval(M)}},[i,n]),ar(()=>{if(g.current!==s||m.current!==b)return;se.current()},[s,b]);let Re=()=>{if(q(""),!h.trim()||!v.length||x!=="record"&&!T.length){q("Choose a name, writable fields, and target records for time or webhook triggers.");return}let M=Object.fromEntries(v.map((U)=>[U,D[U]??null])),k={expectedSchemaVersion:e.schemaVersion,name:h.trim(),trigger:x==="time"?{kind:x,intervalSeconds:S}:{kind:x},targetRecordIds:T,values:M,idempotencyKey:crypto.randomUUID(),...x==="webhook"?{webhookKey:_i()}:{}};O({kind:"create",input:k}),R(!1)},z=(M)=>{O(M),R(!1),q("")},fe=async()=>{if(!A||L)return;let M=A,k=V;R(!0),W(!0),q("");let U=await B(()=>M.kind==="create"?n.create(i,M.input):M.kind==="toggle"?n.toggle(i,M.a.id,M.input):M.kind==="run"?n.runNow(i,M.a.id,M.input):n.retry(i,M.a.id,M.run.id,M.input));if(!E())return;if(W(!1),!U.ok){if(!k&&U.error.status>=400&&U.error.status<500)R(!1);q(`${U.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(M.kind==="create"){let H=U.data;if(g.current=H.id,u(H.id),M.input.webhookKey&&r)oe(JSON.stringify(r(H,M.input.webhookKey),null,2));f(""),P([]),F([]),N({})}O(null),R(!1),m.current=void 0,y(void 0),await se.current()},Q=l.find((M)=>M.id===s),Ae=!!A||L;return he("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[te("p",{children:"Update chosen fields through record changes, a timed interval or a private webhook. Runs keep their original schema and record versions. Automatic changes do not trigger another automation."}),te("button",{type:"button",onClick:()=>void se.current(),children:"Refresh automation"}),le&&te("p",{role:"alert",children:le}),te("form",{onSubmit:(M)=>{M.preventDefault(),Re()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:he("fieldset",{disabled:Ae,style:{minWidth:0},children:[te("legend",{children:"New automation"}),he("label",{children:["Name"," ",te("input",{"aria-label":"Automation name",value:h,maxLength:200,onChange:(M)=>f(M.target.value)})]}),he("label",{children:["Trigger"," ",he("select",{"aria-label":"Automation trigger",value:x,onChange:(M)=>w(M.target.value),children:[te("option",{value:"record",children:"Record changes"}),te("option",{value:"time",children:"Timed interval"}),te("option",{value:"webhook",children:"Private webhook"})]})]}),x==="time"&&he("label",{children:["Interval in seconds"," ",te("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:S,onChange:(M)=>I(Number(M.target.value))})]}),he("fieldset",{children:[te("legend",{children:"Fields to update"}),e.fields.filter((M)=>lr.includes(M.type)).map((M)=>he("label",{style:{display:"block"},children:[te("input",{type:"checkbox",checked:v.includes(M.id),onChange:(k)=>{P(k.target.checked?[...v,M.id]:v.filter((U)=>U!==M.id))}}),M.name]},M.id))]}),te(St,{fields:e.fields.filter((M)=>v.includes(M.id)&&lr.includes(M.type)),values:D,onChange:N}),he("fieldset",{children:[te("legend",{children:"Target records from this page"}),x==="record"&&te("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&te("p",{children:"Open a grid page to choose fixed records."}),t.map((M)=>he("label",{style:{display:"block",overflowWrap:"anywhere"},children:[te("input",{type:"checkbox","aria-label":`Automation target ${M}`,checked:T.includes(M),onChange:(k)=>F(k.target.checked?[...T,M]:T.filter((U)=>U!==M))}),M]},M))]}),te("button",{type:"submit",children:"Review automation"})]})}),A&&he("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[te("p",{children:A.kind==="create"?`Create ${A.input.name} using schema ${A.input.expectedSchemaVersion}; ${A.input.targetRecordIds.length||"event"} targets.`:A.kind==="toggle"?`${A.input.enabled?"Enable":"Disable"} ${A.a.name}. Disabling fences queued and running work.`:A.kind==="run"?`Run ${A.a.name} for ${A.input.recordIds.length} explicitly selected records.`:`Retry ${A.a.name}, run ${A.run.sequence}, using its original record versions.`}),A.kind==="create"&&te("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(A.input.values,null,2)}),te("button",{type:"button",disabled:L,onClick:()=>void fe(),children:L?"Confirming…":V?"Retry automation confirmation":"Confirm automation"}),te("button",{type:"button",disabled:V||L,onClick:()=>O(null),children:"Cancel automation review"}),V&&te("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),J&&he("div",{children:[te("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),te("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:J}),te("button",{type:"button",onClick:()=>oe(""),children:"Hide webhook key"})]}),l.length>0&&he("label",{children:["Automation"," ",te("select",{"aria-label":"Selected automation",disabled:Ae,value:s,onChange:(M)=>{g.current=M.target.value,m.current=void 0,y(void 0),u(M.target.value),C(null)},children:l.map((M)=>te("option",{value:M.id,children:M.name},M.id))})]}),Q&&he("div",{children:[he("p",{children:[Q.enabled?"Enabled":"Disabled"," · ",Q.trigger.kind," · schema ",Q.schemaVersion," · configuration ",Q.version]}),te("button",{type:"button",disabled:Ae,onClick:()=>z({kind:"toggle",a:Q,input:{expectedVersion:Q.version,enabled:!Q.enabled,idempotencyKey:crypto.randomUUID()}}),children:Q.enabled?"Review disable automation":"Review enable automation"}),te("button",{type:"button",disabled:Ae||!Q.enabled||!(Q.targetRecordIds.length||t.length),onClick:()=>z({kind:"run",a:Q,input:{recordIds:Q.targetRecordIds.length?Q.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),p&&he("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!p.items.length&&te("p",{children:"No runs yet."}),p.items.map((M)=>he("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[he("p",{children:["Run ",M.sequence," · ",M.triggerKind," · ",M.status," · step ",M.step]}),he("p",{children:["Attempts: evaluate ",M.stepAttempts.evaluate,", apply ",M.stepAttempts.apply," · original versions: ",M.expectedRows.map((k)=>`${k.id}: ${k.version}`).join(", ")]}),M.errorCode&&te("p",{role:"status",children:M.errorCode}),M.leaseUntil&&he("p",{children:["Lease expires ",M.leaseUntil]}),Q&&M.status==="failed"&&he("button",{type:"button",disabled:Ae||!Q.enabled,onClick:()=>z({kind:"retry",a:Q,run:M,input:{expectedVersion:M.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",M.sequence]})]},M.id)),te("button",{type:"button",disabled:Ae||b===void 0,onClick:()=>{m.current=void 0,y(void 0)},children:"Newest runs"}),te("button",{type:"button",disabled:Ae||p.nextCursor===null,onClick:()=>{m.current=p.nextCursor??void 0,y(m.current)},children:"Older runs"})]})]})}import{useEffect as $i,useId as zi,useRef as sr,useState as De}from"react";import{jsx as ce,jsxs as ve}from"react/jsx-runtime";var dr=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function ji(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&&dr.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 Hi({descriptor:e,records:t,client:n,onApplied:r}){let i=zi(),o=e.id,a=sr({id:o,client:n}),d=sr(!0);a.current={id:o,client:n};let[l,c]=De([]),[s,u]=De(!1),[g,p]=De(""),[C,b]=De(""),[y,m]=De(""),[h,f]=De([]),[x,w]=De([]),[S,I]=De([]),[v,P]=De(null),[T,F]=De(null),[D,N]=De(null),[A,O]=De(!1),[V,R]=De(!1),[L,W]=De(""),[le,q]=De(""),[J,oe]=De(""),E=()=>d.current&&a.current.id===o&&a.current.client===n,B=async(k)=>{try{return await k()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};$i(()=>{d.current=!0,P(null),F(null),N(null),O(!1),W(""),q(""),oe(""),f([]),w([]),I([]),m("");let k=!0;return u(!1),R(!1),c([]),p(""),b(""),n.providers(o).then((U)=>{if(!k||a.current.id!==o||a.current.client!==n)return;if(u(!0),U.ok)c(U.data),p(U.data[0]?.resourceId??""),b(U.data[0]?.allowedModels[0]??"");else W(U.error.message)}).catch(()=>{if(k)u(!0),W("AI configuration is unavailable.")}),()=>{k=!1,d.current=!1}},[o,n]);let ee=()=>{try{let k=ji(e,t,{resourceId:g,model:C,instruction:y,recordIds:h,sourceFieldIds:x,targetFieldIds:S});F(structuredClone(k.records.map((U)=>({id:U.id,version:U.expectedVersion,values:Object.fromEntries(k.sourceFieldIds.map((H)=>[H,t.find((Ee)=>Ee.id===U.id)?.values[H]??null]))})))),P(k),O(!1),W(""),q("")}catch(k){W(k instanceof Error?k.message:"Invalid selection.")}},se=async()=>{if(!v||V)return;let k=v,U=A;R(!0),O(!0),W("");let H=await B(()=>n.propose(o,k));if(!E())return;if(R(!1),!H.ok){if(!U&&H.error.status>=400&&H.error.status<500)O(!1);W(`${H.error.message} Retry keeps the original selection and versions.`);return}N(H.data),oe(H.data.id),O(!1)},Re=async()=>{if(!D||V)return;let k=D,U=A;R(!0),O(!0),W("");let H=await B(()=>n.confirm(o,k));if(!E())return;if(R(!1),!H.ok){if(!U&&H.error.status>=400&&H.error.status<500)O(!1);W(`${H.error.message} The reviewed proposal keeps its original versions.`);return}q(`${H.data.items.length} records filled${H.data.replayed?"; original receipt recovered":""}.`),N(null),P(null),F(null),O(!1);try{await r?.()}catch{if(E())W("The fill committed. Refresh the Collection to see its records.")}},z=async()=>{if(V||v||D)return;R(!0),W("");let k=await B(()=>n.get(o,J));if(!E())return;if(R(!1),k.ok)N(k.data),O(!1),q("");else W(k.error.message)},fe=(k,U,H)=>H(k.includes(U)?k.filter((Ee)=>Ee!==U):[...k,U]),Q=V||!!v||!!D,Ae=e.fields.filter((k)=>dr.includes(k.type)),M=l.find((k)=>k.resourceId===g);return ve("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[ce("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."}),L&&ce("p",{role:"alert",children:L}),le&&ce("p",{role:"status",children:le}),s&&l.length===0&&ce("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),ce("form",{onSubmit:(k)=>{k.preventDefault(),ee()},children:ve("fieldset",{disabled:Q,style:{minWidth:0},children:[ce("legend",{children:"AI fill request"}),ve("label",{children:["AI resource"," ",ve("select",{"aria-label":"AI resource",value:g,onChange:(k)=>{p(k.target.value),b(l.find((U)=>U.resourceId===k.target.value)?.allowedModels[0]??"")},children:[ce("option",{value:"",children:"Choose resource"}),l.map((k)=>ce("option",{value:k.resourceId,children:k.name},k.resourceId))]})]}),ve("label",{htmlFor:i,children:["Model"," ",M?.allowedModels.length?ce("select",{id:i,"aria-label":"AI model",value:C,onChange:(k)=>b(k.target.value),children:M.allowedModels.map((k)=>ce("option",{value:k,children:k},k))}):ce("input",{id:i,"aria-label":"AI model",maxLength:200,value:C,onChange:(k)=>b(k.target.value)})]}),ve("label",{children:["Instructions"," ",ce("textarea",{"aria-label":"AI instructions",maxLength:2000,value:y,onChange:(k)=>m(k.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),ve("fieldset",{children:[ce("legend",{children:"Source fields to send"}),Ae.map((k)=>ve("label",{style:{display:"block"},children:[ce("input",{type:"checkbox","aria-label":`Send ${k.name}`,checked:x.includes(k.id),onChange:()=>fe(x,k.id,w)}),k.name]},k.id))]}),ve("fieldset",{children:[ce("legend",{children:"Fields to fill"}),Ae.map((k)=>ve("label",{style:{display:"block"},children:[ce("input",{type:"checkbox","aria-label":`Fill ${k.name}`,checked:S.includes(k.id),onChange:()=>fe(S,k.id,I)}),k.name]},k.id))]}),ve("fieldset",{children:[ce("legend",{children:"Target records from this page"}),t.map((k)=>ve("label",{style:{display:"block",overflowWrap:"anywhere"},children:[ce("input",{type:"checkbox","aria-label":`AI record ${k.id}`,checked:h.includes(k.id),onChange:()=>fe(h,k.id,f)}),k.id," · version ",k.version]},k.id))]}),ce("button",{type:"submit",disabled:!g,children:"Review AI request"})]})}),v&&!D&&ve("section",{"aria-label":"AI data disclosure",children:[ve("p",{children:["Selected service: ",v.resourceId," · model ",v.model," · schema"," ",v.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),ce("p",{children:v.instruction}),ce("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(T,null,2)}),ce("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),ce("button",{type:"button",disabled:V,onClick:()=>void se(),children:A?"Retry original AI request":"Generate proposal"}),ce("button",{type:"button",disabled:V||A,onClick:()=>{P(null),F(null),W("")},children:"Cancel AI request"})]}),D&&ve("section",{"aria-label":"AI fill confirmation",children:[ve("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",D.id," · ",D.provider," · schema ",D.schemaVersion]}),D.schemaVersion!==e.schemaVersion&&ce("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),D.rows.map((k)=>ve("div",{style:{overflowWrap:"anywhere"},children:[ve("p",{children:[k.id," · original version ",k.expectedVersion]}),Object.keys(k.values).map((U)=>ve("div",{children:[ce("strong",{children:e.fields.find((H)=>H.id===U)?.name??U}),ve("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(k.before[U]),`
|
|
10
|
+
`,"Suggested: ",JSON.stringify(k.values[U])]})]},U))]},k.id)),ce("button",{type:"button",disabled:V,onClick:()=>void Re(),children:A?"Retry original AI fill":"Confirm fill"}),ce("button",{type:"button",disabled:V||A,onClick:()=>{N(null),P(null),F(null),W("")},children:"Dismiss proposal"})]}),ve("label",{children:["Recover a saved proposal"," ",ce("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:J,onChange:(k)=>oe(k.target.value),disabled:Q,style:{width:"100%",boxSizing:"border-box"}})]}),ce("button",{type:"button",disabled:Q||!/^[a-f0-9]{64}$/.test(J),onClick:()=>void z(),children:"Load saved proposal"})]})}import{jsx as j,jsxs as ne}from"react/jsx-runtime";var Wi=[{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 Sc({fields:e,onChange:t,lockedIds:n=[],collections:r=[]}){let i=(o,a)=>t(e.map((d,l)=>l===o?{...d,...a}:d));return ne("div",{className:"flex flex-col gap-3",children:[e.map((o,a)=>{let d=n.includes(o.id);return ne("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)] gap-2 rounded-md border p-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_150px_auto]",children:[j("input",{"aria-label":`Field ${a+1} name`,placeholder:"Display name",value:o.name,onChange:(l)=>i(a,{name:l.target.value})}),j("input",{"aria-label":`Field ${a+1} ID`,placeholder:"field_id",value:o.id,disabled:d,onChange:(l)=>i(a,{id:l.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:(l)=>{let c=l.target.value,s={id:o.id,name:o.name,type:c,required:Me({type:c})?!1:o.required??!1};if(c==="formula")s.formula={expression:""};if(c==="rollup")s.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(c==="singleSelect"||c==="multipleSelect")s.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((u,g)=>g===a?s:u))},children:Wi.map((l)=>j("option",{value:l.value,children:l.name},l.value))}),ne("div",{className:"flex items-center gap-2",children:[ne("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:(l)=>i(a,{required:l.target.checked})}),"Required"]}),!d&&j("button",{type:"button",onClick:()=>t(e.filter((l,c)=>c!==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((l)=>l.name).join(", ")??"",disabled:d,onChange:(l)=>i(a,{options:l.target.value.split(",").map((c,s)=>({id:c.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${s}`,name:c.trim()})).filter((c)=>c.name)})}),o.type==="linkedRecord"&&ne("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ne("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",ne("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} linked collection`,value:o.link?.collectionId??"",disabled:d,onChange:(l)=>{let c=r.find((s)=>s.id===l.target.value);i(a,{link:{collectionId:l.target.value,displayFieldId:c?.fields.find((s)=>s.type==="singleLineText"||s.type==="longText")?.id??""}})},children:[j("option",{value:"",children:"Choose collection…"}),r.map((l)=>j("option",{value:l.id,children:l.name},l.id))]})]}),ne("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",ne("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} record label`,value:o.link?.displayFieldId??"",disabled:d||!o.link?.collectionId,onChange:(l)=>i(a,{link:{collectionId:o.link?.collectionId??"",displayFieldId:l.target.value}}),children:[j("option",{value:"",children:"Choose text field…"}),r.find((l)=>l.id===o.link?.collectionId)?.fields.filter((l)=>l.type==="singleLineText"||l.type==="longText").map((l)=>j("option",{value:l.id,children:l.name},l.id))]})]})]}),o.type==="lookup"&&ne("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ne("label",{children:["Through linked field"," ",ne("select",{"aria-label":`Field ${a+1} lookup link`,value:o.lookup?.linkFieldId??"",disabled:d,onChange:(l)=>i(a,{lookup:{linkFieldId:l.target.value,targetFieldId:""}}),children:[j("option",{value:"",children:"Choose linked field…"}),e.filter((l)=>l.type==="linkedRecord"&&l.link).map((l)=>j("option",{value:l.id,children:l.name},l.id))]})]}),ne("label",{children:["Read target field"," ",ne("select",{"aria-label":`Field ${a+1} lookup target`,value:o.lookup?.targetFieldId??"",disabled:d||!o.lookup?.linkFieldId,onChange:(l)=>i(a,{lookup:{linkFieldId:o.lookup?.linkFieldId??"",targetFieldId:l.target.value}}),children:[j("option",{value:"",children:"Choose target field…"}),r.find((l)=>l.id===e.find((c)=>c.id===o.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((l)=>!Me(l)&&l.type!=="linkedRecord").map((l)=>j("option",{value:l.id,children:l.name},l.id))]})]}),j("small",{children:"Computed from linked records. Values cannot be edited."})]}),o.type==="formula"&&ne("div",{className:"flex flex-col gap-1 md:col-span-4",children:[ne("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:(l)=>i(a,{formula:{expression:l.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."}),ne("small",{children:["References:"," ",e.filter((l)=>l.id!==o.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"]})]}),o.type==="rollup"&&ne("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[ne("label",{children:["Through linked field"," ",ne("select",{"aria-label":`Field ${a+1} rollup link`,value:o.rollup?.linkFieldId??"",onChange:(l)=>i(a,{rollup:{linkFieldId:l.target.value,targetFieldId:"",function:o.rollup?.function??"sum"}}),children:[j("option",{value:"",children:"Choose linked field…"}),e.filter((l)=>l.type==="linkedRecord"&&l.link).map((l)=>j("option",{value:l.id,children:l.name},l.id))]})]}),ne("label",{children:["Aggregate"," ",ne("select",{"aria-label":`Field ${a+1} rollup function`,value:o.rollup?.function??"sum",onChange:(l)=>{let c=l.target.value,s=r.find((u)=>u.id===e.find((g)=>g.id===o.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((u)=>u.id===o.rollup?.targetFieldId);i(a,{rollup:{linkFieldId:o.rollup?.linkFieldId??"",targetFieldId:c==="count"||s?.type==="number"?o.rollup?.targetFieldId??"":"",function:c}})},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"})]})]}),ne("label",{children:["Target field"," ",ne("select",{"aria-label":`Field ${a+1} rollup target`,value:o.rollup?.targetFieldId??"",disabled:!o.rollup?.linkFieldId,onChange:(l)=>i(a,{rollup:{linkFieldId:o.rollup?.linkFieldId??"",targetFieldId:l.target.value,function:o.rollup?.function??"sum"}}),children:[j("option",{value:"",children:"Choose target field…"}),r.find((l)=>l.id===e.find((c)=>c.id===o.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((l)=>!Me(l)&&l.type!=="linkedRecord"&&(o.rollup?.function==="count"||l.type==="number")).map((l)=>j("option",{value:l.id,children:l.name},l.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 Yi(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 Kn(e,Ye(t),n)}function nn(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.required&&typeof a==="string"&&!a.trim())throw Error(n("{name} is required.",{name:o.name}));i[o.id]=dt(Array.isArray(a)?a.join(","):String(a??""),o,r)}return i}function St({fields:e,values:t,onChange:n,relationClient:r,linkedRecords:i,computedErrors:o,locale:a,ui:d,submitted:l=!1}){let c=K(a),s=Ki();return j("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((u)=>{let g=u.description?.trim()??"",p=g?`${s}-${u.id}-hint`:void 0,C=Yi(u,t[u.id],a??"en"),y=Boolean(u.required&&Ye(t[u.id])===""&&C)&&!l?"":C,m=y?`${s}-${u.id}-error`:void 0,h=[p,m].filter(Boolean).join(" "),f={...h?{"aria-describedby":h}:{},...y?{"aria-invalid":!0}:{}};return ne("div",{className:"flex flex-col gap-1 text-sm",children:[ne("label",{htmlFor:`${s}-${u.id}`,children:[u.name,u.required?" *":""]}),g?j("p",{id:p,className:"m-0 text-xs opacity-70",children:g}):null,Me(u)?j("output",{id:`${s}-${u.id}`,"aria-label":c("{name} (read only)",{name:u.name}),...f,children:u.type==="lookup"?Vt(t[u.id]):yn(t[u.id],o?.[u.id],a)}):u.type==="linkedRecord"?j(_o,{...a?{locale:a}:{},field:u,value:t[u.id],labels:i?.[u.id],client:r,onChange:(x)=>n({...t,[u.id]:x}),...f}):u.type==="checkbox"?j("input",{id:`${s}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,type:"checkbox",checked:t[u.id]===!0,onChange:(x)=>n({...t,[u.id]:x.target.checked}),...f}):u.type==="singleSelect"&&d?.Select?j(ke,{ui:d,label:`${u.name}${u.required?" *":""}`,...f,value:String(t[u.id]??""),options:[{value:"",label:c("Choose…")},...(u.options??[]).map((x)=>({value:x.id,label:x.name}))],onChange:(x)=>n({...t,[u.id]:x||null})}):u.type==="multipleSelect"&&d?.MultiSelect?j(d.MultiSelect,{"aria-label":`${u.name}${u.required?" *":""}`,...f,options:(u.options??[]).map((x)=>({value:x.id,label:x.name,slot:fn(u.options,x.id)})),values:Array.isArray(t[u.id])?t[u.id]:[],placeholder:c("Choose…"),onChange:(x)=>n({...t,[u.id]:x})}):u.type==="singleSelect"||u.type==="multipleSelect"?ne("select",{id:`${s}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...f,className:"min-h-9 rounded-md border bg-background p-2",multiple:u.type==="multipleSelect",value:u.type==="multipleSelect"?Array.isArray(t[u.id])?t[u.id]:[]:String(t[u.id]??""),onChange:(x)=>n({...t,[u.id]:u.type==="multipleSelect"?Array.from(x.target.selectedOptions,(w)=>w.value):x.target.value||null}),children:[u.type==="singleSelect"&&j("option",{value:"",children:c("Choose…")}),u.options?.map((x)=>j("option",{value:x.id,children:x.name},x.id))]}):u.type==="date"&&d?.DatePicker?(()=>{let x={kind:Bo(u),timeZone:Ne(u)?.timeZone},w=String(t[u.id]??"");return j(d.DatePicker,{id:`${s}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...f,value:Ko(w,x),withTime:x.kind==="auto"?ct(w):x.kind==="datetime",fixedKind:x.kind!=="auto",clearable:!u.required,onChange:(S)=>n({...t,[u.id]:S?Wo(S,w,x):null})})})():u.type==="longText"?j("textarea",{id:`${s}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...f,className:"rounded-md border bg-background p-2",value:String(t[u.id]??""),onChange:(x)=>n({...t,[u.id]:x.target.value||null})}):j("input",{id:`${s}-${u.id}`,"aria-label":`${u.name}${u.required?" *":""}`,...f,className:"min-h-9 min-w-0 rounded-md border bg-background p-2",type:u.type==="number"?"number":u.type==="date"?"date":"text",step:u.type==="number"?"any":void 0,value:u.type==="date"?String(t[u.id]??"").slice(0,10):String(t[u.id]??""),onChange:(x)=>n({...t,[u.id]:x.target.value===""?null:u.type==="number"?Number(x.target.value):u.type==="date"&&t[u.id]?Cn(t[u.id],x.target.value):x.target.value})}),y?j("span",{id:m,className:"text-xs text-red-600",children:y}):null]},u.id)})})}function Gi(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)&&!Ct(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 Ic({fields:e,view:t,onChange:n,onError:r}){let i=e.filter(Ct),[o,a]=Qn(i[0]?.id??""),d=i.some((m)=>m.id===o)?o:i[0]?.id??"",[l,c]=Qn("contains"),s=d?(()=>{let m=e.find((h)=>h.id===d);return m&&Me(m)?m.resultType:m?.type})():void 0,u=s==="number"?["is","isNot","isEmpty"]:s==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],g=u.includes(l)?l:s==="number"||s==="date"?"is":"contains",[p,C]=Qn(""),y=[...t.columnOrder.flatMap((m)=>{let h=e.find((f)=>f.id===m);return h?[h]:[]}),...e.filter((m)=>!t.columnOrder.includes(m.id))];return ne("div",{className:"flex flex-wrap items-end gap-3",children:[ne("label",{className:"flex min-w-52 flex-col gap-1 text-sm",children:["Search",j("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})})]}),ne("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(m)=>{m.preventDefault();let h=e.find((x)=>x.id===d);if(!h)return;let f;try{f=Gi(h,g,p)}catch(x){r(x instanceof Error?x.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:d,operator:g,...g==="isEmpty"?{}:{value:f}}]}})},children:[ne("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:(m)=>a(m.target.value),children:i.map((m)=>j("option",{value:m.id,children:m.name},m.id))})]}),j("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:g,onChange:(m)=>c(m.target.value),children:u.map((m)=>j("option",{value:m,children:m==="isNot"?"is not":m==="isEmpty"?"is empty":m==="onOrAfter"?"on or after":m},m))}),g!=="isEmpty"&&j("input",{type:s==="number"?"number":s==="date"?"date":"text",step:s==="number"?"any":void 0,className:"min-h-9 max-w-40 rounded-md border bg-background p-2","aria-label":"Filter value",value:p,onChange:(m)=>C(m.target.value)}),j("button",{type:"submit",disabled:!d,children:"Apply filter"}),j("button",{type:"button",onClick:()=>{let m={...t};delete m.filter,n(m)},children:"Clear filter"})]}),ne("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:y.map((m,h)=>ne("div",{className:"flex items-center gap-2 text-sm",children:[ne("label",{className:"flex flex-1 items-center gap-2",children:[j("input",{type:"checkbox",checked:!t.hiddenColumns.includes(m.id),disabled:t.type==="form"&&m.required===!0,onChange:(f)=>n({...t,hiddenColumns:f.target.checked?t.hiddenColumns.filter((x)=>x!==m.id):[...t.hiddenColumns,m.id]})}),m.name]}),j("button",{type:"button","aria-label":`Move ${m.name} left`,disabled:h===0,onClick:()=>{let f=y.map((w)=>w.id),x=f[h-1];if(x!==void 0)[f[h-1],f[h]]=[m.id,x];n({...t,columnOrder:f})},children:"←"}),j("button",{type:"button","aria-label":`Move ${m.name} right`,disabled:h===y.length-1,onClick:()=>{let f=y.map((w)=>w.id),x=f[h+1];if(x!==void 0)[f[h],f[h+1]]=[x,m.id];n({...t,columnOrder:f})},children:"→"})]},m.id))})]})]})}import{useEffect as Ji,useMemo as cr,useState as ur}from"react";import{jsx as Xn}from"react/jsx-runtime";function Zi(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 Qi(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 pr(e,t,n,r={},i={}){return n.map((o)=>{let a=t.groupBy.map((l)=>{let c=e.fields.find((s)=>s.id===l);return`${c?.name??l} ${Qi(c,o.groups[l],i)}`}),d=t.aggregates.map((l)=>{let c=o.values[l.as];return`${r[l.as]??l.as}: ${typeof c==="number"||typeof c==="string"?String(c):i.none??"none"}`});return[...a,...d].join(" · ")})}function Xi({descriptor:e,query:t,rows:n}){return Xn("ul",{"data-uibot":"collection-aggregate",children:pr(e,t,n).map((r)=>Xn("li",{children:r},r))})}function eo({collectionId:e,descriptor:t,view:n,groupBy:r,aggregates:i,client:o,locale:a,labels:d,reloadKey:l=0}){let c=cr(()=>Do(n,{aggregates:i,...r?{groupBy:r}:{}}),[n,r,i]),s=cr(()=>K(a),[a]),[u,g]=ur(s("Loading summary…")),[p,C]=ur(!1);return Ji(()=>{let b=Fo(t,c);if(b){g(s(Zi(b))),C(!0);return}let y=!0;return g(s("Loading summary…")),C(!1),o.aggregate(e,c).then((m)=>{if(!y)return;if(!m.ok){g(m.error.message),C(!0);return}let h=pr(t,c,m.data,d??{},{unassigned:s("Unassigned"),checked:s("Checked"),unchecked:s("Unchecked"),none:s("none")});g(h.length?h.join(" · "):s("No summary rows.")),C(!1)}).catch(()=>{if(!y)return;g(s("The collection service is unavailable.")),C(!0)}),()=>{y=!1}},[o,e,t,c,d,s,l]),Xn("p",{role:p?"alert":"status","data-uibot":"collection-aggregate",children:u})}var mr=["grid","kanban","gallery","calendar","form"],ea=["grid","form"],to={search:!0,filter:!0,columns:!0,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!0,tableList:!0,viewManagement:!0,export:!0},ta={search:!0,filter:!1,columns:!1,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!1,tableList:!1,viewManagement:!1,export:!1},na={search:!0,filter:!0,columns:!0,rowCreate:!1,rowUpdate:!1,rowDelete:!1,schemaEditor:!1,tableList:!0,viewManagement:!1,export:!0},gr={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:mr},no={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:mr},oa={basic:{...gr,...to},full:{...no,...to},simple:{...gr,...ta,viewTypes:ea},workbench:{...no,...to},readonly:{...no,...na,recordContextMenu:!1,optimisticEdit:!1}};function je(e){let{preset:t="basic",...n}=e??{},r={...oa[t],...ra(n)};return r.groupBy?r:{...r,groupCollapse:!1}}function ra(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}import{jsx as Z,jsxs as Oe,Fragment as ao}from"react/jsx-runtime";function qt(e){if(!e.aggregate)return null;return Z(eo,{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 ae={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},He={padding:12,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)"},Rn={items:[],total:0,nextCursor:null,limit:50};function $t(e,t,n=!0){let r=K(e.locale),i=JSON.stringify([e.descriptor.id,e.descriptor.schemaVersion,t]),[o,a]=qe({key:i,history:[]}),d=o.key===i?o.cursor:void 0,l=o.key===i?o.history:[],c=JSON.stringify([i,d]),[s,u]=qe(0),[g,p]=qe({key:c,page:Rn,loading:n,error:""});Sn(()=>{let b=!0;if(!n){p({key:c,page:Rn,loading:!1,error:""});return}p((h)=>({key:c,page:h.key===c?h.page:Rn,loading:!0,error:""}));let[y,,m]=JSON.parse(i);return e.client.query(y,{...m,...d?{cursor:d}:{}}).then((h)=>{if(!b)return;if(h.ok)p({key:c,page:h.data,loading:!1,error:""});else p((f)=>({...f,loading:!1,error:h.error.message}))}).catch(()=>{if(b)p((h)=>({...h,loading:!1,error:r("Collection query failed. Retry to load records.")}))}),()=>{b=!1}},[c,i,d,e.client,e.reloadKey,n,s]);let C=g.key===c?g.page:Rn;return{page:C,loading:n&&(g.key!==c||g.loading),error:g.key===c?g.error:"",previous:l.length?()=>a({key:i,cursor:l.at(-1),history:l.slice(0,-1)}):void 0,next:C.nextCursor?()=>a({key:i,cursor:C.nextCursor??void 0,history:[...l,d]}):void 0,retry:()=>u((b)=>b+1),pageNumber:l.length+1}}function oo(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 ia({hasPrevious:e,hasNext:t,onPrevious:n,onNext:r,loading:i,page:o,locale:a,ui:d}){let l=K(a);if(!e&&!t)return null;return Oe("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[Z(Y,{ui:d,style:ae,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:l("Previous page"),disabled:!e||i,onClick:n}),o?Z("span",{style:{fontSize:12},children:l("Page {page}",{page:o})}):null,Z(Y,{ui:d,style:ae,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:l("Next page"),disabled:!t||i,onClick:r})]})}function zt({state:e,locale:t,ui:n,hideCount:r}){let i=K(t);return Oe("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[r?null:Z("span",{children:oo(i,e.page.total,e.page.items.length,t)}),Z(ia,{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&&Z("span",{role:"status",children:i("Loading records…")}),e.error&&Oe(ao,{children:[Z("span",{role:"alert",children:e.error}),Z(Y,{ui:n,style:ae,variant:"outline",size:"sm",disabled:e.loading,onClick:e.retry,children:i("Retry query")})]})]})}function ro(e){let t=pn(e.client,e.descriptor.id),n=K(e.locale),[r,i]=qe(!1),[o,a]=qe(""),[d,l]=qe(null),c=on(null);Nt({dirty:Boolean(c.current),busy:r});let s=()=>{c.current=null,a(""),l(null)};return{saving:r,error:o,setError:a,remote:d,pending:c,reset:s,commit:async(p)=>{if(r||e.readOnly)return!1;c.current=p,i(!0),a(""),l(null);let C=await e.client.mutate(e.descriptor.id,p).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:n("Saving failed. Your change has been kept.")}}));if(!t.active)return!1;if(i(!1),C.ok)return s(),e.onCommitted(C.data),!0;a(C.error.message);let b=C.error.details?.current;if(b&&typeof b.id==="string"&&Number.isSafeInteger(b.version)&&b.version>0)l(b);return!1},retryRequest:()=>c.current&&d?{idempotencyKey:crypto.randomUUID(),items:c.current.items.map((p)=>p.op!=="insert"&&p.id===d.id?{...p,expectedVersion:d.version}:p)}:c.current}}function io({mutation:e,onRetry:t,locale:n,ui:r}){let i=K(n);return Oe(ao,{children:[e.error&&Z("p",{role:"alert",children:e.error}),e.remote&&Oe("div",{style:He,children:[Z("strong",{children:i("Current server version {version}",{version:e.remote.version})}),Z("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(e.remote.values,null,2)}),Z(Y,{ui:r,style:ae,variant:"outline",size:"sm",disabled:e.saving,onClick:t,children:i("Retry against current version")})]})]})}function It({row:e,onClose:t,onCancel:n,onDirtyChange:r,onBusyChange:i,stickyActions:o,...a}){let d=K(a.locale),l=je(a.features),c=!a.readOnly&&l.rowDelete,s=!a.readOnly&&l.rowUpdate,u=on(e.values),[g,p]=qe(()=>({...u.current})),[C,b]=qe(!1);Nt({dirty:JSON.stringify(g)!==JSON.stringify(u.current),busy:!1});let y=on(null),[m,h]=qe(!1);Sn(()=>{y.current?.focus()},[]);let f=ro(a),x=Pt(a.descriptor.fields,a.view),w=JSON.stringify(g)!==JSON.stringify(e.values);Sn(()=>{r?.(w)},[w,r]),Sn(()=>{i?.(f.saving)},[f.saving,i]);let S=async(v=!1)=>{b(!0);try{let P=v?f.retryRequest():f.pending.current;if(!P){let T=x.filter((D)=>D.type!=="lookup"&&D.type!=="formula"&&D.type!=="rollup"&&JSON.stringify(g[D.id])!==JSON.stringify(e.values[D.id]));if(!T.length){f.setError(d("Change a field before saving."));return}let F=nn(T,g,d,a.locale);P={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:e.id,expectedVersion:e.version,values:F}]}}if(await f.commit(P))t()}catch(P){f.setError(P instanceof Error?P.message:d("Invalid value"))}},I=async()=>{let v=f.pending.current?.items[0]?.op==="delete"?f.pending.current:{idempotencyKey:crypto.randomUUID(),items:[{op:"delete",id:e.id,expectedVersion:e.version}]};if(await f.commit(v))t()};return Oe("div",{ref:y,tabIndex:-1,onKeyDown:(v)=>{if(v.key==="Escape"&&!f.saving)v.stopPropagation(),(n??t)()},role:"dialog","aria-label":d("{name} record",{name:ze(e,a.descriptor.fields)}),style:{...He,marginTop:12},children:[Z("h3",{children:ze(e,a.descriptor.fields)}),a.onInspectRecord&&Z(Y,{ui:a.ui,style:ae,variant:"outline",size:"sm",disabled:f.saving,onClick:()=>a.onInspectRecord?.(e.id),children:d("Open record activity")}),Oe("form",{onSubmit:(v)=>{v.preventDefault(),S()},children:[Z("fieldset",{disabled:f.saving||m||!s,style:{border:0,padding:0},children:Z(St,{fields:x,values:g,submitted:C,...a.locale?{locale:a.locale}:{},...a.ui?{ui:a.ui}:{},relationClient:a.client,linkedRecords:e.linkedRecords,computedErrors:e.computedErrors,onChange:(v)=>{p(v),f.reset()}})}),Oe("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:[s&&Z("button",{type:"submit",style:{...ae,...Bt},disabled:f.saving||m,children:f.saving?d("Saving…"):d("Save record")}),o?null:Z("button",{type:"button",style:ae,disabled:f.saving,onClick:n??t,children:d("Close record")}),o&&c?Z("span",{style:{marginLeft:"auto"},children:Z(Y,{ui:a.ui,variant:"ghost",size:"sm",icon:"trash",disabled:f.saving,onClick:()=>h(!0),children:d("Delete record")})}):null]})]}),c&&!o&&Z("button",{type:"button",style:ae,disabled:f.saving,onClick:()=>h(!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:f.saving,onConfirm:()=>void I(),onCancel:()=>{if(h(!1),f.pending.current?.items[0]?.op==="delete")f.reset()}}):null,m&&!a.ui?.ConfirmDialog&&Oe(Xo,{alert:!0,label:d("Confirm record deletion"),busy:f.saving,onCancel:()=>{if(h(!1),f.pending.current?.items[0]?.op==="delete")f.reset()},children:[Z("p",{children:d("Delete this record? Your unsaved changes will be discarded after deletion.")}),Z("button",{type:"button",style:ae,disabled:f.saving,onClick:()=>void I(),children:d("Confirm deletion")}),Z("button",{type:"button",style:ae,disabled:f.saving,onClick:()=>{if(h(!1),f.pending.current?.items[0]?.op==="delete")f.reset()},children:d("Cancel deletion")})]}),Z(io,{mutation:f,onRetry:()=>void S(!0),locale:a.locale,ui:a.ui})]})}function aa(e){let t=K(e.locale),n=!e.readOnly&&je(e.features).rowCreate,r=on(null),i=Pt(e.descriptor.fields,{...e.view,hiddenColumns:e.view.hiddenColumns.filter((y)=>!e.descriptor.fields.find((m)=>m.id===y)?.required)}),o=()=>({...Object.fromEntries(i.filter((y)=>y.type==="checkbox").map((y)=>[y.id,!1])),...Jt(i)}),a=on(o()),[d,l]=qe(a.current),[c,s]=qe(!1),[u,g]=qe(!1);Nt({dirty:JSON.stringify(d)!==JSON.stringify(a.current),busy:!1});let p=ro(e),C=()=>r.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")?.focus(),b=async()=>{if(!n)return;g(!0);try{let y=p.pending.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:nn(i,d,t,e.locale)}]};if(await p.commit(y))a.current=o(),l(a.current),s(!0),g(!1),requestAnimationFrame(C)}catch(y){p.setError(y instanceof Error?y.message:t("Invalid value"))}};return Oe("section",{"data-uibot":"collection-form",style:He,children:[Z("h3",{children:e.view.name}),e.readOnly&&Z("p",{children:t("Record creation requires editor permission.")}),Oe("form",{ref:r,onSubmit:(y)=>{y.preventDefault(),b()},children:[Z("fieldset",{disabled:p.saving||!n,style:{border:0,padding:0},children:Z(St,{fields:i,values:d,submitted:u,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},relationClient:e.client,onChange:(y)=>{l(y),s(!1),p.reset()}})}),n&&Z("button",{type:"submit",style:{...ae,...Bt},disabled:p.saving,children:p.saving?t("Creating…"):t("Create record")})]}),Z(io,{mutation:p,onRetry:()=>void b(),locale:e.locale,ui:e.ui}),c?Oe("p",{role:"status",children:[t("Record created. Add another below."),e.onShowRecords?Oe(ao,{children:[" ",Z(Y,{ui:e.ui,style:ae,variant:"outline",size:"sm",onClick:e.onShowRecords,children:t("Show records")})]}):null]}):null]})}function In(e){let[t,n]=qe(null),r=ro(e),i=!e.readOnly&&je(e.features).rowUpdate;return{intent:t,mutation:r,move:async(d,l)=>{if(!i||r.saving||t)return;n({row:d,values:l});let c={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:d.id,expectedVersion:d.version,values:l}]};if(await r.commit(c))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 An({state:e,locale:t,ui:n}){let r=K(t);if(!e.intent)return null;return Oe("div",{role:"dialog","aria-label":r("Pending record move"),style:He,children:[Z("p",{children:e.mutation.saving?r("Moving record…"):r("The move has been kept for retry.")}),Z("pre",{children:JSON.stringify(e.intent.values,null,2)}),Z(io,{mutation:e.mutation,onRetry:()=>void e.retry(),locale:t,ui:n}),!e.mutation.remote&&Z(Y,{ui:n,style:ae,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:()=>void e.retry(),children:r("Retry move")}),Z(Y,{ui:n,style:ae,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:e.cancel,children:r("Cancel move")})]})}import{useEffect as ua,useMemo as Cr,useRef as pa,useState as ga}from"react";import{useEffect as lo,useMemo as la,useState as At}from"react";import{jsx as jt,jsxs as fr}from"react/jsx-runtime";function Dn(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 yr(e){let t=la(()=>K(e.locale),[e.locale]),[n,r]=At(""),[i,o]=At(),[a,d]=At(null),[l,c]=At([]),[s,u]=At(()=>Dn({},e.labels)),[g,p]=At(""),[C,b]=At(!1),y=e.field.relation?.collectionId,m=e.field.relation?.labelFieldId,{getOptions:h,value:f}=e;lo(()=>{u((S)=>Dn(S,e.labels))},[e.labels]),lo(()=>{let S=!1;if(!y||!h)return;return b(!0),p(""),h({collectionId:y,...m?{labelFieldId:m}:{},search:n,...i?{cursor:i}:{},limit:50}).then((I)=>{if(S)return;if(!I.ok){p(I.error.message),d(null);return}let v=I.data.items.slice(0,50);u((P)=>Dn(P,v)),c((P)=>{let T=i?[...P,...v]:v;return[...new Map(T.map((F)=>[F.id,F])).values()]}),d(I.data.nextCursor)}).catch(()=>{if(!S)p(t("Relation options unavailable."))}).finally(()=>{if(!S)b(!1)}),()=>{S=!0}},[y,m,n,i,h,t]),lo(()=>{if(!f||!y||!h)return;if(e.labels?.some((I)=>I.id===f&&I.label.trim()))return;let S=!1;return h({collectionId:y,...m?{labelFieldId:m}:{},ids:[f],limit:50}).then((I)=>{if(S||!I.ok)return;let v=I.data.items.find((P)=>P.id===f);if(v)u((P)=>Dn(P,[v]))}).catch(()=>{}),()=>{S=!0}},[f,y,m,h,e.labels]);let x=!y||!h,w=f?s[f]??l.find((S)=>S.id===f)?.label??f:"";return fr("div",{children:[jt("input",{"aria-label":t("Search {name}",{name:e.field.name}),value:n,disabled:e.disabled||x,onChange:(S)=>{r(S.currentTarget.value),o(void 0),c([]),d(null)}}),fr("select",{"aria-label":e.label??e.field.name,value:e.value,disabled:e.disabled||x||C,onChange:(S)=>{let I=S.currentTarget.value;if(!I||l.some((v)=>v.id===I))e.onChange(I)},children:[jt("option",{value:"",children:t("No relation")}),f&&!l.some((S)=>S.id===f)&&jt("option",{value:f,children:w}),l.map((S)=>jt("option",{value:S.id,children:S.label},S.id))]}),a&&jt("button",{type:"button",disabled:C||e.disabled,onClick:()=>o(a),children:t("More {name} options",{name:e.field.name})}),(g||x)&&jt("span",{role:"status",children:g||t("Relation option provider unavailable.")})]})}var sa={"zh-CN":{is:"等于",isNot:"不等于",contains:"包含",notContains:"不包含",isEmpty:"为空",isNotEmpty:"不为空",gt:"大于",gte:"大于等于",lt:"小于",lte:"小于等于",before:"早于",after:"晚于",onOrBefore:"不晚于",onOrAfter:"不早于"},en:{is:"is",isNot:"is not",contains:"contains",notContains:"does not contain",isEmpty:"is empty",isNotEmpty:"is not empty",gt:">",gte:"≥",lt:"<",lte:"≤",before:"is before",after:"is after",onOrBefore:"is on or before",onOrAfter:"is on or after"}},da={"zh-CN":{is:"恰好是",isNot:"不是恰好",contains:"包含任一",notContains:"不包含任一"},en:{is:"is exactly",isNot:"is not exactly",contains:"has any of",notContains:"has none of"}},ca={"zh-CN":{exactDate:"指定日期",dateRange:"日期区间",today:"今天",yesterday:"昨天",tomorrow:"明天",currentWeek:"本周",lastWeek:"上周",nextWeek:"下周",currentMonth:"本月",lastMonth:"上月",nextMonth:"下月",currentYear:"今年",lastYear:"去年",nextYear:"明年",pastDays:"过去 N 天",nextDays:"未来 N 天",daysAgo:"N 天前",daysFromNow:"N 天后"},en:{exactDate:"exact date",dateRange:"date range",today:"today",yesterday:"yesterday",tomorrow:"tomorrow",currentWeek:"this week",lastWeek:"last week",nextWeek:"next week",currentMonth:"this month",lastMonth:"last month",nextMonth:"next month",currentYear:"this year",lastYear:"last year",nextYear:"next year",pastDays:"past N days",nextDays:"next N days",daysAgo:"N days ago",daysFromNow:"N days from now"}},Fn=(e,t="en",n)=>{if(n&&Ke(n)==="multipleSelect"){let r=da[t][e];if(r)return r}return sa[t][e]??e},Tn=(e,t="en")=>ca[t][e]??e;function so(e,t){if(!t)return"";let n=e?Ne(e):void 0;return n?Lt(t,{...n,time:"none"}):t}function br(e,t,n="en"){let r=n==="zh-CN";return e.filterSet.map((i)=>{if("filterSet"in i)return`(${br(i,t,n)})`;let o=t.find((c)=>c.id===i.fieldId),a=Fn(i.operator,n,o);if(i.operator==="isEmpty"||i.operator==="isNotEmpty")return`${o?.name??i.fieldId} ${a}`;let d=(c)=>o?.options?.find((s)=>s.id===c)?.name??String(c??""),l;if($n(i.value)){let c=i.value,s=Tn(c.mode,n);l=c.mode==="exactDate"?so(o,c.date):c.mode==="dateRange"?`${so(o,c.date)} ~ ${so(o,c.to)}`:c.days!==void 0?s.replace("N",String(c.days)):s}else l=Array.isArray(i.value)?i.value.map(d).join(r?"、":", "):d(i.value);return`${o?.name??i.fieldId} ${a} ${l}`}).join(e.conjunction==="or"?r?" 或 ":" OR ":r?" 且 ":" AND ")}import{jsx as re,jsxs as Xe,Fragment as Pr}from"react/jsx-runtime";var ma={text:["is","isNot","contains","isEmpty"],number:["is","isNot","gte","lte","isEmpty"],checkbox:["is"],date:["is","isNot","before","onOrAfter","isEmpty"],singleSelect:["is","isNot","isEmpty"],multipleSelect:["is","contains","isEmpty"]};function Ht(e){return re("span",{style:pe.cell,children:re(ke,{...e})})}var En=()=>`row_${Math.random().toString(36).slice(2,10)}`,fa=(e)=>("filterSet"in e),ya=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}};function co(e,t){if(t)return Mo(e);let n=Ke(e);return n?ma[n]??[]:[]}function uo(e,t,n){if(Mt.has(t))return;let r=Ke(e);if(r==="date"&&n)return{mode:"today",timeZone:Ne(e)?.timeZone??ya()};if(r==="checkbox")return!0;if(r==="multipleSelect")return[];return r==="number"?void 0:""}function hr(e){let t=[],n=[];for(let r of e?.filterSet??[])if(fa(r))n.push({key:En(),node:r});else t.push({key:En(),fieldId:r.fieldId,operator:r.operator,value:r.value});return{rows:t,groups:n,conjunction:e?.conjunction??"and"}}function vr(e,t,n,r){let i=[],o=!0;for(let l of t){let c=e.find((g)=>g.id===l.fieldId);if(!c||!l.operator){o=!1;continue}let s=l.value===""||Array.isArray(l.value)&&l.value.length===0;if(!Mt.has(l.operator)&&s){o=!1;continue}let u={fieldId:l.fieldId,operator:l.operator,...Mt.has(l.operator)?{}:{value:l.value}};if(No(c,u))o=!1;else i.push(u)}let a=n.map((l)=>l.node).filter((l)=>Boolean(l?.filterSet.length)),d=[...i,...a];return{node:d.length?{conjunction:r,filterSet:d}:void 0,complete:o}}function Mn(e){let{ui:t,locale:n}=e,r=e.advanced!==!1,i=e.allowGroups!==!1,o=Cr(()=>K(n),[n]),a=Cr(()=>e.fields.filter((b)=>!Me(b)&&Ke(b)!==null),[e.fields]),[d,l]=ga(()=>hr(e.filter)),c=pa(JSON.stringify(e.filter??null));ua(()=>{let b=JSON.stringify(e.filter??null);if(b!==c.current)c.current=b,l(hr(e.filter))},[e.filter]);let s=(b)=>{l(b);let{node:y}=vr(a,b.rows,b.groups,b.conjunction),m=JSON.stringify(y??null);if(m!==c.current)c.current=m,e.onChange(y)},u=(b,y)=>s({...d,rows:d.rows.map((m)=>m.key===b?{...m,...y}:m)}),g=()=>{let b=a[0];if(!b)return;let y=co(b,r)[0]??"";s({...d,rows:[...d.rows,{key:En(),fieldId:b.id,operator:y,value:y?uo(b,y,r):void 0}]})},p=()=>s({...d,groups:[...d.groups,{key:En(),node:void 0}]}),C=vr(a,d.rows,d.groups,d.conjunction).complete===!1||d.groups.some((b)=>b.node===void 0);return Xe("div",{"data-uibot-filter-builder":"",style:pe.root,children:[d.rows.length+d.groups.length>1?Xe("div",{style:pe.inline,children:[re("span",{children:o("Match")}),re(Ht,{ui:t,label:o("Filter conjunction"),style:pe.control,value:d.conjunction,options:[{value:"and",label:o("all conditions")},{value:"or",label:o("any condition")}],onChange:(b)=>s({...d,conjunction:b==="or"?"or":"and"})})]}):null,d.rows.map((b,y)=>{let m=a.find((x)=>x.id===b.fieldId),h=m?Ke(m):null,f=m?co(m,r):[];return Xe("fieldset",{"aria-label":o("Condition {index}",{index:y+1}),style:{...pe.condition,margin:0,padding:0,border:0,minWidth:0},children:[re("span",{style:pe.slot,children:re(Ht,{ui:t,label:o("Filter field"),style:pe.control,value:b.fieldId,options:a.map((x)=>({value:x.id,label:x.name})),onChange:(x)=>{let w=a.find((P)=>P.id===x);if(!w)return;let S=co(w,r),I=S.includes(b.operator)?b.operator:S[0]??"",v=Ke(w)===h;u(b.key,{fieldId:x,operator:I,value:I&&!(v&&I===b.operator)?uo(w,I,r):b.value})}})}),re("span",{style:pe.slot,children:re(Ht,{ui:t,label:o("Filter operator"),style:pe.control,value:b.operator,options:f.map((x)=>({value:x,label:Fn(x,n??"en",m)})),onChange:(x)=>{if(!m)return;let w=x;u(b.key,{operator:w,value:uo(m,w,r)})}})}),m&&b.operator&&!Mt.has(b.operator)?re("span",{style:pe.slot,children:re(ba,{field:m,row:b,advanced:r,t:o,props:e,onValue:(x)=>u(b.key,{value:x})})}):null,re(Y,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:o("Remove condition {index}",{index:y+1}),title:o("Remove condition {index}",{index:y+1}),style:{flex:"0 0 auto"},onClick:()=>s({...d,rows:d.rows.filter((x)=>x.key!==b.key)})})]},b.key)}),i?d.groups.map((b,y)=>Xe("fieldset",{"aria-label":o("Condition group {index}",{index:y+1}),style:pe.group,children:[Xe("div",{style:pe.groupHead,children:[re("strong",{style:{fontSize:13},children:o("Condition group {index}",{index:y+1})}),re(Y,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:o("Remove group {index}",{index:y+1}),title:o("Remove group {index}",{index:y+1}),onClick:()=>s({...d,groups:d.groups.filter((m)=>m.key!==b.key)})})]}),re(Mn,{fields:e.fields,filter:b.node,allowGroups:!1,advanced:r,...n?{locale:n}:{},...t?{ui:t}:{},...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},onChange:(m)=>s({...d,groups:m?d.groups.map((h)=>h.key===b.key?{...h,node:m}:h):d.groups.filter((h)=>h.key!==b.key)})})]},b.key)):d.groups.length?Xe("p",{style:pe.hint,children:[o("{count} grouped conditions are kept.",{count:d.groups.length})," ",re(Y,{ui:t,variant:"ghost",size:"sm",onClick:()=>s({...d,groups:[]}),children:o("Remove")})]}):null,C?re("p",{role:"status",style:pe.hint,children:o("Finish the highlighted condition to apply it.")}):null,Xe("div",{style:pe.inline,children:[re(Y,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:a.length===0,onClick:g,children:o("Add condition")}),i?re(Y,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:a.length===0,onClick:p,children:o("Add group")}):null,d.rows.length||d.groups.length?re(Y,{ui:t,variant:"ghost",size:"sm",onClick:()=>s({rows:[],groups:[],conjunction:"and"}),children:o("Clear filter")}):null]})]})}function ba({field:e,row:t,advanced:n,t:r,props:i,onValue:o}){let{ui:a}=i,d=Ke(e),l=r("Filter value"),c=(s,u,g,p)=>i.renderCellEditor?.({...i.getRelationOptions?{getRelationOptions:i.getRelationOptions}:{},field:{...e,...p,required:!1},text:s,disabled:!1,mode:"filter",label:g,autoOpen:!1,onChange:u,onSave:()=>{},onCancel:()=>u("")});if(d==="number")return re("input",{"aria-label":l,type:"number",step:"any",style:pe.control,value:typeof t.value==="number"?String(t.value):"",onChange:(s)=>{let u=s.currentTarget.value;o(u===""||!Number.isFinite(Number(u))?void 0:Number(u))}});if(d==="text")return re("input",{"aria-label":l,style:pe.control,value:typeof t.value==="string"?t.value:"",onChange:(s)=>o(s.currentTarget.value)});if(d==="checkbox")return re(Ht,{ui:a,label:l,style:pe.control,value:t.value===!1?"false":"true",options:[{value:"true",label:r("Yes")},{value:"false",label:r("No")}],onChange:(s)=>o(s==="true")});if(d==="singleSelect"||d==="multipleSelect"){let s=Array.isArray(t.value)?t.value.join(","):typeof t.value==="string"?t.value:"",u=c(s,(p)=>o(d==="multipleSelect"?p.split(",").filter(Boolean):p),l);if(u)return u;if(d==="singleSelect")return re(Ht,{ui:a,label:l,style:pe.control,value:s,options:[{value:"",label:r("Choose option")},...(e.options??[]).map((p)=>({value:p.id,label:p.name}))],onChange:o});let g=new Set(s.split(",").filter(Boolean));return re("fieldset",{"aria-label":l,style:{...pe.inline,margin:0,padding:0,border:0},children:(e.options??[]).map((p)=>Xe("label",{style:pe.inline,children:[re("input",{type:"checkbox",checked:g.has(p.id),onChange:(C)=>{let b=new Set(g);if(C.currentTarget.checked)b.add(p.id);else b.delete(p.id);o([...b])}}),p.name]},p.id))})}if(d==="relation"){let s=typeof t.value==="string"?t.value:"";return c(s,o,l)??re(yr,{field:e,value:s,onChange:o,label:l,getOptions:i.getRelationOptions,locale:i.locale})}if(d==="date"){if(!n||typeof t.value==="string"){let s=typeof t.value==="string"?t.value:"";return c(s,o,l)??re("input",{"aria-label":l,type:"date",style:pe.control,value:s.slice(0,10),onChange:(u)=>o(u.currentTarget.value)})}return re(Ca,{field:e,value:t.value,t:r,props:i,custom:c,onValue:o})}return null}function Ca({field:e,value:t,t:n,props:r,custom:i,onValue:o}){let a=t??{mode:"today"},d=(s)=>o({...a,...s}),l=(s,u,g)=>i(u??"",(p)=>g(p.slice(0,10)),s,{formatting:{date:"YYYY-MM-DD",time:"none"}})??re("input",{"aria-label":s,type:"date",style:pe.control,value:u??"",onChange:(p)=>g(p.currentTarget.value)}),c=(s)=>{let{date:u,to:g,days:p,...C}=a;o({...C,mode:s,...cn.has(s)?{days:7}:{}})};return Xe(Pr,{children:[re(Ht,{ui:r.ui,label:n("Date mode"),style:pe.control,value:a.mode,options:qn.map((s)=>({value:s,label:Tn(s,r.locale??"en")})),onChange:(s)=>c(s)}),a.mode==="exactDate"?l(n("Filter value"),a.date,(s)=>d({date:s})):null,a.mode==="dateRange"?Xe(Pr,{children:[l(n("From date"),a.date,(s)=>d({date:s})),l(n("To date"),a.to,(s)=>d({to:s}))]}):null,cn.has(a.mode)?re("input",{"aria-label":n("Number of days"),type:"number",min:0,step:1,style:{...pe.control,width:84},value:a.days??"",onChange:(s)=>{let u=s.currentTarget.value;if(u===""){let{days:g,...p}=a;o(p)}else d({days:Number(u)})}}):null,re("span",{style:pe.hint,children:Ne(e)?.timeZone??a.timeZone??""})]})}var xr="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",pe={group:{margin:0,minWidth:0,display:"grid",gap:8,padding:10,border:`1px solid ${xr}`,borderRadius:8},groupHead:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},cell:{flex:"1 1 120px",minWidth:0,display:"flex"},condition:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},slot:{display:"flex",minWidth:0,flex:"1 1 120px"},root:{display:"grid",gap:8},row:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},inline:{display:"inline-flex",flexWrap:"wrap",alignItems:"center",gap:6},control:{width:"100%",minWidth:0,minHeight:30,padding:"0 8px",border:`1px solid ${xr}`,borderRadius:6,background:"transparent",color:"inherit",font:"inherit"},hint:{margin:0,fontSize:12,opacity:0.7}};import{jsx as me,jsxs as at,Fragment as va}from"react/jsx-runtime";var po={display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},go={minHeight:30,padding:"0 8px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit"};function kr({fields:e,view:t,onChange:n,locale:r,ui:i,editor:o}){return me("div",{"data-uibot-view-filter":"",children:me(Mn,{fields:e,filter:t.filter,locale:r,ui:i,renderCellEditor:o?.renderCellEditor,getRelationOptions:o?.getRelationOptions,advanced:o?.advanced,onChange:(a)=>{if(a)n({...t,filter:a});else{let{filter:d,...l}=t;n(l)}}})})}var ha=10;function wr({fields:e,view:t,onChange:n,locale:r,ui:i}){let o=K(r),a=t.sort??[],d=e.filter((u)=>Ct(u)),l=d.filter((u)=>!a.some((g)=>g.fieldId===u.id)),c=(u)=>{if(u.length)n({...t,sort:u});else{let{sort:g,...p}=t;n(p)}},s=(u,g)=>{let p=[...a],[C]=p.splice(u,1);if(C)p.splice(u+g,0,C);c(p)};return at("div",{"data-uibot-view-sort":"",style:{display:"grid",gap:8},children:[a.map((u,g)=>at("fieldset",{"aria-label":o("Sort {index}",{index:g+1}),style:{...po,margin:0,padding:0,border:0,minWidth:0},children:[me("span",{style:{flex:"1 1 120px",minWidth:110,display:"flex"},children:me(ke,{ui:i,label:o("Sort field"),style:go,value:u.fieldId,options:d.filter((p)=>p.id===u.fieldId||l.includes(p)).map((p)=>({value:p.id,label:p.name})),onChange:(p)=>c(a.map((C,b)=>b===g?{...C,fieldId:p}:C))})}),me("span",{style:{flex:"0 1 110px",minWidth:90,display:"flex"},children:me(ke,{ui:i,label:o("Sort direction"),style:go,value:u.direction,options:[{value:"asc",label:o("Ascending")},{value:"desc",label:o("Descending")}],onChange:(p)=>c(a.map((C,b)=>b===g?{...C,direction:p}:C))})}),me(Y,{ui:i,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:g===0,ariaLabel:o("Move sort {index} up",{index:g+1}),title:o("Move sort {index} up",{index:g+1}),onClick:()=>s(g,-1),children:" "}),me(Y,{ui:i,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:g===a.length-1,ariaLabel:o("Move sort {index} down",{index:g+1}),title:o("Move sort {index} down",{index:g+1}),onClick:()=>s(g,1),children:" "}),me(Y,{ui:i,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:o("Remove sort {index}",{index:g+1}),title:o("Remove sort {index}",{index:g+1}),onClick:()=>c(a.filter((p,C)=>C!==g)),children:" "})]},u.fieldId)),at("div",{style:po,children:[me(Y,{ui:i,variant:"outline",size:"sm",icon:"plus",disabled:l.length===0||a.length>=ha,onClick:()=>{let u=l[0];if(u)c([...a,{fieldId:u.id,direction:"asc"}])},children:o("Add sort")}),a.length?me(Y,{ui:i,variant:"ghost",size:"sm",onClick:()=>c([]),children:o("Clear sort")}):me("span",{style:{fontSize:12,opacity:0.7},children:o("Default order")})]})]})}function Rr({fields:e,view:t,onChange:n,locale:r,ui:i,bare:o}){let a=K(r),l=[...t.columnOrder.flatMap((u)=>{let g=e.find((p)=>p.id===u);return g?[g]:[]}),...e.filter((u)=>!t.columnOrder.includes(u.id))],c=(u,g)=>{let p=l.map((y)=>y.id),C=p[u],b=p[u+g];if(C===void 0||b===void 0)return;p[u]=b,p[u+g]=C,n({...t,columnOrder:p})},s=at("div",{style:{display:"grid",gap:6,paddingTop:o?0:6,minWidth:0},children:[at("label",{children:[me("input",{type:"checkbox",checked:t.showRowNumber!==!1,onChange:(u)=>n({...t,showRowNumber:u.currentTarget.checked})})," ",a("Show row numbers")]}),at("label",{children:[me("input",{type:"checkbox",checked:t.showRecordId===!0,onChange:(u)=>n({...t,showRecordId:u.currentTarget.checked})})," ",a("Show record IDs")]}),l.map((u,g)=>{let p=!t.hiddenColumns.includes(u.id),C=`${u.name}${u.required?" *":""}`;return at("div",{style:{...po,flexWrap:"nowrap",gap:4},children:[me(Y,{ui:i,variant:"ghost",size:"sm",icon:p?"eye":"eyeOff",iconOnly:!0,disabled:t.type==="form"&&u.required===!0,ariaLabel:C,title:a(p?"Hide {name}":"Show {name}",{name:u.name}),onClick:()=>n({...t,hiddenColumns:p?[...t.hiddenColumns,u.id]:t.hiddenColumns.filter((b)=>b!==u.id)})}),me("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:p?1:0.5},children:C}),me(Y,{ui:i,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:g===0,ariaLabel:a("Move {name} left",{name:u.name}),onClick:()=>c(g,-1)}),me(Y,{ui:i,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:g===l.length-1,ariaLabel:a("Move {name} right",{name:u.name}),onClick:()=>c(g,1)})]},u.id)})]});if(o)return me("div",{"data-uibot-view-columns":"",children:s});return at("details",{"data-uibot-view-columns":"",children:[me("summary",{children:a("Columns")}),s]})}function Sr({fields:e,view:t,onChange:n,locale:r,ui:i}){let o=K(r),a=e.filter((d)=>d.type==="singleSelect"||d.type==="checkbox");return me("div",{style:{display:"flex",gap:6,alignItems:"center"},children:t.groupByFieldId?at(va,{children:[me(Fe,{name:"group"}),me(ke,{ui:i,label:o("Grid grouping field"),style:go,value:t.groupByFieldId,options:a.map((d)=>({value:d.id,label:d.name})),onChange:(d)=>n({...t,groupByFieldId:d})}),me(Y,{ui:i,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:o("Remove grouping"),onClick:()=>{let d={...t};delete d.groupByFieldId,n(d)}})]}):me(Y,{ui:i,variant:"outline",size:"sm",icon:"plus",onClick:()=>{let d=a[0];if(d)n({...t,groupByFieldId:d.id})},children:o("Add grouping")})})}import{useState as rn}from"react";import{jsx as we,jsxs as mt}from"react/jsx-runtime";var an={table:{label:"Table",path:"M2.5 3.5h11v9h-11zM2.5 7h11M6.5 3.5v9"},users:{label:"People",path:"M6 7.5a2.2 2.2 0 1 0 0-4.4 2.2 2.2 0 0 0 0 4.4zM2 13c0-2.2 1.8-3.6 4-3.6s4 1.4 4 3.6M11 7a1.8 1.8 0 1 0 0-3.6M12 9.6c1.3.3 2.2 1.4 2.2 3"},briefcase:{label:"Business",path:"M2.5 5.5h11v7h-11zM6 5.5v-2h4v2M2.5 9h11"},list:{label:"List",path:"M5.5 4h8M5.5 8h8M5.5 12h8M2.5 4h.01M2.5 8h.01M2.5 12h.01"},calendar:{label:"Schedule",path:"M3 4.5h10V13H3zM3 7.5h10M6 3v3M10 3v3"},package:{label:"Inventory",path:"M8 2.5l5 2.5v6l-5 2.5L3 11V5zM3 5l5 2.5L13 5M8 7.5v6"}},Ar="table";function Nn({icon:e,size:t=15,icons:n=an}){let r=(e?n[e]:void 0)??n[Ar]??an.table;return we("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",width:t,height:t,fill:"none",stroke:"currentColor",strokeWidth:1.4,strokeLinecap:"round",strokeLinejoin:"round",style:{flex:"none"},children:we("path",{d:r?.path??""})})}function xa(e){let t=K(e.locale);return mt("aside",{"data-uibot-table-list":"",style:Dt.root,children:[mt("div",{style:Dt.title,children:[we("span",{children:t("Tables")}),we("span",{children:e.tables.length})]}),we("nav",{"aria-label":t("Tables"),style:Dt.nav,children:e.tables.map((n)=>mt("button",{type:"button","aria-current":n.id===e.activeId?"page":void 0,onClick:()=>e.onSelect(n.id),style:{...Dt.item,...n.id===e.activeId?Dt.active:{}},children:[we(Nn,{icon:n.icon,icons:e.icons??an}),we("span",{style:Dt.name,children:n.name})]},n.id))}),e.onCreate?we(Y,{ui:e.ui,variant:"ghost",style:Dt.create,disabled:e.createDisabled,onClick:e.onCreate,children:t("New table")}):null]})}function Pa(e){let t=K(e.locale),n=e.icons??an,[r,i]=rn(!1),[o,a]=rn(""),[d,l]=rn(!1),[c,s]=rn(!1),[u,g]=rn(""),p=e.table,C=e.canManage&&Boolean(p)&&!c;async function b(f){s(!0),g("");try{return await f(),!0}catch(x){return g(x instanceof Error?x.message:t("Saving failed. Your edit has been kept.")),!1}finally{s(!1)}}let y=()=>{if(!C||!e.onRename)return;a(p?.name??""),g(""),i(!0)};async function m(){let f=o.trim();if(!f||f===p?.name){i(!1);return}if(await b(()=>e.onRename?.(f)))i(!1)}let h=(f)=>{if(f.key==="Enter"||f.key==="F2")f.preventDefault(),y()};return mt("header",{"data-uibot-table-header":"",style:Je.root,children:[mt("div",{style:Je.left,children:[mt("span",{style:{position:"relative"},children:[we("button",{type:"button","aria-label":t("Change table icon"),"aria-haspopup":"menu","aria-expanded":d,title:e.canManage?t("Double click to change the icon"):t("Schema permission required"),disabled:!C||!e.onIconChange,style:Je.iconButton,onDoubleClick:()=>l(!0),onKeyDown:(f)=>{if(f.key==="Enter"||f.key===" ")f.preventDefault(),l(!0)},children:we(Nn,{icon:p?.icon,size:17,icons:n})}),d?we("div",{role:"menu","aria-label":t("Table icon"),style:Je.menu,children:Object.entries(n).map(([f,x])=>mt("button",{type:"button",role:"menuitemradio","aria-checked":(p?.icon??Ar)===f,title:x.label,style:Je.menuItem,onClick:()=>{l(!1),b(()=>e.onIconChange?.(f))},children:[we(Nn,{icon:f,icons:n}),we("span",{children:x.label})]},f))}):null]}),mt("div",{style:{minWidth:0},children:[r?we("input",{"aria-label":t("Table name"),value:o,disabled:c,style:Je.input,autoFocus:!0,onChange:(f)=>a(f.currentTarget.value),onBlur:()=>{if(!u)m()},onKeyDown:(f)=>{if(f.key==="Enter")f.preventDefault(),m();if(f.key==="Escape")f.preventDefault(),i(!1),g("")}}):we("h2",{style:Je.title,children:we("button",{type:"button","aria-label":t("Rename table {name}",{name:p?.name??""}),title:e.canManage?t("Double click to rename"):t("Schema permission required"),disabled:!C||!e.onRename,style:Je.titleButton,onDoubleClick:y,onKeyDown:h,children:p?.name??t("Start with a table")})}),u?we("p",{role:"alert",style:Je.error,children:u}):null,we("p",{style:Je.summary,children:p?t("{count} fields · {mode}",{count:p.fields.length,mode:e.canWrite?t("Editable"):t("Read only")}):t("Start with a table")})]})]}),we("div",{style:Je.actions,children:e.actions})]})}var Ir="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",Dt={root:{display:"grid",gap:8,alignContent:"start",minWidth:180},title:{display:"flex",justifyContent:"space-between",padding:"0 12px",fontSize:12,opacity:0.7},nav:{display:"grid",gap:2},item:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",border:0,borderRadius:6,background:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},active:{background:"var(--uibot-active-bg, color-mix(in srgb, currentColor 10%, transparent))",fontWeight:600},name:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},create:{justifyContent:"flex-start",width:"100%"}},Je={root:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,padding:"12px 20px"},left:{display:"flex",alignItems:"center",gap:12,minWidth:0},iconButton:{width:32,height:32,display:"grid",placeItems:"center",border:0,borderRadius:8,background:"var(--uibot-active-bg, color-mix(in srgb, currentColor 10%, transparent))",color:"inherit",cursor:"pointer"},menu:{position:"absolute",top:"100%",left:0,zIndex:60,display:"grid",minWidth:150,padding:4,border:`1px solid ${Ir}`,borderRadius:8,background:"var(--background, #fff)"},menuItem:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:0,background:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},input:{height:32,width:240,maxWidth:"100%",padding:"0 8px",border:`1px solid ${Ir}`,borderRadius:6,font:"inherit",fontWeight:600},title:{margin:0,fontSize:16,fontWeight:600},titleButton:{maxWidth:"100%",padding:0,border:0,background:"transparent",color:"inherit",font:"inherit",cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},error:{margin:"4px 0 0",fontSize:12,color:"var(--uibot-danger, #b3261e)"},summary:{margin:"2px 0 0",fontSize:12,opacity:0.7},actions:{display:"flex",alignItems:"center",gap:4}};import{useEffect as mo,useMemo as fo,useRef as Ft,useState as Kt}from"react";import{jsx as ft,jsxs as yo}from"react/jsx-runtime";function ka(e,t){if(!t)return"";let n=e.fields.find((i)=>i.id==="title")??e.fields[0],r=n?t.values[n.id]:void 0;return typeof r==="string"?r.trim():""}function wa(e){let t=fo(()=>K(e.locale),[e.locale]),n=pn(e.client,e.descriptor.id),r=Ft(null);if(r.current===null)r.current=Jt(e.descriptor.fields);let[i,o]=Kt(r.current),[a,d]=Kt(!1),l=fo(()=>({client:e.client,descriptor:e.descriptor}),[e.client,e.descriptor]),c=Ft(l);c.current=l;let s=Ft(!0);mo(()=>(s.current=!0,()=>{s.current=!1}),[]);let[u,g]=Kt(),p=fo(()=>{let N=new Map,A=(O,V)=>{if(!s.current||c.current!==l)return;g((R)=>({scope:l,targets:{...R?.scope===l?R.targets:{},[O]:V}}))};return{query:async(...O)=>{let V=O[0],R=(N.get(V)??0)+1;N.set(V,R),A(V,!1);try{let L=await e.client.query(...O);if(N.get(V)===R)A(V,L.ok);return L}catch(L){if(N.get(V)===R)A(V,!1);throw L}}}},[e.client,l]),C=e.descriptor.fields.some((N)=>N.type==="linkedRecord"&&(!N.link||u?.scope!==l||!u.targets[N.link.collectionId])),[b,y]=Kt(null),m=Ft(null),h=Ft(!1),f=Ft(null),x=Ft(null),{autoFocus:w}=e;mo(()=>{if(b?.error)x.current?.focus()},[b]);let[S,I]=Kt(!1),[v,P]=Kt(!1),T=JSON.stringify(i)!==JSON.stringify(r.current)||S;Nt({dirty:T,busy:a},e);let F=()=>f.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled])")?.focus();mo(()=>{if(w)F()},[w]);async function D(N){if(h.current||e.readOnly||C)return;P(!0);let A;try{A=nn(e.descriptor.fields,i,t,e.locale)}catch(V){y({text:V instanceof Error?V.message:t("Invalid value"),error:!0,clearable:!0});return}h.current=!0,d(!0),y(null);let O=m.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:A}]};m.current=O;try{let V=await e.client.mutate(e.descriptor.id,O);if(!n.active)return;if(!V.ok){let L=V.error.code==="validation";I(!L),y({text:V.error.message,error:!0,clearable:L});return}m.current=null,I(!1),P(!1),r.current=Jt(e.descriptor.fields),o(r.current),e.onCommitted(V.data);let R=ka(e.descriptor,V.data.items[0]);if(y({text:`${N?t("Record saved, keep adding"):t("Record saved")}${R?`:${R}`:""}`,error:!1,clearable:!1}),N)requestAnimationFrame(F);else e.onSaved?.(V.data)}catch{if(!n.active)return;I(!0),y({text:t("Saving failed. Your draft has been kept."),error:!0,clearable:!1})}finally{h.current=!1,d(!1)}}return yo("form",{ref:f,noValidate:!0,"aria-label":t("New record form"),"data-uibot":"record-creator",onSubmit:(N)=>{N.preventDefault();let A=N.nativeEvent.submitter;D(A?.getAttribute("data-continue")==="true")},onKeyDown:(N)=>{if(N.key==="Enter"&&(N.ctrlKey||N.metaKey)&&!N.nativeEvent.isComposing&&!a)N.preventDefault(),N.currentTarget.requestSubmit()},children:[ft("fieldset",{disabled:a||e.readOnly,style:et.fields,children:ft(St,{fields:e.descriptor.fields,values:i,submitted:v,relationClient:p,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},onChange:(N)=>{if(o(N),m.current=null,I(!1),b?.clearable)y(null)}})}),b?ft("p",{ref:x,role:b.error?"alert":"status",tabIndex:-1,style:b.error?et.error:et.status,children:b.text}):null,yo("div",{"data-uibot":"record-creator-actions",style:e.stickyActions?{...et.actions,...et.sticky}:et.actions,children:[yo("span",{style:et.hint,children:[ft("kbd",{children:"Ctrl / ⌘"})," + ",ft("kbd",{children:"Enter"})," ",t("Save")]}),ft("button",{type:"submit","aria-label":t("Save new record"),"aria-busy":a,disabled:a||e.readOnly||C,style:{...et.button,...Bt},children:a?t("Saving…"):t("Save new record")}),ft("button",{type:"submit","data-continue":"true",disabled:a||e.readOnly||C,style:et.button,children:t("Save and continue")}),e.onCancel&&!e.stickyActions?ft(Y,{ui:e.ui,style:et.button,disabled:a,onClick:e.onCancel,children:t("Cancel adding")}):null]})]})}var et={sticky:{position:"sticky",bottom:0,zIndex:1,padding:"12px 0",borderTop:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",background:"var(--background, white)"},fields:{margin:0,padding:0,border:0,minWidth:0},actions:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,marginTop:12},button:{padding:"6px 10px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit",cursor:"pointer"},hint:{marginRight:"auto",fontSize:12,opacity:0.7},error:{margin:"8px 0 0",fontSize:13,color:"var(--uibot-danger, #b3261e)"},status:{margin:"8px 0 0",fontSize:12,opacity:0.8}};import{useEffect as Ea,useLayoutEffect as Ma,useRef as ln}from"react";import{jsx as Wt}from"react/jsx-runtime";var Dr=[["#e8f0fe","#1a56c4"],["#e6f4ea","#1e7a3c"],["#fdecea","#b3261e"],["#fff1e0","#a05a00"],["#e8eaed","#3c4043"],["#e0f2f1","#00695c"],["#f3e8fd","#6a1b9a"]];function Tt(e){let t=Math.max(e,0)%Dr.length,[n,r]=Dr[t]??["#e8eaed","#3c4043"];return{background:`var(--uibot-chip-${t}-bg, ${n})`,color:`var(--uibot-chip-${t}-fg, ${r})`}}function Ra({index:e,children:t}){return Wt("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",...Tt(e)},children:t})}function Ln({ids:e,field:t,wrap:n}){let r=t.options??[];return Wt("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 Wt(Ra,{index:fn(r,i),children:r[o]?.name??String(i)},String(i))})})}function Bu({checked:e,label:t,onToggle:n}){return Wt("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 Fr={singleLineText:"M3 4.5h10M8 4.5v8",longText:"M3 4h10M3 8h10M3 12h6",number:"M6.5 3 5.5 13M10.5 3l-1 10M3 6h10.5M2.5 10h10.5",bigint:"M6.5 3 5.5 13M10.5 3l-1 10M3 6h10.5M2.5 10h10.5",checkbox:"M3.5 3.5h9v9h-9zM5.6 8.1l1.8 1.8 3-3.6",date:"M3 4.5h10V13H3zM3 7.5h10M6 3v3M10 3v3",singleSelect:"M8 14a6 6 0 1 0 0-12 6 6 0 0 0 0 12zM5.8 7l2.2 2.2L10.2 7",multipleSelect:"M6 4h7M6 8h7M6 12h7M3 4h.01M3 8h.01M3 12h.01",relation:"M7 9a2.5 2.5 0 0 0 3.5 0l2-2A2.5 2.5 0 0 0 9 3.5l-.7.7M9 7a2.5 2.5 0 0 0-3.5 0l-2 2A2.5 2.5 0 0 0 7 12.5l.7-.7",linkedRecord:"M7 9a2.5 2.5 0 0 0 3.5 0l2-2A2.5 2.5 0 0 0 9 3.5l-.7.7M9 7a2.5 2.5 0 0 0-3.5 0l-2 2A2.5 2.5 0 0 0 7 12.5l.7-.7",lookup:"M7 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM10 10l3.5 3.5",formula:"M10.5 3.5c-2 0-2.2 1-2.5 3L7.2 12c-.3 1.6-1 2-2.5 2M5 7.5h5",rollup:"M12 3.5H4.5L8.5 8l-4 4.5H12",json:"M6 3.5C4.5 3.5 4.5 5 4.5 6.5S4 8 3 8c1 0 1.5.5 1.5 1.5S4.5 12.5 6 12.5M10 3.5c1.5 0 1.5 1.5 1.5 3S12 8 13 8c-1 0-1.5.5-1.5 1.5s0 3-1.5 3",blob:"M4 3.5h5l3 3V12.5H4z"};function Uu({type:e}){return Wt("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:Wt("path",{d:Fr[e]??Fr.singleLineText})})}var _={root:{display:"grid",gap:12,color:"var(--uibot-schema-fg, inherit)",fontFamily:"inherit"},field:{margin:0,minWidth:0,display:"grid",gap:12,padding:16,border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:10,background:"var(--uibot-schema-bg, transparent)"},row:{display:"flex",flexWrap:"wrap",alignItems:"end",gap:12},control:{display:"grid",flex:"1 1 180px",gap:5,minWidth:140,fontSize:13},label:{color:"var(--uibot-schema-muted, color-mix(in srgb, currentColor 65%, transparent))",fontWeight:600},input:{boxSizing:"border-box",width:"100%",minHeight:"var(--uibot-schema-control-height, 36px)",padding:"7px 9px",border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"var(--uibot-schema-bg, transparent)",color:"inherit",font:"inherit"},button:{minHeight:36,padding:"7px 12px",border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"var(--uibot-schema-surface, transparent)",color:"inherit",font:"inherit",fontWeight:600,cursor:"pointer"},danger:{borderColor:"var(--uibot-schema-danger-border, color-mix(in srgb, #e5534b 45%, transparent))",background:"var(--uibot-schema-danger-bg, transparent)",color:"var(--uibot-schema-danger, #e5534b)"},checkbox:{display:"flex",alignItems:"center",gap:8,minHeight:"var(--uibot-schema-control-height, 36px)",fontSize:13},options:{display:"grid",gap:8,margin:0,minWidth:0,padding:"10px 0 0",border:0,borderTop:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))"},optionRow:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},settings:{display:"grid",gap:10,margin:0,minWidth:0,padding:"10px 0 0",border:0,borderTop:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))"},swatch:{width:18,height:18,padding:0,borderRadius:999,cursor:"pointer",flex:"none"}};import{jsx as Ce,jsxs as xe,Fragment as bo}from"react/jsx-runtime";var Sa=["YYYY-MM-DD","YYYY/MM/DD","MM/DD/YYYY","DD/MM/YYYY","YYYY年M月D日"],Ia=["Asia/Shanghai","Asia/Hong_Kong","Asia/Tokyo","Asia/Singapore","Europe/London","Europe/Paris","America/New_York","America/Los_Angeles","UTC"],Aa=["CNY","USD","EUR","JPY","GBP","HKD"],Da=[0,1,2,3,4,5,6,7,8],Fa={date:"YYYY-MM-DD",time:"none"},Ta={kind:"decimal",precision:0,grouping:!0};function Tr({field:e,onChange:t,disabled:n,locale:r,ui:i,settings:o,dateFormatLocked:a}){let d=o?.formatting!==!1,l=o?.defaults!==!1,c=K(r),s=(p)=>t((C)=>({...C,...p})),u=()=>t((p)=>{let{defaultValue:C,...b}=p;return b}),g=(p,C,b,y,m=!1)=>xe("div",{style:_.control,children:[Ce("span",{style:_.label,children:p}),Ce(ke,{ui:i,label:p,style:_.input,disabled:n||m,value:C,options:b,onChange:y})]});if(e.type==="date"){let p=Ne(e)??Fa,C=(y)=>{let{timeZone:m,...h}=p,f={...h,...m?{timeZone:m}:{},...y};if(y.timeZone==="")delete f.timeZone;s({formatting:f})},b=p.time!=="none";if(!d&&!l)return null;return xe("fieldset",{style:_.settings,"aria-label":c("Format of field {name}",{name:e.name}),children:[d?xe(bo,{children:[Ce("strong",{style:{fontSize:13},children:c("Format")}),xe("div",{style:_.row,children:[g(c("Date format"),p.date,Sa.map((y)=>({value:y,label:y})),(y)=>C({date:y}),Boolean(a)),g(c("Time format"),p.time,[{value:"none",label:c("No time (date only)")},{value:"24h",label:c("24-hour")},{value:"12h",label:c("12-hour")}],(y)=>C({time:y}),Boolean(a)),b?g(c("Time zone"),p.timeZone??"",[{value:"",label:c("Viewer's time zone")},...Ia.map((y)=>({value:y,label:y}))],(y)=>C({timeZone:y}),Boolean(a)):null]}),xe("p",{style:{..._.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[c("Preview"),": ",Lt(new Date().toISOString(),p)]})]}):null,l&&g(c("Default value"),e.defaultValue?.kind==="now"?"now":"",[{value:"",label:c("Empty")},{value:"now",label:b?c("Current date and time"):c("Today")}],(y)=>y==="now"?s({defaultValue:{kind:"now"}}):u())]})}if(e.type==="number"){let p=gn(e)??Ta,C=(y)=>s({formatting:{...p,...y}}),b=e.defaultValue?.kind==="value"?String(e.defaultValue.value):"";if(!d&&!l)return null;return xe("fieldset",{style:_.settings,"aria-label":c("Format of field {name}",{name:e.name}),children:[d?xe(bo,{children:[Ce("strong",{style:{fontSize:13},children:c("Format")}),xe("div",{style:_.row,children:[g(c("Number style"),p.kind,[{value:"decimal",label:c("Number")},{value:"percent",label:c("Percent")},{value:"currency",label:c("Currency")}],(y)=>C({kind:y})),g(c("Decimal places"),String(p.precision),Da.map((y)=>({value:String(y),label:String(y)})),(y)=>C({precision:Number(y)})),p.kind==="currency"?g(c("Currency"),p.currency??"CNY",Aa.map((y)=>({value:y,label:y})),(y)=>C({currency:y})):null]}),xe("label",{style:_.checkbox,children:[Ce("input",{type:"checkbox","aria-label":c("Thousands separator"),checked:p.grouping!==!1,disabled:n,onChange:(y)=>C({grouping:y.currentTarget.checked})}),c("Thousands separator")]}),xe("p",{style:{..._.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[c("Preview"),":"," ",mn(p.kind==="percent"?0.1234:1234.5678,p)]})]}):null,l&&xe("label",{style:_.control,children:[Ce("span",{style:_.label,children:c("Default value")}),Ce("input",{"aria-label":c("Default value"),style:_.input,type:"number",step:"any",disabled:n,value:b,onChange:(y)=>{let m=y.currentTarget.value;if(m===""||!Number.isFinite(Number(m)))u();else s({defaultValue:{kind:"value",value:Number(m)}})}})]})]})}if(!l)return null;if(e.type==="singleLineText"||e.type==="longText")return Ce("fieldset",{style:_.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:xe("label",{style:_.control,children:[Ce("span",{style:_.label,children:c("Default value")}),Ce("input",{"aria-label":c("Default value"),style:_.input,disabled:n,value:e.defaultValue?.kind==="value"?String(e.defaultValue.value):"",onChange:(p)=>{let C=p.currentTarget.value;if(C==="")u();else s({defaultValue:{kind:"value",value:C}})}})]})});if(e.type==="checkbox")return Ce("fieldset",{style:_.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:xe("label",{style:_.checkbox,children:[Ce("input",{type:"checkbox","aria-label":c("Checked by default"),checked:e.defaultValue?.kind==="value"&&e.defaultValue.value===!0,disabled:n,onChange:(p)=>p.currentTarget.checked?s({defaultValue:{kind:"value",value:!0}}):u()}),c("Checked by default")]})});if((e.type==="singleSelect"||e.type==="multipleSelect")&&(e.options?.length??0)>0){let p=e.options??[],C=e.defaultValue?.kind==="value"?e.defaultValue.value:void 0;if(e.type==="singleSelect")return Ce("fieldset",{style:_.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:g(c("Default value"),typeof C==="string"?C:"",[{value:"",label:c("Empty")},...p.map((y)=>({value:y.id,label:y.name}))],(y)=>y?s({defaultValue:{kind:"value",value:y}}):u())});let b=Array.isArray(C)?C:[];return xe("fieldset",{style:_.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:[Ce("span",{style:_.label,children:c("Default value")}),p.map((y)=>xe("label",{style:_.checkbox,children:[Ce("input",{type:"checkbox","aria-label":c("Default option {name}",{name:y.name}),checked:b.includes(y.id),disabled:n,onChange:(m)=>{let h=m.currentTarget.checked?[...b,y.id]:b.filter((f)=>f!==y.id);if(h.length)s({defaultValue:{kind:"value",value:h}});else u()}}),y.name]},y.id))]})}return null}function Er({field:e,fields:t,onChange:n,disabled:r,locale:i}){let o=K(i);if(!Un.has(e.type))return null;let a=e.ai,d=t.filter((s)=>s.id!==e.id&&s.type!=="blob"&&s.type!=="lookup"),l=a?.sourceFieldIds??[],c=(s)=>n((u)=>{if(s)return{...u,ai:s};let{ai:g,...p}=u;return p});return xe("fieldset",{style:_.settings,"aria-label":o("AI settings of field {name}",{name:e.name}),children:[xe("label",{style:_.checkbox,children:[Ce("input",{type:"checkbox",checked:Boolean(a),disabled:r,onChange:(s)=>c(s.currentTarget.checked?{prompt:""}:void 0)}),o("Generate this field with AI")]}),a?xe(bo,{children:[xe("label",{style:_.control,children:[Ce("span",{style:_.label,children:o("AI prompt")}),Ce("textarea",{"aria-label":o("AI prompt"),style:{..._.input,minHeight:72,resize:"vertical"},rows:3,maxLength:Bn,placeholder:o("e.g. Summarize the description in one sentence"),value:a.prompt,disabled:r,onChange:(s)=>{let u=s.currentTarget.value;n((g)=>({...g,ai:{...g.ai,prompt:u}}))}})]}),xe("label",{style:_.checkbox,children:[Ce("input",{type:"checkbox",checked:Boolean(a.autoFill),disabled:r,onChange:(s)=>{let u=s.currentTarget.checked;n((g)=>{let{autoFill:p,...C}=g.ai??{prompt:""};return{...g,ai:u?{...C,autoFill:!0}:C}})}}),o("Generate when a record is created")]}),Ce("span",{style:_.label,children:o("Fields the AI reads (none = all)")}),Ce("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px"},children:d.map((s)=>xe("label",{style:_.checkbox,children:[Ce("input",{type:"checkbox","aria-label":o("AI reads {name}",{name:s.name}),checked:l.includes(s.id),disabled:r,onChange:(u)=>{let g=u.currentTarget.checked;n((p)=>{let C=p.ai?.sourceFieldIds??[],b=g?[...C,s.id]:C.filter((h)=>h!==s.id),{sourceFieldIds:y,...m}=p.ai??{prompt:""};return{...p,ai:b.length?{...m,sourceFieldIds:b}:m}})}}),s.name]},s.id))})]}):null]})}import{jsx as Pe,jsxs as tt}from"react/jsx-runtime";var Na=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],Mr=(e)=>e==="singleSelect"||e==="multipleSelect";function La(e,t){let n=t.slice(0,sn);if(!n.trim()){let{description:r,...i}=e;return i}return{...e,description:n}}function Oa({fields:e,onChange:t,disabled:n=!1,focusFieldId:r,locale:i,ui:o,fieldTypes:a=Na,relationTargets:d=[],lockedFieldIds:l=[],settings:c}){let s=K(i),u={singleLineText:s("Single line text"),longText:s("Long text"),number:s("Number"),checkbox:s("Checkbox"),date:s("Date"),singleSelect:s("Single select"),multipleSelect:s("Multiple select"),relation:s("Linked record")},g=(v)=>a.includes(v.type),p=ln(new Map),C=ln(new Map),b=ln(null),y=ln(new Map),m=ln(null);function h(v,P){let T={fields:v,target:P};m.current=T,t(v),queueMicrotask(()=>{if(m.current===T)m.current=null})}Ma(()=>{let v=m.current;if(!v||v.fields!==e)return;if(m.current=null,n)return;let{target:P}=v,T=P.type==="field-name"?p.current.get(P.fieldId):P.type==="option-name"?C.current.get(`${P.fieldId}:${P.optionId}`):null;if(T){T.focus(),T.select();return}(P.type==="add-field"?b.current:P.type==="add-option"?y.current.get(P.fieldId):null)?.querySelector("button")?.focus()},[n,e]),Ea(()=>{if(!r)return;let v=window.setTimeout(()=>{let P=p.current.get(r);P?.scrollIntoView({block:"center"}),P?.focus(),P?.select()},200);return()=>window.clearTimeout(v)},[r]);let f=(v,P)=>{if(!n)t(e.map((T)=>T.id===v?P(T):T))};function x(){if(n)return;let v={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:s("New field"),type:"singleLineText"};h([...e,v],{type:"field-name",fieldId:v.id})}function w(v){if(n)return;let P=e.filter(g),T=P.findIndex((N)=>N.id===v),F=P.filter((N)=>N.id!==v),D=F[T]??F[T-1];h(e.filter((N)=>N.id!==v),D?{type:"field-name",fieldId:D.id}:{type:"add-field"})}function S(v){if(n)return;let P={id:crypto.randomUUID(),name:s("New option")};h(e.map((T)=>T.id===v.id?{...T,options:[...T.options??[],P]}:T),{type:"option-name",fieldId:v.id,optionId:P.id})}function I(v,P){if(n)return;let T=v.options??[],F=T.findIndex((A)=>A.id===P),D=T.filter((A)=>A.id!==P),N=D[F]??D[F-1];h(e.map((A)=>{if(A.id!==v.id)return A;let O=A.defaultValue;if(!(O?.kind==="value"&&(Array.isArray(O.value)?O.value.includes(P):O.value===P)))return{...A,options:D};let{defaultValue:R,...L}=A;return{...L,options:D}}),N?{type:"option-name",fieldId:v.id,optionId:N.id}:{type:"add-option",fieldId:v.id})}return tt("section",{"aria-label":s("Collection fields"),"data-uibot-schema-editor":"",style:_.root,children:[e.filter(g).map((v)=>tt("fieldset",{"aria-label":s("Field {name}",{name:v.name}),style:_.field,children:[tt("div",{style:_.row,children:[tt("label",{style:_.control,children:[Pe("span",{style:_.label,children:s("Field name")}),Pe("input",{"aria-label":s("Field name"),ref:(P)=>{if(P)p.current.set(v.id,P);else p.current.delete(v.id)},style:_.input,value:v.name,disabled:n,onChange:(P)=>{let T=P.currentTarget.value;f(v.id,(F)=>({...F,name:T}))}})]}),tt("div",{style:_.control,children:[Pe("span",{style:_.label,children:s("Field type")}),Pe(ke,{ui:o,label:s("Field type"),style:_.input,disabled:n||l.includes(v.id),value:v.type,options:a.map((P)=>({value:P,label:u[P]})),onChange:(P)=>f(v.id,(T)=>{let{options:F,relation:D,formatting:N,defaultValue:A,...O}=T;return{...O,type:P,...Mr(P)?{options:T.options??[]}:{},...P==="relation"?{relation:{collectionId:""}}:{}}})})]}),tt("label",{style:_.checkbox,children:[Pe("input",{type:"checkbox","aria-label":s("Required"),checked:Boolean(v.required),disabled:n,onChange:(P)=>{let T=P.currentTarget.checked;f(v.id,(F)=>({...F,required:T}))}}),s("Required")]}),Pe(Y,{ui:o,style:{..._.button,..._.danger},disabled:n||l.includes(v.id),icon:"trash",iconOnly:!0,ariaLabel:s("Delete field"),title:s("Delete field {name}",{name:v.name}),onClick:()=>w(v.id)})]}),c?.descriptions===!1?null:tt("label",{style:_.control,children:[Pe("span",{style:_.label,children:s("Field description")}),Pe("textarea",{"aria-label":s("Field description"),style:{..._.input,minHeight:64,resize:"vertical"},rows:2,maxLength:sn,value:v.description??"",disabled:n,onChange:(P)=>{let T=P.currentTarget.value;f(v.id,(F)=>La(F,T))}})]}),v.type==="relation"?tt("div",{style:_.control,children:[Pe("span",{style:_.label,children:s("Related table")}),Pe(ke,{ui:o,label:s("Related table"),style:_.input,disabled:n||l.includes(v.id),value:v.relation?.collectionId??"",options:[{value:"",label:s("Choose a related table")},...d.map((P)=>({value:P.id,label:P.name}))],onChange:(P)=>f(v.id,(T)=>({...T,relation:{collectionId:P}}))})]}):null,Mr(v.type)?tt("fieldset",{style:_.options,"aria-label":s("Options of field {name}",{name:v.name}),children:[Pe("strong",{style:{fontSize:13},children:s("Options")}),(v.options??[]).map((P,T)=>tt("div",{style:_.optionRow,children:[Pe("input",{"aria-label":s("Option name {index}",{index:T+1}),ref:(F)=>{let D=`${v.id}:${P.id}`;if(F)C.current.set(D,F);else C.current.delete(D)},style:{..._.input,flex:"1 1 120px",minWidth:0,width:"auto"},value:P.name,disabled:n,onChange:(F)=>{let D=F.currentTarget.value;f(v.id,(N)=>({...N,options:(N.options??[]).map((A)=>A.id===P.id?{...A,name:D}:A)}))}}),c?.optionColors===!1?null:Pe("fieldset",{"aria-label":s("Colour of option {index}",{index:T+1}),style:{display:"inline-flex",flex:"none",gap:4,margin:0,padding:0,border:0,minWidth:0},children:Et.map((F,D)=>{let N=(P.color??Et[T%Et.length])===F;return Pe("button",{type:"button","aria-label":s(`Colour ${F}`),"aria-pressed":N,disabled:n,style:{..._.swatch,background:Tt(D).color,border:N?"2px solid currentColor":"1px solid transparent"},onClick:()=>f(v.id,(A)=>({...A,options:(A.options??[]).map((O)=>O.id===P.id?{...O,color:F}:O)}))},F)})}),Pe(Y,{ui:o,style:{..._.button,..._.danger},disabled:n,icon:"trash",iconOnly:!0,ariaLabel:s("Delete option {index}",{index:T+1}),title:s("Delete option {index}",{index:T+1}),onClick:()=>I(v,P.id)})]},P.id)),Pe("div",{ref:(P)=>{if(P)y.current.set(v.id,P);else y.current.delete(v.id)},children:Pe(Y,{ui:o,style:_.button,icon:"plus",disabled:n,onClick:()=>S(v),children:s("Add option")})})]}):null,Pe(Tr,{field:v,...c?{settings:c}:{},dateFormatLocked:l.includes(v.id),disabled:n,locale:i,ui:o,onChange:(P)=>f(v.id,P)}),c?.ai?Pe(Er,{field:v,fields:e,disabled:n,locale:i,onChange:(P)=>f(v.id,P)}):null]},v.id)),Pe("div",{ref:b,children:Pe(Y,{ui:o,style:_.button,icon:"plus",disabled:n,onClick:x,children:s("Add field")})})]})}import{useEffect as Hr,useRef as Kr,useState as xo}from"react";import{useCallback as za,useEffect as _r,useLayoutEffect as ja,useRef as vo,useState as qr}from"react";import{createContext as Va,useContext as Ba,useCallback as Ua,useEffect as Nr,useId as _a,useLayoutEffect as Lr,useRef as Or,useState as Vr}from"react";import{createPortal as qa}from"react-dom";import{jsx as lt,jsxs as Ur,Fragment as Br}from"react/jsx-runtime";var $a=Va(!1),Co="uibot:collection-popover-open";function ho({label:e,trigger:t,defaultOpen:n=!1,disabled:r,menu:i,children:o}){let[a,d]=Vr(n),[l,c]=Vr({left:8,top:8}),s=Or(null),u=Or(null),g=_a();Nr(()=>{let b=(y)=>{let m=y.detail,h=s.current;if(!m||!h||m===h)return;let f=h.closest("[data-uibot-workspace]")??h.parentElement,x=m.closest("[data-uibot-workspace]")??m.parentElement;if(f===x)d(!1)};return document.addEventListener(Co,b),()=>document.removeEventListener(Co,b)},[]);let p=()=>{d(!1),s.current?.focus({preventScroll:!0})},C=Ua(()=>{if(!a)return;let b=s.current?.getBoundingClientRect(),y=u.current?.getBoundingClientRect();if(b&&y){let m={left:Math.max(8,Math.min(b.left,window.innerWidth-y.width-8)),top:Math.max(8,b.bottom+y.height+8<=window.innerHeight?b.bottom+4:b.top-y.height-4)};c((h)=>h.left===m.left&&h.top===m.top?h:m)}},[a]);return Lr(C),Lr(()=>{if(!a)return;if(s.current)document.dispatchEvent(new CustomEvent(Co,{detail:s.current}));(u.current?.querySelector("button:not(:disabled), input, select, textarea")??u.current)?.focus({preventScroll:!0})},[a]),Nr(()=>{if(!a)return;let b=(m)=>{if(m.target instanceof Node&&!u.current?.contains(m.target)&&!s.current?.contains(m.target))d(!1)},y=(m)=>{if(m.key!=="Escape")return;m.preventDefault(),m.stopPropagation(),d(!1),s.current?.focus({preventScroll:!0})};return window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),document.addEventListener("pointerdown",b),document.addEventListener("keydown",y),()=>{window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0),document.removeEventListener("pointerdown",b),document.removeEventListener("keydown",y)}},[a,C]),Ur(Br,{children:[lt("button",{ref:s,type:"button","aria-label":e,"aria-haspopup":i?"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:(b)=>b.stopPropagation(),onClick:()=>a?p():d(!0),children:t}),a&&qa(lt("div",{ref:u,id:g,role:i?"menu":"dialog","aria-label":e,tabIndex:-1,style:{position:"fixed",...l,zIndex:80,padding:i?4:12,minWidth:160,maxWidth:"calc(100vw - 16px)",maxHeight:"min(70vh, 600px)",overflow:"auto",boxSizing:"border-box",border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"var(--foreground, inherit)",fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},onKeyDown:(b)=>{if(!i||!["ArrowDown","ArrowUp","Home","End"].includes(b.key))return;b.preventDefault();let y=[...b.currentTarget.querySelectorAll('button[role="menuitem"]:not(:disabled)')],m=y.indexOf(document.activeElement),h=b.key==="Home"?0:b.key==="End"?y.length-1:(m+(b.key==="ArrowUp"?-1:1)+y.length)%y.length;y[h]?.focus()},children:o(p)}),document.body)]})}function dp({ui:e,label:t,defaultOpen:n,icon:r,chevron:i,quiet:o,active:a,children:d}){let l=Ba($a),c=(s)=>lt("div",{style:{fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},children:lt("fieldset",{disabled:l,style:{border:0,padding:0,margin:0,minWidth:0},children:s})});if(e?.Popover)return e.Popover({label:t,defaultOpen:n,...r?{icon:lt(Fe,{name:r})}:{},...i?{iconEnd:lt(Fe,{name:"chevronDown",size:13})}:{},...o?{quiet:o}:{},active:a,children:typeof d==="function"?(s)=>c(d(s)):c(d)});return lt(ho,{label:t,defaultOpen:n,trigger:Ur(Br,{children:[r?lt(Fe,{name:r}):null,t,i?lt(Fe,{name:"chevronDown",size:13}):null]}),children:(s)=>c(typeof d==="function"?d(s):d)})}import{jsx as On,jsxs as jr,Fragment as Ha}from"react/jsx-runtime";function $r({items:e,label:t,children:n,block:r=!1}){let[i,o]=qr(null),a=vo(null),d=vo(null),[l,c]=qr({x:0,y:0}),s=za(()=>{if(!i||!d.current)return;let g=Math.max(12,Math.min(i.x,window.innerWidth-12-d.current.offsetWidth)),p=Math.max(12,Math.min(i.y,window.innerHeight-12-d.current.offsetHeight));c((C)=>C.x===g&&C.y===p?C:{x:g,y:p})},[i]);ja(s),_r(()=>{if(!i)return;return window.addEventListener("resize",s),()=>window.removeEventListener("resize",s)},[i,s]);let u=vo(null);return _r(()=>{if(!i)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null,d.current?.querySelector("button:not(:disabled)")?.focus();let g=()=>o(null),p=(C)=>{if(C.key==="Escape")C.preventDefault(),C.stopPropagation(),o(null),u.current?.focus({preventScroll:!0})};return window.addEventListener("keydown",p),window.addEventListener("pointerdown",g),window.addEventListener("blur",g),()=>{window.removeEventListener("keydown",p),window.removeEventListener("pointerdown",g),window.removeEventListener("blur",g)}},[i]),jr("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 p=g.target.getBoundingClientRect();o({x:Math.max(8,Math.min(p.left,window.innerWidth-240)),y:Math.max(8,Math.min(p.bottom,window.innerHeight-280))})}},onContextMenu:(g)=>{g.preventDefault(),g.stopPropagation(),o({x:Math.max(8,Math.min(g.clientX,window.innerWidth-240)),y:Math.max(8,Math.min(g.clientY,window.innerHeight-280))})},children:[n,i&&On("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 p=[...g.currentTarget.querySelectorAll("button:not(:disabled)")],C=p.indexOf(document.activeElement);p[(C+(g.key==="ArrowUp"?-1:1)+p.length)%p.length]?.focus()},children:e.map((g)=>On("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:()=>{o(null),g.onSelect()},children:g.label},g.id))})]})}function zr({label:e,items:t,disabled:n,icon:r}){return On(ho,{label:e,disabled:n,menu:!0,trigger:r??"+",children:(i)=>On(Ha,{children:t.map((o)=>jr("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))})})}import{jsx as $e,jsxs as Wr}from"react/jsx-runtime";function Ka(e,t,n,r){if(t===n)return[...e];let i=e.filter((a)=>a!==t),o=i.indexOf(n);if(o<0||!e.includes(t))return[...e];return i.splice(r?o+1:o,0,t),i}var Wa=["grid","kanban","gallery","calendar","form"];function Ya(e,t){return{grid:e("Grid"),kanban:e("Kanban"),gallery:e("Gallery"),calendar:e("Calendar"),form:e("Form")}[t]}function Ga({slot:e,items:t,label:n,children:r}){if(!t.length)return $e("span",{children:r});if(e)return $e(e,{items:t,"aria-label":n,children:r});return $e($r,{items:t,label:n,children:r})}function Ja(e){let t=K(e.locale),[n,r]=xo(null),[i,o]=xo(""),[a,d]=xo(null),l=Kr(null),c=Kr(null),s=Boolean(e.onReorder)&&!e.disabled&&e.views.length>1,u=e.views.map((w)=>w.id),g=(w,S,I)=>{let v=Ka(u,w,S,I);if(v.join("\x00")!==u.join("\x00"))e.onReorder?.(v)};Hr(()=>{let w=l.current;if(!w)return;l.current=null,document.querySelector(`[data-view-tab="${CSS.escape(w)}"]`)?.focus()}),Hr(()=>{if(n)c.current?.select()},[n]);let p=Boolean(e.onDelete)&&e.views.length>1,C=(w)=>{if(!e.onRename||e.disabled)return;o(w.name),r(w.id)},b=()=>{if(!n)return;let w=e.views.find((I)=>I.id===n),S=i.trim();if(r(null),w&&S&&S!==w.name)e.onRename?.(w.id,S)},y=(w)=>[...e.onRename?[{id:"rename",icon:$e(Fe,{name:"pencil"}),label:t("Rename view"),onSelect:()=>C(w)}]:[],...e.onDuplicate?[{id:"duplicate",icon:$e(Fe,{name:"copy"}),label:t("Duplicate view"),onSelect:()=>e.onDuplicate?.(w.id)}]:[],...e.onDelete?[{id:"delete",icon:$e(Fe,{name:"trash"}),label:t("Delete view"),destructive:!0,disabled:!p,onSelect:()=>e.onDelete?.(w.id)}]:[]],m=(w,S)=>{let I=e.views.findIndex((v)=>v.id===S.id);if(w.altKey&&(w.key==="ArrowRight"||w.key==="ArrowLeft")){w.preventDefault();let v=e.views[I+(w.key==="ArrowRight"?1:-1)];if(s&&v)l.current=S.id,g(S.id,v.id,w.key==="ArrowRight")}else if(w.key==="F2")w.preventDefault(),C(S);else if(w.key==="Delete"&&p&&!e.disabled)w.preventDefault(),e.onDelete?.(S.id);else if(w.key==="ArrowRight"||w.key==="ArrowLeft"){w.preventDefault();let v=e.views[I+(w.key==="ArrowRight"?1:-1)];if(v)e.onSelect(v.id),w.currentTarget.parentElement?.parentElement?.querySelectorAll('[role="tab"]')?.[I+(w.key==="ArrowRight"?1:-1)]?.focus()}},h=(e.viewTypes??Wa).map((w)=>({id:w,label:Ya(t,w),disabled:e.disabledViewTypes?.includes(w)??!1,onSelect:()=>e.onAdd?.(w)})),f=e.ui?.ContextMenu,x=e.ui?.DropdownMenu;return Wr("div",{"data-uibot":"collection-view-tabs",style:{display:"flex",alignItems:"flex-end",gap:2,minWidth:0,maxWidth:"100%",overflowX:"auto"},children:[$e("div",{role:"tablist","aria-label":t("Views"),style:{display:"flex",gap:2},children:e.views.map((w)=>{let S=w.id===e.activeId,I=y(w),v=n===w.id?$e("input",{ref:c,"aria-label":t("View name"),value:i,maxLength:80,style:{height:30,padding:"0 8px",font:"inherit",border:"1px solid var(--primary, #1a56c4)",borderRadius:6,background:"var(--background, white)",color:"inherit"},onChange:(P)=>o(P.target.value),onBlur:b,onKeyDown:(P)=>{if(P.stopPropagation(),P.key==="Enter")P.preventDefault(),b();else if(P.key==="Escape")P.preventDefault(),r(null)}}):Wr("button",{type:"button",role:"tab","aria-selected":S,tabIndex:S?0:-1,disabled:e.disabled,title:e.onRename?t("Double click to rename"):void 0,"data-view-tab":w.id,draggable:s,onDragStart:(P)=>{if(!s)return;P.dataTransfer.effectAllowed="move",P.dataTransfer.setData("text/plain",w.id),d({id:w.id})},onDragOver:(P)=>{if(!a||a.id===w.id)return;P.preventDefault();let T=P.currentTarget.getBoundingClientRect(),F=(P.clientX||0)>T.left+T.width/2;if(a.over!==w.id||a.after!==F)d({id:a.id,over:w.id,after:F})},onDrop:(P)=>{if(!a)return;P.preventDefault(),g(a.id,w.id,Boolean(a.after)),d(null)},onDragEnd:()=>d(null),style:{boxShadow:a?.over===w.id?a.after?"inset -2px 0 0 var(--primary, #1a56c4)":"inset 2px 0 0 var(--primary, #1a56c4)":void 0,opacity:a?.id===w.id?0.5:1,position:"relative",display:"inline-flex",alignItems:"center",gap:6,height:34,padding:"0 12px",border:0,borderBottom:S?"2px solid var(--primary, #1a56c4)":"2px solid transparent",background:"transparent",color:S?"var(--primary, #1a56c4)":"inherit",fontWeight:S?600:400,fontSize:13,whiteSpace:"nowrap",cursor:"pointer"},onClick:()=>e.onSelect(w.id),onDoubleClick:()=>C(w),onKeyDown:(P)=>m(P,w),children:[$e("span",{children:w.name}),e.dirty&&S&&$e("span",{role:"img","aria-label":t("Unsaved changes"),style:{width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}})]});return $e(Ga,{slot:f,items:n===w.id?[]:I,label:t("View actions"),children:v},w.id)})}),e.onAdd&&(x?$e(x,{label:t("Add view"),items:h,disabled:e.disabled}):$e(zr,{label:t("Add view"),items:h,disabled:e.disabled}))]})}import{useRef as Za,useState as Qa}from"react";import{jsx as Se,jsxs as Yt}from"react/jsx-runtime";function Xa(e){let t=K(e.locale),n=e.descriptor.fields.find((l)=>l.id===e.view.groupByFieldId),r=In(e),i=Za(null),[o,a]=Qa(null);if(!n||!["singleSelect","checkbox"].includes(n.type))return Se("p",{role:"status",children:t("Choose a single-select or boolean grouping field.")});let d=qo(n,t);return Yt("section",{"data-uibot":"collection-kanban",children:[Se(qt,{...e}),Se("div",{style:{display:"flex",gap:12,overflowX:"auto",alignItems:"flex-start",paddingBottom:12},children:d.map((l)=>Se(el,{...e,field:n,lane:l,lanes:d,blocked:r.blocked,onOpen:a,onMove:(c,s)=>void r.move(c,{[n.id]:s.value}),onDrag:(c)=>{i.current=c},onDrop:(c)=>{if(i.current?.id===c)r.move(i.current,{[n.id]:l.value});i.current=null}},l.id))}),Se(An,{state:r,locale:e.locale,ui:e.ui}),o&&Se(It,{...e,row:o,onClose:()=>a(null)},o.id)]})}function el({field:e,lane:t,lanes:n,blocked:r,onOpen:i,onMove:o,onDrag:a,onDrop:d,...l}){let c=K(l.locale),s=je(l.features),u=s.optionChips,g=!l.readOnly&&s.rowUpdate,p=$t(l,zo(l.view,e,t)),C=l.descriptor.fields.find((m)=>m.type==="singleLineText"||m.type==="longText")?.id,b=Pt(l.descriptor.fields,l.view).filter((m)=>m.id!==e.id&&m.id!==C).slice(0,3),y=g&&!r&&!(e.required&&t.value===null);return Yt("section",{"aria-label":c("Lane {name}",{name:t.name}),"data-lane-id":t.id,style:{...He,flex:"0 0 290px",minWidth:0,...u?{background:"var(--muted, #f4f6f8)",padding:10}:{}},onDragOver:(m)=>{if(y)m.preventDefault()},onDrop:(m)=>{if(!y)return;m.preventDefault(),d(m.dataTransfer.getData("application/x-uibot-record"))},children:[Yt("h3",{style:u?{display:"flex",alignItems:"center",gap:6,margin:"0 0 6px",fontSize:13}:void 0,children:[u&&Se("span",{"aria-hidden":"true",style:{width:8,height:8,borderRadius:999,...t.id.startsWith("option:")?{background:Tt(nl(n,t)).color}:{background:"var(--muted-foreground, #9a9892)"}}}),t.name," · ",oo(c,p.page.total,p.page.items.length,l.locale)]}),Se(zt,{state:p,locale:l.locale,ui:l.ui,hideCount:!0}),Yt("div",{style:{display:"flex",flexDirection:"column",gap:8,marginTop:12,maxHeight:"65vh",overflowY:"auto"},children:[p.page.items.map((m)=>{let h=ze(m,l.descriptor.fields);return Yt("article",{"data-record-id":m.id,style:u?{...He,padding:10,boxShadow:"0 1px 2px rgb(0 0 0 / 0.06)",cursor:"grab",position:"relative"}:He,draggable:g&&!r&&!p.loading,onDragStart:(f)=>{a(m),f.dataTransfer.setData("application/x-uibot-record",m.id),f.dataTransfer.effectAllowed="move"},onDragEnd:()=>a(null),children:[Se("button",{type:"button",style:{...ae,width:"100%",textAlign:"left",overflowWrap:"anywhere",...u?{border:0,padding:"0 28px 0 0",background:"transparent",fontWeight:600}:{}},"aria-label":c("Open {name}",{name:h}),onClick:()=>i(m),children:h}),u&&Se(tl,{row:m,fields:b}),g&&(l.ui?.DropdownMenu?Se("span",{style:{position:"absolute",top:4,right:4},children:l.ui.DropdownMenu({label:c("Move {name}",{name:h}),icon:Se(Fe,{name:"more"}),disabled:r||p.loading,items:n.map((f)=>({id:f.id,label:c("Move to {name}",{name:f.name}),disabled:f.id===t.id||!!e.required&&f.value===null,onSelect:()=>o(m,f)}))})}):Yt("div",{style:{display:"flex",flexDirection:"column",gap:4,marginTop:8},children:[Se("span",{children:c("Move to")}),Se(ke,{ui:l.ui,label:c("Move {name}",{name:h}),style:ae,disabled:r||p.loading,value:t.id,onChange:(f)=>{let x=n.find((w)=>w.id===f);if(x&&x.id!==t.id)o(m,x)},options:n.map((f)=>({value:f.id,label:f.name,disabled:!!e.required&&f.value===null}))})]}))]},m.id)}),!p.loading&&!p.error&&!p.page.items.length&&Se("p",{children:c("No records in this lane.")})]})]})}function tl({row:e,fields:t}){let n=t.map((r)=>{let i=e.values[r.id],o=r.type==="singleSelect"||r.type==="multipleSelect",a=Array.isArray(i)?i:i==null?[]:[i],d=r.type==="linkedRecord"?Qt(e,r):hn(i,r,e.computedErrors?.[r.id]);return{field:r,chips:o,ids:a,text:d}}).filter((r)=>r.chips?r.ids.length>0:r.text!=="");if(!n.length)return null;return Se("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:6,alignItems:"center",fontSize:12,opacity:0.85},children:n.map((r)=>r.chips?Se(Ln,{ids:r.ids,field:r.field},r.field.id):Se("span",{style:{fontVariantNumeric:"tabular-nums"},children:r.text},r.field.id))})}function nl(e,t){return e.filter((n)=>n.id.startsWith("option:")).findIndex((n)=>n.id===t.id)}import{useState as ol}from"react";import{jsx as nt,jsxs as Po}from"react/jsx-runtime";function rl(e){let t=K(e.locale),n=je(e.features).optionChips,r=$t(e,bn(e.view)),[i,o]=ol(null),a=e.descriptor.fields.find((l)=>l.type==="singleLineText"||l.type==="longText")?.id,d=Pt(e.descriptor.fields,e.view).filter((l)=>!n||l.id!==a);return Po("section",{"data-uibot":"collection-gallery",children:[nt(qt,{...e}),nt(zt,{state:r,locale:e.locale,ui:e.ui}),nt("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 240px), 1fr))",gap:12,marginTop:12},children:r.page.items.map((l)=>Po("article",{"data-record-id":l.id,style:{...He,minWidth:0,...n?{boxShadow:"0 1px 2px rgb(0 0 0 / 0.05)"}:{}},children:[nt("button",{type:"button","aria-label":t("Open {name}",{name:ze(l,e.descriptor.fields)}),style:{...ae,width:"100%",textAlign:"left",overflowWrap:"anywhere",...n?{border:0,padding:0,background:"transparent",fontWeight:600,fontSize:"var(--uibot-workspace-font-size, 13px)"}:{}},onClick:()=>o(l),children:ze(l,e.descriptor.fields)}),nt("dl",{children:d.filter((c)=>!n||!il(l,c)).slice(0,n?5:d.length).map((c)=>Po("div",{children:[nt("dt",{style:{fontSize:12,opacity:0.7},children:c.name}),nt("dd",{style:{margin:"0 0 8px",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n&&(c.type==="singleSelect"||c.type==="multipleSelect")&&l.values[c.id]!=null?nt(Ln,{ids:Array.isArray(l.values[c.id])?l.values[c.id]:[l.values[c.id]],field:c}):(c.type==="linkedRecord"?Qt(l,c):hn(l.values[c.id],c,l.computedErrors?.[c.id]))||"—"})]},c.id))})]},l.id))}),!r.loading&&!r.error&&!r.page.items.length&&nt("p",{children:t("No records match this view.")}),i&&nt(It,{...e,row:i,onClose:()=>o(null)},i.id)]})}function il(e,t){let n=e.values[t.id];if(t.type==="linkedRecord")return!Qt(e,t);return n==null||n===""||Array.isArray(n)&&n.length===0}import{useRef as al,useState as ko}from"react";import{jsx as ye,jsxs as yt}from"react/jsx-runtime";function ll(e){let t=K(e.locale),n=je(e.features),r=n.optionChips,i=!e.readOnly&&n.rowUpdate,[o,a]=ko(()=>{let f=new Date().toISOString().slice(0,7),x=e.initialMonth??f;try{return Xt(x),{month:x,error:""}}catch{return{month:f,error:t("Invalid initial month. Showing the current UTC month.")}}}),{month:d,error:l}=o,[c,s]=ko(null),u=e.descriptor.fields.find((f)=>f.id===e.view.dateFieldId&&f.type==="date"),g=al(null),p=In(e),C=$t(e,u?jo(e.view,u.id,d):{limit:1},!!u),b=Xt(d),y=(f)=>{try{Xt(f),a({month:f,error:""})}catch{a((x)=>({...x,error:t("Choose a valid month between years 1 and 9998.")}))}},m=(f)=>{let x=new Date(b.start);x.setUTCMonth(x.getUTCMonth()+f),y(x.toISOString().slice(0,7))},h=(f,x)=>{if(!u)return;try{p.move(f,{[u.id]:Cn(f.values[u.id],x)})}catch(w){p.mutation.setError(w instanceof Error?w.message:t("Invalid date"))}};if(!u)return ye("p",{role:"status",children:t("Choose a date field for this calendar.")});return yt("section",{"data-uibot":"collection-calendar",children:[ye(qt,{...e}),yt("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginBottom:12},children:[ye(Y,{ui:e.ui,style:ae,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:t("Previous month"),onClick:()=>m(-1)}),e.ui?.MonthPicker?ye(e.ui.MonthPicker,{value:d,onChange:y,"aria-label":t("Calendar month")}):e.ui?.Button?ye("strong",{role:"status","aria-label":t("Calendar month"),style:{minWidth:96,textAlign:"center",fontVariantNumeric:"tabular-nums"},children:t("{year}-{month}",{year:d.slice(0,4),month:d.slice(5,7)})}):yt("label",{children:[t("Month")," ",ye("input",{type:"month","aria-label":t("Calendar month"),min:"0001-01",max:"9998-12",value:d,onChange:(f)=>y(f.target.value),style:ae})]}),ye(Y,{ui:e.ui,style:ae,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:t("Next month"),onClick:()=>m(1)}),ye(Y,{ui:e.ui,style:ae,variant:"outline",size:"sm",onClick:()=>y(new Date().toISOString().slice(0,7)),children:t("Today")})]}),l&&ye("p",{role:"alert",children:l}),ye(zt,{state:C,locale:e.locale,ui:e.ui}),ye("div",{style:{overflowX:"auto",minWidth:0},children:yt("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, minmax(0, 1fr))"},children:[[t("Sun"),t("Mon"),t("Tue"),t("Wed"),t("Thu"),t("Fri"),t("Sat")].map((f)=>ye("strong",{style:r?{padding:"8px 10px",fontSize:12,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"}:{padding:8},children:f},f)),["sun","mon","tue","wed","thu","fri","sat"].slice(0,b.weekday).map((f)=>ye("div",{"aria-hidden":"true",style:r?{borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",background:"var(--muted, #f4f6f8)",opacity:0.5}:void 0},f)),Array.from({length:b.days},(f,x)=>{let w=`${d}-${String(x+1).padStart(2,"0")}`,S=C.page.items.filter((I)=>String(I.values[u.id]??"").slice(0,10)===w);return yt("article",{"aria-label":t("Day {day}",{day:w}),"data-calendar-day":w,style:{...He,minHeight:130,maxHeight:280,overflowY:"auto",minWidth:0,borderRadius:0,...r?{padding:8,border:0,borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",fontSize:12}:{}},onDragOver:(I)=>{if(i&&!p.blocked)I.preventDefault()},onDrop:(I)=>{if(!i||p.blocked)return;if(I.preventDefault(),g.current?.id===I.dataTransfer.getData("application/x-uibot-record"))h(g.current,w);g.current=null},children:[ye("time",{dateTime:w,children:x+1}),S.map((I)=>yt("article",{"data-record-id":I.id,style:{marginTop:8},draggable:i&&!p.blocked&&!C.loading,onDragStart:(v)=>{g.current=I,v.dataTransfer.setData("application/x-uibot-record",I.id),v.dataTransfer.effectAllowed="move"},onDragEnd:()=>{g.current=null},children:[yt("button",{type:"button",style:{...ae,textAlign:"left",width:"100%",overflowWrap:"anywhere",...r?{border:0,padding:"3px 8px",fontSize:12,fontWeight:500,...Tt(0)}:{}},"aria-label":t("Open {name}",{name:ze(I,e.descriptor.fields)}),onClick:()=>s(I),children:[ze(I,e.descriptor.fields)," ",ye("small",{children:String(I.values[u.id]).slice(11,16)})]}),i&&ye(sl,{ui:e.ui,t,row:I,fieldId:u.id,title:ze(I,e.descriptor.fields),disabled:p.blocked||C.loading,onMove:h})]},I.id))]},w)})]})}),!C.loading&&!C.error&&!C.page.items.length&&ye("p",{children:t("No dated records match this month.")}),ye(An,{state:p,locale:e.locale,ui:e.ui}),!p.intent&&p.mutation.error&&ye("p",{role:"alert",children:p.mutation.error}),c&&ye(It,{...e,row:c,onClose:()=>s(null)},c.id)]})}function sl({ui:e,t,row:n,fieldId:r,title:i,disabled:o,onMove:a}){let[d,l]=ko({day:String(n.values[r]).slice(0,10)}),c=e?.DateMove;if(c)return ye(c,{label:t("Move {name} to date",{name:i}),value:d.day,disabled:o,onPick:(s)=>a(d.baseline??n,s)});return yt("div",{style:{marginTop:4,display:"flex",gap:4,flexWrap:"wrap"},children:[ye("input",{type:"date","aria-label":t("Move {name} to date",{name:i}),value:d.day,disabled:o,style:{width:"100%",minWidth:0},onChange:(s)=>l({day:s.target.value,baseline:d.baseline??n})}),ye("button",{type:"button",style:ae,"aria-label":t("Move {name}",{name:i}),disabled:o||!d.day,onClick:()=>a(d.baseline??n,d.day),children:t("Move")})]})}import{jsx as st,jsxs as Gt}from"react/jsx-runtime";function og({fields:e,view:t,onChange:n,locale:r,ui:i,features:o,sections:a,filterEditor:d,grouping:l,rowHeight:c}){let s=K(r),u=je(o),g=e.filter((h)=>h.type==="singleSelect"||h.type==="checkbox"),p=e.filter((h)=>h.type==="date"),C=(h)=>{let f={...t,type:h};if(delete f.groupByFieldId,delete f.dateFieldId,h==="kanban"&&g[0])f.groupByFieldId=g[0].id;if(h==="calendar"&&p[0])f.dateFieldId=p[0].id;if(h==="form")f.hiddenColumns=f.hiddenColumns.filter((x)=>!e.find((w)=>w.id===x)?.required);n(f)},b={grid:s("Grid"),kanban:s("Kanban"),gallery:s("Gallery"),calendar:s("Calendar"),form:s("Form")},y=u.viewTypes.map((h)=>({value:h,label:b[h],disabled:h==="kanban"&&!g.length||h==="calendar"&&!p.length})),m=t.type??"grid";return Gt("div",{style:{display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},children:[Gt("div",{children:[s("View type")," ",st(ke,{ui:i,label:s("View type"),style:ae,value:m,options:y,onChange:(h)=>C(h)})]}),m==="grid"&&u.groupBy&&g.length>0&&l!==!1&&st("div",{style:{flexBasis:"100%"},children:st(Sr,{fields:e,view:t,onChange:n,locale:r,ui:i})}),m==="grid"&&c!==!1&&Gt("div",{children:[s("Row height")," ",st(ke,{ui:i,label:s("Row height"),style:ae,value:t.rowHeight??"short",options:Ao.map((h)=>({value:h,label:s(`Row height ${h}`)})),onChange:(h)=>{let f={...t};if(h==="short")delete f.rowHeight;else f.rowHeight=h;n(f)}})]}),m==="kanban"&&Gt("div",{children:[s("Group by")," ",st(ke,{ui:i,label:s("Kanban grouping field"),style:ae,value:t.groupByFieldId??"",options:g.map((h)=>({value:h.id,label:h.name})),onChange:(h)=>n({...t,groupByFieldId:h})})]}),m==="calendar"&&Gt("div",{children:[s("Date field")," ",st(ke,{ui:i,label:s("Calendar date field"),style:ae,value:t.dateFieldId??"",options:p.map((h)=>({value:h.id,label:h.name})),onChange:(h)=>n({...t,dateFieldId:h})})]}),(a?.filter||a?.columns||a?.sort)&&Gt("div",{style:{display:"grid",gap:12,flexBasis:"100%"},children:[a?.filter&&st(kr,{fields:e,view:t,onChange:n,locale:r,ui:i,editor:d}),a?.columns&&st(Rr,{fields:e,view:t,onChange:n,locale:r,ui:i}),a?.sort&&st(wr,{fields:e,view:t,onChange:n,locale:r,ui:i})]})]})}export{Xi as CollectionAggregateRows,eo as CollectionAggregateSummary,ll as CollectionCalendar,aa as CollectionForm,rl as CollectionGallery,Xa as CollectionKanban,It as CollectionRecordEditor,og as CollectionViewSettings,Ja as CollectionViewTabs,an as PAGED_TABLE_ICONS,Mn as PagedCollectionFilterBuilder,wa as PagedCollectionRecordCreator,Oa as PagedCollectionSchemaEditor,Pa as PagedCollectionTableHeader,xa as PagedCollectionTableList,Nn as PagedTableIcon,Tn as dateModeLabel,Fn as filterOperatorLabel,br as pagedFilterSummary};
|