@uibot/renderer-react 0.7.0 → 0.9.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 +11 -11
- package/dist/collection-editors.js +10 -10
- package/dist/collection-grid/hyperlink.d.ts +38 -0
- package/dist/collection-grid/paged-model.d.ts +1 -1
- package/dist/collection-views/field-config.d.ts +3 -1
- package/dist/collection-views/field-editor-popover.d.ts +15 -0
- package/dist/collection-views/model.d.ts +1 -1
- package/dist/collection-views/schema-editor.d.ts +10 -2
- package/dist/collection-views.js +10 -10
- package/dist/collection-workspace.d.ts +6 -1
- package/dist/collection-workspace.js +13 -13
- package/dist/index.js +12 -12
- package/dist/paged-collection-grid.d.ts +3 -0
- package/dist/paged-collection-grid.js +12 -12
- package/package.json +4 -4
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{useId as sr,useState as bt}from"react";function ur(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var xt=["blue","green","red","orange","gray","teal","purple"];function an(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 Ct(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 o=n.find((d)=>d.id===i.fieldId),s=o?.type==="number"||o?.type==="rating"||o?.type==="autoNumber"?e.reduce((d,a)=>d+(an(a.values[i.fieldId])??0),0):0;return{fieldId:i.fieldId,fn:"sum",value:s}})}function ht(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function sn(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function ln(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 vt(e,t){if(!t)return!0;if(ht(t)){let n=t.filterSet.map((i)=>ht(i)?vt(e,i):sn(i)?ln(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 kt(e,t,n,i){let o=e.views.find((P)=>P.id===n)??e.views[0];if(!o)return{view:{id:n,name:n,kind:"table"},columns:e.fields,rows:[...t]};let r=[...t];if(o.filter)r=r.filter((P)=>vt(P,o.filter));if(o.sort?.length)r.sort((P,w)=>{for(let A of o.sort??[]){let D=P.values[A.fieldId],g=w.values[A.fieldId];if(D===g)continue;if(D==null)return 1;if(g==null)return-1;let x=e.fields.find((U)=>U.id===A.fieldId)?.type,C=(U)=>{if(["number","rating","autoNumber"].includes(x??"")&&typeof U==="number")return U;if(["date","createdTime","lastModifiedTime"].includes(x??"")){let I=Date.parse(String(U));if(Number.isFinite(I))return I}return String(U)},f=C(D),_=C(g);if(f===_)continue;let T=f<_?-1:1;return A.direction==="desc"?-T:T}return P.id<w.id?-1:P.id===w.id?0:1});let s=o.projection?.length?e.fields.filter((P)=>o.projection?.includes(P.id)):e.fields,d=i?.search?.trim().toLowerCase();if(d)r=r.filter((P)=>s.some((w)=>String(P.values[w.id]??"").toLowerCase().includes(d)));let a=Ct(r,o.aggregates,e.fields),m=o.group?.fieldId;if(!m)return{view:o,columns:s,rows:r,...a.length?{aggregates:a}:{}};let p=[],c=new Map;for(let P of r){let w=String(P.values[m]??"");if(!c.has(w))c.set(w,[]),p.push(w);c.get(w)?.push(P)}let y=p.map((P)=>{let w=c.get(P)??[];return{key:P,fieldId:m,rows:w,aggregates:Ct(w,o.aggregates,e.fields)}});return{view:o,columns:s,rows:r,groups:y,...a.length?{aggregates:a}:{}}}var cn=500,dn=2000,un=new Set(["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"]);function ke(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function Ge(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 vr=["short","medium","tall","extra"];function kr(e,t){return t.map((n)=>{let i={},o={};for(let r of e.groupBy){let s=n[r];if(!(r in n)||s!==null&&typeof s!=="string"&&typeof s!=="number"&&typeof s!=="boolean")throw Error(`Invalid aggregate group ${r}.`);i[r]=s}for(let{as:r,fn:s}of e.aggregates){let d=n[r];if(!(r in n)||d!==null&&!(typeof d==="number"&&Number.isFinite(d))&&!((s==="min"||s==="max")&&typeof d==="string"&&Number.isFinite(Date.parse(d))))throw Error(`Invalid aggregate value ${r}.`);o[r]=d}return{groups:i,values:o}})}var pn=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,gn=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function Pr(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function Ce(e,t){return{code:e,...t}}function mn(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function st(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function wr(e,t){if(t.aggregates.length===0)return Ce("empty");if(t.aggregates.length>8||t.groupBy.length>3)return Ce("too_many");let n=new Set;for(let o of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(o.fn))return Ce("function");if(!pn.test(o.as)||n.has(o.as)||t.groupBy.includes(o.as))return Ce("alias",{alias:o.as,...o.fieldId!==void 0?{fieldId:o.fieldId}:{}});if(n.add(o.as),o.fn==="count"&&o.fieldId===void 0)continue;let r=e.fields.find((s)=>s.id===o.fieldId);if(!r)return Ce(o.fn==="sum"?"sum_field":"unknown_field",{alias:o.as,...o.fieldId!==void 0?{fieldId:o.fieldId}:{}});if(o.fn==="sum"&&!st(r))return Ce("sum_field",{fieldId:r.id,alias:o.as});if(o.fn==="avg"&&!st(r))return Ce("numeric_field",{fieldId:r.id,alias:o.as});if((o.fn==="min"||o.fn==="max")&&!st(r)&&r.type!=="date"&&!((r.type==="formula"||r.type==="rollup")&&r.resultType==="date"))return Ce("extrema_field",{fieldId:r.id,alias:o.as});if((o.fn==="filled"||o.fn==="empty")&&!Ge(r))return Ce("queryable_field",{fieldId:r.id,alias:o.as});if(o.fn==="count"&&!Ge(r))return Ce("count_field",{fieldId:r.id,alias:o.as})}let i=new Set;for(let o of t.groupBy){if(i.has(o))return Ce("duplicate_group",{fieldId:o});i.add(o);let r=e.fields.find((s)=>s.id===o);if(!r)return Ce("unknown_field",{fieldId:o});if(!gn.has(r.type)&&!mn(r))return Ce("not_groupable",{fieldId:o})}return null}var Pt=(e)=>String(e).padStart(2,"0");function Se(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=(o)=>Number(n.find((r)=>r.type===o)?.value??0);return{year:i("year"),month:i("month"),day:i("day"),hour:i("hour"),minute:i("minute"),second:i("second")}}function _e(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 o=0;o<2;o++){let r=Se(new Date(i),t),s=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second);i+=n-s}return new Date(i)}function Xe(e,t){let n=Se(e,t??"UTC");return`${n.year}-${Pt(n.month)}-${Pt(n.day)}`}function Dr(e,t=new Date,n){let i={};for(let o of e){let r=o.defaultValue;if(!r)continue;if(r.kind==="value")i[o.id]=Array.isArray(r.value)?[...r.value]:r.value;else if(o.type==="date"){let s=o.formatting;if(s&&"time"in s&&s.time==="none"){let d=Se(t,n);i[o.id]=`${d.year}-${String(d.month).padStart(2,"0")}-${String(d.day).padStart(2,"0")}`}else i[o.id]=t.toISOString()}}return i}var fn=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],yn=new Set(["pastDays","nextDays","daysAgo","daysFromNow"]),wt={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"]},bn=new Set(["isEmpty","isNotEmpty"]);function Rt(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 Fr(e){let t=Rt(e);return t?wt[t]:[]}var lt=/^\d{4}-\d{2}-\d{2}$/,Cn=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function hn(e){if(!Cn(e))return!1;let t=e.mode;if(!fn.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&<.test(e.date);if(t==="dateRange")return typeof e.date==="string"&<.test(e.date)&&typeof e.to==="string"&<.test(e.to)&&e.date<=e.to;if(yn.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function Nr(e,t){if(!e)return"unknown field";let n=Rt(e),i=t.operator==="contains"&&(n==="number"||n==="checkbox"||n==="date"||n==="singleSelect");if(!n||!(wt[n].includes(t.operator)||i))return"operator not allowed";if(bn.has(t.operator))return null;let o=t.value;if(i)return n==="number"?typeof o==="number"&&Number.isFinite(o)?null:"number required":n==="checkbox"?typeof o==="boolean"?null:"boolean required":typeof o==="string"?null:"text required";switch(n){case"text":return typeof o==="string"?null:"text value required";case"number":return typeof o==="number"&&Number.isFinite(o)?null:"number required";case"checkbox":return typeof o==="boolean"?null:"boolean required";case"singleSelect":return typeof o==="string"?null:"option required";case"relation":return typeof o==="string"&&o!==""?null:"record required";case"multipleSelect":return typeof o==="string"||Array.isArray(o)&&o.every((r)=>typeof r==="string")?null:"options required";case"date":return hn(o)||typeof o==="string"&&Number.isFinite(Date.parse(o))?null:"date required"}}var xn={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},no=Array.from(new Set(Object.values(xn).flat()));var io=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 vn(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function uo(e,t){if(t===e.draft)return e;return{...e,draft:t}}function kn(e){return e.draft!==e.savedContent}function po(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 go(e,t){if(kn(e))return e;let n=vn(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 De=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),Be=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),Ue=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,It=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,et=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),St=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every(et)&&new Set(e).size===e.length;function Pn(e){if(!De(e)||!Be(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!et(e.id)||!Ue(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)=>!De(t)||!Be(t,["id","name"])||!et(t.id)||!Ue(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 o=e[n];if(e.type===t!==(o!==void 0))return!1;if(o!==void 0&&(!De(o)||!Be(o,[...i])||i.some((r)=>!Ue(o[r],r==="expression"?2048:512))))return!1}return!0}function fo(e){if(!De(e)||!Be(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))||!Ue(e.collectionId,512)||!Ue(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(!De(t)||!Be(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!Ue(t.name,200)||!It(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(Pn)||new Set(t.fields.map((r)=>r.id)).size!==t.fields.length)return!1;if(!De(n)||!Be(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!et(n.id)||!Ue(n.name,200)||!It(n.version)||!St(n.columnOrder)||!St(n.hiddenColumns)||!De(n.columnWidths)||Object.values(n.columnWidths).some((r)=>typeof r!=="number"||!Number.isInteger(r)||r<72||r>800))return!1;let i=t.fields,o=(r)=>i.some((s)=>De(s)&&s.id===r);if([...n.columnOrder,...n.hiddenColumns,...Object.keys(n.columnWidths)].some((r)=>!o(r)))return!1;if(n.type!==void 0&&!["grid","kanban","gallery","calendar","form"].includes(String(n.type)))return!1;if(n.type==="kanban"&&!t.fields.some((r)=>r.id===n.groupByFieldId&&["singleSelect","checkbox"].includes(r.type)))return!1;if(n.type==="calendar"&&!t.fields.some((r)=>r.id===n.dateFieldId&&r.type==="date"))return!1;if(n.search!==void 0&&(typeof n.search!=="string"||n.search.length>200))return!1;if(n.sort!==void 0&&(!Array.isArray(n.sort)||n.sort.length>4||n.sort.some((r)=>!De(r)||!Be(r,["fieldId","direction"])||!o(r.fieldId)||!["asc","desc"].includes(String(r.direction)))))return!1;return!0}var we=(e)=>String(e).padStart(2,"0"),wn=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function qe(e){let t=e.formatting;return wn(e)&&t&&"date"in t?t:void 0}function At(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function Dt(e){let t=qe(e);return!t?"auto":t.time==="none"?"date":"datetime"}function ct(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 Et(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 ct(Number(i[1]),Number(i[2]),Number(i[3]),t.date);let d=new Date(n);if(!Number.isFinite(d.getTime()))return n;let a=Se(d,t.timeZone??"UTC");return ct(a.year,a.month,a.day,t.date)}let o=i?_e({year:Number(i[1]),month:Number(i[2]),day:Number(i[3])},t.timeZone):new Date(n);if(!Number.isFinite(o.getTime()))return n;let r=Se(o,t.timeZone),s=ct(r.year,r.month,r.day,t.date);if(t.time==="12h"){let d=r.hour%12||12;return`${s} ${d}:${we(r.minute)} ${r.hour<12?"AM":"PM"}`}return`${s} ${we(r.hour)}:${we(r.minute)}`}function Tt(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 Ft(e,t){let n=e?.findIndex((r)=>r.id===t)??-1,i=n>=0?e?.[n]?.color:void 0,o=xt.findIndex((r)=>r===i);return o>=0?o:n}var Rn={"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 Pe(e="en"){return(t,n={})=>(e==="zh-CN"?Rn[t]??t:t).replace(/\{(\w+)\}/g,(i,o)=>String(n[o]??i))}function bi(e,t,n,i,o=!1){let{row:r,column:s}=e;if(t==="ArrowUp")r--;if(t==="ArrowDown")r++;if(t==="ArrowLeft")s--;if(t==="ArrowRight")s++;if(t==="Home")s=0;if(t==="End")s=i-1;if(t==="Tab"){let d=Math.max(0,Math.min(n*i-1,r*i+s+(o?-1:1)));r=Math.floor(d/i),s=d%i}return{row:Math.max(0,Math.min(n-1,r)),column:Math.max(0,Math.min(i-1,s))}}function In(e,t){return{firstRow:Math.min(e.row,t.row),lastRow:Math.max(e.row,t.row),firstColumn:Math.min(e.column,t.column),lastColumn:Math.max(e.column,t.column)}}function Re(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function Ci(e,t,n,i){let o=In(n,i),r=[];for(let s=o.firstRow;s<=o.lastRow;s++){let d=[];for(let a=o.firstColumn;a<=o.lastColumn;a++){let m=t[a],p=e[s]?.values[m?.id??""],c=m?.type==="json"&&p!=null?JSON.stringify(p):Re(p);d.push(/[\t\r\n"]/.test(c)?`"${c.replaceAll('"','""')}"`:c)}r.push(d.join("\t"))}return r.join(`
|
|
2
|
-
`)}function
|
|
3
|
-
`||
|
|
4
|
-
`)d++}}else r+=a}if(s)throw Error(n("Unclosed quoted cell."));if(r||o.length||i.length===0)o.push(r),i.push(o);return i}function Fe(e,t,n="en"){let i=Pe(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 r=Number(e);if(!e.trim()||!Number.isFinite(r))throw Error(i("{name} needs a number.",{name:t.name}));return r}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 r=qe(t);if(r){let _=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!_)throw Error(i("{name} needs a date.",{name:t.name}));let[,T,U,I]=_,M=new Date(Date.UTC(Number(T),Number(U)-1,Number(I)));if(M.getUTCMonth()!==Number(U)-1||M.getUTCDate()!==Number(I))throw Error(i("{name} needs a valid calendar date.",{name:t.name}));if(r.time==="none"){if(/T.*(?:Z|[+-]\d{2}:\d{2})$/i.test(e)&&Number.isFinite(Date.parse(e)))return Xe(new Date(e),r.timeZone);return`${T}-${U}-${I}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return _e({year:Number(T),month:Number(U),day:Number(I)},r.timeZone).toISOString()}let s=/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-](\d{2}):(\d{2})))?$/i.exec(e);if(!s)throw Error(i("{name} needs a date.",{name:t.name}));let[,d,a,m,p,c,y,P,w]=s,A=Number(d),D=Number(a),g=Number(m),C=[31,A%4===0&&(A%100!==0||A%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(D<1||D>12||g<1||g>(C[D-1]??0)||Number(p??0)>23||Number(c??0)>59||Number(y??0)>59||Number(P??0)>23||Number(w??0)>59)throw Error(i("{name} needs a valid calendar date.",{name:t.name}));let f=new Date(e);if(!Number.isFinite(f.getTime()))throw Error(i("{name} needs a date.",{name:t.name}));return f.toISOString()}let o=(r)=>{let s=t.options?.find((d)=>d.id===r||d.name===r);if(!s)throw Error(i("{name} has no option '{option}'.",{name:t.name,option:r}));return s.id};if(t.type==="singleSelect")return o(e);if(t.type==="multipleSelect")return[...new Set(e.split(",").map((r)=>o(r.trim())))];return e}function hi(e,t,n,i,o="en"){let r=Pe(o);try{if(e.length>1048576)throw Error(r("Paste is too large."));let s=Sn(e,o);if(s.length>100||i.row+s.length>t.length)throw Error(r("Paste must fit within the loaded page and contain at most 100 rows."));return{ok:!0,items:s.map((a,m)=>{if(i.column+a.length>n.length)throw Error(r("Paste extends beyond the visible columns."));let p=t[i.row+m];if(!p)throw Error(r("Row is not loaded."));let c={};return a.forEach((y,P)=>{let w=n[i.column+P];if(w?.generation==="autoIncrement")throw Error(r("{name} is auto-generated and cannot be edited.",{name:w.name}));if(w)c[w.id]=Fe(y,w,o)}),{op:"update",id:p.id,expectedVersion:p.version,values:c}})}}catch(s){return{ok:!1,message:s instanceof Error?s.message:r("Invalid paste.")}}}function Nt(e,t){let n=Re(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 o=new Intl.DateTimeFormat("en-CA",{...t?{timeZone:t}:{},year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(i),r=(m)=>o.find((p)=>p.type===m)?.value??"",s=i.getUTCMilliseconds(),d=r("second"),a=d!=="00"||s?`:${d}${s?`.${String(s).padStart(3,"0")}`:""}`:"";return`${r("year")}-${r("month")}-${r("day")} ${r("hour")}:${r("minute")}${a}`}import{useEffect as An,useRef as Dn,useState as Ke}from"react";import{jsx as Ie,jsxs as Je}from"react/jsx-runtime";function He(e){if(e==null)return"—";if(Array.isArray(e))return e.map(He).join(", ");return String(e)}function wi(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((i)=>i.label||i.id).join(", "):void 0)??He(e.values[t.id])}function Ri(e,t){return Re(e.values[t.id])}function Mt({field:e,value:t,labels:n=[],client:i,onChange:o,disabled:r=!1,locale:s,"aria-describedby":d,"aria-invalid":a}){let m=Pe(s),p=Array.isArray(t)?t.filter((R)=>typeof R==="string"):[],c=Dn(new Set(p));c.current=new Set(p);let[y,P]=Ke(""),[w,A]=Ke(),[D,g]=Ke([]),[x,C]=Ke(0),[f,_]=Ke({}),[T,U]=Ke({rows:[],next:null,error:"",loading:!0}),I=e.link?.collectionId,M=e.link?.displayFieldId;An(()=>{let R=!0;if(U({rows:[],next:null,error:"",loading:!0}),!i||!I||!M){U({rows:[],next:null,error:m("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return i.query(I,{limit:50,search:y,...w?{cursor:w}:{}}).then((h)=>{if(!R)return;if(!h.ok){U({rows:[],next:null,error:h.error.message,loading:!1});return}_((K)=>({...Object.fromEntries(Object.entries(K).filter(([k])=>c.current.has(k))),...Object.fromEntries(h.data.items.map((k)=>{let q=String(k.values[M]??"");return[k.id,q.trim()?q.slice(0,256):k.id]}))})),U({rows:h.data.items,next:h.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(R)U({rows:[],next:null,error:m("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{R=!1}},[i,I,M,y,w,x]);let L=(R)=>f[R]??n.find((h)=>h.id===R)?.label??R;return Je("fieldset",{disabled:r,"aria-label":m("{name} linked records",{name:e.name}),...d?{"aria-describedby":d}:{},...a?{"aria-invalid":!0}:{},className:"flex min-w-0 flex-col gap-2 rounded-md border p-2",children:[Ie("div",{className:"flex flex-wrap gap-1",children:p.map((R)=>Je("span",{className:"rounded border px-2 py-1 text-sm",children:[L(R)," ",Ie("button",{type:"button","aria-label":m("Remove {name}",{name:L(R)}),onClick:()=>o(p.filter((h)=>h!==R)),children:"×"})]},R))}),Ie("input",{"aria-label":m("Search {name} records",{name:e.name}),type:"search",placeholder:m("Search linked records"),value:y,onChange:(R)=>{P(R.target.value),A(void 0),g([])}}),T.loading&&Ie("p",{role:"status",children:m("Loading linked records…")}),T.error&&Je("div",{role:"alert",children:[T.error," ",Ie("button",{type:"button",onClick:()=>C((R)=>R+1),children:m("Retry linked records")})]}),Ie("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:T.rows.map((R)=>Je("label",{className:"flex items-center gap-2 text-sm",children:[Ie("input",{type:"checkbox","aria-label":m("Link {name}",{name:L(R.id)}),checked:p.includes(R.id),disabled:!p.includes(R.id)&&p.length>=100,onChange:(h)=>o(h.target.checked?[...p,R.id]:p.filter((K)=>K!==R.id))}),L(R.id)]},R.id))}),!T.loading&&!T.error&&!T.rows.length&&Ie("p",{children:m("No matching records.")}),Je("div",{className:"flex gap-2",children:[Ie("button",{type:"button",disabled:!D.length||T.loading,onClick:()=>{A(D.at(-1)),g((R)=>R.slice(0,-1))},children:m("Previous linked records")}),Ie("button",{type:"button",disabled:!T.next||T.loading,onClick:()=>{g((R)=>[...R,w]),A(T.next??void 0)},children:m("Next linked records")})]}),Ie("small",{children:m("{count} selected · up to 100 per record across all link fields",{count:p.length})})]})}var En={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function tt(e,t,n){return t?Pe(n)(En[t]):e==null?"—":String(e)}function Mi(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 Ot(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function Lt(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function Oi(e,t,n){let i=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...Lt(e),filter:Ot(e.filter,i)}}function Tn(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 o=new Date(`${e}-01T00:00:00.000Z`),r=new Date(o);return r.setUTCMonth(r.getUTCMonth()+1),{start:o.toISOString(),end:r.toISOString(),days:Math.round((r.getTime()-o.getTime())/86400000),weekday:o.getUTCDay()}}function Li(e,t,n){let{start:i,end:o}=Tn(n);return{...Lt(e),filter:Ot(e.filter,{fieldId:t,operator:"onOrAfter",value:i},{fieldId:t,operator:"before",value:o})}}function Vt(e,t){let n={id:"date",name:"Date",type:"date"},i=String(Fe(t,n)),o=String(Fe(String(e),n));return`${i.slice(0,10)}${o.slice(10)}`}function Vi(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((o)=>o.id===i))}function _i(e,t){let n=t.find((i)=>i.type==="singleLineText"||i.type==="longText");return(n?Re(e.values[n.id]):"")||e.id}function Bi(e,t,n){if(t.type==="lookup")return He(e);if(t.type==="date"){let i=qe(t);return i?Et(e,i):Nt(e)}if(t.type==="number"){let i=At(t);return i?Tt(e,i):Re(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return tt(e,n);if(t.type==="singleSelect"||t.type==="multipleSelect")return(Array.isArray(e)?e:e==null?[]:[e]).map((o)=>t.options?.find((r)=>r.id===o)?.name??String(o)).join(", ");return Re(e)}import{useEffect as qt,useId as Nn,useMemo as Mn,useRef as On,useState as $t}from"react";var Fn=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function Ne(e){return Fn.test(e)}var Ee=(e)=>String(e).padStart(2,"0");function _t(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${Ee(t.getMonth()+1)}-${Ee(t.getDate())}T${Ee(t.getHours())}:${Ee(t.getMinutes())}:${Ee(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var dt=(e,t)=>{let n=Se(e,t);return`${n.year}-${Ee(n.month)}-${Ee(n.day)}T${Ee(n.hour)}:${Ee(n.minute)}`};function Bt(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!Ne(e))return e.slice(0,10);return dt(new Date(e),t.timeZone??"UTC").slice(0,10)}if(Ne(e))return dt(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function Ut(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||Ne(t)))return e;let o=e.length>10?e.slice(11,16):t&&Ne(t)?dt(new Date(t),n.timeZone).slice(11,16):"00:00",[r,s,d]=e.slice(0,10).split("-").map(Number),[a,m]=o.split(":").map(Number),p=_e({year:r??0,month:s??1,day:d??1,hour:a??0,minute:m??0},n.timeZone);return Number.isFinite(p.getTime())?p.toISOString():e}import{jsx as $e,jsxs as jt}from"react/jsx-runtime";function ut(e,t,n){if(e.type==="blob")return"";try{return Fe(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 Yi({field:e,text:t,disabled:n,id:i,label:o,ariaLabel:r,onChange:s,onSave:d,onCancel:a,locale:m="en",submitted:p=!1,describedBy:c}){let y=Mn(()=>Pe(m),[m]),P=Nn(),w=On(null),A=Boolean(d);qt(()=>{if(A)w.current?.querySelector("input,textarea,select")?.focus()},[A]);let D=i??P,g=`${D}-error`,[x,C]=$t(t),[f,_]=$t(!1);qt(()=>C(t),[t]);let T=ut(e,x,m),I=Boolean(e.required&&x===""&&T)&&!f&&!p?"":T,M=r??o??e.name,L=e.type==="date"&&Ne(x),R=L&&!T?_t(x):x,h=[c,I?g:void 0].filter(Boolean).join(" "),K={id:D,"aria-label":M,"aria-invalid":Boolean(I),...h?{"aria-describedby":h}:{},disabled:n,onBlur:()=>_(!0),onKeyDown:(u)=>{if(d||a)u.stopPropagation();let F=e.type==="longText"||e.type==="json";if(u.key==="Tab"&&d)u.preventDefault(),d(u.shiftKey?"previous":"next");else if(u.key==="Enter"&&!u.shiftKey&&d&&(!F||u.ctrlKey||u.metaKey))u.preventDefault(),d();else if(u.key==="Escape"&&a)u.preventDefault(),a()},style:{width:"100%",...A?{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"},k=(u)=>{_(!0),C(u),s(u)},q=(u)=>{if(e.type==="date"&&L&&u){let F=new Date(u);k(Number.isFinite(F.getTime())?F.toISOString():u)}else k(u)},j;if(e.type==="checkbox")j=jt("select",{...K,value:x,onChange:(u)=>k(u.currentTarget.value),children:[!e.required&&$e("option",{value:"",children:y("No value")}),$e("option",{value:"true",children:y("Yes")}),$e("option",{value:"false",children:y("No")})]});else if(e.type==="longText"||e.type==="json")j=$e("textarea",{...K,value:x,rows:e.type==="json"?4:3,onChange:(u)=>k(u.currentTarget.value)});else{let u=e.type==="date"&&!(T&&x)?L?"datetime-local":"date":"text",F=e.type==="blob";j=$e("input",{...K,type:u,inputMode:e.type==="number"?"decimal":void 0,step:L?"0.001":void 0,value:R,readOnly:F,onInput:e.type==="date"?(z)=>q(z.currentTarget.value):void 0,onChange:(z)=>q(z.currentTarget.value)})}return jt("div",{ref:w,className:"grid min-w-0 gap-1",style:A?{height:"100%"}:void 0,children:[o&&$e("label",{className:"text-xs font-medium",htmlFor:D,children:o}),j,I&&$e("span",{id:g,role:"alert",className:"text-xs text-red-600",children:I})]})}import{useEffect as Vn,useRef as _n}from"react";import{jsx as zt}from"react/jsx-runtime";var Ln={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 Kt({name:e,size:t=15,style:n}){return zt("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:zt("path",{d:Ln[e]})})}import{jsx as Me,jsxs as Ht,Fragment as Un}from"react/jsx-runtime";var Bn={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function ea({ui:e,style:t,variant:n,size:i,children:o,disabled:r,onClick:s,title:d,ariaLabel:a,icon:m,iconOnly:p,badge:c}){let y=e?.Button,P=m?Ht("span",{style:{position:"relative",display:"inline-flex"},children:[Me(Kt,{name:m}),c?Me("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,w=p?P:Ht(Un,{children:[P,o]}),A=a,D=d??(p?A:void 0),g=p?"icon":i;if(y)return Me(y,{...n?{variant:n}:{},...g?{size:g}:{},disabled:r,onClick:s,title:D,"aria-label":A,children:w});return Me("button",{type:"button",style:{...m?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?Bn:{},...p?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:r,onClick:s,title:D,"aria-label":A,children:w})}function Yt({ui:e,value:t,options:n,onChange:i,disabled:o,label:r,style:s,"aria-describedby":d,"aria-invalid":a}){let m=e?.Select,p={...d?{"aria-describedby":d}:{},...a?{"aria-invalid":!0}:{}};if(m)return Me(m,{value:t,options:n,onChange:i,disabled:o,"aria-label":r,...p});return Me("select",{"aria-label":r,...p,style:s,disabled:o,value:t,onChange:(c)=>i(c.target.value),children:n.map((c)=>Me("option",{value:c.value,disabled:c.disabled,children:c.label},c.value))})}function ta({label:e,busy:t,onCancel:n,children:i,alert:o=!1}){let r=_n(null);return Vn(()=>{let s=r.current,d=document.activeElement;if(s?.showModal)s.showModal();else s?.setAttribute("open","");return()=>{if(s?.close?.(),d instanceof HTMLElement&&d.isConnected)d.focus({preventScroll:!0})}},[]),Me("dialog",{ref:r,role:o?"alertdialog":"dialog","aria-modal":"true","aria-label":e,style:{position:"fixed",inset:0,margin:"auto",maxWidth:"min(440px, calc(100vw - 32px))",maxHeight:"80vh",overflow:"auto",boxSizing:"border-box",padding:20,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"inherit",font:"inherit"},onKeyDown:(s)=>{if(s.key!=="Tab")return;let d=s.currentTarget,a=[...d.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter((c)=>!c.hidden),m=a[0],p=a.at(-1);if(!m||(s.shiftKey?document.activeElement===m:document.activeElement===p)||!d.contains(document.activeElement)){if(s.preventDefault(),(s.shiftKey?p:m)?.focus(),!m)d.focus()}},tabIndex:-1,onCancel:(s)=>{if(s.preventDefault(),!t)n()},children:i})}import{useEffect as Wt,useRef as Ze,useState as Ae}from"react";import{jsx as H,jsxs as ee,Fragment as zn}from"react/jsx-runtime";function qn(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 $n=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function jn({descriptor:e,fieldIds:t,query:n,client:i,readOnly:o=!1,reloadKey:r=0,onImported:s,onRefreshSchema:d}){let[a,m]=Ae(null),[p,c]=Ae(null),[y,P]=Ae(null),[w,A]=Ae([]),[D,g]=Ae(""),[x,C]=Ae(!1),[f,_]=Ae(!1),[T,U]=Ae(!0),[I,M]=Ae(null),[L,R]=Ae(!1),h=Ze(!1),K=Ze(!1),k=Ze(!1),q=Ze(null),j=Ze({client:i,onImported:s,descriptor:e});j.current={client:i,onImported:s,descriptor:e},Wt(()=>(h.current=!0,()=>{h.current=!1,K.current=!1}),[]),Wt(()=>{let b=!0;if(!o)i.imports(e.id).then((S)=>{if(!b||!h.current||!S.ok)return;if(A((J)=>S.data.map((ne)=>{let ue=J.find((O)=>O.id===ne.id);return ue&&ue.version>ne.version?ue:ne})),!k.current)P((J)=>{let ne=S.data.find((ue)=>ue.id===J?.id);return J&&ne&&ne.version>J.version?ne:J})});return()=>{b=!1}},[i,e.id,o,r]);let u=(b)=>{P(b),A((S)=>[b,...S.filter((J)=>J.id!==b.id)].slice(0,50)),M(null)};async function F(b){if(k.current||o)return;k.current=!0,K.current=!0,C(!0),_(!0),g("");let S=b;try{while(h.current&&K.current&&S.status==="ready"){let J=await j.current.client.advanceImport(e.id,S.id,S.version);if(!h.current)break;if(!J.ok){g(J.error.message);break}let ne=J.data;if(u(ne),ne.importedRows>S.importedRows)j.current.onImported();if(ne.version===S.version&&ne.status==="ready"){g("Import paused. Refresh the saved progress before retrying.");break}S=ne}}finally{if(k.current=!1,K.current=!1,h.current)C(!1),_(!1)}}async function z(){if(!a||k.current)return;k.current=!0,C(!0),g("");let b=await i.previewImport(e.id,{...a,expectedSchemaVersion:e.schemaVersion});if(k.current=!1,!h.current)return;if(C(!1),b.ok)c(b.data),m({...a,expectedSchemaVersion:b.data.schemaVersion,mapping:b.data.mapping});else g(b.error.message)}async function te(){if(!a||!p||p.missingRequiredFieldIds.length||!p.totalRows||k.current||o)return;k.current=!0,C(!0),g(""),q.current??=crypto.randomUUID();let b=await i.createImport(e.id,{...a,idempotencyKey:q.current});if(k.current=!1,!h.current)return;if(C(!1),b.ok)u(b.data),m(null),c(null),q.current=null,F(b.data);else g(b.error.message)}async function N(){if(!y||k.current||o)return;if(y.status==="ready"){F(y);return}k.current=!0,C(!0),g("");let b=d?await d():j.current.descriptor;if(!b){k.current=!1,C(!1),g("Refresh the collection schema and try again.");return}let S=await i.resumeImport(e.id,y.id,y.version,b.schemaVersion);if(k.current=!1,!h.current)return;if(C(!1),S.ok)u(S.data),F(S.data);else g(S.error.message)}async function Y(b){if(!y)return;let S=await i.importErrors(e.id,y.id,{limit:100,...b===void 0?{}:{cursor:b},expectedVersion:y.version});if(!h.current)return;if(S.ok)M(S.data);else g(S.error.message)}async function X(b=!1){if(x||k.current)return;k.current=!0,C(!0),g("");let S=b&&y?await i.exportImportErrors(e.id,y.id):await i.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:T});if(k.current=!1,!h.current)return;if(C(!1),S.ok)qn(S.data),g(`${S.data.rowCount} rows downloaded${S.data.protectedCells?`; ${S.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else g(S.error.message)}return ee("details",{className:"min-w-0 rounded-lg border p-4",children:[H("summary",{className:"cursor-pointer text-sm font-medium",children:"CSV import and export"}),ee("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[ee("div",{className:"flex flex-wrap items-center gap-3",children:[H("button",{type:"button",disabled:x||!t.length,onClick:()=>void X(),children:"Export CSV"}),ee("label",{className:"flex items-center gap-2 text-sm",children:[H("input",{type:"checkbox",checked:T,onChange:(b)=>U(b.target.checked)}),"Spreadsheet view"]})]}),H("p",{className:"text-xs text-muted-foreground",children:"Export all matching records and visible columns from the active query. Spreadsheet view prefixes potentially active text with a tab and changes those values; application support varies. Turn it off for exact text. Limit: 100,000 rows or 20 MiB."}),!o&&ee(zn,{children:[ee("label",{className:"flex min-w-0 flex-col gap-2 text-sm",children:["CSV file",H("input",{"aria-label":"CSV file",className:"max-w-full",type:"file",accept:".csv,text/csv",disabled:x,onChange:async(b)=>{let S=b.target.files?.[0];if(!S)return;if(g(""),c(null),m(null),q.current=null,S.size>20971520){g("Choose a UTF-8 CSV file no larger than 20 MiB.");return}C(!0),k.current=!0;try{let J=new TextDecoder("utf-8",{fatal:!0}).decode(await S.arrayBuffer());if(h.current)m({fileName:S.name,csv:J,expectedSchemaVersion:e.schemaVersion})}catch{if(h.current)g("The file must be valid UTF-8 text.")}finally{if(k.current=!1,h.current)C(!1)}}})]}),a&&ee("div",{className:"flex flex-wrap gap-3",children:[H("span",{className:"break-all text-sm",children:a.fileName}),H("button",{type:"button",disabled:x,onClick:()=>void z(),children:"Preview CSV"})]}),H("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."}),p&&a&&ee("div",{className:"flex min-w-0 flex-col gap-3",children:[ee("p",{className:"text-sm",children:[p.totalRows," rows · ",p.validRows," valid · ",p.invalidRows," ","invalid · ",p.ignoredColumns.length," skipped columns"]}),p.headers.map((b,S)=>ee("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[ee("span",{className:"max-w-64 break-all",children:["Column ",S+1,": ",b||"(empty)"]}),ee("select",{"aria-label":`Column ${S+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:a.mapping?.[S]??"",disabled:x,onChange:(J)=>{let ne=[...a.mapping??p.mapping];ne[S]=J.target.value||null,m({...a,mapping:ne}),c(null),q.current=null},children:[H("option",{value:"",children:"Skip column"}),e.fields.filter((J)=>!ke(J)).map((J)=>ee("option",{value:J.id,children:[J.name," (",J.id,")",J.required?" · required":""]},J.id))]})]},`${S}:${b}`)),p.missingRequiredFieldIds.length>0&&ee("p",{role:"alert",children:["Map required fields: ",p.missingRequiredFieldIds.join(", ")]}),H("div",{className:"max-w-full overflow-x-auto",children:ee("table",{className:"w-full text-xs",children:[ee("caption",{children:["First ",p.sample.length," normalized rows; row numbers include the header."]}),H("thead",{children:ee("tr",{children:[H("th",{children:"Row"}),H("th",{children:"Normalized values"}),H("th",{children:"Error"})]})}),H("tbody",{children:p.sample.map((b)=>ee("tr",{children:[H("td",{children:b.rowNumber}),H("td",{className:"max-w-96 break-all",children:$n(b.values)}),H("td",{children:b.error?.code??""})]},b.rowNumber))})]})}),H("button",{type:"button",className:"self-start",disabled:x||!p.totalRows||p.missingRequiredFieldIds.length>0,onClick:()=>void te(),children:"Confirm import"})]}),ee("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",ee("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:y?.id??"",disabled:x,onChange:async(b)=>{if(!b.target.value){P(null);return}let S=await i.importJob(e.id,b.target.value);if(h.current)if(S.ok)u(S.data),R(!1);else g(S.error.message)},children:[H("option",{value:"",children:"Choose saved progress…"}),w.map((b)=>ee("option",{value:b.id,children:[b.fileName," · ",b.processedRows,"/",b.totalRows," · ",b.status]},b.id))]})]}),H("button",{type:"button",className:"self-start",disabled:x,onClick:async()=>{let b=await i.imports(e.id);if(h.current)if(b.ok)A(b.data);else g(b.error.message)},children:"Refresh saved imports"}),y&&ee("div",{className:"flex flex-col gap-3",children:[ee("p",{role:"status",children:[f?"Importing":y.status==="ready"?"Paused":y.status==="schemaChanged"?"Schema changed — confirm before continuing":y.status==="completed"?"Completed":"Cancelled"," ","· ",y.processedRows," of ",y.totalRows," processed · ",y.importedRows," imported ·"," ",y.failedRows," failed"]}),H("progress",{"aria-label":"Import progress",max:y.totalRows,value:y.processedRows,className:"max-w-full"}),H("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."}),ee("div",{className:"flex flex-wrap gap-3",children:[f&&H("button",{type:"button",onClick:()=>{K.current=!1,_(!1)},children:"Pause import"}),!f&&(y.status==="ready"||y.status==="schemaChanged")&&H("button",{type:"button",disabled:x,onClick:()=>void N(),children:y.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(y.status==="ready"||y.status==="schemaChanged")&&H("button",{type:"button",disabled:x,onClick:()=>R(!0),children:"Cancel import"}),H("button",{type:"button",disabled:x||!y.failedRows,onClick:()=>void Y(),children:"Show import errors"}),H("button",{type:"button",disabled:x||!y.failedRows,onClick:()=>void X(!0),children:"Download all import errors"})]}),L&&ee("div",{children:[ee("p",{children:["Stop remaining rows? The ",y.importedRows," imported records will remain."]}),H("button",{type:"button",disabled:x,onClick:async()=>{k.current=!0,C(!0);let b=await i.cancelImport(e.id,y.id);if(k.current=!1,!h.current)return;if(C(!1),b.ok)u(b.data),R(!1);else g(b.error.message)},children:"Confirm cancellation"}),H("button",{type:"button",onClick:()=>R(!1),children:"Keep import"})]}),I&&ee("div",{className:"max-w-full overflow-x-auto",children:[ee("table",{className:"w-full text-xs",children:[ee("caption",{children:[I.total," failed rows"]}),H("thead",{children:ee("tr",{children:[H("th",{children:"Row"}),H("th",{children:"Field"}),H("th",{children:"Error"})]})}),H("tbody",{children:I.items.map((b)=>ee("tr",{children:[H("td",{children:b.rowNumber}),H("td",{children:b.fieldId??""}),H("td",{children:b.code})]},b.rowNumber))})]}),I.nextCursor!==null&&H("button",{type:"button",onClick:()=>void Y(I.nextCursor??void 0),children:"Next errors"})]})]})]}),D&&H("p",{role:"alert",className:"break-words text-sm",children:D})]})]})}import{useEffect as Gt,useRef as je,useState as ze}from"react";import{jsx as ae,jsxs as be,Fragment as Hn}from"react/jsx-runtime";var nt=[{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 Kn({descriptor:e,client:t,onConverted:n}){let i=e.fields.filter((u)=>nt.some((F)=>F.type===u.type)),[o,r]=ze(i[0]?.id??""),s=i.find((u)=>u.id===o)??i[0],[d,a]=ze(s?.type??"singleLineText"),[m,p]=ze(s?.required??!1),[c,y]=ze(s?.options?.map((u)=>`${u.id}=${u.name}`).join(`
|
|
5
|
-
`)??""),[P,
|
|
6
|
-
`)??"");
|
|
7
|
-
`)??""),
|
|
8
|
-
`).filter((F)=>F.trim()).map((F)=>{let z=F.indexOf("=");if(z<1)throw Error("Each option must use stable_id=Display name.");return{id:F.slice(0,z).trim(),name:F.slice(z+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:
|
|
9
|
-
done=Done`})]}),A&&ae("p",{role:"alert",className:"text-sm text-destructive",children:A}),ae("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:I,onClick:async()=>{let u;try{u=q()}catch(F){D(F instanceof Error?F.message:"Invalid conversion options.");return}x(!0),D(""),w(null),C.current=null;try{let F=await t.previewConversion(e.id,u);if(!j())return;if(F.ok)w(F.data);else D(F.error.message)}catch{if(j())D("Preview unavailable. Your draft is kept.")}finally{if(j())x(!1)}},children:g?"Working…":"Preview conversion"}),P&&be(Hn,{children:[be("p",{role:"status",children:[P.validRows," valid · ",P.invalidRows," invalid"]}),be("p",{className:"text-xs",children:["Preview covers ",P.totalRows," records. Samples and errors show at most 20 records."]}),ae("div",{className:"overflow-x-auto",children:be("table",{className:"w-full text-sm",children:[ae("thead",{children:be("tr",{children:[ae("th",{children:"Record"}),ae("th",{children:"Before"}),ae("th",{children:"After"}),ae("th",{children:"Error"})]})}),ae("tbody",{children:P.sample.map((u)=>be("tr",{children:[ae("td",{className:"max-w-32 break-all",children:u.id}),ae("td",{className:"max-w-48 break-words",children:JSON.stringify(u.before)}),ae("td",{className:"max-w-48 break-words",children:JSON.stringify(u.after)}),ae("td",{children:u.error})]},u.id))})]})}),P.errors.length>0&&ae("ul",{children:P.errors.map((u)=>be("li",{children:[ae("span",{className:"break-all",children:u.id}),": ",ae("span",{children:u.code})]},u.id))}),ae("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:g||P.invalidRows>0,onClick:async()=>{if(!C.current)f.current=e.id,_.current++;C.current??={expectedSchemaVersion:P.schemaVersion,field:P.field,previewToken:P.previewToken,idempotencyKey:crypto.randomUUID()};let u=C.current,F=_.current,z=()=>h.current&&T.current.id===e.id&&F===_.current;x(!0),D("");try{let te=await t.convertField(e.id,u);if(!z())return;if(te.ok){if(w(null),C.current=null,f.current=null,te.data.descriptor.schemaVersion>=T.current.schemaVersion)n(te.data.descriptor)}else if(D(te.error.message),te.error.status===409)w(null),C.current=null,f.current=null}catch{if(z())D("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(z())x(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as Yn,useRef as pt,useState as Jt}from"react";import{jsx as Zt,jsxs as Gn}from"react/jsx-runtime";function Wn({collectionIds:e,client:t,onChanges:n,pollIntervalMs:i=2000}){let o=JSON.stringify([...new Set(e)].sort()),r=pt(o);r.current=o;let s=pt(n);s.current=n;let d=pt(()=>{}),[a,m]=Jt("connecting"),[p,c]=Jt(!1);return Yn(()=>{let y=JSON.parse(o),P=new Map,w=!1,A=!1,D=0,g,x=()=>!w&&r.current===o,C=Math.max(50,Math.min(60000,i)),f=async()=>{if(!x()||A)return;A=!0,c(!0);let U=!1;try{let I=D>0;for(let M of y){let L=P.get(M),R=await t.changes(M,{...L!==void 0?{cursor:L}:{},limit:100});if(!x())return;if(!R.ok)throw m(R.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let h=L===void 0;if(h||I||R.data.items.length>0)await s.current(M,R.data,h);if(!x())return;P.set(M,R.data.cursor),U||=R.data.hasMore}D=0,m("live")}catch{if(D++,x())m((I)=>I==="expired"?"expired":"offline")}finally{if(A=!1,x())c(!1),g=setTimeout(()=>{f()},U&&D===0?0:Math.min(30000,C*2**Math.min(D,8)))}},_=()=>{if(g!==void 0)clearTimeout(g);f()};d.current=_,m("connecting"),f();let T=()=>{if(document.visibilityState==="visible")_()};return window.addEventListener("online",_),document.addEventListener("visibilitychange",T),()=>{if(w=!0,g!==void 0)clearTimeout(g);window.removeEventListener("online",_),document.removeEventListener("visibilitychange",T)}},[o,t,i]),Gn("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[Zt("p",{role:"status",children:a==="live"?"Live updates":a==="connecting"?"Connecting live updates…":a==="expired"?"Session expired. Renew your session; drafts are kept.":"Connection interrupted. Drafts are kept."}),(a==="offline"||a==="expired")&&Zt("button",{type:"button",className:"rounded border px-2 py-1",disabled:p,onClick:()=>d.current(),children:"Reconnect now"})]})}import{useEffect as rt,useRef as Oe,useState as he}from"react";import{jsx as G,jsxs as re,Fragment as ft}from"react/jsx-runtime";var mt={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function Qe(e){try{return await e()}catch{return{ok:!1,error:mt}}}function gt({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return re("div",{className:"min-w-0",children:[G("strong",{children:t}),G("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&&re(ft,{children:[G("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),G("button",{type:"button",onClick:()=>{let i=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),o=document.createElement("a");o.href=i,o.download=`record-${e?.id}-${e?.version}.json`,o.click(),setTimeout(()=>URL.revokeObjectURL(i),1000)},children:"Download snapshot"})]})]})}function Jn({descriptor:e,recordId:t,client:n,readOnly:i=!1,onCommitted:o,registerRefresh:r}){let[s,d]=he(null),[a,m]=he(null),[p,c]=he(null),[y,P]=he(),[w,A]=he(),[D,g]=he([]),[x,C]=he([]),[f,_]=he(""),[T,U]=he(null),[I,M]=he(null),[L,R]=he(null),[h,K]=he(!1),[k,q]=he(""),j=Oe(null),u=Oe(null),F=Oe(n);F.current=n;let z=Oe(!1),te=Oe(0),N=`${e.id}:${t}`,Y=Oe(N);Y.current=N;let X=Oe({historyBefore:y,commentBefore:w});X.current={historyBefore:y,commentBefore:w};let b=Oe(async()=>{}),S=(l=N)=>z.current&&Y.current===l&&F.current===n,J=async()=>{let l=N,E=++te.current,B=X.current,[ye,Ve]=await Promise.all([Qe(()=>n.history(e.id,t,{...B.historyBefore===void 0?{}:{before:B.historyBefore},limit:20})),Qe(()=>n.comments(e.id,t,{...B.commentBefore===void 0?{}:{before:B.commentBefore},limit:50}))]);if(!S(l)||E!==te.current)throw Error("Refresh superseded");if(!ye.ok||!Ve.ok)throw q(!ye.ok?ye.error.message:!Ve.ok?Ve.error.message:mt.message),Error("Activity refresh failed");m(ye.data),c(Ve.data),d(l)};b.current=J,rt(()=>(z.current=!0,()=>{z.current=!1,te.current++}),[]),rt(()=>(r?.(()=>b.current()),()=>r?.(null)),[r]),rt(()=>{if(Y.current!==N)return;m(null),c(null),d(null),P(void 0),A(void 0),g([]),C([]),X.current={historyBefore:void 0,commentBefore:void 0},_(""),U(null),M(null),R(null),j.current=null,u.current=null,K(!1),q("")},[N]),rt(()=>{if(Y.current!==N||F.current!==n||X.current.historyBefore!==y||X.current.commentBefore!==w)return;b.current().catch(()=>{})},[N,n,y,w]);let ne=(l)=>{let E=j.current;if(E?.signature===l)return E.key;let B={signature:l,key:crypto.randomUUID()};return j.current=B,B.key},ue=async(l)=>{if(h||i||!p||s!==N)return;let E=l==="delete"?I:T;if(l!=="create"&&(!E||E.authorId!==p.actorId))return;let B=l==="create"?f:T?.draft??"";if(l!=="delete"&&(!B.trim()||B.length>4000||B.includes("\x00"))){q("Comments require 1–4,000 characters.");return}let ye=ne(JSON.stringify([l,E?.id,E?.version,B]));K(!0),q("");let Ve=await Qe(async()=>{if(l==="create")return n.createComment(e.id,t,{text:B,idempotencyKey:ye});if(!E)return{ok:!1,error:mt};if(l==="edit")return n.editComment(e.id,t,E.id,{text:B,expectedVersion:E.version,idempotencyKey:ye});return n.deleteComment(e.id,t,E.id,{expectedVersion:E.version,idempotencyKey:ye})});if(!S())return;if(K(!1),!Ve.ok){q(Ve.error.message);return}if(j.current=null,l==="create")_("");else if(l==="edit")U(null);else M(null);if(l==="create"&&w!==void 0)A(void 0),C([]);else await b.current().catch(()=>{})},O=async(l)=>{if(h||i||!a||s!==N)return;K(!0),q(""),u.current=null;let E={targetVersion:l,expectedCurrentVersion:a.currentVersion,expectedSchemaVersion:e.schemaVersion},B=await Qe(()=>n.previewUndo(e.id,t,E));if(!S())return;if(K(!1),B.ok)R(B.data);else R(null),q(B.error.message)},se=async()=>{if(h||i||s!==N||!L&&!u.current)return;let l=u.current;if(!l){if(!L)return;l={targetVersion:L.targetVersion,expectedCurrentVersion:L.currentVersion,expectedSchemaVersion:L.schemaVersion,idempotencyKey:crypto.randomUUID()},u.current=l}let E=l;K(!0),q("");let B=await Qe(()=>n.undo(e.id,t,E));if(!S())return;if(K(!1),!B.ok){if(B.error.code==="version_conflict"||B.error.code==="reference_conflict"||B.error.code==="validation")u.current=null,R(null);q(B.error.message),await b.current().catch(()=>{});return}u.current=null,R(null),o(B.data),P(void 0),g([]),await b.current().catch(()=>{})},W=p?.items.find((l)=>l.id===T?.id),ge=T&&W&&W.version!==T.version,v=L&&(L.currentVersion!==a?.currentVersion||L.schemaVersion!==e.schemaVersion);return re("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[re("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[re("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),G("button",{type:"button",disabled:h,onClick:()=>{q(""),b.current().catch(()=>{})},children:"Refresh activity"})]}),k&&G("p",{role:"alert",className:"text-sm text-destructive",children:k}),!a||!p||s!==N?G("p",{role:"status",children:"Loading record activity…"}):re(ft,{children:[re("p",{role:"status",children:["Current version ",a.currentVersion,a.currentDeleted?" · Deleted record":""]}),G("h3",{className:"font-medium",children:"Comments"}),p.items.length===0&&G("p",{className:"text-sm",children:"No comments yet."}),G("ol",{className:"flex flex-col gap-3",children:p.items.map((l)=>re("li",{className:"min-w-0 rounded border p-3",children:[re("p",{className:"break-all text-xs",children:[l.authorId," · ",l.updatedAt," · version ",l.version]}),G("p",{className:"whitespace-pre-wrap break-words text-sm",children:l.text??"Comment deleted"}),!i&&l.text!==null&&l.authorId===p.actorId&&re("div",{className:"flex gap-3",children:[G("button",{type:"button",disabled:h,onClick:()=>{U({...l,draft:l.text??""}),M(null),j.current=null},children:"Edit comment"}),G("button",{type:"button",disabled:h,onClick:()=>{M(l),U(null),j.current=null},children:"Delete comment"})]})]},l.id))}),re("div",{className:"flex gap-3",children:[G("button",{type:"button",disabled:h||!x.length,onClick:()=>{A(x.at(-1)),C((l)=>l.slice(0,-1))},children:"Newer comments"}),G("button",{type:"button",disabled:h||p.nextCursor===null,onClick:()=>{C((l)=>[...l,w]),A(p.nextCursor??void 0)},children:"Older comments"})]}),!i&&re(ft,{children:[T&&re("div",{className:"flex flex-col gap-2",children:[re("label",{children:["Edit comment text",G("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:h,maxLength:4000,value:T.draft,onChange:(l)=>{U({...T,draft:l.target.value}),j.current=null}})]}),ge&&re("div",{role:"status",children:[G("p",{children:"This comment changed. Your draft and original version are kept."}),re("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",W.text??"Comment deleted"]}),W.text!==null&&W.authorId===p.actorId&&G("button",{type:"button",disabled:h,onClick:()=>{U({...W,draft:T.draft}),j.current=null},children:"Use current comment version"})]}),re("div",{className:"flex gap-3",children:[G("button",{type:"button",disabled:h||T.authorId!==p.actorId,onClick:()=>void ue("edit"),children:"Save comment"}),G("button",{type:"button",disabled:h,onClick:()=>{U(null),j.current=null},children:"Cancel comment edit"})]})]}),I&&re("div",{children:[G("p",{children:"Delete this comment? A deletion marker will remain."}),G("p",{className:"whitespace-pre-wrap break-words",children:I.text}),G("button",{type:"button",disabled:h||I.authorId!==p.actorId,onClick:()=>void ue("delete"),children:"Confirm delete comment"}),G("button",{type:"button",disabled:h,onClick:()=>M(null),children:"Cancel delete comment"})]}),re("label",{children:["New comment",G("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:h,maxLength:4000,value:f,onChange:(l)=>{_(l.target.value),j.current=null}})]}),G("button",{type:"button",className:"self-start",disabled:h||!f.trim(),onClick:()=>void ue("create"),children:"Add comment"})]}),G("h3",{className:"font-medium",children:"Record history"}),G("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."}),G("ol",{className:"flex flex-col gap-3",children:a.items.map((l)=>re("li",{className:"min-w-0 rounded border p-3",children:[re("p",{className:"break-all text-xs",children:["Version ",l.version," · ",l.operation," · schema ",l.schemaVersion," · ",l.actorId," ·"," ",l.createdAt]}),re("details",{children:[re("summary",{children:["Stored values at version ",l.version]}),G(gt,{record:l.snapshot,label:`Version ${l.version}`})]}),!i&&l.version<a.currentVersion&&re("button",{type:"button",disabled:h,onClick:()=>void O(l.version),children:["Preview restore version ",l.version]})]},l.id))}),re("div",{className:"flex gap-3",children:[G("button",{type:"button",disabled:h||!D.length,onClick:()=>{P(D.at(-1)),g((l)=>l.slice(0,-1))},children:"Newer history"}),G("button",{type:"button",disabled:h||a.nextCursor===null,onClick:()=>{g((l)=>[...l,y]),P(a.nextCursor??void 0)},children:"Older history"})]}),!i&&L&&re("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[re("h3",{children:["Restore version ",L.targetVersion," as a new version"]}),re("p",{children:["Current version ",L.currentVersion," · schema ",L.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),re("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[G(gt,{record:L.before,label:"Current stored values"}),G(gt,{record:L.target,label:"Values to restore"})]}),v&&!u.current&&G("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),re("div",{className:"flex gap-3",children:[G("button",{type:"button",disabled:h||!!v&&!u.current,onClick:()=>void se(),children:u.current?"Retry undo":"Confirm restore"}),G("button",{type:"button",disabled:h,onClick:()=>{R(null),u.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as ot,useRef as Le,useState as Te}from"react";import{jsx as pe,jsxs as xe,Fragment as Qt}from"react/jsx-runtime";async function it(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 Zn(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let i of t)n+=String.fromCharCode(i);return btoa(n)}function Qn({collectionId:e,recordId:t,client:n,readOnly:i=!1,registerRefresh:o}){let r=`${e}:${t}`,s=Le({identity:r,client:n});s.current={identity:r,client:n};let d=Le(!1),a=Le(0),m=Le(0),[p,c]=Te(null),[y,P]=Te(null),[w,A]=Te(),[D,g]=Te([]),x=Le(w);x.current=w;let[C,f]=Te(null),[_,T]=Te(null),U=Le(null),I=Le(null),[M,L]=Te(!1),[R,h]=Te(!1),[K,k]=Te(""),q=()=>d.current&&s.current.identity===r&&s.current.client===n,j=async()=>{let N=++a.current,Y=await it(()=>n.list(e,t,{limit:20,...x.current===void 0?{}:{before:x.current}}));if(!q()||N!==a.current)throw Error("Refresh superseded");if(!Y.ok)throw k(Y.error.message),Error("Attachment refresh failed");P(Y.data),c(r)},u=Le(j);u.current=j,ot(()=>(d.current=!0,()=>{d.current=!1,++a.current,++m.current}),[]),ot(()=>{if(s.current.identity!==r||s.current.client!==n)return;c(null),P(null),f(null),T(null),U.current=null,L(!1),h(!1),k(""),A(void 0),g([]),x.current=void 0,++m.current,u.current().catch(()=>{})},[r,n]),ot(()=>{if(x.current===w&&p===r)u.current().catch(()=>{})},[w,r,p]),ot(()=>(o?.(()=>u.current()),()=>o?.(null)),[o]);let F=async()=>{if(M||i||!C||p!==r)return;let N=C;L(!0),k("");let Y=await it(()=>n.upload(e,t,N));if(!q())return;if(L(!1),!Y.ok){k(Y.error.message);return}if(f(null),I.current)I.current.value="";A(void 0),g([]),x.current=void 0,await u.current().catch(()=>{})},z=async()=>{if(M||i||!_||_.authorId!==y?.actorId||p!==r)return;U.current??=crypto.randomUUID();let N=_,Y=U.current;L(!0),k("");let X=await it(()=>n.delete(e,t,N.id,{expectedVersion:N.version,idempotencyKey:Y}));if(!q())return;if(L(!1),!X.ok){k(X.error.message),await u.current().catch(()=>{});return}T(null),U.current=null,await u.current().catch(()=>{})},te=async(N)=>{if(M||p!==r)return;L(!0),k("");let Y=await it(()=>n.content(e,t,N.id));if(!q())return;if(L(!1),!Y.ok){k(Y.error.message);return}let X=Uint8Array.from(atob(Y.data.base64),(J)=>J.charCodeAt(0)),b=URL.createObjectURL(new Blob([X],{type:"application/octet-stream"})),S=document.createElement("a");S.href=b,S.download=Y.data.attachment.name,S.click(),setTimeout(()=>URL.revokeObjectURL(b),1000)};return xe("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[xe("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[pe("h3",{className:"font-medium",children:"Attachments"}),pe("button",{type:"button",disabled:M,onClick:()=>{k(""),u.current().catch(()=>{})},children:"Refresh attachments"})]}),K&&pe("p",{role:"alert",children:K}),!y||p!==r?pe("p",{role:"status",children:"Loading attachments…"}):xe(Qt,{children:[y.items.length===0&&pe("p",{children:"No attachments yet."}),pe("ol",{className:"flex min-w-0 flex-col gap-2",children:y.items.map((N)=>xe("li",{className:"min-w-0 rounded border p-2",children:[pe("p",{className:"break-all",children:N.name}),xe("p",{className:"break-all text-xs",children:[N.size," bytes · version ",N.version," · ",N.authorId]}),N.deletedAt?pe("p",{children:"Attachment deleted"}):xe("div",{className:"flex flex-wrap gap-3",children:[pe("button",{type:"button",disabled:M,"aria-label":`Download attachment ${N.name}`,onClick:()=>void te(N),children:"Download"}),!i&&N.authorId===y.actorId&&pe("button",{type:"button",disabled:M,"aria-label":`Delete attachment ${N.name}`,onClick:()=>{T(N),U.current=null},children:"Delete"})]})]},N.id))}),xe("div",{className:"flex flex-wrap gap-3",children:[pe("button",{type:"button",disabled:M||!D.length,onClick:()=>{A(D.at(-1)),g((N)=>N.slice(0,-1))},children:"Newer attachments"}),pe("button",{type:"button",disabled:M||y.nextCursor===null,onClick:()=>{g((N)=>[...N,w]),A(y.nextCursor??void 0)},children:"Older attachments"})]}),!i&&xe(Qt,{children:[pe("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."}),xe("label",{children:["Attachment file",pe("input",{ref:I,"aria-label":"Attachment file",type:"file",disabled:M||R,onChange:async(N)=>{let Y=N.target.files?.[0];if(!Y)return;let X=++m.current;if(f(null),k(""),!Y.size||Y.size>1048576){k("Choose a nonempty file up to 1 MiB.");return}h(!0);try{let b=await Zn(Y);if(!q()||X!==m.current)return;let S=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(Y.type)?Y.type:"application/octet-stream";f({name:Y.name,contentType:S,base64:b,idempotencyKey:crypto.randomUUID()})}catch{if(q()&&X===m.current)k("The selected file could not be read.")}finally{if(q()&&X===m.current)h(!1)}}},r)]}),C&&xe("p",{className:"break-all",children:["Selected file: ",C.name]}),pe("button",{type:"button",className:"self-start",disabled:M||R||!C,onClick:()=>void F(),children:"Upload attachment"}),_&&xe("div",{children:[xe("p",{className:"break-all",children:["Delete ",_.name,"? This permanently removes its bytes and keeps a deletion marker."]}),xe("div",{className:"flex flex-wrap gap-3",children:[pe("button",{type:"button",disabled:M,onClick:()=>void z(),children:"Confirm delete attachment"}),pe("button",{type:"button",disabled:M,onClick:()=>{T(null),U.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as at,useRef as Ye,useState as ve}from"react";import{jsx as ie,jsxs as le,Fragment as Xt}from"react/jsx-runtime";async function yt(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function Xn(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function er({descriptor:e,recordIds:t,client:n,linkForGrant:i,registerRefresh:o}){let r=e.id,s=Ye({identity:r,client:n});s.current={identity:r,client:n};let d=Ye(!1),a=Ye(0),[m,p]=ve(null),[c,y]=ve(null),[P,w]=ve(),A=Ye(P);A.current=P;let[D,g]=ve([]),[x,C]=ve([]),[f,_]=ve([]),[T,U]=ve(3600),[I,M]=ve(null),[L,R]=ve(!1),[h,K]=ve(""),[k,q]=ve(null),j=Ye(null),[u,F]=ve(!1),[z,te]=ve(""),N=()=>d.current&&s.current.identity===r&&s.current.client===n,Y=async()=>{let O=++a.current,se=await yt(()=>n.list(r,{limit:20,...A.current===void 0?{}:{before:A.current}}));if(!N()||O!==a.current)throw Error("Refresh superseded");if(!se.ok)throw te(se.error.message),Error("Share refresh failed");y(se.data),p(r)},X=Ye(Y);X.current=Y,at(()=>(d.current=!0,()=>{d.current=!1,++a.current}),[]),at(()=>{if(s.current.identity!==r||s.current.client!==n)return;p(null),y(null),C([]),_([]),M(null),R(!1),K(""),q(null),j.current=null,F(!1),te(""),w(void 0),g([]),A.current=void 0,X.current().catch(()=>{})},[r,n]),at(()=>{if(A.current===P&&m===r)X.current().catch(()=>{})},[P,m,r]),at(()=>(o?.(()=>X.current()),()=>o?.(null)),[o]);let b=()=>{if(!L)M(null)},S=async()=>{if(u||!I||m!==r)return;let O=I;F(!0),R(!0),te("");let se=await yt(()=>n.create(r,O));if(!N())return;if(F(!1),!se.ok){te(se.error.message);return}K(i(se.data,O.key)),M(null),R(!1),w(void 0),g([]),A.current=void 0,await X.current().catch(()=>{})},J=async()=>{if(u||!k||m!==r)return;let O=k;j.current??=crypto.randomUUID();let se=j.current;F(!0),te("");let W=await yt(()=>n.revoke(r,O.id,{expectedVersion:O.version,idempotencyKey:se}));if(!N())return;if(F(!1),!W.ok){te(W.error.message),await X.current().catch(()=>{});return}q(null),j.current=null,K(""),await X.current().catch(()=>{})},ne=e.fields.filter((O)=>!["linkedRecord","lookup","formula","rollup"].includes(O.type)),ue=u||L;return le("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[le("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[ie("h3",{className:"font-medium",children:"Read-only sharing"}),ie("button",{type:"button",disabled:u,onClick:()=>{te(""),X.current().catch(()=>{})},children:"Refresh share grants"})]}),ie("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."}),ie("p",{className:"text-xs",children:"Relations, computed fields, attachments, discussions, history and writes are excluded. Up to 100 records, 20 active grants and 24 hours per grant. Keys are shown only when created."}),z&&ie("p",{role:"alert",children:z}),le("fieldset",{disabled:ue,className:"flex min-w-0 flex-col gap-2",children:[ie("legend",{children:"Fields to share"}),ne.map((O)=>le("label",{className:"break-all",children:[ie("input",{type:"checkbox","aria-label":`Share field ${O.name}`,checked:x.includes(O.id),onChange:(se)=>{b(),C((W)=>se.target.checked?[...W,O.id]:W.filter((ge)=>ge!==O.id))}})," ",O.name]},O.id))]}),le("fieldset",{disabled:ue,className:"flex min-w-0 flex-col gap-2",children:[ie("legend",{children:"Records on the current page"}),t.slice(0,100).map((O)=>le("label",{className:"break-all",children:[ie("input",{type:"checkbox","aria-label":`Share record ${O}`,checked:f.includes(O),onChange:(se)=>{b(),_((W)=>se.target.checked?[...W,O]:W.filter((ge)=>ge!==O))}})," ",O]},O)),t.length===0&&ie("p",{children:"Load records in Grid to choose a share scope."})]}),le("p",{className:"break-all text-xs",children:["Selected record IDs: ",f.join(", ")||"none"]}),le("label",{children:["Link lifetime"," ",le("select",{"aria-label":"Share link lifetime",disabled:ue,value:T,onChange:(O)=>{b(),U(Number(O.target.value))},children:[ie("option",{value:60,children:"1 minute"}),ie("option",{value:3600,children:"1 hour"}),ie("option",{value:86400,children:"24 hours"})]})]}),ie("button",{type:"button",className:"self-start",disabled:ue||m!==r||!x.length||!f.length||f.length>100||x.some((O)=>!ne.some((se)=>se.id===O)),onClick:()=>{te("");try{M({expectedSchemaVersion:e.schemaVersion,fieldIds:[...x],recordIds:[...f],expiresInSeconds:T,key:Xn(),idempotencyKey:crypto.randomUUID()})}catch{te("A secure share key could not be generated.")}},children:"Review read-only share"}),I&&le("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[le("p",{className:"break-all",children:["Confirm schema ",I.expectedSchemaVersion,", fields ",I.fieldIds.join(", "),", records ",I.recordIds.join(", ")," for ",I.expiresInSeconds," seconds."]}),I.expectedSchemaVersion!==e.schemaVersion&&ie("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),le("div",{className:"flex flex-wrap gap-3",children:[ie("button",{type:"button",disabled:u,onClick:()=>void S(),children:L?"Retry create read link":"Create read link"}),ie("button",{type:"button",disabled:u,onClick:()=>{M(null),R(!1),te("")},children:"Discard share confirmation"})]}),L&&ie("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."})]}),h&&le("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",ie("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:h,onFocus:(O)=>O.target.select()})]}),!c||m!==r?ie("p",{role:"status",children:"Loading share grants…"}):le(Xt,{children:[c.items.length===0&&ie("p",{children:"No share grants yet."}),ie("ol",{className:"flex min-w-0 flex-col gap-2",children:c.items.map((O)=>le("li",{className:"min-w-0 rounded border p-2",children:[le("p",{className:"break-all",children:["Grant ",O.id," · version ",O.version," · schema ",O.schemaVersion]}),le("p",{className:"break-all text-xs",children:["Fields: ",O.fieldIds.join(", ")," · Records: ",O.recordIds.join(", ")," · Expires:"," ",O.expiresAt]}),O.revokedAt?ie("p",{children:"Share revoked"}):le(Xt,{children:[ie("p",{children:O.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(O.expiresAt)<=Date.now()?"Share expired":"Share active"}),ie("button",{type:"button",disabled:u,"aria-label":`Revoke share ${O.id}`,onClick:()=>{q(O),j.current=null},children:"Revoke"})]})]},O.id))}),le("div",{className:"flex flex-wrap gap-3",children:[ie("button",{type:"button",disabled:u||!D.length,onClick:()=>{w(D.at(-1)),g((O)=>O.slice(0,-1))},children:"Newer share grants"}),ie("button",{type:"button",disabled:u||c.nextCursor===null,onClick:()=>{g((O)=>[...O,P]),w(c.nextCursor??void 0)},children:"Older share grants"})]})]}),k&&le("div",{children:[le("p",{className:"break-all",children:["Revoke grant ",k.id," at version ",k.version,"? Every existing share session will lose access."]}),le("div",{className:"flex flex-wrap gap-3",children:[ie("button",{type:"button",disabled:u,onClick:()=>void J(),children:"Confirm revoke share"}),ie("button",{type:"button",disabled:u,onClick:()=>{q(null),j.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as en,useRef as We,useState as fe}from"react";import{jsx as Z,jsxs as ce}from"react/jsx-runtime";var tn=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],tr=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function nr({descriptor:e,recordIds:t,client:n,webhookRequest:i}){let o=e.id,r=We({id:o,client:n});r.current={id:o,client:n};let s=We(!0),d=We(0),[a,m]=fe([]),[p,c]=fe(""),y=We(p);y.current=p;let[P,w]=fe(null),[A,D]=fe(),g=We(A);g.current=A;let[x,C]=fe(""),[f,_]=fe("record"),[T,U]=fe(60),[I,M]=fe([]),[L,R]=fe([]),[h,K]=fe({}),[k,q]=fe(null),[j,u]=fe(!1),[F,z]=fe(!1),[te,N]=fe(""),[Y,X]=fe(""),b=()=>s.current&&r.current.id===o&&r.current.client===n,S=async(v)=>{try{return await v()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},J=async()=>{let v=++d.current,l=await S(()=>n.list(o));if(!b()||v!==d.current)return;if(!l.ok){N(l.error.message);return}m(l.data);let E=l.data.find((ye)=>ye.id===y.current)?.id??l.data[0]?.id??"";if(y.current=E,c(E),!E){w(null);return}let B=await S(()=>n.runs(o,E,{limit:20,...g.current?{before:g.current}:{}}));if(!b()||v!==d.current||y.current!==E)return;if(B.ok)w(B.data);else N(B.error.message)},ne=We(J);ne.current=J,en(()=>{if(r.current.id!==o||r.current.client!==n)return;s.current=!0,ne.current();let v=setInterval(()=>void ne.current(),5000);return()=>{s.current=!1,++d.current,clearInterval(v)}},[o,n]),en(()=>{if(y.current!==p||g.current!==A)return;ne.current()},[p,A]);let ue=()=>{if(N(""),!x.trim()||!I.length||f!=="record"&&!L.length){N("Choose a name, writable fields, and target records for time or webhook triggers.");return}let v=Object.fromEntries(I.map((E)=>[E,h[E]??null])),l={expectedSchemaVersion:e.schemaVersion,name:x.trim(),trigger:f==="time"?{kind:f,intervalSeconds:T}:{kind:f},targetRecordIds:L,values:v,idempotencyKey:crypto.randomUUID(),...f==="webhook"?{webhookKey:tr()}:{}};q({kind:"create",input:l}),u(!1)},O=(v)=>{q(v),u(!1),N("")},se=async()=>{if(!k||F)return;let v=k,l=j;u(!0),z(!0),N("");let E=await S(()=>v.kind==="create"?n.create(o,v.input):v.kind==="toggle"?n.toggle(o,v.a.id,v.input):v.kind==="run"?n.runNow(o,v.a.id,v.input):n.retry(o,v.a.id,v.run.id,v.input));if(!b())return;if(z(!1),!E.ok){if(!l&&E.error.status>=400&&E.error.status<500)u(!1);N(`${E.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(v.kind==="create"){let B=E.data;if(y.current=B.id,c(B.id),v.input.webhookKey&&i)X(JSON.stringify(i(B,v.input.webhookKey),null,2));C(""),M([]),R([]),K({})}q(null),u(!1),g.current=void 0,D(void 0),await ne.current()},W=a.find((v)=>v.id===p),ge=!!k||F;return ce("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[Z("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."}),Z("button",{type:"button",onClick:()=>void ne.current(),children:"Refresh automation"}),te&&Z("p",{role:"alert",children:te}),Z("form",{onSubmit:(v)=>{v.preventDefault(),ue()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:ce("fieldset",{disabled:ge,style:{minWidth:0},children:[Z("legend",{children:"New automation"}),ce("label",{children:["Name"," ",Z("input",{"aria-label":"Automation name",value:x,maxLength:200,onChange:(v)=>C(v.target.value)})]}),ce("label",{children:["Trigger"," ",ce("select",{"aria-label":"Automation trigger",value:f,onChange:(v)=>_(v.target.value),children:[Z("option",{value:"record",children:"Record changes"}),Z("option",{value:"time",children:"Timed interval"}),Z("option",{value:"webhook",children:"Private webhook"})]})]}),f==="time"&&ce("label",{children:["Interval in seconds"," ",Z("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:T,onChange:(v)=>U(Number(v.target.value))})]}),ce("fieldset",{children:[Z("legend",{children:"Fields to update"}),e.fields.filter((v)=>tn.includes(v.type)).map((v)=>ce("label",{style:{display:"block"},children:[Z("input",{type:"checkbox",checked:I.includes(v.id),onChange:(l)=>{M(l.target.checked?[...I,v.id]:I.filter((E)=>E!==v.id))}}),v.name]},v.id))]}),Z(nn,{fields:e.fields.filter((v)=>I.includes(v.id)&&tn.includes(v.type)),values:h,onChange:K}),ce("fieldset",{children:[Z("legend",{children:"Target records from this page"}),f==="record"&&Z("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&Z("p",{children:"Open a grid page to choose fixed records."}),t.map((v)=>ce("label",{style:{display:"block",overflowWrap:"anywhere"},children:[Z("input",{type:"checkbox","aria-label":`Automation target ${v}`,checked:L.includes(v),onChange:(l)=>R(l.target.checked?[...L,v]:L.filter((E)=>E!==v))}),v]},v))]}),Z("button",{type:"submit",children:"Review automation"})]})}),k&&ce("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[Z("p",{children:k.kind==="create"?`Create ${k.input.name} using schema ${k.input.expectedSchemaVersion}; ${k.input.targetRecordIds.length||"event"} targets.`:k.kind==="toggle"?`${k.input.enabled?"Enable":"Disable"} ${k.a.name}. Disabling fences queued and running work.`:k.kind==="run"?`Run ${k.a.name} for ${k.input.recordIds.length} explicitly selected records.`:`Retry ${k.a.name}, run ${k.run.sequence}, using its original record versions.`}),k.kind==="create"&&Z("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(k.input.values,null,2)}),Z("button",{type:"button",disabled:F,onClick:()=>void se(),children:F?"Confirming…":j?"Retry automation confirmation":"Confirm automation"}),Z("button",{type:"button",disabled:j||F,onClick:()=>q(null),children:"Cancel automation review"}),j&&Z("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),Y&&ce("div",{children:[Z("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),Z("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:Y}),Z("button",{type:"button",onClick:()=>X(""),children:"Hide webhook key"})]}),a.length>0&&ce("label",{children:["Automation"," ",Z("select",{"aria-label":"Selected automation",disabled:ge,value:p,onChange:(v)=>{y.current=v.target.value,g.current=void 0,D(void 0),c(v.target.value),w(null)},children:a.map((v)=>Z("option",{value:v.id,children:v.name},v.id))})]}),W&&ce("div",{children:[ce("p",{children:[W.enabled?"Enabled":"Disabled"," · ",W.trigger.kind," · schema ",W.schemaVersion," · configuration ",W.version]}),Z("button",{type:"button",disabled:ge,onClick:()=>O({kind:"toggle",a:W,input:{expectedVersion:W.version,enabled:!W.enabled,idempotencyKey:crypto.randomUUID()}}),children:W.enabled?"Review disable automation":"Review enable automation"}),Z("button",{type:"button",disabled:ge||!W.enabled||!(W.targetRecordIds.length||t.length),onClick:()=>O({kind:"run",a:W,input:{recordIds:W.targetRecordIds.length?W.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),P&&ce("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!P.items.length&&Z("p",{children:"No runs yet."}),P.items.map((v)=>ce("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[ce("p",{children:["Run ",v.sequence," · ",v.triggerKind," · ",v.status," · step ",v.step]}),ce("p",{children:["Attempts: evaluate ",v.stepAttempts.evaluate,", apply ",v.stepAttempts.apply," · original versions: ",v.expectedRows.map((l)=>`${l.id}: ${l.version}`).join(", ")]}),v.errorCode&&Z("p",{role:"status",children:v.errorCode}),v.leaseUntil&&ce("p",{children:["Lease expires ",v.leaseUntil]}),W&&v.status==="failed"&&ce("button",{type:"button",disabled:ge||!W.enabled,onClick:()=>O({kind:"retry",a:W,run:v,input:{expectedVersion:v.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",v.sequence]})]},v.id)),Z("button",{type:"button",disabled:ge||A===void 0,onClick:()=>{g.current=void 0,D(void 0)},children:"Newest runs"}),Z("button",{type:"button",disabled:ge||P.nextCursor===null,onClick:()=>{g.current=P.nextCursor??void 0,D(g.current)},children:"Older runs"})]})]})}import{useEffect as rr,useId as or,useRef as rn,useState as me}from"react";import{jsx as oe,jsxs as de}from"react/jsx-runtime";var on=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function ir(e,t,n){if(!n.resourceId||!n.model.trim()||n.model.length>200||!n.instruction.trim()||new TextEncoder().encode(n.instruction).length>2000||n.recordIds.length<1||n.recordIds.length>10||new Set(n.recordIds).size!==n.recordIds.length)throw Error("Choose an AI resource, model, instruction and up to ten records.");for(let o of[n.sourceFieldIds,n.targetFieldIds])if(o.length<1||o.length>10||new Set(o).size!==o.length||o.some((r)=>!e.fields.some((s)=>s.id===r&&on.includes(s.type))))throw Error("Choose up to ten basic source and target fields.");let i=n.recordIds.map((o)=>{let r=t.find((s)=>s.id===o);if(!r)throw Error("A selected record is no longer on this page.");return{id:o,expectedVersion:r.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 ar({descriptor:e,records:t,client:n,onApplied:i}){let o=or(),r=e.id,s=rn({id:r,client:n}),d=rn(!0);s.current={id:r,client:n};let[a,m]=me([]),[p,c]=me(!1),[y,P]=me(""),[w,A]=me(""),[D,g]=me(""),[x,C]=me([]),[f,_]=me([]),[T,U]=me([]),[I,M]=me(null),[L,R]=me(null),[h,K]=me(null),[k,q]=me(!1),[j,u]=me(!1),[F,z]=me(""),[te,N]=me(""),[Y,X]=me(""),b=()=>d.current&&s.current.id===r&&s.current.client===n,S=async(l)=>{try{return await l()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};rr(()=>{d.current=!0,M(null),R(null),K(null),q(!1),z(""),N(""),X(""),C([]),_([]),U([]),g("");let l=!0;return c(!1),u(!1),m([]),P(""),A(""),n.providers(r).then((E)=>{if(!l||s.current.id!==r||s.current.client!==n)return;if(c(!0),E.ok)m(E.data),P(E.data[0]?.resourceId??""),A(E.data[0]?.allowedModels[0]??"");else z(E.error.message)}).catch(()=>{if(l)c(!0),z("AI configuration is unavailable.")}),()=>{l=!1,d.current=!1}},[r,n]);let J=()=>{try{let l=ir(e,t,{resourceId:y,model:w,instruction:D,recordIds:x,sourceFieldIds:f,targetFieldIds:T});R(structuredClone(l.records.map((E)=>({id:E.id,version:E.expectedVersion,values:Object.fromEntries(l.sourceFieldIds.map((B)=>[B,t.find((ye)=>ye.id===E.id)?.values[B]??null]))})))),M(l),q(!1),z(""),N("")}catch(l){z(l instanceof Error?l.message:"Invalid selection.")}},ne=async()=>{if(!I||j)return;let l=I,E=k;u(!0),q(!0),z("");let B=await S(()=>n.propose(r,l));if(!b())return;if(u(!1),!B.ok){if(!E&&B.error.status>=400&&B.error.status<500)q(!1);z(`${B.error.message} Retry keeps the original selection and versions.`);return}K(B.data),X(B.data.id),q(!1)},ue=async()=>{if(!h||j)return;let l=h,E=k;u(!0),q(!0),z("");let B=await S(()=>n.confirm(r,l));if(!b())return;if(u(!1),!B.ok){if(!E&&B.error.status>=400&&B.error.status<500)q(!1);z(`${B.error.message} The reviewed proposal keeps its original versions.`);return}N(`${B.data.items.length} records filled${B.data.replayed?"; original receipt recovered":""}.`),K(null),M(null),R(null),q(!1);try{await i?.()}catch{if(b())z("The fill committed. Refresh the Collection to see its records.")}},O=async()=>{if(j||I||h)return;u(!0),z("");let l=await S(()=>n.get(r,Y));if(!b())return;if(u(!1),l.ok)K(l.data),q(!1),N("");else z(l.error.message)},se=(l,E,B)=>B(l.includes(E)?l.filter((ye)=>ye!==E):[...l,E]),W=j||!!I||!!h,ge=e.fields.filter((l)=>on.includes(l.type)),v=a.find((l)=>l.resourceId===y);return de("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[oe("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."}),F&&oe("p",{role:"alert",children:F}),te&&oe("p",{role:"status",children:te}),p&&a.length===0&&oe("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),oe("form",{onSubmit:(l)=>{l.preventDefault(),J()},children:de("fieldset",{disabled:W,style:{minWidth:0},children:[oe("legend",{children:"AI fill request"}),de("label",{children:["AI resource"," ",de("select",{"aria-label":"AI resource",value:y,onChange:(l)=>{P(l.target.value),A(a.find((E)=>E.resourceId===l.target.value)?.allowedModels[0]??"")},children:[oe("option",{value:"",children:"Choose resource"}),a.map((l)=>oe("option",{value:l.resourceId,children:l.name},l.resourceId))]})]}),de("label",{htmlFor:o,children:["Model"," ",v?.allowedModels.length?oe("select",{id:o,"aria-label":"AI model",value:w,onChange:(l)=>A(l.target.value),children:v.allowedModels.map((l)=>oe("option",{value:l,children:l},l))}):oe("input",{id:o,"aria-label":"AI model",maxLength:200,value:w,onChange:(l)=>A(l.target.value)})]}),de("label",{children:["Instructions"," ",oe("textarea",{"aria-label":"AI instructions",maxLength:2000,value:D,onChange:(l)=>g(l.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),de("fieldset",{children:[oe("legend",{children:"Source fields to send"}),ge.map((l)=>de("label",{style:{display:"block"},children:[oe("input",{type:"checkbox","aria-label":`Send ${l.name}`,checked:f.includes(l.id),onChange:()=>se(f,l.id,_)}),l.name]},l.id))]}),de("fieldset",{children:[oe("legend",{children:"Fields to fill"}),ge.map((l)=>de("label",{style:{display:"block"},children:[oe("input",{type:"checkbox","aria-label":`Fill ${l.name}`,checked:T.includes(l.id),onChange:()=>se(T,l.id,U)}),l.name]},l.id))]}),de("fieldset",{children:[oe("legend",{children:"Target records from this page"}),t.map((l)=>de("label",{style:{display:"block",overflowWrap:"anywhere"},children:[oe("input",{type:"checkbox","aria-label":`AI record ${l.id}`,checked:x.includes(l.id),onChange:()=>se(x,l.id,C)}),l.id," · version ",l.version]},l.id))]}),oe("button",{type:"submit",disabled:!y,children:"Review AI request"})]})}),I&&!h&&de("section",{"aria-label":"AI data disclosure",children:[de("p",{children:["Selected service: ",I.resourceId," · model ",I.model," · schema"," ",I.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),oe("p",{children:I.instruction}),oe("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(L,null,2)}),oe("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),oe("button",{type:"button",disabled:j,onClick:()=>void ne(),children:k?"Retry original AI request":"Generate proposal"}),oe("button",{type:"button",disabled:j||k,onClick:()=>{M(null),R(null),z("")},children:"Cancel AI request"})]}),h&&de("section",{"aria-label":"AI fill confirmation",children:[de("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",h.id," · ",h.provider," · schema ",h.schemaVersion]}),h.schemaVersion!==e.schemaVersion&&oe("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),h.rows.map((l)=>de("div",{style:{overflowWrap:"anywhere"},children:[de("p",{children:[l.id," · original version ",l.expectedVersion]}),Object.keys(l.values).map((E)=>de("div",{children:[oe("strong",{children:e.fields.find((B)=>B.id===E)?.name??E}),de("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(l.before[E]),`
|
|
10
|
-
`,"Suggested: ",JSON.stringify(l.values[E])]})]},E))]},l.id)),oe("button",{type:"button",disabled:j,onClick:()=>void ue(),children:k?"Retry original AI fill":"Confirm fill"}),oe("button",{type:"button",disabled:j||k,onClick:()=>{K(null),M(null),R(null),z("")},children:"Dismiss proposal"})]}),de("label",{children:["Recover a saved proposal"," ",oe("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:Y,onChange:(l)=>X(l.target.value),disabled:W,style:{width:"100%",boxSizing:"border-box"}})]}),oe("button",{type:"button",disabled:W||!/^[a-f0-9]{64}$/.test(Y),onClick:()=>void O(),children:"Load saved proposal"})]})}import{jsx as V,jsxs as Q}from"react/jsx-runtime";var lr=[{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 qa({fields:e,onChange:t,lockedIds:n=[],collections:i=[]}){let o=(r,s)=>t(e.map((d,a)=>a===r?{...d,...s}:d));return Q("div",{className:"flex flex-col gap-3",children:[e.map((r,s)=>{let d=n.includes(r.id);return Q("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:[V("input",{"aria-label":`Field ${s+1} name`,placeholder:"Display name",value:r.name,onChange:(a)=>o(s,{name:a.target.value})}),V("input",{"aria-label":`Field ${s+1} ID`,placeholder:"field_id",value:r.id,disabled:d,onChange:(a)=>o(s,{id:a.target.value})}),V("select",{"aria-label":`Field ${s+1} type`,className:"rounded-md border bg-background px-2 text-sm",value:r.type,disabled:d,onChange:(a)=>{let m=a.target.value,p={id:r.id,name:r.name,type:m,required:ke({type:m})?!1:r.required??!1};if(m==="formula")p.formula={expression:""};if(m==="rollup")p.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(m==="singleSelect"||m==="multipleSelect")p.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((c,y)=>y===s?p:c))},children:lr.map((a)=>V("option",{value:a.value,children:a.name},a.value))}),Q("div",{className:"flex items-center gap-2",children:[Q("label",{className:"flex items-center gap-1 text-xs",children:[V("input",{type:"checkbox",checked:r.required??!1,disabled:d||n.length>0||ke(r),onChange:(a)=>o(s,{required:a.target.checked})}),"Required"]}),!d&&V("button",{type:"button",onClick:()=>t(e.filter((a,m)=>m!==s)),children:"Remove"})]}),(r.type==="singleSelect"||r.type==="multipleSelect")&&V("input",{className:"md:col-span-4","aria-label":`Field ${s+1} options`,placeholder:"Open, Done",value:r.options?.map((a)=>a.name).join(", ")??"",disabled:d,onChange:(a)=>o(s,{options:a.target.value.split(",").map((m,p)=>({id:m.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${p}`,name:m.trim()})).filter((m)=>m.name)})}),r.type==="linkedRecord"&&Q("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Q("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",Q("select",{className:"min-w-0 max-w-full","aria-label":`Field ${s+1} linked collection`,value:r.link?.collectionId??"",disabled:d,onChange:(a)=>{let m=i.find((p)=>p.id===a.target.value);o(s,{link:{collectionId:a.target.value,displayFieldId:m?.fields.find((p)=>p.type==="singleLineText"||p.type==="longText")?.id??""}})},children:[V("option",{value:"",children:"Choose collection…"}),i.map((a)=>V("option",{value:a.id,children:a.name},a.id))]})]}),Q("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",Q("select",{className:"min-w-0 max-w-full","aria-label":`Field ${s+1} record label`,value:r.link?.displayFieldId??"",disabled:d||!r.link?.collectionId,onChange:(a)=>o(s,{link:{collectionId:r.link?.collectionId??"",displayFieldId:a.target.value}}),children:[V("option",{value:"",children:"Choose text field…"}),i.find((a)=>a.id===r.link?.collectionId)?.fields.filter((a)=>a.type==="singleLineText"||a.type==="longText").map((a)=>V("option",{value:a.id,children:a.name},a.id))]})]})]}),r.type==="lookup"&&Q("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Q("label",{children:["Through linked field"," ",Q("select",{"aria-label":`Field ${s+1} lookup link`,value:r.lookup?.linkFieldId??"",disabled:d,onChange:(a)=>o(s,{lookup:{linkFieldId:a.target.value,targetFieldId:""}}),children:[V("option",{value:"",children:"Choose linked field…"}),e.filter((a)=>a.type==="linkedRecord"&&a.link).map((a)=>V("option",{value:a.id,children:a.name},a.id))]})]}),Q("label",{children:["Read target field"," ",Q("select",{"aria-label":`Field ${s+1} lookup target`,value:r.lookup?.targetFieldId??"",disabled:d||!r.lookup?.linkFieldId,onChange:(a)=>o(s,{lookup:{linkFieldId:r.lookup?.linkFieldId??"",targetFieldId:a.target.value}}),children:[V("option",{value:"",children:"Choose target field…"}),i.find((a)=>a.id===e.find((m)=>m.id===r.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((a)=>!ke(a)&&a.type!=="linkedRecord").map((a)=>V("option",{value:a.id,children:a.name},a.id))]})]}),V("small",{children:"Computed from linked records. Values cannot be edited."})]}),r.type==="formula"&&Q("div",{className:"flex flex-col gap-1 md:col-span-4",children:[Q("label",{children:["Formula",V("textarea",{"aria-label":`Field ${s+1} formula`,maxLength:2048,className:"min-h-16 w-full rounded-md border bg-background p-2",placeholder:"{quantity} * {price}",value:r.formula?.expression??"",onChange:(a)=>o(s,{formula:{expression:a.target.value}})})]}),V("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."}),Q("small",{children:["References:"," ",e.filter((a)=>a.id!==r.id&&(a.type==="singleLineText"||a.type==="longText"||a.type==="date"||a.type==="number"||a.type==="formula"||a.type==="rollup")).map((a)=>`{${a.id}}`).join(", ")||"None yet"]})]}),r.type==="rollup"&&Q("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Q("label",{children:["Through linked field"," ",Q("select",{"aria-label":`Field ${s+1} rollup link`,value:r.rollup?.linkFieldId??"",onChange:(a)=>o(s,{rollup:{linkFieldId:a.target.value,targetFieldId:"",function:r.rollup?.function??"sum"}}),children:[V("option",{value:"",children:"Choose linked field…"}),e.filter((a)=>a.type==="linkedRecord"&&a.link).map((a)=>V("option",{value:a.id,children:a.name},a.id))]})]}),Q("label",{children:["Aggregate"," ",Q("select",{"aria-label":`Field ${s+1} rollup function`,value:r.rollup?.function??"sum",onChange:(a)=>{let m=a.target.value,p=i.find((c)=>c.id===e.find((y)=>y.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((c)=>c.id===r.rollup?.targetFieldId);o(s,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:m==="count"||p?.type==="number"?r.rollup?.targetFieldId??"":"",function:m}})},children:[V("option",{value:"sum",children:"Sum"}),V("option",{value:"average",children:"Average"}),V("option",{value:"min",children:"Minimum"}),V("option",{value:"max",children:"Maximum"}),V("option",{value:"count",children:"Count values"})]})]}),Q("label",{children:["Target field"," ",Q("select",{"aria-label":`Field ${s+1} rollup target`,value:r.rollup?.targetFieldId??"",disabled:!r.rollup?.linkFieldId,onChange:(a)=>o(s,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:a.target.value,function:r.rollup?.function??"sum"}}),children:[V("option",{value:"",children:"Choose target field…"}),i.find((a)=>a.id===e.find((m)=>m.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((a)=>!ke(a)&&a.type!=="linkedRecord"&&(r.rollup?.function==="count"||a.type==="number")).map((a)=>V("option",{value:a.id,children:a.name},a.id))]})]}),V("small",{className:"w-full",children:"Null targets are skipped. Count counts values; empty sum/count are zero. Other empty aggregates have no result."})]})]},s)}),V("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 cr(e,t,n){if(ke(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 ut(e,Re(t),n)}function $a(e,t,n,i){let o=Object.create(null);for(let r of e){if(r.type==="lookup"||r.type==="formula"||r.type==="rollup"||r.type==="blob"||r.generation==="autoIncrement")continue;if(!Object.hasOwn(t,r.id)){if(r.required)throw Error(n("{name} is required.",{name:r.name}));continue}let s=t[r.id];if(r.type==="linkedRecord"){if(!Array.isArray(s)||s.some((d)=>typeof d!=="string")||s.length>100||new Set(s).size!==s.length)throw Error(n("{name} needs unique linked records.",{name:r.name}));if(r.required&&!s.length)throw Error(n("{name} is required.",{name:r.name}));o[r.id]=s;continue}if(r.type==="relation"){if(s==null||s===""){if(r.required)throw Error(n("{name} is required.",{name:r.name}));o[r.id]=null;continue}if(typeof s!=="string")throw Error(n("{name} needs a server-provided option.",{name:r.name}));o[r.id]=s;continue}if(r.required&&typeof s==="string"&&!s.trim())throw Error(n("{name} is required.",{name:r.name}));o[r.id]=Fe(Array.isArray(s)?s.join(","):String(s??""),r,i)}return o}function nn({fields:e,values:t,onChange:n,relationClient:i,linkedRecords:o,computedErrors:r,locale:s,ui:d,submitted:a=!1}){let m=Pe(s),p=sr();return V("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((c)=>{let y=c.description?.trim()??"",P=y?`${p}-${c.id}-hint`:void 0,w=cr(c,t[c.id],s??"en"),D=Boolean(c.required&&Re(t[c.id])===""&&w)&&!a?"":w,g=D?`${p}-${c.id}-error`:void 0,x=[P,g].filter(Boolean).join(" "),C={...x?{"aria-describedby":x}:{},...D?{"aria-invalid":!0}:{}};return Q("div",{className:"flex flex-col gap-1 text-sm",children:[Q("label",{htmlFor:`${p}-${c.id}`,children:[c.name,c.required?" *":""]}),y?V("p",{id:P,className:"m-0 text-xs opacity-70",children:y}):null,ke(c)?V("output",{id:`${p}-${c.id}`,"aria-label":m("{name} (read only)",{name:c.name}),...C,children:c.type==="lookup"?He(t[c.id]):tt(t[c.id],r?.[c.id],s)}):c.type==="linkedRecord"?V(Mt,{...s?{locale:s}:{},field:c,value:t[c.id],labels:o?.[c.id],client:i,onChange:(f)=>n({...t,[c.id]:f}),...C}):c.type==="checkbox"?V("input",{id:`${p}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,type:"checkbox",checked:t[c.id]===!0,onChange:(f)=>n({...t,[c.id]:f.target.checked}),...C}):c.type==="singleSelect"&&d?.Select?V(Yt,{ui:d,label:`${c.name}${c.required?" *":""}`,...C,value:String(t[c.id]??""),options:[{value:"",label:m("Choose…")},...(c.options??[]).map((f)=>({value:f.id,label:f.name}))],onChange:(f)=>n({...t,[c.id]:f||null})}):c.type==="multipleSelect"&&d?.MultiSelect?V(d.MultiSelect,{"aria-label":`${c.name}${c.required?" *":""}`,...C,options:(c.options??[]).map((f)=>({value:f.id,label:f.name,slot:Ft(c.options,f.id)})),values:Array.isArray(t[c.id])?t[c.id]:[],placeholder:m("Choose…"),onChange:(f)=>n({...t,[c.id]:f})}):c.type==="singleSelect"||c.type==="multipleSelect"?Q("select",{id:`${p}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...C,className:"min-h-9 rounded-md border bg-background p-2",multiple:c.type==="multipleSelect",value:c.type==="multipleSelect"?Array.isArray(t[c.id])?t[c.id]:[]:String(t[c.id]??""),onChange:(f)=>n({...t,[c.id]:c.type==="multipleSelect"?Array.from(f.target.selectedOptions,(_)=>_.value):f.target.value||null}),children:[c.type==="singleSelect"&&V("option",{value:"",children:m("Choose…")}),c.options?.map((f)=>V("option",{value:f.id,children:f.name},f.id))]}):c.type==="date"&&d?.DatePicker?(()=>{let f={kind:Dt(c),timeZone:qe(c)?.timeZone},_=String(t[c.id]??"");return V(d.DatePicker,{id:`${p}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...C,value:Bt(_,f),withTime:f.kind==="auto"?Ne(_):f.kind==="datetime",fixedKind:f.kind!=="auto",clearable:!c.required,onChange:(T)=>n({...t,[c.id]:T?Ut(T,_,f):null})})})():c.type==="longText"?V("textarea",{id:`${p}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...C,className:"rounded-md border bg-background p-2",value:String(t[c.id]??""),onChange:(f)=>n({...t,[c.id]:f.target.value||null})}):V("input",{id:`${p}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...C,className:"min-h-9 min-w-0 rounded-md border bg-background p-2",type:c.type==="number"?"number":c.type==="date"?"date":"text",step:c.type==="number"?"any":void 0,value:c.type==="date"?String(t[c.id]??"").slice(0,10):String(t[c.id]??""),onChange:(f)=>n({...t,[c.id]:f.target.value===""?null:c.type==="number"?Number(f.target.value):c.type==="date"&&t[c.id]?Vt(t[c.id],f.target.value):f.target.value})}),D?V("span",{id:g,className:"text-xs text-red-600",children:D}):null]},c.id)})})}function dr(e,t,n){if(t==="isEmpty")return;let i=ke(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 o=Number(n);if(!n.trim()||!Number.isFinite(o))throw Error("Filter needs a number.");return o}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(ke(e)&&!Ge(e))throw Error("Computed filters are not available for this field.");if((e.type==="multipleSelect"||e.type==="linkedRecord")&&t!=="contains")return n.split(",").map((o)=>o.trim());return n}function ja({fields:e,view:t,onChange:n,onError:i}){let o=e.filter(Ge),[r,s]=bt(o[0]?.id??""),d=o.some((g)=>g.id===r)?r:o[0]?.id??"",[a,m]=bt("contains"),p=d?(()=>{let g=e.find((x)=>x.id===d);return g&&ke(g)?g.resultType:g?.type})():void 0,c=p==="number"?["is","isNot","isEmpty"]:p==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],y=c.includes(a)?a:p==="number"||p==="date"?"is":"contains",[P,w]=bt(""),D=[...t.columnOrder.flatMap((g)=>{let x=e.find((C)=>C.id===g);return x?[x]:[]}),...e.filter((g)=>!t.columnOrder.includes(g.id))];return Q("div",{className:"flex flex-wrap items-end gap-3",children:[Q("label",{className:"flex min-w-52 flex-col gap-1 text-sm",children:["Search",V("input",{type:"search",className:"min-h-9 min-w-0 rounded-md border bg-background p-2",value:t.search??"",onChange:(g)=>n({...t,search:g.target.value})})]}),Q("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(g)=>{g.preventDefault();let x=e.find((f)=>f.id===d);if(!x)return;let C;try{C=dr(x,y,P)}catch(f){i(f instanceof Error?f.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:d,operator:y,...y==="isEmpty"?{}:{value:C}}]}})},children:[Q("label",{className:"flex flex-col gap-1 text-sm",children:["Filter field",V("select",{className:"h-9 rounded-md border bg-background px-2",value:d,onChange:(g)=>s(g.target.value),children:o.map((g)=>V("option",{value:g.id,children:g.name},g.id))})]}),V("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:y,onChange:(g)=>m(g.target.value),children:c.map((g)=>V("option",{value:g,children:g==="isNot"?"is not":g==="isEmpty"?"is empty":g==="onOrAfter"?"on or after":g},g))}),y!=="isEmpty"&&V("input",{type:p==="number"?"number":p==="date"?"date":"text",step:p==="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:(g)=>w(g.target.value)}),V("button",{type:"submit",disabled:!d,children:"Apply filter"}),V("button",{type:"button",onClick:()=>{let g={...t};delete g.filter,n(g)},children:"Clear filter"})]}),Q("details",{className:"relative",children:[V("summary",{className:"cursor-pointer rounded-md border px-3 py-2 text-sm",children:"Columns"}),V("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:D.map((g,x)=>Q("div",{className:"flex items-center gap-2 text-sm",children:[Q("label",{className:"flex flex-1 items-center gap-2",children:[V("input",{type:"checkbox",checked:!t.hiddenColumns.includes(g.id),disabled:t.type==="form"&&g.required===!0,onChange:(C)=>n({...t,hiddenColumns:C.target.checked?t.hiddenColumns.filter((f)=>f!==g.id):[...t.hiddenColumns,g.id]})}),g.name]}),V("button",{type:"button","aria-label":`Move ${g.name} left`,disabled:x===0,onClick:()=>{let C=D.map((_)=>_.id),f=C[x-1];if(f!==void 0)[C[x-1],C[x]]=[g.id,f];n({...t,columnOrder:C})},children:"←"}),V("button",{type:"button","aria-label":`Move ${g.name} right`,disabled:x===D.length-1,onClick:()=>{let C=D.map((_)=>_.id),f=C[x+1];if(f!==void 0)[C[x],C[x+1]]=[f,g.id];n({...t,columnOrder:C})},children:"→"})]},g.id))})]})]})}export{ar as CollectionAiControls,Qn as CollectionAttachments,nr as CollectionAutomationControls,Kn as CollectionConversionControls,Wn as CollectionLiveChanges,ja as CollectionQueryControls,Jn as CollectionRecordActivity,er as CollectionShareControls,jn as CollectionTransferControls,qa as FieldDefinitions,nn as RecordFields,dr as filterValueForField,$a as validateDraft};
|
|
1
|
+
import{useId as Fr,useState as It}from"react";function Or(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var Dt=["blue","green","red","orange","gray","teal","purple"];function xn(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 St(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 o=n.find((c)=>c.id===i.fieldId),a=o?.type==="number"||o?.type==="rating"||o?.type==="autoNumber"?e.reduce((c,s)=>c+(xn(s.values[i.fieldId])??0),0):0;return{fieldId:i.fieldId,fn:"sum",value:a}})}function At(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function kn(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function vn(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 Et(e,t){if(!t)return!0;if(At(t)){let n=t.filterSet.map((i)=>At(i)?Et(e,i):kn(i)?vn(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 Tt(e,t,n,i){let o=e.views.find((P)=>P.id===n)??e.views[0];if(!o)return{view:{id:n,name:n,kind:"table"},columns:e.fields,rows:[...t]};let r=[...t];if(o.filter)r=r.filter((P)=>Et(P,o.filter));if(o.sort?.length)r.sort((P,R)=>{for(let D of o.sort??[]){let S=P.values[D.fieldId],m=R.values[D.fieldId];if(S===m)continue;if(S==null)return 1;if(m==null)return-1;let v=e.fields.find((_)=>_.id===D.fieldId)?.type,h=(_)=>{if(["number","rating","autoNumber"].includes(v??"")&&typeof _==="number")return _;if(["date","createdTime","lastModifiedTime"].includes(v??"")){let I=Date.parse(String(_));if(Number.isFinite(I))return I}return String(_)},y=h(S),M=h(m);if(y===M)continue;let A=y<M?-1:1;return D.direction==="desc"?-A:A}return P.id<R.id?-1:P.id===R.id?0:1});let a=o.projection?.length?e.fields.filter((P)=>o.projection?.includes(P.id)):e.fields,c=i?.search?.trim().toLowerCase();if(c)r=r.filter((P)=>a.some((R)=>String(P.values[R.id]??"").toLowerCase().includes(c)));let s=St(r,o.aggregates,e.fields),f=o.group?.fieldId;if(!f)return{view:o,columns:a,rows:r,...s.length?{aggregates:s}:{}};let u=[],l=new Map;for(let P of r){let R=String(P.values[f]??"");if(!l.has(R))l.set(R,[]),u.push(R);l.get(R)?.push(P)}let C=u.map((P)=>{let R=l.get(P)??[];return{key:P,fieldId:f,rows:R,aggregates:St(R,o.aggregates,e.fields)}});return{view:o,columns:a,rows:r,groups:C,...s.length?{aggregates:s}:{}}}var Pn=500,wn=2000,Rn=new Set(["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"]);function Pe(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function et(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 Kr=["short","medium","tall","extra"];function Yr(e,t){return t.map((n)=>{let i={},o={};for(let r of e.groupBy){let a=n[r];if(!(r in n)||a!==null&&typeof a!=="string"&&typeof a!=="number"&&typeof a!=="boolean")throw Error(`Invalid aggregate group ${r}.`);i[r]=a}for(let{as:r,fn:a}of e.aggregates){let c=n[r];if(!(r in n)||c!==null&&!(typeof c==="number"&&Number.isFinite(c))&&!((a==="min"||a==="max")&&typeof c==="string"&&Number.isFinite(Date.parse(c))))throw Error(`Invalid aggregate value ${r}.`);o[r]=c}return{groups:i,values:o}})}var In=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,Sn=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function Wr(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function he(e,t){return{code:e,...t}}function An(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function yt(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function Gr(e,t){if(t.aggregates.length===0)return he("empty");if(t.aggregates.length>8||t.groupBy.length>3)return he("too_many");let n=new Set;for(let o of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(o.fn))return he("function");if(!In.test(o.as)||n.has(o.as)||t.groupBy.includes(o.as))return he("alias",{alias:o.as,...o.fieldId!==void 0?{fieldId:o.fieldId}:{}});if(n.add(o.as),o.fn==="count"&&o.fieldId===void 0)continue;let r=e.fields.find((a)=>a.id===o.fieldId);if(!r)return he(o.fn==="sum"?"sum_field":"unknown_field",{alias:o.as,...o.fieldId!==void 0?{fieldId:o.fieldId}:{}});if(o.fn==="sum"&&!yt(r))return he("sum_field",{fieldId:r.id,alias:o.as});if(o.fn==="avg"&&!yt(r))return he("numeric_field",{fieldId:r.id,alias:o.as});if((o.fn==="min"||o.fn==="max")&&!yt(r)&&r.type!=="date"&&!((r.type==="formula"||r.type==="rollup")&&r.resultType==="date"))return he("extrema_field",{fieldId:r.id,alias:o.as});if((o.fn==="filled"||o.fn==="empty")&&!et(r))return he("queryable_field",{fieldId:r.id,alias:o.as});if(o.fn==="count"&&!et(r))return he("count_field",{fieldId:r.id,alias:o.as})}let i=new Set;for(let o of t.groupBy){if(i.has(o))return he("duplicate_group",{fieldId:o});i.add(o);let r=e.fields.find((a)=>a.id===o);if(!r)return he("unknown_field",{fieldId:o});if(!Sn.has(r.type)&&!An(r))return he("not_groupable",{fieldId:o})}return null}var Ft=(e)=>String(e).padStart(2,"0");function Ae(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=(o)=>Number(n.find((r)=>r.type===o)?.value??0);return{year:i("year"),month:i("month"),day:i("day"),hour:i("hour"),minute:i("minute"),second:i("second")}}function Ue(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 o=0;o<2;o++){let r=Ae(new Date(i),t),a=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second);i+=n-a}return new Date(i)}function at(e,t){let n=Ae(e,t??"UTC");return`${n.year}-${Ft(n.month)}-${Ft(n.day)}`}var Dn=/^[a-z][a-z0-9_-]{0,31}$/,st=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function Nt(e){if(!e||e.length>2048||/\s/.test(e))return!1;for(let n=0;n<e.length;n++)if(e.charCodeAt(n)<32||e.charCodeAt(n)===127)return!1;if(e.startsWith("/"))return!e.startsWith("//")&&!e.startsWith("/\\");let t=/^([a-z][a-z0-9+.-]*):/i.exec(e)?.[1]?.toLowerCase();if(t==="http"||t==="https")try{return Boolean(new URL(e).hostname)}catch{return!1}return t==="mailto"||t==="tel"}function En(e){if(!st(e))return"hyperlink must be an object";if(Object.keys(e).some((t)=>t!=="url"&&t!=="text"&&t!=="ref"))return"hyperlink has unknown keys";if(typeof e.url!=="string"||!Nt(e.url))return"hyperlink URL is invalid";if(e.text!==void 0&&(typeof e.text!=="string"||e.text.length>500))return"hyperlink text is invalid";if(e.ref!==void 0){let t=e.ref;if(!st(t)||Object.keys(t).length!==2||typeof t.kind!=="string"||!Dn.test(t.kind)||typeof t.id!=="string"||!t.id||t.id.length>200)return"hyperlink reference is invalid"}return null}var Ye=(e)=>En(e)===null;function tt(e){if(!st(e)||typeof e.url!=="string")return"";return typeof e.text==="string"&&e.text.trim()?e.text:e.url}function Mt(e){if(!st(e)||typeof e.url!=="string")return"";let t=typeof e.text==="string"?e.text.trim():"";return t&&t!==e.url?`[${t.replace(/[[\]]/g,"")}](${e.url})`:e.url}function qe(e){let t=e.trim();if(!t)return null;if(t.startsWith("{"))try{let r=JSON.parse(t);return Ye(r)?r:null}catch{return null}let n=/^\[([^\]]*)\]\((\S+)\)$/.exec(t)??/^(.*?)\s*<(\S+)>$/.exec(t),i=n?.[1]?.trim().slice(0,500)??"",o=n?.[2]??t;if(!/^[a-z][a-z0-9+.-]*:/i.test(o)&&!o.startsWith("/")){if(/^[\w-]+(\.[\w-]+)+(:\d+)?([/?#]\S*)?$/.test(o))o=`https://${o}`;else if(/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(o))o=`mailto:${o}`}if(!Nt(o))return null;return i&&i!==o?{url:o,text:i}:{url:o}}function ro(e,t=new Date,n){let i={};for(let o of e){let r=o.defaultValue;if(!r)continue;if(r.kind==="value")i[o.id]=Array.isArray(r.value)?[...r.value]:r.value;else if(o.type==="date"){let a=o.formatting;if(a&&"time"in a&&a.time==="none"){let c=Ae(t,n);i[o.id]=`${c.year}-${String(c.month).padStart(2,"0")}-${String(c.day).padStart(2,"0")}`}else i[o.id]=t.toISOString()}}return i}var Tn=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],Fn=new Set(["pastDays","nextDays","daysAgo","daysFromNow"]),Lt={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"]},Nn=new Set(["isEmpty","isNotEmpty"]);function Ot(e){switch(e.type){case"singleLineText":case"longText":case"hyperlink":return"text";case"number":return"number";case"checkbox":return"checkbox";case"date":return"date";case"singleSelect":return"singleSelect";case"multipleSelect":return"multipleSelect";case"relation":return"relation";case"formula":case"rollup":return e.resultType==="text"?"text":e.resultType==="number"?"number":e.resultType==="date"?"date":null;default:return null}}function ao(e){let t=Ot(e);return t?Lt[t]:[]}var bt=/^\d{4}-\d{2}-\d{2}$/,Mn=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function Ln(e){if(!Mn(e))return!1;let t=e.mode;if(!Tn.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&&bt.test(e.date);if(t==="dateRange")return typeof e.date==="string"&&bt.test(e.date)&&typeof e.to==="string"&&bt.test(e.to)&&e.date<=e.to;if(Fn.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function so(e,t){if(!e)return"unknown field";let n=Ot(e),i=t.operator==="contains"&&(n==="number"||n==="checkbox"||n==="date"||n==="singleSelect");if(!n||!(Lt[n].includes(t.operator)||i))return"operator not allowed";if(Nn.has(t.operator))return null;let o=t.value;if(i)return n==="number"?typeof o==="number"&&Number.isFinite(o)?null:"number required":n==="checkbox"?typeof o==="boolean"?null:"boolean required":typeof o==="string"?null:"text required";switch(n){case"text":return typeof o==="string"?null:"text value required";case"number":return typeof o==="number"&&Number.isFinite(o)?null:"number required";case"checkbox":return typeof o==="boolean"?null:"boolean required";case"singleSelect":return typeof o==="string"?null:"option required";case"relation":return typeof o==="string"&&o!==""?null:"record required";case"multipleSelect":return typeof o==="string"||Array.isArray(o)&&o.every((r)=>typeof r==="string")?null:"options required";case"date":return Ln(o)||typeof o==="string"&&Number.isFinite(Date.parse(o))?null:"date required"}}var On={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},To=Array.from(new Set(Object.values(On).flat()));var Mo=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 Vn(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function Bo(e,t){if(t===e.draft)return e;return{...e,draft:t}}function _n(e){return e.draft!==e.savedContent}function Uo(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 qo(e,t){if(_n(e))return e;let n=Vn(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 Ee=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),$e=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),je=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,Vt=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,lt=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),_t=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every(lt)&&new Set(e).size===e.length;function Bn(e){if(!Ee(e)||!$e(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!lt(e.id)||!je(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)=>!Ee(t)||!$e(t,["id","name"])||!lt(t.id)||!je(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 o=e[n];if(e.type===t!==(o!==void 0))return!1;if(o!==void 0&&(!Ee(o)||!$e(o,[...i])||i.some((r)=>!je(o[r],r==="expression"?2048:512))))return!1}return!0}function jo(e){if(!Ee(e)||!$e(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))||!je(e.collectionId,512)||!je(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(!Ee(t)||!$e(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!je(t.name,200)||!Vt(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(Bn)||new Set(t.fields.map((r)=>r.id)).size!==t.fields.length)return!1;if(!Ee(n)||!$e(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!lt(n.id)||!je(n.name,200)||!Vt(n.version)||!_t(n.columnOrder)||!_t(n.hiddenColumns)||!Ee(n.columnWidths)||Object.values(n.columnWidths).some((r)=>typeof r!=="number"||!Number.isInteger(r)||r<72||r>800))return!1;let i=t.fields,o=(r)=>i.some((a)=>Ee(a)&&a.id===r);if([...n.columnOrder,...n.hiddenColumns,...Object.keys(n.columnWidths)].some((r)=>!o(r)))return!1;if(n.type!==void 0&&!["grid","kanban","gallery","calendar","form"].includes(String(n.type)))return!1;if(n.type==="kanban"&&!t.fields.some((r)=>r.id===n.groupByFieldId&&["singleSelect","checkbox"].includes(r.type)))return!1;if(n.type==="calendar"&&!t.fields.some((r)=>r.id===n.dateFieldId&&r.type==="date"))return!1;if(n.search!==void 0&&(typeof n.search!=="string"||n.search.length>200))return!1;if(n.sort!==void 0&&(!Array.isArray(n.sort)||n.sort.length>4||n.sort.some((r)=>!Ee(r)||!$e(r,["fieldId","direction"])||!o(r.fieldId)||!["asc","desc"].includes(String(r.direction)))))return!1;return!0}var Re=(e)=>String(e).padStart(2,"0"),Un=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function He(e){let t=e.formatting;return Un(e)&&t&&"date"in t?t:void 0}function Bt(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function Ut(e){let t=He(e);return!t?"auto":t.time==="none"?"date":"datetime"}function Ct(e,t,n,i){switch(i){case"YYYY/MM/DD":return`${e}/${Re(t)}/${Re(n)}`;case"MM/DD/YYYY":return`${Re(t)}/${Re(n)}/${e}`;case"DD/MM/YYYY":return`${Re(n)}/${Re(t)}/${e}`;case"YYYY年M月D日":return`${e}年${t}月${n}日`;default:return`${e}-${Re(t)}-${Re(n)}`}}function qt(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 Ct(Number(i[1]),Number(i[2]),Number(i[3]),t.date);let c=new Date(n);if(!Number.isFinite(c.getTime()))return n;let s=Ae(c,t.timeZone??"UTC");return Ct(s.year,s.month,s.day,t.date)}let o=i?Ue({year:Number(i[1]),month:Number(i[2]),day:Number(i[3])},t.timeZone):new Date(n);if(!Number.isFinite(o.getTime()))return n;let r=Ae(o,t.timeZone),a=Ct(r.year,r.month,r.day,t.date);if(t.time==="12h"){let c=r.hour%12||12;return`${a} ${c}:${Re(r.minute)} ${r.hour<12?"AM":"PM"}`}return`${a} ${Re(r.hour)}:${Re(r.minute)}`}function $t(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 jt(e,t){let n=e?.findIndex((r)=>r.id===t)??-1,i=n>=0?e?.[n]?.color:void 0,o=Dt.findIndex((r)=>r===i);return o>=0?o:n}var qn={"AI fill":"AI 填充","AI field":"AI 字段","Generate {name} with AI":"AI 生成「{name}」","Only records with empty target cells":"只处理目标为空的记录","No records have empty target cells.":"没有目标为空的记录。","AI settings of field {name}":"字段 {name} 的 AI 设置","Generate this field with AI":"用 AI 生成此字段","Generate when a record is created":"新建记录时自动生成","AI auto-fill stopped: {message}":"AI 自动生成中断:{message}",Hyperlink:"超链接","Search or paste a link":"搜索文档或粘贴链接","Use link {url}":"使用链接 {url}","Display text":"显示文字","Remove link":"移除链接","Link suggestions":"链接建议","Searching…":"搜索中…","No matching resources":"没有匹配的内容","{name} needs a link.":"{name}需要有效链接(http(s)、邮箱或站内路径)。","Link targets":"可选的链接目标","None chosen offers every kind.":"都不选则提供全部类型。","AI prompt":"AI 提示词","e.g. Summarize the description in one sentence":"例如:用一句话概括描述","Fields the AI reads (none = all)":"AI 读取的字段(不选则读取全部)","AI reads {name}":"AI 读取 {name}","All records in this view ({count})":"当前视图全部记录({count})","Generating batch {done} of {total}…":"正在生成第 {done}/{total} 批…","{count} records could not be processed: {reason}":"{count} 条记录处理失败:{reason}","Retry failed":"重试失败批次",Close:"关闭","Records in scope":"记录范围","Selected records ({count})":"已选记录({count})","Loaded records ({count})":"已载入记录({count})","Fields to fill":"要填充的字段",Instruction:"指令","Describe what to fill or change":"描述要填写或修改的内容","Fill empty cells":"补全空白","Fill the empty target cells using the other fields of the same record.":"根据同一条记录的其他字段,补全目标字段中的空白单元格。","Translate to English":"翻译成英文","Translate the target fields into English and keep proper nouns.":"把目标字段翻译成英文,专有名词保持原样。",Summarize:"生成摘要","Write a one-sentence summary of each record for the target fields.":"为每条记录在目标字段中写一句话摘要。",Classify:"自动归类","Pick the best matching option for each record from the allowed options.":"为每条记录从可选项中选择最匹配的一项。",Model:"模型",Suggestions:"建议","{count} suggested changes":"{count} 处建议修改","Select all":"全选","Select none":"全不选","No changes were suggested.":"没有需要修改的内容。","(empty)":"(空)","Generating suggestions…":"正在生成建议…",Stop:"停止","Apply {count} changes":"应用 {count} 处修改",Regenerate:"重新生成","Generate preview":"生成预览","Applied {count} AI changes":"已应用 {count} 处 AI 修改","AI changes undone":"已撤销 AI 修改",Undo:"撤销","Some records changed since the preview. Generate again to review the latest values.":"部分记录在预览后已被修改,请重新生成以查看最新内容。","Loaded records fallback: {value}":"已载入记录兜底:{value}","That summary function is not supported.":"不支持该汇总函数。","Average only a number field.":"只能对数字字段求平均值。","Minimum and maximum need a number or date field.":"最大值和最小值需要数字或日期字段。","Summarize a queryable field.":"请选择可查询字段汇总。","Select row":"选择行","Select all loaded records":"全选已载入记录","{count} selected":"已选择 {count} 条","Column color":"整列填色","Column color for {name}":"{name}整列填色","Column color {number}":"列色 {number}","No color":"无色","Fill selection":"拖拽填充","Fill at most 100 rows at once.":"一次最多 100 行","Filled {count} cells":"已填充 {count} 个单元格","Skipped {count} cells":"已跳过 {count} 个不可填充单元格","Table not found":"数据表不存在或不可访问","View not found":"视图不存在或不可访问","{count} records total":"共 {count} 条","Row height":"行高","Row height short":"紧凑","Row height medium":"中等","Row height tall":"较高","Row height extra":"超高","Sort {index}":"排序 {index}","Move sort {index} up":"上移排序 {index}","Move sort {index} down":"下移排序 {index}","Remove sort {index}":"删除排序 {index}","Add sort":"添加排序","Clear sort":"清除排序","Default order":"默认顺序",Match:"满足","all conditions":"全部条件","any condition":"任一条件","Filter conjunction":"条件关系","Condition {index}":"条件 {index}","Remove condition {index}":"删除条件 {index}","{count} grouped conditions are kept.":"另有 {count} 组嵌套条件保持不变。",Remove:"移除","Finish the highlighted condition to apply it.":"补全未完成的条件后才会生效。","Add condition":"添加条件","Add group":"添加条件组","Condition group {index}":"条件组 {index}","Remove group {index}":"删除条件组 {index}","Clear filter":"清除筛选","Filter value":"筛选值","Filter field":"筛选字段","Filter operator":"筛选条件","Date mode":"日期方式","From date":"起始日期","To date":"结束日期","Number of days":"天数","Choose option":"选择选项",Format:"格式","Format of field {name}":"字段{name}的格式","Defaults of field {name}":"字段{name}的默认值","Date format":"日期格式","Time format":"时间格式","Time zone":"时区","Viewer's time zone":"跟随查看者","No time (date only)":"不含时间(仅日期)","24-hour":"24 小时制","12-hour":"12 小时制",Preview:"预览","Default value":"默认值",Empty:"空","Current date and time":"当前日期和时间","Number style":"数字样式",Percent:"百分比",Currency:"货币","Decimal places":"小数位数","Thousands separator":"千分位分隔","Checked by default":"默认勾选","Default option {name}":"默认选中{name}","Colour of option {index}":"选项 {index} 的颜色","Colour blue":"蓝","Colour green":"绿","Colour red":"红","Colour orange":"橙","Colour gray":"灰","Colour teal":"青","Colour purple":"紫","Unsaved changes":"修改未保存","Your edit":"我的修改","Server value":"服务端当前值","Record ID":"记录 ID","Record ID {id}":"记录 ID {id}",Row:"序号","Generated automatically":"自动生成","{name} is auto-generated and cannot be edited.":"{name}由系统自动生成,不能手动修改。","Saving failed. Your edit has been kept.":"保存失败,修改已保留。",Saved:"已保存","Invalid value":"输入值无效","{name} is read-only; its original bytes are preserved.":"{name}为只读字段,原始文件内容保持不变。","{name} needs a server-provided option.":"{name}需要由服务端提供可选项。","{name} is read only.":"{name}为只读字段。","Use the {name} record picker.":"请使用{name}记录选择器。","{name} needs a number.":"{name}需要有效数字。","{name} needs valid JSON.":"{name}必须是有效 JSON。","{name} needs an integer.":"{name}必须是整数。","{name} needs true or false.":"{name}请选择是或否。","{name} needs a date.":"{name}需要有效日期。","{name} needs a valid calendar date.":"{name}需要有效日期。","{name} has no option '{option}'.":"{name}没有名为“{option}”的选项。","Paste is too large.":"粘贴内容过大。","Paste must fit within the loaded page and contain at most 100 rows.":"粘贴内容必须位于当前已加载页内,且最多包含 100 行。","Paste extends beyond the visible columns.":"粘贴内容超出可见列范围。","Row is not loaded.":"目标行尚未加载。","Unclosed quoted cell.":"粘贴内容中的引号没有闭合。","Invalid paste.":"粘贴内容无效。","Edit {name}":"编辑 {name}","{name} editor":"{name}编辑器","Sorting is unavailable for this field":"此字段暂不支持排序","Clear selection":"清空选择","{id} (unavailable)":"{id}(选项已移除)","Select at most 100 rows per delete.":"每次最多删除 100 条记录。","{total} records · {loaded} loaded":"共 {total} 条 · 已载入 {loaded} 条","Arrows · Shift select · Enter edit · Copy / paste":"方向键移动 · Shift 多选 · Enter 编辑 · 复制 / 粘贴","Arrows · Shift select · Copy":"方向键移动 · Shift 多选 · 复制","Delete selected rows":"删除所选记录","{name} records":"{name} 数据表","Resize {name}":"调整 {name} 列宽","Saving…":"保存中…","Save edit":"保存修改","Cancel edit":"取消修改","Confirm bulk change":"确认批量修改","Apply {count} row changes in one transaction?":"确认一次性提交 {count} 条记录的修改?","If any record changed or any value is invalid, all changes are rejected.":"如有记录版本冲突或输入值无效,整批修改将不提交。","Confirm changes":"确认修改","Cancel changes":"取消修改","Current server version {version}":"服务端当前版本 {version}","Retry against current version":"按当前版本重试","Saving failed. Your draft has been kept.":"保存失败,草稿已保留。","Choose a text, checkbox or single select grouping field.":"请选择文本、复选框或单选字段作为看板分组。",Ungrouped:"未分组","Invalid grouping value":"分组值无效","Move {name}":"移动 {name}","Retry change":"重试修改","{name} is required.":"请填写 {name}。","No changes":"没有修改","{name} record":"{name} 记录","No value":"未选择",Yes:"是",No:"否","Save record":"保存记录","Create record":"新建记录","Search {name}":"搜索 {name}","No relation":"未关联","More {name} options":"加载更多 {name} 选项","Relation options unavailable.":"关联选项加载失败,请重试。","Relation option provider unavailable.":"暂时无法选择关联记录。","Collection query failed. Retry to load records.":"记录加载失败,请重试。","Previous page":"上一页","Next page":"下一页","Page {page}":"第 {page} 页","Loading records…":"正在加载记录…","Retry query":"重新加载","Saving failed. Your change has been kept.":"保存失败,已保留当前修改。","{name} needs unique linked records.":"{name}需要不重复的关联记录。","Change a field before saving.":"请先修改字段再保存。","Close record":"关闭记录","Delete record":"删除记录","Confirm record deletion":"确认删除记录","Delete this record? Your unsaved changes will be discarded after deletion.":"确定删除此记录?删除后将丢弃尚未保存的修改。","Confirm deletion":"确认删除","Cancel deletion":"取消删除","Record creation requires editor permission.":"新建记录需要编辑权限。","Creating…":"正在创建…","Record created.":"记录已创建。","Record created. Add another below.":"记录已创建,可继续新增。","Show records":"查看记录","Pending record move":"待处理的记录移动","Moving record…":"正在移动记录…","The move has been kept for retry.":"已保留移动请求,可重试。","Retry move":"重试移动","Cancel move":"取消移动","Choose a single-select or boolean grouping field.":"请选择单选或复选框分组字段。","Lane {name}":"分组{name}","Open {name}":"打开{name}","Move to":"移动至","No records in this lane.":"此分组暂无记录。","No records match this view.":"此视图暂无匹配记录。",Unassigned:"未分组","Choose a valid month.":"请选择有效月份。","Invalid initial month. Showing the current UTC month.":"初始月份无效,已显示当前月份。","Choose a valid month between years 1 and 9998.":"请选择 1 至 9998 年之间的有效月份。","Invalid date":"日期无效","Choose a date field for this calendar.":"请为日历选择日期字段。","Previous month":"上个月","Next month":"下个月",Today:"今天","Calendar month":"日历月份",Month:"月份","{year}-{month}":"{year} 年 {month} 月",Sun:"周日",Mon:"周一",Tue:"周二",Wed:"周三",Thu:"周四",Fri:"周五",Sat:"周六","Day {day}":"日期 {day}","No dated records match this month.":"本月暂无匹配的日期记录。","Move {name} to date":"将 {name} 移动至日期",Move:"移动",Grid:"表格",Kanban:"看板",Gallery:"画廊",Calendar:"日历",Form:"表单","View type":"视图类型","Group by":"分组依据","Grid grouping field":"表格分组字段","No grouping":"不分组","Hide fields":"隐藏字段","Field menu {name}":"{name} 字段菜单","Edit field":"修改字段","Field saved":"字段已保存","Field added":"字段已添加","Edit all fields":"批量编辑字段","Save field":"保存","Field name is required.":"请填写字段名。","Duplicate field":"复制字段","Hide field":"隐藏字段","Undo/redo recovery":"撤销/重做恢复","Retry undo/redo":"重试撤销/重做","Clear undo/redo history":"清除撤销/重做历史",Undone:"已撤销",Redone:"已重做","Duplicate {count} selected records":"复制所选 {count} 条记录","Add record below the table":"在表格末尾新增记录","Move to {name}":"移至 {name}","Delete this record?":"删除这条记录?","Filter by {name}":"按 {name} 筛选","Record details":"记录详情","Expand record":"展开记录","Select all rows":"全选记录",Summary:"统计","Auto summary":"自动计算","Footer record count":"{count} 条记录","No summary":"不统计","Footer count":"记录数","Footer filled":"已填写","Footer empty":"未填写","Footer sum":"求和","Footer avg":"平均值","Footer min":"最小值","Footer max":"最大值","Summaries cover the {count} loaded records.":"统计范围为已载入的 {count} 条记录。","Freeze up to this field":"冻结至此字段","Unfreeze columns":"取消冻结","Insert field left":"向左插入字段","Insert field right":"向右插入字段","Sort {name} ascending":"按 {name} 升序","Sort {name} descending":"按 {name} 降序","Group by {name}":"按 {name} 分组","Ungroup by {name}":"取消按 {name} 分组","Create kanban by {name}":"按 {name} 创建看板","Delete field “{name}”?":"删除字段“{name}”?","The field and its values in every record are removed. This cannot be undone.":"该字段及其在所有记录中的值都会被删除,且无法恢复。","Field duplicated":"已复制字段","Field deleted":"已删除字段","Deleted {count} records":"已删除 {count} 条记录","Delete {count} records?":"删除 {count} 条记录?","The selected records will be deleted. If any of them changed meanwhile, nothing is deleted.":"所选记录将被删除。若其中任一条记录已被他人修改,则整体取消、不会删除任何记录。","Search fields":"搜索字段","Reorder {name}":"拖动或按上下方向键调整 {name} 的顺序","No matching fields":"没有匹配的字段","Edit field {name}":"编辑字段 {name}","Field config":"字段配置","View config":"视图配置","{count} hidden fields":"已隐藏 {count} 个字段",Filter:"筛选",Group:"分组",Sort:"排序","{count} sorts":"{count} 项排序","Add grouping":"添加分组","Remove grouping":"移除分组","Hide {name}":"隐藏{name}","Show {name}":"显示{name}","Kanban grouping field":"看板分组字段","Date field":"日期字段","Calendar date field":"日历日期字段","Linked records are unavailable. Ask the host to connect this collection.":"关联记录不可用,请确认表格已连接。","Linked records could not be loaded. Retry to keep editing.":"关联记录加载失败,请重试后继续编辑。","{name} linked records":"{name}关联记录","Remove {name}":"移除 {name}","Search {name} records":"搜索 {name} 记录","Search linked records":"搜索关联记录","Loading linked records…":"加载关联记录…","Retry linked records":"重试加载关联记录","Link {name}":"关联 {name}","No matching records.":"没有匹配记录。","Previous linked records":"上一页关联记录","Next linked records":"下一页关联记录","{count} selected · up to 100 per record across all link fields":"已选择 {count} 项 · 每条记录的所有关联字段合计最多 100 项","{name} (read only)":"{name}(只读)","Choose…":"请选择…","Division by zero":"除数不能为零","Invalid computed value":"计算值无效","Computed value overflow":"计算值超出范围","Dependency failed":"依赖字段计算失败",Views:"视图","Add view":"添加视图","Rename view":"重命名视图","Duplicate view":"复制视图","Delete view":"删除视图","View name":"视图名称","View actions":"视图操作","Double click to rename":"双击重命名","Record actions":"记录操作","Copy cells":"复制所选单元格","Delete {count} selected records":"删除所选 {count} 条记录","Not set":"未设置",Checked:"已勾选",Unchecked:"未勾选","Expand group {name}":"展开分组 {name}","Collapse group {name}":"折叠分组 {name}","{count} records":"{count} 条","Collection fields":"表格字段","Field {name}":"字段 {name}","Field name":"字段名","Field description":"字段说明","Field type":"字段类型",Required:"必填","Delete field":"删除字段","Delete field {name}":"删除字段「{name}」","Options of field {name}":"字段 {name} 的选项",Options:"选项","Option name {index}":"选项名称 {index}","Delete option {index}":"删除选项 {index}",Delete:"删除","Add option":"新增选项","Add field":"新增字段","New field":"新字段","New option":"新选项","Single line text":"单行文本","Long text":"长文本",Number:"数字",Checkbox:"复选框",Date:"日期","Single select":"单选","Multiple select":"多选","Filter applied":"已应用筛选","Sort field":"排序字段","Sort direction":"排序方向",Default:"默认",Ascending:"升序",Descending:"降序",Columns:"列设置","Show row numbers":"显示行号","Show record IDs":"显示记录 ID","Move {name} left":"移动{name}到左侧","Move {name} right":"移动{name}到右侧",Tables:"数据表","New table":"新建数据表","Change table icon":"修改数据表图标","Table icon":"数据表图标","Double click to change the icon":"双击修改图标","Schema permission required":"需要数据结构管理权限","Table name":"数据表名称","Rename table {name}":"重命名数据表 {name}","Start with a table":"从一张数据表开始","{count} fields · {mode}":"{count} 个字段 · {mode}",Editable:"可编辑","Read only":"只读",Table:"表格",People:"人员",Business:"业务",List:"清单",Schedule:"日程",Inventory:"库存","Choose a table first.":"请先选择数据表。","Save view":"保存视图",Done:"完成","View settings":"视图设置","Save fields":"保存字段",Cancel:"取消",Refresh:"刷新","Search records":"搜索记录",Search:"搜索",Fields:"字段","Add record":"新增记录","Unsaved view changes":"视图设置未保存","Delete view “{name}”?":"删除视图「{name}」?","Reload records":"重新加载记录","Loading…":"加载中…","{name} copy":"{name} 副本",Name:"名称","New grid view":"新网格视图","New kanban view":"新看板视图","New gallery view":"新画廊视图","New calendar view":"新日历视图","New form view":"新表单视图","Create table":"创建数据表","Sum field":"求和字段","No sum":"不求和","Linked record":"关联记录","Related table":"关联数据表","Choose a related table":"选择关联表",Relations:"关联","{name} · inverse records":"{name} · 反向记录","No tables yet":"还没有数据表","All records":"全部记录","Loading summary…":"正在汇总…","No summary rows.":"没有汇总数据","The collection service is unavailable.":"数据服务暂不可用",none:"无","Choose a count or sum.":"请选择计数或求和。","Use at most three groups and eight summaries.":"最多使用三个分组和八项汇总。","That field is not in this collection.":"该字段不在此数据表中。","Group by a text, number, date, checkbox, or single select field.":"请按文本、数字、日期、复选框或单选字段分组。","Sum only a number field.":"只能对数字字段求和。","Count a queryable field, or omit the field to count records.":"请统计可查询字段,或不选字段以统计记录数。","Each summary needs its own name, different from the group fields.":"每项汇总需要独立名称,且不能与分组字段重名。","Each group field can be used once.":"每个分组字段只能使用一次。",Records:"记录数","Sum of {name}":"{name}合计","Discard unsaved changes?":"放弃未保存的更改?",Discard:"放弃更改","Keep editing":"继续编辑","View deleted":"视图已删除","View saved":"视图已保存","Fields saved":"字段已保存","Record saved":"记录已保存","Record saved, keep adding":"记录已保存,可继续新增","New record form":"新增记录表单",Save:"保存","Save new record":"保存新记录","Save and continue":"保存并继续","Cancel adding":"取消新增","Clear current filter":"清除当前筛选","Configure fields":"配置字段","Table title":"表格标题","{count} filters":"{count} 项筛选","Cancel field settings":"取消字段设置","Only this view's filters, sort and layout are removed; no records are deleted.":"只删除这个视图的筛选、排序和布局设置,不会删除任何记录。","Expand all groups before pasting.":"请先展开所有分组再粘贴。"};function fe(e="en"){return(t,n={})=>(e==="zh-CN"?qn[t]??t:t).replace(/\{(\w+)\}/g,(i,o)=>String(n[o]??i))}function Yi(e,t,n,i,o=!1){let{row:r,column:a}=e;if(t==="ArrowUp")r--;if(t==="ArrowDown")r++;if(t==="ArrowLeft")a--;if(t==="ArrowRight")a++;if(t==="Home")a=0;if(t==="End")a=i-1;if(t==="Tab"){let c=Math.max(0,Math.min(n*i-1,r*i+a+(o?-1:1)));r=Math.floor(c/i),a=c%i}return{row:Math.max(0,Math.min(n-1,r)),column:Math.max(0,Math.min(i-1,a))}}function $n(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 Ie(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function Wi(e,t,n,i){let o=$n(n,i),r=[];for(let a=o.firstRow;a<=o.lastRow;a++){let c=[];for(let s=o.firstColumn;s<=o.lastColumn;s++){let f=t[s],u=e[a]?.values[f?.id??""],l=f?.type==="json"&&u!=null?JSON.stringify(u):f?.type==="hyperlink"?Mt(u):Ie(u);c.push(/[\t\r\n"]/.test(l)?`"${l.replaceAll('"','""')}"`:l)}r.push(c.join("\t"))}return r.join(`
|
|
2
|
+
`)}function jn(e,t="en"){let n=fe(t),i=[],o=[],r="",a=!1;for(let c=0;c<e.length;c++){let s=e[c];if(s==='"'&&(a||r===""))if(a&&e[c+1]==='"')r+='"',c++;else a=!a;else if(!a&&(s==="\t"||s===`
|
|
3
|
+
`||s==="\r")){if(o.push(r),r="",s!=="\t"){if(i.push(o),o=[],s==="\r"&&e[c+1]===`
|
|
4
|
+
`)c++}}else r+=s}if(a)throw Error(n("Unclosed quoted cell."));if(r||o.length||i.length===0)o.push(r),i.push(o);return i}function Ne(e,t,n="en"){let i=fe(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 r=Number(e);if(!e.trim()||!Number.isFinite(r))throw Error(i("{name} needs a number.",{name:t.name}));return r}if(t.type==="hyperlink"){let r=qe(e);if(!r)throw Error(i("{name} needs a link.",{name:t.name}));return r}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 r=He(t);if(r){let M=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!M)throw Error(i("{name} needs a date.",{name:t.name}));let[,A,_,I]=M,N=new Date(Date.UTC(Number(A),Number(_)-1,Number(I)));if(N.getUTCMonth()!==Number(_)-1||N.getUTCDate()!==Number(I))throw Error(i("{name} needs a valid calendar date.",{name:t.name}));if(r.time==="none"){if(/T.*(?:Z|[+-]\d{2}:\d{2})$/i.test(e)&&Number.isFinite(Date.parse(e)))return at(new Date(e),r.timeZone);return`${A}-${_}-${I}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return Ue({year:Number(A),month:Number(_),day:Number(I)},r.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[,c,s,f,u,l,C,P,R]=a,D=Number(c),S=Number(s),m=Number(f),h=[31,D%4===0&&(D%100!==0||D%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(S<1||S>12||m<1||m>(h[S-1]??0)||Number(u??0)>23||Number(l??0)>59||Number(C??0)>59||Number(P??0)>23||Number(R??0)>59)throw Error(i("{name} needs a valid calendar date.",{name:t.name}));let y=new Date(e);if(!Number.isFinite(y.getTime()))throw Error(i("{name} needs a date.",{name:t.name}));return y.toISOString()}let o=(r)=>{let a=t.options?.find((c)=>c.id===r||c.name===r);if(!a)throw Error(i("{name} has no option '{option}'.",{name:t.name,option:r}));return a.id};if(t.type==="singleSelect")return o(e);if(t.type==="multipleSelect")return[...new Set(e.split(",").map((r)=>o(r.trim())))];return e}function Gi(e,t,n,i,o="en"){let r=fe(o);try{if(e.length>1048576)throw Error(r("Paste is too large."));let a=jn(e,o);if(a.length>100||i.row+a.length>t.length)throw Error(r("Paste must fit within the loaded page and contain at most 100 rows."));return{ok:!0,items:a.map((s,f)=>{if(i.column+s.length>n.length)throw Error(r("Paste extends beyond the visible columns."));let u=t[i.row+f];if(!u)throw Error(r("Row is not loaded."));let l={};return s.forEach((C,P)=>{let R=n[i.column+P];if(R?.generation==="autoIncrement")throw Error(r("{name} is auto-generated and cannot be edited.",{name:R.name}));if(R)l[R.id]=Ne(C,R,o)}),{op:"update",id:u.id,expectedVersion:u.version,values:l}})}}catch(a){return{ok:!1,message:a instanceof Error?a.message:r("Invalid paste.")}}}function Ht(e,t){let n=Ie(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 o=new Intl.DateTimeFormat("en-CA",{...t?{timeZone:t}:{},year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hourCycle:"h23"}).formatToParts(i),r=(f)=>o.find((u)=>u.type===f)?.value??"",a=i.getUTCMilliseconds(),c=r("second"),s=c!=="00"||a?`:${c}${a?`.${String(a).padStart(3,"0")}`:""}`:"";return`${r("year")}-${r("month")}-${r("day")} ${r("hour")}:${r("minute")}${s}`}import{useEffect as Hn,useRef as zn,useState as We}from"react";import{jsx as Se,jsxs as nt}from"react/jsx-runtime";function Ge(e){if(e==null)return"—";if(Array.isArray(e))return e.map(Ge).join(", ");return String(e)}function ea(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((i)=>i.label||i.id).join(", "):void 0)??Ge(e.values[t.id])}function ta(e,t){return Ie(e.values[t.id])}function zt({field:e,value:t,labels:n=[],client:i,onChange:o,disabled:r=!1,locale:a,"aria-describedby":c,"aria-invalid":s}){let f=fe(a),u=Array.isArray(t)?t.filter((g)=>typeof g==="string"):[],l=zn(new Set(u));l.current=new Set(u);let[C,P]=We(""),[R,D]=We(),[S,m]=We([]),[v,h]=We(0),[y,M]=We({}),[A,_]=We({rows:[],next:null,error:"",loading:!0}),I=e.link?.collectionId,N=e.link?.displayFieldId;Hn(()=>{let g=!0;if(_({rows:[],next:null,error:"",loading:!0}),!i||!I||!N){_({rows:[],next:null,error:f("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return i.query(I,{limit:50,search:C,...R?{cursor:R}:{}}).then((b)=>{if(!g)return;if(!b.ok){_({rows:[],next:null,error:b.error.message,loading:!1});return}M((O)=>({...Object.fromEntries(Object.entries(O).filter(([k])=>l.current.has(k))),...Object.fromEntries(b.data.items.map((k)=>{let j=String(k.values[N]??"");return[k.id,j.trim()?j.slice(0,256):k.id]}))})),_({rows:b.data.items,next:b.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(g)_({rows:[],next:null,error:f("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{g=!1}},[i,I,N,C,R,v]);let L=(g)=>y[g]??n.find((b)=>b.id===g)?.label??g;return nt("fieldset",{disabled:r,"aria-label":f("{name} linked records",{name:e.name}),...c?{"aria-describedby":c}:{},...s?{"aria-invalid":!0}:{},className:"flex min-w-0 flex-col gap-2 rounded-md border p-2",children:[Se("div",{className:"flex flex-wrap gap-1",children:u.map((g)=>nt("span",{className:"rounded border px-2 py-1 text-sm",children:[L(g)," ",Se("button",{type:"button","aria-label":f("Remove {name}",{name:L(g)}),onClick:()=>o(u.filter((b)=>b!==g)),children:"×"})]},g))}),Se("input",{"aria-label":f("Search {name} records",{name:e.name}),type:"search",placeholder:f("Search linked records"),value:C,onChange:(g)=>{P(g.target.value),D(void 0),m([])}}),A.loading&&Se("p",{role:"status",children:f("Loading linked records…")}),A.error&&nt("div",{role:"alert",children:[A.error," ",Se("button",{type:"button",onClick:()=>h((g)=>g+1),children:f("Retry linked records")})]}),Se("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:A.rows.map((g)=>nt("label",{className:"flex items-center gap-2 text-sm",children:[Se("input",{type:"checkbox","aria-label":f("Link {name}",{name:L(g.id)}),checked:u.includes(g.id),disabled:!u.includes(g.id)&&u.length>=100,onChange:(b)=>o(b.target.checked?[...u,g.id]:u.filter((O)=>O!==g.id))}),L(g.id)]},g.id))}),!A.loading&&!A.error&&!A.rows.length&&Se("p",{children:f("No matching records.")}),nt("div",{className:"flex gap-2",children:[Se("button",{type:"button",disabled:!S.length||A.loading,onClick:()=>{D(S.at(-1)),m((g)=>g.slice(0,-1))},children:f("Previous linked records")}),Se("button",{type:"button",disabled:!A.next||A.loading,onClick:()=>{m((g)=>[...g,R]),D(A.next??void 0)},children:f("Next linked records")})]}),Se("small",{children:f("{count} selected · up to 100 per record across all link fields",{count:u.length})})]})}var Kn={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function dt(e,t,n){return t?fe(n)(Kn[t]):e==null?"—":String(e)}function ua(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 Kt(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function Yt(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function pa(e,t,n){let i=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...Yt(e),filter:Kt(e.filter,i)}}function Yn(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 o=new Date(`${e}-01T00:00:00.000Z`),r=new Date(o);return r.setUTCMonth(r.getUTCMonth()+1),{start:o.toISOString(),end:r.toISOString(),days:Math.round((r.getTime()-o.getTime())/86400000),weekday:o.getUTCDay()}}function ga(e,t,n){let{start:i,end:o}=Yn(n);return{...Yt(e),filter:Kt(e.filter,{fieldId:t,operator:"onOrAfter",value:i},{fieldId:t,operator:"before",value:o})}}function Wt(e,t){let n={id:"date",name:"Date",type:"date"},i=String(Ne(t,n)),o=String(Ne(String(e),n));return`${i.slice(0,10)}${o.slice(10)}`}function ma(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((o)=>o.id===i))}function fa(e,t){let n=t.find((i)=>i.type==="singleLineText"||i.type==="longText");return(n?Ie(e.values[n.id]):"")||e.id}function ya(e,t,n){if(t.type==="lookup")return Ge(e);if(t.type==="hyperlink")return tt(e);if(t.type==="date"){let i=He(t);return i?qt(e,i):Ht(e)}if(t.type==="number"){let i=Bt(t);return i?$t(e,i):Ie(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return dt(e,n);if(t.type==="singleSelect"||t.type==="multipleSelect")return(Array.isArray(e)?e:e==null?[]:[e]).map((o)=>t.options?.find((r)=>r.id===o)?.name??String(o)).join(", ");return Ie(e)}import{createContext as Wn,useContext as Gn,useEffect as Jn,useId as Zn,useLayoutEffect as Qn,useMemo as Xn,useRef as er,useState as Je}from"react";import{jsx as we,jsxs as Ze}from"react/jsx-runtime";var Jt=Wn(void 0);function ka(e){return we(Jt.Provider,{value:e.client,children:e.children})}var Zt=()=>Gn(Jt),Gt=(e)=>/^https?:/i.test(e);function tr(e){let t=Zt();if(!Ye(e.value))return null;let n=e.value,i=t?.href?.(n)??n.url;return we("a",{href:i,title:n.url,"data-uibot-link":n.ref?.kind??(Gt(i)?"external":"internal"),...Gt(i)?{target:"_blank",rel:"noopener noreferrer"}:{},style:{color:"var(--uibot-link, currentColor)",textDecoration:"underline",textUnderlineOffset:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...e.style},onMouseDown:(o)=>o.stopPropagation(),onDoubleClick:(o)=>o.stopPropagation(),onClick:(o)=>{if(o.stopPropagation(),!(o.button!==0||o.metaKey||o.ctrlKey||o.shiftKey||o.altKey)&&t?.open?.(n))o.preventDefault()},children:tt(n)})}var rt=(e)=>e?JSON.stringify(e):"",nr=(e)=>e.trim().startsWith("{")?qe(e):null;function ct(e){let t=Xn(()=>fe(e.locale),[e.locale]),n=Zt(),i=Zn(),o=nr(e.text),[r,a]=Je(()=>o?"":e.text),[c,s]=Je(!1),[f,u]=Je([]),[l,C]=Je(""),[P,R]=Je(-1),D=er(null),[S,m]=Je(null),h=e.field.hyperlink?.kinds?.join(",")??"";Jn(()=>{if(!n||!c||e.disabled)return;let g=new AbortController,b=setTimeout(()=>{C(t("Searching…")),n.search({search:r.trim(),...h?{kinds:h.split(",")}:{},limit:8},{signal:g.signal}).then((O)=>{if(g.signal.aborted)return;u(O.ok?O.data.slice(0,8):[]),C(O.ok?"":O.error.message)}).catch((O)=>{if(!g.signal.aborted)C(O instanceof Error?O.message:String(O))})},200);return()=>{clearTimeout(b),g.abort()}},[n,c,r,h,e.disabled,t]);let y=qe(r),M=(g)=>n?.kinds?.find((b)=>b.id===g)?.label??g,A=[...y&&!y.ref?[{key:"typed",value:y,title:t("Use link {url}",{url:y.url})}]:[],...f.map((g)=>({key:`${g.kind}:${g.id}`,value:{url:g.url,text:g.title,ref:{kind:g.kind,id:g.id}},title:g.title,subtitle:[M(g.kind),g.subtitle].filter(Boolean).join(" · ")}))],_=Boolean(n&&!l&&!f.length&&r.trim()),I=c&&!e.disabled&&(A.length>0||Boolean(l)||_);Qn(()=>{if(!I)return;let g=()=>m(D.current?.getBoundingClientRect()??null);return g(),window.addEventListener("scroll",g,!0),window.addEventListener("resize",g),()=>{window.removeEventListener("scroll",g,!0),window.removeEventListener("resize",g)}},[I]);let N=(g)=>{a(""),R(-1),e.onChange(rt(g.value))},L=(g)=>{a(g),R(-1),e.onChange(g||rt(o))};return Ze("div",{style:{display:"grid",gap:4,minWidth:0,height:"100%"},children:[we("input",{ref:D,id:e.id,role:"combobox","aria-label":e.ariaLabel,"aria-expanded":I,"aria-controls":i,"aria-autocomplete":"list","aria-invalid":e.invalid,...e.describedBy?{"aria-describedby":e.describedBy}:{},...P>=0?{"aria-activedescendant":`${i}-${P}`}:{},disabled:e.disabled,placeholder:o?tt(o):t("Search or paste a link"),value:r,style:e.inputStyle,className:e.inputClassName,onFocus:()=>s(!0),onBlur:()=>s(!1),onChange:(g)=>L(g.currentTarget.value),onKeyDown:(g)=>{if(e.onSave||e.onCancel)g.stopPropagation();if(g.key==="ArrowDown"||g.key==="ArrowUp"){if(!A.length)return;g.preventDefault();let b=g.key==="ArrowDown"?1:-1;R((O)=>b>0?(O+1)%A.length:O<=0?A.length-1:O-1)}else if(g.key==="Enter"){g.preventDefault();let b=A[P];if(b)N(b);else e.onSave?.()}else if(g.key==="Tab"&&e.onSave)g.preventDefault(),e.onSave();else if(g.key==="Escape")if(g.preventDefault(),r)L("");else e.onCancel?.()}}),o&&!r&&!e.onSave&&Ze("div",{style:{display:"grid",gap:4,minWidth:0,fontSize:12},children:[Ze("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[we(tr,{value:o,style:{flex:"0 1 auto"}}),we("span",{style:{flex:"1 1 0",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:0.6},children:o.url}),we("button",{type:"button","aria-label":t("Remove link"),title:t("Remove link"),disabled:e.disabled,onMouseDown:(g)=>g.preventDefault(),onClick:()=>e.onChange(""),style:{border:0,background:"none",color:"inherit",cursor:"pointer",opacity:0.6},children:"×"})]}),Ze("label",{style:{display:"grid",gap:2},children:[we("span",{style:{opacity:0.7},children:t("Display text")}),we("input",{"aria-label":t("Display text"),placeholder:o.url,value:o.text??"",disabled:e.disabled,className:e.inputClassName,onChange:(g)=>{let b=g.currentTarget.value.slice(0,500),{text:O,...k}=o;e.onChange(rt(b?{...k,text:b}:k))}})]})]}),I&&S&&Ze("div",{id:i,role:"listbox","aria-label":t("Link suggestions"),style:{position:"fixed",top:S.bottom+4,left:S.left,width:Math.max(S.width,280),maxHeight:320,overflowY:"auto",zIndex:1000,padding:4,border:"1px solid var(--uibot-border, #d4d4d8)",borderRadius:8,background:"var(--uibot-surface, var(--background, #fff))",color:"var(--uibot-text, inherit)",boxShadow:"0 8px 24px rgb(0 0 0 / 0.12)"},onMouseDown:(g)=>g.preventDefault(),children:[A.map((g,b)=>Ze("div",{id:`${i}-${b}`,role:"option","aria-selected":b===P,tabIndex:-1,onMouseEnter:()=>R(b),onClick:()=>N(g),onKeyDown:()=>{},style:{display:"grid",gap:2,padding:"6px 8px",borderRadius:6,cursor:"pointer",background:b===P?"var(--uibot-hover, rgb(0 0 0 / 0.06))":void 0},children:[we("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g.title}),g.subtitle&&we("span",{style:{fontSize:12,opacity:0.65},children:g.subtitle})]},g.key)),l&&we("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:l}),_&&we("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:t("No matching resources")})]})]})}import{useEffect as tn,useId as or,useMemo as ir,useRef as ar,useState as nn}from"react";var rr=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function Me(e){return rr.test(e)}var Te=(e)=>String(e).padStart(2,"0");function Qt(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${Te(t.getMonth()+1)}-${Te(t.getDate())}T${Te(t.getHours())}:${Te(t.getMinutes())}:${Te(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var ht=(e,t)=>{let n=Ae(e,t);return`${n.year}-${Te(n.month)}-${Te(n.day)}T${Te(n.hour)}:${Te(n.minute)}`};function Xt(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!Me(e))return e.slice(0,10);return ht(new Date(e),t.timeZone??"UTC").slice(0,10)}if(Me(e))return ht(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function en(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||Me(t)))return e;let o=e.length>10?e.slice(11,16):t&&Me(t)?ht(new Date(t),n.timeZone).slice(11,16):"00:00",[r,a,c]=e.slice(0,10).split("-").map(Number),[s,f]=o.split(":").map(Number),u=Ue({year:r??0,month:a??1,day:c??1,hour:s??0,minute:f??0},n.timeZone);return Number.isFinite(u.getTime())?u.toISOString():e}import{jsx as Le,jsxs as rn}from"react/jsx-runtime";function xt(e,t,n){if(e.type==="blob")return"";try{return Ne(t,e),""}catch{if(t===""&&e.required)return n==="zh-CN"?`请填写${e.name}。`:`${e.name} is required.`;if(e.type==="number")return n==="zh-CN"?`${e.name}需要有效数字。`:`${e.name} needs a number.`;if(e.type==="bigint")return n==="zh-CN"?`${e.name}必须是整数。`:`${e.name} needs an integer.`;if(e.type==="date")return n==="zh-CN"?`${e.name}需要有效日期。`:`${e.name} needs a valid date.`;if(e.type==="checkbox")return n==="zh-CN"?`${e.name}请选择是或否。`:`${e.name} needs true or false.`;if(e.type==="hyperlink")return fe(n)("{name} needs a link.",{name:e.name});if(e.type==="json")return n==="zh-CN"?`${e.name}必须是有效 JSON。`:`${e.name} needs valid JSON.`;return n==="zh-CN"?"输入值无效":"Invalid value"}}function Ta({field:e,text:t,disabled:n,id:i,label:o,ariaLabel:r,onChange:a,onSave:c,onCancel:s,locale:f="en",submitted:u=!1,describedBy:l}){let C=ir(()=>fe(f),[f]),P=or(),R=ar(null),D=Boolean(c);tn(()=>{if(D)R.current?.querySelector("input,textarea,select")?.focus()},[D]);let S=i??P,m=`${S}-error`,[v,h]=nn(t),[y,M]=nn(!1);tn(()=>h(t),[t]);let A=xt(e,v,f),I=Boolean(e.required&&v===""&&A)&&!y&&!u?"":A,N=r??o??e.name,L=e.type==="date"&&Me(v),g=L&&!A?Qt(v):v,b=[l,I?m:void 0].filter(Boolean).join(" "),O={id:S,"aria-label":N,"aria-invalid":Boolean(I),...b?{"aria-describedby":b}:{},disabled:n,onBlur:()=>M(!0),onKeyDown:(p)=>{if(c||s)p.stopPropagation();let F=e.type==="longText"||e.type==="json";if(p.key==="Tab"&&c)p.preventDefault(),c(p.shiftKey?"previous":"next");else if(p.key==="Enter"&&!p.shiftKey&&c&&(!F||p.ctrlKey||p.metaKey))p.preventDefault(),c();else if(p.key==="Escape"&&s)p.preventDefault(),s()},style:{width:"100%",...D?{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"},k=(p)=>{M(!0),h(p),a(p)},j=(p)=>{if(e.type==="date"&&L&&p){let F=new Date(p);k(Number.isFinite(F.getTime())?F.toISOString():p)}else k(p)},H;if(e.type==="hyperlink")H=Le(ct,{field:e,text:v,id:S,ariaLabel:N,invalid:Boolean(I),describedBy:b||void 0,disabled:n,locale:f,inputStyle:O.style,inputClassName:O.className,onChange:k,onSave:c,onCancel:s});else if(e.type==="checkbox")H=rn("select",{...O,value:v,onChange:(p)=>k(p.currentTarget.value),children:[!e.required&&Le("option",{value:"",children:C("No value")}),Le("option",{value:"true",children:C("Yes")}),Le("option",{value:"false",children:C("No")})]});else if(e.type==="longText"||e.type==="json")H=Le("textarea",{...O,value:v,rows:e.type==="json"?4:3,onChange:(p)=>k(p.currentTarget.value)});else{let p=e.type==="date"&&!(A&&v)?L?"datetime-local":"date":"text",F=e.type==="blob";H=Le("input",{...O,type:p,inputMode:e.type==="number"?"decimal":void 0,step:L?"0.001":void 0,value:g,readOnly:F,onInput:e.type==="date"?(z)=>j(z.currentTarget.value):void 0,onChange:(z)=>j(z.currentTarget.value)})}return rn("div",{ref:R,className:"grid min-w-0 gap-1",style:D?{height:"100%"}:void 0,children:[o&&Le("label",{className:"text-xs font-medium",htmlFor:S,children:o}),H,I&&Le("span",{id:m,role:"alert",className:"text-xs text-red-600",children:I})]})}import{useEffect as lr,useRef as dr}from"react";import{jsx as on}from"react/jsx-runtime";var sr={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 an({name:e,size:t=15,style:n}){return on("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:on("path",{d:sr[e]})})}import{jsx as Oe,jsxs as sn,Fragment as ur}from"react/jsx-runtime";var cr={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function _a({ui:e,style:t,variant:n,size:i,children:o,disabled:r,onClick:a,title:c,ariaLabel:s,icon:f,iconOnly:u,badge:l}){let C=e?.Button,P=f?sn("span",{style:{position:"relative",display:"inline-flex"},children:[Oe(an,{name:f}),l?Oe("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,R=u?P:sn(ur,{children:[P,o]}),D=s,S=c??(u?D:void 0),m=u?"icon":i;if(C)return Oe(C,{...n?{variant:n}:{},...m?{size:m}:{},disabled:r,onClick:a,title:S,"aria-label":D,children:R});return Oe("button",{type:"button",style:{...f?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?cr:{},...u?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:r,onClick:a,title:S,"aria-label":D,children:R})}function ln({ui:e,value:t,options:n,onChange:i,disabled:o,label:r,style:a,"aria-describedby":c,"aria-invalid":s}){let f=e?.Select,u={...c?{"aria-describedby":c}:{},...s?{"aria-invalid":!0}:{}};if(f)return Oe(f,{value:t,options:n,onChange:i,disabled:o,"aria-label":r,...u});return Oe("select",{"aria-label":r,...u,style:a,disabled:o,value:t,onChange:(l)=>i(l.target.value),children:n.map((l)=>Oe("option",{value:l.value,disabled:l.disabled,children:l.label},l.value))})}function Ba({label:e,busy:t,onCancel:n,children:i,alert:o=!1}){let r=dr(null);return lr(()=>{let a=r.current,c=document.activeElement;if(a?.showModal)a.showModal();else a?.setAttribute("open","");return()=>{if(a?.close?.(),c instanceof HTMLElement&&c.isConnected)c.focus({preventScroll:!0})}},[]),Oe("dialog",{ref:r,role:o?"alertdialog":"dialog","aria-modal":"true","aria-label":e,style:{position:"fixed",inset:0,margin:"auto",maxWidth:"min(440px, calc(100vw - 32px))",maxHeight:"80vh",overflow:"auto",boxSizing:"border-box",padding:20,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"inherit",font:"inherit"},onKeyDown:(a)=>{if(a.key!=="Tab")return;let c=a.currentTarget,s=[...c.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter((l)=>!l.hidden),f=s[0],u=s.at(-1);if(!f||(a.shiftKey?document.activeElement===f:document.activeElement===u)||!c.contains(document.activeElement)){if(a.preventDefault(),(a.shiftKey?u:f)?.focus(),!f)c.focus()}},tabIndex:-1,onCancel:(a)=>{if(a.preventDefault(),!t)n()},children:i})}import{useEffect as dn,useRef as ot,useState as De}from"react";import{jsx as K,jsxs as ee,Fragment as fr}from"react/jsx-runtime";function pr(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 gr=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function mr({descriptor:e,fieldIds:t,query:n,client:i,readOnly:o=!1,reloadKey:r=0,onImported:a,onRefreshSchema:c}){let[s,f]=De(null),[u,l]=De(null),[C,P]=De(null),[R,D]=De([]),[S,m]=De(""),[v,h]=De(!1),[y,M]=De(!1),[A,_]=De(!0),[I,N]=De(null),[L,g]=De(!1),b=ot(!1),O=ot(!1),k=ot(!1),j=ot(null),H=ot({client:i,onImported:a,descriptor:e});H.current={client:i,onImported:a,descriptor:e},dn(()=>(b.current=!0,()=>{b.current=!1,O.current=!1}),[]),dn(()=>{let x=!0;if(!o)i.imports(e.id).then((E)=>{if(!x||!b.current||!E.ok)return;if(D((J)=>E.data.map((ne)=>{let ue=J.find((B)=>B.id===ne.id);return ue&&ue.version>ne.version?ue:ne})),!k.current)P((J)=>{let ne=E.data.find((ue)=>ue.id===J?.id);return J&&ne&&ne.version>J.version?ne:J})});return()=>{x=!1}},[i,e.id,o,r]);let p=(x)=>{P(x),D((E)=>[x,...E.filter((J)=>J.id!==x.id)].slice(0,50)),N(null)};async function F(x){if(k.current||o)return;k.current=!0,O.current=!0,h(!0),M(!0),m("");let E=x;try{while(b.current&&O.current&&E.status==="ready"){let J=await H.current.client.advanceImport(e.id,E.id,E.version);if(!b.current)break;if(!J.ok){m(J.error.message);break}let ne=J.data;if(p(ne),ne.importedRows>E.importedRows)H.current.onImported();if(ne.version===E.version&&ne.status==="ready"){m("Import paused. Refresh the saved progress before retrying.");break}E=ne}}finally{if(k.current=!1,O.current=!1,b.current)h(!1),M(!1)}}async function z(){if(!s||k.current)return;k.current=!0,h(!0),m("");let x=await i.previewImport(e.id,{...s,expectedSchemaVersion:e.schemaVersion});if(k.current=!1,!b.current)return;if(h(!1),x.ok)l(x.data),f({...s,expectedSchemaVersion:x.data.schemaVersion,mapping:x.data.mapping});else m(x.error.message)}async function te(){if(!s||!u||u.missingRequiredFieldIds.length||!u.totalRows||k.current||o)return;k.current=!0,h(!0),m(""),j.current??=crypto.randomUUID();let x=await i.createImport(e.id,{...s,idempotencyKey:j.current});if(k.current=!1,!b.current)return;if(h(!1),x.ok)p(x.data),f(null),l(null),j.current=null,F(x.data);else m(x.error.message)}async function V(){if(!C||k.current||o)return;if(C.status==="ready"){F(C);return}k.current=!0,h(!0),m("");let x=c?await c():H.current.descriptor;if(!x){k.current=!1,h(!1),m("Refresh the collection schema and try again.");return}let E=await i.resumeImport(e.id,C.id,C.version,x.schemaVersion);if(k.current=!1,!b.current)return;if(h(!1),E.ok)p(E.data),F(E.data);else m(E.error.message)}async function Y(x){if(!C)return;let E=await i.importErrors(e.id,C.id,{limit:100,...x===void 0?{}:{cursor:x},expectedVersion:C.version});if(!b.current)return;if(E.ok)N(E.data);else m(E.error.message)}async function X(x=!1){if(v||k.current)return;k.current=!0,h(!0),m("");let E=x&&C?await i.exportImportErrors(e.id,C.id):await i.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:A});if(k.current=!1,!b.current)return;if(h(!1),E.ok)pr(E.data),m(`${E.data.rowCount} rows downloaded${E.data.protectedCells?`; ${E.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else m(E.error.message)}return ee("details",{className:"min-w-0 rounded-lg border p-4",children:[K("summary",{className:"cursor-pointer text-sm font-medium",children:"CSV import and export"}),ee("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[ee("div",{className:"flex flex-wrap items-center gap-3",children:[K("button",{type:"button",disabled:v||!t.length,onClick:()=>void X(),children:"Export CSV"}),ee("label",{className:"flex items-center gap-2 text-sm",children:[K("input",{type:"checkbox",checked:A,onChange:(x)=>_(x.target.checked)}),"Spreadsheet view"]})]}),K("p",{className:"text-xs text-muted-foreground",children:"Export all matching records and visible columns from the active query. Spreadsheet view prefixes potentially active text with a tab and changes those values; application support varies. Turn it off for exact text. Limit: 100,000 rows or 20 MiB."}),!o&&ee(fr,{children:[ee("label",{className:"flex min-w-0 flex-col gap-2 text-sm",children:["CSV file",K("input",{"aria-label":"CSV file",className:"max-w-full",type:"file",accept:".csv,text/csv",disabled:v,onChange:async(x)=>{let E=x.target.files?.[0];if(!E)return;if(m(""),l(null),f(null),j.current=null,E.size>20971520){m("Choose a UTF-8 CSV file no larger than 20 MiB.");return}h(!0),k.current=!0;try{let J=new TextDecoder("utf-8",{fatal:!0}).decode(await E.arrayBuffer());if(b.current)f({fileName:E.name,csv:J,expectedSchemaVersion:e.schemaVersion})}catch{if(b.current)m("The file must be valid UTF-8 text.")}finally{if(k.current=!1,b.current)h(!1)}}})]}),s&&ee("div",{className:"flex flex-wrap gap-3",children:[K("span",{className:"break-all text-sm",children:s.fileName}),K("button",{type:"button",disabled:v,onClick:()=>void z(),children:"Preview CSV"})]}),K("p",{className:"text-xs text-muted-foreground",children:"Insert into this collection. Existing records and options stay unchanged. Dates: ISO or YYYY-MM-DD; selections: IDs or names; multi-select: JSON array or semicolon list; linked records: JSON IDs. Blank non-text cells become null. Computed columns are skipped. Invalid rows are skipped with downloadable errors."}),u&&s&&ee("div",{className:"flex min-w-0 flex-col gap-3",children:[ee("p",{className:"text-sm",children:[u.totalRows," rows · ",u.validRows," valid · ",u.invalidRows," ","invalid · ",u.ignoredColumns.length," skipped columns"]}),u.headers.map((x,E)=>ee("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[ee("span",{className:"max-w-64 break-all",children:["Column ",E+1,": ",x||"(empty)"]}),ee("select",{"aria-label":`Column ${E+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:s.mapping?.[E]??"",disabled:v,onChange:(J)=>{let ne=[...s.mapping??u.mapping];ne[E]=J.target.value||null,f({...s,mapping:ne}),l(null),j.current=null},children:[K("option",{value:"",children:"Skip column"}),e.fields.filter((J)=>!Pe(J)).map((J)=>ee("option",{value:J.id,children:[J.name," (",J.id,")",J.required?" · required":""]},J.id))]})]},`${E}:${x}`)),u.missingRequiredFieldIds.length>0&&ee("p",{role:"alert",children:["Map required fields: ",u.missingRequiredFieldIds.join(", ")]}),K("div",{className:"max-w-full overflow-x-auto",children:ee("table",{className:"w-full text-xs",children:[ee("caption",{children:["First ",u.sample.length," normalized rows; row numbers include the header."]}),K("thead",{children:ee("tr",{children:[K("th",{children:"Row"}),K("th",{children:"Normalized values"}),K("th",{children:"Error"})]})}),K("tbody",{children:u.sample.map((x)=>ee("tr",{children:[K("td",{children:x.rowNumber}),K("td",{className:"max-w-96 break-all",children:gr(x.values)}),K("td",{children:x.error?.code??""})]},x.rowNumber))})]})}),K("button",{type:"button",className:"self-start",disabled:v||!u.totalRows||u.missingRequiredFieldIds.length>0,onClick:()=>void te(),children:"Confirm import"})]}),ee("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",ee("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:C?.id??"",disabled:v,onChange:async(x)=>{if(!x.target.value){P(null);return}let E=await i.importJob(e.id,x.target.value);if(b.current)if(E.ok)p(E.data),g(!1);else m(E.error.message)},children:[K("option",{value:"",children:"Choose saved progress…"}),R.map((x)=>ee("option",{value:x.id,children:[x.fileName," · ",x.processedRows,"/",x.totalRows," · ",x.status]},x.id))]})]}),K("button",{type:"button",className:"self-start",disabled:v,onClick:async()=>{let x=await i.imports(e.id);if(b.current)if(x.ok)D(x.data);else m(x.error.message)},children:"Refresh saved imports"}),C&&ee("div",{className:"flex flex-col gap-3",children:[ee("p",{role:"status",children:[y?"Importing":C.status==="ready"?"Paused":C.status==="schemaChanged"?"Schema changed — confirm before continuing":C.status==="completed"?"Completed":"Cancelled"," ","· ",C.processedRows," of ",C.totalRows," processed · ",C.importedRows," imported ·"," ",C.failedRows," failed"]}),K("progress",{"aria-label":"Import progress",max:C.totalRows,value:C.processedRows,className:"max-w-full"}),K("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."}),ee("div",{className:"flex flex-wrap gap-3",children:[y&&K("button",{type:"button",onClick:()=>{O.current=!1,M(!1)},children:"Pause import"}),!y&&(C.status==="ready"||C.status==="schemaChanged")&&K("button",{type:"button",disabled:v,onClick:()=>void V(),children:C.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(C.status==="ready"||C.status==="schemaChanged")&&K("button",{type:"button",disabled:v,onClick:()=>g(!0),children:"Cancel import"}),K("button",{type:"button",disabled:v||!C.failedRows,onClick:()=>void Y(),children:"Show import errors"}),K("button",{type:"button",disabled:v||!C.failedRows,onClick:()=>void X(!0),children:"Download all import errors"})]}),L&&ee("div",{children:[ee("p",{children:["Stop remaining rows? The ",C.importedRows," imported records will remain."]}),K("button",{type:"button",disabled:v,onClick:async()=>{k.current=!0,h(!0);let x=await i.cancelImport(e.id,C.id);if(k.current=!1,!b.current)return;if(h(!1),x.ok)p(x.data),g(!1);else m(x.error.message)},children:"Confirm cancellation"}),K("button",{type:"button",onClick:()=>g(!1),children:"Keep import"})]}),I&&ee("div",{className:"max-w-full overflow-x-auto",children:[ee("table",{className:"w-full text-xs",children:[ee("caption",{children:[I.total," failed rows"]}),K("thead",{children:ee("tr",{children:[K("th",{children:"Row"}),K("th",{children:"Field"}),K("th",{children:"Error"})]})}),K("tbody",{children:I.items.map((x)=>ee("tr",{children:[K("td",{children:x.rowNumber}),K("td",{children:x.fieldId??""}),K("td",{children:x.code})]},x.rowNumber))})]}),I.nextCursor!==null&&K("button",{type:"button",onClick:()=>void Y(I.nextCursor??void 0),children:"Next errors"})]})]})]}),S&&K("p",{role:"alert",className:"break-words text-sm",children:S})]})]})}import{useEffect as cn,useRef as ze,useState as Ke}from"react";import{jsx as ae,jsxs as Ce,Fragment as br}from"react/jsx-runtime";var ut=[{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 yr({descriptor:e,client:t,onConverted:n}){let i=e.fields.filter((p)=>ut.some((F)=>F.type===p.type)),[o,r]=Ke(i[0]?.id??""),a=i.find((p)=>p.id===o)??i[0],[c,s]=Ke(a?.type??"singleLineText"),[f,u]=Ke(a?.required??!1),[l,C]=Ke(a?.options?.map((p)=>`${p.id}=${p.name}`).join(`
|
|
5
|
+
`)??""),[P,R]=Ke(null),[D,S]=Ke(""),[m,v]=Ke(!1),h=ze(null),y=ze(null),M=ze(0),A=ze(e);A.current=e;let _=h.current?.field??a,I=m||h.current!==null,N=`${e.id}:${e.schemaVersion}:${JSON.stringify(e.fields)}`,L=ze(e.fields);L.current=e.fields;let g=ze(N);g.current=N;let b=ze(!0);cn(()=>(b.current=!0,()=>{b.current=!1,M.current++}),[]),cn(()=>{if(g.current!==N)return;if(h.current&&y.current===e.id)return;M.current++;let p=L.current.find((F)=>F.id===o&&ut.some((z)=>z.type===F.type))??L.current.find((F)=>ut.some((z)=>z.type===F.type));if(p)r(p.id),s(p.type),u(p.required??!1),C(p.options?.map((F)=>`${F.id}=${F.name}`).join(`
|
|
6
|
+
`)??"");R(null),h.current=null,y.current=null,S(""),v(!1)},[N,o,e.id]);let O=()=>{R(null),h.current=null,y.current=null,M.current++,S("")},k=(p)=>{r(p.id),s(p.type),u(p.required??!1),C(p.options?.map((F)=>`${F.id}=${F.name}`).join(`
|
|
7
|
+
`)??""),O()};if(!_)return null;let j=()=>{let p={id:_.id,name:_.name,type:c,required:f};if(c==="singleSelect"||c==="multipleSelect")p.options=l.split(`
|
|
8
|
+
`).filter((F)=>F.trim()).map((F)=>{let z=F.indexOf("=");if(z<1)throw Error("Each option must use stable_id=Display name.");return{id:F.slice(0,z).trim(),name:F.slice(z+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:p}},H=()=>b.current&&g.current===N;return Ce("details",{className:"rounded-lg border p-4",children:[ae("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),Ce("div",{className:"mt-4 flex flex-col gap-3",children:[ae("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."}),Ce("label",{children:["Field"," ",Ce("select",{"aria-label":"Conversion field",value:_.id,disabled:I,onChange:(p)=>{let F=i.find((z)=>z.id===p.target.value);if(F)k(F)},children:[h.current&&!i.some((p)=>p.id===_.id)&&ae("option",{value:_.id,children:_.name}),i.map((p)=>ae("option",{value:p.id,children:p.name},p.id))]})]}),Ce("label",{children:["Target type"," ",ae("select",{"aria-label":"Conversion target type",value:c,disabled:I,onChange:(p)=>{s(p.target.value),O()},children:ut.map((p)=>ae("option",{value:p.type,children:p.label},p.type))})]}),Ce("label",{children:[ae("input",{type:"checkbox",checked:f,disabled:I,onChange:(p)=>{u(p.target.checked),O()}})," ","Required after conversion"]}),(c==="singleSelect"||c==="multipleSelect")&&Ce("label",{children:["Stable option IDs and display names",ae("textarea",{"aria-label":"Conversion options",className:"block w-full rounded border p-2",disabled:I,value:l,onChange:(p)=>{C(p.target.value),O()},placeholder:`open=Open
|
|
9
|
+
done=Done`})]}),D&&ae("p",{role:"alert",className:"text-sm text-destructive",children:D}),ae("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:I,onClick:async()=>{let p;try{p=j()}catch(F){S(F instanceof Error?F.message:"Invalid conversion options.");return}v(!0),S(""),R(null),h.current=null;try{let F=await t.previewConversion(e.id,p);if(!H())return;if(F.ok)R(F.data);else S(F.error.message)}catch{if(H())S("Preview unavailable. Your draft is kept.")}finally{if(H())v(!1)}},children:m?"Working…":"Preview conversion"}),P&&Ce(br,{children:[Ce("p",{role:"status",children:[P.validRows," valid · ",P.invalidRows," invalid"]}),Ce("p",{className:"text-xs",children:["Preview covers ",P.totalRows," records. Samples and errors show at most 20 records."]}),ae("div",{className:"overflow-x-auto",children:Ce("table",{className:"w-full text-sm",children:[ae("thead",{children:Ce("tr",{children:[ae("th",{children:"Record"}),ae("th",{children:"Before"}),ae("th",{children:"After"}),ae("th",{children:"Error"})]})}),ae("tbody",{children:P.sample.map((p)=>Ce("tr",{children:[ae("td",{className:"max-w-32 break-all",children:p.id}),ae("td",{className:"max-w-48 break-words",children:JSON.stringify(p.before)}),ae("td",{className:"max-w-48 break-words",children:JSON.stringify(p.after)}),ae("td",{children:p.error})]},p.id))})]})}),P.errors.length>0&&ae("ul",{children:P.errors.map((p)=>Ce("li",{children:[ae("span",{className:"break-all",children:p.id}),": ",ae("span",{children:p.code})]},p.id))}),ae("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:m||P.invalidRows>0,onClick:async()=>{if(!h.current)y.current=e.id,M.current++;h.current??={expectedSchemaVersion:P.schemaVersion,field:P.field,previewToken:P.previewToken,idempotencyKey:crypto.randomUUID()};let p=h.current,F=M.current,z=()=>b.current&&A.current.id===e.id&&F===M.current;v(!0),S("");try{let te=await t.convertField(e.id,p);if(!z())return;if(te.ok){if(R(null),h.current=null,y.current=null,te.data.descriptor.schemaVersion>=A.current.schemaVersion)n(te.data.descriptor)}else if(S(te.error.message),te.error.status===409)R(null),h.current=null,y.current=null}catch{if(z())S("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(z())v(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as Cr,useRef as kt,useState as un}from"react";import{jsx as pn,jsxs as xr}from"react/jsx-runtime";function hr({collectionIds:e,client:t,onChanges:n,pollIntervalMs:i=2000}){let o=JSON.stringify([...new Set(e)].sort()),r=kt(o);r.current=o;let a=kt(n);a.current=n;let c=kt(()=>{}),[s,f]=un("connecting"),[u,l]=un(!1);return Cr(()=>{let C=JSON.parse(o),P=new Map,R=!1,D=!1,S=0,m,v=()=>!R&&r.current===o,h=Math.max(50,Math.min(60000,i)),y=async()=>{if(!v()||D)return;D=!0,l(!0);let _=!1;try{let I=S>0;for(let N of C){let L=P.get(N),g=await t.changes(N,{...L!==void 0?{cursor:L}:{},limit:100});if(!v())return;if(!g.ok)throw f(g.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let b=L===void 0;if(b||I||g.data.items.length>0)await a.current(N,g.data,b);if(!v())return;P.set(N,g.data.cursor),_||=g.data.hasMore}S=0,f("live")}catch{if(S++,v())f((I)=>I==="expired"?"expired":"offline")}finally{if(D=!1,v())l(!1),m=setTimeout(()=>{y()},_&&S===0?0:Math.min(30000,h*2**Math.min(S,8)))}},M=()=>{if(m!==void 0)clearTimeout(m);y()};c.current=M,f("connecting"),y();let A=()=>{if(document.visibilityState==="visible")M()};return window.addEventListener("online",M),document.addEventListener("visibilitychange",A),()=>{if(R=!0,m!==void 0)clearTimeout(m);window.removeEventListener("online",M),document.removeEventListener("visibilitychange",A)}},[o,t,i]),xr("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[pn("p",{role:"status",children:s==="live"?"Live updates":s==="connecting"?"Connecting live updates…":s==="expired"?"Session expired. Renew your session; drafts are kept.":"Connection interrupted. Drafts are kept."}),(s==="offline"||s==="expired")&&pn("button",{type:"button",className:"rounded border px-2 py-1",disabled:u,onClick:()=>c.current(),children:"Reconnect now"})]})}import{useEffect as pt,useRef as Ve,useState as xe}from"react";import{jsx as G,jsxs as re,Fragment as wt}from"react/jsx-runtime";var Pt={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function it(e){try{return await e()}catch{return{ok:!1,error:Pt}}}function vt({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return re("div",{className:"min-w-0",children:[G("strong",{children:t}),G("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&&re(wt,{children:[G("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),G("button",{type:"button",onClick:()=>{let i=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),o=document.createElement("a");o.href=i,o.download=`record-${e?.id}-${e?.version}.json`,o.click(),setTimeout(()=>URL.revokeObjectURL(i),1000)},children:"Download snapshot"})]})]})}function kr({descriptor:e,recordId:t,client:n,readOnly:i=!1,onCommitted:o,registerRefresh:r}){let[a,c]=xe(null),[s,f]=xe(null),[u,l]=xe(null),[C,P]=xe(),[R,D]=xe(),[S,m]=xe([]),[v,h]=xe([]),[y,M]=xe(""),[A,_]=xe(null),[I,N]=xe(null),[L,g]=xe(null),[b,O]=xe(!1),[k,j]=xe(""),H=Ve(null),p=Ve(null),F=Ve(n);F.current=n;let z=Ve(!1),te=Ve(0),V=`${e.id}:${t}`,Y=Ve(V);Y.current=V;let X=Ve({historyBefore:C,commentBefore:R});X.current={historyBefore:C,commentBefore:R};let x=Ve(async()=>{}),E=(d=V)=>z.current&&Y.current===d&&F.current===n,J=async()=>{let d=V,T=++te.current,q=X.current,[be,Be]=await Promise.all([it(()=>n.history(e.id,t,{...q.historyBefore===void 0?{}:{before:q.historyBefore},limit:20})),it(()=>n.comments(e.id,t,{...q.commentBefore===void 0?{}:{before:q.commentBefore},limit:50}))]);if(!E(d)||T!==te.current)throw Error("Refresh superseded");if(!be.ok||!Be.ok)throw j(!be.ok?be.error.message:!Be.ok?Be.error.message:Pt.message),Error("Activity refresh failed");f(be.data),l(Be.data),c(d)};x.current=J,pt(()=>(z.current=!0,()=>{z.current=!1,te.current++}),[]),pt(()=>(r?.(()=>x.current()),()=>r?.(null)),[r]),pt(()=>{if(Y.current!==V)return;f(null),l(null),c(null),P(void 0),D(void 0),m([]),h([]),X.current={historyBefore:void 0,commentBefore:void 0},M(""),_(null),N(null),g(null),H.current=null,p.current=null,O(!1),j("")},[V]),pt(()=>{if(Y.current!==V||F.current!==n||X.current.historyBefore!==C||X.current.commentBefore!==R)return;x.current().catch(()=>{})},[V,n,C,R]);let ne=(d)=>{let T=H.current;if(T?.signature===d)return T.key;let q={signature:d,key:crypto.randomUUID()};return H.current=q,q.key},ue=async(d)=>{if(b||i||!u||a!==V)return;let T=d==="delete"?I:A;if(d!=="create"&&(!T||T.authorId!==u.actorId))return;let q=d==="create"?y:A?.draft??"";if(d!=="delete"&&(!q.trim()||q.length>4000||q.includes("\x00"))){j("Comments require 1–4,000 characters.");return}let be=ne(JSON.stringify([d,T?.id,T?.version,q]));O(!0),j("");let Be=await it(async()=>{if(d==="create")return n.createComment(e.id,t,{text:q,idempotencyKey:be});if(!T)return{ok:!1,error:Pt};if(d==="edit")return n.editComment(e.id,t,T.id,{text:q,expectedVersion:T.version,idempotencyKey:be});return n.deleteComment(e.id,t,T.id,{expectedVersion:T.version,idempotencyKey:be})});if(!E())return;if(O(!1),!Be.ok){j(Be.error.message);return}if(H.current=null,d==="create")M("");else if(d==="edit")_(null);else N(null);if(d==="create"&&R!==void 0)D(void 0),h([]);else await x.current().catch(()=>{})},B=async(d)=>{if(b||i||!s||a!==V)return;O(!0),j(""),p.current=null;let T={targetVersion:d,expectedCurrentVersion:s.currentVersion,expectedSchemaVersion:e.schemaVersion},q=await it(()=>n.previewUndo(e.id,t,T));if(!E())return;if(O(!1),q.ok)g(q.data);else g(null),j(q.error.message)},se=async()=>{if(b||i||a!==V||!L&&!p.current)return;let d=p.current;if(!d){if(!L)return;d={targetVersion:L.targetVersion,expectedCurrentVersion:L.currentVersion,expectedSchemaVersion:L.schemaVersion,idempotencyKey:crypto.randomUUID()},p.current=d}let T=d;O(!0),j("");let q=await it(()=>n.undo(e.id,t,T));if(!E())return;if(O(!1),!q.ok){if(q.error.code==="version_conflict"||q.error.code==="reference_conflict"||q.error.code==="validation")p.current=null,g(null);j(q.error.message),await x.current().catch(()=>{});return}p.current=null,g(null),o(q.data),P(void 0),m([]),await x.current().catch(()=>{})},W=u?.items.find((d)=>d.id===A?.id),ge=A&&W&&W.version!==A.version,w=L&&(L.currentVersion!==s?.currentVersion||L.schemaVersion!==e.schemaVersion);return re("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[re("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[re("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),G("button",{type:"button",disabled:b,onClick:()=>{j(""),x.current().catch(()=>{})},children:"Refresh activity"})]}),k&&G("p",{role:"alert",className:"text-sm text-destructive",children:k}),!s||!u||a!==V?G("p",{role:"status",children:"Loading record activity…"}):re(wt,{children:[re("p",{role:"status",children:["Current version ",s.currentVersion,s.currentDeleted?" · Deleted record":""]}),G("h3",{className:"font-medium",children:"Comments"}),u.items.length===0&&G("p",{className:"text-sm",children:"No comments yet."}),G("ol",{className:"flex flex-col gap-3",children:u.items.map((d)=>re("li",{className:"min-w-0 rounded border p-3",children:[re("p",{className:"break-all text-xs",children:[d.authorId," · ",d.updatedAt," · version ",d.version]}),G("p",{className:"whitespace-pre-wrap break-words text-sm",children:d.text??"Comment deleted"}),!i&&d.text!==null&&d.authorId===u.actorId&&re("div",{className:"flex gap-3",children:[G("button",{type:"button",disabled:b,onClick:()=>{_({...d,draft:d.text??""}),N(null),H.current=null},children:"Edit comment"}),G("button",{type:"button",disabled:b,onClick:()=>{N(d),_(null),H.current=null},children:"Delete comment"})]})]},d.id))}),re("div",{className:"flex gap-3",children:[G("button",{type:"button",disabled:b||!v.length,onClick:()=>{D(v.at(-1)),h((d)=>d.slice(0,-1))},children:"Newer comments"}),G("button",{type:"button",disabled:b||u.nextCursor===null,onClick:()=>{h((d)=>[...d,R]),D(u.nextCursor??void 0)},children:"Older comments"})]}),!i&&re(wt,{children:[A&&re("div",{className:"flex flex-col gap-2",children:[re("label",{children:["Edit comment text",G("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:b,maxLength:4000,value:A.draft,onChange:(d)=>{_({...A,draft:d.target.value}),H.current=null}})]}),ge&&re("div",{role:"status",children:[G("p",{children:"This comment changed. Your draft and original version are kept."}),re("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",W.text??"Comment deleted"]}),W.text!==null&&W.authorId===u.actorId&&G("button",{type:"button",disabled:b,onClick:()=>{_({...W,draft:A.draft}),H.current=null},children:"Use current comment version"})]}),re("div",{className:"flex gap-3",children:[G("button",{type:"button",disabled:b||A.authorId!==u.actorId,onClick:()=>void ue("edit"),children:"Save comment"}),G("button",{type:"button",disabled:b,onClick:()=>{_(null),H.current=null},children:"Cancel comment edit"})]})]}),I&&re("div",{children:[G("p",{children:"Delete this comment? A deletion marker will remain."}),G("p",{className:"whitespace-pre-wrap break-words",children:I.text}),G("button",{type:"button",disabled:b||I.authorId!==u.actorId,onClick:()=>void ue("delete"),children:"Confirm delete comment"}),G("button",{type:"button",disabled:b,onClick:()=>N(null),children:"Cancel delete comment"})]}),re("label",{children:["New comment",G("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:b,maxLength:4000,value:y,onChange:(d)=>{M(d.target.value),H.current=null}})]}),G("button",{type:"button",className:"self-start",disabled:b||!y.trim(),onClick:()=>void ue("create"),children:"Add comment"})]}),G("h3",{className:"font-medium",children:"Record history"}),G("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."}),G("ol",{className:"flex flex-col gap-3",children:s.items.map((d)=>re("li",{className:"min-w-0 rounded border p-3",children:[re("p",{className:"break-all text-xs",children:["Version ",d.version," · ",d.operation," · schema ",d.schemaVersion," · ",d.actorId," ·"," ",d.createdAt]}),re("details",{children:[re("summary",{children:["Stored values at version ",d.version]}),G(vt,{record:d.snapshot,label:`Version ${d.version}`})]}),!i&&d.version<s.currentVersion&&re("button",{type:"button",disabled:b,onClick:()=>void B(d.version),children:["Preview restore version ",d.version]})]},d.id))}),re("div",{className:"flex gap-3",children:[G("button",{type:"button",disabled:b||!S.length,onClick:()=>{P(S.at(-1)),m((d)=>d.slice(0,-1))},children:"Newer history"}),G("button",{type:"button",disabled:b||s.nextCursor===null,onClick:()=>{m((d)=>[...d,C]),P(s.nextCursor??void 0)},children:"Older history"})]}),!i&&L&&re("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[re("h3",{children:["Restore version ",L.targetVersion," as a new version"]}),re("p",{children:["Current version ",L.currentVersion," · schema ",L.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),re("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[G(vt,{record:L.before,label:"Current stored values"}),G(vt,{record:L.target,label:"Values to restore"})]}),w&&!p.current&&G("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),re("div",{className:"flex gap-3",children:[G("button",{type:"button",disabled:b||!!w&&!p.current,onClick:()=>void se(),children:p.current?"Retry undo":"Confirm restore"}),G("button",{type:"button",disabled:b,onClick:()=>{g(null),p.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as gt,useRef as _e,useState as Fe}from"react";import{jsx as pe,jsxs as ke,Fragment as gn}from"react/jsx-runtime";async function mt(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 vr(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let i of t)n+=String.fromCharCode(i);return btoa(n)}function Pr({collectionId:e,recordId:t,client:n,readOnly:i=!1,registerRefresh:o}){let r=`${e}:${t}`,a=_e({identity:r,client:n});a.current={identity:r,client:n};let c=_e(!1),s=_e(0),f=_e(0),[u,l]=Fe(null),[C,P]=Fe(null),[R,D]=Fe(),[S,m]=Fe([]),v=_e(R);v.current=R;let[h,y]=Fe(null),[M,A]=Fe(null),_=_e(null),I=_e(null),[N,L]=Fe(!1),[g,b]=Fe(!1),[O,k]=Fe(""),j=()=>c.current&&a.current.identity===r&&a.current.client===n,H=async()=>{let V=++s.current,Y=await mt(()=>n.list(e,t,{limit:20,...v.current===void 0?{}:{before:v.current}}));if(!j()||V!==s.current)throw Error("Refresh superseded");if(!Y.ok)throw k(Y.error.message),Error("Attachment refresh failed");P(Y.data),l(r)},p=_e(H);p.current=H,gt(()=>(c.current=!0,()=>{c.current=!1,++s.current,++f.current}),[]),gt(()=>{if(a.current.identity!==r||a.current.client!==n)return;l(null),P(null),y(null),A(null),_.current=null,L(!1),b(!1),k(""),D(void 0),m([]),v.current=void 0,++f.current,p.current().catch(()=>{})},[r,n]),gt(()=>{if(v.current===R&&u===r)p.current().catch(()=>{})},[R,r,u]),gt(()=>(o?.(()=>p.current()),()=>o?.(null)),[o]);let F=async()=>{if(N||i||!h||u!==r)return;let V=h;L(!0),k("");let Y=await mt(()=>n.upload(e,t,V));if(!j())return;if(L(!1),!Y.ok){k(Y.error.message);return}if(y(null),I.current)I.current.value="";D(void 0),m([]),v.current=void 0,await p.current().catch(()=>{})},z=async()=>{if(N||i||!M||M.authorId!==C?.actorId||u!==r)return;_.current??=crypto.randomUUID();let V=M,Y=_.current;L(!0),k("");let X=await mt(()=>n.delete(e,t,V.id,{expectedVersion:V.version,idempotencyKey:Y}));if(!j())return;if(L(!1),!X.ok){k(X.error.message),await p.current().catch(()=>{});return}A(null),_.current=null,await p.current().catch(()=>{})},te=async(V)=>{if(N||u!==r)return;L(!0),k("");let Y=await mt(()=>n.content(e,t,V.id));if(!j())return;if(L(!1),!Y.ok){k(Y.error.message);return}let X=Uint8Array.from(atob(Y.data.base64),(J)=>J.charCodeAt(0)),x=URL.createObjectURL(new Blob([X],{type:"application/octet-stream"})),E=document.createElement("a");E.href=x,E.download=Y.data.attachment.name,E.click(),setTimeout(()=>URL.revokeObjectURL(x),1000)};return ke("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[ke("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[pe("h3",{className:"font-medium",children:"Attachments"}),pe("button",{type:"button",disabled:N,onClick:()=>{k(""),p.current().catch(()=>{})},children:"Refresh attachments"})]}),O&&pe("p",{role:"alert",children:O}),!C||u!==r?pe("p",{role:"status",children:"Loading attachments…"}):ke(gn,{children:[C.items.length===0&&pe("p",{children:"No attachments yet."}),pe("ol",{className:"flex min-w-0 flex-col gap-2",children:C.items.map((V)=>ke("li",{className:"min-w-0 rounded border p-2",children:[pe("p",{className:"break-all",children:V.name}),ke("p",{className:"break-all text-xs",children:[V.size," bytes · version ",V.version," · ",V.authorId]}),V.deletedAt?pe("p",{children:"Attachment deleted"}):ke("div",{className:"flex flex-wrap gap-3",children:[pe("button",{type:"button",disabled:N,"aria-label":`Download attachment ${V.name}`,onClick:()=>void te(V),children:"Download"}),!i&&V.authorId===C.actorId&&pe("button",{type:"button",disabled:N,"aria-label":`Delete attachment ${V.name}`,onClick:()=>{A(V),_.current=null},children:"Delete"})]})]},V.id))}),ke("div",{className:"flex flex-wrap gap-3",children:[pe("button",{type:"button",disabled:N||!S.length,onClick:()=>{D(S.at(-1)),m((V)=>V.slice(0,-1))},children:"Newer attachments"}),pe("button",{type:"button",disabled:N||C.nextCursor===null,onClick:()=>{m((V)=>[...V,R]),D(C.nextCursor??void 0)},children:"Older attachments"})]}),!i&&ke(gn,{children:[pe("p",{className:"text-xs",children:"Up to 1 MiB per file, 20 active files and 5 MiB per record. Files have independent versions; restoring record values does not restore deleted files."}),ke("label",{children:["Attachment file",pe("input",{ref:I,"aria-label":"Attachment file",type:"file",disabled:N||g,onChange:async(V)=>{let Y=V.target.files?.[0];if(!Y)return;let X=++f.current;if(y(null),k(""),!Y.size||Y.size>1048576){k("Choose a nonempty file up to 1 MiB.");return}b(!0);try{let x=await vr(Y);if(!j()||X!==f.current)return;let E=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(Y.type)?Y.type:"application/octet-stream";y({name:Y.name,contentType:E,base64:x,idempotencyKey:crypto.randomUUID()})}catch{if(j()&&X===f.current)k("The selected file could not be read.")}finally{if(j()&&X===f.current)b(!1)}}},r)]}),h&&ke("p",{className:"break-all",children:["Selected file: ",h.name]}),pe("button",{type:"button",className:"self-start",disabled:N||g||!h,onClick:()=>void F(),children:"Upload attachment"}),M&&ke("div",{children:[ke("p",{className:"break-all",children:["Delete ",M.name,"? This permanently removes its bytes and keeps a deletion marker."]}),ke("div",{className:"flex flex-wrap gap-3",children:[pe("button",{type:"button",disabled:N,onClick:()=>void z(),children:"Confirm delete attachment"}),pe("button",{type:"button",disabled:N,onClick:()=>{A(null),_.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as ft,useRef as Qe,useState as ve}from"react";import{jsx as ie,jsxs as le,Fragment as mn}from"react/jsx-runtime";async function Rt(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function wr(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function Rr({descriptor:e,recordIds:t,client:n,linkForGrant:i,registerRefresh:o}){let r=e.id,a=Qe({identity:r,client:n});a.current={identity:r,client:n};let c=Qe(!1),s=Qe(0),[f,u]=ve(null),[l,C]=ve(null),[P,R]=ve(),D=Qe(P);D.current=P;let[S,m]=ve([]),[v,h]=ve([]),[y,M]=ve([]),[A,_]=ve(3600),[I,N]=ve(null),[L,g]=ve(!1),[b,O]=ve(""),[k,j]=ve(null),H=Qe(null),[p,F]=ve(!1),[z,te]=ve(""),V=()=>c.current&&a.current.identity===r&&a.current.client===n,Y=async()=>{let B=++s.current,se=await Rt(()=>n.list(r,{limit:20,...D.current===void 0?{}:{before:D.current}}));if(!V()||B!==s.current)throw Error("Refresh superseded");if(!se.ok)throw te(se.error.message),Error("Share refresh failed");C(se.data),u(r)},X=Qe(Y);X.current=Y,ft(()=>(c.current=!0,()=>{c.current=!1,++s.current}),[]),ft(()=>{if(a.current.identity!==r||a.current.client!==n)return;u(null),C(null),h([]),M([]),N(null),g(!1),O(""),j(null),H.current=null,F(!1),te(""),R(void 0),m([]),D.current=void 0,X.current().catch(()=>{})},[r,n]),ft(()=>{if(D.current===P&&f===r)X.current().catch(()=>{})},[P,f,r]),ft(()=>(o?.(()=>X.current()),()=>o?.(null)),[o]);let x=()=>{if(!L)N(null)},E=async()=>{if(p||!I||f!==r)return;let B=I;F(!0),g(!0),te("");let se=await Rt(()=>n.create(r,B));if(!V())return;if(F(!1),!se.ok){te(se.error.message);return}O(i(se.data,B.key)),N(null),g(!1),R(void 0),m([]),D.current=void 0,await X.current().catch(()=>{})},J=async()=>{if(p||!k||f!==r)return;let B=k;H.current??=crypto.randomUUID();let se=H.current;F(!0),te("");let W=await Rt(()=>n.revoke(r,B.id,{expectedVersion:B.version,idempotencyKey:se}));if(!V())return;if(F(!1),!W.ok){te(W.error.message),await X.current().catch(()=>{});return}j(null),H.current=null,O(""),await X.current().catch(()=>{})},ne=e.fields.filter((B)=>!["linkedRecord","lookup","formula","rollup"].includes(B.type)),ue=p||L;return le("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[le("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[ie("h3",{className:"font-medium",children:"Read-only sharing"}),ie("button",{type:"button",disabled:p,onClick:()=>{te(""),X.current().catch(()=>{})},children:"Refresh share grants"})]}),ie("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."}),ie("p",{className:"text-xs",children:"Relations, computed fields, attachments, discussions, history and writes are excluded. Up to 100 records, 20 active grants and 24 hours per grant. Keys are shown only when created."}),z&&ie("p",{role:"alert",children:z}),le("fieldset",{disabled:ue,className:"flex min-w-0 flex-col gap-2",children:[ie("legend",{children:"Fields to share"}),ne.map((B)=>le("label",{className:"break-all",children:[ie("input",{type:"checkbox","aria-label":`Share field ${B.name}`,checked:v.includes(B.id),onChange:(se)=>{x(),h((W)=>se.target.checked?[...W,B.id]:W.filter((ge)=>ge!==B.id))}})," ",B.name]},B.id))]}),le("fieldset",{disabled:ue,className:"flex min-w-0 flex-col gap-2",children:[ie("legend",{children:"Records on the current page"}),t.slice(0,100).map((B)=>le("label",{className:"break-all",children:[ie("input",{type:"checkbox","aria-label":`Share record ${B}`,checked:y.includes(B),onChange:(se)=>{x(),M((W)=>se.target.checked?[...W,B]:W.filter((ge)=>ge!==B))}})," ",B]},B)),t.length===0&&ie("p",{children:"Load records in Grid to choose a share scope."})]}),le("p",{className:"break-all text-xs",children:["Selected record IDs: ",y.join(", ")||"none"]}),le("label",{children:["Link lifetime"," ",le("select",{"aria-label":"Share link lifetime",disabled:ue,value:A,onChange:(B)=>{x(),_(Number(B.target.value))},children:[ie("option",{value:60,children:"1 minute"}),ie("option",{value:3600,children:"1 hour"}),ie("option",{value:86400,children:"24 hours"})]})]}),ie("button",{type:"button",className:"self-start",disabled:ue||f!==r||!v.length||!y.length||y.length>100||v.some((B)=>!ne.some((se)=>se.id===B)),onClick:()=>{te("");try{N({expectedSchemaVersion:e.schemaVersion,fieldIds:[...v],recordIds:[...y],expiresInSeconds:A,key:wr(),idempotencyKey:crypto.randomUUID()})}catch{te("A secure share key could not be generated.")}},children:"Review read-only share"}),I&&le("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[le("p",{className:"break-all",children:["Confirm schema ",I.expectedSchemaVersion,", fields ",I.fieldIds.join(", "),", records ",I.recordIds.join(", ")," for ",I.expiresInSeconds," seconds."]}),I.expectedSchemaVersion!==e.schemaVersion&&ie("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),le("div",{className:"flex flex-wrap gap-3",children:[ie("button",{type:"button",disabled:p,onClick:()=>void E(),children:L?"Retry create read link":"Create read link"}),ie("button",{type:"button",disabled:p,onClick:()=>{N(null),g(!1),te("")},children:"Discard share confirmation"})]}),L&&ie("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."})]}),b&&le("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",ie("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:b,onFocus:(B)=>B.target.select()})]}),!l||f!==r?ie("p",{role:"status",children:"Loading share grants…"}):le(mn,{children:[l.items.length===0&&ie("p",{children:"No share grants yet."}),ie("ol",{className:"flex min-w-0 flex-col gap-2",children:l.items.map((B)=>le("li",{className:"min-w-0 rounded border p-2",children:[le("p",{className:"break-all",children:["Grant ",B.id," · version ",B.version," · schema ",B.schemaVersion]}),le("p",{className:"break-all text-xs",children:["Fields: ",B.fieldIds.join(", ")," · Records: ",B.recordIds.join(", ")," · Expires:"," ",B.expiresAt]}),B.revokedAt?ie("p",{children:"Share revoked"}):le(mn,{children:[ie("p",{children:B.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(B.expiresAt)<=Date.now()?"Share expired":"Share active"}),ie("button",{type:"button",disabled:p,"aria-label":`Revoke share ${B.id}`,onClick:()=>{j(B),H.current=null},children:"Revoke"})]})]},B.id))}),le("div",{className:"flex flex-wrap gap-3",children:[ie("button",{type:"button",disabled:p||!S.length,onClick:()=>{R(S.at(-1)),m((B)=>B.slice(0,-1))},children:"Newer share grants"}),ie("button",{type:"button",disabled:p||l.nextCursor===null,onClick:()=>{m((B)=>[...B,P]),R(l.nextCursor??void 0)},children:"Older share grants"})]})]}),k&&le("div",{children:[le("p",{className:"break-all",children:["Revoke grant ",k.id," at version ",k.version,"? Every existing share session will lose access."]}),le("div",{className:"flex flex-wrap gap-3",children:[ie("button",{type:"button",disabled:p,onClick:()=>void J(),children:"Confirm revoke share"}),ie("button",{type:"button",disabled:p,onClick:()=>{j(null),H.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as fn,useRef as Xe,useState as ye}from"react";import{jsx as Z,jsxs as de}from"react/jsx-runtime";var yn=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],Ir=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function Sr({descriptor:e,recordIds:t,client:n,webhookRequest:i}){let o=e.id,r=Xe({id:o,client:n});r.current={id:o,client:n};let a=Xe(!0),c=Xe(0),[s,f]=ye([]),[u,l]=ye(""),C=Xe(u);C.current=u;let[P,R]=ye(null),[D,S]=ye(),m=Xe(D);m.current=D;let[v,h]=ye(""),[y,M]=ye("record"),[A,_]=ye(60),[I,N]=ye([]),[L,g]=ye([]),[b,O]=ye({}),[k,j]=ye(null),[H,p]=ye(!1),[F,z]=ye(!1),[te,V]=ye(""),[Y,X]=ye(""),x=()=>a.current&&r.current.id===o&&r.current.client===n,E=async(w)=>{try{return await w()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},J=async()=>{let w=++c.current,d=await E(()=>n.list(o));if(!x()||w!==c.current)return;if(!d.ok){V(d.error.message);return}f(d.data);let T=d.data.find((be)=>be.id===C.current)?.id??d.data[0]?.id??"";if(C.current=T,l(T),!T){R(null);return}let q=await E(()=>n.runs(o,T,{limit:20,...m.current?{before:m.current}:{}}));if(!x()||w!==c.current||C.current!==T)return;if(q.ok)R(q.data);else V(q.error.message)},ne=Xe(J);ne.current=J,fn(()=>{if(r.current.id!==o||r.current.client!==n)return;a.current=!0,ne.current();let w=setInterval(()=>void ne.current(),5000);return()=>{a.current=!1,++c.current,clearInterval(w)}},[o,n]),fn(()=>{if(C.current!==u||m.current!==D)return;ne.current()},[u,D]);let ue=()=>{if(V(""),!v.trim()||!I.length||y!=="record"&&!L.length){V("Choose a name, writable fields, and target records for time or webhook triggers.");return}let w=Object.fromEntries(I.map((T)=>[T,b[T]??null])),d={expectedSchemaVersion:e.schemaVersion,name:v.trim(),trigger:y==="time"?{kind:y,intervalSeconds:A}:{kind:y},targetRecordIds:L,values:w,idempotencyKey:crypto.randomUUID(),...y==="webhook"?{webhookKey:Ir()}:{}};j({kind:"create",input:d}),p(!1)},B=(w)=>{j(w),p(!1),V("")},se=async()=>{if(!k||F)return;let w=k,d=H;p(!0),z(!0),V("");let T=await E(()=>w.kind==="create"?n.create(o,w.input):w.kind==="toggle"?n.toggle(o,w.a.id,w.input):w.kind==="run"?n.runNow(o,w.a.id,w.input):n.retry(o,w.a.id,w.run.id,w.input));if(!x())return;if(z(!1),!T.ok){if(!d&&T.error.status>=400&&T.error.status<500)p(!1);V(`${T.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(w.kind==="create"){let q=T.data;if(C.current=q.id,l(q.id),w.input.webhookKey&&i)X(JSON.stringify(i(q,w.input.webhookKey),null,2));h(""),N([]),g([]),O({})}j(null),p(!1),m.current=void 0,S(void 0),await ne.current()},W=s.find((w)=>w.id===u),ge=!!k||F;return de("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[Z("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."}),Z("button",{type:"button",onClick:()=>void ne.current(),children:"Refresh automation"}),te&&Z("p",{role:"alert",children:te}),Z("form",{onSubmit:(w)=>{w.preventDefault(),ue()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:de("fieldset",{disabled:ge,style:{minWidth:0},children:[Z("legend",{children:"New automation"}),de("label",{children:["Name"," ",Z("input",{"aria-label":"Automation name",value:v,maxLength:200,onChange:(w)=>h(w.target.value)})]}),de("label",{children:["Trigger"," ",de("select",{"aria-label":"Automation trigger",value:y,onChange:(w)=>M(w.target.value),children:[Z("option",{value:"record",children:"Record changes"}),Z("option",{value:"time",children:"Timed interval"}),Z("option",{value:"webhook",children:"Private webhook"})]})]}),y==="time"&&de("label",{children:["Interval in seconds"," ",Z("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:A,onChange:(w)=>_(Number(w.target.value))})]}),de("fieldset",{children:[Z("legend",{children:"Fields to update"}),e.fields.filter((w)=>yn.includes(w.type)).map((w)=>de("label",{style:{display:"block"},children:[Z("input",{type:"checkbox",checked:I.includes(w.id),onChange:(d)=>{N(d.target.checked?[...I,w.id]:I.filter((T)=>T!==w.id))}}),w.name]},w.id))]}),Z(bn,{fields:e.fields.filter((w)=>I.includes(w.id)&&yn.includes(w.type)),values:b,onChange:O}),de("fieldset",{children:[Z("legend",{children:"Target records from this page"}),y==="record"&&Z("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&Z("p",{children:"Open a grid page to choose fixed records."}),t.map((w)=>de("label",{style:{display:"block",overflowWrap:"anywhere"},children:[Z("input",{type:"checkbox","aria-label":`Automation target ${w}`,checked:L.includes(w),onChange:(d)=>g(d.target.checked?[...L,w]:L.filter((T)=>T!==w))}),w]},w))]}),Z("button",{type:"submit",children:"Review automation"})]})}),k&&de("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[Z("p",{children:k.kind==="create"?`Create ${k.input.name} using schema ${k.input.expectedSchemaVersion}; ${k.input.targetRecordIds.length||"event"} targets.`:k.kind==="toggle"?`${k.input.enabled?"Enable":"Disable"} ${k.a.name}. Disabling fences queued and running work.`:k.kind==="run"?`Run ${k.a.name} for ${k.input.recordIds.length} explicitly selected records.`:`Retry ${k.a.name}, run ${k.run.sequence}, using its original record versions.`}),k.kind==="create"&&Z("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(k.input.values,null,2)}),Z("button",{type:"button",disabled:F,onClick:()=>void se(),children:F?"Confirming…":H?"Retry automation confirmation":"Confirm automation"}),Z("button",{type:"button",disabled:H||F,onClick:()=>j(null),children:"Cancel automation review"}),H&&Z("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),Y&&de("div",{children:[Z("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),Z("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:Y}),Z("button",{type:"button",onClick:()=>X(""),children:"Hide webhook key"})]}),s.length>0&&de("label",{children:["Automation"," ",Z("select",{"aria-label":"Selected automation",disabled:ge,value:u,onChange:(w)=>{C.current=w.target.value,m.current=void 0,S(void 0),l(w.target.value),R(null)},children:s.map((w)=>Z("option",{value:w.id,children:w.name},w.id))})]}),W&&de("div",{children:[de("p",{children:[W.enabled?"Enabled":"Disabled"," · ",W.trigger.kind," · schema ",W.schemaVersion," · configuration ",W.version]}),Z("button",{type:"button",disabled:ge,onClick:()=>B({kind:"toggle",a:W,input:{expectedVersion:W.version,enabled:!W.enabled,idempotencyKey:crypto.randomUUID()}}),children:W.enabled?"Review disable automation":"Review enable automation"}),Z("button",{type:"button",disabled:ge||!W.enabled||!(W.targetRecordIds.length||t.length),onClick:()=>B({kind:"run",a:W,input:{recordIds:W.targetRecordIds.length?W.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),P&&de("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!P.items.length&&Z("p",{children:"No runs yet."}),P.items.map((w)=>de("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[de("p",{children:["Run ",w.sequence," · ",w.triggerKind," · ",w.status," · step ",w.step]}),de("p",{children:["Attempts: evaluate ",w.stepAttempts.evaluate,", apply ",w.stepAttempts.apply," · original versions: ",w.expectedRows.map((d)=>`${d.id}: ${d.version}`).join(", ")]}),w.errorCode&&Z("p",{role:"status",children:w.errorCode}),w.leaseUntil&&de("p",{children:["Lease expires ",w.leaseUntil]}),W&&w.status==="failed"&&de("button",{type:"button",disabled:ge||!W.enabled,onClick:()=>B({kind:"retry",a:W,run:w,input:{expectedVersion:w.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",w.sequence]})]},w.id)),Z("button",{type:"button",disabled:ge||D===void 0,onClick:()=>{m.current=void 0,S(void 0)},children:"Newest runs"}),Z("button",{type:"button",disabled:ge||P.nextCursor===null,onClick:()=>{m.current=P.nextCursor??void 0,S(m.current)},children:"Older runs"})]})]})}import{useEffect as Ar,useId as Dr,useRef as Cn,useState as me}from"react";import{jsx as oe,jsxs as ce}from"react/jsx-runtime";var hn=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function Er(e,t,n){if(!n.resourceId||!n.model.trim()||n.model.length>200||!n.instruction.trim()||new TextEncoder().encode(n.instruction).length>2000||n.recordIds.length<1||n.recordIds.length>10||new Set(n.recordIds).size!==n.recordIds.length)throw Error("Choose an AI resource, model, instruction and up to ten records.");for(let o of[n.sourceFieldIds,n.targetFieldIds])if(o.length<1||o.length>10||new Set(o).size!==o.length||o.some((r)=>!e.fields.some((a)=>a.id===r&&hn.includes(a.type))))throw Error("Choose up to ten basic source and target fields.");let i=n.recordIds.map((o)=>{let r=t.find((a)=>a.id===o);if(!r)throw Error("A selected record is no longer on this page.");return{id:o,expectedVersion:r.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 Tr({descriptor:e,records:t,client:n,onApplied:i}){let o=Dr(),r=e.id,a=Cn({id:r,client:n}),c=Cn(!0);a.current={id:r,client:n};let[s,f]=me([]),[u,l]=me(!1),[C,P]=me(""),[R,D]=me(""),[S,m]=me(""),[v,h]=me([]),[y,M]=me([]),[A,_]=me([]),[I,N]=me(null),[L,g]=me(null),[b,O]=me(null),[k,j]=me(!1),[H,p]=me(!1),[F,z]=me(""),[te,V]=me(""),[Y,X]=me(""),x=()=>c.current&&a.current.id===r&&a.current.client===n,E=async(d)=>{try{return await d()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};Ar(()=>{c.current=!0,N(null),g(null),O(null),j(!1),z(""),V(""),X(""),h([]),M([]),_([]),m("");let d=!0;return l(!1),p(!1),f([]),P(""),D(""),n.providers(r).then((T)=>{if(!d||a.current.id!==r||a.current.client!==n)return;if(l(!0),T.ok)f(T.data),P(T.data[0]?.resourceId??""),D(T.data[0]?.allowedModels[0]??"");else z(T.error.message)}).catch(()=>{if(d)l(!0),z("AI configuration is unavailable.")}),()=>{d=!1,c.current=!1}},[r,n]);let J=()=>{try{let d=Er(e,t,{resourceId:C,model:R,instruction:S,recordIds:v,sourceFieldIds:y,targetFieldIds:A});g(structuredClone(d.records.map((T)=>({id:T.id,version:T.expectedVersion,values:Object.fromEntries(d.sourceFieldIds.map((q)=>[q,t.find((be)=>be.id===T.id)?.values[q]??null]))})))),N(d),j(!1),z(""),V("")}catch(d){z(d instanceof Error?d.message:"Invalid selection.")}},ne=async()=>{if(!I||H)return;let d=I,T=k;p(!0),j(!0),z("");let q=await E(()=>n.propose(r,d));if(!x())return;if(p(!1),!q.ok){if(!T&&q.error.status>=400&&q.error.status<500)j(!1);z(`${q.error.message} Retry keeps the original selection and versions.`);return}O(q.data),X(q.data.id),j(!1)},ue=async()=>{if(!b||H)return;let d=b,T=k;p(!0),j(!0),z("");let q=await E(()=>n.confirm(r,d));if(!x())return;if(p(!1),!q.ok){if(!T&&q.error.status>=400&&q.error.status<500)j(!1);z(`${q.error.message} The reviewed proposal keeps its original versions.`);return}V(`${q.data.items.length} records filled${q.data.replayed?"; original receipt recovered":""}.`),O(null),N(null),g(null),j(!1);try{await i?.()}catch{if(x())z("The fill committed. Refresh the Collection to see its records.")}},B=async()=>{if(H||I||b)return;p(!0),z("");let d=await E(()=>n.get(r,Y));if(!x())return;if(p(!1),d.ok)O(d.data),j(!1),V("");else z(d.error.message)},se=(d,T,q)=>q(d.includes(T)?d.filter((be)=>be!==T):[...d,T]),W=H||!!I||!!b,ge=e.fields.filter((d)=>hn.includes(d.type)),w=s.find((d)=>d.resourceId===C);return ce("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[oe("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."}),F&&oe("p",{role:"alert",children:F}),te&&oe("p",{role:"status",children:te}),u&&s.length===0&&oe("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),oe("form",{onSubmit:(d)=>{d.preventDefault(),J()},children:ce("fieldset",{disabled:W,style:{minWidth:0},children:[oe("legend",{children:"AI fill request"}),ce("label",{children:["AI resource"," ",ce("select",{"aria-label":"AI resource",value:C,onChange:(d)=>{P(d.target.value),D(s.find((T)=>T.resourceId===d.target.value)?.allowedModels[0]??"")},children:[oe("option",{value:"",children:"Choose resource"}),s.map((d)=>oe("option",{value:d.resourceId,children:d.name},d.resourceId))]})]}),ce("label",{htmlFor:o,children:["Model"," ",w?.allowedModels.length?oe("select",{id:o,"aria-label":"AI model",value:R,onChange:(d)=>D(d.target.value),children:w.allowedModels.map((d)=>oe("option",{value:d,children:d},d))}):oe("input",{id:o,"aria-label":"AI model",maxLength:200,value:R,onChange:(d)=>D(d.target.value)})]}),ce("label",{children:["Instructions"," ",oe("textarea",{"aria-label":"AI instructions",maxLength:2000,value:S,onChange:(d)=>m(d.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),ce("fieldset",{children:[oe("legend",{children:"Source fields to send"}),ge.map((d)=>ce("label",{style:{display:"block"},children:[oe("input",{type:"checkbox","aria-label":`Send ${d.name}`,checked:y.includes(d.id),onChange:()=>se(y,d.id,M)}),d.name]},d.id))]}),ce("fieldset",{children:[oe("legend",{children:"Fields to fill"}),ge.map((d)=>ce("label",{style:{display:"block"},children:[oe("input",{type:"checkbox","aria-label":`Fill ${d.name}`,checked:A.includes(d.id),onChange:()=>se(A,d.id,_)}),d.name]},d.id))]}),ce("fieldset",{children:[oe("legend",{children:"Target records from this page"}),t.map((d)=>ce("label",{style:{display:"block",overflowWrap:"anywhere"},children:[oe("input",{type:"checkbox","aria-label":`AI record ${d.id}`,checked:v.includes(d.id),onChange:()=>se(v,d.id,h)}),d.id," · version ",d.version]},d.id))]}),oe("button",{type:"submit",disabled:!C,children:"Review AI request"})]})}),I&&!b&&ce("section",{"aria-label":"AI data disclosure",children:[ce("p",{children:["Selected service: ",I.resourceId," · model ",I.model," · schema"," ",I.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),oe("p",{children:I.instruction}),oe("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(L,null,2)}),oe("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),oe("button",{type:"button",disabled:H,onClick:()=>void ne(),children:k?"Retry original AI request":"Generate proposal"}),oe("button",{type:"button",disabled:H||k,onClick:()=>{N(null),g(null),z("")},children:"Cancel AI request"})]}),b&&ce("section",{"aria-label":"AI fill confirmation",children:[ce("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",b.id," · ",b.provider," · schema ",b.schemaVersion]}),b.schemaVersion!==e.schemaVersion&&oe("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),b.rows.map((d)=>ce("div",{style:{overflowWrap:"anywhere"},children:[ce("p",{children:[d.id," · original version ",d.expectedVersion]}),Object.keys(d.values).map((T)=>ce("div",{children:[oe("strong",{children:e.fields.find((q)=>q.id===T)?.name??T}),ce("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(d.before[T]),`
|
|
10
|
+
`,"Suggested: ",JSON.stringify(d.values[T])]})]},T))]},d.id)),oe("button",{type:"button",disabled:H,onClick:()=>void ue(),children:k?"Retry original AI fill":"Confirm fill"}),oe("button",{type:"button",disabled:H||k,onClick:()=>{O(null),N(null),g(null),z("")},children:"Dismiss proposal"})]}),ce("label",{children:["Recover a saved proposal"," ",oe("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:Y,onChange:(d)=>X(d.target.value),disabled:W,style:{width:"100%",boxSizing:"border-box"}})]}),oe("button",{type:"button",disabled:W||!/^[a-f0-9]{64}$/.test(Y),onClick:()=>void B(),children:"Load saved proposal"})]})}import{jsx as U,jsxs as Q}from"react/jsx-runtime";var Nr=[{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 Is({fields:e,onChange:t,lockedIds:n=[],collections:i=[]}){let o=(r,a)=>t(e.map((c,s)=>s===r?{...c,...a}:c));return Q("div",{className:"flex flex-col gap-3",children:[e.map((r,a)=>{let c=n.includes(r.id);return Q("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:[U("input",{"aria-label":`Field ${a+1} name`,placeholder:"Display name",value:r.name,onChange:(s)=>o(a,{name:s.target.value})}),U("input",{"aria-label":`Field ${a+1} ID`,placeholder:"field_id",value:r.id,disabled:c,onChange:(s)=>o(a,{id:s.target.value})}),U("select",{"aria-label":`Field ${a+1} type`,className:"rounded-md border bg-background px-2 text-sm",value:r.type,disabled:c,onChange:(s)=>{let f=s.target.value,u={id:r.id,name:r.name,type:f,required:Pe({type:f})?!1:r.required??!1};if(f==="formula")u.formula={expression:""};if(f==="rollup")u.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(f==="singleSelect"||f==="multipleSelect")u.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((l,C)=>C===a?u:l))},children:Nr.map((s)=>U("option",{value:s.value,children:s.name},s.value))}),Q("div",{className:"flex items-center gap-2",children:[Q("label",{className:"flex items-center gap-1 text-xs",children:[U("input",{type:"checkbox",checked:r.required??!1,disabled:c||n.length>0||Pe(r),onChange:(s)=>o(a,{required:s.target.checked})}),"Required"]}),!c&&U("button",{type:"button",onClick:()=>t(e.filter((s,f)=>f!==a)),children:"Remove"})]}),(r.type==="singleSelect"||r.type==="multipleSelect")&&U("input",{className:"md:col-span-4","aria-label":`Field ${a+1} options`,placeholder:"Open, Done",value:r.options?.map((s)=>s.name).join(", ")??"",disabled:c,onChange:(s)=>o(a,{options:s.target.value.split(",").map((f,u)=>({id:f.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${u}`,name:f.trim()})).filter((f)=>f.name)})}),r.type==="linkedRecord"&&Q("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Q("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",Q("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} linked collection`,value:r.link?.collectionId??"",disabled:c,onChange:(s)=>{let f=i.find((u)=>u.id===s.target.value);o(a,{link:{collectionId:s.target.value,displayFieldId:f?.fields.find((u)=>u.type==="singleLineText"||u.type==="longText")?.id??""}})},children:[U("option",{value:"",children:"Choose collection…"}),i.map((s)=>U("option",{value:s.id,children:s.name},s.id))]})]}),Q("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",Q("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} record label`,value:r.link?.displayFieldId??"",disabled:c||!r.link?.collectionId,onChange:(s)=>o(a,{link:{collectionId:r.link?.collectionId??"",displayFieldId:s.target.value}}),children:[U("option",{value:"",children:"Choose text field…"}),i.find((s)=>s.id===r.link?.collectionId)?.fields.filter((s)=>s.type==="singleLineText"||s.type==="longText").map((s)=>U("option",{value:s.id,children:s.name},s.id))]})]})]}),r.type==="lookup"&&Q("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Q("label",{children:["Through linked field"," ",Q("select",{"aria-label":`Field ${a+1} lookup link`,value:r.lookup?.linkFieldId??"",disabled:c,onChange:(s)=>o(a,{lookup:{linkFieldId:s.target.value,targetFieldId:""}}),children:[U("option",{value:"",children:"Choose linked field…"}),e.filter((s)=>s.type==="linkedRecord"&&s.link).map((s)=>U("option",{value:s.id,children:s.name},s.id))]})]}),Q("label",{children:["Read target field"," ",Q("select",{"aria-label":`Field ${a+1} lookup target`,value:r.lookup?.targetFieldId??"",disabled:c||!r.lookup?.linkFieldId,onChange:(s)=>o(a,{lookup:{linkFieldId:r.lookup?.linkFieldId??"",targetFieldId:s.target.value}}),children:[U("option",{value:"",children:"Choose target field…"}),i.find((s)=>s.id===e.find((f)=>f.id===r.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((s)=>!Pe(s)&&s.type!=="linkedRecord").map((s)=>U("option",{value:s.id,children:s.name},s.id))]})]}),U("small",{children:"Computed from linked records. Values cannot be edited."})]}),r.type==="formula"&&Q("div",{className:"flex flex-col gap-1 md:col-span-4",children:[Q("label",{children:["Formula",U("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:r.formula?.expression??"",onChange:(s)=>o(a,{formula:{expression:s.target.value}})})]}),U("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."}),Q("small",{children:["References:"," ",e.filter((s)=>s.id!==r.id&&(s.type==="singleLineText"||s.type==="longText"||s.type==="date"||s.type==="number"||s.type==="formula"||s.type==="rollup")).map((s)=>`{${s.id}}`).join(", ")||"None yet"]})]}),r.type==="rollup"&&Q("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[Q("label",{children:["Through linked field"," ",Q("select",{"aria-label":`Field ${a+1} rollup link`,value:r.rollup?.linkFieldId??"",onChange:(s)=>o(a,{rollup:{linkFieldId:s.target.value,targetFieldId:"",function:r.rollup?.function??"sum"}}),children:[U("option",{value:"",children:"Choose linked field…"}),e.filter((s)=>s.type==="linkedRecord"&&s.link).map((s)=>U("option",{value:s.id,children:s.name},s.id))]})]}),Q("label",{children:["Aggregate"," ",Q("select",{"aria-label":`Field ${a+1} rollup function`,value:r.rollup?.function??"sum",onChange:(s)=>{let f=s.target.value,u=i.find((l)=>l.id===e.find((C)=>C.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((l)=>l.id===r.rollup?.targetFieldId);o(a,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:f==="count"||u?.type==="number"?r.rollup?.targetFieldId??"":"",function:f}})},children:[U("option",{value:"sum",children:"Sum"}),U("option",{value:"average",children:"Average"}),U("option",{value:"min",children:"Minimum"}),U("option",{value:"max",children:"Maximum"}),U("option",{value:"count",children:"Count values"})]})]}),Q("label",{children:["Target field"," ",Q("select",{"aria-label":`Field ${a+1} rollup target`,value:r.rollup?.targetFieldId??"",disabled:!r.rollup?.linkFieldId,onChange:(s)=>o(a,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:s.target.value,function:r.rollup?.function??"sum"}}),children:[U("option",{value:"",children:"Choose target field…"}),i.find((s)=>s.id===e.find((f)=>f.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((s)=>!Pe(s)&&s.type!=="linkedRecord"&&(r.rollup?.function==="count"||s.type==="number")).map((s)=>U("option",{value:s.id,children:s.name},s.id))]})]}),U("small",{className:"w-full",children:"Null targets are skipped. Count counts values; empty sum/count are zero. Other empty aggregates have no result."})]})]},a)}),U("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 Mr(e,t,n){if(Pe(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 xt(e,Ie(t),n)}function Ss(e,t,n,i){let o=Object.create(null);for(let r of e){if(r.type==="lookup"||r.type==="formula"||r.type==="rollup"||r.type==="blob"||r.generation==="autoIncrement")continue;if(!Object.hasOwn(t,r.id)){if(r.required)throw Error(n("{name} is required.",{name:r.name}));continue}let a=t[r.id];if(r.type==="linkedRecord"){if(!Array.isArray(a)||a.some((c)=>typeof c!=="string")||a.length>100||new Set(a).size!==a.length)throw Error(n("{name} needs unique linked records.",{name:r.name}));if(r.required&&!a.length)throw Error(n("{name} is required.",{name:r.name}));o[r.id]=a;continue}if(r.type==="relation"){if(a==null||a===""){if(r.required)throw Error(n("{name} is required.",{name:r.name}));o[r.id]=null;continue}if(typeof a!=="string")throw Error(n("{name} needs a server-provided option.",{name:r.name}));o[r.id]=a;continue}if(r.type==="hyperlink"&&a!==null&&typeof a==="object"){if(!Ye(a))throw Error(n("{name} needs a link.",{name:r.name}));o[r.id]=a;continue}if(r.required&&typeof a==="string"&&!a.trim())throw Error(n("{name} is required.",{name:r.name}));o[r.id]=Ne(Array.isArray(a)?a.join(","):String(a??""),r,i)}return o}function bn({fields:e,values:t,onChange:n,relationClient:i,linkedRecords:o,computedErrors:r,locale:a,ui:c,submitted:s=!1}){let f=fe(a),u=Fr();return U("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((l)=>{let C=l.description?.trim()??"",P=C?`${u}-${l.id}-hint`:void 0,R=Mr(l,t[l.id],a??"en"),S=Boolean(l.required&&Ie(t[l.id])===""&&R)&&!s?"":R,m=S?`${u}-${l.id}-error`:void 0,v=[P,m].filter(Boolean).join(" "),h={...v?{"aria-describedby":v}:{},...S?{"aria-invalid":!0}:{}};return Q("div",{className:"flex flex-col gap-1 text-sm",children:[Q("label",{htmlFor:`${u}-${l.id}`,children:[l.name,l.required?" *":""]}),C?U("p",{id:P,className:"m-0 text-xs opacity-70",children:C}):null,Pe(l)?U("output",{id:`${u}-${l.id}`,"aria-label":f("{name} (read only)",{name:l.name}),...h,children:l.type==="lookup"?Ge(t[l.id]):dt(t[l.id],r?.[l.id],a)}):l.type==="linkedRecord"?U(zt,{...a?{locale:a}:{},field:l,value:t[l.id],labels:o?.[l.id],client:i,onChange:(y)=>n({...t,[l.id]:y}),...h}):l.type==="checkbox"?U("input",{id:`${u}-${l.id}`,"aria-label":`${l.name}${l.required?" *":""}`,type:"checkbox",checked:t[l.id]===!0,onChange:(y)=>n({...t,[l.id]:y.target.checked}),...h}):l.type==="singleSelect"&&c?.Select?U(ln,{ui:c,label:`${l.name}${l.required?" *":""}`,...h,value:String(t[l.id]??""),options:[{value:"",label:f("Choose…")},...(l.options??[]).map((y)=>({value:y.id,label:y.name}))],onChange:(y)=>n({...t,[l.id]:y||null})}):l.type==="multipleSelect"&&c?.MultiSelect?U(c.MultiSelect,{"aria-label":`${l.name}${l.required?" *":""}`,...h,options:(l.options??[]).map((y)=>({value:y.id,label:y.name,slot:jt(l.options,y.id)})),values:Array.isArray(t[l.id])?t[l.id]:[],placeholder:f("Choose…"),onChange:(y)=>n({...t,[l.id]:y})}):l.type==="singleSelect"||l.type==="multipleSelect"?Q("select",{id:`${u}-${l.id}`,"aria-label":`${l.name}${l.required?" *":""}`,...h,className:"min-h-9 rounded-md border bg-background p-2",multiple:l.type==="multipleSelect",value:l.type==="multipleSelect"?Array.isArray(t[l.id])?t[l.id]:[]:String(t[l.id]??""),onChange:(y)=>n({...t,[l.id]:l.type==="multipleSelect"?Array.from(y.target.selectedOptions,(M)=>M.value):y.target.value||null}),children:[l.type==="singleSelect"&&U("option",{value:"",children:f("Choose…")}),l.options?.map((y)=>U("option",{value:y.id,children:y.name},y.id))]}):l.type==="date"&&c?.DatePicker?(()=>{let y={kind:Ut(l),timeZone:He(l)?.timeZone},M=String(t[l.id]??"");return U(c.DatePicker,{id:`${u}-${l.id}`,"aria-label":`${l.name}${l.required?" *":""}`,...h,value:Xt(M,y),withTime:y.kind==="auto"?Me(M):y.kind==="datetime",fixedKind:y.kind!=="auto",clearable:!l.required,onChange:(A)=>n({...t,[l.id]:A?en(A,M,y):null})})})():l.type==="hyperlink"?U(ct,{field:l,id:`${u}-${l.id}`,ariaLabel:`${l.name}${l.required?" *":""}`,describedBy:h["aria-describedby"],invalid:Boolean(S),locale:a,inputClassName:"min-h-9 min-w-0 rounded-md border bg-background p-2",text:typeof t[l.id]==="string"?String(t[l.id]):rt(Ye(t[l.id])?t[l.id]:null),onChange:(y)=>{let M=y.trim().startsWith("{")?qe(y):null;n({...t,[l.id]:M??(y||null)})}}):l.type==="longText"?U("textarea",{id:`${u}-${l.id}`,"aria-label":`${l.name}${l.required?" *":""}`,...h,className:"rounded-md border bg-background p-2",value:String(t[l.id]??""),onChange:(y)=>n({...t,[l.id]:y.target.value||null})}):U("input",{id:`${u}-${l.id}`,"aria-label":`${l.name}${l.required?" *":""}`,...h,className:"min-h-9 min-w-0 rounded-md border bg-background p-2",type:l.type==="number"?"number":l.type==="date"?"date":"text",step:l.type==="number"?"any":void 0,value:l.type==="date"?String(t[l.id]??"").slice(0,10):String(t[l.id]??""),onChange:(y)=>n({...t,[l.id]:y.target.value===""?null:l.type==="number"?Number(y.target.value):l.type==="date"&&t[l.id]?Wt(t[l.id],y.target.value):y.target.value})}),S?U("span",{id:m,className:"text-xs text-red-600",children:S}):null]},l.id)})})}function Lr(e,t,n){if(t==="isEmpty")return;let i=Pe(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 o=Number(n);if(!n.trim()||!Number.isFinite(o))throw Error("Filter needs a number.");return o}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(Pe(e)&&!et(e))throw Error("Computed filters are not available for this field.");if((e.type==="multipleSelect"||e.type==="linkedRecord")&&t!=="contains")return n.split(",").map((o)=>o.trim());return n}function As({fields:e,view:t,onChange:n,onError:i}){let o=e.filter(et),[r,a]=It(o[0]?.id??""),c=o.some((m)=>m.id===r)?r:o[0]?.id??"",[s,f]=It("contains"),u=c?(()=>{let m=e.find((v)=>v.id===c);return m&&Pe(m)?m.resultType:m?.type})():void 0,l=u==="number"?["is","isNot","isEmpty"]:u==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],C=l.includes(s)?s:u==="number"||u==="date"?"is":"contains",[P,R]=It(""),S=[...t.columnOrder.flatMap((m)=>{let v=e.find((h)=>h.id===m);return v?[v]:[]}),...e.filter((m)=>!t.columnOrder.includes(m.id))];return Q("div",{className:"flex flex-wrap items-end gap-3",children:[Q("label",{className:"flex min-w-52 flex-col gap-1 text-sm",children:["Search",U("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})})]}),Q("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(m)=>{m.preventDefault();let v=e.find((y)=>y.id===c);if(!v)return;let h;try{h=Lr(v,C,P)}catch(y){i(y instanceof Error?y.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:c,operator:C,...C==="isEmpty"?{}:{value:h}}]}})},children:[Q("label",{className:"flex flex-col gap-1 text-sm",children:["Filter field",U("select",{className:"h-9 rounded-md border bg-background px-2",value:c,onChange:(m)=>a(m.target.value),children:o.map((m)=>U("option",{value:m.id,children:m.name},m.id))})]}),U("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:C,onChange:(m)=>f(m.target.value),children:l.map((m)=>U("option",{value:m,children:m==="isNot"?"is not":m==="isEmpty"?"is empty":m==="onOrAfter"?"on or after":m},m))}),C!=="isEmpty"&&U("input",{type:u==="number"?"number":u==="date"?"date":"text",step:u==="number"?"any":void 0,className:"min-h-9 max-w-40 rounded-md border bg-background p-2","aria-label":"Filter value",value:P,onChange:(m)=>R(m.target.value)}),U("button",{type:"submit",disabled:!c,children:"Apply filter"}),U("button",{type:"button",onClick:()=>{let m={...t};delete m.filter,n(m)},children:"Clear filter"})]}),Q("details",{className:"relative",children:[U("summary",{className:"cursor-pointer rounded-md border px-3 py-2 text-sm",children:"Columns"}),U("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:S.map((m,v)=>Q("div",{className:"flex items-center gap-2 text-sm",children:[Q("label",{className:"flex flex-1 items-center gap-2",children:[U("input",{type:"checkbox",checked:!t.hiddenColumns.includes(m.id),disabled:t.type==="form"&&m.required===!0,onChange:(h)=>n({...t,hiddenColumns:h.target.checked?t.hiddenColumns.filter((y)=>y!==m.id):[...t.hiddenColumns,m.id]})}),m.name]}),U("button",{type:"button","aria-label":`Move ${m.name} left`,disabled:v===0,onClick:()=>{let h=S.map((M)=>M.id),y=h[v-1];if(y!==void 0)[h[v-1],h[v]]=[m.id,y];n({...t,columnOrder:h})},children:"←"}),U("button",{type:"button","aria-label":`Move ${m.name} right`,disabled:v===S.length-1,onClick:()=>{let h=S.map((M)=>M.id),y=h[v+1];if(y!==void 0)[h[v],h[v+1]]=[y,m.id];n({...t,columnOrder:h})},children:"→"})]},m.id))})]})]})}export{Tr as CollectionAiControls,Pr as CollectionAttachments,Sr as CollectionAutomationControls,yr as CollectionConversionControls,hr as CollectionLiveChanges,As as CollectionQueryControls,kr as CollectionRecordActivity,Rr as CollectionShareControls,mr as CollectionTransferControls,Is as FieldDefinitions,bn as RecordFields,Lr as filterValueForField,Ss as validateDraft};
|