@uibot/renderer-react 0.19.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collection-application.js +12 -12
- package/dist/collection-editors.d.ts +3 -2
- package/dist/collection-editors.js +10 -10
- package/dist/collection-grid/field-changes.d.ts +9 -0
- package/dist/collection-grid/paged-locale.d.ts +6 -0
- package/dist/collection-grid/relation-editor.d.ts +3 -0
- package/dist/collection-ui.d.ts +2 -0
- package/dist/collection-views/aggregate.d.ts +2 -0
- package/dist/collection-views/record-creator.d.ts +2 -1
- package/dist/collection-views/shared.d.ts +7 -1
- package/dist/collection-views.js +10 -10
- package/dist/collection-workspace.js +13 -13
- package/dist/index.js +12 -12
- package/dist/paged-collection-grid.js +12 -12
- package/package.json +4 -4
package/dist/collection-views.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
function Ls(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var Mt=["blue","green","red","orange","gray","teal","purple"];function li(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 Nr(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((l)=>l.id===i.fieldId),a=o?.type==="number"||o?.type==="rating"||o?.type==="autoNumber"?e.reduce((l,s)=>l+(li(s.values[i.fieldId])??0),0):0;return{fieldId:i.fieldId,fn:"sum",value:a}})}function Mr(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function di(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function ci(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 Lr(e,t){if(!t)return!0;if(Mr(t)){let n=t.filterSet.map((i)=>Mr(i)?Lr(e,i):di(i)?ci(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 Or(e,t,n,i){let o=e.views.find((g)=>g.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((g)=>Lr(g,o.filter));if(o.sort?.length)r.sort((g,C)=>{for(let b of o.sort??[]){let y=g.values[b.fieldId],m=C.values[b.fieldId];if(y===m)continue;if(y==null)return 1;if(m==null)return-1;let v=e.fields.find((E)=>E.id===b.fieldId)?.type,f=(E)=>{if(["number","rating","autoNumber"].includes(v??"")&&typeof E==="number")return E;if(["date","createdTime","lastModifiedTime"].includes(v??"")){let D=Date.parse(String(E));if(Number.isFinite(D))return D}return String(E)},k=f(y),S=f(m);if(k===S)continue;let R=k<S?-1:1;return b.direction==="desc"?-R:R}return g.id<C.id?-1:g.id===C.id?0:1});let a=o.projection?.length?e.fields.filter((g)=>o.projection?.includes(g.id)):e.fields,l=i?.search?.trim().toLowerCase();if(l)r=r.filter((g)=>a.some((C)=>String(g.values[C.id]??"").toLowerCase().includes(l)));let s=Nr(r,o.aggregates,e.fields),u=o.group?.fieldId;if(!u)return{view:o,columns:a,rows:r,...s.length?{aggregates:s}:{}};let d=[],c=new Map;for(let g of r){let C=String(g.values[u]??"");if(!c.has(C))c.set(C,[]),d.push(C);c.get(C)?.push(g)}let p=d.map((g)=>{let C=c.get(g)??[];return{key:g,fieldId:u,rows:C,aggregates:Nr(C,o.aggregates,e.fields)}});return{view:o,columns:a,rows:r,groups:p,...s.length?{aggregates:s}:{}}}var fn=500,Yn=2000,Gn=new Set(["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"]);function Ne(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function vt(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 Hs(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 l=n[r];if(!(r in n)||l!==null&&!(typeof l==="number"&&Number.isFinite(l))&&!((a==="min"||a==="max")&&typeof l==="string"&&Number.isFinite(Date.parse(l))))throw Error(`Invalid aggregate value ${r}.`);o[r]=l}return{groups:i,values:o}})}var ui=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,pi=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function _r(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function Ve(e,t){return{code:e,...t}}function gi(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function Wn(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function Br(e,t){if(t.aggregates.length===0)return Ve("empty");if(t.aggregates.length>8||t.groupBy.length>3)return Ve("too_many");let n=new Set;for(let o of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(o.fn))return Ve("function");if(!ui.test(o.as)||n.has(o.as)||t.groupBy.includes(o.as))return Ve("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 Ve(o.fn==="sum"?"sum_field":"unknown_field",{alias:o.as,...o.fieldId!==void 0?{fieldId:o.fieldId}:{}});if(o.fn==="sum"&&!Wn(r))return Ve("sum_field",{fieldId:r.id,alias:o.as});if(o.fn==="avg"&&!Wn(r))return Ve("numeric_field",{fieldId:r.id,alias:o.as});if((o.fn==="min"||o.fn==="max")&&!Wn(r)&&r.type!=="date"&&!((r.type==="formula"||r.type==="rollup")&&r.resultType==="date"))return Ve("extrema_field",{fieldId:r.id,alias:o.as});if((o.fn==="filled"||o.fn==="empty")&&!vt(r))return Ve("queryable_field",{fieldId:r.id,alias:o.as});if(o.fn==="count"&&!vt(r))return Ve("count_field",{fieldId:r.id,alias:o.as})}let i=new Set;for(let o of t.groupBy){if(i.has(o))return Ve("duplicate_group",{fieldId:o});i.add(o);let r=e.fields.find((a)=>a.id===o);if(!r)return Ve("unknown_field",{fieldId:o});if(!pi.has(r.type)&&!gi(r))return Ve("not_groupable",{fieldId:o})}return null}var Ur=(e)=>String(e).padStart(2,"0");function Xe(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 xt(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=Xe(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 yn(e,t){let n=Xe(e,t??"UTC");return`${n.year}-${Ur(n.month)}-${Ur(n.day)}`}var mi=/^[a-z][a-z0-9_-]{0,31}$/,bn=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function qr(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 fi(e){if(!bn(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"||!qr(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(!bn(t)||Object.keys(t).length!==2||typeof t.kind!=="string"||!mi.test(t.kind)||typeof t.id!=="string"||!t.id||t.id.length>200)return"hyperlink reference is invalid"}return null}var Lt=(e)=>fi(e)===null;function tn(e){if(!bn(e)||typeof e.url!=="string")return"";return typeof e.text==="string"&&e.text.trim()?e.text:e.url}function $r(e){if(!bn(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 kt(e){let t=e.trim();if(!t)return null;if(t.startsWith("{"))try{let r=JSON.parse(t);return Lt(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(!qr(o))return null;return i&&i!==o?{url:o,text:i}:{url:o}}function nn(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 l=Xe(t,n);i[o.id]=`${l.year}-${String(l.month).padStart(2,"0")}-${String(l.day).padStart(2,"0")}`}else i[o.id]=t.toISOString()}}return i}var Zn=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],hn=new Set(["pastDays","nextDays","daysAgo","daysFromNow"]),zr={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"]},Ot=new Set(["isEmpty","isNotEmpty"]);function Ye(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 jr(e){let t=Ye(e);return t?zr[t]:[]}var Jn=/^\d{4}-\d{2}-\d{2}$/,yi=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function Qn(e){if(!yi(e))return!1;let t=e.mode;if(!Zn.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&&Jn.test(e.date);if(t==="dateRange")return typeof e.date==="string"&&Jn.test(e.date)&&typeof e.to==="string"&&Jn.test(e.to)&&e.date<=e.to;if(hn.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function Hr(e,t){if(!e)return"unknown field";let n=Ye(e),i=t.operator==="contains"&&(n==="number"||n==="checkbox"||n==="date"||n==="singleSelect");if(!n||!(zr[n].includes(t.operator)||i))return"operator not allowed";if(Ot.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 Qn(o)||typeof o==="string"&&Number.isFinite(Date.parse(o))?null:"date required"}}var bi={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},wl=Array.from(new Set(Object.values(bi).flat()));var Il=Object.freeze([Object.freeze({name:"manifest",summary:"Describe query operations and list the derived resource index.",positionals:Object.freeze([]),options:Object.freeze([])}),Object.freeze({name:"search",summary:"Search resources with deterministic bilingual ranking and reasons.",positionals:Object.freeze([Object.freeze({name:"text",property:"text",type:"string",required:!1})]),options:Object.freeze([...[["function","functions"],["scenario","scenarios"],["unit","units"],["industry","industries"]].map(([e,t])=>Object.freeze({name:e,property:t,type:"string",multiple:!0,cliEncoding:"comma-separated"})),Object.freeze({name:"kind",property:"kinds",type:"resource-kind",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"tag",property:"tags",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"category",property:"categories",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"capability",property:"capabilities",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"maturity",property:"maturities",type:"resource-maturity",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"limit",property:"limit",type:"positive-integer"})])}),Object.freeze({name:"get",summary:"Resolve one canonical resource id or unambiguous alias.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([])}),Object.freeze({name:"build",summary:"Plan dependency closure and gaps without writing or installing.",positionals:Object.freeze([Object.freeze({name:"root",property:"roots",type:"string",required:!0,variadic:!0})]),options:Object.freeze([])}),Object.freeze({name:"docs",summary:"Read curated public documentation for one resource.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([{name:"locale",property:"locale",type:"string"},{name:"page",property:"page",type:"positive-integer"}])}),Object.freeze({name:"examples",summary:"Read one bounded page of examples and exact dependencies. Follow nextPage for complete source.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([{name:"page",property:"page",type:"positive-integer"}])}),Object.freeze({name:"install-plan",summary:"Describe distribution channels and fixed snapshot identity/closure without installing or writing.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([])})]);var hi=["background","foreground","card","card-foreground","popover","popover-foreground","primary","primary-foreground","secondary","secondary-foreground","muted","muted-foreground","accent","accent-foreground","border","input","ring","destructive","destructive-foreground","success","success-foreground","warning","warning-foreground"],El=[...hi,"radius","font-display","font-body","font-mono"];function Ci(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function _l(e,t){if(t===e.draft)return e;return{...e,draft:t}}function vi(e){return e.draft!==e.savedContent}function Bl(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 Ul(e,t){if(vi(e))return e;let n=Ci(t);if(e.expectedRevisionId===n.expectedRevisionId&&e.savedContent===n.savedContent&&e.draft===n.draft&&e.format===n.format&&e.schemaVersion===n.schemaVersion)return e;return n}var ot=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),Pt=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),wt=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,Kr=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,Cn=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),Wr=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every(Cn)&&new Set(e).size===e.length;function xi(e){if(!ot(e)||!Pt(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!Cn(e.id)||!wt(e.name,200)||!["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect","linkedRecord","lookup","formula","rollup"].includes(String(e.type))||e.required!==void 0&&typeof e.required!=="boolean")return!1;if(e.options!==void 0&&(!Array.isArray(e.options)||e.options.length>100||e.options.some((t)=>!ot(t)||!Pt(t,["id","name"])||!Cn(t.id)||!wt(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&&(!ot(o)||!Pt(o,[...i])||i.some((r)=>!wt(o[r],r==="expression"?2048:512))))return!1}return!0}function $l(e){if(!ot(e)||!Pt(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))||!wt(e.collectionId,512)||!wt(e.authorId,512)||typeof e.createdAt!=="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.createdAt)||!Number.isFinite(Date.parse(e.createdAt)))return!1;try{if(new TextEncoder().encode(JSON.stringify(e)).length>131072)return!1}catch{return!1}let{descriptor:t,view:n}=e;if(!ot(t)||!Pt(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!wt(t.name,200)||!Kr(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(xi)||new Set(t.fields.map((r)=>r.id)).size!==t.fields.length)return!1;if(!ot(n)||!Pt(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!Cn(n.id)||!wt(n.name,200)||!Kr(n.version)||!Wr(n.columnOrder)||!Wr(n.hiddenColumns)||!ot(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)=>ot(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)=>!ot(r)||!Pt(r,["fieldId","direction"])||!o(r.fieldId)||!["asc","desc"].includes(String(r.direction)))))return!1;return!0}import{createContext as ki,useCallback as Pi,useContext as wi,useLayoutEffect as Xn,useMemo as Si,useRef as Yr,useState as Ri}from"react";var Ii=ki(void 0);function Vt(e,t={}){let n=wi(Ii),i=Yr({}),{dirty:o,busy:r}=e,{onDirtyChange:a,onBusyChange:l}=t;Xn(()=>{n?.(i.current,{dirty:o,busy:r}),a?.(o),l?.(r)},[n,o,r,a,l]),Xn(()=>()=>{n?.(i.current),a?.(!1),l?.(!1)},[n,a,l])}function sc(){let e=Yr(new Map),[t,n]=Ri({dirty:!1,busy:!1}),i=Pi((o,r)=>{if(r)e.current.set(o,r);else e.current.delete(o);let a=[...e.current.values()],l=a.some((u)=>u.dirty),s=a.some((u)=>u.busy);n((u)=>u.dirty===l&&u.busy===s?u:{dirty:l,busy:s})},[]);return{...t,report:i}}function vn(e,t){let n=Si(()=>({active:!0,client:e,id:t}),[e,t]);return Xn(()=>(n.active=!0,()=>{n.active=!1}),[n]),n}import{useEffect as On,useRef as un,useState as qe}from"react";import{useId as ha,useState as lr}from"react";var Ge=(e)=>String(e).padStart(2,"0"),Ai=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function Me(e){let t=e.formatting;return Ai(e)&&t&&"date"in t?t:void 0}function xn(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function Gr(e){let t=Me(e);return!t?"auto":t.time==="none"?"date":"datetime"}function er(e,t,n,i){switch(i){case"YYYY/MM/DD":return`${e}/${Ge(t)}/${Ge(n)}`;case"MM/DD/YYYY":return`${Ge(t)}/${Ge(n)}/${e}`;case"DD/MM/YYYY":return`${Ge(n)}/${Ge(t)}/${e}`;case"YYYY年M月D日":return`${e}年${t}月${n}日`;default:return`${e}-${Ge(t)}-${Ge(n)}`}}function _t(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 er(Number(i[1]),Number(i[2]),Number(i[3]),t.date);let l=new Date(n);if(!Number.isFinite(l.getTime()))return n;let s=Xe(l,t.timeZone??"UTC");return er(s.year,s.month,s.day,t.date)}let o=i?xt({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=Xe(o,t.timeZone),a=er(r.year,r.month,r.day,t.date);if(t.time==="12h"){let l=r.hour%12||12;return`${a} ${l}:${Ge(r.minute)} ${r.hour<12?"AM":"PM"}`}return`${a} ${Ge(r.hour)}:${Ge(r.minute)}`}function kn(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 Pn(e,t){let n=e?.findIndex((r)=>r.id===t)??-1,i=n>=0?e?.[n]?.color:void 0,o=Mt.findIndex((r)=>r===i);return o>=0?o:n}var Di={"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 H(e="en"){return(t,n={})=>(e==="zh-CN"?Di[t]??t:t).replace(/\{(\w+)\}/g,(i,o)=>String(n[o]??i))}function fc(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 l=Math.max(0,Math.min(n*i-1,r*i+a+(o?-1:1)));r=Math.floor(l/i),a=l%i}return{row:Math.max(0,Math.min(n-1,r)),column:Math.max(0,Math.min(i-1,a))}}function Ei(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 Je(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function yc(e,t,n,i){let o=Ei(n,i),r=[];for(let a=o.firstRow;a<=o.lastRow;a++){let l=[];for(let s=o.firstColumn;s<=o.lastColumn;s++){let u=t[s],d=e[a]?.values[u?.id??""],c=u?.type==="json"&&d!=null?JSON.stringify(d):u?.type==="hyperlink"?$r(d):Je(d);l.push(/[\t\r\n"]/.test(c)?`"${c.replaceAll('"','""')}"`:c)}r.push(l.join("\t"))}return r.join(`
|
|
2
|
-
`)}function
|
|
3
|
-
`||s==="\r")){if(o.push(r),r="",s!=="\t"){if(i.push(o),o=[],s==="\r"&&e[
|
|
4
|
-
`)l++}}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 ct(e,t,n="en"){let i=H(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=kt(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=Me(t);if(r){let S=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!S)throw Error(i("{name} needs a date.",{name:t.name}));let[,R,E,D]=S,T=new Date(Date.UTC(Number(R),Number(E)-1,Number(D)));if(T.getUTCMonth()!==Number(E)-1||T.getUTCDate()!==Number(D))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 yn(new Date(e),r.timeZone);return`${R}-${E}-${D}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return xt({year:Number(R),month:Number(E),day:Number(D)},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[,l,s,u,d,c,p,g,C]=a,b=Number(l),y=Number(s),m=Number(u),f=[31,b%4===0&&(b%100!==0||b%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(y<1||y>12||m<1||m>(f[y-1]??0)||Number(d??0)>23||Number(c??0)>59||Number(p??0)>59||Number(g??0)>23||Number(C??0)>59)throw Error(i("{name} needs a valid calendar date.",{name:t.name}));let k=new Date(e);if(!Number.isFinite(k.getTime()))throw Error(i("{name} needs a date.",{name:t.name}));return k.toISOString()}let o=(r)=>{let a=t.options?.find((l)=>l.id===r||l.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 bc(e,t,n,i,o="en"){let r=H(o);try{if(e.length>1048576)throw Error(r("Paste is too large."));let a=Ti(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,u)=>{if(i.column+s.length>n.length)throw Error(r("Paste extends beyond the visible columns."));let d=t[i.row+u];if(!d)throw Error(r("Row is not loaded."));let c={};return s.forEach((p,g)=>{let C=n[i.column+g];if(C?.generation==="autoIncrement")throw Error(r("{name} is auto-generated and cannot be edited.",{name:C.name}));if(C)c[C.id]=ct(p,C,o)}),{op:"update",id:d.id,expectedVersion:d.version,values:c}})}}catch(a){return{ok:!1,message:a instanceof Error?a.message:r("Invalid paste.")}}}function Jr(e,t){let n=Je(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=(u)=>o.find((d)=>d.type===u)?.value??"",a=i.getUTCMilliseconds(),l=r("second"),s=l!=="00"||a?`:${l}${a?`.${String(a).padStart(3,"0")}`:""}`:"";return`${r("year")}-${r("month")}-${r("day")} ${r("hour")}:${r("minute")}${s}`}import{useEffect as Fi,useRef as Ni,useState as Bt}from"react";import{jsx as Ze,jsxs as rn}from"react/jsx-runtime";function Ut(e){if(e==null)return"—";if(Array.isArray(e))return e.map(Ut).join(", ");return String(e)}function on(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((i)=>i.label||i.id).join(", "):void 0)??Ut(e.values[t.id])}function kc(e,t){return Je(e.values[t.id])}function Zr({field:e,value:t,labels:n=[],client:i,onChange:o,disabled:r=!1,locale:a,"aria-describedby":l,"aria-invalid":s}){let u=H(a),d=Array.isArray(t)?t.filter((h)=>typeof h==="string"):[],c=Ni(new Set(d));c.current=new Set(d);let[p,g]=Bt(""),[C,b]=Bt(),[y,m]=Bt([]),[v,f]=Bt(0),[k,S]=Bt({}),[R,E]=Bt({rows:[],next:null,error:"",loading:!0}),D=e.link?.collectionId,T=e.link?.displayFieldId;Fi(()=>{let h=!0;if(E({rows:[],next:null,error:"",loading:!0}),!i||!D||!T){E({rows:[],next:null,error:u("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return i.query(D,{limit:50,search:p,...C?{cursor:C}:{}}).then((x)=>{if(!h)return;if(!x.ok){E({rows:[],next:null,error:x.error.message,loading:!1});return}S((I)=>({...Object.fromEntries(Object.entries(I).filter(([A])=>c.current.has(A))),...Object.fromEntries(x.data.items.map((A)=>{let O=String(A.values[T]??"");return[A.id,O.trim()?O.slice(0,256):A.id]}))})),E({rows:x.data.items,next:x.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(h)E({rows:[],next:null,error:u("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{h=!1}},[i,D,T,p,C,v]);let V=(h)=>k[h]??n.find((x)=>x.id===h)?.label??h;return rn("fieldset",{disabled:r,"aria-label":u("{name} linked records",{name:e.name}),...l?{"aria-describedby":l}:{},...s?{"aria-invalid":!0}:{},className:"flex min-w-0 flex-col gap-2 rounded-md border p-2",children:[Ze("div",{className:"flex flex-wrap gap-1",children:d.map((h)=>rn("span",{className:"rounded border px-2 py-1 text-sm",children:[V(h)," ",Ze("button",{type:"button","aria-label":u("Remove {name}",{name:V(h)}),onClick:()=>o(d.filter((x)=>x!==h)),children:"×"})]},h))}),Ze("input",{"aria-label":u("Search {name} records",{name:e.name}),type:"search",placeholder:u("Search linked records"),value:p,onChange:(h)=>{g(h.target.value),b(void 0),m([])}}),R.loading&&Ze("p",{role:"status",children:u("Loading linked records…")}),R.error&&rn("div",{role:"alert",children:[R.error," ",Ze("button",{type:"button",onClick:()=>f((h)=>h+1),children:u("Retry linked records")})]}),Ze("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:R.rows.map((h)=>rn("label",{className:"flex items-center gap-2 text-sm",children:[Ze("input",{type:"checkbox","aria-label":u("Link {name}",{name:V(h.id)}),checked:d.includes(h.id),disabled:!d.includes(h.id)&&d.length>=100,onChange:(x)=>o(x.target.checked?[...d,h.id]:d.filter((I)=>I!==h.id))}),V(h.id)]},h.id))}),!R.loading&&!R.error&&!R.rows.length&&Ze("p",{children:u("No matching records.")}),rn("div",{className:"flex gap-2",children:[Ze("button",{type:"button",disabled:!y.length||R.loading,onClick:()=>{b(y.at(-1)),m((h)=>h.slice(0,-1))},children:u("Previous linked records")}),Ze("button",{type:"button",disabled:!R.next||R.loading,onClick:()=>{m((h)=>[...h,C]),b(R.next??void 0)},children:u("Next linked records")})]}),Ze("small",{children:u("{count} selected · up to 100 per record across all link fields",{count:d.length})})]})}var Mi={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function wn(e,t,n){return t?H(n)(Mi[t]):e==null?"—":String(e)}function Qr(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 Xr(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function Sn(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function eo(e,t,n){let i=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...Sn(e),filter:Xr(e.filter,i)}}function an(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 to(e,t,n){let{start:i,end:o}=an(n);return{...Sn(e),filter:Xr(e.filter,{fieldId:t,operator:"onOrAfter",value:i},{fieldId:t,operator:"before",value:o})}}function Rn(e,t){let n={id:"date",name:"Date",type:"date"},i=String(ct(t,n)),o=String(ct(String(e),n));return`${i.slice(0,10)}${o.slice(10)}`}function St(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 ze(e,t){let n=t.find((i)=>i.type==="singleLineText"||i.type==="longText");return(n?Je(e.values[n.id]):"")||e.id}function In(e,t,n){if(t.type==="lookup")return Ut(e);if(t.type==="hyperlink")return tn(e);if(t.type==="date"){let i=Me(t);return i?_t(e,i):Jr(e)}if(t.type==="number"){let i=xn(t);return i?kn(e,i):Je(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return wn(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 Je(e)}import{createContext as Li,useContext as Oi,useEffect as Vi,useId as _i,useLayoutEffect as Bi,useMemo as Ui,useRef as qi,useState as qt}from"react";import{jsx as je,jsxs as $t}from"react/jsx-runtime";var ro=Li(void 0);function Oc(e){return je(ro.Provider,{value:e.client,children:e.children})}var An=()=>Oi(ro),no=(e)=>/^https?:/i.test(e);function $i(e){let t=An();if(!Lt(e.value))return null;let n=e.value,i=t?.href?.(n)??n.url;return je("a",{href:i,title:n.url,"data-uibot-link":n.ref?.kind??(no(i)?"external":"internal"),...no(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:tn(n)})}var sn=(e)=>e?JSON.stringify(e):"",zi=(e)=>e.trim().startsWith("{")?kt(e):null;function Dn(e){let t=Ui(()=>H(e.locale),[e.locale]),n=An(),i=_i(),o=zi(e.text),[r,a]=qt(()=>o?"":e.text),[l,s]=qt(!1),[u,d]=qt([]),[c,p]=qt(""),[g,C]=qt(-1),b=qi(null),[y,m]=qt(null),f=e.field.hyperlink?.kinds?.join(",")??"";Vi(()=>{if(!n||!l||e.disabled)return;let h=new AbortController,x=setTimeout(()=>{p(t("Searching…")),n.search({search:r.trim(),...f?{kinds:f.split(",")}:{},limit:8},{signal:h.signal}).then((I)=>{if(h.signal.aborted)return;d(I.ok?I.data.slice(0,8):[]),p(I.ok?"":I.error.message)}).catch((I)=>{if(!h.signal.aborted)p(I instanceof Error?I.message:String(I))})},200);return()=>{clearTimeout(x),h.abort()}},[n,l,r,f,e.disabled,t]);let k=kt(r),S=(h)=>n?.kinds?.find((x)=>x.id===h)?.label??h,R=[...k&&!k.ref?[{key:"typed",value:k,title:t("Use link {url}",{url:k.url})}]:[],...u.map((h)=>({key:`${h.kind}:${h.id}`,value:{url:h.url,text:h.title,ref:{kind:h.kind,id:h.id}},title:h.title,subtitle:[S(h.kind),h.subtitle].filter(Boolean).join(" · ")}))],E=Boolean(n&&!c&&!u.length&&r.trim()),D=l&&!e.disabled&&(R.length>0||Boolean(c)||E);Bi(()=>{if(!D)return;let h=()=>m(b.current?.getBoundingClientRect()??null);return h(),window.addEventListener("scroll",h,!0),window.addEventListener("resize",h),()=>{window.removeEventListener("scroll",h,!0),window.removeEventListener("resize",h)}},[D]);let T=(h)=>{a(""),C(-1),e.onChange(sn(h.value))},V=(h)=>{a(h),C(-1),e.onChange(h||sn(o))};return $t("div",{style:{display:"grid",gap:4,minWidth:0,height:"100%"},children:[je("input",{ref:b,id:e.id,role:"combobox","aria-label":e.ariaLabel,"aria-expanded":D,"aria-controls":i,"aria-autocomplete":"list","aria-invalid":e.invalid,...e.describedBy?{"aria-describedby":e.describedBy}:{},...g>=0?{"aria-activedescendant":`${i}-${g}`}:{},disabled:e.disabled,placeholder:o?tn(o):t("Search or paste a link"),value:r,style:e.inputStyle,className:e.inputClassName,onFocus:()=>s(!0),onBlur:()=>s(!1),onChange:(h)=>V(h.currentTarget.value),onKeyDown:(h)=>{if(e.onSave||e.onCancel)h.stopPropagation();if(h.key==="ArrowDown"||h.key==="ArrowUp"){if(!R.length)return;h.preventDefault();let x=h.key==="ArrowDown"?1:-1;C((I)=>x>0?(I+1)%R.length:I<=0?R.length-1:I-1)}else if(h.key==="Enter"){h.preventDefault();let x=R[g];if(x)T(x);else e.onSave?.()}else if(h.key==="Tab"&&e.onSave)h.preventDefault(),e.onSave();else if(h.key==="Escape")if(h.preventDefault(),r)V("");else e.onCancel?.()}}),o&&!r&&!e.onSave&&$t("div",{style:{display:"grid",gap:4,minWidth:0,fontSize:12},children:[$t("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[je($i,{value:o,style:{flex:"0 1 auto"}}),je("span",{style:{flex:"1 1 0",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:0.6},children:o.url}),je("button",{type:"button","aria-label":t("Remove link"),title:t("Remove link"),disabled:e.disabled,onMouseDown:(h)=>h.preventDefault(),onClick:()=>e.onChange(""),style:{border:0,background:"none",color:"inherit",cursor:"pointer",opacity:0.6},children:"×"})]}),$t("label",{style:{display:"grid",gap:2},children:[je("span",{style:{opacity:0.7},children:t("Display text")}),je("input",{"aria-label":t("Display text"),placeholder:o.url,value:o.text??"",disabled:e.disabled,className:e.inputClassName,onChange:(h)=>{let x=h.currentTarget.value.slice(0,500),{text:I,...A}=o;e.onChange(sn(x?{...A,text:x}:A))}})]})]}),D&&y&&$t("div",{id:i,role:"listbox","aria-label":t("Link suggestions"),style:{position:"fixed",top:y.bottom+4,left:y.left,width:Math.max(y.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:(h)=>h.preventDefault(),children:[R.map((h,x)=>$t("div",{id:`${i}-${x}`,role:"option","aria-selected":x===g,tabIndex:-1,onMouseEnter:()=>C(x),onClick:()=>T(h),onKeyDown:()=>{},style:{display:"grid",gap:2,padding:"6px 8px",borderRadius:6,cursor:"pointer",background:x===g?"var(--uibot-hover, rgb(0 0 0 / 0.06))":void 0},children:[je("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:h.title}),h.subtitle&&je("span",{style:{fontSize:12,opacity:0.65},children:h.subtitle})]},h.key)),c&&je("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:c}),E&&je("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:t("No matching resources")})]})]})}import{useEffect as so,useId as Hi,useMemo as Ki,useRef as Wi,useState as lo}from"react";var ji=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function ut(e){return ji.test(e)}var it=(e)=>String(e).padStart(2,"0");function oo(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${it(t.getMonth()+1)}-${it(t.getDate())}T${it(t.getHours())}:${it(t.getMinutes())}:${it(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var tr=(e,t)=>{let n=Xe(e,t);return`${n.year}-${it(n.month)}-${it(n.day)}T${it(n.hour)}:${it(n.minute)}`};function io(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!ut(e))return e.slice(0,10);return tr(new Date(e),t.timeZone??"UTC").slice(0,10)}if(ut(e))return tr(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function ao(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||ut(t)))return e;let o=e.length>10?e.slice(11,16):t&&ut(t)?tr(new Date(t),n.timeZone).slice(11,16):"00:00",[r,a,l]=e.slice(0,10).split("-").map(Number),[s,u]=o.split(":").map(Number),d=xt({year:r??0,month:a??1,day:l??1,hour:s??0,minute:u??0},n.timeZone);return Number.isFinite(d.getTime())?d.toISOString():e}import{jsx as pt,jsxs as co}from"react/jsx-runtime";function nr(e,t,n){if(e.type==="blob")return"";try{return ct(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 H(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 Kc({field:e,text:t,disabled:n,id:i,label:o,ariaLabel:r,onChange:a,onSave:l,onCancel:s,locale:u="en",submitted:d=!1,describedBy:c}){let p=Ki(()=>H(u),[u]),g=Hi(),C=Wi(null),b=Boolean(l);so(()=>{if(b)C.current?.querySelector("input,textarea,select")?.focus()},[b]);let y=i??g,m=`${y}-error`,[v,f]=lo(t),[k,S]=lo(!1);so(()=>f(t),[t]);let R=nr(e,v,u),D=Boolean(e.required&&v===""&&R)&&!k&&!d?"":R,T=r??o??e.name,V=e.type==="date"&&ut(v),h=V&&!R?oo(v):v,x=[c,D?m:void 0].filter(Boolean).join(" "),I={id:y,"aria-label":T,"aria-invalid":Boolean(D),...x?{"aria-describedby":x}:{},disabled:n,onBlur:()=>S(!0),onKeyDown:(P)=>{if(l||s)P.stopPropagation();let M=e.type==="longText"||e.type==="json";if(P.key==="Tab"&&l)P.preventDefault(),l(P.shiftKey?"previous":"next");else if(P.key==="Enter"&&!P.shiftKey&&l&&(!M||P.ctrlKey||P.metaKey))P.preventDefault(),l();else if(P.key==="Escape"&&s)P.preventDefault(),s()},style:{width:"100%",...b?{height:"100%",border:0,borderRadius:0,outline:"none",boxShadow:"none",padding:"0 7px",boxSizing:"border-box",font:"inherit"}:{},background:"var(--background, white)",color:"inherit"},className:"min-w-0 rounded-md border border-[var(--uibot-border,#d4d4d8)] bg-[var(--uibot-surface,#fff)] px-2 py-1 text-sm text-[var(--uibot-text,#18181b)] disabled:cursor-not-allowed disabled:opacity-60"},A=(P)=>{S(!0),f(P),a(P)},O=(P)=>{if(e.type==="date"&&V&&P){let M=new Date(P);A(Number.isFinite(M.getTime())?M.toISOString():P)}else A(P)},F;if(e.type==="hyperlink")F=pt(Dn,{field:e,text:v,id:y,ariaLabel:T,invalid:Boolean(D),describedBy:x||void 0,disabled:n,locale:u,inputStyle:I.style,inputClassName:I.className,onChange:A,onSave:l,onCancel:s});else if(e.type==="checkbox")F=co("select",{...I,value:v,onChange:(P)=>A(P.currentTarget.value),children:[!e.required&&pt("option",{value:"",children:p("No value")}),pt("option",{value:"true",children:p("Yes")}),pt("option",{value:"false",children:p("No")})]});else if(e.type==="longText"||e.type==="json")F=pt("textarea",{...I,value:v,rows:e.type==="json"?4:3,onChange:(P)=>A(P.currentTarget.value)});else{let P=e.type==="date"&&!(R&&v)?V?"datetime-local":"date":"text",M=e.type==="blob";F=pt("input",{...I,type:P,inputMode:e.type==="number"?"decimal":void 0,step:V?"0.001":void 0,value:h,readOnly:M,onInput:e.type==="date"?(W)=>O(W.currentTarget.value):void 0,onChange:(W)=>O(W.currentTarget.value)})}return co("div",{ref:C,className:"grid min-w-0 gap-1",style:b?{height:"100%"}:void 0,children:[o&&pt("label",{className:"text-xs font-medium",htmlFor:y,children:o}),F,D&&pt("span",{id:m,role:"alert",className:"text-xs text-red-600",children:D})]})}import{useEffect as Gi,useRef as Ji}from"react";import{jsx as uo}from"react/jsx-runtime";var Yi={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 Ee({name:e,size:t=15,style:n}){return uo("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:uo("path",{d:Yi[e]})})}import{jsx as gt,jsxs as po,Fragment as Zi}from"react/jsx-runtime";var zt={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function Y({ui:e,style:t,variant:n,size:i,children:o,disabled:r,onClick:a,title:l,ariaLabel:s,icon:u,iconOnly:d,badge:c}){let p=e?.Button,g=u?po("span",{style:{position:"relative",display:"inline-flex"},children:[gt(Ee,{name:u}),c?gt("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,C=d?g:po(Zi,{children:[g,o]}),b=s,y=l??(d?b:void 0),m=d?"icon":i;if(p)return gt(p,{...n?{variant:n}:{},...m?{size:m}:{},disabled:r,onClick:a,title:y,"aria-label":b,children:C});return gt("button",{type:"button",style:{...u?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?zt:{},...d?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:r,onClick:a,title:y,"aria-label":b,children:C})}function Pe({ui:e,value:t,options:n,onChange:i,disabled:o,label:r,style:a,"aria-describedby":l,"aria-invalid":s}){let u=e?.Select,d={...l?{"aria-describedby":l}:{},...s?{"aria-invalid":!0}:{}};if(u)return gt(u,{value:t,options:n,onChange:i,disabled:o,"aria-label":r,...d});return gt("select",{"aria-label":r,...d,style:a,disabled:o,value:t,onChange:(c)=>i(c.target.value),children:n.map((c)=>gt("option",{value:c.value,disabled:c.disabled,children:c.label},c.value))})}function go({label:e,busy:t,onCancel:n,children:i,alert:o=!1}){let r=Ji(null);return Gi(()=>{let a=r.current,l=document.activeElement;if(a?.showModal)a.showModal();else a?.setAttribute("open","");return()=>{if(a?.close?.(),l instanceof HTMLElement&&l.isConnected)l.focus({preventScroll:!0})}},[]),gt("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 l=a.currentTarget,s=[...l.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter((c)=>!c.hidden),u=s[0],d=s.at(-1);if(!u||(a.shiftKey?document.activeElement===u:document.activeElement===d)||!l.contains(document.activeElement)){if(a.preventDefault(),(a.shiftKey?d:u)?.focus(),!u)l.focus()}},tabIndex:-1,onCancel:(a)=>{if(a.preventDefault(),!t)n()},children:i})}import{useEffect as mo,useRef as ln,useState as et}from"react";import{jsx as G,jsxs as ae,Fragment as ta}from"react/jsx-runtime";function Qi(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 Xi=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function ea({descriptor:e,fieldIds:t,query:n,client:i,readOnly:o=!1,reloadKey:r=0,onImported:a,onRefreshSchema:l}){let[s,u]=et(null),[d,c]=et(null),[p,g]=et(null),[C,b]=et([]),[y,m]=et(""),[v,f]=et(!1),[k,S]=et(!1),[R,E]=et(!0),[D,T]=et(null),[V,h]=et(!1),x=ln(!1),I=ln(!1),A=ln(!1),O=ln(null),F=ln({client:i,onImported:a,descriptor:e});F.current={client:i,onImported:a,descriptor:e},mo(()=>(x.current=!0,()=>{x.current=!1,I.current=!1}),[]),mo(()=>{let N=!0;if(!o)i.imports(e.id).then((_)=>{if(!N||!x.current||!_.ok)return;if(b((ee)=>_.data.map((le)=>{let Se=ee.find((z)=>z.id===le.id);return Se&&Se.version>le.version?Se:le})),!A.current)g((ee)=>{let le=_.data.find((Se)=>Se.id===ee?.id);return ee&&le&&le.version>ee.version?le:ee})});return()=>{N=!1}},[i,e.id,o,r]);let P=(N)=>{g(N),b((_)=>[N,..._.filter((ee)=>ee.id!==N.id)].slice(0,50)),T(null)};async function M(N){if(A.current||o)return;A.current=!0,I.current=!0,f(!0),S(!0),m("");let _=N;try{while(x.current&&I.current&&_.status==="ready"){let ee=await F.current.client.advanceImport(e.id,_.id,_.version);if(!x.current)break;if(!ee.ok){m(ee.error.message);break}let le=ee.data;if(P(le),le.importedRows>_.importedRows)F.current.onImported();if(le.version===_.version&&le.status==="ready"){m("Import paused. Refresh the saved progress before retrying.");break}_=le}}finally{if(A.current=!1,I.current=!1,x.current)f(!1),S(!1)}}async function W(){if(!s||A.current)return;A.current=!0,f(!0),m("");let N=await i.previewImport(e.id,{...s,expectedSchemaVersion:e.schemaVersion});if(A.current=!1,!x.current)return;if(f(!1),N.ok)c(N.data),u({...s,expectedSchemaVersion:N.data.schemaVersion,mapping:N.data.mapping});else m(N.error.message)}async function te(){if(!s||!d||d.missingRequiredFieldIds.length||!d.totalRows||A.current||o)return;A.current=!0,f(!0),m(""),O.current??=crypto.randomUUID();let N=await i.createImport(e.id,{...s,idempotencyKey:O.current});if(A.current=!1,!x.current)return;if(f(!1),N.ok)P(N.data),u(null),c(null),O.current=null,M(N.data);else m(N.error.message)}async function q(){if(!p||A.current||o)return;if(p.status==="ready"){M(p);return}A.current=!0,f(!0),m("");let N=l?await l():F.current.descriptor;if(!N){A.current=!1,f(!1),m("Refresh the collection schema and try again.");return}let _=await i.resumeImport(e.id,p.id,p.version,N.schemaVersion);if(A.current=!1,!x.current)return;if(f(!1),_.ok)P(_.data),M(_.data);else m(_.error.message)}async function J(N){if(!p)return;let _=await i.importErrors(e.id,p.id,{limit:100,...N===void 0?{}:{cursor:N},expectedVersion:p.version});if(!x.current)return;if(_.ok)T(_.data);else m(_.error.message)}async function oe(N=!1){if(v||A.current)return;A.current=!0,f(!0),m("");let _=N&&p?await i.exportImportErrors(e.id,p.id):await i.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:R});if(A.current=!1,!x.current)return;if(f(!1),_.ok)Qi(_.data),m(`${_.data.rowCount} rows downloaded${_.data.protectedCells?`; ${_.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else m(_.error.message)}return ae("details",{className:"min-w-0 rounded-lg border p-4",children:[G("summary",{className:"cursor-pointer text-sm font-medium",children:"CSV import and export"}),ae("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[ae("div",{className:"flex flex-wrap items-center gap-3",children:[G("button",{type:"button",disabled:v||!t.length,onClick:()=>void oe(),children:"Export CSV"}),ae("label",{className:"flex items-center gap-2 text-sm",children:[G("input",{type:"checkbox",checked:R,onChange:(N)=>E(N.target.checked)}),"Spreadsheet view"]})]}),G("p",{className:"text-xs text-muted-foreground",children:"Export all matching records and visible columns from the active query. Spreadsheet view prefixes potentially active text with a tab and changes those values; application support varies. Turn it off for exact text. Limit: 100,000 rows or 20 MiB."}),!o&&ae(ta,{children:[ae("label",{className:"flex min-w-0 flex-col gap-2 text-sm",children:["CSV file",G("input",{"aria-label":"CSV file",className:"max-w-full",type:"file",accept:".csv,text/csv",disabled:v,onChange:async(N)=>{let _=N.target.files?.[0];if(!_)return;if(m(""),c(null),u(null),O.current=null,_.size>20971520){m("Choose a UTF-8 CSV file no larger than 20 MiB.");return}f(!0),A.current=!0;try{let ee=new TextDecoder("utf-8",{fatal:!0}).decode(await _.arrayBuffer());if(x.current)u({fileName:_.name,csv:ee,expectedSchemaVersion:e.schemaVersion})}catch{if(x.current)m("The file must be valid UTF-8 text.")}finally{if(A.current=!1,x.current)f(!1)}}})]}),s&&ae("div",{className:"flex flex-wrap gap-3",children:[G("span",{className:"break-all text-sm",children:s.fileName}),G("button",{type:"button",disabled:v,onClick:()=>void W(),children:"Preview CSV"})]}),G("p",{className:"text-xs text-muted-foreground",children:"Insert into this collection. Existing records and options stay unchanged. Dates: ISO or YYYY-MM-DD; selections: IDs or names; multi-select: JSON array or semicolon list; linked records: JSON IDs. Blank non-text cells become null. Computed columns are skipped. Invalid rows are skipped with downloadable errors."}),d&&s&&ae("div",{className:"flex min-w-0 flex-col gap-3",children:[ae("p",{className:"text-sm",children:[d.totalRows," rows · ",d.validRows," valid · ",d.invalidRows," ","invalid · ",d.ignoredColumns.length," skipped columns"]}),d.headers.map((N,_)=>ae("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[ae("span",{className:"max-w-64 break-all",children:["Column ",_+1,": ",N||"(empty)"]}),ae("select",{"aria-label":`Column ${_+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:s.mapping?.[_]??"",disabled:v,onChange:(ee)=>{let le=[...s.mapping??d.mapping];le[_]=ee.target.value||null,u({...s,mapping:le}),c(null),O.current=null},children:[G("option",{value:"",children:"Skip column"}),e.fields.filter((ee)=>!Ne(ee)).map((ee)=>ae("option",{value:ee.id,children:[ee.name," (",ee.id,")",ee.required?" · required":""]},ee.id))]})]},`${_}:${N}`)),d.missingRequiredFieldIds.length>0&&ae("p",{role:"alert",children:["Map required fields: ",d.missingRequiredFieldIds.join(", ")]}),G("div",{className:"max-w-full overflow-x-auto",children:ae("table",{className:"w-full text-xs",children:[ae("caption",{children:["First ",d.sample.length," normalized rows; row numbers include the header."]}),G("thead",{children:ae("tr",{children:[G("th",{children:"Row"}),G("th",{children:"Normalized values"}),G("th",{children:"Error"})]})}),G("tbody",{children:d.sample.map((N)=>ae("tr",{children:[G("td",{children:N.rowNumber}),G("td",{className:"max-w-96 break-all",children:Xi(N.values)}),G("td",{children:N.error?.code??""})]},N.rowNumber))})]})}),G("button",{type:"button",className:"self-start",disabled:v||!d.totalRows||d.missingRequiredFieldIds.length>0,onClick:()=>void te(),children:"Confirm import"})]}),ae("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",ae("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:p?.id??"",disabled:v,onChange:async(N)=>{if(!N.target.value){g(null);return}let _=await i.importJob(e.id,N.target.value);if(x.current)if(_.ok)P(_.data),h(!1);else m(_.error.message)},children:[G("option",{value:"",children:"Choose saved progress…"}),C.map((N)=>ae("option",{value:N.id,children:[N.fileName," · ",N.processedRows,"/",N.totalRows," · ",N.status]},N.id))]})]}),G("button",{type:"button",className:"self-start",disabled:v,onClick:async()=>{let N=await i.imports(e.id);if(x.current)if(N.ok)b(N.data);else m(N.error.message)},children:"Refresh saved imports"}),p&&ae("div",{className:"flex flex-col gap-3",children:[ae("p",{role:"status",children:[k?"Importing":p.status==="ready"?"Paused":p.status==="schemaChanged"?"Schema changed — confirm before continuing":p.status==="completed"?"Completed":"Cancelled"," ","· ",p.processedRows," of ",p.totalRows," processed · ",p.importedRows," imported ·"," ",p.failedRows," failed"]}),G("progress",{"aria-label":"Import progress",max:p.totalRows,value:p.processedRows,className:"max-w-full"}),G("p",{className:"text-xs text-muted-foreground",children:"Closing this page pauses new batches. An in-flight batch may finish. Resume saved progress after signing in with the same credential. Imported records remain if you cancel."}),ae("div",{className:"flex flex-wrap gap-3",children:[k&&G("button",{type:"button",onClick:()=>{I.current=!1,S(!1)},children:"Pause import"}),!k&&(p.status==="ready"||p.status==="schemaChanged")&&G("button",{type:"button",disabled:v,onClick:()=>void q(),children:p.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(p.status==="ready"||p.status==="schemaChanged")&&G("button",{type:"button",disabled:v,onClick:()=>h(!0),children:"Cancel import"}),G("button",{type:"button",disabled:v||!p.failedRows,onClick:()=>void J(),children:"Show import errors"}),G("button",{type:"button",disabled:v||!p.failedRows,onClick:()=>void oe(!0),children:"Download all import errors"})]}),V&&ae("div",{children:[ae("p",{children:["Stop remaining rows? The ",p.importedRows," imported records will remain."]}),G("button",{type:"button",disabled:v,onClick:async()=>{A.current=!0,f(!0);let N=await i.cancelImport(e.id,p.id);if(A.current=!1,!x.current)return;if(f(!1),N.ok)P(N.data),h(!1);else m(N.error.message)},children:"Confirm cancellation"}),G("button",{type:"button",onClick:()=>h(!1),children:"Keep import"})]}),D&&ae("div",{className:"max-w-full overflow-x-auto",children:[ae("table",{className:"w-full text-xs",children:[ae("caption",{children:[D.total," failed rows"]}),G("thead",{children:ae("tr",{children:[G("th",{children:"Row"}),G("th",{children:"Field"}),G("th",{children:"Error"})]})}),G("tbody",{children:D.items.map((N)=>ae("tr",{children:[G("td",{children:N.rowNumber}),G("td",{children:N.fieldId??""}),G("td",{children:N.code})]},N.rowNumber))})]}),D.nextCursor!==null&&G("button",{type:"button",onClick:()=>void J(D.nextCursor??void 0),children:"Next errors"})]})]})]}),y&&G("p",{role:"alert",className:"break-words text-sm",children:y})]})]})}import{useEffect as fo,useRef as Rt,useState as It}from"react";import{jsx as ge,jsxs as Le,Fragment as ra}from"react/jsx-runtime";var En=[{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 na({descriptor:e,client:t,onConverted:n}){let i=e.fields.filter((P)=>En.some((M)=>M.type===P.type)),[o,r]=It(i[0]?.id??""),a=i.find((P)=>P.id===o)??i[0],[l,s]=It(a?.type??"singleLineText"),[u,d]=It(a?.required??!1),[c,p]=It(a?.options?.map((P)=>`${P.id}=${P.name}`).join(`
|
|
5
|
-
`)??""),[
|
|
6
|
-
`)??"");C(null),f.current=null,
|
|
7
|
-
`)??""),I()};if(!
|
|
8
|
-
`).filter((M)=>M.trim()).map((M)=>{let W=M.indexOf("=");if(W<1)throw Error("Each option must use stable_id=Display name.");return{id:M.slice(0,W).trim(),name:M.slice(W+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:P}},F=()=>x.current&&h.current===T;return Le("details",{className:"rounded-lg border p-4",children:[ge("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),Le("div",{className:"mt-4 flex flex-col gap-3",children:[ge("p",{className:"text-sm",children:"Preview every existing record before changing the field. Invalid values or a changed preview block confirmation. All record versions advance together."}),Le("label",{children:["Field"," ",Le("select",{"aria-label":"Conversion field",value:
|
|
9
|
-
done=Done`})]}),b&&ge("p",{role:"alert",className:"text-sm text-destructive",children:b}),ge("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:D,onClick:async()=>{let P;try{P=O()}catch(M){y(M instanceof Error?M.message:"Invalid conversion options.");return}v(!0),y(""),C(null),f.current=null;try{let M=await t.previewConversion(e.id,P);if(!F())return;if(M.ok)C(M.data);else y(M.error.message)}catch{if(F())y("Preview unavailable. Your draft is kept.")}finally{if(F())v(!1)}},children:m?"Working…":"Preview conversion"}),g&&Le(ra,{children:[Le("p",{role:"status",children:[g.validRows," valid · ",g.invalidRows," invalid"]}),Le("p",{className:"text-xs",children:["Preview covers ",g.totalRows," records. Samples and errors show at most 20 records."]}),ge("div",{className:"overflow-x-auto",children:Le("table",{className:"w-full text-sm",children:[ge("thead",{children:Le("tr",{children:[ge("th",{children:"Record"}),ge("th",{children:"Before"}),ge("th",{children:"After"}),ge("th",{children:"Error"})]})}),ge("tbody",{children:g.sample.map((P)=>Le("tr",{children:[ge("td",{className:"max-w-32 break-all",children:P.id}),ge("td",{className:"max-w-48 break-words",children:JSON.stringify(P.before)}),ge("td",{className:"max-w-48 break-words",children:JSON.stringify(P.after)}),ge("td",{children:P.error})]},P.id))})]})}),g.errors.length>0&&ge("ul",{children:g.errors.map((P)=>Le("li",{children:[ge("span",{className:"break-all",children:P.id}),": ",ge("span",{children:P.code})]},P.id))}),ge("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:m||g.invalidRows>0,onClick:async()=>{if(!f.current)k.current=e.id,S.current++;f.current??={expectedSchemaVersion:g.schemaVersion,field:g.field,previewToken:g.previewToken,idempotencyKey:crypto.randomUUID()};let P=f.current,M=S.current,W=()=>x.current&&R.current.id===e.id&&M===S.current;v(!0),y("");try{let te=await t.convertField(e.id,P);if(!W())return;if(te.ok){if(C(null),f.current=null,k.current=null,te.data.descriptor.schemaVersion>=R.current.schemaVersion)n(te.data.descriptor)}else if(y(te.error.message),te.error.status===409)C(null),f.current=null,k.current=null}catch{if(W())y("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(W())v(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as oa,useRef as rr,useState as yo}from"react";import{jsx as bo,jsxs as aa}from"react/jsx-runtime";function ia({collectionIds:e,client:t,onChanges:n,pollIntervalMs:i=2000}){let o=JSON.stringify([...new Set(e)].sort()),r=rr(o);r.current=o;let a=rr(n);a.current=n;let l=rr(()=>{}),[s,u]=yo("connecting"),[d,c]=yo(!1);return oa(()=>{let p=JSON.parse(o),g=new Map,C=!1,b=!1,y=0,m,v=()=>!C&&r.current===o,f=Math.max(50,Math.min(60000,i)),k=async()=>{if(!v()||b)return;b=!0,c(!0);let E=!1;try{let D=y>0;for(let T of p){let V=g.get(T),h=await t.changes(T,{...V!==void 0?{cursor:V}:{},limit:100});if(!v())return;if(!h.ok)throw u(h.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let x=V===void 0;if(x||D||h.data.items.length>0)await a.current(T,h.data,x);if(!v())return;g.set(T,h.data.cursor),E||=h.data.hasMore}y=0,u("live")}catch{if(y++,v())u((D)=>D==="expired"?"expired":"offline")}finally{if(b=!1,v())c(!1),m=setTimeout(()=>{k()},E&&y===0?0:Math.min(30000,f*2**Math.min(y,8)))}},S=()=>{if(m!==void 0)clearTimeout(m);k()};l.current=S,u("connecting"),k();let R=()=>{if(document.visibilityState==="visible")S()};return window.addEventListener("online",S),document.addEventListener("visibilitychange",R),()=>{if(C=!0,m!==void 0)clearTimeout(m);window.removeEventListener("online",S),document.removeEventListener("visibilitychange",R)}},[o,t,i]),aa("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[bo("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")&&bo("button",{type:"button",className:"rounded border px-2 py-1",disabled:d,onClick:()=>l.current(),children:"Reconnect now"})]})}import{useEffect as Tn,useRef as mt,useState as _e}from"react";import{jsx as X,jsxs as de,Fragment as ar}from"react/jsx-runtime";var ir={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function dn(e){try{return await e()}catch{return{ok:!1,error:ir}}}function or({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return de("div",{className:"min-w-0",children:[X("strong",{children:t}),X("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-words rounded border p-2 text-xs",children:n.slice(0,16000)}),n.length>16000&&de(ar,{children:[X("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),X("button",{type:"button",onClick:()=>{let i=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),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 sa({descriptor:e,recordId:t,client:n,readOnly:i=!1,onCommitted:o,registerRefresh:r}){let[a,l]=_e(null),[s,u]=_e(null),[d,c]=_e(null),[p,g]=_e(),[C,b]=_e(),[y,m]=_e([]),[v,f]=_e([]),[k,S]=_e(""),[R,E]=_e(null),[D,T]=_e(null),[V,h]=_e(null),[x,I]=_e(!1),[A,O]=_e(""),F=mt(null),P=mt(null),M=mt(n);M.current=n;let W=mt(!1),te=mt(0),q=`${e.id}:${t}`,J=mt(q);J.current=q;let oe=mt({historyBefore:p,commentBefore:C});oe.current={historyBefore:p,commentBefore:C};let N=mt(async()=>{}),_=(w=q)=>W.current&&J.current===w&&M.current===n,ee=async()=>{let w=q,U=++te.current,K=oe.current,[Fe,Ct]=await Promise.all([dn(()=>n.history(e.id,t,{...K.historyBefore===void 0?{}:{before:K.historyBefore},limit:20})),dn(()=>n.comments(e.id,t,{...K.commentBefore===void 0?{}:{before:K.commentBefore},limit:50}))]);if(!_(w)||U!==te.current)throw Error("Refresh superseded");if(!Fe.ok||!Ct.ok)throw O(!Fe.ok?Fe.error.message:!Ct.ok?Ct.error.message:ir.message),Error("Activity refresh failed");u(Fe.data),c(Ct.data),l(w)};N.current=ee,Tn(()=>(W.current=!0,()=>{W.current=!1,te.current++}),[]),Tn(()=>(r?.(()=>N.current()),()=>r?.(null)),[r]),Tn(()=>{if(J.current!==q)return;u(null),c(null),l(null),g(void 0),b(void 0),m([]),f([]),oe.current={historyBefore:void 0,commentBefore:void 0},S(""),E(null),T(null),h(null),F.current=null,P.current=null,I(!1),O("")},[q]),Tn(()=>{if(J.current!==q||M.current!==n||oe.current.historyBefore!==p||oe.current.commentBefore!==C)return;N.current().catch(()=>{})},[q,n,p,C]);let le=(w)=>{let U=F.current;if(U?.signature===w)return U.key;let K={signature:w,key:crypto.randomUUID()};return F.current=K,K.key},Se=async(w)=>{if(x||i||!d||a!==q)return;let U=w==="delete"?D:R;if(w!=="create"&&(!U||U.authorId!==d.actorId))return;let K=w==="create"?k:R?.draft??"";if(w!=="delete"&&(!K.trim()||K.length>4000||K.includes("\x00"))){O("Comments require 1–4,000 characters.");return}let Fe=le(JSON.stringify([w,U?.id,U?.version,K]));I(!0),O("");let Ct=await dn(async()=>{if(w==="create")return n.createComment(e.id,t,{text:K,idempotencyKey:Fe});if(!U)return{ok:!1,error:ir};if(w==="edit")return n.editComment(e.id,t,U.id,{text:K,expectedVersion:U.version,idempotencyKey:Fe});return n.deleteComment(e.id,t,U.id,{expectedVersion:U.version,idempotencyKey:Fe})});if(!_())return;if(I(!1),!Ct.ok){O(Ct.error.message);return}if(F.current=null,w==="create")S("");else if(w==="edit")E(null);else T(null);if(w==="create"&&C!==void 0)b(void 0),f([]);else await N.current().catch(()=>{})},z=async(w)=>{if(x||i||!s||a!==q)return;I(!0),O(""),P.current=null;let U={targetVersion:w,expectedCurrentVersion:s.currentVersion,expectedSchemaVersion:e.schemaVersion},K=await dn(()=>n.previewUndo(e.id,t,U));if(!_())return;if(I(!1),K.ok)h(K.data);else h(null),O(K.error.message)},ye=async()=>{if(x||i||a!==q||!V&&!P.current)return;let w=P.current;if(!w){if(!V)return;w={targetVersion:V.targetVersion,expectedCurrentVersion:V.currentVersion,expectedSchemaVersion:V.schemaVersion,idempotencyKey:crypto.randomUUID()},P.current=w}let U=w;I(!0),O("");let K=await dn(()=>n.undo(e.id,t,U));if(!_())return;if(I(!1),!K.ok){if(K.error.code==="version_conflict"||K.error.code==="reference_conflict"||K.error.code==="validation")P.current=null,h(null);O(K.error.message),await N.current().catch(()=>{});return}P.current=null,h(null),o(K.data),g(void 0),m([]),await N.current().catch(()=>{})},Q=d?.items.find((w)=>w.id===R?.id),Ae=R&&Q&&Q.version!==R.version,L=V&&(V.currentVersion!==s?.currentVersion||V.schemaVersion!==e.schemaVersion);return de("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[de("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[de("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),X("button",{type:"button",disabled:x,onClick:()=>{O(""),N.current().catch(()=>{})},children:"Refresh activity"})]}),A&&X("p",{role:"alert",className:"text-sm text-destructive",children:A}),!s||!d||a!==q?X("p",{role:"status",children:"Loading record activity…"}):de(ar,{children:[de("p",{role:"status",children:["Current version ",s.currentVersion,s.currentDeleted?" · Deleted record":""]}),X("h3",{className:"font-medium",children:"Comments"}),d.items.length===0&&X("p",{className:"text-sm",children:"No comments yet."}),X("ol",{className:"flex flex-col gap-3",children:d.items.map((w)=>de("li",{className:"min-w-0 rounded border p-3",children:[de("p",{className:"break-all text-xs",children:[w.authorId," · ",w.updatedAt," · version ",w.version]}),X("p",{className:"whitespace-pre-wrap break-words text-sm",children:w.text??"Comment deleted"}),!i&&w.text!==null&&w.authorId===d.actorId&&de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:x,onClick:()=>{E({...w,draft:w.text??""}),T(null),F.current=null},children:"Edit comment"}),X("button",{type:"button",disabled:x,onClick:()=>{T(w),E(null),F.current=null},children:"Delete comment"})]})]},w.id))}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:x||!v.length,onClick:()=>{b(v.at(-1)),f((w)=>w.slice(0,-1))},children:"Newer comments"}),X("button",{type:"button",disabled:x||d.nextCursor===null,onClick:()=>{f((w)=>[...w,C]),b(d.nextCursor??void 0)},children:"Older comments"})]}),!i&&de(ar,{children:[R&&de("div",{className:"flex flex-col gap-2",children:[de("label",{children:["Edit comment text",X("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:x,maxLength:4000,value:R.draft,onChange:(w)=>{E({...R,draft:w.target.value}),F.current=null}})]}),Ae&&de("div",{role:"status",children:[X("p",{children:"This comment changed. Your draft and original version are kept."}),de("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",Q.text??"Comment deleted"]}),Q.text!==null&&Q.authorId===d.actorId&&X("button",{type:"button",disabled:x,onClick:()=>{E({...Q,draft:R.draft}),F.current=null},children:"Use current comment version"})]}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:x||R.authorId!==d.actorId,onClick:()=>void Se("edit"),children:"Save comment"}),X("button",{type:"button",disabled:x,onClick:()=>{E(null),F.current=null},children:"Cancel comment edit"})]})]}),D&&de("div",{children:[X("p",{children:"Delete this comment? A deletion marker will remain."}),X("p",{className:"whitespace-pre-wrap break-words",children:D.text}),X("button",{type:"button",disabled:x||D.authorId!==d.actorId,onClick:()=>void Se("delete"),children:"Confirm delete comment"}),X("button",{type:"button",disabled:x,onClick:()=>T(null),children:"Cancel delete comment"})]}),de("label",{children:["New comment",X("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:x,maxLength:4000,value:k,onChange:(w)=>{S(w.target.value),F.current=null}})]}),X("button",{type:"button",className:"self-start",disabled:x||!k.trim(),onClick:()=>void Se("create"),children:"Add comment"})]}),X("h3",{className:"font-medium",children:"Record history"}),X("p",{className:"text-xs",children:"Stored writable values at each version. Live computed values are excluded. A legacy baseline has an unknown author; earlier versions cannot be recovered."}),X("ol",{className:"flex flex-col gap-3",children:s.items.map((w)=>de("li",{className:"min-w-0 rounded border p-3",children:[de("p",{className:"break-all text-xs",children:["Version ",w.version," · ",w.operation," · schema ",w.schemaVersion," · ",w.actorId," ·"," ",w.createdAt]}),de("details",{children:[de("summary",{children:["Stored values at version ",w.version]}),X(or,{record:w.snapshot,label:`Version ${w.version}`})]}),!i&&w.version<s.currentVersion&&de("button",{type:"button",disabled:x,onClick:()=>void z(w.version),children:["Preview restore version ",w.version]})]},w.id))}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:x||!y.length,onClick:()=>{g(y.at(-1)),m((w)=>w.slice(0,-1))},children:"Newer history"}),X("button",{type:"button",disabled:x||s.nextCursor===null,onClick:()=>{m((w)=>[...w,p]),g(s.nextCursor??void 0)},children:"Older history"})]}),!i&&V&&de("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[de("h3",{children:["Restore version ",V.targetVersion," as a new version"]}),de("p",{children:["Current version ",V.currentVersion," · schema ",V.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),de("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[X(or,{record:V.before,label:"Current stored values"}),X(or,{record:V.target,label:"Values to restore"})]}),L&&!P.current&&X("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:x||!!L&&!P.current,onClick:()=>void ye(),children:P.current?"Retry undo":"Confirm restore"}),X("button",{type:"button",disabled:x,onClick:()=>{h(null),P.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as Fn,useRef as ft,useState as at}from"react";import{jsx as Ie,jsxs as Be,Fragment as ho}from"react/jsx-runtime";async function Nn(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 la(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let i of t)n+=String.fromCharCode(i);return btoa(n)}function da({collectionId:e,recordId:t,client:n,readOnly:i=!1,registerRefresh:o}){let r=`${e}:${t}`,a=ft({identity:r,client:n});a.current={identity:r,client:n};let l=ft(!1),s=ft(0),u=ft(0),[d,c]=at(null),[p,g]=at(null),[C,b]=at(),[y,m]=at([]),v=ft(C);v.current=C;let[f,k]=at(null),[S,R]=at(null),E=ft(null),D=ft(null),[T,V]=at(!1),[h,x]=at(!1),[I,A]=at(""),O=()=>l.current&&a.current.identity===r&&a.current.client===n,F=async()=>{let q=++s.current,J=await Nn(()=>n.list(e,t,{limit:20,...v.current===void 0?{}:{before:v.current}}));if(!O()||q!==s.current)throw Error("Refresh superseded");if(!J.ok)throw A(J.error.message),Error("Attachment refresh failed");g(J.data),c(r)},P=ft(F);P.current=F,Fn(()=>(l.current=!0,()=>{l.current=!1,++s.current,++u.current}),[]),Fn(()=>{if(a.current.identity!==r||a.current.client!==n)return;c(null),g(null),k(null),R(null),E.current=null,V(!1),x(!1),A(""),b(void 0),m([]),v.current=void 0,++u.current,P.current().catch(()=>{})},[r,n]),Fn(()=>{if(v.current===C&&d===r)P.current().catch(()=>{})},[C,r,d]),Fn(()=>(o?.(()=>P.current()),()=>o?.(null)),[o]);let M=async()=>{if(T||i||!f||d!==r)return;let q=f;V(!0),A("");let J=await Nn(()=>n.upload(e,t,q));if(!O())return;if(V(!1),!J.ok){A(J.error.message);return}if(k(null),D.current)D.current.value="";b(void 0),m([]),v.current=void 0,await P.current().catch(()=>{})},W=async()=>{if(T||i||!S||S.authorId!==p?.actorId||d!==r)return;E.current??=crypto.randomUUID();let q=S,J=E.current;V(!0),A("");let oe=await Nn(()=>n.delete(e,t,q.id,{expectedVersion:q.version,idempotencyKey:J}));if(!O())return;if(V(!1),!oe.ok){A(oe.error.message),await P.current().catch(()=>{});return}R(null),E.current=null,await P.current().catch(()=>{})},te=async(q)=>{if(T||d!==r)return;V(!0),A("");let J=await Nn(()=>n.content(e,t,q.id));if(!O())return;if(V(!1),!J.ok){A(J.error.message);return}let oe=Uint8Array.from(atob(J.data.base64),(ee)=>ee.charCodeAt(0)),N=URL.createObjectURL(new Blob([oe],{type:"application/octet-stream"})),_=document.createElement("a");_.href=N,_.download=J.data.attachment.name,_.click(),setTimeout(()=>URL.revokeObjectURL(N),1000)};return Be("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Be("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ie("h3",{className:"font-medium",children:"Attachments"}),Ie("button",{type:"button",disabled:T,onClick:()=>{A(""),P.current().catch(()=>{})},children:"Refresh attachments"})]}),I&&Ie("p",{role:"alert",children:I}),!p||d!==r?Ie("p",{role:"status",children:"Loading attachments…"}):Be(ho,{children:[p.items.length===0&&Ie("p",{children:"No attachments yet."}),Ie("ol",{className:"flex min-w-0 flex-col gap-2",children:p.items.map((q)=>Be("li",{className:"min-w-0 rounded border p-2",children:[Ie("p",{className:"break-all",children:q.name}),Be("p",{className:"break-all text-xs",children:[q.size," bytes · version ",q.version," · ",q.authorId]}),q.deletedAt?Ie("p",{children:"Attachment deleted"}):Be("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:T,"aria-label":`Download attachment ${q.name}`,onClick:()=>void te(q),children:"Download"}),!i&&q.authorId===p.actorId&&Ie("button",{type:"button",disabled:T,"aria-label":`Delete attachment ${q.name}`,onClick:()=>{R(q),E.current=null},children:"Delete"})]})]},q.id))}),Be("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:T||!y.length,onClick:()=>{b(y.at(-1)),m((q)=>q.slice(0,-1))},children:"Newer attachments"}),Ie("button",{type:"button",disabled:T||p.nextCursor===null,onClick:()=>{m((q)=>[...q,C]),b(p.nextCursor??void 0)},children:"Older attachments"})]}),!i&&Be(ho,{children:[Ie("p",{className:"text-xs",children:"Up to 1 MiB per file, 20 active files and 5 MiB per record. Files have independent versions; restoring record values does not restore deleted files."}),Be("label",{children:["Attachment file",Ie("input",{ref:D,"aria-label":"Attachment file",type:"file",disabled:T||h,onChange:async(q)=>{let J=q.target.files?.[0];if(!J)return;let oe=++u.current;if(k(null),A(""),!J.size||J.size>1048576){A("Choose a nonempty file up to 1 MiB.");return}x(!0);try{let N=await la(J);if(!O()||oe!==u.current)return;let _=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(J.type)?J.type:"application/octet-stream";k({name:J.name,contentType:_,base64:N,idempotencyKey:crypto.randomUUID()})}catch{if(O()&&oe===u.current)A("The selected file could not be read.")}finally{if(O()&&oe===u.current)x(!1)}}},r)]}),f&&Be("p",{className:"break-all",children:["Selected file: ",f.name]}),Ie("button",{type:"button",className:"self-start",disabled:T||h||!f,onClick:()=>void M(),children:"Upload attachment"}),S&&Be("div",{children:[Be("p",{className:"break-all",children:["Delete ",S.name,"? This permanently removes its bytes and keeps a deletion marker."]}),Be("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:T,onClick:()=>void W(),children:"Confirm delete attachment"}),Ie("button",{type:"button",disabled:T,onClick:()=>{R(null),E.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as Mn,useRef as jt,useState as Ue}from"react";import{jsx as ue,jsxs as he,Fragment as Co}from"react/jsx-runtime";async function sr(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function ca(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function ua({descriptor:e,recordIds:t,client:n,linkForGrant:i,registerRefresh:o}){let r=e.id,a=jt({identity:r,client:n});a.current={identity:r,client:n};let l=jt(!1),s=jt(0),[u,d]=Ue(null),[c,p]=Ue(null),[g,C]=Ue(),b=jt(g);b.current=g;let[y,m]=Ue([]),[v,f]=Ue([]),[k,S]=Ue([]),[R,E]=Ue(3600),[D,T]=Ue(null),[V,h]=Ue(!1),[x,I]=Ue(""),[A,O]=Ue(null),F=jt(null),[P,M]=Ue(!1),[W,te]=Ue(""),q=()=>l.current&&a.current.identity===r&&a.current.client===n,J=async()=>{let z=++s.current,ye=await sr(()=>n.list(r,{limit:20,...b.current===void 0?{}:{before:b.current}}));if(!q()||z!==s.current)throw Error("Refresh superseded");if(!ye.ok)throw te(ye.error.message),Error("Share refresh failed");p(ye.data),d(r)},oe=jt(J);oe.current=J,Mn(()=>(l.current=!0,()=>{l.current=!1,++s.current}),[]),Mn(()=>{if(a.current.identity!==r||a.current.client!==n)return;d(null),p(null),f([]),S([]),T(null),h(!1),I(""),O(null),F.current=null,M(!1),te(""),C(void 0),m([]),b.current=void 0,oe.current().catch(()=>{})},[r,n]),Mn(()=>{if(b.current===g&&u===r)oe.current().catch(()=>{})},[g,u,r]),Mn(()=>(o?.(()=>oe.current()),()=>o?.(null)),[o]);let N=()=>{if(!V)T(null)},_=async()=>{if(P||!D||u!==r)return;let z=D;M(!0),h(!0),te("");let ye=await sr(()=>n.create(r,z));if(!q())return;if(M(!1),!ye.ok){te(ye.error.message);return}I(i(ye.data,z.key)),T(null),h(!1),C(void 0),m([]),b.current=void 0,await oe.current().catch(()=>{})},ee=async()=>{if(P||!A||u!==r)return;let z=A;F.current??=crypto.randomUUID();let ye=F.current;M(!0),te("");let Q=await sr(()=>n.revoke(r,z.id,{expectedVersion:z.version,idempotencyKey:ye}));if(!q())return;if(M(!1),!Q.ok){te(Q.error.message),await oe.current().catch(()=>{});return}O(null),F.current=null,I(""),await oe.current().catch(()=>{})},le=e.fields.filter((z)=>!["linkedRecord","lookup","formula","rollup"].includes(z.type)),Se=P||V;return he("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[he("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[ue("h3",{className:"font-medium",children:"Read-only sharing"}),ue("button",{type:"button",disabled:P,onClick:()=>{te(""),oe.current().catch(()=>{})},children:"Refresh share grants"})]}),ue("p",{className:"text-sm",children:"Select the exact basic fields and stable record IDs. Links expose current selected values until expiry or revocation. Schema changes close access."}),ue("p",{className:"text-xs",children:"Relations, computed fields, attachments, discussions, history and writes are excluded. Up to 100 records, 20 active grants and 24 hours per grant. Keys are shown only when created."}),W&&ue("p",{role:"alert",children:W}),he("fieldset",{disabled:Se,className:"flex min-w-0 flex-col gap-2",children:[ue("legend",{children:"Fields to share"}),le.map((z)=>he("label",{className:"break-all",children:[ue("input",{type:"checkbox","aria-label":`Share field ${z.name}`,checked:v.includes(z.id),onChange:(ye)=>{N(),f((Q)=>ye.target.checked?[...Q,z.id]:Q.filter((Ae)=>Ae!==z.id))}})," ",z.name]},z.id))]}),he("fieldset",{disabled:Se,className:"flex min-w-0 flex-col gap-2",children:[ue("legend",{children:"Records on the current page"}),t.slice(0,100).map((z)=>he("label",{className:"break-all",children:[ue("input",{type:"checkbox","aria-label":`Share record ${z}`,checked:k.includes(z),onChange:(ye)=>{N(),S((Q)=>ye.target.checked?[...Q,z]:Q.filter((Ae)=>Ae!==z))}})," ",z]},z)),t.length===0&&ue("p",{children:"Load records in Grid to choose a share scope."})]}),he("p",{className:"break-all text-xs",children:["Selected record IDs: ",k.join(", ")||"none"]}),he("label",{children:["Link lifetime"," ",he("select",{"aria-label":"Share link lifetime",disabled:Se,value:R,onChange:(z)=>{N(),E(Number(z.target.value))},children:[ue("option",{value:60,children:"1 minute"}),ue("option",{value:3600,children:"1 hour"}),ue("option",{value:86400,children:"24 hours"})]})]}),ue("button",{type:"button",className:"self-start",disabled:Se||u!==r||!v.length||!k.length||k.length>100||v.some((z)=>!le.some((ye)=>ye.id===z)),onClick:()=>{te("");try{T({expectedSchemaVersion:e.schemaVersion,fieldIds:[...v],recordIds:[...k],expiresInSeconds:R,key:ca(),idempotencyKey:crypto.randomUUID()})}catch{te("A secure share key could not be generated.")}},children:"Review read-only share"}),D&&he("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[he("p",{className:"break-all",children:["Confirm schema ",D.expectedSchemaVersion,", fields ",D.fieldIds.join(", "),", records ",D.recordIds.join(", ")," for ",D.expiresInSeconds," seconds."]}),D.expectedSchemaVersion!==e.schemaVersion&&ue("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),he("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:P,onClick:()=>void _(),children:V?"Retry create read link":"Create read link"}),ue("button",{type:"button",disabled:P,onClick:()=>{T(null),h(!1),te("")},children:"Discard share confirmation"})]}),V&&ue("p",{className:"text-xs",children:"If the response was lost, retry returns the same grant. A discarded committed grant remains in the directory and can be revoked."})]}),x&&he("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",ue("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:x,onFocus:(z)=>z.target.select()})]}),!c||u!==r?ue("p",{role:"status",children:"Loading share grants…"}):he(Co,{children:[c.items.length===0&&ue("p",{children:"No share grants yet."}),ue("ol",{className:"flex min-w-0 flex-col gap-2",children:c.items.map((z)=>he("li",{className:"min-w-0 rounded border p-2",children:[he("p",{className:"break-all",children:["Grant ",z.id," · version ",z.version," · schema ",z.schemaVersion]}),he("p",{className:"break-all text-xs",children:["Fields: ",z.fieldIds.join(", ")," · Records: ",z.recordIds.join(", ")," · Expires:"," ",z.expiresAt]}),z.revokedAt?ue("p",{children:"Share revoked"}):he(Co,{children:[ue("p",{children:z.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(z.expiresAt)<=Date.now()?"Share expired":"Share active"}),ue("button",{type:"button",disabled:P,"aria-label":`Revoke share ${z.id}`,onClick:()=>{O(z),F.current=null},children:"Revoke"})]})]},z.id))}),he("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:P||!y.length,onClick:()=>{C(y.at(-1)),m((z)=>z.slice(0,-1))},children:"Newer share grants"}),ue("button",{type:"button",disabled:P||c.nextCursor===null,onClick:()=>{m((z)=>[...z,g]),C(c.nextCursor??void 0)},children:"Older share grants"})]})]}),A&&he("div",{children:[he("p",{className:"break-all",children:["Revoke grant ",A.id," at version ",A.version,"? Every existing share session will lose access."]}),he("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:P,onClick:()=>void ee(),children:"Confirm revoke share"}),ue("button",{type:"button",disabled:P,onClick:()=>{O(null),F.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as vo,useRef as Ht,useState as Te}from"react";import{jsx as ne,jsxs as ve}from"react/jsx-runtime";var xo=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],pa=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function ga({descriptor:e,recordIds:t,client:n,webhookRequest:i}){let o=e.id,r=Ht({id:o,client:n});r.current={id:o,client:n};let a=Ht(!0),l=Ht(0),[s,u]=Te([]),[d,c]=Te(""),p=Ht(d);p.current=d;let[g,C]=Te(null),[b,y]=Te(),m=Ht(b);m.current=b;let[v,f]=Te(""),[k,S]=Te("record"),[R,E]=Te(60),[D,T]=Te([]),[V,h]=Te([]),[x,I]=Te({}),[A,O]=Te(null),[F,P]=Te(!1),[M,W]=Te(!1),[te,q]=Te(""),[J,oe]=Te(""),N=()=>a.current&&r.current.id===o&&r.current.client===n,_=async(L)=>{try{return await L()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},ee=async()=>{let L=++l.current,w=await _(()=>n.list(o));if(!N()||L!==l.current)return;if(!w.ok){q(w.error.message);return}u(w.data);let U=w.data.find((Fe)=>Fe.id===p.current)?.id??w.data[0]?.id??"";if(p.current=U,c(U),!U){C(null);return}let K=await _(()=>n.runs(o,U,{limit:20,...m.current?{before:m.current}:{}}));if(!N()||L!==l.current||p.current!==U)return;if(K.ok)C(K.data);else q(K.error.message)},le=Ht(ee);le.current=ee,vo(()=>{if(r.current.id!==o||r.current.client!==n)return;a.current=!0,le.current();let L=setInterval(()=>void le.current(),5000);return()=>{a.current=!1,++l.current,clearInterval(L)}},[o,n]),vo(()=>{if(p.current!==d||m.current!==b)return;le.current()},[d,b]);let Se=()=>{if(q(""),!v.trim()||!D.length||k!=="record"&&!V.length){q("Choose a name, writable fields, and target records for time or webhook triggers.");return}let L=Object.fromEntries(D.map((U)=>[U,x[U]??null])),w={expectedSchemaVersion:e.schemaVersion,name:v.trim(),trigger:k==="time"?{kind:k,intervalSeconds:R}:{kind:k},targetRecordIds:V,values:L,idempotencyKey:crypto.randomUUID(),...k==="webhook"?{webhookKey:pa()}:{}};O({kind:"create",input:w}),P(!1)},z=(L)=>{O(L),P(!1),q("")},ye=async()=>{if(!A||M)return;let L=A,w=F;P(!0),W(!0),q("");let U=await _(()=>L.kind==="create"?n.create(o,L.input):L.kind==="toggle"?n.toggle(o,L.a.id,L.input):L.kind==="run"?n.runNow(o,L.a.id,L.input):n.retry(o,L.a.id,L.run.id,L.input));if(!N())return;if(W(!1),!U.ok){if(!w&&U.error.status>=400&&U.error.status<500)P(!1);q(`${U.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(L.kind==="create"){let K=U.data;if(p.current=K.id,c(K.id),L.input.webhookKey&&i)oe(JSON.stringify(i(K,L.input.webhookKey),null,2));f(""),T([]),h([]),I({})}O(null),P(!1),m.current=void 0,y(void 0),await le.current()},Q=s.find((L)=>L.id===d),Ae=!!A||M;return ve("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[ne("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."}),ne("button",{type:"button",onClick:()=>void le.current(),children:"Refresh automation"}),te&&ne("p",{role:"alert",children:te}),ne("form",{onSubmit:(L)=>{L.preventDefault(),Se()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:ve("fieldset",{disabled:Ae,style:{minWidth:0},children:[ne("legend",{children:"New automation"}),ve("label",{children:["Name"," ",ne("input",{"aria-label":"Automation name",value:v,maxLength:200,onChange:(L)=>f(L.target.value)})]}),ve("label",{children:["Trigger"," ",ve("select",{"aria-label":"Automation trigger",value:k,onChange:(L)=>S(L.target.value),children:[ne("option",{value:"record",children:"Record changes"}),ne("option",{value:"time",children:"Timed interval"}),ne("option",{value:"webhook",children:"Private webhook"})]})]}),k==="time"&&ve("label",{children:["Interval in seconds"," ",ne("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:R,onChange:(L)=>E(Number(L.target.value))})]}),ve("fieldset",{children:[ne("legend",{children:"Fields to update"}),e.fields.filter((L)=>xo.includes(L.type)).map((L)=>ve("label",{style:{display:"block"},children:[ne("input",{type:"checkbox",checked:D.includes(L.id),onChange:(w)=>{T(w.target.checked?[...D,L.id]:D.filter((U)=>U!==L.id))}}),L.name]},L.id))]}),ne(At,{fields:e.fields.filter((L)=>D.includes(L.id)&&xo.includes(L.type)),values:x,onChange:I}),ve("fieldset",{children:[ne("legend",{children:"Target records from this page"}),k==="record"&&ne("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&ne("p",{children:"Open a grid page to choose fixed records."}),t.map((L)=>ve("label",{style:{display:"block",overflowWrap:"anywhere"},children:[ne("input",{type:"checkbox","aria-label":`Automation target ${L}`,checked:V.includes(L),onChange:(w)=>h(w.target.checked?[...V,L]:V.filter((U)=>U!==L))}),L]},L))]}),ne("button",{type:"submit",children:"Review automation"})]})}),A&&ve("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[ne("p",{children:A.kind==="create"?`Create ${A.input.name} using schema ${A.input.expectedSchemaVersion}; ${A.input.targetRecordIds.length||"event"} targets.`:A.kind==="toggle"?`${A.input.enabled?"Enable":"Disable"} ${A.a.name}. Disabling fences queued and running work.`:A.kind==="run"?`Run ${A.a.name} for ${A.input.recordIds.length} explicitly selected records.`:`Retry ${A.a.name}, run ${A.run.sequence}, using its original record versions.`}),A.kind==="create"&&ne("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(A.input.values,null,2)}),ne("button",{type:"button",disabled:M,onClick:()=>void ye(),children:M?"Confirming…":F?"Retry automation confirmation":"Confirm automation"}),ne("button",{type:"button",disabled:F||M,onClick:()=>O(null),children:"Cancel automation review"}),F&&ne("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),J&&ve("div",{children:[ne("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),ne("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:J}),ne("button",{type:"button",onClick:()=>oe(""),children:"Hide webhook key"})]}),s.length>0&&ve("label",{children:["Automation"," ",ne("select",{"aria-label":"Selected automation",disabled:Ae,value:d,onChange:(L)=>{p.current=L.target.value,m.current=void 0,y(void 0),c(L.target.value),C(null)},children:s.map((L)=>ne("option",{value:L.id,children:L.name},L.id))})]}),Q&&ve("div",{children:[ve("p",{children:[Q.enabled?"Enabled":"Disabled"," · ",Q.trigger.kind," · schema ",Q.schemaVersion," · configuration ",Q.version]}),ne("button",{type:"button",disabled:Ae,onClick:()=>z({kind:"toggle",a:Q,input:{expectedVersion:Q.version,enabled:!Q.enabled,idempotencyKey:crypto.randomUUID()}}),children:Q.enabled?"Review disable automation":"Review enable automation"}),ne("button",{type:"button",disabled:Ae||!Q.enabled||!(Q.targetRecordIds.length||t.length),onClick:()=>z({kind:"run",a:Q,input:{recordIds:Q.targetRecordIds.length?Q.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),g&&ve("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!g.items.length&&ne("p",{children:"No runs yet."}),g.items.map((L)=>ve("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[ve("p",{children:["Run ",L.sequence," · ",L.triggerKind," · ",L.status," · step ",L.step]}),ve("p",{children:["Attempts: evaluate ",L.stepAttempts.evaluate,", apply ",L.stepAttempts.apply," · original versions: ",L.expectedRows.map((w)=>`${w.id}: ${w.version}`).join(", ")]}),L.errorCode&&ne("p",{role:"status",children:L.errorCode}),L.leaseUntil&&ve("p",{children:["Lease expires ",L.leaseUntil]}),Q&&L.status==="failed"&&ve("button",{type:"button",disabled:Ae||!Q.enabled,onClick:()=>z({kind:"retry",a:Q,run:L,input:{expectedVersion:L.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",L.sequence]})]},L.id)),ne("button",{type:"button",disabled:Ae||b===void 0,onClick:()=>{m.current=void 0,y(void 0)},children:"Newest runs"}),ne("button",{type:"button",disabled:Ae||g.nextCursor===null,onClick:()=>{m.current=g.nextCursor??void 0,y(m.current)},children:"Older runs"})]})]})}import{useEffect as ma,useId as fa,useRef as ko,useState as De}from"react";import{jsx as ce,jsxs as xe}from"react/jsx-runtime";var Po=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function ya(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&&Po.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 ba({descriptor:e,records:t,client:n,onApplied:i}){let o=fa(),r=e.id,a=ko({id:r,client:n}),l=ko(!0);a.current={id:r,client:n};let[s,u]=De([]),[d,c]=De(!1),[p,g]=De(""),[C,b]=De(""),[y,m]=De(""),[v,f]=De([]),[k,S]=De([]),[R,E]=De([]),[D,T]=De(null),[V,h]=De(null),[x,I]=De(null),[A,O]=De(!1),[F,P]=De(!1),[M,W]=De(""),[te,q]=De(""),[J,oe]=De(""),N=()=>l.current&&a.current.id===r&&a.current.client===n,_=async(w)=>{try{return await w()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};ma(()=>{l.current=!0,T(null),h(null),I(null),O(!1),W(""),q(""),oe(""),f([]),S([]),E([]),m("");let w=!0;return c(!1),P(!1),u([]),g(""),b(""),n.providers(r).then((U)=>{if(!w||a.current.id!==r||a.current.client!==n)return;if(c(!0),U.ok)u(U.data),g(U.data[0]?.resourceId??""),b(U.data[0]?.allowedModels[0]??"");else W(U.error.message)}).catch(()=>{if(w)c(!0),W("AI configuration is unavailable.")}),()=>{w=!1,l.current=!1}},[r,n]);let ee=()=>{try{let w=ya(e,t,{resourceId:p,model:C,instruction:y,recordIds:v,sourceFieldIds:k,targetFieldIds:R});h(structuredClone(w.records.map((U)=>({id:U.id,version:U.expectedVersion,values:Object.fromEntries(w.sourceFieldIds.map((K)=>[K,t.find((Fe)=>Fe.id===U.id)?.values[K]??null]))})))),T(w),O(!1),W(""),q("")}catch(w){W(w instanceof Error?w.message:"Invalid selection.")}},le=async()=>{if(!D||F)return;let w=D,U=A;P(!0),O(!0),W("");let K=await _(()=>n.propose(r,w));if(!N())return;if(P(!1),!K.ok){if(!U&&K.error.status>=400&&K.error.status<500)O(!1);W(`${K.error.message} Retry keeps the original selection and versions.`);return}I(K.data),oe(K.data.id),O(!1)},Se=async()=>{if(!x||F)return;let w=x,U=A;P(!0),O(!0),W("");let K=await _(()=>n.confirm(r,w));if(!N())return;if(P(!1),!K.ok){if(!U&&K.error.status>=400&&K.error.status<500)O(!1);W(`${K.error.message} The reviewed proposal keeps its original versions.`);return}q(`${K.data.items.length} records filled${K.data.replayed?"; original receipt recovered":""}.`),I(null),T(null),h(null),O(!1);try{await i?.()}catch{if(N())W("The fill committed. Refresh the Collection to see its records.")}},z=async()=>{if(F||D||x)return;P(!0),W("");let w=await _(()=>n.get(r,J));if(!N())return;if(P(!1),w.ok)I(w.data),O(!1),q("");else W(w.error.message)},ye=(w,U,K)=>K(w.includes(U)?w.filter((Fe)=>Fe!==U):[...w,U]),Q=F||!!D||!!x,Ae=e.fields.filter((w)=>Po.includes(w.type)),L=s.find((w)=>w.resourceId===p);return xe("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[ce("p",{children:"Choose the records and fields to send to your configured AI service. Review suggested values before writing. Conflicts keep the original record versions."}),M&&ce("p",{role:"alert",children:M}),te&&ce("p",{role:"status",children:te}),d&&s.length===0&&ce("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),ce("form",{onSubmit:(w)=>{w.preventDefault(),ee()},children:xe("fieldset",{disabled:Q,style:{minWidth:0},children:[ce("legend",{children:"AI fill request"}),xe("label",{children:["AI resource"," ",xe("select",{"aria-label":"AI resource",value:p,onChange:(w)=>{g(w.target.value),b(s.find((U)=>U.resourceId===w.target.value)?.allowedModels[0]??"")},children:[ce("option",{value:"",children:"Choose resource"}),s.map((w)=>ce("option",{value:w.resourceId,children:w.name},w.resourceId))]})]}),xe("label",{htmlFor:o,children:["Model"," ",L?.allowedModels.length?ce("select",{id:o,"aria-label":"AI model",value:C,onChange:(w)=>b(w.target.value),children:L.allowedModels.map((w)=>ce("option",{value:w,children:w},w))}):ce("input",{id:o,"aria-label":"AI model",maxLength:200,value:C,onChange:(w)=>b(w.target.value)})]}),xe("label",{children:["Instructions"," ",ce("textarea",{"aria-label":"AI instructions",maxLength:2000,value:y,onChange:(w)=>m(w.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),xe("fieldset",{children:[ce("legend",{children:"Source fields to send"}),Ae.map((w)=>xe("label",{style:{display:"block"},children:[ce("input",{type:"checkbox","aria-label":`Send ${w.name}`,checked:k.includes(w.id),onChange:()=>ye(k,w.id,S)}),w.name]},w.id))]}),xe("fieldset",{children:[ce("legend",{children:"Fields to fill"}),Ae.map((w)=>xe("label",{style:{display:"block"},children:[ce("input",{type:"checkbox","aria-label":`Fill ${w.name}`,checked:R.includes(w.id),onChange:()=>ye(R,w.id,E)}),w.name]},w.id))]}),xe("fieldset",{children:[ce("legend",{children:"Target records from this page"}),t.map((w)=>xe("label",{style:{display:"block",overflowWrap:"anywhere"},children:[ce("input",{type:"checkbox","aria-label":`AI record ${w.id}`,checked:v.includes(w.id),onChange:()=>ye(v,w.id,f)}),w.id," · version ",w.version]},w.id))]}),ce("button",{type:"submit",disabled:!p,children:"Review AI request"})]})}),D&&!x&&xe("section",{"aria-label":"AI data disclosure",children:[xe("p",{children:["Selected service: ",D.resourceId," · model ",D.model," · schema"," ",D.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),ce("p",{children:D.instruction}),ce("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(V,null,2)}),ce("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),ce("button",{type:"button",disabled:F,onClick:()=>void le(),children:A?"Retry original AI request":"Generate proposal"}),ce("button",{type:"button",disabled:F||A,onClick:()=>{T(null),h(null),W("")},children:"Cancel AI request"})]}),x&&xe("section",{"aria-label":"AI fill confirmation",children:[xe("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",x.id," · ",x.provider," · schema ",x.schemaVersion]}),x.schemaVersion!==e.schemaVersion&&ce("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),x.rows.map((w)=>xe("div",{style:{overflowWrap:"anywhere"},children:[xe("p",{children:[w.id," · original version ",w.expectedVersion]}),Object.keys(w.values).map((U)=>xe("div",{children:[ce("strong",{children:e.fields.find((K)=>K.id===U)?.name??U}),xe("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(w.before[U]),`
|
|
10
|
-
`,"Suggested: ",JSON.stringify(w.values[U])]})]},U))]},w.id)),ce("button",{type:"button",disabled:F,onClick:()=>void Se(),children:A?"Retry original AI fill":"Confirm fill"}),ce("button",{type:"button",disabled:F||A,onClick:()=>{I(null),T(null),h(null),W("")},children:"Dismiss proposal"})]}),xe("label",{children:["Recover a saved proposal"," ",ce("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:J,onChange:(w)=>oe(w.target.value),disabled:Q,style:{width:"100%",boxSizing:"border-box"}})]}),ce("button",{type:"button",disabled:Q||!/^[a-f0-9]{64}$/.test(J),onClick:()=>void z(),children:"Load saved proposal"})]})}import{jsx as j,jsxs as re}from"react/jsx-runtime";var Ca=[{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 Bu({fields:e,onChange:t,lockedIds:n=[],collections:i=[]}){let o=(r,a)=>t(e.map((l,s)=>s===r?{...l,...a}:l));return re("div",{className:"flex flex-col gap-3",children:[e.map((r,a)=>{let l=n.includes(r.id);return re("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)] gap-2 rounded-md border p-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_150px_auto]",children:[j("input",{"aria-label":`Field ${a+1} name`,placeholder:"Display name",value:r.name,onChange:(s)=>o(a,{name:s.target.value})}),j("input",{"aria-label":`Field ${a+1} ID`,placeholder:"field_id",value:r.id,disabled:l,onChange:(s)=>o(a,{id:s.target.value})}),j("select",{"aria-label":`Field ${a+1} type`,className:"rounded-md border bg-background px-2 text-sm",value:r.type,disabled:l,onChange:(s)=>{let u=s.target.value,d={id:r.id,name:r.name,type:u,required:Ne({type:u})?!1:r.required??!1};if(u==="formula")d.formula={expression:""};if(u==="rollup")d.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(u==="singleSelect"||u==="multipleSelect")d.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((c,p)=>p===a?d:c))},children:Ca.map((s)=>j("option",{value:s.value,children:s.name},s.value))}),re("div",{className:"flex items-center gap-2",children:[re("label",{className:"flex items-center gap-1 text-xs",children:[j("input",{type:"checkbox",checked:r.required??!1,disabled:l||n.length>0||Ne(r),onChange:(s)=>o(a,{required:s.target.checked})}),"Required"]}),!l&&j("button",{type:"button",onClick:()=>t(e.filter((s,u)=>u!==a)),children:"Remove"})]}),(r.type==="singleSelect"||r.type==="multipleSelect")&&j("input",{className:"md:col-span-4","aria-label":`Field ${a+1} options`,placeholder:"Open, Done",value:r.options?.map((s)=>s.name).join(", ")??"",disabled:l,onChange:(s)=>o(a,{options:s.target.value.split(",").map((u,d)=>({id:u.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${d}`,name:u.trim()})).filter((u)=>u.name)})}),r.type==="linkedRecord"&&re("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[re("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",re("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} linked collection`,value:r.link?.collectionId??"",disabled:l,onChange:(s)=>{let u=i.find((d)=>d.id===s.target.value);o(a,{link:{collectionId:s.target.value,displayFieldId:u?.fields.find((d)=>d.type==="singleLineText"||d.type==="longText")?.id??""}})},children:[j("option",{value:"",children:"Choose collection…"}),i.map((s)=>j("option",{value:s.id,children:s.name},s.id))]})]}),re("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",re("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} record label`,value:r.link?.displayFieldId??"",disabled:l||!r.link?.collectionId,onChange:(s)=>o(a,{link:{collectionId:r.link?.collectionId??"",displayFieldId:s.target.value}}),children:[j("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)=>j("option",{value:s.id,children:s.name},s.id))]})]})]}),r.type==="lookup"&&re("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[re("label",{children:["Through linked field"," ",re("select",{"aria-label":`Field ${a+1} lookup link`,value:r.lookup?.linkFieldId??"",disabled:l,onChange:(s)=>o(a,{lookup:{linkFieldId:s.target.value,targetFieldId:""}}),children:[j("option",{value:"",children:"Choose linked field…"}),e.filter((s)=>s.type==="linkedRecord"&&s.link).map((s)=>j("option",{value:s.id,children:s.name},s.id))]})]}),re("label",{children:["Read target field"," ",re("select",{"aria-label":`Field ${a+1} lookup target`,value:r.lookup?.targetFieldId??"",disabled:l||!r.lookup?.linkFieldId,onChange:(s)=>o(a,{lookup:{linkFieldId:r.lookup?.linkFieldId??"",targetFieldId:s.target.value}}),children:[j("option",{value:"",children:"Choose target field…"}),i.find((s)=>s.id===e.find((u)=>u.id===r.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((s)=>!Ne(s)&&s.type!=="linkedRecord").map((s)=>j("option",{value:s.id,children:s.name},s.id))]})]}),j("small",{children:"Computed from linked records. Values cannot be edited."})]}),r.type==="formula"&&re("div",{className:"flex flex-col gap-1 md:col-span-4",children:[re("label",{children:["Formula",j("textarea",{"aria-label":`Field ${a+1} formula`,maxLength:2048,className:"min-h-16 w-full rounded-md border bg-background p-2",placeholder:"{quantity} * {price}",value:r.formula?.expression??"",onChange:(s)=>o(a,{formula:{expression:s.target.value}})})]}),j("small",{children:"Use numbers, stable field references, + - * / and parentheses. Text and date functions: CONCAT, UPPER, LOWER, TRIM, DATE_ADD_DAYS, DATE_DIFF_DAYS. Empty inputs produce an empty result."}),re("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"&&re("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[re("label",{children:["Through linked field"," ",re("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:[j("option",{value:"",children:"Choose linked field…"}),e.filter((s)=>s.type==="linkedRecord"&&s.link).map((s)=>j("option",{value:s.id,children:s.name},s.id))]})]}),re("label",{children:["Aggregate"," ",re("select",{"aria-label":`Field ${a+1} rollup function`,value:r.rollup?.function??"sum",onChange:(s)=>{let u=s.target.value,d=i.find((c)=>c.id===e.find((p)=>p.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((c)=>c.id===r.rollup?.targetFieldId);o(a,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:u==="count"||d?.type==="number"?r.rollup?.targetFieldId??"":"",function:u}})},children:[j("option",{value:"sum",children:"Sum"}),j("option",{value:"average",children:"Average"}),j("option",{value:"min",children:"Minimum"}),j("option",{value:"max",children:"Maximum"}),j("option",{value:"count",children:"Count values"})]})]}),re("label",{children:["Target field"," ",re("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:[j("option",{value:"",children:"Choose target field…"}),i.find((s)=>s.id===e.find((u)=>u.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((s)=>!Ne(s)&&s.type!=="linkedRecord"&&(r.rollup?.function==="count"||s.type==="number")).map((s)=>j("option",{value:s.id,children:s.name},s.id))]})]}),j("small",{className:"w-full",children:"Null targets are skipped. Count counts values; empty sum/count are zero. Other empty aggregates have no result."})]})]},a)}),j("button",{type:"button",className:"self-start",onClick:()=>t([...e,{id:`field_${crypto.randomUUID().replaceAll("-","").slice(0,8)}`,name:"New field",type:"singleLineText",required:!1}]),children:"Add field"})]})}function va(e,t,n){if(Ne(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 nr(e,Je(t),n)}function cn(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((l)=>typeof l!=="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(!Lt(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]=ct(Array.isArray(a)?a.join(","):String(a??""),r,i)}return o}function At({fields:e,values:t,onChange:n,relationClient:i,linkedRecords:o,computedErrors:r,locale:a,ui:l,submitted:s=!1}){let u=H(a),d=ha();return j("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((c)=>{let p=c.description?.trim()??"",g=p?`${d}-${c.id}-hint`:void 0,C=va(c,t[c.id],a??"en"),y=Boolean(c.required&&Je(t[c.id])===""&&C)&&!s?"":C,m=y?`${d}-${c.id}-error`:void 0,v=[g,m].filter(Boolean).join(" "),f={...v?{"aria-describedby":v}:{},...y?{"aria-invalid":!0}:{}};return re("div",{className:"flex flex-col gap-1 text-sm",children:[re("label",{htmlFor:`${d}-${c.id}`,children:[c.name,c.required?" *":""]}),p?j("p",{id:g,className:"m-0 text-xs opacity-70",children:p}):null,Ne(c)?j("output",{id:`${d}-${c.id}`,"aria-label":u("{name} (read only)",{name:c.name}),...f,children:c.type==="lookup"?Ut(t[c.id]):wn(t[c.id],r?.[c.id],a)}):c.type==="linkedRecord"?j(Zr,{...a?{locale:a}:{},field:c,value:t[c.id],labels:o?.[c.id],client:i,onChange:(k)=>n({...t,[c.id]:k}),...f}):c.type==="checkbox"?j("input",{id:`${d}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,type:"checkbox",checked:t[c.id]===!0,onChange:(k)=>n({...t,[c.id]:k.target.checked}),...f}):c.type==="singleSelect"&&l?.Select?j(Pe,{ui:l,label:`${c.name}${c.required?" *":""}`,...f,value:String(t[c.id]??""),options:[{value:"",label:u("Choose…")},...(c.options??[]).map((k)=>({value:k.id,label:k.name}))],onChange:(k)=>n({...t,[c.id]:k||null})}):c.type==="multipleSelect"&&l?.MultiSelect?j(l.MultiSelect,{"aria-label":`${c.name}${c.required?" *":""}`,...f,options:(c.options??[]).map((k)=>({value:k.id,label:k.name,slot:Pn(c.options,k.id)})),values:Array.isArray(t[c.id])?t[c.id]:[],placeholder:u("Choose…"),onChange:(k)=>n({...t,[c.id]:k})}):c.type==="singleSelect"||c.type==="multipleSelect"?re("select",{id:`${d}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...f,className:"min-h-9 rounded-md border bg-background p-2",multiple:c.type==="multipleSelect",value:c.type==="multipleSelect"?Array.isArray(t[c.id])?t[c.id]:[]:String(t[c.id]??""),onChange:(k)=>n({...t,[c.id]:c.type==="multipleSelect"?Array.from(k.target.selectedOptions,(S)=>S.value):k.target.value||null}),children:[c.type==="singleSelect"&&j("option",{value:"",children:u("Choose…")}),c.options?.map((k)=>j("option",{value:k.id,children:k.name},k.id))]}):c.type==="date"&&l?.DatePicker?(()=>{let k={kind:Gr(c),timeZone:Me(c)?.timeZone},S=String(t[c.id]??"");return j(l.DatePicker,{id:`${d}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...f,value:io(S,k),withTime:k.kind==="auto"?ut(S):k.kind==="datetime",fixedKind:k.kind!=="auto",clearable:!c.required,onChange:(R)=>n({...t,[c.id]:R?ao(R,S,k):null})})})():c.type==="hyperlink"?j(Dn,{field:c,id:`${d}-${c.id}`,ariaLabel:`${c.name}${c.required?" *":""}`,describedBy:f["aria-describedby"],invalid:Boolean(y),locale:a,inputClassName:"min-h-9 min-w-0 rounded-md border bg-background p-2",text:typeof t[c.id]==="string"?String(t[c.id]):sn(Lt(t[c.id])?t[c.id]:null),onChange:(k)=>{let S=k.trim().startsWith("{")?kt(k):null;n({...t,[c.id]:S??(k||null)})}}):c.type==="longText"?j("textarea",{id:`${d}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...f,className:"rounded-md border bg-background p-2",value:String(t[c.id]??""),onChange:(k)=>n({...t,[c.id]:k.target.value||null})}):j("input",{id:`${d}-${c.id}`,"aria-label":`${c.name}${c.required?" *":""}`,...f,className:"min-h-9 min-w-0 rounded-md border bg-background p-2",type:c.type==="number"?"number":c.type==="date"?"date":"text",step:c.type==="number"?"any":void 0,value:c.type==="date"?String(t[c.id]??"").slice(0,10):String(t[c.id]??""),onChange:(k)=>n({...t,[c.id]:k.target.value===""?null:c.type==="number"?Number(k.target.value):c.type==="date"&&t[c.id]?Rn(t[c.id],k.target.value):k.target.value})}),y?j("span",{id:m,className:"text-xs text-red-600",children:y}):null]},c.id)})})}function xa(e,t,n){if(t==="isEmpty")return;let i=Ne(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(Ne(e)&&!vt(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 Uu({fields:e,view:t,onChange:n,onError:i}){let o=e.filter(vt),[r,a]=lr(o[0]?.id??""),l=o.some((m)=>m.id===r)?r:o[0]?.id??"",[s,u]=lr("contains"),d=l?(()=>{let m=e.find((v)=>v.id===l);return m&&Ne(m)?m.resultType:m?.type})():void 0,c=d==="number"?["is","isNot","isEmpty"]:d==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],p=c.includes(s)?s:d==="number"||d==="date"?"is":"contains",[g,C]=lr(""),y=[...t.columnOrder.flatMap((m)=>{let v=e.find((f)=>f.id===m);return v?[v]:[]}),...e.filter((m)=>!t.columnOrder.includes(m.id))];return re("div",{className:"flex flex-wrap items-end gap-3",children:[re("label",{className:"flex min-w-52 flex-col gap-1 text-sm",children:["Search",j("input",{type:"search",className:"min-h-9 min-w-0 rounded-md border bg-background p-2",value:t.search??"",onChange:(m)=>n({...t,search:m.target.value})})]}),re("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(m)=>{m.preventDefault();let v=e.find((k)=>k.id===l);if(!v)return;let f;try{f=xa(v,p,g)}catch(k){i(k instanceof Error?k.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:l,operator:p,...p==="isEmpty"?{}:{value:f}}]}})},children:[re("label",{className:"flex flex-col gap-1 text-sm",children:["Filter field",j("select",{className:"h-9 rounded-md border bg-background px-2",value:l,onChange:(m)=>a(m.target.value),children:o.map((m)=>j("option",{value:m.id,children:m.name},m.id))})]}),j("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:p,onChange:(m)=>u(m.target.value),children:c.map((m)=>j("option",{value:m,children:m==="isNot"?"is not":m==="isEmpty"?"is empty":m==="onOrAfter"?"on or after":m},m))}),p!=="isEmpty"&&j("input",{type:d==="number"?"number":d==="date"?"date":"text",step:d==="number"?"any":void 0,className:"min-h-9 max-w-40 rounded-md border bg-background p-2","aria-label":"Filter value",value:g,onChange:(m)=>C(m.target.value)}),j("button",{type:"submit",disabled:!l,children:"Apply filter"}),j("button",{type:"button",onClick:()=>{let m={...t};delete m.filter,n(m)},children:"Clear filter"})]}),re("details",{className:"relative",children:[j("summary",{className:"cursor-pointer rounded-md border px-3 py-2 text-sm",children:"Columns"}),j("div",{className:"absolute right-0 top-full z-10 mt-1 flex max-h-96 min-w-64 flex-col gap-2 overflow-auto rounded-md border bg-background p-3 shadow-md",children:y.map((m,v)=>re("div",{className:"flex items-center gap-2 text-sm",children:[re("label",{className:"flex flex-1 items-center gap-2",children:[j("input",{type:"checkbox",checked:!t.hiddenColumns.includes(m.id),disabled:t.type==="form"&&m.required===!0,onChange:(f)=>n({...t,hiddenColumns:f.target.checked?t.hiddenColumns.filter((k)=>k!==m.id):[...t.hiddenColumns,m.id]})}),m.name]}),j("button",{type:"button","aria-label":`Move ${m.name} left`,disabled:v===0,onClick:()=>{let f=y.map((S)=>S.id),k=f[v-1];if(k!==void 0)[f[v-1],f[v]]=[m.id,k];n({...t,columnOrder:f})},children:"←"}),j("button",{type:"button","aria-label":`Move ${m.name} right`,disabled:v===y.length-1,onClick:()=>{let f=y.map((S)=>S.id),k=f[v+1];if(k!==void 0)[f[v],f[v+1]]=[k,m.id];n({...t,columnOrder:f})},children:"→"})]},m.id))})]})]})}import{useEffect as ka,useMemo as wo,useState as So}from"react";import{jsx as dr}from"react/jsx-runtime";function Pa(e){switch(e.code){case"empty":return"Choose a count or sum.";case"too_many":return"Use at most three groups and eight summaries.";case"unknown_field":return"That field is not in this collection.";case"not_groupable":return"Group by a text, number, date, checkbox, or single select field.";case"function":return"That summary function is not supported.";case"numeric_field":return"Average only a number field.";case"extrema_field":return"Minimum and maximum need a number or date field.";case"queryable_field":return"Summarize a queryable field.";case"sum_field":return"Sum only a number field.";case"count_field":return"Count a queryable field, or omit the field to count records.";case"alias":return"Each summary needs its own name, different from the group fields.";case"duplicate_group":return"Each group field can be used once."}}function wa(e,t,n){let i=n.unassigned??"Unassigned";if(t===null||t===void 0)return i;if(e?.type==="singleSelect")return e.options?.find((o)=>o.id===t)?.name??String(t);if(e?.type==="checkbox")return t===!0?n.checked??"Checked":n.unchecked??"Unchecked";return typeof t==="string"||typeof t==="number"||typeof t==="boolean"?String(t):i}function Ro(e,t,n,i={},o={}){return n.map((r)=>{let a=t.groupBy.map((s)=>{let u=e.fields.find((d)=>d.id===s);return`${u?.name??s} ${wa(u,r.groups[s],o)}`}),l=t.aggregates.map((s)=>{let u=r.values[s.as];return`${i[s.as]??s.as}: ${typeof u==="number"||typeof u==="string"?String(u):o.none??"none"}`});return[...a,...l].join(" · ")})}function Sa({descriptor:e,query:t,rows:n}){return dr("ul",{"data-uibot":"collection-aggregate",children:Ro(e,t,n).map((i)=>dr("li",{children:i},i))})}function cr({collectionId:e,descriptor:t,view:n,groupBy:i,aggregates:o,client:r,locale:a,labels:l,reloadKey:s=0}){let u=wo(()=>_r(n,{aggregates:o,...i?{groupBy:i}:{}}),[n,i,o]),d=wo(()=>H(a),[a]),[c,p]=So(d("Loading summary…")),[g,C]=So(!1);return ka(()=>{let b=Br(t,u);if(b){p(d(Pa(b))),C(!0);return}let y=!0;return p(d("Loading summary…")),C(!1),r.aggregate(e,u).then((m)=>{if(!y)return;if(!m.ok){p(m.error.message),C(!0);return}let v=Ro(t,u,m.data,l??{},{unassigned:d("Unassigned"),checked:d("Checked"),unchecked:d("Unchecked"),none:d("none")});p(v.length?v.join(" · "):d("No summary rows.")),C(!1)}).catch(()=>{if(!y)return;p(d("The collection service is unavailable.")),C(!0)}),()=>{y=!1}},[r,e,t,u,l,d,s]),dr("p",{role:g?"alert":"status","data-uibot":"collection-aggregate",children:c})}var Ao=["grid","kanban","gallery","calendar","form"],Ra=["grid","form"],ur={search:!0,filter:!0,columns:!0,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!0,tableList:!0,viewManagement:!0,export:!0},Ia={search:!0,filter:!1,columns:!1,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!1,tableList:!1,viewManagement:!1,export:!1},Aa={search:!0,filter:!0,columns:!0,rowCreate:!1,rowUpdate:!1,rowDelete:!1,schemaEditor:!1,tableList:!0,viewManagement:!1,export:!0},Io={fieldTypeIcons:!1,optionChips:!1,groupBy:!1,groupCollapse:!1,autoHeight:!1,sorting:!0,columnResize:!0,columnReorder:!1,columnFreezing:!1,columnColors:!1,footerStats:!1,recordContextMenu:!1,optimisticEdit:!1,viewTypes:Ao},pr={fieldTypeIcons:!0,optionChips:!0,groupBy:!0,groupCollapse:!0,autoHeight:!0,sorting:!0,columnResize:!0,columnReorder:!0,columnFreezing:!0,columnColors:!0,footerStats:!0,recordContextMenu:!0,optimisticEdit:!0,viewTypes:Ao},Da={basic:{...Io,...ur},full:{...pr,...ur},simple:{...Io,...Ia,viewTypes:Ra},workbench:{...pr,...ur},readonly:{...pr,...Aa,recordContextMenu:!1,optimisticEdit:!1}};function He(e){let{preset:t="basic",...n}=e??{},i={...Da[t],...Ea(n)};return i.groupBy?i:{...i,groupCollapse:!1}}function Ea(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}import{jsx as Z,jsxs as Oe,Fragment as yr}from"react/jsx-runtime";function Kt(e){if(!e.aggregate)return null;return Z(cr,{collectionId:e.descriptor.id,descriptor:e.descriptor,view:e.view,...e.aggregate.groupBy?{groupBy:e.aggregate.groupBy}:{},aggregates:e.aggregate.aggregates,client:e.aggregate.client,...e.locale?{locale:e.locale}:{},...e.reloadKey!==void 0?{reloadKey:e.reloadKey}:{}})}var se={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},Ke={padding:12,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)"},Ln={items:[],total:0,nextCursor:null,limit:50};function Wt(e,t,n=!0){let i=H(e.locale),o=JSON.stringify([e.descriptor.id,e.descriptor.schemaVersion,t]),[r,a]=qe({key:o,history:[]}),l=r.key===o?r.cursor:void 0,s=r.key===o?r.history:[],u=JSON.stringify([o,l]),[d,c]=qe(0),[p,g]=qe({key:u,page:Ln,loading:n,error:""});On(()=>{let b=!0;if(!n){g({key:u,page:Ln,loading:!1,error:""});return}g((v)=>({key:u,page:v.key===u?v.page:Ln,loading:!0,error:""}));let[y,,m]=JSON.parse(o);return e.client.query(y,{...m,...l?{cursor:l}:{}}).then((v)=>{if(!b)return;if(v.ok)g({key:u,page:v.data,loading:!1,error:""});else g((f)=>({...f,loading:!1,error:v.error.message}))}).catch(()=>{if(b)g((v)=>({...v,loading:!1,error:i("Collection query failed. Retry to load records.")}))}),()=>{b=!1}},[u,o,l,e.client,e.reloadKey,n,d]);let C=p.key===u?p.page:Ln;return{page:C,loading:n&&(p.key!==u||p.loading),error:p.key===u?p.error:"",previous:s.length?()=>a({key:o,cursor:s.at(-1),history:s.slice(0,-1)}):void 0,next:C.nextCursor?()=>a({key:o,cursor:C.nextCursor??void 0,history:[...s,l]}):void 0,retry:()=>c((b)=>b+1),pageNumber:s.length+1}}function gr(e,t,n,i){return n>=t?e("{count} records total",{count:t.toLocaleString(i)}):e("{total} records · {loaded} loaded",{total:t.toLocaleString(i),loaded:n})}function Ta({hasPrevious:e,hasNext:t,onPrevious:n,onNext:i,loading:o,page:r,locale:a,ui:l}){let s=H(a);if(!e&&!t)return null;return Oe("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[Z(Y,{ui:l,style:se,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:s("Previous page"),disabled:!e||o,onClick:n}),r?Z("span",{style:{fontSize:12},children:s("Page {page}",{page:r})}):null,Z(Y,{ui:l,style:se,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:s("Next page"),disabled:!t||o,onClick:i})]})}function Yt({state:e,locale:t,ui:n,hideCount:i}){let o=H(t);return Oe("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[i?null:Z("span",{children:gr(o,e.page.total,e.page.items.length,t)}),Z(Ta,{hasPrevious:Boolean(e.previous),hasNext:Boolean(e.next),onPrevious:e.previous,onNext:e.next,loading:e.loading,page:e.pageNumber,locale:t,ui:n}),e.loading&&Z("span",{role:"status",children:o("Loading records…")}),e.error&&Oe(yr,{children:[Z("span",{role:"alert",children:e.error}),Z(Y,{ui:n,style:se,variant:"outline",size:"sm",disabled:e.loading,onClick:e.retry,children:o("Retry query")})]})]})}function mr(e){let t=vn(e.client,e.descriptor.id),n=H(e.locale),[i,o]=qe(!1),[r,a]=qe(""),[l,s]=qe(null),u=un(null);Vt({dirty:Boolean(u.current),busy:i});let d=()=>{u.current=null,a(""),s(null)};return{saving:i,error:r,setError:a,remote:l,pending:u,reset:d,commit:async(g)=>{if(i||e.readOnly)return!1;u.current=g,o(!0),a(""),s(null);let C=await e.client.mutate(e.descriptor.id,g).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:n("Saving failed. Your change has been kept.")}}));if(!t.active)return!1;if(o(!1),C.ok)return d(),e.onCommitted(C.data),!0;a(C.error.message);let b=C.error.details?.current;if(b&&typeof b.id==="string"&&Number.isSafeInteger(b.version)&&b.version>0)s(b);return!1},retryRequest:()=>u.current&&l?{idempotencyKey:crypto.randomUUID(),items:u.current.items.map((g)=>g.op!=="insert"&&g.id===l.id?{...g,expectedVersion:l.version}:g)}:u.current}}function fr({mutation:e,onRetry:t,locale:n,ui:i}){let o=H(n);return Oe(yr,{children:[e.error&&Z("p",{role:"alert",children:e.error}),e.remote&&Oe("div",{style:Ke,children:[Z("strong",{children:o("Current server version {version}",{version:e.remote.version})}),Z("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(e.remote.values,null,2)}),Z(Y,{ui:i,style:se,variant:"outline",size:"sm",disabled:e.saving,onClick:t,children:o("Retry against current version")})]})]})}function Dt({row:e,onClose:t,onCancel:n,onDirtyChange:i,onBusyChange:o,stickyActions:r,...a}){let l=H(a.locale),s=He(a.features),u=!a.readOnly&&s.rowDelete,d=!a.readOnly&&s.rowUpdate,c=un(e.values),[p,g]=qe(()=>({...c.current})),[C,b]=qe(!1);Vt({dirty:JSON.stringify(p)!==JSON.stringify(c.current),busy:!1});let y=un(null),[m,v]=qe(!1);On(()=>{y.current?.focus()},[]);let f=mr(a),k=St(a.descriptor.fields,a.view),S=JSON.stringify(p)!==JSON.stringify(e.values);On(()=>{i?.(S)},[S,i]),On(()=>{o?.(f.saving)},[f.saving,o]);let R=async(D=!1)=>{b(!0);try{let T=D?f.retryRequest():f.pending.current;if(!T){let V=k.filter((x)=>x.type!=="lookup"&&x.type!=="formula"&&x.type!=="rollup"&&JSON.stringify(p[x.id])!==JSON.stringify(e.values[x.id]));if(!V.length){f.setError(l("Change a field before saving."));return}let h=cn(V,p,l,a.locale);T={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:e.id,expectedVersion:e.version,values:h}]}}if(await f.commit(T))t()}catch(T){f.setError(T instanceof Error?T.message:l("Invalid value"))}},E=async()=>{let D=f.pending.current?.items[0]?.op==="delete"?f.pending.current:{idempotencyKey:crypto.randomUUID(),items:[{op:"delete",id:e.id,expectedVersion:e.version}]};if(await f.commit(D))t()};return Oe("div",{ref:y,tabIndex:-1,onKeyDown:(D)=>{if(D.key==="Escape"&&!f.saving)D.stopPropagation(),(n??t)()},role:"dialog","aria-label":l("{name} record",{name:ze(e,a.descriptor.fields)}),style:{...Ke,marginTop:12},children:[Z("h3",{children:ze(e,a.descriptor.fields)}),a.onInspectRecord&&Z(Y,{ui:a.ui,style:se,variant:"outline",size:"sm",disabled:f.saving,onClick:()=>a.onInspectRecord?.(e.id),children:l("Open record activity")}),Oe("form",{onSubmit:(D)=>{D.preventDefault(),R()},children:[Z("fieldset",{disabled:f.saving||m||!d,style:{border:0,padding:0},children:Z(At,{fields:k,values:p,submitted:C,...a.locale?{locale:a.locale}:{},...a.ui?{ui:a.ui}:{},relationClient:a.client,linkedRecords:e.linkedRecords,computedErrors:e.computedErrors,onChange:(D)=>{g(D),f.reset()}})}),Oe("div",{"data-uibot":"record-editor-actions",style:r?{position:"sticky",bottom:0,zIndex:1,display:"flex",gap:8,alignItems:"center",padding:"12px 0",borderTop:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",background:"var(--background, white)"}:void 0,children:[d&&Z("button",{type:"submit",style:{...se,...zt},disabled:f.saving||m,children:f.saving?l("Saving…"):l("Save record")}),r?null:Z("button",{type:"button",style:se,disabled:f.saving,onClick:n??t,children:l("Close record")}),r&&u?Z("span",{style:{marginLeft:"auto"},children:Z(Y,{ui:a.ui,variant:"ghost",size:"sm",icon:"trash",disabled:f.saving,onClick:()=>v(!0),children:l("Delete record")})}):null]})]}),u&&!r&&Z("button",{type:"button",style:se,disabled:f.saving,onClick:()=>v(!0),children:l("Delete record")}),m&&a.ui?.ConfirmDialog?a.ui.ConfirmDialog({open:!0,destructive:!0,title:l("Delete this record?"),description:l("Delete this record? Your unsaved changes will be discarded after deletion."),confirmLabel:l("Delete"),cancelLabel:l("Cancel"),busy:f.saving,onConfirm:()=>void E(),onCancel:()=>{if(v(!1),f.pending.current?.items[0]?.op==="delete")f.reset()}}):null,m&&!a.ui?.ConfirmDialog&&Oe(go,{alert:!0,label:l("Confirm record deletion"),busy:f.saving,onCancel:()=>{if(v(!1),f.pending.current?.items[0]?.op==="delete")f.reset()},children:[Z("p",{children:l("Delete this record? Your unsaved changes will be discarded after deletion.")}),Z("button",{type:"button",style:se,disabled:f.saving,onClick:()=>void E(),children:l("Confirm deletion")}),Z("button",{type:"button",style:se,disabled:f.saving,onClick:()=>{if(v(!1),f.pending.current?.items[0]?.op==="delete")f.reset()},children:l("Cancel deletion")})]}),Z(fr,{mutation:f,onRetry:()=>void R(!0),locale:a.locale,ui:a.ui})]})}function Fa(e){let t=H(e.locale),n=!e.readOnly&&He(e.features).rowCreate,i=un(null),o=St(e.descriptor.fields,{...e.view,hiddenColumns:e.view.hiddenColumns.filter((y)=>!e.descriptor.fields.find((m)=>m.id===y)?.required)}),r=()=>({...Object.fromEntries(o.filter((y)=>y.type==="checkbox").map((y)=>[y.id,!1])),...nn(o)}),a=un(r()),[l,s]=qe(a.current),[u,d]=qe(!1),[c,p]=qe(!1);Vt({dirty:JSON.stringify(l)!==JSON.stringify(a.current),busy:!1});let g=mr(e),C=()=>i.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")?.focus(),b=async()=>{if(!n)return;p(!0);try{let y=g.pending.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:cn(o,l,t,e.locale)}]};if(await g.commit(y))a.current=r(),s(a.current),d(!0),p(!1),requestAnimationFrame(C)}catch(y){g.setError(y instanceof Error?y.message:t("Invalid value"))}};return Oe("section",{"data-uibot":"collection-form",style:Ke,children:[Z("h3",{children:e.view.name}),e.readOnly&&Z("p",{children:t("Record creation requires editor permission.")}),Oe("form",{ref:i,onSubmit:(y)=>{y.preventDefault(),b()},children:[Z("fieldset",{disabled:g.saving||!n,style:{border:0,padding:0},children:Z(At,{fields:o,values:l,submitted:c,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},relationClient:e.client,onChange:(y)=>{s(y),d(!1),g.reset()}})}),n&&Z("button",{type:"submit",style:{...se,...zt},disabled:g.saving,children:g.saving?t("Creating…"):t("Create record")})]}),Z(fr,{mutation:g,onRetry:()=>void b(),locale:e.locale,ui:e.ui}),u?Oe("p",{role:"status",children:[t("Record created. Add another below."),e.onShowRecords?Oe(yr,{children:[" ",Z(Y,{ui:e.ui,style:se,variant:"outline",size:"sm",onClick:e.onShowRecords,children:t("Show records")})]}):null]}):null]})}function Vn(e){let[t,n]=qe(null),i=mr(e),o=!e.readOnly&&He(e.features).rowUpdate;return{intent:t,mutation:i,move:async(l,s)=>{if(!o||i.saving||t)return;n({row:l,values:s});let u={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:l.id,expectedVersion:l.version,values:s}]};if(await i.commit(u))n(null)},retry:async()=>{let l=i.retryRequest();if(l&&await i.commit(l))n(null)},cancel:()=>{n(null),i.reset()},blocked:i.saving||!!t}}function _n({state:e,locale:t,ui:n}){let i=H(t);if(!e.intent)return null;return Oe("div",{role:"dialog","aria-label":i("Pending record move"),style:Ke,children:[Z("p",{children:e.mutation.saving?i("Moving record…"):i("The move has been kept for retry.")}),Z("pre",{children:JSON.stringify(e.intent.values,null,2)}),Z(fr,{mutation:e.mutation,onRetry:()=>void e.retry(),locale:t,ui:n}),!e.mutation.remote&&Z(Y,{ui:n,style:se,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:()=>void e.retry(),children:i("Retry move")}),Z(Y,{ui:n,style:se,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:e.cancel,children:i("Cancel move")})]})}import{useEffect as Va,useMemo as Fo,useRef as _a,useState as Ba}from"react";import{useEffect as br,useMemo as Na,useState as Et}from"react";import{jsx as Gt,jsxs as Do}from"react/jsx-runtime";function Bn(e,t){if(!t?.length)return e;let n=!1,i={...e};for(let o of t){let r=o.label.trim();if(!r||i[o.id]===r)continue;i[o.id]=r,n=!0}return n?i:e}function Eo(e){let t=Na(()=>H(e.locale),[e.locale]),[n,i]=Et(""),[o,r]=Et(),[a,l]=Et(null),[s,u]=Et([]),[d,c]=Et(()=>Bn({},e.labels)),[p,g]=Et(""),[C,b]=Et(!1),y=e.field.relation?.collectionId,m=e.field.relation?.labelFieldId,{getOptions:v,value:f}=e;br(()=>{c((R)=>Bn(R,e.labels))},[e.labels]),br(()=>{let R=!1;if(!y||!v)return;return b(!0),g(""),v({collectionId:y,...m?{labelFieldId:m}:{},search:n,...o?{cursor:o}:{},limit:50}).then((E)=>{if(R)return;if(!E.ok){g(E.error.message),l(null);return}let D=E.data.items.slice(0,50);c((T)=>Bn(T,D)),u((T)=>{let V=o?[...T,...D]:D;return[...new Map(V.map((h)=>[h.id,h])).values()]}),l(E.data.nextCursor)}).catch(()=>{if(!R)g(t("Relation options unavailable."))}).finally(()=>{if(!R)b(!1)}),()=>{R=!0}},[y,m,n,o,v,t]),br(()=>{if(!f||!y||!v)return;if(e.labels?.some((E)=>E.id===f&&E.label.trim()))return;let R=!1;return v({collectionId:y,...m?{labelFieldId:m}:{},ids:[f],limit:50}).then((E)=>{if(R||!E.ok)return;let D=E.data.items.find((T)=>T.id===f);if(D)c((T)=>Bn(T,[D]))}).catch(()=>{}),()=>{R=!0}},[f,y,m,v,e.labels]);let k=!y||!v,S=f?d[f]??s.find((R)=>R.id===f)?.label??f:"";return Do("div",{children:[Gt("input",{"aria-label":t("Search {name}",{name:e.field.name}),value:n,disabled:e.disabled||k,onChange:(R)=>{i(R.currentTarget.value),r(void 0),u([]),l(null)}}),Do("select",{"aria-label":e.label??e.field.name,value:e.value,disabled:e.disabled||k||C,onChange:(R)=>{let E=R.currentTarget.value;if(!E||s.some((D)=>D.id===E))e.onChange(E)},children:[Gt("option",{value:"",children:t("No relation")}),f&&!s.some((R)=>R.id===f)&&Gt("option",{value:f,children:S}),s.map((R)=>Gt("option",{value:R.id,children:R.label},R.id))]}),a&&Gt("button",{type:"button",disabled:C||e.disabled,onClick:()=>r(a),children:t("More {name} options",{name:e.field.name})}),(p||k)&&Gt("span",{role:"status",children:p||t("Relation option provider unavailable.")})]})}var Ma={"zh-CN":{is:"等于",isNot:"不等于",contains:"包含",notContains:"不包含",isEmpty:"为空",isNotEmpty:"不为空",gt:"大于",gte:"大于等于",lt:"小于",lte:"小于等于",before:"早于",after:"晚于",onOrBefore:"不晚于",onOrAfter:"不早于"},en:{is:"is",isNot:"is not",contains:"contains",notContains:"does not contain",isEmpty:"is empty",isNotEmpty:"is not empty",gt:">",gte:"≥",lt:"<",lte:"≤",before:"is before",after:"is after",onOrBefore:"is on or before",onOrAfter:"is on or after"}},La={"zh-CN":{is:"恰好是",isNot:"不是恰好",contains:"包含任一",notContains:"不包含任一"},en:{is:"is exactly",isNot:"is not exactly",contains:"has any of",notContains:"has none of"}},Oa={"zh-CN":{exactDate:"指定日期",dateRange:"日期区间",today:"今天",yesterday:"昨天",tomorrow:"明天",currentWeek:"本周",lastWeek:"上周",nextWeek:"下周",currentMonth:"本月",lastMonth:"上月",nextMonth:"下月",currentYear:"今年",lastYear:"去年",nextYear:"明年",pastDays:"过去 N 天",nextDays:"未来 N 天",daysAgo:"N 天前",daysFromNow:"N 天后"},en:{exactDate:"exact date",dateRange:"date range",today:"today",yesterday:"yesterday",tomorrow:"tomorrow",currentWeek:"this week",lastWeek:"last week",nextWeek:"next week",currentMonth:"this month",lastMonth:"last month",nextMonth:"next month",currentYear:"this year",lastYear:"last year",nextYear:"next year",pastDays:"past N days",nextDays:"next N days",daysAgo:"N days ago",daysFromNow:"N days from now"}},Un=(e,t="en",n)=>{if(n&&Ye(n)==="multipleSelect"){let i=La[t][e];if(i)return i}return Ma[t][e]??e},qn=(e,t="en")=>Oa[t][e]??e;function hr(e,t){if(!t)return"";let n=e?Me(e):void 0;return n?_t(t,{...n,time:"none"}):t}function To(e,t,n="en"){let i=n==="zh-CN";return e.filterSet.map((o)=>{if("filterSet"in o)return`(${To(o,t,n)})`;let r=t.find((u)=>u.id===o.fieldId),a=Un(o.operator,n,r);if(o.operator==="isEmpty"||o.operator==="isNotEmpty")return`${r?.name??o.fieldId} ${a}`;let l=(u)=>r?.options?.find((d)=>d.id===u)?.name??String(u??""),s;if(Qn(o.value)){let u=o.value,d=qn(u.mode,n);s=u.mode==="exactDate"?hr(r,u.date):u.mode==="dateRange"?`${hr(r,u.date)} ~ ${hr(r,u.to)}`:u.days!==void 0?d.replace("N",String(u.days)):d}else s=Array.isArray(o.value)?o.value.map(l).join(i?"、":", "):l(o.value);return`${r?.name??o.fieldId} ${a} ${s}`}).join(e.conjunction==="or"?i?" 或 ":" OR ":i?" 且 ":" AND ")}import{jsx as ie,jsxs as tt,Fragment as Oo}from"react/jsx-runtime";var Ua={text:["is","isNot","contains","isEmpty"],number:["is","isNot","gte","lte","isEmpty"],checkbox:["is"],date:["is","isNot","before","onOrAfter","isEmpty"],singleSelect:["is","isNot","isEmpty"],multipleSelect:["is","contains","isEmpty"]};function Jt(e){return ie("span",{style:pe.cell,children:ie(Pe,{...e})})}var $n=()=>`row_${Math.random().toString(36).slice(2,10)}`,qa=(e)=>("filterSet"in e),$a=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}};function Cr(e,t){if(t)return jr(e);let n=Ye(e);return n?Ua[n]??[]:[]}function vr(e,t,n){if(Ot.has(t))return;let i=Ye(e);if(i==="date"&&n)return{mode:"today",timeZone:Me(e)?.timeZone??$a()};if(i==="checkbox")return!0;if(i==="multipleSelect")return[];return i==="number"?void 0:""}function No(e){let t=[],n=[];for(let i of e?.filterSet??[])if(qa(i))n.push({key:$n(),node:i});else t.push({key:$n(),fieldId:i.fieldId,operator:i.operator,value:i.value});return{rows:t,groups:n,conjunction:e?.conjunction??"and"}}function Mo(e,t,n,i){let o=[],r=!0;for(let s of t){let u=e.find((p)=>p.id===s.fieldId);if(!u||!s.operator){r=!1;continue}let d=s.value===""||Array.isArray(s.value)&&s.value.length===0;if(!Ot.has(s.operator)&&d){r=!1;continue}let c={fieldId:s.fieldId,operator:s.operator,...Ot.has(s.operator)?{}:{value:s.value}};if(Hr(u,c))r=!1;else o.push(c)}let a=n.map((s)=>s.node).filter((s)=>Boolean(s?.filterSet.length)),l=[...o,...a];return{node:l.length?{conjunction:i,filterSet:l}:void 0,complete:r}}function zn(e){let{ui:t,locale:n}=e,i=e.advanced!==!1,o=e.allowGroups!==!1,r=Fo(()=>H(n),[n]),a=Fo(()=>e.fields.filter((b)=>!Ne(b)&&Ye(b)!==null),[e.fields]),[l,s]=Ba(()=>No(e.filter)),u=_a(JSON.stringify(e.filter??null));Va(()=>{let b=JSON.stringify(e.filter??null);if(b!==u.current)u.current=b,s(No(e.filter))},[e.filter]);let d=(b)=>{s(b);let{node:y}=Mo(a,b.rows,b.groups,b.conjunction),m=JSON.stringify(y??null);if(m!==u.current)u.current=m,e.onChange(y)},c=(b,y)=>d({...l,rows:l.rows.map((m)=>m.key===b?{...m,...y}:m)}),p=()=>{let b=a[0];if(!b)return;let y=Cr(b,i)[0]??"";d({...l,rows:[...l.rows,{key:$n(),fieldId:b.id,operator:y,value:y?vr(b,y,i):void 0}]})},g=()=>d({...l,groups:[...l.groups,{key:$n(),node:void 0}]}),C=Mo(a,l.rows,l.groups,l.conjunction).complete===!1||l.groups.some((b)=>b.node===void 0);return tt("div",{"data-uibot-filter-builder":"",style:pe.root,children:[l.rows.length+l.groups.length>1?tt("div",{style:pe.inline,children:[ie("span",{children:r("Match")}),ie(Jt,{ui:t,label:r("Filter conjunction"),style:pe.control,value:l.conjunction,options:[{value:"and",label:r("all conditions")},{value:"or",label:r("any condition")}],onChange:(b)=>d({...l,conjunction:b==="or"?"or":"and"})})]}):null,l.rows.map((b,y)=>{let m=a.find((k)=>k.id===b.fieldId),v=m?Ye(m):null,f=m?Cr(m,i):[];return tt("fieldset",{"aria-label":r("Condition {index}",{index:y+1}),style:{...pe.condition,margin:0,padding:0,border:0,minWidth:0},children:[ie("span",{style:pe.slot,children:ie(Jt,{ui:t,label:r("Filter field"),style:pe.control,value:b.fieldId,options:a.map((k)=>({value:k.id,label:k.name})),onChange:(k)=>{let S=a.find((T)=>T.id===k);if(!S)return;let R=Cr(S,i),E=R.includes(b.operator)?b.operator:R[0]??"",D=Ye(S)===v;c(b.key,{fieldId:k,operator:E,value:E&&!(D&&E===b.operator)?vr(S,E,i):b.value})}})}),ie("span",{style:pe.slot,children:ie(Jt,{ui:t,label:r("Filter operator"),style:pe.control,value:b.operator,options:f.map((k)=>({value:k,label:Un(k,n??"en",m)})),onChange:(k)=>{if(!m)return;let S=k;c(b.key,{operator:S,value:vr(m,S,i)})}})}),m&&b.operator&&!Ot.has(b.operator)?ie("span",{style:pe.slot,children:ie(za,{field:m,row:b,advanced:i,t:r,props:e,onValue:(k)=>c(b.key,{value:k})})}):null,ie(Y,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove condition {index}",{index:y+1}),title:r("Remove condition {index}",{index:y+1}),style:{flex:"0 0 auto"},onClick:()=>d({...l,rows:l.rows.filter((k)=>k.key!==b.key)})})]},b.key)}),o?l.groups.map((b,y)=>tt("fieldset",{"aria-label":r("Condition group {index}",{index:y+1}),style:pe.group,children:[tt("div",{style:pe.groupHead,children:[ie("strong",{style:{fontSize:13},children:r("Condition group {index}",{index:y+1})}),ie(Y,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove group {index}",{index:y+1}),title:r("Remove group {index}",{index:y+1}),onClick:()=>d({...l,groups:l.groups.filter((m)=>m.key!==b.key)})})]}),ie(zn,{fields:e.fields,filter:b.node,allowGroups:!1,advanced:i,...n?{locale:n}:{},...t?{ui:t}:{},...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},onChange:(m)=>d({...l,groups:m?l.groups.map((v)=>v.key===b.key?{...v,node:m}:v):l.groups.filter((v)=>v.key!==b.key)})})]},b.key)):l.groups.length?tt("p",{style:pe.hint,children:[r("{count} grouped conditions are kept.",{count:l.groups.length})," ",ie(Y,{ui:t,variant:"ghost",size:"sm",onClick:()=>d({...l,groups:[]}),children:r("Remove")})]}):null,C?ie("p",{role:"status",style:pe.hint,children:r("Finish the highlighted condition to apply it.")}):null,tt("div",{style:pe.inline,children:[ie(Y,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:a.length===0,onClick:p,children:r("Add condition")}),o?ie(Y,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:a.length===0,onClick:g,children:r("Add group")}):null,l.rows.length||l.groups.length?ie(Y,{ui:t,variant:"ghost",size:"sm",onClick:()=>d({rows:[],groups:[],conjunction:"and"}),children:r("Clear filter")}):null]})]})}function za({field:e,row:t,advanced:n,t:i,props:o,onValue:r}){let{ui:a}=o,l=Ye(e),s=i("Filter value"),u=(d,c,p,g)=>o.renderCellEditor?.({...o.getRelationOptions?{getRelationOptions:o.getRelationOptions}:{},field:{...e,...g,required:!1},text:d,disabled:!1,mode:"filter",label:p,autoOpen:!1,onChange:c,onSave:()=>{},onCancel:()=>c("")});if(l==="number")return ie("input",{"aria-label":s,type:"number",step:"any",style:pe.control,value:typeof t.value==="number"?String(t.value):"",onChange:(d)=>{let c=d.currentTarget.value;r(c===""||!Number.isFinite(Number(c))?void 0:Number(c))}});if(l==="text")return ie("input",{"aria-label":s,style:pe.control,value:typeof t.value==="string"?t.value:"",onChange:(d)=>r(d.currentTarget.value)});if(l==="checkbox")return ie(Jt,{ui:a,label:s,style:pe.control,value:t.value===!1?"false":"true",options:[{value:"true",label:i("Yes")},{value:"false",label:i("No")}],onChange:(d)=>r(d==="true")});if(l==="singleSelect"||l==="multipleSelect"){let d=Array.isArray(t.value)?t.value.join(","):typeof t.value==="string"?t.value:"",c=u(d,(g)=>r(l==="multipleSelect"?g.split(",").filter(Boolean):g),s);if(c)return c;if(l==="singleSelect")return ie(Jt,{ui:a,label:s,style:pe.control,value:d,options:[{value:"",label:i("Choose option")},...(e.options??[]).map((g)=>({value:g.id,label:g.name}))],onChange:r});let p=new Set(d.split(",").filter(Boolean));return ie("fieldset",{"aria-label":s,style:{...pe.inline,margin:0,padding:0,border:0},children:(e.options??[]).map((g)=>tt("label",{style:pe.inline,children:[ie("input",{type:"checkbox",checked:p.has(g.id),onChange:(C)=>{let b=new Set(p);if(C.currentTarget.checked)b.add(g.id);else b.delete(g.id);r([...b])}}),g.name]},g.id))})}if(l==="relation"){let d=typeof t.value==="string"?t.value:"";return u(d,r,s)??ie(Eo,{field:e,value:d,onChange:r,label:s,getOptions:o.getRelationOptions,locale:o.locale})}if(l==="date"){if(!n||typeof t.value==="string"){let d=typeof t.value==="string"?t.value:"";return u(d,r,s)??ie("input",{"aria-label":s,type:"date",style:pe.control,value:d.slice(0,10),onChange:(c)=>r(c.currentTarget.value)})}return ie(ja,{field:e,value:t.value,t:i,props:o,custom:u,onValue:r})}return null}function ja({field:e,value:t,t:n,props:i,custom:o,onValue:r}){let a=t??{mode:"today"},l=(d)=>r({...a,...d}),s=(d,c,p)=>o(c??"",(g)=>p(g.slice(0,10)),d,{formatting:{date:"YYYY-MM-DD",time:"none"}})??ie("input",{"aria-label":d,type:"date",style:pe.control,value:c??"",onChange:(g)=>p(g.currentTarget.value)}),u=(d)=>{let{date:c,to:p,days:g,...C}=a;r({...C,mode:d,...hn.has(d)?{days:7}:{}})};return tt(Oo,{children:[ie(Jt,{ui:i.ui,label:n("Date mode"),style:pe.control,value:a.mode,options:Zn.map((d)=>({value:d,label:qn(d,i.locale??"en")})),onChange:(d)=>u(d)}),a.mode==="exactDate"?s(n("Filter value"),a.date,(d)=>l({date:d})):null,a.mode==="dateRange"?tt(Oo,{children:[s(n("From date"),a.date,(d)=>l({date:d})),s(n("To date"),a.to,(d)=>l({to:d}))]}):null,hn.has(a.mode)?ie("input",{"aria-label":n("Number of days"),type:"number",min:0,step:1,style:{...pe.control,width:84},value:a.days??"",onChange:(d)=>{let c=d.currentTarget.value;if(c===""){let{days:p,...g}=a;r(g)}else l({days:Number(c)})}}):null,ie("span",{style:pe.hint,children:Me(e)?.timeZone??a.timeZone??""})]})}var Lo="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",pe={group:{margin:0,minWidth:0,display:"grid",gap:8,padding:10,border:`1px solid ${Lo}`,borderRadius:8},groupHead:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},cell:{flex:"1 1 120px",minWidth:0,display:"flex"},condition:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},slot:{display:"flex",minWidth:0,flex:"1 1 120px"},root:{display:"grid",gap:8},row:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},inline:{display:"inline-flex",flexWrap:"wrap",alignItems:"center",gap:6},control:{width:"100%",minWidth:0,minHeight:30,padding:"0 8px",border:`1px solid ${Lo}`,borderRadius:6,background:"transparent",color:"inherit",font:"inherit"},hint:{margin:0,fontSize:12,opacity:0.7}};import{jsx as me,jsxs as st,Fragment as Ka}from"react/jsx-runtime";var xr={display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},kr={minHeight:30,padding:"0 8px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit"};function Vo({fields:e,view:t,onChange:n,locale:i,ui:o,editor:r}){return me("div",{"data-uibot-view-filter":"",children:me(zn,{fields:e,filter:t.filter,locale:i,ui:o,renderCellEditor:r?.renderCellEditor,getRelationOptions:r?.getRelationOptions,advanced:r?.advanced,onChange:(a)=>{if(a)n({...t,filter:a});else{let{filter:l,...s}=t;n(s)}}})})}var Ha=10;function _o({fields:e,view:t,onChange:n,locale:i,ui:o}){let r=H(i),a=t.sort??[],l=e.filter((c)=>vt(c)),s=l.filter((c)=>!a.some((p)=>p.fieldId===c.id)),u=(c)=>{if(c.length)n({...t,sort:c});else{let{sort:p,...g}=t;n(g)}},d=(c,p)=>{let g=[...a],[C]=g.splice(c,1);if(C)g.splice(c+p,0,C);u(g)};return st("div",{"data-uibot-view-sort":"",style:{display:"grid",gap:8},children:[a.map((c,p)=>st("fieldset",{"aria-label":r("Sort {index}",{index:p+1}),style:{...xr,margin:0,padding:0,border:0,minWidth:0},children:[me("span",{style:{flex:"1 1 120px",minWidth:110,display:"flex"},children:me(Pe,{ui:o,label:r("Sort field"),style:kr,value:c.fieldId,options:l.filter((g)=>g.id===c.fieldId||s.includes(g)).map((g)=>({value:g.id,label:g.name})),onChange:(g)=>u(a.map((C,b)=>b===p?{...C,fieldId:g}:C))})}),me("span",{style:{flex:"0 1 110px",minWidth:90,display:"flex"},children:me(Pe,{ui:o,label:r("Sort direction"),style:kr,value:c.direction,options:[{value:"asc",label:r("Ascending")},{value:"desc",label:r("Descending")}],onChange:(g)=>u(a.map((C,b)=>b===p?{...C,direction:g}:C))})}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:p===0,ariaLabel:r("Move sort {index} up",{index:p+1}),title:r("Move sort {index} up",{index:p+1}),onClick:()=>d(p,-1),children:" "}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:p===a.length-1,ariaLabel:r("Move sort {index} down",{index:p+1}),title:r("Move sort {index} down",{index:p+1}),onClick:()=>d(p,1),children:" "}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove sort {index}",{index:p+1}),title:r("Remove sort {index}",{index:p+1}),onClick:()=>u(a.filter((g,C)=>C!==p)),children:" "})]},c.fieldId)),st("div",{style:xr,children:[me(Y,{ui:o,variant:"outline",size:"sm",icon:"plus",disabled:s.length===0||a.length>=Ha,onClick:()=>{let c=s[0];if(c)u([...a,{fieldId:c.id,direction:"asc"}])},children:r("Add sort")}),a.length?me(Y,{ui:o,variant:"ghost",size:"sm",onClick:()=>u([]),children:r("Clear sort")}):me("span",{style:{fontSize:12,opacity:0.7},children:r("Default order")})]})]})}function Bo({fields:e,view:t,onChange:n,locale:i,ui:o,bare:r}){let a=H(i),s=[...t.columnOrder.flatMap((c)=>{let p=e.find((g)=>g.id===c);return p?[p]:[]}),...e.filter((c)=>!t.columnOrder.includes(c.id))],u=(c,p)=>{let g=s.map((y)=>y.id),C=g[c],b=g[c+p];if(C===void 0||b===void 0)return;g[c]=b,g[c+p]=C,n({...t,columnOrder:g})},d=st("div",{style:{display:"grid",gap:6,paddingTop:r?0:6,minWidth:0},children:[st("label",{children:[me("input",{type:"checkbox",checked:t.showRowNumber!==!1,onChange:(c)=>n({...t,showRowNumber:c.currentTarget.checked})})," ",a("Show row numbers")]}),st("label",{children:[me("input",{type:"checkbox",checked:t.showRecordId===!0,onChange:(c)=>n({...t,showRecordId:c.currentTarget.checked})})," ",a("Show record IDs")]}),s.map((c,p)=>{let g=!t.hiddenColumns.includes(c.id),C=`${c.name}${c.required?" *":""}`;return st("div",{style:{...xr,flexWrap:"nowrap",gap:4},children:[me(Y,{ui:o,variant:"ghost",size:"sm",icon:g?"eye":"eyeOff",iconOnly:!0,disabled:t.type==="form"&&c.required===!0,ariaLabel:C,title:a(g?"Hide {name}":"Show {name}",{name:c.name}),onClick:()=>n({...t,hiddenColumns:g?[...t.hiddenColumns,c.id]:t.hiddenColumns.filter((b)=>b!==c.id)})}),me("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:g?1:0.5},children:C}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:p===0,ariaLabel:a("Move {name} left",{name:c.name}),onClick:()=>u(p,-1)}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:p===s.length-1,ariaLabel:a("Move {name} right",{name:c.name}),onClick:()=>u(p,1)})]},c.id)})]});if(r)return me("div",{"data-uibot-view-columns":"",children:d});return st("details",{"data-uibot-view-columns":"",children:[me("summary",{children:a("Columns")}),d]})}function Uo({fields:e,view:t,onChange:n,locale:i,ui:o}){let r=H(i),a=e.filter((l)=>l.type==="singleSelect"||l.type==="checkbox");return me("div",{style:{display:"flex",gap:6,alignItems:"center"},children:t.groupByFieldId?st(Ka,{children:[me(Ee,{name:"group"}),me(Pe,{ui:o,label:r("Grid grouping field"),style:kr,value:t.groupByFieldId,options:a.map((l)=>({value:l.id,label:l.name})),onChange:(l)=>n({...t,groupByFieldId:l})}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove grouping"),onClick:()=>{let l={...t};delete l.groupByFieldId,n(l)}})]}):me(Y,{ui:o,variant:"outline",size:"sm",icon:"plus",onClick:()=>{let l=a[0];if(l)n({...t,groupByFieldId:l.id})},children:r("Add grouping")})})}import{useState as pn}from"react";import{jsx as we,jsxs as yt}from"react/jsx-runtime";var gn={table:{label:"Table",path:"M2.5 3.5h11v9h-11zM2.5 7h11M6.5 3.5v9"},users:{label:"People",path:"M6 7.5a2.2 2.2 0 1 0 0-4.4 2.2 2.2 0 0 0 0 4.4zM2 13c0-2.2 1.8-3.6 4-3.6s4 1.4 4 3.6M11 7a1.8 1.8 0 1 0 0-3.6M12 9.6c1.3.3 2.2 1.4 2.2 3"},briefcase:{label:"Business",path:"M2.5 5.5h11v7h-11zM6 5.5v-2h4v2M2.5 9h11"},list:{label:"List",path:"M5.5 4h8M5.5 8h8M5.5 12h8M2.5 4h.01M2.5 8h.01M2.5 12h.01"},calendar:{label:"Schedule",path:"M3 4.5h10V13H3zM3 7.5h10M6 3v3M10 3v3"},package:{label:"Inventory",path:"M8 2.5l5 2.5v6l-5 2.5L3 11V5zM3 5l5 2.5L13 5M8 7.5v6"}},$o="table";function jn({icon:e,size:t=15,icons:n=gn}){let i=(e?n[e]:void 0)??n[$o]??gn.table;return we("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",width:t,height:t,fill:"none",stroke:"currentColor",strokeWidth:1.4,strokeLinecap:"round",strokeLinejoin:"round",style:{flex:"none"},children:we("path",{d:i?.path??""})})}function Wa(e){let t=H(e.locale);return yt("aside",{"data-uibot-table-list":"",style:Tt.root,children:[yt("div",{style:Tt.title,children:[we("span",{children:t("Tables")}),we("span",{children:e.tables.length})]}),we("nav",{"aria-label":t("Tables"),style:Tt.nav,children:e.tables.map((n)=>yt("button",{type:"button","aria-current":n.id===e.activeId?"page":void 0,onClick:()=>e.onSelect(n.id),style:{...Tt.item,...n.id===e.activeId?Tt.active:{}},children:[we(jn,{icon:n.icon,icons:e.icons??gn}),we("span",{style:Tt.name,children:n.name})]},n.id))}),e.onCreate?we(Y,{ui:e.ui,variant:"ghost",style:Tt.create,disabled:e.createDisabled,onClick:e.onCreate,children:t("New table")}):null]})}function Ya(e){let t=H(e.locale),n=e.icons??gn,[i,o]=pn(!1),[r,a]=pn(""),[l,s]=pn(!1),[u,d]=pn(!1),[c,p]=pn(""),g=e.table,C=e.canManage&&Boolean(g)&&!u;async function b(f){d(!0),p("");try{return await f(),!0}catch(k){return p(k instanceof Error?k.message:t("Saving failed. Your edit has been kept.")),!1}finally{d(!1)}}let y=()=>{if(!C||!e.onRename)return;a(g?.name??""),p(""),o(!0)};async function m(){let f=r.trim();if(!f||f===g?.name){o(!1);return}if(await b(()=>e.onRename?.(f)))o(!1)}let v=(f)=>{if(f.key==="Enter"||f.key==="F2")f.preventDefault(),y()};return yt("header",{"data-uibot-table-header":"",style:Qe.root,children:[yt("div",{style:Qe.left,children:[yt("span",{style:{position:"relative"},children:[we("button",{type:"button","aria-label":t("Change table icon"),"aria-haspopup":"menu","aria-expanded":l,title:e.canManage?t("Double click to change the icon"):t("Schema permission required"),disabled:!C||!e.onIconChange,style:Qe.iconButton,onDoubleClick:()=>s(!0),onKeyDown:(f)=>{if(f.key==="Enter"||f.key===" ")f.preventDefault(),s(!0)},children:we(jn,{icon:g?.icon,size:17,icons:n})}),l?we("div",{role:"menu","aria-label":t("Table icon"),style:Qe.menu,children:Object.entries(n).map(([f,k])=>yt("button",{type:"button",role:"menuitemradio","aria-checked":(g?.icon??$o)===f,title:k.label,style:Qe.menuItem,onClick:()=>{s(!1),b(()=>e.onIconChange?.(f))},children:[we(jn,{icon:f,icons:n}),we("span",{children:k.label})]},f))}):null]}),yt("div",{style:{minWidth:0},children:[i?we("input",{"aria-label":t("Table name"),value:r,disabled:u,style:Qe.input,autoFocus:!0,onChange:(f)=>a(f.currentTarget.value),onBlur:()=>{if(!c)m()},onKeyDown:(f)=>{if(f.key==="Enter")f.preventDefault(),m();if(f.key==="Escape")f.preventDefault(),o(!1),p("")}}):we("h2",{style:Qe.title,children:we("button",{type:"button","aria-label":t("Rename table {name}",{name:g?.name??""}),title:e.canManage?t("Double click to rename"):t("Schema permission required"),disabled:!C||!e.onRename,style:Qe.titleButton,onDoubleClick:y,onKeyDown:v,children:g?.name??t("Start with a table")})}),c?we("p",{role:"alert",style:Qe.error,children:c}):null,we("p",{style:Qe.summary,children:g?t("{count} fields · {mode}",{count:g.fields.length,mode:e.canWrite?t("Editable"):t("Read only")}):t("Start with a table")})]})]}),we("div",{style:Qe.actions,children:e.actions})]})}var qo="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",Tt={root:{display:"grid",gap:8,alignContent:"start",minWidth:180},title:{display:"flex",justifyContent:"space-between",padding:"0 12px",fontSize:12,opacity:0.7},nav:{display:"grid",gap:2},item:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",border:0,borderRadius:6,background:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},active:{background:"var(--uibot-active-bg, color-mix(in srgb, currentColor 10%, transparent))",fontWeight:600},name:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},create:{justifyContent:"flex-start",width:"100%"}},Qe={root:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,padding:"12px 20px"},left:{display:"flex",alignItems:"center",gap:12,minWidth:0},iconButton:{width:32,height:32,display:"grid",placeItems:"center",border:0,borderRadius:8,background:"var(--uibot-active-bg, color-mix(in srgb, currentColor 10%, transparent))",color:"inherit",cursor:"pointer"},menu:{position:"absolute",top:"100%",left:0,zIndex:60,display:"grid",minWidth:150,padding:4,border:`1px solid ${qo}`,borderRadius:8,background:"var(--background, #fff)"},menuItem:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:0,background:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},input:{height:32,width:240,maxWidth:"100%",padding:"0 8px",border:`1px solid ${qo}`,borderRadius:6,font:"inherit",fontWeight:600},title:{margin:0,fontSize:16,fontWeight:600},titleButton:{maxWidth:"100%",padding:0,border:0,background:"transparent",color:"inherit",font:"inherit",cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},error:{margin:"4px 0 0",fontSize:12,color:"var(--uibot-danger, #b3261e)"},summary:{margin:"2px 0 0",fontSize:12,opacity:0.7},actions:{display:"flex",alignItems:"center",gap:4}};import{useEffect as Pr,useMemo as wr,useRef as Ft,useState as Zt}from"react";import{jsx as bt,jsxs as Sr}from"react/jsx-runtime";function Ga(e,t){if(!t)return"";let n=e.fields.find((o)=>o.id==="title")??e.fields[0],i=n?t.values[n.id]:void 0;return typeof i==="string"?i.trim():""}function Ja(e){let t=wr(()=>H(e.locale),[e.locale]),n=vn(e.client,e.descriptor.id),i=Ft(null);if(i.current===null)i.current=nn(e.descriptor.fields);let[o,r]=Zt(i.current),[a,l]=Zt(!1),s=wr(()=>({client:e.client,descriptor:e.descriptor}),[e.client,e.descriptor]),u=Ft(s);u.current=s;let d=Ft(!0);Pr(()=>(d.current=!0,()=>{d.current=!1}),[]);let[c,p]=Zt(),g=wr(()=>{let I=new Map,A=(O,F)=>{if(!d.current||u.current!==s)return;p((P)=>({scope:s,targets:{...P?.scope===s?P.targets:{},[O]:F}}))};return{query:async(...O)=>{let F=O[0],P=(I.get(F)??0)+1;I.set(F,P),A(F,!1);try{let M=await e.client.query(...O);if(I.get(F)===P)A(F,M.ok);return M}catch(M){if(I.get(F)===P)A(F,!1);throw M}}}},[e.client,s]),C=e.descriptor.fields.some((I)=>I.type==="linkedRecord"&&(!I.link||c?.scope!==s||!c.targets[I.link.collectionId])),[b,y]=Zt(null),m=Ft(null),v=Ft(!1),f=Ft(null),k=Ft(null),{autoFocus:S}=e;Pr(()=>{if(b?.error)k.current?.focus()},[b]);let[R,E]=Zt(!1),[D,T]=Zt(!1),V=JSON.stringify(o)!==JSON.stringify(i.current)||R;Vt({dirty:V,busy:a},e);let h=()=>f.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled])")?.focus();Pr(()=>{if(S)h()},[S]);async function x(I){if(v.current||e.readOnly||C)return;T(!0);let A;try{A=cn(e.descriptor.fields,o,t,e.locale)}catch(F){y({text:F instanceof Error?F.message:t("Invalid value"),error:!0,clearable:!0});return}v.current=!0,l(!0),y(null);let O=m.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:A}]};m.current=O;try{let F=await e.client.mutate(e.descriptor.id,O);if(!n.active)return;if(!F.ok){let M=F.error.code==="validation";E(!M),y({text:F.error.message,error:!0,clearable:M});return}m.current=null,E(!1),T(!1),i.current=nn(e.descriptor.fields),r(i.current),e.onCommitted(F.data);let P=Ga(e.descriptor,F.data.items[0]);if(y({text:`${I?t("Record saved, keep adding"):t("Record saved")}${P?`:${P}`:""}`,error:!1,clearable:!1}),I)requestAnimationFrame(h);else e.onSaved?.(F.data)}catch{if(!n.active)return;E(!0),y({text:t("Saving failed. Your draft has been kept."),error:!0,clearable:!1})}finally{v.current=!1,l(!1)}}return Sr("form",{ref:f,noValidate:!0,"aria-label":t("New record form"),"data-uibot":"record-creator",onSubmit:(I)=>{I.preventDefault();let A=I.nativeEvent.submitter;x(A?.getAttribute("data-continue")==="true")},onKeyDown:(I)=>{if(I.key==="Enter"&&(I.ctrlKey||I.metaKey)&&!I.nativeEvent.isComposing&&!a)I.preventDefault(),I.currentTarget.requestSubmit()},children:[bt("fieldset",{disabled:a||e.readOnly,style:nt.fields,children:bt(At,{fields:e.descriptor.fields,values:o,submitted:D,relationClient:g,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},onChange:(I)=>{if(r(I),m.current=null,E(!1),b?.clearable)y(null)}})}),b?bt("p",{ref:k,role:b.error?"alert":"status",tabIndex:-1,style:b.error?nt.error:nt.status,children:b.text}):null,Sr("div",{"data-uibot":"record-creator-actions",style:e.stickyActions?{...nt.actions,...nt.sticky}:nt.actions,children:[Sr("span",{style:nt.hint,children:[bt("kbd",{children:"Ctrl / ⌘"})," + ",bt("kbd",{children:"Enter"})," ",t("Save")]}),bt("button",{type:"submit","aria-label":t("Save new record"),"aria-busy":a,disabled:a||e.readOnly||C,style:{...nt.button,...zt},children:a?t("Saving…"):t("Save new record")}),bt("button",{type:"submit","data-continue":"true",disabled:a||e.readOnly||C,style:nt.button,children:t("Save and continue")}),e.onCancel&&!e.stickyActions?bt(Y,{ui:e.ui,style:nt.button,disabled:a,onClick:e.onCancel,children:t("Cancel adding")}):null]})]})}var nt={sticky:{position:"sticky",bottom:0,zIndex:1,padding:"12px 0",borderTop:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",background:"var(--background, white)"},fields:{margin:0,padding:0,border:0,minWidth:0},actions:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,marginTop:12},button:{padding:"6px 10px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit",cursor:"pointer"},hint:{marginRight:"auto",fontSize:12,opacity:0.7},error:{margin:"8px 0 0",fontSize:13,color:"var(--uibot-danger, #b3261e)"},status:{margin:"8px 0 0",fontSize:12,opacity:0.8}};import{useEffect as os,useLayoutEffect as is,useRef as mn}from"react";import{jsx as Qt}from"react/jsx-runtime";var zo=[["#e8f0fe","#1a56c4"],["#e6f4ea","#1e7a3c"],["#fdecea","#b3261e"],["#fff1e0","#a05a00"],["#e8eaed","#3c4043"],["#e0f2f1","#00695c"],["#f3e8fd","#6a1b9a"]];function Nt(e){let t=Math.max(e,0)%zo.length,[n,i]=zo[t]??["#e8eaed","#3c4043"];return{background:`var(--uibot-chip-${t}-bg, ${n})`,color:`var(--uibot-chip-${t}-fg, ${i})`}}function Za({index:e,children:t}){return Qt("span",{"data-uibot-chip":"",style:{display:"inline-flex",alignItems:"center",maxWidth:"100%",padding:"1px 8px",borderRadius:999,fontSize:12,lineHeight:"18px",fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",...Nt(e)},children:t})}function Hn({ids:e,field:t,wrap:n}){let i=t.options??[];return Qt("span",{style:{display:"inline-flex",gap:4,alignItems:"center",maxWidth:"100%",overflow:"hidden",...n?{flexWrap:"wrap"}:{}},children:e.map((o)=>{let r=i.findIndex((a)=>a.id===o);return Qt(Za,{index:Pn(i,o),children:i[r]?.name??String(o)},String(o))})})}function Zp({checked:e,label:t,onToggle:n}){return Qt("input",{type:"checkbox","aria-label":t,checked:e,disabled:!n,style:{width:16,height:16,margin:0,accentColor:"var(--primary, #1a56c4)"},onMouseDown:(i)=>i.stopPropagation(),onKeyDown:(i)=>i.stopPropagation(),onChange:()=>n?.()})}var jo={singleLineText:"M3 4.5h10M8 4.5v8",longText:"M3 4h10M3 8h10M3 12h6",number:"M6.5 3 5.5 13M10.5 3l-1 10M3 6h10.5M2.5 10h10.5",bigint:"M6.5 3 5.5 13M10.5 3l-1 10M3 6h10.5M2.5 10h10.5",checkbox:"M3.5 3.5h9v9h-9zM5.6 8.1l1.8 1.8 3-3.6",date:"M3 4.5h10V13H3zM3 7.5h10M6 3v3M10 3v3",singleSelect:"M8 14a6 6 0 1 0 0-12 6 6 0 0 0 0 12zM5.8 7l2.2 2.2L10.2 7",multipleSelect:"M6 4h7M6 8h7M6 12h7M3 4h.01M3 8h.01M3 12h.01",relation:"M7 9a2.5 2.5 0 0 0 3.5 0l2-2A2.5 2.5 0 0 0 9 3.5l-.7.7M9 7a2.5 2.5 0 0 0-3.5 0l-2 2A2.5 2.5 0 0 0 7 12.5l.7-.7",linkedRecord:"M7 9a2.5 2.5 0 0 0 3.5 0l2-2A2.5 2.5 0 0 0 9 3.5l-.7.7M9 7a2.5 2.5 0 0 0-3.5 0l-2 2A2.5 2.5 0 0 0 7 12.5l.7-.7",hyperlink:"M9 3h4v4M13 3 7.5 8.5M11 9.5V13H3V5h3.5",lookup:"M7 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM10 10l3.5 3.5",formula:"M10.5 3.5c-2 0-2.2 1-2.5 3L7.2 12c-.3 1.6-1 2-2.5 2M5 7.5h5",rollup:"M12 3.5H4.5L8.5 8l-4 4.5H12",json:"M6 3.5C4.5 3.5 4.5 5 4.5 6.5S4 8 3 8c1 0 1.5.5 1.5 1.5S4.5 12.5 6 12.5M10 3.5c1.5 0 1.5 1.5 1.5 3S12 8 13 8c-1 0-1.5.5-1.5 1.5s0 3-1.5 3",blob:"M4 3.5h5l3 3V12.5H4z"};function Qp({type:e}){return Qt("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",width:13,height:13,fill:"none",stroke:"currentColor",strokeWidth:1.4,strokeLinecap:"round",strokeLinejoin:"round",style:{flex:"none",opacity:0.62},children:Qt("path",{d:jo[e]??jo.singleLineText})})}var B={root:{display:"grid",gap:12,color:"var(--uibot-schema-fg, inherit)",fontFamily:"inherit"},field:{margin:0,minWidth:0,display:"grid",gap:12,padding:16,border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:10,background:"var(--uibot-schema-bg, transparent)"},row:{display:"flex",flexWrap:"wrap",alignItems:"end",gap:12},control:{display:"grid",flex:"1 1 180px",gap:5,minWidth:140,fontSize:13},label:{color:"var(--uibot-schema-muted, color-mix(in srgb, currentColor 65%, transparent))",fontWeight:600},input:{boxSizing:"border-box",width:"100%",minHeight:"var(--uibot-schema-control-height, 36px)",padding:"7px 9px",border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"var(--uibot-schema-bg, transparent)",color:"inherit",font:"inherit"},button:{minHeight:36,padding:"7px 12px",border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"var(--uibot-schema-surface, transparent)",color:"inherit",font:"inherit",fontWeight:600,cursor:"pointer"},danger:{borderColor:"var(--uibot-schema-danger-border, color-mix(in srgb, #e5534b 45%, transparent))",background:"var(--uibot-schema-danger-bg, transparent)",color:"var(--uibot-schema-danger, #e5534b)"},checkbox:{display:"flex",alignItems:"center",gap:8,minHeight:"var(--uibot-schema-control-height, 36px)",fontSize:13},options:{display:"grid",gap:8,margin:0,minWidth:0,padding:"10px 0 0",border:0,borderTop:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))"},optionRow:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},settings:{display:"grid",gap:10,margin:0,minWidth:0,padding:"10px 0 0",border:0,borderTop:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))"},swatch:{width:18,height:18,padding:0,borderRadius:999,cursor:"pointer",flex:"none"}};import{jsx as Ce,jsxs as ke,Fragment as Rr}from"react/jsx-runtime";var Qa=["YYYY-MM-DD","YYYY/MM/DD","MM/DD/YYYY","DD/MM/YYYY","YYYY年M月D日"],Xa=["Asia/Shanghai","Asia/Hong_Kong","Asia/Tokyo","Asia/Singapore","Europe/London","Europe/Paris","America/New_York","America/Los_Angeles","UTC"],es=["CNY","USD","EUR","JPY","GBP","HKD"],ts=[0,1,2,3,4,5,6,7,8],ns={date:"YYYY-MM-DD",time:"none"},rs={kind:"decimal",precision:0,grouping:!0};function Ho({field:e,onChange:t,disabled:n,locale:i,ui:o,settings:r,dateFormatLocked:a}){let l=r?.formatting!==!1,s=r?.defaults!==!1,u=H(i),d=(g)=>t((C)=>({...C,...g})),c=()=>t((g)=>{let{defaultValue:C,...b}=g;return b}),p=(g,C,b,y,m=!1)=>ke("div",{style:B.control,children:[Ce("span",{style:B.label,children:g}),Ce(Pe,{ui:o,label:g,style:B.input,disabled:n||m,value:C,options:b,onChange:y})]});if(e.type==="date"){let g=Me(e)??ns,C=(y)=>{let{timeZone:m,...v}=g,f={...v,...m?{timeZone:m}:{},...y};if(y.timeZone==="")delete f.timeZone;d({formatting:f})},b=g.time!=="none";if(!l&&!s)return null;return ke("fieldset",{style:B.settings,"aria-label":u("Format of field {name}",{name:e.name}),children:[l?ke(Rr,{children:[Ce("strong",{style:{fontSize:13},children:u("Format")}),ke("div",{style:B.row,children:[p(u("Date format"),g.date,Qa.map((y)=>({value:y,label:y})),(y)=>C({date:y}),Boolean(a)),p(u("Time format"),g.time,[{value:"none",label:u("No time (date only)")},{value:"24h",label:u("24-hour")},{value:"12h",label:u("12-hour")}],(y)=>C({time:y}),Boolean(a)),b?p(u("Time zone"),g.timeZone??"",[{value:"",label:u("Viewer's time zone")},...Xa.map((y)=>({value:y,label:y}))],(y)=>C({timeZone:y}),Boolean(a)):null]}),ke("p",{style:{...B.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[u("Preview"),": ",_t(new Date().toISOString(),g)]})]}):null,s&&p(u("Default value"),e.defaultValue?.kind==="now"?"now":"",[{value:"",label:u("Empty")},{value:"now",label:b?u("Current date and time"):u("Today")}],(y)=>y==="now"?d({defaultValue:{kind:"now"}}):c())]})}if(e.type==="number"){let g=xn(e)??rs,C=(y)=>d({formatting:{...g,...y}}),b=e.defaultValue?.kind==="value"?String(e.defaultValue.value):"";if(!l&&!s)return null;return ke("fieldset",{style:B.settings,"aria-label":u("Format of field {name}",{name:e.name}),children:[l?ke(Rr,{children:[Ce("strong",{style:{fontSize:13},children:u("Format")}),ke("div",{style:B.row,children:[p(u("Number style"),g.kind,[{value:"decimal",label:u("Number")},{value:"percent",label:u("Percent")},{value:"currency",label:u("Currency")}],(y)=>C({kind:y})),p(u("Decimal places"),String(g.precision),ts.map((y)=>({value:String(y),label:String(y)})),(y)=>C({precision:Number(y)})),g.kind==="currency"?p(u("Currency"),g.currency??"CNY",es.map((y)=>({value:y,label:y})),(y)=>C({currency:y})):null]}),ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox","aria-label":u("Thousands separator"),checked:g.grouping!==!1,disabled:n,onChange:(y)=>C({grouping:y.currentTarget.checked})}),u("Thousands separator")]}),ke("p",{style:{...B.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[u("Preview"),":"," ",kn(g.kind==="percent"?0.1234:1234.5678,g)]})]}):null,s&&ke("label",{style:B.control,children:[Ce("span",{style:B.label,children:u("Default value")}),Ce("input",{"aria-label":u("Default value"),style:B.input,type:"number",step:"any",disabled:n,value:b,onChange:(y)=>{let m=y.currentTarget.value;if(m===""||!Number.isFinite(Number(m)))c();else d({defaultValue:{kind:"value",value:Number(m)}})}})]})]})}if(!s)return null;if(e.type==="singleLineText"||e.type==="longText")return Ce("fieldset",{style:B.settings,"aria-label":u("Defaults of field {name}",{name:e.name}),children:ke("label",{style:B.control,children:[Ce("span",{style:B.label,children:u("Default value")}),Ce("input",{"aria-label":u("Default value"),style:B.input,disabled:n,value:e.defaultValue?.kind==="value"?String(e.defaultValue.value):"",onChange:(g)=>{let C=g.currentTarget.value;if(C==="")c();else d({defaultValue:{kind:"value",value:C}})}})]})});if(e.type==="checkbox")return Ce("fieldset",{style:B.settings,"aria-label":u("Defaults of field {name}",{name:e.name}),children:ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox","aria-label":u("Checked by default"),checked:e.defaultValue?.kind==="value"&&e.defaultValue.value===!0,disabled:n,onChange:(g)=>g.currentTarget.checked?d({defaultValue:{kind:"value",value:!0}}):c()}),u("Checked by default")]})});if((e.type==="singleSelect"||e.type==="multipleSelect")&&(e.options?.length??0)>0){let g=e.options??[],C=e.defaultValue?.kind==="value"?e.defaultValue.value:void 0;if(e.type==="singleSelect")return Ce("fieldset",{style:B.settings,"aria-label":u("Defaults of field {name}",{name:e.name}),children:p(u("Default value"),typeof C==="string"?C:"",[{value:"",label:u("Empty")},...g.map((y)=>({value:y.id,label:y.name}))],(y)=>y?d({defaultValue:{kind:"value",value:y}}):c())});let b=Array.isArray(C)?C:[];return ke("fieldset",{style:B.settings,"aria-label":u("Defaults of field {name}",{name:e.name}),children:[Ce("span",{style:B.label,children:u("Default value")}),g.map((y)=>ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox","aria-label":u("Default option {name}",{name:y.name}),checked:b.includes(y.id),disabled:n,onChange:(m)=>{let v=m.currentTarget.checked?[...b,y.id]:b.filter((f)=>f!==y.id);if(v.length)d({defaultValue:{kind:"value",value:v}});else c()}}),y.name]},y.id))]})}return null}function Ko({field:e,fields:t,onChange:n,disabled:i,locale:o}){let r=H(o);if(!Gn.has(e.type))return null;let a=e.ai,l=t.filter((d)=>d.id!==e.id&&d.type!=="blob"&&d.type!=="lookup"),s=a?.sourceFieldIds??[],u=(d)=>n((c)=>{if(d)return{...c,ai:d};let{ai:p,...g}=c;return g});return ke("fieldset",{style:B.settings,"aria-label":r("AI settings of field {name}",{name:e.name}),children:[ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox",checked:Boolean(a),disabled:i,onChange:(d)=>u(d.currentTarget.checked?{prompt:""}:void 0)}),r("Generate this field with AI")]}),a?ke(Rr,{children:[ke("label",{style:B.control,children:[Ce("span",{style:B.label,children:r("AI prompt")}),Ce("textarea",{"aria-label":r("AI prompt"),style:{...B.input,minHeight:72,resize:"vertical"},rows:3,maxLength:Yn,placeholder:r("e.g. Summarize the description in one sentence"),value:a.prompt,disabled:i,onChange:(d)=>{let c=d.currentTarget.value;n((p)=>({...p,ai:{...p.ai,prompt:c}}))}})]}),ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox",checked:Boolean(a.autoFill),disabled:i,onChange:(d)=>{let c=d.currentTarget.checked;n((p)=>{let{autoFill:g,...C}=p.ai??{prompt:""};return{...p,ai:c?{...C,autoFill:!0}:C}})}}),r("Generate when a record is created")]}),Ce("span",{style:B.label,children:r("Fields the AI reads (none = all)")}),Ce("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px"},children:l.map((d)=>ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox","aria-label":r("AI reads {name}",{name:d.name}),checked:s.includes(d.id),disabled:i,onChange:(c)=>{let p=c.currentTarget.checked;n((g)=>{let C=g.ai?.sourceFieldIds??[],b=p?[...C,d.id]:C.filter((v)=>v!==d.id),{sourceFieldIds:y,...m}=g.ai??{prompt:""};return{...g,ai:b.length?{...m,sourceFieldIds:b}:m}})}}),d.name]},d.id))})]}):null]})}import{jsx as fe,jsxs as We}from"react/jsx-runtime";var as=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],Wo=(e)=>e==="singleSelect"||e==="multipleSelect";function ss(e,t){let n=t.slice(0,fn);if(!n.trim()){let{description:i,...o}=e;return o}return{...e,description:n}}function ls({fields:e,onChange:t,disabled:n=!1,focusFieldId:i,locale:o,ui:r,fieldTypes:a=as,relationTargets:l=[],lockedFieldIds:s=[],settings:u,single:d=!1,contextFields:c}){let p=H(o),g={singleLineText:p("Single line text"),longText:p("Long text"),number:p("Number"),checkbox:p("Checkbox"),date:p("Date"),singleSelect:p("Single select"),multipleSelect:p("Multiple select"),relation:p("Linked record"),hyperlink:p("Hyperlink")},C=An()?.kinds??[],b=(h)=>a.includes(h.type),y=mn(new Map),m=mn(new Map),v=mn(null),f=mn(new Map),k=mn(null);function S(h,x){let I={fields:h,target:x};k.current=I,t(h),queueMicrotask(()=>{if(k.current===I)k.current=null})}is(()=>{let h=k.current;if(!h||h.fields!==e)return;if(k.current=null,n)return;let{target:x}=h,I=x.type==="field-name"?y.current.get(x.fieldId):x.type==="option-name"?m.current.get(`${x.fieldId}:${x.optionId}`):null;if(I){I.focus(),I.select();return}(x.type==="add-field"?v.current:x.type==="add-option"?f.current.get(x.fieldId):null)?.querySelector("button")?.focus()},[n,e]),os(()=>{if(!i)return;let h=window.setTimeout(()=>{let x=y.current.get(i);x?.scrollIntoView({block:"center"}),x?.focus(),x?.select()},200);return()=>window.clearTimeout(h)},[i]);let R=(h,x)=>{if(!n)t(e.map((I)=>I.id===h?x(I):I))};function E(){if(n)return;let h={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:p("New field"),type:"singleLineText"};S([...e,h],{type:"field-name",fieldId:h.id})}function D(h){if(n)return;let x=e.filter(b),I=x.findIndex((F)=>F.id===h),A=x.filter((F)=>F.id!==h),O=A[I]??A[I-1];S(e.filter((F)=>F.id!==h),O?{type:"field-name",fieldId:O.id}:{type:"add-field"})}function T(h){if(n)return;let x={id:crypto.randomUUID(),name:p("New option")};S(e.map((I)=>I.id===h.id?{...I,options:[...I.options??[],x]}:I),{type:"option-name",fieldId:h.id,optionId:x.id})}function V(h,x){if(n)return;let I=h.options??[],A=I.findIndex((P)=>P.id===x),O=I.filter((P)=>P.id!==x),F=O[A]??O[A-1];S(e.map((P)=>{if(P.id!==h.id)return P;let M=P.defaultValue;if(!(M?.kind==="value"&&(Array.isArray(M.value)?M.value.includes(x):M.value===x)))return{...P,options:O};let{defaultValue:te,...q}=P;return{...q,options:O}}),F?{type:"option-name",fieldId:h.id,optionId:F.id}:{type:"add-option",fieldId:h.id})}return We("section",{"aria-label":p("Collection fields"),"data-uibot-schema-editor":"",style:B.root,children:[e.filter(b).map((h)=>We("fieldset",{"aria-label":p("Field {name}",{name:h.name}),style:d?{...B.field,border:0,padding:0,background:"none"}:B.field,children:[We("div",{style:B.row,children:[We("label",{style:B.control,children:[fe("span",{style:B.label,children:p("Field name")}),fe("input",{"aria-label":p("Field name"),ref:(x)=>{if(x)y.current.set(h.id,x);else y.current.delete(h.id)},style:B.input,value:h.name,disabled:n,onChange:(x)=>{let I=x.currentTarget.value;R(h.id,(A)=>({...A,name:I}))}})]}),We("div",{style:B.control,children:[fe("span",{style:B.label,children:p("Field type")}),fe(Pe,{ui:r,label:p("Field type"),style:B.input,disabled:n||s.includes(h.id),value:h.type,options:a.map((x)=>({value:x,label:g[x]})),onChange:(x)=>R(h.id,(I)=>{let{options:A,relation:O,hyperlink:F,formatting:P,defaultValue:M,...W}=I;return{...W,type:x,...Wo(x)?{options:I.options??[]}:{},...x==="relation"?{relation:{collectionId:""}}:{}}})})]}),We("label",{style:B.checkbox,children:[fe("input",{type:"checkbox","aria-label":p("Required"),checked:Boolean(h.required),disabled:n,onChange:(x)=>{let I=x.currentTarget.checked;R(h.id,(A)=>({...A,required:I}))}}),p("Required")]}),d?null:fe(Y,{ui:r,style:{...B.button,...B.danger},disabled:n||s.includes(h.id),icon:"trash",iconOnly:!0,ariaLabel:p("Delete field"),title:p("Delete field {name}",{name:h.name}),onClick:()=>D(h.id)})]}),u?.descriptions===!1?null:We("label",{style:B.control,children:[fe("span",{style:B.label,children:p("Field description")}),fe("textarea",{"aria-label":p("Field description"),style:{...B.input,minHeight:64,resize:"vertical"},rows:2,maxLength:fn,value:h.description??"",disabled:n,onChange:(x)=>{let I=x.currentTarget.value;R(h.id,(A)=>ss(A,I))}})]}),h.type==="relation"?We("div",{style:B.control,children:[fe("span",{style:B.label,children:p("Related table")}),fe(Pe,{ui:r,label:p("Related table"),style:B.input,disabled:n||s.includes(h.id),value:h.relation?.collectionId??"",options:[{value:"",label:p("Choose a related table")},...l.map((x)=>({value:x.id,label:x.name}))],onChange:(x)=>R(h.id,(I)=>({...I,relation:{collectionId:x}}))})]}):null,h.type==="hyperlink"&&C.length>0?We("fieldset",{style:B.settings,"aria-label":p("Link targets"),children:[fe("span",{style:B.label,children:p("Link targets")}),fe("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px"},children:C.map((x)=>{let I=h.hyperlink?.kinds??[];return We("label",{style:B.checkbox,children:[fe("input",{type:"checkbox",checked:I.includes(x.id),disabled:n,onChange:(A)=>{let O=A.currentTarget.checked;R(h.id,(F)=>{let P=F.hyperlink?.kinds??[],M=O?[...P,x.id]:P.filter((q)=>q!==x.id),{hyperlink:W,...te}=F;return M.length?{...te,hyperlink:{kinds:M}}:te})}}),x.label]},x.id)})}),fe("span",{style:{...B.label,opacity:0.7},children:p("None chosen offers every kind.")})]}):null,Wo(h.type)?We("fieldset",{style:B.options,"aria-label":p("Options of field {name}",{name:h.name}),children:[fe("strong",{style:{fontSize:13},children:p("Options")}),(h.options??[]).map((x,I)=>We("div",{style:B.optionRow,children:[fe("input",{"aria-label":p("Option name {index}",{index:I+1}),ref:(A)=>{let O=`${h.id}:${x.id}`;if(A)m.current.set(O,A);else m.current.delete(O)},style:{...B.input,flex:"1 1 120px",minWidth:0,width:"auto"},value:x.name,disabled:n,onChange:(A)=>{let O=A.currentTarget.value;R(h.id,(F)=>({...F,options:(F.options??[]).map((P)=>P.id===x.id?{...P,name:O}:P)}))}}),u?.optionColors===!1?null:fe("fieldset",{"aria-label":p("Colour of option {index}",{index:I+1}),style:{display:"inline-flex",flex:"none",gap:4,margin:0,padding:0,border:0,minWidth:0},children:Mt.map((A,O)=>{let F=(x.color??Mt[I%Mt.length])===A;return fe("button",{type:"button","aria-label":p(`Colour ${A}`),"aria-pressed":F,disabled:n,style:{...B.swatch,background:Nt(O).color,border:F?"2px solid currentColor":"1px solid transparent"},onClick:()=>R(h.id,(P)=>({...P,options:(P.options??[]).map((M)=>M.id===x.id?{...M,color:A}:M)}))},A)})}),fe(Y,{ui:r,style:{...B.button,...B.danger},disabled:n,icon:"trash",iconOnly:!0,ariaLabel:p("Delete option {index}",{index:I+1}),title:p("Delete option {index}",{index:I+1}),onClick:()=>V(h,x.id)})]},x.id)),fe("div",{ref:(x)=>{if(x)f.current.set(h.id,x);else f.current.delete(h.id)},children:fe(Y,{ui:r,style:B.button,icon:"plus",disabled:n,onClick:()=>T(h),children:p("Add option")})})]}):null,fe(Ho,{field:h,...u?{settings:u}:{},dateFormatLocked:s.includes(h.id),disabled:n,locale:o,ui:r,onChange:(x)=>R(h.id,x)}),u?.ai?fe(Ko,{field:h,fields:d&&c?[...c,h]:e,disabled:n,locale:o,onChange:(x)=>R(h.id,x)}):null]},h.id)),d?null:fe("div",{ref:v,children:fe(Y,{ui:r,style:B.button,icon:"plus",disabled:n,onClick:E,children:p("Add field")})})]})}import{useEffect as ii,useRef as ai,useState as Er}from"react";import{useCallback as fs,useEffect as ei,useLayoutEffect as ys,useRef as Dr,useState as ti}from"react";import{createContext as ds,useContext as cs,useCallback as us,useEffect as Yo,useId as ps,useLayoutEffect as Go,useRef as Jo,useState as Zo}from"react";import{createPortal as gs}from"react-dom";import{jsx as lt,jsxs as Xo,Fragment as Qo}from"react/jsx-runtime";var ms=ds(!1),Ir="uibot:collection-popover-open";function Ar({label:e,trigger:t,defaultOpen:n=!1,disabled:i,menu:o,children:r}){let[a,l]=Zo(n),[s,u]=Zo({left:8,top:8}),d=Jo(null),c=Jo(null),p=ps();Yo(()=>{let b=(y)=>{let m=y.detail,v=d.current;if(!m||!v||m===v)return;let f=v.closest("[data-uibot-workspace]")??v.parentElement,k=m.closest("[data-uibot-workspace]")??m.parentElement;if(f===k)l(!1)};return document.addEventListener(Ir,b),()=>document.removeEventListener(Ir,b)},[]);let g=()=>{l(!1),d.current?.focus({preventScroll:!0})},C=us(()=>{if(!a)return;let b=d.current?.getBoundingClientRect(),y=c.current?.getBoundingClientRect();if(b&&y){let m={left:Math.max(8,Math.min(b.left,window.innerWidth-y.width-8)),top:Math.max(8,b.bottom+y.height+8<=window.innerHeight?b.bottom+4:b.top-y.height-4)};u((v)=>v.left===m.left&&v.top===m.top?v:m)}},[a]);return Go(C),Go(()=>{if(!a)return;if(d.current)document.dispatchEvent(new CustomEvent(Ir,{detail:d.current}));(c.current?.querySelector("button:not(:disabled), input, select, textarea")??c.current)?.focus({preventScroll:!0})},[a]),Yo(()=>{if(!a)return;let b=(m)=>{if(m.target instanceof Node&&!c.current?.contains(m.target)&&!d.current?.contains(m.target))l(!1)},y=(m)=>{if(m.key!=="Escape")return;m.preventDefault(),m.stopPropagation(),l(!1),d.current?.focus({preventScroll:!0})};return window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),document.addEventListener("pointerdown",b),document.addEventListener("keydown",y),()=>{window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0),document.removeEventListener("pointerdown",b),document.removeEventListener("keydown",y)}},[a,C]),Xo(Qo,{children:[lt("button",{ref:d,type:"button","aria-label":e,"aria-haspopup":o?"menu":"dialog","aria-expanded":a,"aria-controls":a?p:void 0,disabled:i,style:{display:"inline-flex",alignItems:"center",gap:6,border:0,background:"transparent",color:"inherit",font:"inherit",padding:"4px 6px",cursor:"pointer"},onPointerDown:(b)=>b.stopPropagation(),onClick:()=>a?g():l(!0),children:t}),a&&gs(lt("div",{ref:c,id:p,role:o?"menu":"dialog","aria-label":e,tabIndex:-1,style:{position:"fixed",...s,zIndex:80,padding:o?4:12,minWidth:160,maxWidth:"calc(100vw - 16px)",maxHeight:"min(70vh, 600px)",overflow:"auto",boxSizing:"border-box",border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"var(--foreground, inherit)",fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},onKeyDown:(b)=>{if(!o||!["ArrowDown","ArrowUp","Home","End"].includes(b.key))return;b.preventDefault();let y=[...b.currentTarget.querySelectorAll('button[role="menuitem"]:not(:disabled)')],m=y.indexOf(document.activeElement),v=b.key==="Home"?0:b.key==="End"?y.length-1:(m+(b.key==="ArrowUp"?-1:1)+y.length)%y.length;y[v]?.focus()},children:r(g)}),document.body)]})}function Pg({ui:e,label:t,defaultOpen:n,icon:i,chevron:o,quiet:r,active:a,children:l}){let s=cs(ms),u=(d)=>lt("div",{style:{fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},children:lt("fieldset",{disabled:s,style:{border:0,padding:0,margin:0,minWidth:0},children:d})});if(e?.Popover)return e.Popover({label:t,defaultOpen:n,...i?{icon:lt(Ee,{name:i})}:{},...o?{iconEnd:lt(Ee,{name:"chevronDown",size:13})}:{},...r?{quiet:r}:{},active:a,children:typeof l==="function"?(d)=>u(l(d)):u(l)});return lt(Ar,{label:t,defaultOpen:n,trigger:Xo(Qo,{children:[i?lt(Ee,{name:i}):null,t,o?lt(Ee,{name:"chevronDown",size:13}):null]}),children:(d)=>u(typeof l==="function"?l(d):l)})}import{jsx as Kn,jsxs as oi,Fragment as bs}from"react/jsx-runtime";function ni({items:e,label:t,children:n,block:i=!1}){let[o,r]=ti(null),a=Dr(null),l=Dr(null),[s,u]=ti({x:0,y:0}),d=fs(()=>{if(!o||!l.current)return;let p=Math.max(12,Math.min(o.x,window.innerWidth-12-l.current.offsetWidth)),g=Math.max(12,Math.min(o.y,window.innerHeight-12-l.current.offsetHeight));u((C)=>C.x===p&&C.y===g?C:{x:p,y:g})},[o]);ys(d),ei(()=>{if(!o)return;return window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[o,d]);let c=Dr(null);return ei(()=>{if(!o)return;c.current=document.activeElement instanceof HTMLElement?document.activeElement:null,l.current?.querySelector("button:not(:disabled)")?.focus();let p=()=>r(null),g=(C)=>{if(C.key==="Escape")C.preventDefault(),C.stopPropagation(),r(null),c.current?.focus({preventScroll:!0})};return window.addEventListener("keydown",g),window.addEventListener("pointerdown",p),window.addEventListener("blur",p),()=>{window.removeEventListener("keydown",g),window.removeEventListener("pointerdown",p),window.removeEventListener("blur",p)}},[o]),oi("span",{ref:a,style:{display:i?"block":"inline-flex"},onKeyDown:(p)=>{if(p.shiftKey&&p.key==="F10"||p.key==="ContextMenu"){p.preventDefault(),p.stopPropagation();let g=p.target.getBoundingClientRect();r({x:Math.max(8,Math.min(g.left,window.innerWidth-240)),y:Math.max(8,Math.min(g.bottom,window.innerHeight-280))})}},onContextMenu:(p)=>{p.preventDefault(),p.stopPropagation(),r({x:Math.max(8,Math.min(p.clientX,window.innerWidth-240)),y:Math.max(8,Math.min(p.clientY,window.innerHeight-280))})},children:[n,o&&Kn("div",{ref:l,role:"menu","aria-label":t,style:{position:"fixed",left:s.x,top:s.y,boxSizing:"border-box",maxWidth:"calc(100vw - 24px)",maxHeight:"min(70vh, calc(100vh - 24px))",overflow:"auto",zIndex:60,minWidth:140,font:"inherit",padding:4,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",boxShadow:"0 4px 16px rgb(0 0 0 / 0.12)"},onPointerDown:(p)=>p.stopPropagation(),onKeyDown:(p)=>{if(!["ArrowDown","ArrowUp"].includes(p.key))return;p.preventDefault();let g=[...p.currentTarget.querySelectorAll("button:not(:disabled)")],C=g.indexOf(document.activeElement);g[(C+(p.key==="ArrowUp"?-1:1)+g.length)%g.length]?.focus()},children:e.map((p)=>Kn("button",{type:"button",role:"menuitem",disabled:p.disabled,style:{display:"block",width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderRadius:6,background:"transparent",color:p.destructive?"var(--destructive, #b3261e)":"inherit",cursor:p.disabled?"default":"pointer",opacity:p.disabled?0.5:1},onClick:()=>{r(null),p.onSelect()},children:p.label},p.id))})]})}function ri({label:e,items:t,disabled:n,icon:i}){return Kn(Ar,{label:e,disabled:n,menu:!0,trigger:i??"+",children:(o)=>Kn(bs,{children:t.map((r)=>oi("button",{type:"button",role:"menuitem",disabled:r.disabled,style:{display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderTop:r.separatorBefore?"1px solid var(--border, #d5d9df)":void 0,background:"transparent",color:r.destructive?"var(--destructive, #b3261e)":"inherit",opacity:r.disabled?0.5:1,font:"inherit"},onClick:()=>{o(),r.onSelect()},children:[r.icon,r.label]},r.id))})})}import{jsx as $e,jsxs as si}from"react/jsx-runtime";function hs(e,t,n,i){if(t===n)return[...e];let o=e.filter((a)=>a!==t),r=o.indexOf(n);if(r<0||!e.includes(t))return[...e];return o.splice(i?r+1:r,0,t),o}var Cs=["grid","kanban","gallery","calendar","form"];function vs(e,t){return{grid:e("Grid"),kanban:e("Kanban"),gallery:e("Gallery"),calendar:e("Calendar"),form:e("Form")}[t]}function xs({slot:e,items:t,label:n,children:i}){if(!t.length)return $e("span",{children:i});if(e)return $e(e,{items:t,"aria-label":n,children:i});return $e(ni,{items:t,label:n,children:i})}function ks(e){let t=H(e.locale),[n,i]=Er(null),[o,r]=Er(""),[a,l]=Er(null),s=ai(null),u=ai(null),d=Boolean(e.onReorder)&&!e.disabled&&e.views.length>1,c=e.views.map((S)=>S.id),p=(S,R,E)=>{let D=hs(c,S,R,E);if(D.join("\x00")!==c.join("\x00"))e.onReorder?.(D)};ii(()=>{let S=s.current;if(!S)return;s.current=null,document.querySelector(`[data-view-tab="${CSS.escape(S)}"]`)?.focus()}),ii(()=>{if(n)u.current?.select()},[n]);let g=Boolean(e.onDelete)&&e.views.length>1,C=(S)=>{if(!e.onRename||e.disabled)return;r(S.name),i(S.id)},b=()=>{if(!n)return;let S=e.views.find((E)=>E.id===n),R=o.trim();if(i(null),S&&R&&R!==S.name)e.onRename?.(S.id,R)},y=(S)=>[...e.onRename?[{id:"rename",icon:$e(Ee,{name:"pencil"}),label:t("Rename view"),onSelect:()=>C(S)}]:[],...e.onDuplicate?[{id:"duplicate",icon:$e(Ee,{name:"copy"}),label:t("Duplicate view"),onSelect:()=>e.onDuplicate?.(S.id)}]:[],...e.onDelete?[{id:"delete",icon:$e(Ee,{name:"trash"}),label:t("Delete view"),destructive:!0,disabled:!g,onSelect:()=>e.onDelete?.(S.id)}]:[]],m=(S,R)=>{let E=e.views.findIndex((D)=>D.id===R.id);if(S.altKey&&(S.key==="ArrowRight"||S.key==="ArrowLeft")){S.preventDefault();let D=e.views[E+(S.key==="ArrowRight"?1:-1)];if(d&&D)s.current=R.id,p(R.id,D.id,S.key==="ArrowRight")}else if(S.key==="F2")S.preventDefault(),C(R);else if(S.key==="Delete"&&g&&!e.disabled)S.preventDefault(),e.onDelete?.(R.id);else if(S.key==="ArrowRight"||S.key==="ArrowLeft"){S.preventDefault();let D=e.views[E+(S.key==="ArrowRight"?1:-1)];if(D)e.onSelect(D.id),S.currentTarget.parentElement?.parentElement?.querySelectorAll('[role="tab"]')?.[E+(S.key==="ArrowRight"?1:-1)]?.focus()}},v=(e.viewTypes??Cs).map((S)=>({id:S,label:vs(t,S),disabled:e.disabledViewTypes?.includes(S)??!1,onSelect:()=>e.onAdd?.(S)})),f=e.ui?.ContextMenu,k=e.ui?.DropdownMenu;return si("div",{"data-uibot":"collection-view-tabs",style:{display:"flex",alignItems:"flex-end",gap:2,minWidth:0,maxWidth:"100%",overflowX:"auto"},children:[$e("div",{role:"tablist","aria-label":t("Views"),style:{display:"flex",gap:2},children:e.views.map((S)=>{let R=S.id===e.activeId,E=y(S),D=n===S.id?$e("input",{ref:u,"aria-label":t("View name"),value:o,maxLength:80,style:{height:30,padding:"0 8px",font:"inherit",border:"1px solid var(--primary, #1a56c4)",borderRadius:6,background:"var(--background, white)",color:"inherit"},onChange:(T)=>r(T.target.value),onBlur:b,onKeyDown:(T)=>{if(T.stopPropagation(),T.key==="Enter")T.preventDefault(),b();else if(T.key==="Escape")T.preventDefault(),i(null)}}):si("button",{type:"button",role:"tab","aria-selected":R,tabIndex:R?0:-1,disabled:e.disabled,title:e.onRename?t("Double click to rename"):void 0,"data-view-tab":S.id,draggable:d,onDragStart:(T)=>{if(!d)return;T.dataTransfer.effectAllowed="move",T.dataTransfer.setData("text/plain",S.id),l({id:S.id})},onDragOver:(T)=>{if(!a||a.id===S.id)return;T.preventDefault();let V=T.currentTarget.getBoundingClientRect(),h=(T.clientX||0)>V.left+V.width/2;if(a.over!==S.id||a.after!==h)l({id:a.id,over:S.id,after:h})},onDrop:(T)=>{if(!a)return;T.preventDefault(),p(a.id,S.id,Boolean(a.after)),l(null)},onDragEnd:()=>l(null),style:{boxShadow:a?.over===S.id?a.after?"inset -2px 0 0 var(--primary, #1a56c4)":"inset 2px 0 0 var(--primary, #1a56c4)":void 0,opacity:a?.id===S.id?0.5:1,position:"relative",display:"inline-flex",alignItems:"center",gap:6,height:34,padding:"0 12px",border:0,borderBottom:R?"2px solid var(--primary, #1a56c4)":"2px solid transparent",background:"transparent",color:R?"var(--primary, #1a56c4)":"inherit",fontWeight:R?600:400,fontSize:13,whiteSpace:"nowrap",cursor:"pointer"},onClick:()=>e.onSelect(S.id),onDoubleClick:()=>C(S),onKeyDown:(T)=>m(T,S),children:[$e("span",{children:S.name}),e.dirty&&R&&$e("span",{role:"img","aria-label":t("Unsaved changes"),style:{width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}})]});return $e(xs,{slot:f,items:n===S.id?[]:E,label:t("View actions"),children:D},S.id)})}),e.onAdd&&(k?$e(k,{label:t("Add view"),items:v,disabled:e.disabled}):$e(ri,{label:t("Add view"),items:v,disabled:e.disabled}))]})}import{useRef as Ps,useState as ws}from"react";import{jsx as Re,jsxs as Xt}from"react/jsx-runtime";function Ss(e){let t=H(e.locale),n=e.descriptor.fields.find((s)=>s.id===e.view.groupByFieldId),i=Vn(e),o=Ps(null),[r,a]=ws(null);if(!n||!["singleSelect","checkbox"].includes(n.type))return Re("p",{role:"status",children:t("Choose a single-select or boolean grouping field.")});let l=Qr(n,t);return Xt("section",{"data-uibot":"collection-kanban",children:[Re(Kt,{...e}),Re("div",{style:{display:"flex",gap:12,overflowX:"auto",alignItems:"flex-start",paddingBottom:12},children:l.map((s)=>Re(Rs,{...e,field:n,lane:s,lanes:l,blocked:i.blocked,onOpen:a,onMove:(u,d)=>void i.move(u,{[n.id]:d.value}),onDrag:(u)=>{o.current=u},onDrop:(u)=>{if(o.current?.id===u)i.move(o.current,{[n.id]:s.value});o.current=null}},s.id))}),Re(_n,{state:i,locale:e.locale,ui:e.ui}),r&&Re(Dt,{...e,row:r,onClose:()=>a(null)},r.id)]})}function Rs({field:e,lane:t,lanes:n,blocked:i,onOpen:o,onMove:r,onDrag:a,onDrop:l,...s}){let u=H(s.locale),d=He(s.features),c=d.optionChips,p=!s.readOnly&&d.rowUpdate,g=Wt(s,eo(s.view,e,t)),C=s.descriptor.fields.find((m)=>m.type==="singleLineText"||m.type==="longText")?.id,b=St(s.descriptor.fields,s.view).filter((m)=>m.id!==e.id&&m.id!==C).slice(0,3),y=p&&!i&&!(e.required&&t.value===null);return Xt("section",{"aria-label":u("Lane {name}",{name:t.name}),"data-lane-id":t.id,style:{...Ke,flex:"0 0 290px",minWidth:0,...c?{background:"var(--muted, #f4f6f8)",padding:10}:{}},onDragOver:(m)=>{if(y)m.preventDefault()},onDrop:(m)=>{if(!y)return;m.preventDefault(),l(m.dataTransfer.getData("application/x-uibot-record"))},children:[Xt("h3",{style:c?{display:"flex",alignItems:"center",gap:6,margin:"0 0 6px",fontSize:13}:void 0,children:[c&&Re("span",{"aria-hidden":"true",style:{width:8,height:8,borderRadius:999,...t.id.startsWith("option:")?{background:Nt(As(n,t)).color}:{background:"var(--muted-foreground, #9a9892)"}}}),t.name," · ",gr(u,g.page.total,g.page.items.length,s.locale)]}),Re(Yt,{state:g,locale:s.locale,ui:s.ui,hideCount:!0}),Xt("div",{style:{display:"flex",flexDirection:"column",gap:8,marginTop:12,maxHeight:"65vh",overflowY:"auto"},children:[g.page.items.map((m)=>{let v=ze(m,s.descriptor.fields);return Xt("article",{"data-record-id":m.id,style:c?{...Ke,padding:10,boxShadow:"0 1px 2px rgb(0 0 0 / 0.06)",cursor:"grab",position:"relative"}:Ke,draggable:p&&!i&&!g.loading,onDragStart:(f)=>{a(m),f.dataTransfer.setData("application/x-uibot-record",m.id),f.dataTransfer.effectAllowed="move"},onDragEnd:()=>a(null),children:[Re("button",{type:"button",style:{...se,width:"100%",textAlign:"left",overflowWrap:"anywhere",...c?{border:0,padding:"0 28px 0 0",background:"transparent",fontWeight:600}:{}},"aria-label":u("Open {name}",{name:v}),onClick:()=>o(m),children:v}),c&&Re(Is,{row:m,fields:b}),p&&(s.ui?.DropdownMenu?Re("span",{style:{position:"absolute",top:4,right:4},children:s.ui.DropdownMenu({label:u("Move {name}",{name:v}),icon:Re(Ee,{name:"more"}),disabled:i||g.loading,items:n.map((f)=>({id:f.id,label:u("Move to {name}",{name:f.name}),disabled:f.id===t.id||!!e.required&&f.value===null,onSelect:()=>r(m,f)}))})}):Xt("div",{style:{display:"flex",flexDirection:"column",gap:4,marginTop:8},children:[Re("span",{children:u("Move to")}),Re(Pe,{ui:s.ui,label:u("Move {name}",{name:v}),style:se,disabled:i||g.loading,value:t.id,onChange:(f)=>{let k=n.find((S)=>S.id===f);if(k&&k.id!==t.id)r(m,k)},options:n.map((f)=>({value:f.id,label:f.name,disabled:!!e.required&&f.value===null}))})]}))]},m.id)}),!g.loading&&!g.error&&!g.page.items.length&&Re("p",{children:u("No records in this lane.")})]})]})}function Is({row:e,fields:t}){let n=t.map((i)=>{let o=e.values[i.id],r=i.type==="singleSelect"||i.type==="multipleSelect",a=Array.isArray(o)?o:o==null?[]:[o],l=i.type==="linkedRecord"?on(e,i):In(o,i,e.computedErrors?.[i.id]);return{field:i,chips:r,ids:a,text:l}}).filter((i)=>i.chips?i.ids.length>0:i.text!=="");if(!n.length)return null;return Re("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:6,alignItems:"center",fontSize:12,opacity:0.85},children:n.map((i)=>i.chips?Re(Hn,{ids:i.ids,field:i.field},i.field.id):Re("span",{style:{fontVariantNumeric:"tabular-nums"},children:i.text},i.field.id))})}function As(e,t){return e.filter((n)=>n.id.startsWith("option:")).findIndex((n)=>n.id===t.id)}import{useState as Ds}from"react";import{jsx as rt,jsxs as Tr}from"react/jsx-runtime";function Es(e){let t=H(e.locale),n=He(e.features).optionChips,i=Wt(e,Sn(e.view)),[o,r]=Ds(null),a=e.descriptor.fields.find((s)=>s.type==="singleLineText"||s.type==="longText")?.id,l=St(e.descriptor.fields,e.view).filter((s)=>!n||s.id!==a);return Tr("section",{"data-uibot":"collection-gallery",children:[rt(Kt,{...e}),rt(Yt,{state:i,locale:e.locale,ui:e.ui}),rt("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 240px), 1fr))",gap:12,marginTop:12},children:i.page.items.map((s)=>Tr("article",{"data-record-id":s.id,style:{...Ke,minWidth:0,...n?{boxShadow:"0 1px 2px rgb(0 0 0 / 0.05)"}:{}},children:[rt("button",{type:"button","aria-label":t("Open {name}",{name:ze(s,e.descriptor.fields)}),style:{...se,width:"100%",textAlign:"left",overflowWrap:"anywhere",...n?{border:0,padding:0,background:"transparent",fontWeight:600,fontSize:"var(--uibot-workspace-font-size, 13px)"}:{}},onClick:()=>r(s),children:ze(s,e.descriptor.fields)}),rt("dl",{children:l.filter((u)=>!n||!Ts(s,u)).slice(0,n?5:l.length).map((u)=>Tr("div",{children:[rt("dt",{style:{fontSize:12,opacity:0.7},children:u.name}),rt("dd",{style:{margin:"0 0 8px",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n&&(u.type==="singleSelect"||u.type==="multipleSelect")&&s.values[u.id]!=null?rt(Hn,{ids:Array.isArray(s.values[u.id])?s.values[u.id]:[s.values[u.id]],field:u}):(u.type==="linkedRecord"?on(s,u):In(s.values[u.id],u,s.computedErrors?.[u.id]))||"—"})]},u.id))})]},s.id))}),!i.loading&&!i.error&&!i.page.items.length&&rt("p",{children:t("No records match this view.")}),o&&rt(Dt,{...e,row:o,onClose:()=>r(null)},o.id)]})}function Ts(e,t){let n=e.values[t.id];if(t.type==="linkedRecord")return!on(e,t);return n==null||n===""||Array.isArray(n)&&n.length===0}import{useRef as Fs,useState as Fr}from"react";import{jsx as be,jsxs as ht}from"react/jsx-runtime";function Ns(e){let t=H(e.locale),n=He(e.features),i=n.optionChips,o=!e.readOnly&&n.rowUpdate,[r,a]=Fr(()=>{let f=new Date().toISOString().slice(0,7),k=e.initialMonth??f;try{return an(k),{month:k,error:""}}catch{return{month:f,error:t("Invalid initial month. Showing the current UTC month.")}}}),{month:l,error:s}=r,[u,d]=Fr(null),c=e.descriptor.fields.find((f)=>f.id===e.view.dateFieldId&&f.type==="date"),p=Fs(null),g=Vn(e),C=Wt(e,c?to(e.view,c.id,l):{limit:1},!!c),b=an(l),y=(f)=>{try{an(f),a({month:f,error:""})}catch{a((k)=>({...k,error:t("Choose a valid month between years 1 and 9998.")}))}},m=(f)=>{let k=new Date(b.start);k.setUTCMonth(k.getUTCMonth()+f),y(k.toISOString().slice(0,7))},v=(f,k)=>{if(!c)return;try{g.move(f,{[c.id]:Rn(f.values[c.id],k)})}catch(S){g.mutation.setError(S instanceof Error?S.message:t("Invalid date"))}};if(!c)return be("p",{role:"status",children:t("Choose a date field for this calendar.")});return ht("section",{"data-uibot":"collection-calendar",children:[be(Kt,{...e}),ht("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginBottom:12},children:[be(Y,{ui:e.ui,style:se,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:t("Previous month"),onClick:()=>m(-1)}),e.ui?.MonthPicker?be(e.ui.MonthPicker,{value:l,onChange:y,"aria-label":t("Calendar month")}):e.ui?.Button?be("strong",{role:"status","aria-label":t("Calendar month"),style:{minWidth:96,textAlign:"center",fontVariantNumeric:"tabular-nums"},children:t("{year}-{month}",{year:l.slice(0,4),month:l.slice(5,7)})}):ht("label",{children:[t("Month")," ",be("input",{type:"month","aria-label":t("Calendar month"),min:"0001-01",max:"9998-12",value:l,onChange:(f)=>y(f.target.value),style:se})]}),be(Y,{ui:e.ui,style:se,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:t("Next month"),onClick:()=>m(1)}),be(Y,{ui:e.ui,style:se,variant:"outline",size:"sm",onClick:()=>y(new Date().toISOString().slice(0,7)),children:t("Today")})]}),s&&be("p",{role:"alert",children:s}),be(Yt,{state:C,locale:e.locale,ui:e.ui}),be("div",{style:{overflowX:"auto",minWidth:0},children:ht("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, minmax(0, 1fr))"},children:[[t("Sun"),t("Mon"),t("Tue"),t("Wed"),t("Thu"),t("Fri"),t("Sat")].map((f)=>be("strong",{style:i?{padding:"8px 10px",fontSize:12,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"}:{padding:8},children:f},f)),["sun","mon","tue","wed","thu","fri","sat"].slice(0,b.weekday).map((f)=>be("div",{"aria-hidden":"true",style:i?{borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",background:"var(--muted, #f4f6f8)",opacity:0.5}:void 0},f)),Array.from({length:b.days},(f,k)=>{let S=`${l}-${String(k+1).padStart(2,"0")}`,R=C.page.items.filter((E)=>String(E.values[c.id]??"").slice(0,10)===S);return ht("article",{"aria-label":t("Day {day}",{day:S}),"data-calendar-day":S,style:{...Ke,minHeight:130,maxHeight:280,overflowY:"auto",minWidth:0,borderRadius:0,...i?{padding:8,border:0,borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",fontSize:12}:{}},onDragOver:(E)=>{if(o&&!g.blocked)E.preventDefault()},onDrop:(E)=>{if(!o||g.blocked)return;if(E.preventDefault(),p.current?.id===E.dataTransfer.getData("application/x-uibot-record"))v(p.current,S);p.current=null},children:[be("time",{dateTime:S,children:k+1}),R.map((E)=>ht("article",{"data-record-id":E.id,style:{marginTop:8},draggable:o&&!g.blocked&&!C.loading,onDragStart:(D)=>{p.current=E,D.dataTransfer.setData("application/x-uibot-record",E.id),D.dataTransfer.effectAllowed="move"},onDragEnd:()=>{p.current=null},children:[ht("button",{type:"button",style:{...se,textAlign:"left",width:"100%",overflowWrap:"anywhere",...i?{border:0,padding:"3px 8px",fontSize:12,fontWeight:500,...Nt(0)}:{}},"aria-label":t("Open {name}",{name:ze(E,e.descriptor.fields)}),onClick:()=>d(E),children:[ze(E,e.descriptor.fields)," ",be("small",{children:String(E.values[c.id]).slice(11,16)})]}),o&&be(Ms,{ui:e.ui,t,row:E,fieldId:c.id,title:ze(E,e.descriptor.fields),disabled:g.blocked||C.loading,onMove:v})]},E.id))]},S)})]})}),!C.loading&&!C.error&&!C.page.items.length&&be("p",{children:t("No dated records match this month.")}),be(_n,{state:g,locale:e.locale,ui:e.ui}),!g.intent&&g.mutation.error&&be("p",{role:"alert",children:g.mutation.error}),u&&be(Dt,{...e,row:u,onClose:()=>d(null)},u.id)]})}function Ms({ui:e,t,row:n,fieldId:i,title:o,disabled:r,onMove:a}){let[l,s]=Fr({day:String(n.values[i]).slice(0,10)}),u=e?.DateMove;if(u)return be(u,{label:t("Move {name} to date",{name:o}),value:l.day,disabled:r,onPick:(d)=>a(l.baseline??n,d)});return ht("div",{style:{marginTop:4,display:"flex",gap:4,flexWrap:"wrap"},children:[be("input",{type:"date","aria-label":t("Move {name} to date",{name:o}),value:l.day,disabled:r,style:{width:"100%",minWidth:0},onChange:(d)=>s({day:d.target.value,baseline:l.baseline??n})}),be("button",{type:"button",style:se,"aria-label":t("Move {name}",{name:o}),disabled:r||!l.day,onClick:()=>a(l.baseline??n,l.day),children:t("Move")})]})}import{jsx as dt,jsxs as en}from"react/jsx-runtime";function bm({fields:e,view:t,onChange:n,locale:i,ui:o,features:r,sections:a,filterEditor:l,grouping:s,rowHeight:u}){let d=H(i),c=He(r),p=e.filter((v)=>v.type==="singleSelect"||v.type==="checkbox"),g=e.filter((v)=>v.type==="date"),C=(v)=>{let f={...t,type:v};if(delete f.groupByFieldId,delete f.dateFieldId,v==="kanban"&&p[0])f.groupByFieldId=p[0].id;if(v==="calendar"&&g[0])f.dateFieldId=g[0].id;if(v==="form")f.hiddenColumns=f.hiddenColumns.filter((k)=>!e.find((S)=>S.id===k)?.required);n(f)},b={grid:d("Grid"),kanban:d("Kanban"),gallery:d("Gallery"),calendar:d("Calendar"),form:d("Form")},y=c.viewTypes.map((v)=>({value:v,label:b[v],disabled:v==="kanban"&&!p.length||v==="calendar"&&!g.length})),m=t.type??"grid";return en("div",{style:{display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},children:[en("div",{children:[d("View type")," ",dt(Pe,{ui:o,label:d("View type"),style:se,value:m,options:y,onChange:(v)=>C(v)})]}),m==="grid"&&c.groupBy&&p.length>0&&s!==!1&&dt("div",{style:{flexBasis:"100%"},children:dt(Uo,{fields:e,view:t,onChange:n,locale:i,ui:o})}),m==="grid"&&u!==!1&&en("div",{children:[d("Row height")," ",dt(Pe,{ui:o,label:d("Row height"),style:se,value:t.rowHeight??"short",options:Vr.map((v)=>({value:v,label:d(`Row height ${v}`)})),onChange:(v)=>{let f={...t};if(v==="short")delete f.rowHeight;else f.rowHeight=v;n(f)}})]}),m==="kanban"&&en("div",{children:[d("Group by")," ",dt(Pe,{ui:o,label:d("Kanban grouping field"),style:se,value:t.groupByFieldId??"",options:p.map((v)=>({value:v.id,label:v.name})),onChange:(v)=>n({...t,groupByFieldId:v})})]}),m==="calendar"&&en("div",{children:[d("Date field")," ",dt(Pe,{ui:o,label:d("Calendar date field"),style:se,value:t.dateFieldId??"",options:g.map((v)=>({value:v.id,label:v.name})),onChange:(v)=>n({...t,dateFieldId:v})})]}),(a?.filter||a?.columns||a?.sort)&&en("div",{style:{display:"grid",gap:12,flexBasis:"100%"},children:[a?.filter&&dt(Vo,{fields:e,view:t,onChange:n,locale:i,ui:o,editor:l}),a?.columns&&dt(Bo,{fields:e,view:t,onChange:n,locale:i,ui:o}),a?.sort&&dt(_o,{fields:e,view:t,onChange:n,locale:i,ui:o})]})]})}export{Sa as CollectionAggregateRows,cr as CollectionAggregateSummary,Ns as CollectionCalendar,Fa as CollectionForm,Es as CollectionGallery,Ss as CollectionKanban,Dt as CollectionRecordEditor,bm as CollectionViewSettings,ks as CollectionViewTabs,gn as PAGED_TABLE_ICONS,zn as PagedCollectionFilterBuilder,Ja as PagedCollectionRecordCreator,ls as PagedCollectionSchemaEditor,Ya as PagedCollectionTableHeader,Wa as PagedCollectionTableList,jn as PagedTableIcon,qn as dateModeLabel,Un as filterOperatorLabel,To as pagedFilterSummary};
|
|
1
|
+
function Zs(e){return{...e,components:e.components,actions:e.actions??{},templates:e.templates??{}}}var Lt=["blue","green","red","orange","gray","teal","purple"];function vi(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 Vr(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),a=o?.type==="number"||o?.type==="rating"||o?.type==="autoNumber"?e.reduce((d,s)=>d+(vi(s.values[i.fieldId])??0),0):0;return{fieldId:i.fieldId,fn:"sum",value:a}})}function _r(e){return!!e&&typeof e==="object"&&"conjunction"in e&&"filterSet"in e}function xi(e){return!!e&&typeof e==="object"&&"fieldId"in e&&"operator"in e}function ki(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 Br(e,t){if(!t)return!0;if(_r(t)){let n=t.filterSet.map((i)=>_r(i)?Br(e,i):xi(i)?ki(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 Ur(e,t,n,i){let o=e.views.find((l)=>l.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((l)=>Br(l,o.filter));if(o.sort?.length)r.sort((l,C)=>{for(let b of o.sort??[]){let y=l.values[b.fieldId],g=C.values[b.fieldId];if(y===g)continue;if(y==null)return 1;if(g==null)return-1;let v=e.fields.find((A)=>A.id===b.fieldId)?.type,f=(A)=>{if(["number","rating","autoNumber"].includes(v??"")&&typeof A==="number")return A;if(["date","createdTime","lastModifiedTime"].includes(v??"")){let E=Date.parse(String(A));if(Number.isFinite(E))return E}return String(A)},S=f(y),R=f(g);if(S===R)continue;let k=S<R?-1:1;return b.direction==="desc"?-k:k}return l.id<C.id?-1:l.id===C.id?0:1});let a=o.projection?.length?e.fields.filter((l)=>o.projection?.includes(l.id)):e.fields,d=i?.search?.trim().toLowerCase();if(d)r=r.filter((l)=>a.some((C)=>String(l.values[C.id]??"").toLowerCase().includes(d)));let s=Vr(r,o.aggregates,e.fields),c=o.group?.fieldId;if(!c)return{view:o,columns:a,rows:r,...s.length?{aggregates:s}:{}};let u=[],m=new Map;for(let l of r){let C=String(l.values[c]??"");if(!m.has(C))m.set(C,[]),u.push(C);m.get(C)?.push(l)}let p=u.map((l)=>{let C=m.get(l)??[];return{key:l,fieldId:c,rows:C,aggregates:Vr(C,o.aggregates,e.fields)}});return{view:o,columns:a,rows:r,groups:p,...s.length?{aggregates:s}:{}}}var bn=500,Zn=2000,Qn=new Set(["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"]);function Ne(e){return e.type==="lookup"||e.type==="formula"||e.type==="rollup"}function xt(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 qr=["short","medium","tall","extra"];function sl(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 d=n[r];if(!(r in n)||d!==null&&!(typeof d==="number"&&Number.isFinite(d))&&!((a==="min"||a==="max")&&typeof d==="string"&&Number.isFinite(Date.parse(d))))throw Error(`Invalid aggregate value ${r}.`);o[r]=d}return{groups:i,values:o}})}var Pi=/^[A-Za-z][A-Za-z0-9_]{0,31}$/,wi=new Set(["singleLineText","number","checkbox","date","singleSelect"]);function $r(e,t){return{...e.filter?{filter:e.filter}:{},search:e.search??"",groupBy:t.groupBy??[],aggregates:t.aggregates}}function Ve(e,t){return{code:e,...t}}function Ri(e){return(e.type==="formula"||e.type==="rollup")&&(e.resultType==="text"||e.resultType==="number"||e.resultType==="date")}function Jn(e){return e.type==="number"||(e.type==="formula"||e.type==="rollup")&&e.resultType==="number"}function jr(e,t){if(t.aggregates.length===0)return Ve("empty");if(t.aggregates.length>8||t.groupBy.length>3)return Ve("too_many");let n=new Set;for(let o of t.aggregates){if(!["count","sum","avg","min","max","filled","empty"].includes(o.fn))return Ve("function");if(!Pi.test(o.as)||n.has(o.as)||t.groupBy.includes(o.as))return Ve("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 Ve(o.fn==="sum"?"sum_field":"unknown_field",{alias:o.as,...o.fieldId!==void 0?{fieldId:o.fieldId}:{}});if(o.fn==="sum"&&!Jn(r))return Ve("sum_field",{fieldId:r.id,alias:o.as});if(o.fn==="avg"&&!Jn(r))return Ve("numeric_field",{fieldId:r.id,alias:o.as});if((o.fn==="min"||o.fn==="max")&&!Jn(r)&&r.type!=="date"&&!((r.type==="formula"||r.type==="rollup")&&r.resultType==="date"))return Ve("extrema_field",{fieldId:r.id,alias:o.as});if((o.fn==="filled"||o.fn==="empty")&&!xt(r))return Ve("queryable_field",{fieldId:r.id,alias:o.as});if(o.fn==="count"&&!xt(r))return Ve("count_field",{fieldId:r.id,alias:o.as})}let i=new Set;for(let o of t.groupBy){if(i.has(o))return Ve("duplicate_group",{fieldId:o});i.add(o);let r=e.fields.find((a)=>a.id===o);if(!r)return Ve("unknown_field",{fieldId:o});if(!wi.has(r.type)&&!Ri(r))return Ve("not_groupable",{fieldId:o})}return null}var zr=(e)=>String(e).padStart(2,"0");function Xe(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 kt(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=Xe(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 hn(e,t){let n=Xe(e,t??"UTC");return`${n.year}-${zr(n.month)}-${zr(n.day)}`}var Si=/^[a-z][a-z0-9_-]{0,31}$/,Cn=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function Hr(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 Ii(e){if(!Cn(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"||!Hr(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(!Cn(t)||Object.keys(t).length!==2||typeof t.kind!=="string"||!Si.test(t.kind)||typeof t.id!=="string"||!t.id||t.id.length>200)return"hyperlink reference is invalid"}return null}var Ot=(e)=>Ii(e)===null;function on(e){if(!Cn(e)||typeof e.url!=="string")return"";return typeof e.text==="string"&&e.text.trim()?e.text:e.url}function Kr(e){if(!Cn(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 Pt(e){let t=e.trim();if(!t)return null;if(t.startsWith("{"))try{let r=JSON.parse(t);return Ot(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(!Hr(o))return null;return i&&i!==o?{url:o,text:i}:{url:o}}function an(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 d=Xe(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 er=["exactDate","dateRange","today","yesterday","tomorrow","currentWeek","lastWeek","nextWeek","currentMonth","lastMonth","nextMonth","currentYear","lastYear","nextYear","pastDays","nextDays","daysAgo","daysFromNow"],vn=new Set(["pastDays","nextDays","daysAgo","daysFromNow"]),Wr={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"]},Vt=new Set(["isEmpty","isNotEmpty"]);function Ye(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 Yr(e){let t=Ye(e);return t?Wr[t]:[]}var Xn=/^\d{4}-\d{2}-\d{2}$/,Ai=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function tr(e){if(!Ai(e))return!1;let t=e.mode;if(!er.includes(t))return!1;if(e.timeZone!==void 0&&typeof e.timeZone!=="string")return!1;if(t==="exactDate")return typeof e.date==="string"&&Xn.test(e.date);if(t==="dateRange")return typeof e.date==="string"&&Xn.test(e.date)&&typeof e.to==="string"&&Xn.test(e.to)&&e.date<=e.to;if(vn.has(t))return Number.isInteger(e.days)&&Number(e.days)>=0&&Number(e.days)<=36500;return!0}function Gr(e,t){if(!e)return"unknown field";let n=Ye(e),i=t.operator==="contains"&&(n==="number"||n==="checkbox"||n==="date"||n==="singleSelect");if(!n||!(Wr[n].includes(t.operator)||i))return"operator not allowed";if(Vt.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 tr(o)||typeof o==="string"&&Number.isFinite(Date.parse(o))?null:"date required"}}var Di={spec:["html","markdown","zip"],prototype:["html","zip"],deck:["html","pptx","zip"],poster:["html","zip"]},Ul=Array.from(new Set(Object.values(Di).flat()));var jl=Object.freeze([Object.freeze({name:"manifest",summary:"Describe query operations and list the derived resource index.",positionals:Object.freeze([]),options:Object.freeze([])}),Object.freeze({name:"search",summary:"Search resources with deterministic bilingual ranking and reasons.",positionals:Object.freeze([Object.freeze({name:"text",property:"text",type:"string",required:!1})]),options:Object.freeze([...[["function","functions"],["scenario","scenarios"],["unit","units"],["industry","industries"]].map(([e,t])=>Object.freeze({name:e,property:t,type:"string",multiple:!0,cliEncoding:"comma-separated"})),Object.freeze({name:"kind",property:"kinds",type:"resource-kind",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"tag",property:"tags",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"category",property:"categories",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"capability",property:"capabilities",type:"string",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"maturity",property:"maturities",type:"resource-maturity",multiple:!0,cliEncoding:"comma-separated"}),Object.freeze({name:"limit",property:"limit",type:"positive-integer"})])}),Object.freeze({name:"get",summary:"Resolve one canonical resource id or unambiguous alias.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([])}),Object.freeze({name:"build",summary:"Plan dependency closure and gaps without writing or installing.",positionals:Object.freeze([Object.freeze({name:"root",property:"roots",type:"string",required:!0,variadic:!0})]),options:Object.freeze([])}),Object.freeze({name:"docs",summary:"Read curated public documentation for one resource.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([{name:"locale",property:"locale",type:"string"},{name:"page",property:"page",type:"positive-integer"}])}),Object.freeze({name:"examples",summary:"Read one bounded page of examples and exact dependencies. Follow nextPage for complete source.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([{name:"page",property:"page",type:"positive-integer"}])}),Object.freeze({name:"install-plan",summary:"Describe distribution channels and fixed snapshot identity/closure without installing or writing.",positionals:Object.freeze([Object.freeze({name:"id-or-alias",property:"id",type:"string",required:!0})]),options:Object.freeze([])})]);var Ei=["background","foreground","card","card-foreground","popover","popover-foreground","primary","primary-foreground","secondary","secondary-foreground","muted","muted-foreground","accent","accent-foreground","border","input","ring","destructive","destructive-foreground","success","success-foreground","warning","warning-foreground"],Kl=[...Ei,"radius","font-display","font-body","font-mono"];function Ti(e){return{expectedRevisionId:e.revisionId,savedContent:e.content.content,draft:e.content.content,format:e.content.format,schemaVersion:e.content.schemaVersion}}function ed(e,t){if(t===e.draft)return e;return{...e,draft:t}}function Fi(e){return e.draft!==e.savedContent}function td(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 nd(e,t){if(Fi(e))return e;let n=Ti(t);if(e.expectedRevisionId===n.expectedRevisionId&&e.savedContent===n.savedContent&&e.draft===n.draft&&e.format===n.format&&e.schemaVersion===n.schemaVersion)return e;return n}var ot=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),wt=(e,t)=>Object.keys(e).every((n)=>t.includes(n)),Rt=(e,t)=>typeof e==="string"&&e.length>0&&e.length<=t,Jr=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,xn=(e)=>typeof e==="string"&&/^[A-Za-z0-9_]{1,64}$/.test(e),Zr=(e,t=100)=>Array.isArray(e)&&e.length<=t&&e.every(xn)&&new Set(e).size===e.length;function Ni(e){if(!ot(e)||!wt(e,["id","name","type","required","options","link","lookup","formula","rollup"])||!xn(e.id)||!Rt(e.name,200)||!["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect","linkedRecord","lookup","formula","rollup"].includes(String(e.type))||e.required!==void 0&&typeof e.required!=="boolean")return!1;if(e.options!==void 0&&(!Array.isArray(e.options)||e.options.length>100||e.options.some((t)=>!ot(t)||!wt(t,["id","name"])||!xn(t.id)||!Rt(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&&(!ot(o)||!wt(o,[...i])||i.some((r)=>!Rt(o[r],r==="expression"?2048:512))))return!1}return!0}function od(e){if(!ot(e)||!wt(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))||!Rt(e.collectionId,512)||!Rt(e.authorId,512)||typeof e.createdAt!=="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.createdAt)||!Number.isFinite(Date.parse(e.createdAt)))return!1;try{if(new TextEncoder().encode(JSON.stringify(e)).length>131072)return!1}catch{return!1}let{descriptor:t,view:n}=e;if(!ot(t)||!wt(t,["id","name","schemaVersion","fields"])||t.id!==e.collectionId||!Rt(t.name,200)||!Jr(t.schemaVersion)||!Array.isArray(t.fields)||t.fields.length<1||t.fields.length>100||!t.fields.every(Ni)||new Set(t.fields.map((r)=>r.id)).size!==t.fields.length)return!1;if(!ot(n)||!wt(n,["id","name","version","type","groupByFieldId","dateFieldId","search","filter","sort","columnOrder","hiddenColumns","columnWidths"])||!xn(n.id)||!Rt(n.name,200)||!Jr(n.version)||!Zr(n.columnOrder)||!Zr(n.hiddenColumns)||!ot(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)=>ot(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)=>!ot(r)||!wt(r,["fieldId","direction"])||!o(r.fieldId)||!["asc","desc"].includes(String(r.direction)))))return!1;return!0}import{createContext as Li,useCallback as Oi,useContext as Vi,useLayoutEffect as nr,useMemo as _i,useRef as Qr,useState as Bi}from"react";var Ui=Li(void 0);function _t(e,t={}){let n=Vi(Ui),i=Qr({}),{dirty:o,busy:r}=e,{onDirtyChange:a,onBusyChange:d}=t;nr(()=>{n?.(i.current,{dirty:o,busy:r}),a?.(o),d?.(r)},[n,o,r,a,d]),nr(()=>()=>{n?.(i.current),a?.(!1),d?.(!1)},[n,a,d])}function Rc(){let e=Qr(new Map),[t,n]=Bi({dirty:!1,busy:!1}),i=Oi((o,r)=>{if(r)e.current.set(o,r);else e.current.delete(o);let a=[...e.current.values()],d=a.some((c)=>c.dirty),s=a.some((c)=>c.busy);n((c)=>c.dirty===d&&c.busy===s?c:{dirty:d,busy:s})},[]);return{...t,report:i}}function kn(e,t){let n=_i(()=>({active:!0,client:e,id:t}),[e,t]);return nr(()=>(n.active=!0,()=>{n.active=!1}),[n]),n}import{useEffect as Un,useRef as Gt,useState as $e}from"react";import{useId as Ma,useMemo as La,useState as pr}from"react";var Ge=(e)=>String(e).padStart(2,"0"),qi=(e)=>e.type==="date"||e.type==="formula"&&e.resultType==="date";function Me(e){let t=e.formatting;return qi(e)&&t&&"date"in t?t:void 0}function Pn(e){let t=e.formatting;return e.type==="number"&&t&&"kind"in t?t:void 0}function Xr(e){let t=Me(e);return!t?"auto":t.time==="none"?"date":"datetime"}function rr(e,t,n,i){switch(i){case"YYYY/MM/DD":return`${e}/${Ge(t)}/${Ge(n)}`;case"MM/DD/YYYY":return`${Ge(t)}/${Ge(n)}/${e}`;case"DD/MM/YYYY":return`${Ge(n)}/${Ge(t)}/${e}`;case"YYYY年M月D日":return`${e}年${t}月${n}日`;default:return`${e}-${Ge(t)}-${Ge(n)}`}}function Bt(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 rr(Number(i[1]),Number(i[2]),Number(i[3]),t.date);let d=new Date(n);if(!Number.isFinite(d.getTime()))return n;let s=Xe(d,t.timeZone??"UTC");return rr(s.year,s.month,s.day,t.date)}let o=i?kt({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=Xe(o,t.timeZone),a=rr(r.year,r.month,r.day,t.date);if(t.time==="12h"){let d=r.hour%12||12;return`${a} ${d}:${Ge(r.minute)} ${r.hour<12?"AM":"PM"}`}return`${a} ${Ge(r.hour)}:${Ge(r.minute)}`}function wn(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 Rn(e,t){let n=e?.findIndex((r)=>r.id===t)??-1,i=n>=0?e?.[n]?.color:void 0,o=Lt.findIndex((r)=>r===i);return o>=0?o:n}var eo={"Footer record count":"{count} records","Footer count":"Count","Footer filled":"Filled","Footer empty":"Empty","Footer sum":"Sum","Footer avg":"Average","Footer min":"Minimum","Footer max":"Maximum"},$i={"AI fill":"AI 填充","AI field":"AI 字段","Generate {name} with AI":"AI 生成「{name}」","Only records with empty target cells":"只处理目标为空的记录","No records have empty target cells.":"没有目标为空的记录。","AI settings of field {name}":"字段 {name} 的 AI 设置","Generate this field with AI":"用 AI 生成此字段","Generate when a record is created":"新建记录时自动生成","AI auto-fill stopped: {message}":"AI 自动生成中断:{message}",Hyperlink:"超链接","Search or paste a link":"搜索文档或粘贴链接","Use link {url}":"使用链接 {url}","Display text":"显示文字","Remove link":"移除链接","Link suggestions":"链接建议","Searching…":"搜索中…","No matching resources":"没有匹配的内容","{name} needs a link.":"{name}需要有效链接(http(s)、邮箱或站内路径)。","Link targets":"可选的链接目标","None chosen offers every kind.":"都不选则提供全部类型。","AI prompt":"AI 提示词","e.g. Summarize the description in one sentence":"例如:用一句话概括描述","Fields the AI reads (none = all)":"AI 读取的字段(不选则读取全部)","AI reads {name}":"AI 读取 {name}","All records in this view ({count})":"当前视图全部记录({count})","Generating batch {done} of {total}…":"正在生成第 {done}/{total} 批…","{count} records could not be processed: {reason}":"{count} 条记录处理失败:{reason}","Retry failed":"重试失败批次",Close:"关闭","Records in scope":"记录范围","Selected records ({count})":"已选记录({count})","Loaded records ({count})":"已载入记录({count})","Fields to fill":"要填充的字段",Instruction:"指令","Describe what to fill or change":"描述要填写或修改的内容","Fill empty cells":"补全空白","Fill the empty target cells using the other fields of the same record.":"根据同一条记录的其他字段,补全目标字段中的空白单元格。","Translate to English":"翻译成英文","Translate the target fields into English and keep proper nouns.":"把目标字段翻译成英文,专有名词保持原样。",Summarize:"生成摘要","Write a one-sentence summary of each record for the target fields.":"为每条记录在目标字段中写一句话摘要。",Classify:"自动归类","Pick the best matching option for each record from the allowed options.":"为每条记录从可选项中选择最匹配的一项。",Model:"模型",Suggestions:"建议","{count} suggested changes":"{count} 处建议修改","Select all":"全选","Select none":"全不选","No changes were suggested.":"没有需要修改的内容。","(empty)":"(空)","Generating suggestions…":"正在生成建议…",Stop:"停止","Apply {count} changes":"应用 {count} 处修改",Regenerate:"重新生成","Generate preview":"生成预览","Applied {count} AI changes":"已应用 {count} 处 AI 修改","AI changes undone":"已撤销 AI 修改",Undo:"撤销","Some records changed since the preview. Generate again to review the latest values.":"部分记录在预览后已被修改,请重新生成以查看最新内容。","Loaded records fallback: {value}":"已载入记录兜底:{value}","That summary function is not supported.":"不支持该汇总函数。","Average only a number field.":"只能对数字字段求平均值。","Minimum and maximum need a number or date field.":"最大值和最小值需要数字或日期字段。","Summarize a queryable field.":"请选择可查询字段汇总。","Select row":"选择行","Select all loaded records":"全选已载入记录","{count} selected":"已选择 {count} 条","Column color":"整列填色","Column color for {name}":"{name}整列填色","Column color {number}":"列色 {number}","No color":"无色","Fill selection":"拖拽填充","Fill at most 100 rows at once.":"一次最多 100 行","Filled {count} cells":"已填充 {count} 个单元格","Skipped {count} cells":"已跳过 {count} 个不可填充单元格","Table not found":"数据表不存在或不可访问","View not found":"视图不存在或不可访问","{count} records total":"共 {count} 条","Row height":"行高","Row height short":"紧凑","Row height medium":"中等","Row height tall":"较高","Row height extra":"超高","Sort {index}":"排序 {index}","Move sort {index} up":"上移排序 {index}","Move sort {index} down":"下移排序 {index}","Remove sort {index}":"删除排序 {index}","Add sort":"添加排序","Clear sort":"清除排序","Default order":"默认顺序",Match:"满足","all conditions":"全部条件","any condition":"任一条件","Filter conjunction":"条件关系","Condition {index}":"条件 {index}","Remove condition {index}":"删除条件 {index}","{count} grouped conditions are kept.":"另有 {count} 组嵌套条件保持不变。",Remove:"移除","Finish the highlighted condition to apply it.":"补全未完成的条件后才会生效。","Add condition":"添加条件","Add group":"添加条件组","Condition group {index}":"条件组 {index}","Remove group {index}":"删除条件组 {index}","Clear filter":"清除筛选","Filter value":"筛选值","Filter field":"筛选字段","Filter operator":"筛选条件","Date mode":"日期方式","From date":"起始日期","To date":"结束日期","Number of days":"天数","Choose option":"选择选项",Format:"格式","Format of field {name}":"字段{name}的格式","Defaults of field {name}":"字段{name}的默认值","Date format":"日期格式","Time format":"时间格式","Time zone":"时区","Viewer's time zone":"跟随查看者","No time (date only)":"不含时间(仅日期)","24-hour":"24 小时制","12-hour":"12 小时制",Preview:"预览","Default value":"默认值",Empty:"空","Current date and time":"当前日期和时间","Number style":"数字样式",Percent:"百分比",Currency:"货币","Decimal places":"小数位数","Thousands separator":"千分位分隔","Checked by default":"默认勾选","Default option {name}":"默认选中{name}","Colour of option {index}":"选项 {index} 的颜色","Colour blue":"蓝","Colour green":"绿","Colour red":"红","Colour orange":"橙","Colour gray":"灰","Colour teal":"青","Colour purple":"紫","Unsaved changes":"修改未保存","Your edit":"我的修改","Server value":"服务端当前值","Record ID":"记录 ID","Record ID {id}":"记录 ID {id}",Row:"序号","Generated automatically":"自动生成","{name} is auto-generated and cannot be edited.":"{name}由系统自动生成,不能手动修改。","Saving failed. Your edit has been kept.":"保存失败,修改已保留。",Saved:"已保存","Invalid value":"输入值无效","{name} is read-only; its original bytes are preserved.":"{name}为只读字段,原始文件内容保持不变。","{name} needs a server-provided option.":"{name}需要由服务端提供可选项。","{name} is read only.":"{name}为只读字段。","Use the {name} record picker.":"请使用{name}记录选择器。","{name} needs a number.":"{name}需要有效数字。","{name} needs valid JSON.":"{name}必须是有效 JSON。","{name} needs an integer.":"{name}必须是整数。","{name} needs true or false.":"{name}请选择是或否。","{name} needs a date.":"{name}需要有效日期。","{name} needs a valid calendar date.":"{name}需要有效日期。","{name} has no option '{option}'.":"{name}没有名为“{option}”的选项。","Paste is too large.":"粘贴内容过大。","Paste must fit within the loaded page and contain at most 100 rows.":"粘贴内容必须位于当前已加载页内,且最多包含 100 行。","Paste extends beyond the visible columns.":"粘贴内容超出可见列范围。","Row is not loaded.":"目标行尚未加载。","Unclosed quoted cell.":"粘贴内容中的引号没有闭合。","Invalid paste.":"粘贴内容无效。","Edit {name}":"编辑 {name}","{name} editor":"{name}编辑器","Sorting is unavailable for this field":"此字段暂不支持排序","Clear selection":"清空选择","{id} (unavailable)":"{id}(选项已移除)","Select at most 100 rows per delete.":"每次最多删除 100 条记录。","{total} records · {loaded} loaded":"共 {total} 条 · 已载入 {loaded} 条","Arrows · Shift select · Enter edit · Copy / paste":"方向键移动 · Shift 多选 · Enter 编辑 · 复制 / 粘贴","Arrows · Shift select · Copy":"方向键移动 · Shift 多选 · 复制","Delete selected rows":"删除所选记录","{name} records":"{name} 数据表","Resize {name}":"调整 {name} 列宽","Saving…":"保存中…","Save edit":"保存修改","Cancel edit":"取消修改","Confirm bulk change":"确认批量修改","Apply {count} row changes in one transaction?":"确认一次性提交 {count} 条记录的修改?","If any record changed or any value is invalid, all changes are rejected.":"如有记录版本冲突或输入值无效,整批修改将不提交。","Confirm changes":"确认修改","Cancel changes":"取消修改","Current server version {version}":"服务端当前版本 {version}","Retry against current version":"按当前版本重试","Saving failed. Your draft has been kept.":"保存失败,草稿已保留。","Choose a text, checkbox or single select grouping field.":"请选择文本、复选框或单选字段作为看板分组。",Ungrouped:"未分组","Invalid grouping value":"分组值无效","Move {name}":"移动 {name}","Retry change":"重试修改","{name} is required.":"请填写 {name}。","No changes":"没有修改","{name} record":"{name} 记录","No value":"未选择",Yes:"是",No:"否","Save record":"保存记录","Create record":"新建记录","Search {name}":"搜索 {name}","No relation":"未关联","More {name} options":"加载更多 {name} 选项","Relation options unavailable.":"关联选项加载失败,请重试。","Relation option provider unavailable.":"暂时无法选择关联记录。","Collection query failed. Retry to load records.":"记录加载失败,请重试。","Previous page":"上一页","Next page":"下一页","Page {page}":"第 {page} 页","Loading records…":"正在加载记录…","Retry query":"重新加载","Saving failed. Your change has been kept.":"保存失败,已保留当前修改。","{name} needs unique linked records.":"{name}需要不重复的关联记录。","Change a field before saving.":"请先修改字段再保存。","Close record":"关闭记录","Delete record":"删除记录","Confirm record deletion":"确认删除记录","Delete this record? Your unsaved changes will be discarded after deletion.":"确定删除此记录?删除后将丢弃尚未保存的修改。","Confirm deletion":"确认删除","Cancel deletion":"取消删除","Record creation requires editor permission.":"新建记录需要编辑权限。","Creating…":"正在创建…","Record created.":"记录已创建。","Record created. Add another below.":"记录已创建,可继续新增。","Show records":"查看记录","Pending record move":"待处理的记录移动","Moving record…":"正在移动记录…","The move has been kept for retry.":"已保留移动请求,可重试。","Retry move":"重试移动","Cancel move":"取消移动","Choose a single-select or boolean grouping field.":"请选择单选或复选框分组字段。","Lane {name}":"分组{name}","Open {name}":"打开{name}","Move to":"移动至","No records in this lane.":"此分组暂无记录。","No records match this view.":"此视图暂无匹配记录。",Unassigned:"未分组","Choose a valid month.":"请选择有效月份。","Invalid initial month. Showing the current UTC month.":"初始月份无效,已显示当前月份。","Choose a valid month between years 1 and 9998.":"请选择 1 至 9998 年之间的有效月份。","Invalid date":"日期无效","Choose a date field for this calendar.":"请为日历选择日期字段。","Previous month":"上个月","Next month":"下个月",Today:"今天","Calendar month":"日历月份",Month:"月份","{year}-{month}":"{year} 年 {month} 月",Sun:"周日",Mon:"周一",Tue:"周二",Wed:"周三",Thu:"周四",Fri:"周五",Sat:"周六","Day {day}":"日期 {day}","No dated records match this month.":"本月暂无匹配的日期记录。","Move {name} to date":"将 {name} 移动至日期",Move:"移动",Grid:"表格",Kanban:"看板",Gallery:"画廊",Calendar:"日历",Form:"表单","View type":"视图类型","Group by":"分组依据","Grid grouping field":"表格分组字段","No grouping":"不分组","Hide fields":"隐藏字段","Field menu {name}":"{name} 字段菜单","Edit field":"修改字段","Field saved":"字段已保存","Field added":"字段已添加","Edit all fields":"批量编辑字段","Save field":"保存","Field name is required.":"请填写字段名。","Duplicate field":"复制字段","Hide field":"隐藏字段","Undo/redo recovery":"撤销/重做恢复","Retry undo/redo":"重试撤销/重做","Clear undo/redo history":"清除撤销/重做历史",Undone:"已撤销",Redone:"已重做","Duplicate {count} selected records":"复制所选 {count} 条记录","Add record below the table":"在表格末尾新增记录","Move to {name}":"移至 {name}","Delete this record?":"删除这条记录?","Filter by {name}":"按 {name} 筛选","Record details":"记录详情","Expand record":"展开记录","Select all rows":"全选记录",Summary:"统计","Auto summary":"自动计算","Footer record count":"{count} 条记录","No summary":"不统计","Footer count":"记录数","Footer filled":"已填写","Footer empty":"未填写","Footer sum":"求和","Footer avg":"平均值","Footer min":"最小值","Footer max":"最大值","Summaries cover the {count} loaded records.":"统计范围为已载入的 {count} 条记录。","Freeze up to this field":"冻结至此字段","Unfreeze columns":"取消冻结","Insert field left":"向左插入字段","Insert field right":"向右插入字段","Sort {name} ascending":"按 {name} 升序","Sort {name} descending":"按 {name} 降序","Group by {name}":"按 {name} 分组","Ungroup by {name}":"取消按 {name} 分组","Create kanban by {name}":"按 {name} 创建看板","Delete field “{name}”?":"删除字段“{name}”?","The field and its values in every record are removed. This cannot be undone.":"该字段及其在所有记录中的值都会被删除,且无法恢复。","Field duplicated":"已复制字段","Field deleted":"已删除字段","Deleted {count} records":"已删除 {count} 条记录","Delete {count} records?":"删除 {count} 条记录?","The selected records will be deleted. If any of them changed meanwhile, nothing is deleted.":"所选记录将被删除。若其中任一条记录已被他人修改,则整体取消、不会删除任何记录。","Search fields":"搜索字段","Reorder {name}":"拖动或按上下方向键调整 {name} 的顺序","No matching fields":"没有匹配的字段","Edit field {name}":"编辑字段 {name}","Field config":"字段配置","View config":"视图配置","{count} hidden fields":"已隐藏 {count} 个字段",Filter:"筛选",Group:"分组",Sort:"排序","{count} sorts":"{count} 项排序","Add grouping":"添加分组","Remove grouping":"移除分组","Hide {name}":"隐藏{name}","Show {name}":"显示{name}","Kanban grouping field":"看板分组字段","Date field":"日期字段","Calendar date field":"日历日期字段","Linked records are unavailable. Ask the host to connect this collection.":"关联记录不可用,请确认表格已连接。","Linked records could not be loaded. Retry to keep editing.":"关联记录加载失败,请重试后继续编辑。","{name} linked records":"{name}关联记录","Remove {name}":"移除 {name}","Search {name} records":"搜索 {name} 记录","Search linked records":"搜索关联记录","Loading linked records…":"加载关联记录…","Retry linked records":"重试加载关联记录","Link {name}":"关联 {name}","No matching records.":"没有匹配记录。","Previous linked records":"上一页关联记录","Next linked records":"下一页关联记录","{count} selected · up to 100 per record across all link fields":"已选择 {count} 项 · 每条记录的所有关联字段合计最多 100 项","{name} (read only)":"{name}(只读)","Choose…":"请选择…","Division by zero":"除数不能为零","Invalid computed value":"计算值无效","Computed value overflow":"计算值超出范围","Dependency failed":"依赖字段计算失败",Views:"视图","Add view":"添加视图","Rename view":"重命名视图","Duplicate view":"复制视图","Delete view":"删除视图","View name":"视图名称","View actions":"视图操作","Double click to rename":"双击重命名","Record actions":"记录操作","Copy cells":"复制所选单元格","Delete {count} selected records":"删除所选 {count} 条记录","Not set":"未设置",Checked:"已勾选",Unchecked:"未勾选","Expand group {name}":"展开分组 {name}","Collapse group {name}":"折叠分组 {name}","{count} records":"{count} 条","Collection fields":"表格字段","Field {name}":"字段 {name}","Field name":"字段名","Field description":"字段说明","Field type":"字段类型",Required:"必填","Delete field":"删除字段","Delete field {name}":"删除字段「{name}」","Options of field {name}":"字段 {name} 的选项",Options:"选项","Option name {index}":"选项名称 {index}","Delete option {index}":"删除选项 {index}",Delete:"删除","Add option":"新增选项","Add field":"新增字段","New field":"新字段","New option":"新选项","Single line text":"单行文本","Long text":"长文本",Number:"数字",Checkbox:"复选框",Date:"日期","Single select":"单选","Multiple select":"多选","Filter applied":"已应用筛选","Sort field":"排序字段","Sort direction":"排序方向",Default:"默认",Ascending:"升序",Descending:"降序",Columns:"列设置","Show row numbers":"显示行号","Show record IDs":"显示记录 ID","Move {name} left":"移动{name}到左侧","Move {name} right":"移动{name}到右侧",Tables:"数据表","New table":"新建数据表","Change table icon":"修改数据表图标","Table icon":"数据表图标","Double click to change the icon":"双击修改图标","Schema permission required":"需要数据结构管理权限","Table name":"数据表名称","Rename table {name}":"重命名数据表 {name}","Start with a table":"从一张数据表开始","{count} fields · {mode}":"{count} 个字段 · {mode}",Editable:"可编辑","Read only":"只读",Table:"表格",People:"人员",Business:"业务",List:"清单",Schedule:"日程",Inventory:"库存","Choose a table first.":"请先选择数据表。","Save view":"保存视图",Done:"完成","View settings":"视图设置","Save fields":"保存字段",Cancel:"取消",Refresh:"刷新","Search records":"搜索记录",Search:"搜索",Fields:"字段","Add record":"新增记录","Unsaved view changes":"视图设置未保存","Delete view “{name}”?":"删除视图「{name}」?","Reload records":"重新加载记录","Reload permissions":"重新加载权限","Loading…":"加载中…","{name} copy":"{name} 副本",Name:"名称","New grid view":"新网格视图","New kanban view":"新看板视图","New gallery view":"新画廊视图","New calendar view":"新日历视图","New form view":"新表单视图","Create table":"创建数据表","Sum field":"求和字段","No sum":"不求和","Linked record":"关联记录","Related table":"关联数据表","Choose a related table":"选择关联表",Relations:"关联","{name} · inverse records":"{name} · 反向记录","No tables yet":"还没有数据表","All records":"全部记录","Loading summary…":"正在汇总…","No summary rows.":"没有汇总数据","The collection service is unavailable.":"数据服务暂不可用","You do not have permission to make this change.":"你没有权限进行此修改。","You do not have permission to view this data.":"你没有权限查看此数据。","Sign in to view this data.":"请登录后查看此数据。","This data is missing or inaccessible.":"此数据不存在或无法访问。","This record has changed. Review the current version.":"记录已被修改,请核对当前版本。",none:"无","Choose a count or sum.":"请选择计数或求和。","Use at most three groups and eight summaries.":"最多使用三个分组和八项汇总。","That field is not in this collection.":"该字段不在此数据表中。","Group by a text, number, date, checkbox, or single select field.":"请按文本、数字、日期、复选框或单选字段分组。","Sum only a number field.":"只能对数字字段求和。","Count a queryable field, or omit the field to count records.":"请统计可查询字段,或不选字段以统计记录数。","Each summary needs its own name, different from the group fields.":"每项汇总需要独立名称,且不能与分组字段重名。","Each group field can be used once.":"每个分组字段只能使用一次。",Records:"记录数","Sum of {name}":"{name}合计","Discard unsaved changes?":"放弃未保存的更改?",Discard:"放弃更改","Keep editing":"继续编辑","View deleted":"视图已删除","View saved":"视图已保存","Fields saved":"字段已保存","Record saved":"记录已保存","Record saved, keep adding":"记录已保存,可继续新增","New record form":"新增记录表单",Save:"保存","Save new record":"保存新记录","Save and continue":"保存并继续","Cancel adding":"取消新增","Clear current filter":"清除当前筛选","Configure fields":"配置字段","Table title":"表格标题","{count} filters":"{count} 项筛选","Cancel field settings":"取消字段设置","Only this view's filters, sort and layout are removed; no records are deleted.":"只删除这个视图的筛选、排序和布局设置,不会删除任何记录。","Expand all groups before pasting.":"请先展开所有分组再粘贴。"};function j(e="en"){return(t,n={})=>(e==="zh-CN"?$i[t]??t:Object.hasOwn(eo,t)?eo[t]??t:t).replace(/\{(\w+)\}/g,(i,o)=>String(n[o]??i))}var to={permission_denied:"You do not have permission to make this change.",version_conflict:"This record has changed. Review the current version.",unavailable:"The collection service is unavailable."};function Sn(e,t="en"){if(t!=="zh-CN"||!Object.hasOwn(to,e.code))return e.message;let n=to[e.code];return n?j(t)(n):e.message}function no({code:e,message:t},n="en"){if(n!=="zh-CN")return t;let i=j(n);switch(e){case"permission_denied":return i("You do not have permission to view this data.");case"unauthorized":return i("Sign in to view this data.");case"not_found":return i("This data is missing or inaccessible.");case"unavailable":return i("The collection service is unavailable.");default:return t}}function Nc(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 d=Math.max(0,Math.min(n*i-1,r*i+a+(o?-1:1)));r=Math.floor(d/i),a=d%i}return{row:Math.max(0,Math.min(n-1,r)),column:Math.max(0,Math.min(i-1,a))}}function ji(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 Je(e){if(e==null)return"";if(Array.isArray(e))return e.join(",");if(typeof e==="object")return JSON.stringify(e);return String(e)}function Mc(e,t,n,i){let o=ji(n,i),r=[];for(let a=o.firstRow;a<=o.lastRow;a++){let d=[];for(let s=o.firstColumn;s<=o.lastColumn;s++){let c=t[s],u=e[a]?.values[c?.id??""],m=c?.type==="json"&&u!=null?JSON.stringify(u):c?.type==="hyperlink"?Kr(u):Je(u);d.push(/[\t\r\n"]/.test(m)?`"${m.replaceAll('"','""')}"`:m)}r.push(d.join("\t"))}return r.join(`
|
|
2
|
+
`)}function zi(e,t="en"){let n=j(t),i=[],o=[],r="",a=!1;for(let d=0;d<e.length;d++){let s=e[d];if(s==='"'&&(a||r===""))if(a&&e[d+1]==='"')r+='"',d++;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[d+1]===`
|
|
4
|
+
`)d++}}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 ct(e,t,n="en"){let i=j(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=Pt(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=Me(t);if(r){let R=/^(\d{4})-(\d{2})-(\d{2})(?:T.*)?$/.exec(e);if(!R)throw Error(i("{name} needs a date.",{name:t.name}));let[,k,A,E]=R,T=new Date(Date.UTC(Number(k),Number(A)-1,Number(E)));if(T.getUTCMonth()!==Number(A)-1||T.getUTCDate()!==Number(E))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 hn(new Date(e),r.timeZone);return`${k}-${A}-${E}`}if(/^\d{4}-\d{2}-\d{2}$/.test(e))return kt({year:Number(k),month:Number(A),day:Number(E)},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[,d,s,c,u,m,p,l,C]=a,b=Number(d),y=Number(s),g=Number(c),f=[31,b%4===0&&(b%100!==0||b%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];if(y<1||y>12||g<1||g>(f[y-1]??0)||Number(u??0)>23||Number(m??0)>59||Number(p??0)>59||Number(l??0)>23||Number(C??0)>59)throw Error(i("{name} needs a valid calendar date.",{name:t.name}));let S=new Date(e);if(!Number.isFinite(S.getTime()))throw Error(i("{name} needs a date.",{name:t.name}));return S.toISOString()}let o=(r)=>{let a=t.options?.find((d)=>d.id===r||d.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 Lc(e,t,n,i,o="en"){let r=j(o);try{if(e.length>1048576)throw Error(r("Paste is too large."));let a=zi(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,c)=>{if(i.column+s.length>n.length)throw Error(r("Paste extends beyond the visible columns."));let u=t[i.row+c];if(!u)throw Error(r("Row is not loaded."));let m={};return s.forEach((p,l)=>{let C=n[i.column+l];if(C?.generation==="autoIncrement")throw Error(r("{name} is auto-generated and cannot be edited.",{name:C.name}));if(C)m[C.id]=ct(p,C,o)}),{op:"update",id:u.id,expectedVersion:u.version,values:m}})}}catch(a){return{ok:!1,message:a instanceof Error?a.message:r("Invalid paste.")}}}function ro(e,t){let n=Je(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=(c)=>o.find((u)=>u.type===c)?.value??"",a=i.getUTCMilliseconds(),d=r("second"),s=d!=="00"||a?`:${d}${a?`.${String(a).padStart(3,"0")}`:""}`:"";return`${r("year")}-${r("month")}-${r("day")} ${r("hour")}:${r("minute")}${s}`}import{useEffect as Hi,useRef as Ki,useState as Ut}from"react";import{jsx as Ze,jsxs as sn}from"react/jsx-runtime";function qt(e){if(e==null)return"—";if(Array.isArray(e))return e.map(qt).join(", ");return String(e)}function ln(e,t){let n=e.linkedRecords?.[t.id];return(n?.length?n.map((i)=>i.label||i.id).join(", "):void 0)??qt(e.values[t.id])}function Uc(e,t){return Je(e.values[t.id])}function oo({field:e,value:t,labels:n=[],client:i,onChange:o,disabled:r=!1,locale:a,"aria-describedby":d,"aria-invalid":s}){let c=j(a),u=Array.isArray(t)?t.filter((h)=>typeof h==="string"):[],m=Ki(new Set(u));m.current=new Set(u);let[p,l]=Ut(""),[C,b]=Ut(),[y,g]=Ut([]),[v,f]=Ut(0),[S,R]=Ut({}),[k,A]=Ut({rows:[],next:null,error:"",loading:!0}),E=e.link?.collectionId,T=e.link?.displayFieldId;Hi(()=>{let h=!0;if(A({rows:[],next:null,error:"",loading:!0}),!i||!E||!T){A({rows:[],next:null,error:c("Linked records are unavailable. Ask the host to connect this collection."),loading:!1});return}return i.query(E,{limit:50,search:p,...C?{cursor:C}:{}}).then((x)=>{if(!h)return;if(!x.ok){A({rows:[],next:null,error:x.error.message,loading:!1});return}R((I)=>({...Object.fromEntries(Object.entries(I).filter(([D])=>m.current.has(D))),...Object.fromEntries(x.data.items.map((D)=>{let O=String(D.values[T]??"");return[D.id,O.trim()?O.slice(0,256):D.id]}))})),A({rows:x.data.items,next:x.data.nextCursor,error:"",loading:!1})}).catch(()=>{if(h)A({rows:[],next:null,error:c("Linked records could not be loaded. Retry to keep editing."),loading:!1})}),()=>{h=!1}},[i,E,T,p,C,v]);let V=(h)=>S[h]??n.find((x)=>x.id===h)?.label??h;return sn("fieldset",{disabled:r,"aria-label":c("{name} linked records",{name:e.name}),...d?{"aria-describedby":d}:{},...s?{"aria-invalid":!0}:{},className:"flex min-w-0 flex-col gap-2 rounded-md border p-2",children:[Ze("div",{className:"flex flex-wrap gap-1",children:u.map((h)=>sn("span",{className:"rounded border px-2 py-1 text-sm",children:[V(h)," ",Ze("button",{type:"button","aria-label":c("Remove {name}",{name:V(h)}),onClick:()=>o(u.filter((x)=>x!==h)),children:"×"})]},h))}),Ze("input",{"aria-label":c("Search {name} records",{name:e.name}),type:"search",placeholder:c("Search linked records"),value:p,onChange:(h)=>{l(h.target.value),b(void 0),g([])}}),k.loading&&Ze("p",{role:"status",children:c("Loading linked records…")}),k.error&&sn("div",{role:"alert",children:[k.error," ",Ze("button",{type:"button",onClick:()=>f((h)=>h+1),children:c("Retry linked records")})]}),Ze("div",{className:"flex max-h-48 flex-col gap-1 overflow-auto",children:k.rows.map((h)=>sn("label",{className:"flex items-center gap-2 text-sm",children:[Ze("input",{type:"checkbox","aria-label":c("Link {name}",{name:V(h.id)}),checked:u.includes(h.id),disabled:!u.includes(h.id)&&u.length>=100,onChange:(x)=>o(x.target.checked?[...u,h.id]:u.filter((I)=>I!==h.id))}),V(h.id)]},h.id))}),!k.loading&&!k.error&&!k.rows.length&&Ze("p",{children:c("No matching records.")}),sn("div",{className:"flex gap-2",children:[Ze("button",{type:"button",disabled:!y.length||k.loading,onClick:()=>{b(y.at(-1)),g((h)=>h.slice(0,-1))},children:c("Previous linked records")}),Ze("button",{type:"button",disabled:!k.next||k.loading,onClick:()=>{g((h)=>[...h,C]),b(k.next??void 0)},children:c("Next linked records")})]}),Ze("small",{children:c("{count} selected · up to 100 per record across all link fields",{count:u.length})})]})}var Wi={division_by_zero:"Division by zero",invalid_value:"Invalid computed value",overflow:"Computed value overflow",dependency_error:"Dependency failed"};function In(e,t,n){return t?j(n)(Wi[t]):e==null?"—":String(e)}function io(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 ao(...e){return{conjunction:"and",filterSet:e.filter((n)=>n!==void 0)}}function An(e){return{limit:50,search:e.search??"",...e.filter?{filter:e.filter}:{},sort:e.sort??[]}}function so(e,t,n){let i=n.value===null?{fieldId:t.id,operator:"isEmpty"}:{fieldId:t.id,operator:"is",value:n.value};return{...An(e),filter:ao(e.filter,i)}}function dn(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 lo(e,t,n){let{start:i,end:o}=dn(n);return{...An(e),filter:ao(e.filter,{fieldId:t,operator:"onOrAfter",value:i},{fieldId:t,operator:"before",value:o})}}function Dn(e,t){let n={id:"date",name:"Date",type:"date"},i=String(ct(t,n)),o=String(ct(String(e),n));return`${i.slice(0,10)}${o.slice(10)}`}function ut(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 ze(e,t){let n=t.find((i)=>i.type==="singleLineText"||i.type==="longText");return(n?Je(e.values[n.id]):"")||e.id}function $t(e,t,n){if(t.type==="lookup")return qt(e);if(t.type==="hyperlink")return on(e);if(t.type==="date"){let i=Me(t);return i?Bt(e,i):ro(e)}if(t.type==="number"){let i=Pn(t);return i?wn(e,i):Je(e)}if(t.type==="checkbox")return e===!0?"✓":"";if(t.type==="formula"||t.type==="rollup")return In(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 Je(e)}import{useEffect as or,useMemo as Yi,useState as St}from"react";import{jsx as jt,jsxs as co}from"react/jsx-runtime";function En(e,t){if(!t?.length)return e;let n=!1,i={...e};for(let o of t){let r=o.label.trim();if(!r||i[o.id]===r)continue;i[o.id]=r,n=!0}return n?i:e}function Tn(e){let t=Yi(()=>j(e.locale),[e.locale]),[n,i]=St(""),[o,r]=St(),[a,d]=St(null),[s,c]=St([]),[u,m]=St(()=>En({},e.labels)),[p,l]=St(""),[C,b]=St(!1),y=e.field.relation?.collectionId,g=e.field.relation?.labelFieldId,{getOptions:v,value:f}=e;or(()=>{m((k)=>En(k,e.labels))},[e.labels]),or(()=>{let k=!1;if(!y||!v)return;return b(!0),l(""),v({collectionId:y,...g?{labelFieldId:g}:{},search:n,...o?{cursor:o}:{},limit:50}).then((A)=>{if(k)return;if(!A.ok){l(A.error.message),d(null);return}let E=A.data.items.slice(0,50);m((T)=>En(T,E)),c((T)=>{let V=o?[...T,...E]:E;return[...new Map(V.map((h)=>[h.id,h])).values()]}),d(A.data.nextCursor)}).catch(()=>{if(!k)l(t("Relation options unavailable."))}).finally(()=>{if(!k)b(!1)}),()=>{k=!0}},[y,g,n,o,v,t]),or(()=>{if(!f||!y||!v)return;if(e.labels?.some((A)=>A.id===f&&A.label.trim()))return;let k=!1;return v({collectionId:y,...g?{labelFieldId:g}:{},ids:[f],limit:50}).then((A)=>{if(k||!A.ok)return;let E=A.data.items.find((T)=>T.id===f);if(E)m((T)=>En(T,[E]))}).catch(()=>{}),()=>{k=!0}},[f,y,g,v,e.labels]);let S=!y||!v,R=f?u[f]??s.find((k)=>k.id===f)?.label??f:"";return co("div",{children:[jt("input",{"aria-label":t("Search {name}",{name:e.field.name}),value:n,disabled:e.disabled||S,onKeyDown:(k)=>{if(k.key==="Enter"&&!k.ctrlKey&&!k.metaKey)k.preventDefault()},onChange:(k)=>{i(k.currentTarget.value),r(void 0),c([]),d(null)}}),co("select",{id:e.id,"aria-describedby":e["aria-describedby"],"aria-invalid":e["aria-invalid"],"aria-label":e.label??e.field.name,value:e.value,disabled:e.disabled||S||C,onChange:(k)=>{let A=k.currentTarget.value;if(!A||s.some((E)=>E.id===A))e.onChange(A)},children:[jt("option",{value:"",children:t("No relation")}),f&&!s.some((k)=>k.id===f)&&jt("option",{value:f,children:R}),s.map((k)=>jt("option",{value:k.id,children:k.label},k.id))]}),a&&jt("button",{type:"button",disabled:C||e.disabled,onClick:()=>r(a),children:t("More {name} options",{name:e.field.name})}),(p||S)&&jt("span",{role:"status",children:p||t("Relation option provider unavailable.")})]})}var uo=(e)=>e.type==="singleLineText"||e.type==="longText",po=(e)=>{let n=e.name.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9一-鿿]+/g,"_");return/(?:^|_)(?:id|uuid)$/.test(n)||n==="recordid"},go=(e)=>{let t=e.toLowerCase().replace(/[\s_-]+/g,"");if(/^(name|名称|姓名|客户名称|公司名称|标题|title|label|displayname)$/.test(t))return 0;if(/(名称|姓名|标题|name|title|label)/.test(t))return 1;return 2};function Gi(e,t){let n=e?.fields??[],i=n.find((r)=>r.id===t),o=n.filter((r)=>uo(r)&&!po(r)).sort((r,a)=>go(r.name)-go(a.name));return[...i&&uo(i)&&!po(i)?[i]:[],...o].filter((r,a,d)=>d.findIndex((s)=>s.id===r.id)===a)}function Ji(e){if(!e?.length)return;let t=[...new Set(e.filter((n)=>n!==""))].slice(0,50);return t.length?t:void 0}function mo(e,t){return async(n)=>{let i=Ji(n.ids),o=await e.query(n.collectionId,{...i?{ids:i}:n.search?{search:n.search}:{},...!i&&n.cursor?{cursor:n.cursor}:{},limit:Math.min(50,n.limit)});if(!o.ok)return o;let r=Gi((typeof t==="function"?t():t).find((a)=>a.id===n.collectionId),n.labelFieldId);return{ok:!0,data:{items:o.data.items.map((a)=>{let d=r.map((s)=>a.values[s.id]).find((s)=>s!==null&&s!==void 0&&String(s).trim()!=="");return{id:a.id,label:d===void 0?a.id:String(d)}}),nextCursor:o.data.nextCursor}}}}import{createContext as Zi,useContext as Qi,useEffect as Xi,useId as ea,useLayoutEffect as ta,useMemo as na,useRef as ra,useState as zt}from"react";import{jsx as He,jsxs as Ht}from"react/jsx-runtime";var yo=Zi(void 0);function iu(e){return He(yo.Provider,{value:e.client,children:e.children})}var Fn=()=>Qi(yo),fo=(e)=>/^https?:/i.test(e);function oa(e){let t=Fn();if(!Ot(e.value))return null;let n=e.value,i=t?.href?.(n)??n.url;return He("a",{href:i,title:n.url,"data-uibot-link":n.ref?.kind??(fo(i)?"external":"internal"),...fo(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:on(n)})}var cn=(e)=>e?JSON.stringify(e):"",ia=(e)=>e.trim().startsWith("{")?Pt(e):null;function Nn(e){let t=na(()=>j(e.locale),[e.locale]),n=Fn(),i=ea(),o=ia(e.text),[r,a]=zt(()=>o?"":e.text),[d,s]=zt(!1),[c,u]=zt([]),[m,p]=zt(""),[l,C]=zt(-1),b=ra(null),[y,g]=zt(null),f=e.field.hyperlink?.kinds?.join(",")??"";Xi(()=>{if(!n||!d||e.disabled)return;let h=new AbortController,x=setTimeout(()=>{p(t("Searching…")),n.search({search:r.trim(),...f?{kinds:f.split(",")}:{},limit:8},{signal:h.signal}).then((I)=>{if(h.signal.aborted)return;u(I.ok?I.data.slice(0,8):[]),p(I.ok?"":I.error.message)}).catch((I)=>{if(!h.signal.aborted)p(I instanceof Error?I.message:String(I))})},200);return()=>{clearTimeout(x),h.abort()}},[n,d,r,f,e.disabled,t]);let S=Pt(r),R=(h)=>n?.kinds?.find((x)=>x.id===h)?.label??h,k=[...S&&!S.ref?[{key:"typed",value:S,title:t("Use link {url}",{url:S.url})}]:[],...c.map((h)=>({key:`${h.kind}:${h.id}`,value:{url:h.url,text:h.title,ref:{kind:h.kind,id:h.id}},title:h.title,subtitle:[R(h.kind),h.subtitle].filter(Boolean).join(" · ")}))],A=Boolean(n&&!m&&!c.length&&r.trim()),E=d&&!e.disabled&&(k.length>0||Boolean(m)||A);ta(()=>{if(!E)return;let h=()=>g(b.current?.getBoundingClientRect()??null);return h(),window.addEventListener("scroll",h,!0),window.addEventListener("resize",h),()=>{window.removeEventListener("scroll",h,!0),window.removeEventListener("resize",h)}},[E]);let T=(h)=>{a(""),C(-1),e.onChange(cn(h.value))},V=(h)=>{a(h),C(-1),e.onChange(h||cn(o))};return Ht("div",{style:{display:"grid",gap:4,minWidth:0,height:"100%"},children:[He("input",{ref:b,id:e.id,role:"combobox","aria-label":e.ariaLabel,"aria-expanded":E,"aria-controls":i,"aria-autocomplete":"list","aria-invalid":e.invalid,...e.describedBy?{"aria-describedby":e.describedBy}:{},...l>=0?{"aria-activedescendant":`${i}-${l}`}:{},disabled:e.disabled,placeholder:o?on(o):t("Search or paste a link"),value:r,style:e.inputStyle,className:e.inputClassName,onFocus:()=>s(!0),onBlur:()=>s(!1),onChange:(h)=>V(h.currentTarget.value),onKeyDown:(h)=>{if(e.onSave||e.onCancel)h.stopPropagation();if(h.key==="ArrowDown"||h.key==="ArrowUp"){if(!k.length)return;h.preventDefault();let x=h.key==="ArrowDown"?1:-1;C((I)=>x>0?(I+1)%k.length:I<=0?k.length-1:I-1)}else if(h.key==="Enter"){h.preventDefault();let x=k[l];if(x)T(x);else e.onSave?.()}else if(h.key==="Tab"&&e.onSave)h.preventDefault(),e.onSave();else if(h.key==="Escape")if(h.preventDefault(),r)V("");else e.onCancel?.()}}),o&&!r&&!e.onSave&&Ht("div",{style:{display:"grid",gap:4,minWidth:0,fontSize:12},children:[Ht("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[He(oa,{value:o,style:{flex:"0 1 auto"}}),He("span",{style:{flex:"1 1 0",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:0.6},children:o.url}),He("button",{type:"button","aria-label":t("Remove link"),title:t("Remove link"),disabled:e.disabled,onMouseDown:(h)=>h.preventDefault(),onClick:()=>e.onChange(""),style:{border:0,background:"none",color:"inherit",cursor:"pointer",opacity:0.6},children:"×"})]}),Ht("label",{style:{display:"grid",gap:2},children:[He("span",{style:{opacity:0.7},children:t("Display text")}),He("input",{"aria-label":t("Display text"),placeholder:o.url,value:o.text??"",disabled:e.disabled,className:e.inputClassName,onChange:(h)=>{let x=h.currentTarget.value.slice(0,500),{text:I,...D}=o;e.onChange(cn(x?{...D,text:x}:D))}})]})]}),E&&y&&Ht("div",{id:i,role:"listbox","aria-label":t("Link suggestions"),style:{position:"fixed",top:y.bottom+4,left:y.left,width:Math.max(y.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:(h)=>h.preventDefault(),children:[k.map((h,x)=>Ht("div",{id:`${i}-${x}`,role:"option","aria-selected":x===l,tabIndex:-1,onMouseEnter:()=>C(x),onClick:()=>T(h),onKeyDown:()=>{},style:{display:"grid",gap:2,padding:"6px 8px",borderRadius:6,cursor:"pointer",background:x===l?"var(--uibot-hover, rgb(0 0 0 / 0.06))":void 0},children:[He("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:h.title}),h.subtitle&&He("span",{style:{fontSize:12,opacity:0.65},children:h.subtitle})]},h.key)),m&&He("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:m}),A&&He("div",{role:"status",style:{padding:"6px 8px",fontSize:12,opacity:0.65},children:t("No matching resources")})]})]})}import{useEffect as vo,useId as sa,useMemo as la,useRef as da,useState as xo}from"react";var aa=/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/i;function pt(e){return aa.test(e)}var it=(e)=>String(e).padStart(2,"0");function bo(e){let t=new Date(e);if(!Number.isFinite(t.getTime()))return"";return`${t.getFullYear()}-${it(t.getMonth()+1)}-${it(t.getDate())}T${it(t.getHours())}:${it(t.getMinutes())}:${it(t.getSeconds())}.${String(t.getMilliseconds()).padStart(3,"0")}`}var ir=(e,t)=>{let n=Xe(e,t);return`${n.year}-${it(n.month)}-${it(n.day)}T${it(n.hour)}:${it(n.minute)}`};function ho(e,t={kind:"auto"}){if(!e)return"";if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(e))return"";if(t.kind==="date"){if(!pt(e))return e.slice(0,10);return ir(new Date(e),t.timeZone??"UTC").slice(0,10)}if(pt(e))return ir(new Date(e),t.timeZone);return t.kind==="datetime"?`${e.slice(0,10)}T00:00`:e.slice(0,10)}function Co(e,t,n={kind:"auto"}){if(!e)return"";if(n.kind==="date")return e.slice(0,10);if(!(n.kind==="datetime"||e.length>10||pt(t)))return e;let o=e.length>10?e.slice(11,16):t&&pt(t)?ir(new Date(t),n.timeZone).slice(11,16):"00:00",[r,a,d]=e.slice(0,10).split("-").map(Number),[s,c]=o.split(":").map(Number),u=kt({year:r??0,month:a??1,day:d??1,hour:s??0,minute:c??0},n.timeZone);return Number.isFinite(u.getTime())?u.toISOString():e}import{jsx as gt,jsxs as ko}from"react/jsx-runtime";function ar(e,t,n){if(e.type==="blob")return"";try{return ct(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 j(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 fu({field:e,text:t,disabled:n,id:i,label:o,ariaLabel:r,onChange:a,onSave:d,onCancel:s,locale:c="en",submitted:u=!1,describedBy:m}){let p=la(()=>j(c),[c]),l=sa(),C=da(null),b=Boolean(d);vo(()=>{if(b)C.current?.querySelector("input,textarea,select")?.focus()},[b]);let y=i??l,g=`${y}-error`,[v,f]=xo(t),[S,R]=xo(!1);vo(()=>f(t),[t]);let k=ar(e,v,c),E=Boolean(e.required&&v===""&&k)&&!S&&!u?"":k,T=r??o??e.name,V=e.type==="date"&&pt(v),h=V&&!k?bo(v):v,x=[m,E?g:void 0].filter(Boolean).join(" "),I={id:y,"aria-label":T,"aria-invalid":Boolean(E),...x?{"aria-describedby":x}:{},disabled:n,onBlur:()=>R(!0),onKeyDown:(P)=>{if(d||s)P.stopPropagation();let M=e.type==="longText"||e.type==="json";if(P.key==="Tab"&&d)P.preventDefault(),d(P.shiftKey?"previous":"next");else if(P.key==="Enter"&&!P.shiftKey&&d&&(!M||P.ctrlKey||P.metaKey))P.preventDefault(),d();else if(P.key==="Escape"&&s)P.preventDefault(),s()},style:{width:"100%",...b?{height:"100%",border:0,borderRadius:0,outline:"none",boxShadow:"none",padding:"0 7px",boxSizing:"border-box",font:"inherit"}:{},background:"var(--background, white)",color:"inherit"},className:"min-w-0 rounded-md border border-[var(--uibot-border,#d4d4d8)] bg-[var(--uibot-surface,#fff)] px-2 py-1 text-sm text-[var(--uibot-text,#18181b)] disabled:cursor-not-allowed disabled:opacity-60"},D=(P)=>{R(!0),f(P),a(P)},O=(P)=>{if(e.type==="date"&&V&&P){let M=new Date(P);D(Number.isFinite(M.getTime())?M.toISOString():P)}else D(P)},F;if(e.type==="hyperlink")F=gt(Nn,{field:e,text:v,id:y,ariaLabel:T,invalid:Boolean(E),describedBy:x||void 0,disabled:n,locale:c,inputStyle:I.style,inputClassName:I.className,onChange:D,onSave:d,onCancel:s});else if(e.type==="checkbox")F=ko("select",{...I,value:v,onChange:(P)=>D(P.currentTarget.value),children:[!e.required&>("option",{value:"",children:p("No value")}),gt("option",{value:"true",children:p("Yes")}),gt("option",{value:"false",children:p("No")})]});else if(e.type==="longText"||e.type==="json")F=gt("textarea",{...I,value:v,rows:e.type==="json"?4:3,onChange:(P)=>D(P.currentTarget.value)});else{let P=e.type==="date"&&!(k&&v)?V?"datetime-local":"date":"text",M=e.type==="blob";F=gt("input",{...I,type:P,inputMode:e.type==="number"?"decimal":void 0,step:V?"0.001":void 0,value:h,readOnly:M,onInput:e.type==="date"?(W)=>O(W.currentTarget.value):void 0,onChange:(W)=>O(W.currentTarget.value)})}return ko("div",{ref:C,className:"grid min-w-0 gap-1",style:b?{height:"100%"}:void 0,children:[o&>("label",{className:"text-xs font-medium",htmlFor:y,children:o}),F,E&>("span",{id:g,role:"alert",className:"text-xs text-red-600",children:E})]})}import{useEffect as ua,useRef as pa}from"react";import{jsx as Po}from"react/jsx-runtime";var ca={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 Ee({name:e,size:t=15,style:n}){return Po("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:Po("path",{d:ca[e]})})}import{jsx as mt,jsxs as wo,Fragment as ga}from"react/jsx-runtime";var Kt={background:"var(--uibot-primary, var(--primary, #17171a))",color:"var(--uibot-primary-foreground, var(--primary-foreground, #ffffff))",borderColor:"transparent",fontWeight:600};function Y({ui:e,style:t,variant:n,size:i,children:o,disabled:r,onClick:a,title:d,ariaLabel:s,icon:c,iconOnly:u,badge:m}){let p=e?.Button,l=c?wo("span",{style:{position:"relative",display:"inline-flex"},children:[mt(Ee,{name:c}),m?mt("span",{"aria-hidden":"true",style:{position:"absolute",top:-2,right:-3,width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}}):null]}):null,C=u?l:wo(ga,{children:[l,o]}),b=s,y=d??(u?b:void 0),g=u?"icon":i;if(p)return mt(p,{...n?{variant:n}:{},...g?{size:g}:{},disabled:r,onClick:a,title:y,"aria-label":b,children:C});return mt("button",{type:"button",style:{...c?{display:"inline-flex",alignItems:"center",gap:6}:{},...n==="default"?Kt:{},...u?{width:30,height:30,padding:0,justifyContent:"center"}:{},...t},disabled:r,onClick:a,title:y,"aria-label":b,children:C})}function Pe({ui:e,value:t,options:n,onChange:i,disabled:o,label:r,style:a,"aria-describedby":d,"aria-invalid":s}){let c=e?.Select,u={...d?{"aria-describedby":d}:{},...s?{"aria-invalid":!0}:{}};if(c)return mt(c,{value:t,options:n,onChange:i,disabled:o,"aria-label":r,...u});return mt("select",{"aria-label":r,...u,style:a,disabled:o,value:t,onChange:(m)=>i(m.target.value),children:n.map((m)=>mt("option",{value:m.value,disabled:m.disabled,children:m.label},m.value))})}function Ro({label:e,busy:t,onCancel:n,children:i,alert:o=!1}){let r=pa(null);return ua(()=>{let a=r.current,d=document.activeElement;if(a?.showModal)a.showModal();else a?.setAttribute("open","");return()=>{if(a?.close?.(),d instanceof HTMLElement&&d.isConnected)d.focus({preventScroll:!0})}},[]),mt("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 d=a.currentTarget,s=[...d.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], [tabindex="0"]')].filter((m)=>!m.hidden),c=s[0],u=s.at(-1);if(!c||(a.shiftKey?document.activeElement===c:document.activeElement===u)||!d.contains(document.activeElement)){if(a.preventDefault(),(a.shiftKey?u:c)?.focus(),!c)d.focus()}},tabIndex:-1,onCancel:(a)=>{if(a.preventDefault(),!t)n()},children:i})}import{useEffect as So,useRef as un,useState as et}from"react";import{jsx as G,jsxs as ae,Fragment as ba}from"react/jsx-runtime";function ma(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 fa=(e)=>{let t=typeof e==="string"?e:JSON.stringify(e)??"";return t.length>160?`${t.slice(0,160)}…`:t};function ya({descriptor:e,fieldIds:t,query:n,client:i,readOnly:o=!1,reloadKey:r=0,onImported:a,onRefreshSchema:d}){let[s,c]=et(null),[u,m]=et(null),[p,l]=et(null),[C,b]=et([]),[y,g]=et(""),[v,f]=et(!1),[S,R]=et(!1),[k,A]=et(!0),[E,T]=et(null),[V,h]=et(!1),x=un(!1),I=un(!1),D=un(!1),O=un(null),F=un({client:i,onImported:a,descriptor:e});F.current={client:i,onImported:a,descriptor:e},So(()=>(x.current=!0,()=>{x.current=!1,I.current=!1}),[]),So(()=>{let N=!0;if(!o)i.imports(e.id).then((_)=>{if(!N||!x.current||!_.ok)return;if(b((ee)=>_.data.map((le)=>{let Re=ee.find((H)=>H.id===le.id);return Re&&Re.version>le.version?Re:le})),!D.current)l((ee)=>{let le=_.data.find((Re)=>Re.id===ee?.id);return ee&&le&&le.version>ee.version?le:ee})});return()=>{N=!1}},[i,e.id,o,r]);let P=(N)=>{l(N),b((_)=>[N,..._.filter((ee)=>ee.id!==N.id)].slice(0,50)),T(null)};async function M(N){if(D.current||o)return;D.current=!0,I.current=!0,f(!0),R(!0),g("");let _=N;try{while(x.current&&I.current&&_.status==="ready"){let ee=await F.current.client.advanceImport(e.id,_.id,_.version);if(!x.current)break;if(!ee.ok){g(ee.error.message);break}let le=ee.data;if(P(le),le.importedRows>_.importedRows)F.current.onImported();if(le.version===_.version&&le.status==="ready"){g("Import paused. Refresh the saved progress before retrying.");break}_=le}}finally{if(D.current=!1,I.current=!1,x.current)f(!1),R(!1)}}async function W(){if(!s||D.current)return;D.current=!0,f(!0),g("");let N=await i.previewImport(e.id,{...s,expectedSchemaVersion:e.schemaVersion});if(D.current=!1,!x.current)return;if(f(!1),N.ok)m(N.data),c({...s,expectedSchemaVersion:N.data.schemaVersion,mapping:N.data.mapping});else g(N.error.message)}async function te(){if(!s||!u||u.missingRequiredFieldIds.length||!u.totalRows||D.current||o)return;D.current=!0,f(!0),g(""),O.current??=crypto.randomUUID();let N=await i.createImport(e.id,{...s,idempotencyKey:O.current});if(D.current=!1,!x.current)return;if(f(!1),N.ok)P(N.data),c(null),m(null),O.current=null,M(N.data);else g(N.error.message)}async function q(){if(!p||D.current||o)return;if(p.status==="ready"){M(p);return}D.current=!0,f(!0),g("");let N=d?await d():F.current.descriptor;if(!N){D.current=!1,f(!1),g("Refresh the collection schema and try again.");return}let _=await i.resumeImport(e.id,p.id,p.version,N.schemaVersion);if(D.current=!1,!x.current)return;if(f(!1),_.ok)P(_.data),M(_.data);else g(_.error.message)}async function Z(N){if(!p)return;let _=await i.importErrors(e.id,p.id,{limit:100,...N===void 0?{}:{cursor:N},expectedVersion:p.version});if(!x.current)return;if(_.ok)T(_.data);else g(_.error.message)}async function oe(N=!1){if(v||D.current)return;D.current=!0,f(!0),g("");let _=N&&p?await i.exportImportErrors(e.id,p.id):await i.exportCsv(e.id,{...n,expectedSchemaVersion:e.schemaVersion,fieldIds:t,spreadsheetView:k});if(D.current=!1,!x.current)return;if(f(!1),_.ok)ma(_.data),g(`${_.data.rowCount} rows downloaded${_.data.protectedCells?`; ${_.data.protectedCells} text cells prefixed for spreadsheet viewing`:""}.`);else g(_.error.message)}return ae("details",{className:"min-w-0 rounded-lg border p-4",children:[G("summary",{className:"cursor-pointer text-sm font-medium",children:"CSV import and export"}),ae("div",{className:"mt-4 flex min-w-0 flex-col gap-4",children:[ae("div",{className:"flex flex-wrap items-center gap-3",children:[G("button",{type:"button",disabled:v||!t.length,onClick:()=>void oe(),children:"Export CSV"}),ae("label",{className:"flex items-center gap-2 text-sm",children:[G("input",{type:"checkbox",checked:k,onChange:(N)=>A(N.target.checked)}),"Spreadsheet view"]})]}),G("p",{className:"text-xs text-muted-foreground",children:"Export all matching records and visible columns from the active query. Spreadsheet view prefixes potentially active text with a tab and changes those values; application support varies. Turn it off for exact text. Limit: 100,000 rows or 20 MiB."}),!o&&ae(ba,{children:[ae("label",{className:"flex min-w-0 flex-col gap-2 text-sm",children:["CSV file",G("input",{"aria-label":"CSV file",className:"max-w-full",type:"file",accept:".csv,text/csv",disabled:v,onChange:async(N)=>{let _=N.target.files?.[0];if(!_)return;if(g(""),m(null),c(null),O.current=null,_.size>20971520){g("Choose a UTF-8 CSV file no larger than 20 MiB.");return}f(!0),D.current=!0;try{let ee=new TextDecoder("utf-8",{fatal:!0}).decode(await _.arrayBuffer());if(x.current)c({fileName:_.name,csv:ee,expectedSchemaVersion:e.schemaVersion})}catch{if(x.current)g("The file must be valid UTF-8 text.")}finally{if(D.current=!1,x.current)f(!1)}}})]}),s&&ae("div",{className:"flex flex-wrap gap-3",children:[G("span",{className:"break-all text-sm",children:s.fileName}),G("button",{type:"button",disabled:v,onClick:()=>void W(),children:"Preview CSV"})]}),G("p",{className:"text-xs text-muted-foreground",children:"Insert into this collection. Existing records and options stay unchanged. Dates: ISO or YYYY-MM-DD; selections: IDs or names; multi-select: JSON array or semicolon list; linked records: JSON IDs. Blank non-text cells become null. Computed columns are skipped. Invalid rows are skipped with downloadable errors."}),u&&s&&ae("div",{className:"flex min-w-0 flex-col gap-3",children:[ae("p",{className:"text-sm",children:[u.totalRows," rows · ",u.validRows," valid · ",u.invalidRows," ","invalid · ",u.ignoredColumns.length," skipped columns"]}),u.headers.map((N,_)=>ae("label",{className:"flex min-w-0 flex-wrap gap-2 text-sm",children:[ae("span",{className:"max-w-64 break-all",children:["Column ",_+1,": ",N||"(empty)"]}),ae("select",{"aria-label":`Column ${_+1} mapping`,className:"max-w-full rounded-md border bg-background p-1",value:s.mapping?.[_]??"",disabled:v,onChange:(ee)=>{let le=[...s.mapping??u.mapping];le[_]=ee.target.value||null,c({...s,mapping:le}),m(null),O.current=null},children:[G("option",{value:"",children:"Skip column"}),e.fields.filter((ee)=>!Ne(ee)).map((ee)=>ae("option",{value:ee.id,children:[ee.name," (",ee.id,")",ee.required?" · required":""]},ee.id))]})]},`${_}:${N}`)),u.missingRequiredFieldIds.length>0&&ae("p",{role:"alert",children:["Map required fields: ",u.missingRequiredFieldIds.join(", ")]}),G("div",{className:"max-w-full overflow-x-auto",children:ae("table",{className:"w-full text-xs",children:[ae("caption",{children:["First ",u.sample.length," normalized rows; row numbers include the header."]}),G("thead",{children:ae("tr",{children:[G("th",{children:"Row"}),G("th",{children:"Normalized values"}),G("th",{children:"Error"})]})}),G("tbody",{children:u.sample.map((N)=>ae("tr",{children:[G("td",{children:N.rowNumber}),G("td",{className:"max-w-96 break-all",children:fa(N.values)}),G("td",{children:N.error?.code??""})]},N.rowNumber))})]})}),G("button",{type:"button",className:"self-start",disabled:v||!u.totalRows||u.missingRequiredFieldIds.length>0,onClick:()=>void te(),children:"Confirm import"})]}),ae("label",{className:"flex flex-wrap gap-2 text-sm",children:["Saved import",ae("select",{"aria-label":"Saved import",className:"max-w-full rounded-md border bg-background p-1",value:p?.id??"",disabled:v,onChange:async(N)=>{if(!N.target.value){l(null);return}let _=await i.importJob(e.id,N.target.value);if(x.current)if(_.ok)P(_.data),h(!1);else g(_.error.message)},children:[G("option",{value:"",children:"Choose saved progress…"}),C.map((N)=>ae("option",{value:N.id,children:[N.fileName," · ",N.processedRows,"/",N.totalRows," · ",N.status]},N.id))]})]}),G("button",{type:"button",className:"self-start",disabled:v,onClick:async()=>{let N=await i.imports(e.id);if(x.current)if(N.ok)b(N.data);else g(N.error.message)},children:"Refresh saved imports"}),p&&ae("div",{className:"flex flex-col gap-3",children:[ae("p",{role:"status",children:[S?"Importing":p.status==="ready"?"Paused":p.status==="schemaChanged"?"Schema changed — confirm before continuing":p.status==="completed"?"Completed":"Cancelled"," ","· ",p.processedRows," of ",p.totalRows," processed · ",p.importedRows," imported ·"," ",p.failedRows," failed"]}),G("progress",{"aria-label":"Import progress",max:p.totalRows,value:p.processedRows,className:"max-w-full"}),G("p",{className:"text-xs text-muted-foreground",children:"Closing this page pauses new batches. An in-flight batch may finish. Resume saved progress after signing in with the same credential. Imported records remain if you cancel."}),ae("div",{className:"flex flex-wrap gap-3",children:[S&&G("button",{type:"button",onClick:()=>{I.current=!1,R(!1)},children:"Pause import"}),!S&&(p.status==="ready"||p.status==="schemaChanged")&&G("button",{type:"button",disabled:v,onClick:()=>void q(),children:p.status==="schemaChanged"?"Revalidate and resume":"Resume import"}),(p.status==="ready"||p.status==="schemaChanged")&&G("button",{type:"button",disabled:v,onClick:()=>h(!0),children:"Cancel import"}),G("button",{type:"button",disabled:v||!p.failedRows,onClick:()=>void Z(),children:"Show import errors"}),G("button",{type:"button",disabled:v||!p.failedRows,onClick:()=>void oe(!0),children:"Download all import errors"})]}),V&&ae("div",{children:[ae("p",{children:["Stop remaining rows? The ",p.importedRows," imported records will remain."]}),G("button",{type:"button",disabled:v,onClick:async()=>{D.current=!0,f(!0);let N=await i.cancelImport(e.id,p.id);if(D.current=!1,!x.current)return;if(f(!1),N.ok)P(N.data),h(!1);else g(N.error.message)},children:"Confirm cancellation"}),G("button",{type:"button",onClick:()=>h(!1),children:"Keep import"})]}),E&&ae("div",{className:"max-w-full overflow-x-auto",children:[ae("table",{className:"w-full text-xs",children:[ae("caption",{children:[E.total," failed rows"]}),G("thead",{children:ae("tr",{children:[G("th",{children:"Row"}),G("th",{children:"Field"}),G("th",{children:"Error"})]})}),G("tbody",{children:E.items.map((N)=>ae("tr",{children:[G("td",{children:N.rowNumber}),G("td",{children:N.fieldId??""}),G("td",{children:N.code})]},N.rowNumber))})]}),E.nextCursor!==null&&G("button",{type:"button",onClick:()=>void Z(E.nextCursor??void 0),children:"Next errors"})]})]})]}),y&&G("p",{role:"alert",className:"break-words text-sm",children:y})]})]})}import{useEffect as Io,useRef as It,useState as At}from"react";import{jsx as ge,jsxs as Le,Fragment as Ca}from"react/jsx-runtime";var Mn=[{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 ha({descriptor:e,client:t,onConverted:n}){let i=e.fields.filter((P)=>Mn.some((M)=>M.type===P.type)),[o,r]=At(i[0]?.id??""),a=i.find((P)=>P.id===o)??i[0],[d,s]=At(a?.type??"singleLineText"),[c,u]=At(a?.required??!1),[m,p]=At(a?.options?.map((P)=>`${P.id}=${P.name}`).join(`
|
|
5
|
+
`)??""),[l,C]=At(null),[b,y]=At(""),[g,v]=At(!1),f=It(null),S=It(null),R=It(0),k=It(e);k.current=e;let A=f.current?.field??a,E=g||f.current!==null,T=`${e.id}:${e.schemaVersion}:${JSON.stringify(e.fields)}`,V=It(e.fields);V.current=e.fields;let h=It(T);h.current=T;let x=It(!0);Io(()=>(x.current=!0,()=>{x.current=!1,R.current++}),[]),Io(()=>{if(h.current!==T)return;if(f.current&&S.current===e.id)return;R.current++;let P=V.current.find((M)=>M.id===o&&Mn.some((W)=>W.type===M.type))??V.current.find((M)=>Mn.some((W)=>W.type===M.type));if(P)r(P.id),s(P.type),u(P.required??!1),p(P.options?.map((M)=>`${M.id}=${M.name}`).join(`
|
|
6
|
+
`)??"");C(null),f.current=null,S.current=null,y(""),v(!1)},[T,o,e.id]);let I=()=>{C(null),f.current=null,S.current=null,R.current++,y("")},D=(P)=>{r(P.id),s(P.type),u(P.required??!1),p(P.options?.map((M)=>`${M.id}=${M.name}`).join(`
|
|
7
|
+
`)??""),I()};if(!A)return null;let O=()=>{let P={id:A.id,name:A.name,type:d,required:c};if(d==="singleSelect"||d==="multipleSelect")P.options=m.split(`
|
|
8
|
+
`).filter((M)=>M.trim()).map((M)=>{let W=M.indexOf("=");if(W<1)throw Error("Each option must use stable_id=Display name.");return{id:M.slice(0,W).trim(),name:M.slice(W+1).trim()}});return{expectedSchemaVersion:e.schemaVersion,field:P}},F=()=>x.current&&h.current===T;return Le("details",{className:"rounded-lg border p-4",children:[ge("summary",{className:"cursor-pointer text-sm font-medium",children:"Convert field type"}),Le("div",{className:"mt-4 flex flex-col gap-3",children:[ge("p",{className:"text-sm",children:"Preview every existing record before changing the field. Invalid values or a changed preview block confirmation. All record versions advance together."}),Le("label",{children:["Field"," ",Le("select",{"aria-label":"Conversion field",value:A.id,disabled:E,onChange:(P)=>{let M=i.find((W)=>W.id===P.target.value);if(M)D(M)},children:[f.current&&!i.some((P)=>P.id===A.id)&&ge("option",{value:A.id,children:A.name}),i.map((P)=>ge("option",{value:P.id,children:P.name},P.id))]})]}),Le("label",{children:["Target type"," ",ge("select",{"aria-label":"Conversion target type",value:d,disabled:E,onChange:(P)=>{s(P.target.value),I()},children:Mn.map((P)=>ge("option",{value:P.type,children:P.label},P.type))})]}),Le("label",{children:[ge("input",{type:"checkbox",checked:c,disabled:E,onChange:(P)=>{u(P.target.checked),I()}})," ","Required after conversion"]}),(d==="singleSelect"||d==="multipleSelect")&&Le("label",{children:["Stable option IDs and display names",ge("textarea",{"aria-label":"Conversion options",className:"block w-full rounded border p-2",disabled:E,value:m,onChange:(P)=>{p(P.target.value),I()},placeholder:`open=Open
|
|
9
|
+
done=Done`})]}),b&&ge("p",{role:"alert",className:"text-sm text-destructive",children:b}),ge("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:E,onClick:async()=>{let P;try{P=O()}catch(M){y(M instanceof Error?M.message:"Invalid conversion options.");return}v(!0),y(""),C(null),f.current=null;try{let M=await t.previewConversion(e.id,P);if(!F())return;if(M.ok)C(M.data);else y(M.error.message)}catch{if(F())y("Preview unavailable. Your draft is kept.")}finally{if(F())v(!1)}},children:g?"Working…":"Preview conversion"}),l&&Le(Ca,{children:[Le("p",{role:"status",children:[l.validRows," valid · ",l.invalidRows," invalid"]}),Le("p",{className:"text-xs",children:["Preview covers ",l.totalRows," records. Samples and errors show at most 20 records."]}),ge("div",{className:"overflow-x-auto",children:Le("table",{className:"w-full text-sm",children:[ge("thead",{children:Le("tr",{children:[ge("th",{children:"Record"}),ge("th",{children:"Before"}),ge("th",{children:"After"}),ge("th",{children:"Error"})]})}),ge("tbody",{children:l.sample.map((P)=>Le("tr",{children:[ge("td",{className:"max-w-32 break-all",children:P.id}),ge("td",{className:"max-w-48 break-words",children:JSON.stringify(P.before)}),ge("td",{className:"max-w-48 break-words",children:JSON.stringify(P.after)}),ge("td",{children:P.error})]},P.id))})]})}),l.errors.length>0&&ge("ul",{children:l.errors.map((P)=>Le("li",{children:[ge("span",{className:"break-all",children:P.id}),": ",ge("span",{children:P.code})]},P.id))}),ge("button",{type:"button",className:"self-start rounded border px-3 py-2",disabled:g||l.invalidRows>0,onClick:async()=>{if(!f.current)S.current=e.id,R.current++;f.current??={expectedSchemaVersion:l.schemaVersion,field:l.field,previewToken:l.previewToken,idempotencyKey:crypto.randomUUID()};let P=f.current,M=R.current,W=()=>x.current&&k.current.id===e.id&&M===R.current;v(!0),y("");try{let te=await t.convertField(e.id,P);if(!W())return;if(te.ok){if(C(null),f.current=null,S.current=null,te.data.descriptor.schemaVersion>=k.current.schemaVersion)n(te.data.descriptor)}else if(y(te.error.message),te.error.status===409)C(null),f.current=null,S.current=null}catch{if(W())y("Confirmation unavailable. Your preview and retry key are kept.")}finally{if(W())v(!1)}},children:"Confirm conversion"})]})]})]})}import{useEffect as va,useRef as sr,useState as Ao}from"react";import{jsx as Do,jsxs as ka}from"react/jsx-runtime";function xa({collectionIds:e,client:t,onChanges:n,pollIntervalMs:i=2000}){let o=JSON.stringify([...new Set(e)].sort()),r=sr(o);r.current=o;let a=sr(n);a.current=n;let d=sr(()=>{}),[s,c]=Ao("connecting"),[u,m]=Ao(!1);return va(()=>{let p=JSON.parse(o),l=new Map,C=!1,b=!1,y=0,g,v=()=>!C&&r.current===o,f=Math.max(50,Math.min(60000,i)),S=async()=>{if(!v()||b)return;b=!0,m(!0);let A=!1;try{let E=y>0;for(let T of p){let V=l.get(T),h=await t.changes(T,{...V!==void 0?{cursor:V}:{},limit:100});if(!v())return;if(!h.ok)throw c(h.error.code==="unauthorized"?"expired":"offline"),Error("change stream unavailable");let x=V===void 0;if(x||E||h.data.items.length>0)await a.current(T,h.data,x);if(!v())return;l.set(T,h.data.cursor),A||=h.data.hasMore}y=0,c("live")}catch{if(y++,v())c((E)=>E==="expired"?"expired":"offline")}finally{if(b=!1,v())m(!1),g=setTimeout(()=>{S()},A&&y===0?0:Math.min(30000,f*2**Math.min(y,8)))}},R=()=>{if(g!==void 0)clearTimeout(g);S()};d.current=R,c("connecting"),S();let k=()=>{if(document.visibilityState==="visible")R()};return window.addEventListener("online",R),document.addEventListener("visibilitychange",k),()=>{if(C=!0,g!==void 0)clearTimeout(g);window.removeEventListener("online",R),document.removeEventListener("visibilitychange",k)}},[o,t,i]),ka("div",{className:"flex flex-wrap items-center gap-2 text-sm",children:[Do("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")&&Do("button",{type:"button",className:"rounded border px-2 py-1",disabled:u,onClick:()=>d.current(),children:"Reconnect now"})]})}import{useEffect as Ln,useRef as ft,useState as _e}from"react";import{jsx as X,jsxs as de,Fragment as cr}from"react/jsx-runtime";var dr={code:"unavailable",status:503,message:"Record activity is unavailable. Your draft has been kept."};async function pn(e){try{return await e()}catch{return{ok:!1,error:dr}}}function lr({record:e,label:t}){let n=e?JSON.stringify(e.values,null,2):"Deleted record";return de("div",{className:"min-w-0",children:[X("strong",{children:t}),X("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap break-words rounded border p-2 text-xs",children:n.slice(0,16000)}),n.length>16000&&de(cr,{children:[X("p",{className:"text-xs",children:"Display shortened. Download the complete stored snapshot to inspect all values."}),X("button",{type:"button",onClick:()=>{let i=URL.createObjectURL(new Blob([JSON.stringify(e,null,2)],{type:"application/json"})),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 Pa({descriptor:e,recordId:t,client:n,readOnly:i=!1,onCommitted:o,registerRefresh:r}){let[a,d]=_e(null),[s,c]=_e(null),[u,m]=_e(null),[p,l]=_e(),[C,b]=_e(),[y,g]=_e([]),[v,f]=_e([]),[S,R]=_e(""),[k,A]=_e(null),[E,T]=_e(null),[V,h]=_e(null),[x,I]=_e(!1),[D,O]=_e(""),F=ft(null),P=ft(null),M=ft(n);M.current=n;let W=ft(!1),te=ft(0),q=`${e.id}:${t}`,Z=ft(q);Z.current=q;let oe=ft({historyBefore:p,commentBefore:C});oe.current={historyBefore:p,commentBefore:C};let N=ft(async()=>{}),_=(w=q)=>W.current&&Z.current===w&&M.current===n,ee=async()=>{let w=q,U=++te.current,K=oe.current,[Fe,vt]=await Promise.all([pn(()=>n.history(e.id,t,{...K.historyBefore===void 0?{}:{before:K.historyBefore},limit:20})),pn(()=>n.comments(e.id,t,{...K.commentBefore===void 0?{}:{before:K.commentBefore},limit:50}))]);if(!_(w)||U!==te.current)throw Error("Refresh superseded");if(!Fe.ok||!vt.ok)throw O(!Fe.ok?Fe.error.message:!vt.ok?vt.error.message:dr.message),Error("Activity refresh failed");c(Fe.data),m(vt.data),d(w)};N.current=ee,Ln(()=>(W.current=!0,()=>{W.current=!1,te.current++}),[]),Ln(()=>(r?.(()=>N.current()),()=>r?.(null)),[r]),Ln(()=>{if(Z.current!==q)return;c(null),m(null),d(null),l(void 0),b(void 0),g([]),f([]),oe.current={historyBefore:void 0,commentBefore:void 0},R(""),A(null),T(null),h(null),F.current=null,P.current=null,I(!1),O("")},[q]),Ln(()=>{if(Z.current!==q||M.current!==n||oe.current.historyBefore!==p||oe.current.commentBefore!==C)return;N.current().catch(()=>{})},[q,n,p,C]);let le=(w)=>{let U=F.current;if(U?.signature===w)return U.key;let K={signature:w,key:crypto.randomUUID()};return F.current=K,K.key},Re=async(w)=>{if(x||i||!u||a!==q)return;let U=w==="delete"?E:k;if(w!=="create"&&(!U||U.authorId!==u.actorId))return;let K=w==="create"?S:k?.draft??"";if(w!=="delete"&&(!K.trim()||K.length>4000||K.includes("\x00"))){O("Comments require 1–4,000 characters.");return}let Fe=le(JSON.stringify([w,U?.id,U?.version,K]));I(!0),O("");let vt=await pn(async()=>{if(w==="create")return n.createComment(e.id,t,{text:K,idempotencyKey:Fe});if(!U)return{ok:!1,error:dr};if(w==="edit")return n.editComment(e.id,t,U.id,{text:K,expectedVersion:U.version,idempotencyKey:Fe});return n.deleteComment(e.id,t,U.id,{expectedVersion:U.version,idempotencyKey:Fe})});if(!_())return;if(I(!1),!vt.ok){O(vt.error.message);return}if(F.current=null,w==="create")R("");else if(w==="edit")A(null);else T(null);if(w==="create"&&C!==void 0)b(void 0),f([]);else await N.current().catch(()=>{})},H=async(w)=>{if(x||i||!s||a!==q)return;I(!0),O(""),P.current=null;let U={targetVersion:w,expectedCurrentVersion:s.currentVersion,expectedSchemaVersion:e.schemaVersion},K=await pn(()=>n.previewUndo(e.id,t,U));if(!_())return;if(I(!1),K.ok)h(K.data);else h(null),O(K.error.message)},ye=async()=>{if(x||i||a!==q||!V&&!P.current)return;let w=P.current;if(!w){if(!V)return;w={targetVersion:V.targetVersion,expectedCurrentVersion:V.currentVersion,expectedSchemaVersion:V.schemaVersion,idempotencyKey:crypto.randomUUID()},P.current=w}let U=w;I(!0),O("");let K=await pn(()=>n.undo(e.id,t,U));if(!_())return;if(I(!1),!K.ok){if(K.error.code==="version_conflict"||K.error.code==="reference_conflict"||K.error.code==="validation")P.current=null,h(null);O(K.error.message),await N.current().catch(()=>{});return}P.current=null,h(null),o(K.data),l(void 0),g([]),await N.current().catch(()=>{})},Q=u?.items.find((w)=>w.id===k?.id),Ae=k&&Q&&Q.version!==k.version,L=V&&(V.currentVersion!==s?.currentVersion||V.schemaVersion!==e.schemaVersion);return de("section",{"aria-label":"Record activity",className:"flex min-w-0 flex-col gap-4 rounded-lg border p-4",children:[de("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[de("h2",{className:"break-all font-medium",children:["Record activity · ",t]}),X("button",{type:"button",disabled:x,onClick:()=>{O(""),N.current().catch(()=>{})},children:"Refresh activity"})]}),D&&X("p",{role:"alert",className:"text-sm text-destructive",children:D}),!s||!u||a!==q?X("p",{role:"status",children:"Loading record activity…"}):de(cr,{children:[de("p",{role:"status",children:["Current version ",s.currentVersion,s.currentDeleted?" · Deleted record":""]}),X("h3",{className:"font-medium",children:"Comments"}),u.items.length===0&&X("p",{className:"text-sm",children:"No comments yet."}),X("ol",{className:"flex flex-col gap-3",children:u.items.map((w)=>de("li",{className:"min-w-0 rounded border p-3",children:[de("p",{className:"break-all text-xs",children:[w.authorId," · ",w.updatedAt," · version ",w.version]}),X("p",{className:"whitespace-pre-wrap break-words text-sm",children:w.text??"Comment deleted"}),!i&&w.text!==null&&w.authorId===u.actorId&&de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:x,onClick:()=>{A({...w,draft:w.text??""}),T(null),F.current=null},children:"Edit comment"}),X("button",{type:"button",disabled:x,onClick:()=>{T(w),A(null),F.current=null},children:"Delete comment"})]})]},w.id))}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:x||!v.length,onClick:()=>{b(v.at(-1)),f((w)=>w.slice(0,-1))},children:"Newer comments"}),X("button",{type:"button",disabled:x||u.nextCursor===null,onClick:()=>{f((w)=>[...w,C]),b(u.nextCursor??void 0)},children:"Older comments"})]}),!i&&de(cr,{children:[k&&de("div",{className:"flex flex-col gap-2",children:[de("label",{children:["Edit comment text",X("textarea",{"aria-label":"Edit comment text",className:"w-full rounded border bg-background p-2",disabled:x,maxLength:4000,value:k.draft,onChange:(w)=>{A({...k,draft:w.target.value}),F.current=null}})]}),Ae&&de("div",{role:"status",children:[X("p",{children:"This comment changed. Your draft and original version are kept."}),de("p",{className:"whitespace-pre-wrap break-words",children:["Current text: ",Q.text??"Comment deleted"]}),Q.text!==null&&Q.authorId===u.actorId&&X("button",{type:"button",disabled:x,onClick:()=>{A({...Q,draft:k.draft}),F.current=null},children:"Use current comment version"})]}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:x||k.authorId!==u.actorId,onClick:()=>void Re("edit"),children:"Save comment"}),X("button",{type:"button",disabled:x,onClick:()=>{A(null),F.current=null},children:"Cancel comment edit"})]})]}),E&&de("div",{children:[X("p",{children:"Delete this comment? A deletion marker will remain."}),X("p",{className:"whitespace-pre-wrap break-words",children:E.text}),X("button",{type:"button",disabled:x||E.authorId!==u.actorId,onClick:()=>void Re("delete"),children:"Confirm delete comment"}),X("button",{type:"button",disabled:x,onClick:()=>T(null),children:"Cancel delete comment"})]}),de("label",{children:["New comment",X("textarea",{"aria-label":"New comment",className:"w-full rounded border bg-background p-2",disabled:x,maxLength:4000,value:S,onChange:(w)=>{R(w.target.value),F.current=null}})]}),X("button",{type:"button",className:"self-start",disabled:x||!S.trim(),onClick:()=>void Re("create"),children:"Add comment"})]}),X("h3",{className:"font-medium",children:"Record history"}),X("p",{className:"text-xs",children:"Stored writable values at each version. Live computed values are excluded. A legacy baseline has an unknown author; earlier versions cannot be recovered."}),X("ol",{className:"flex flex-col gap-3",children:s.items.map((w)=>de("li",{className:"min-w-0 rounded border p-3",children:[de("p",{className:"break-all text-xs",children:["Version ",w.version," · ",w.operation," · schema ",w.schemaVersion," · ",w.actorId," ·"," ",w.createdAt]}),de("details",{children:[de("summary",{children:["Stored values at version ",w.version]}),X(lr,{record:w.snapshot,label:`Version ${w.version}`})]}),!i&&w.version<s.currentVersion&&de("button",{type:"button",disabled:x,onClick:()=>void H(w.version),children:["Preview restore version ",w.version]})]},w.id))}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:x||!y.length,onClick:()=>{l(y.at(-1)),g((w)=>w.slice(0,-1))},children:"Newer history"}),X("button",{type:"button",disabled:x||s.nextCursor===null,onClick:()=>{g((w)=>[...w,p]),l(s.nextCursor??void 0)},children:"Older history"})]}),!i&&V&&de("div",{className:"flex min-w-0 flex-col gap-3 rounded border p-3",children:[de("h3",{children:["Restore version ",V.targetVersion," as a new version"]}),de("p",{children:["Current version ",V.currentVersion," · schema ",V.schemaVersion,". Confirmation preserves the history and requires both versions to remain unchanged."]}),de("div",{className:"grid min-w-0 gap-3 sm:grid-cols-2",children:[X(lr,{record:V.before,label:"Current stored values"}),X(lr,{record:V.target,label:"Values to restore"})]}),L&&!P.current&&X("p",{role:"status",children:"The record or schema changed. Preview the restore again."}),de("div",{className:"flex gap-3",children:[X("button",{type:"button",disabled:x||!!L&&!P.current,onClick:()=>void ye(),children:P.current?"Retry undo":"Confirm restore"}),X("button",{type:"button",disabled:x,onClick:()=>{h(null),P.current=null},children:"Cancel restore"})]})]})]})]})}import{useEffect as On,useRef as yt,useState as at}from"react";import{jsx as Ie,jsxs as Be,Fragment as Eo}from"react/jsx-runtime";async function Vn(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 wa(e){let t=new Uint8Array(await e.arrayBuffer()),n="";for(let i of t)n+=String.fromCharCode(i);return btoa(n)}function Ra({collectionId:e,recordId:t,client:n,readOnly:i=!1,registerRefresh:o}){let r=`${e}:${t}`,a=yt({identity:r,client:n});a.current={identity:r,client:n};let d=yt(!1),s=yt(0),c=yt(0),[u,m]=at(null),[p,l]=at(null),[C,b]=at(),[y,g]=at([]),v=yt(C);v.current=C;let[f,S]=at(null),[R,k]=at(null),A=yt(null),E=yt(null),[T,V]=at(!1),[h,x]=at(!1),[I,D]=at(""),O=()=>d.current&&a.current.identity===r&&a.current.client===n,F=async()=>{let q=++s.current,Z=await Vn(()=>n.list(e,t,{limit:20,...v.current===void 0?{}:{before:v.current}}));if(!O()||q!==s.current)throw Error("Refresh superseded");if(!Z.ok)throw D(Z.error.message),Error("Attachment refresh failed");l(Z.data),m(r)},P=yt(F);P.current=F,On(()=>(d.current=!0,()=>{d.current=!1,++s.current,++c.current}),[]),On(()=>{if(a.current.identity!==r||a.current.client!==n)return;m(null),l(null),S(null),k(null),A.current=null,V(!1),x(!1),D(""),b(void 0),g([]),v.current=void 0,++c.current,P.current().catch(()=>{})},[r,n]),On(()=>{if(v.current===C&&u===r)P.current().catch(()=>{})},[C,r,u]),On(()=>(o?.(()=>P.current()),()=>o?.(null)),[o]);let M=async()=>{if(T||i||!f||u!==r)return;let q=f;V(!0),D("");let Z=await Vn(()=>n.upload(e,t,q));if(!O())return;if(V(!1),!Z.ok){D(Z.error.message);return}if(S(null),E.current)E.current.value="";b(void 0),g([]),v.current=void 0,await P.current().catch(()=>{})},W=async()=>{if(T||i||!R||R.authorId!==p?.actorId||u!==r)return;A.current??=crypto.randomUUID();let q=R,Z=A.current;V(!0),D("");let oe=await Vn(()=>n.delete(e,t,q.id,{expectedVersion:q.version,idempotencyKey:Z}));if(!O())return;if(V(!1),!oe.ok){D(oe.error.message),await P.current().catch(()=>{});return}k(null),A.current=null,await P.current().catch(()=>{})},te=async(q)=>{if(T||u!==r)return;V(!0),D("");let Z=await Vn(()=>n.content(e,t,q.id));if(!O())return;if(V(!1),!Z.ok){D(Z.error.message);return}let oe=Uint8Array.from(atob(Z.data.base64),(ee)=>ee.charCodeAt(0)),N=URL.createObjectURL(new Blob([oe],{type:"application/octet-stream"})),_=document.createElement("a");_.href=N,_.download=Z.data.attachment.name,_.click(),setTimeout(()=>URL.revokeObjectURL(N),1000)};return Be("section",{"aria-label":"Record attachments",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[Be("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[Ie("h3",{className:"font-medium",children:"Attachments"}),Ie("button",{type:"button",disabled:T,onClick:()=>{D(""),P.current().catch(()=>{})},children:"Refresh attachments"})]}),I&&Ie("p",{role:"alert",children:I}),!p||u!==r?Ie("p",{role:"status",children:"Loading attachments…"}):Be(Eo,{children:[p.items.length===0&&Ie("p",{children:"No attachments yet."}),Ie("ol",{className:"flex min-w-0 flex-col gap-2",children:p.items.map((q)=>Be("li",{className:"min-w-0 rounded border p-2",children:[Ie("p",{className:"break-all",children:q.name}),Be("p",{className:"break-all text-xs",children:[q.size," bytes · version ",q.version," · ",q.authorId]}),q.deletedAt?Ie("p",{children:"Attachment deleted"}):Be("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:T,"aria-label":`Download attachment ${q.name}`,onClick:()=>void te(q),children:"Download"}),!i&&q.authorId===p.actorId&&Ie("button",{type:"button",disabled:T,"aria-label":`Delete attachment ${q.name}`,onClick:()=>{k(q),A.current=null},children:"Delete"})]})]},q.id))}),Be("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:T||!y.length,onClick:()=>{b(y.at(-1)),g((q)=>q.slice(0,-1))},children:"Newer attachments"}),Ie("button",{type:"button",disabled:T||p.nextCursor===null,onClick:()=>{g((q)=>[...q,C]),b(p.nextCursor??void 0)},children:"Older attachments"})]}),!i&&Be(Eo,{children:[Ie("p",{className:"text-xs",children:"Up to 1 MiB per file, 20 active files and 5 MiB per record. Files have independent versions; restoring record values does not restore deleted files."}),Be("label",{children:["Attachment file",Ie("input",{ref:E,"aria-label":"Attachment file",type:"file",disabled:T||h,onChange:async(q)=>{let Z=q.target.files?.[0];if(!Z)return;let oe=++c.current;if(S(null),D(""),!Z.size||Z.size>1048576){D("Choose a nonempty file up to 1 MiB.");return}x(!0);try{let N=await wa(Z);if(!O()||oe!==c.current)return;let _=["text/plain","text/csv","application/json","application/pdf","image/png","image/jpeg","image/webp"].includes(Z.type)?Z.type:"application/octet-stream";S({name:Z.name,contentType:_,base64:N,idempotencyKey:crypto.randomUUID()})}catch{if(O()&&oe===c.current)D("The selected file could not be read.")}finally{if(O()&&oe===c.current)x(!1)}}},r)]}),f&&Be("p",{className:"break-all",children:["Selected file: ",f.name]}),Ie("button",{type:"button",className:"self-start",disabled:T||h||!f,onClick:()=>void M(),children:"Upload attachment"}),R&&Be("div",{children:[Be("p",{className:"break-all",children:["Delete ",R.name,"? This permanently removes its bytes and keeps a deletion marker."]}),Be("div",{className:"flex flex-wrap gap-3",children:[Ie("button",{type:"button",disabled:T,onClick:()=>void W(),children:"Confirm delete attachment"}),Ie("button",{type:"button",disabled:T,onClick:()=>{k(null),A.current=null},children:"Cancel delete attachment"})]})]})]})]})]})}import{useEffect as _n,useRef as Wt,useState as Ue}from"react";import{jsx as ue,jsxs as he,Fragment as To}from"react/jsx-runtime";async function ur(e){try{return await e()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Sharing is unavailable. Your confirmation request is kept."}}}}function Sa(){return[...crypto.getRandomValues(new Uint8Array(32))].map((t)=>t.toString(16).padStart(2,"0")).join("")}function Ia({descriptor:e,recordIds:t,client:n,linkForGrant:i,registerRefresh:o}){let r=e.id,a=Wt({identity:r,client:n});a.current={identity:r,client:n};let d=Wt(!1),s=Wt(0),[c,u]=Ue(null),[m,p]=Ue(null),[l,C]=Ue(),b=Wt(l);b.current=l;let[y,g]=Ue([]),[v,f]=Ue([]),[S,R]=Ue([]),[k,A]=Ue(3600),[E,T]=Ue(null),[V,h]=Ue(!1),[x,I]=Ue(""),[D,O]=Ue(null),F=Wt(null),[P,M]=Ue(!1),[W,te]=Ue(""),q=()=>d.current&&a.current.identity===r&&a.current.client===n,Z=async()=>{let H=++s.current,ye=await ur(()=>n.list(r,{limit:20,...b.current===void 0?{}:{before:b.current}}));if(!q()||H!==s.current)throw Error("Refresh superseded");if(!ye.ok)throw te(ye.error.message),Error("Share refresh failed");p(ye.data),u(r)},oe=Wt(Z);oe.current=Z,_n(()=>(d.current=!0,()=>{d.current=!1,++s.current}),[]),_n(()=>{if(a.current.identity!==r||a.current.client!==n)return;u(null),p(null),f([]),R([]),T(null),h(!1),I(""),O(null),F.current=null,M(!1),te(""),C(void 0),g([]),b.current=void 0,oe.current().catch(()=>{})},[r,n]),_n(()=>{if(b.current===l&&c===r)oe.current().catch(()=>{})},[l,c,r]),_n(()=>(o?.(()=>oe.current()),()=>o?.(null)),[o]);let N=()=>{if(!V)T(null)},_=async()=>{if(P||!E||c!==r)return;let H=E;M(!0),h(!0),te("");let ye=await ur(()=>n.create(r,H));if(!q())return;if(M(!1),!ye.ok){te(ye.error.message);return}I(i(ye.data,H.key)),T(null),h(!1),C(void 0),g([]),b.current=void 0,await oe.current().catch(()=>{})},ee=async()=>{if(P||!D||c!==r)return;let H=D;F.current??=crypto.randomUUID();let ye=F.current;M(!0),te("");let Q=await ur(()=>n.revoke(r,H.id,{expectedVersion:H.version,idempotencyKey:ye}));if(!q())return;if(M(!1),!Q.ok){te(Q.error.message),await oe.current().catch(()=>{});return}O(null),F.current=null,I(""),await oe.current().catch(()=>{})},le=e.fields.filter((H)=>!["linkedRecord","lookup","formula","rollup"].includes(H.type)),Re=P||V;return he("section",{"aria-label":"Collection sharing",className:"flex min-w-0 flex-col gap-3 rounded-lg border p-4",children:[he("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[ue("h3",{className:"font-medium",children:"Read-only sharing"}),ue("button",{type:"button",disabled:P,onClick:()=>{te(""),oe.current().catch(()=>{})},children:"Refresh share grants"})]}),ue("p",{className:"text-sm",children:"Select the exact basic fields and stable record IDs. Links expose current selected values until expiry or revocation. Schema changes close access."}),ue("p",{className:"text-xs",children:"Relations, computed fields, attachments, discussions, history and writes are excluded. Up to 100 records, 20 active grants and 24 hours per grant. Keys are shown only when created."}),W&&ue("p",{role:"alert",children:W}),he("fieldset",{disabled:Re,className:"flex min-w-0 flex-col gap-2",children:[ue("legend",{children:"Fields to share"}),le.map((H)=>he("label",{className:"break-all",children:[ue("input",{type:"checkbox","aria-label":`Share field ${H.name}`,checked:v.includes(H.id),onChange:(ye)=>{N(),f((Q)=>ye.target.checked?[...Q,H.id]:Q.filter((Ae)=>Ae!==H.id))}})," ",H.name]},H.id))]}),he("fieldset",{disabled:Re,className:"flex min-w-0 flex-col gap-2",children:[ue("legend",{children:"Records on the current page"}),t.slice(0,100).map((H)=>he("label",{className:"break-all",children:[ue("input",{type:"checkbox","aria-label":`Share record ${H}`,checked:S.includes(H),onChange:(ye)=>{N(),R((Q)=>ye.target.checked?[...Q,H]:Q.filter((Ae)=>Ae!==H))}})," ",H]},H)),t.length===0&&ue("p",{children:"Load records in Grid to choose a share scope."})]}),he("p",{className:"break-all text-xs",children:["Selected record IDs: ",S.join(", ")||"none"]}),he("label",{children:["Link lifetime"," ",he("select",{"aria-label":"Share link lifetime",disabled:Re,value:k,onChange:(H)=>{N(),A(Number(H.target.value))},children:[ue("option",{value:60,children:"1 minute"}),ue("option",{value:3600,children:"1 hour"}),ue("option",{value:86400,children:"24 hours"})]})]}),ue("button",{type:"button",className:"self-start",disabled:Re||c!==r||!v.length||!S.length||S.length>100||v.some((H)=>!le.some((ye)=>ye.id===H)),onClick:()=>{te("");try{T({expectedSchemaVersion:e.schemaVersion,fieldIds:[...v],recordIds:[...S],expiresInSeconds:k,key:Sa(),idempotencyKey:crypto.randomUUID()})}catch{te("A secure share key could not be generated.")}},children:"Review read-only share"}),E&&he("div",{className:"flex min-w-0 flex-col gap-2 rounded border p-3",children:[he("p",{className:"break-all",children:["Confirm schema ",E.expectedSchemaVersion,", fields ",E.fieldIds.join(", "),", records ",E.recordIds.join(", ")," for ",E.expiresInSeconds," seconds."]}),E.expectedSchemaVersion!==e.schemaVersion&&ue("p",{children:"Schema changed. Retry keeps the original request; the resulting link may be closed."}),he("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:P,onClick:()=>void _(),children:V?"Retry create read link":"Create read link"}),ue("button",{type:"button",disabled:P,onClick:()=>{T(null),h(!1),te("")},children:"Discard share confirmation"})]}),V&&ue("p",{className:"text-xs",children:"If the response was lost, retry returns the same grant. A discarded committed grant remains in the directory and can be revoked."})]}),x&&he("label",{className:"flex min-w-0 flex-col gap-1",children:["Created read link",ue("input",{"aria-label":"Created read link",className:"w-full min-w-0 rounded border p-2",readOnly:!0,value:x,onFocus:(H)=>H.target.select()})]}),!m||c!==r?ue("p",{role:"status",children:"Loading share grants…"}):he(To,{children:[m.items.length===0&&ue("p",{children:"No share grants yet."}),ue("ol",{className:"flex min-w-0 flex-col gap-2",children:m.items.map((H)=>he("li",{className:"min-w-0 rounded border p-2",children:[he("p",{className:"break-all",children:["Grant ",H.id," · version ",H.version," · schema ",H.schemaVersion]}),he("p",{className:"break-all text-xs",children:["Fields: ",H.fieldIds.join(", ")," · Records: ",H.recordIds.join(", ")," · Expires:"," ",H.expiresAt]}),H.revokedAt?ue("p",{children:"Share revoked"}):he(To,{children:[ue("p",{children:H.schemaVersion!==e.schemaVersion?"Schema changed; access closed":Date.parse(H.expiresAt)<=Date.now()?"Share expired":"Share active"}),ue("button",{type:"button",disabled:P,"aria-label":`Revoke share ${H.id}`,onClick:()=>{O(H),F.current=null},children:"Revoke"})]})]},H.id))}),he("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:P||!y.length,onClick:()=>{C(y.at(-1)),g((H)=>H.slice(0,-1))},children:"Newer share grants"}),ue("button",{type:"button",disabled:P||m.nextCursor===null,onClick:()=>{g((H)=>[...H,l]),C(m.nextCursor??void 0)},children:"Older share grants"})]})]}),D&&he("div",{children:[he("p",{className:"break-all",children:["Revoke grant ",D.id," at version ",D.version,"? Every existing share session will lose access."]}),he("div",{className:"flex flex-wrap gap-3",children:[ue("button",{type:"button",disabled:P,onClick:()=>void ee(),children:"Confirm revoke share"}),ue("button",{type:"button",disabled:P,onClick:()=>{O(null),F.current=null},children:"Cancel revoke share"})]})]})]})}import{useEffect as Fo,useRef as Yt,useState as Te}from"react";import{jsx as ne,jsxs as ve}from"react/jsx-runtime";var No=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],Aa=()=>[...crypto.getRandomValues(new Uint8Array(32))].map((e)=>e.toString(16).padStart(2,"0")).join("");function Da({descriptor:e,recordIds:t,client:n,webhookRequest:i}){let o=e.id,r=Yt({id:o,client:n});r.current={id:o,client:n};let a=Yt(!0),d=Yt(0),[s,c]=Te([]),[u,m]=Te(""),p=Yt(u);p.current=u;let[l,C]=Te(null),[b,y]=Te(),g=Yt(b);g.current=b;let[v,f]=Te(""),[S,R]=Te("record"),[k,A]=Te(60),[E,T]=Te([]),[V,h]=Te([]),[x,I]=Te({}),[D,O]=Te(null),[F,P]=Te(!1),[M,W]=Te(!1),[te,q]=Te(""),[Z,oe]=Te(""),N=()=>a.current&&r.current.id===o&&r.current.client===n,_=async(L)=>{try{return await L()}catch{return{ok:!1,error:{code:"unavailable",status:503,message:"Automation is unavailable. The original confirmation is kept."}}}},ee=async()=>{let L=++d.current,w=await _(()=>n.list(o));if(!N()||L!==d.current)return;if(!w.ok){q(w.error.message);return}c(w.data);let U=w.data.find((Fe)=>Fe.id===p.current)?.id??w.data[0]?.id??"";if(p.current=U,m(U),!U){C(null);return}let K=await _(()=>n.runs(o,U,{limit:20,...g.current?{before:g.current}:{}}));if(!N()||L!==d.current||p.current!==U)return;if(K.ok)C(K.data);else q(K.error.message)},le=Yt(ee);le.current=ee,Fo(()=>{if(r.current.id!==o||r.current.client!==n)return;a.current=!0,le.current();let L=setInterval(()=>void le.current(),5000);return()=>{a.current=!1,++d.current,clearInterval(L)}},[o,n]),Fo(()=>{if(p.current!==u||g.current!==b)return;le.current()},[u,b]);let Re=()=>{if(q(""),!v.trim()||!E.length||S!=="record"&&!V.length){q("Choose a name, writable fields, and target records for time or webhook triggers.");return}let L=Object.fromEntries(E.map((U)=>[U,x[U]??null])),w={expectedSchemaVersion:e.schemaVersion,name:v.trim(),trigger:S==="time"?{kind:S,intervalSeconds:k}:{kind:S},targetRecordIds:V,values:L,idempotencyKey:crypto.randomUUID(),...S==="webhook"?{webhookKey:Aa()}:{}};O({kind:"create",input:w}),P(!1)},H=(L)=>{O(L),P(!1),q("")},ye=async()=>{if(!D||M)return;let L=D,w=F;P(!0),W(!0),q("");let U=await _(()=>L.kind==="create"?n.create(o,L.input):L.kind==="toggle"?n.toggle(o,L.a.id,L.input):L.kind==="run"?n.runNow(o,L.a.id,L.input):n.retry(o,L.a.id,L.run.id,L.input));if(!N())return;if(W(!1),!U.ok){if(!w&&U.error.status>=400&&U.error.status<500)P(!1);q(`${U.error.message} Retry keeps the same request, record versions and idempotency key.`);return}if(L.kind==="create"){let K=U.data;if(p.current=K.id,m(K.id),L.input.webhookKey&&i)oe(JSON.stringify(i(K,L.input.webhookKey),null,2));f(""),T([]),h([]),I({})}O(null),P(!1),g.current=void 0,y(void 0),await le.current()},Q=s.find((L)=>L.id===u),Ae=!!D||M;return ve("section",{"aria-label":"Collection automation",style:{minWidth:0,display:"flex",flexDirection:"column",gap:12},children:[ne("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."}),ne("button",{type:"button",onClick:()=>void le.current(),children:"Refresh automation"}),te&&ne("p",{role:"alert",children:te}),ne("form",{onSubmit:(L)=>{L.preventDefault(),Re()},style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},children:ve("fieldset",{disabled:Ae,style:{minWidth:0},children:[ne("legend",{children:"New automation"}),ve("label",{children:["Name"," ",ne("input",{"aria-label":"Automation name",value:v,maxLength:200,onChange:(L)=>f(L.target.value)})]}),ve("label",{children:["Trigger"," ",ve("select",{"aria-label":"Automation trigger",value:S,onChange:(L)=>R(L.target.value),children:[ne("option",{value:"record",children:"Record changes"}),ne("option",{value:"time",children:"Timed interval"}),ne("option",{value:"webhook",children:"Private webhook"})]})]}),S==="time"&&ve("label",{children:["Interval in seconds"," ",ne("input",{type:"number","aria-label":"Automation interval",min:60,max:86400,value:k,onChange:(L)=>A(Number(L.target.value))})]}),ve("fieldset",{children:[ne("legend",{children:"Fields to update"}),e.fields.filter((L)=>No.includes(L.type)).map((L)=>ve("label",{style:{display:"block"},children:[ne("input",{type:"checkbox",checked:E.includes(L.id),onChange:(w)=>{T(w.target.checked?[...E,L.id]:E.filter((U)=>U!==L.id))}}),L.name]},L.id))]}),ne(Dt,{fields:e.fields.filter((L)=>E.includes(L.id)&&No.includes(L.type)),values:x,onChange:I}),ve("fieldset",{children:[ne("legend",{children:"Target records from this page"}),S==="record"&&ne("p",{children:"Leave targets empty to update the live records in each change."}),!t.length&&ne("p",{children:"Open a grid page to choose fixed records."}),t.map((L)=>ve("label",{style:{display:"block",overflowWrap:"anywhere"},children:[ne("input",{type:"checkbox","aria-label":`Automation target ${L}`,checked:V.includes(L),onChange:(w)=>h(w.target.checked?[...V,L]:V.filter((U)=>U!==L))}),L]},L))]}),ne("button",{type:"submit",children:"Review automation"})]})}),D&&ve("section",{"aria-label":"Automation confirmation",style:{minWidth:0},children:[ne("p",{children:D.kind==="create"?`Create ${D.input.name} using schema ${D.input.expectedSchemaVersion}; ${D.input.targetRecordIds.length||"event"} targets.`:D.kind==="toggle"?`${D.input.enabled?"Enable":"Disable"} ${D.a.name}. Disabling fences queued and running work.`:D.kind==="run"?`Run ${D.a.name} for ${D.input.recordIds.length} explicitly selected records.`:`Retry ${D.a.name}, run ${D.run.sequence}, using its original record versions.`}),D.kind==="create"&&ne("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(D.input.values,null,2)}),ne("button",{type:"button",disabled:M,onClick:()=>void ye(),children:M?"Confirming…":F?"Retry automation confirmation":"Confirm automation"}),ne("button",{type:"button",disabled:F||M,onClick:()=>O(null),children:"Cancel automation review"}),F&&ne("p",{children:"The request may have committed. Keep this confirmation until the same request is acknowledged."})]}),Z&&ve("div",{children:[ne("p",{children:"Copy this private webhook request now. Replace eventId with a stable unique event identifier. The key is only displayed in this session."}),ne("textarea",{"aria-label":"Private webhook request",readOnly:!0,rows:8,style:{width:"100%",boxSizing:"border-box"},value:Z}),ne("button",{type:"button",onClick:()=>oe(""),children:"Hide webhook key"})]}),s.length>0&&ve("label",{children:["Automation"," ",ne("select",{"aria-label":"Selected automation",disabled:Ae,value:u,onChange:(L)=>{p.current=L.target.value,g.current=void 0,y(void 0),m(L.target.value),C(null)},children:s.map((L)=>ne("option",{value:L.id,children:L.name},L.id))})]}),Q&&ve("div",{children:[ve("p",{children:[Q.enabled?"Enabled":"Disabled"," · ",Q.trigger.kind," · schema ",Q.schemaVersion," · configuration ",Q.version]}),ne("button",{type:"button",disabled:Ae,onClick:()=>H({kind:"toggle",a:Q,input:{expectedVersion:Q.version,enabled:!Q.enabled,idempotencyKey:crypto.randomUUID()}}),children:Q.enabled?"Review disable automation":"Review enable automation"}),ne("button",{type:"button",disabled:Ae||!Q.enabled||!(Q.targetRecordIds.length||t.length),onClick:()=>H({kind:"run",a:Q,input:{recordIds:Q.targetRecordIds.length?Q.targetRecordIds:t,idempotencyKey:crypto.randomUUID()}}),children:"Review run now"})]}),l&&ve("section",{"aria-label":"Automation runs",style:{minWidth:0},children:[!l.items.length&&ne("p",{children:"No runs yet."}),l.items.map((L)=>ve("article",{style:{overflowWrap:"anywhere",padding:8,borderBottom:"1px solid #8886"},children:[ve("p",{children:["Run ",L.sequence," · ",L.triggerKind," · ",L.status," · step ",L.step]}),ve("p",{children:["Attempts: evaluate ",L.stepAttempts.evaluate,", apply ",L.stepAttempts.apply," · original versions: ",L.expectedRows.map((w)=>`${w.id}: ${w.version}`).join(", ")]}),L.errorCode&&ne("p",{role:"status",children:L.errorCode}),L.leaseUntil&&ve("p",{children:["Lease expires ",L.leaseUntil]}),Q&&L.status==="failed"&&ve("button",{type:"button",disabled:Ae||!Q.enabled,onClick:()=>H({kind:"retry",a:Q,run:L,input:{expectedVersion:L.version,idempotencyKey:crypto.randomUUID()}}),children:["Review retry run ",L.sequence]})]},L.id)),ne("button",{type:"button",disabled:Ae||b===void 0,onClick:()=>{g.current=void 0,y(void 0)},children:"Newest runs"}),ne("button",{type:"button",disabled:Ae||l.nextCursor===null,onClick:()=>{g.current=l.nextCursor??void 0,y(g.current)},children:"Older runs"})]})]})}import{useEffect as Ea,useId as Ta,useRef as Mo,useState as De}from"react";import{jsx as ce,jsxs as xe}from"react/jsx-runtime";var Lo=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"];function Fa(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&&Lo.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 Na({descriptor:e,records:t,client:n,onApplied:i}){let o=Ta(),r=e.id,a=Mo({id:r,client:n}),d=Mo(!0);a.current={id:r,client:n};let[s,c]=De([]),[u,m]=De(!1),[p,l]=De(""),[C,b]=De(""),[y,g]=De(""),[v,f]=De([]),[S,R]=De([]),[k,A]=De([]),[E,T]=De(null),[V,h]=De(null),[x,I]=De(null),[D,O]=De(!1),[F,P]=De(!1),[M,W]=De(""),[te,q]=De(""),[Z,oe]=De(""),N=()=>d.current&&a.current.id===r&&a.current.client===n,_=async(w)=>{try{return await w()}catch{return{ok:!1,error:{status:503,code:"unavailable",message:"The result is unknown. Retry keeps the original request."}}}};Ea(()=>{d.current=!0,T(null),h(null),I(null),O(!1),W(""),q(""),oe(""),f([]),R([]),A([]),g("");let w=!0;return m(!1),P(!1),c([]),l(""),b(""),n.providers(r).then((U)=>{if(!w||a.current.id!==r||a.current.client!==n)return;if(m(!0),U.ok)c(U.data),l(U.data[0]?.resourceId??""),b(U.data[0]?.allowedModels[0]??"");else W(U.error.message)}).catch(()=>{if(w)m(!0),W("AI configuration is unavailable.")}),()=>{w=!1,d.current=!1}},[r,n]);let ee=()=>{try{let w=Fa(e,t,{resourceId:p,model:C,instruction:y,recordIds:v,sourceFieldIds:S,targetFieldIds:k});h(structuredClone(w.records.map((U)=>({id:U.id,version:U.expectedVersion,values:Object.fromEntries(w.sourceFieldIds.map((K)=>[K,t.find((Fe)=>Fe.id===U.id)?.values[K]??null]))})))),T(w),O(!1),W(""),q("")}catch(w){W(w instanceof Error?w.message:"Invalid selection.")}},le=async()=>{if(!E||F)return;let w=E,U=D;P(!0),O(!0),W("");let K=await _(()=>n.propose(r,w));if(!N())return;if(P(!1),!K.ok){if(!U&&K.error.status>=400&&K.error.status<500)O(!1);W(`${K.error.message} Retry keeps the original selection and versions.`);return}I(K.data),oe(K.data.id),O(!1)},Re=async()=>{if(!x||F)return;let w=x,U=D;P(!0),O(!0),W("");let K=await _(()=>n.confirm(r,w));if(!N())return;if(P(!1),!K.ok){if(!U&&K.error.status>=400&&K.error.status<500)O(!1);W(`${K.error.message} The reviewed proposal keeps its original versions.`);return}q(`${K.data.items.length} records filled${K.data.replayed?"; original receipt recovered":""}.`),I(null),T(null),h(null),O(!1);try{await i?.()}catch{if(N())W("The fill committed. Refresh the Collection to see its records.")}},H=async()=>{if(F||E||x)return;P(!0),W("");let w=await _(()=>n.get(r,Z));if(!N())return;if(P(!1),w.ok)I(w.data),O(!1),q("");else W(w.error.message)},ye=(w,U,K)=>K(w.includes(U)?w.filter((Fe)=>Fe!==U):[...w,U]),Q=F||!!E||!!x,Ae=e.fields.filter((w)=>Lo.includes(w.type)),L=s.find((w)=>w.resourceId===p);return xe("section",{"aria-label":"Collection AI",style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[ce("p",{children:"Choose the records and fields to send to your configured AI service. Review suggested values before writing. Conflicts keep the original record versions."}),M&&ce("p",{role:"alert",children:M}),te&&ce("p",{role:"status",children:te}),u&&s.length===0&&ce("p",{role:"status",children:"No real AI resource is configured for this Collection. Configure an existing workspace AI resource to generate proposals."}),ce("form",{onSubmit:(w)=>{w.preventDefault(),ee()},children:xe("fieldset",{disabled:Q,style:{minWidth:0},children:[ce("legend",{children:"AI fill request"}),xe("label",{children:["AI resource"," ",xe("select",{"aria-label":"AI resource",value:p,onChange:(w)=>{l(w.target.value),b(s.find((U)=>U.resourceId===w.target.value)?.allowedModels[0]??"")},children:[ce("option",{value:"",children:"Choose resource"}),s.map((w)=>ce("option",{value:w.resourceId,children:w.name},w.resourceId))]})]}),xe("label",{htmlFor:o,children:["Model"," ",L?.allowedModels.length?ce("select",{id:o,"aria-label":"AI model",value:C,onChange:(w)=>b(w.target.value),children:L.allowedModels.map((w)=>ce("option",{value:w,children:w},w))}):ce("input",{id:o,"aria-label":"AI model",maxLength:200,value:C,onChange:(w)=>b(w.target.value)})]}),xe("label",{children:["Instructions"," ",ce("textarea",{"aria-label":"AI instructions",maxLength:2000,value:y,onChange:(w)=>g(w.target.value),style:{width:"100%",boxSizing:"border-box"}})]}),xe("fieldset",{children:[ce("legend",{children:"Source fields to send"}),Ae.map((w)=>xe("label",{style:{display:"block"},children:[ce("input",{type:"checkbox","aria-label":`Send ${w.name}`,checked:S.includes(w.id),onChange:()=>ye(S,w.id,R)}),w.name]},w.id))]}),xe("fieldset",{children:[ce("legend",{children:"Fields to fill"}),Ae.map((w)=>xe("label",{style:{display:"block"},children:[ce("input",{type:"checkbox","aria-label":`Fill ${w.name}`,checked:k.includes(w.id),onChange:()=>ye(k,w.id,A)}),w.name]},w.id))]}),xe("fieldset",{children:[ce("legend",{children:"Target records from this page"}),t.map((w)=>xe("label",{style:{display:"block",overflowWrap:"anywhere"},children:[ce("input",{type:"checkbox","aria-label":`AI record ${w.id}`,checked:v.includes(w.id),onChange:()=>ye(v,w.id,f)}),w.id," · version ",w.version]},w.id))]}),ce("button",{type:"submit",disabled:!p,children:"Review AI request"})]})}),E&&!x&&xe("section",{"aria-label":"AI data disclosure",children:[xe("p",{children:["Selected service: ",E.resourceId," · model ",E.model," · schema"," ",E.expectedSchemaVersion,". Sensitive field names are redacted by the server."]}),ce("p",{children:E.instruction}),ce("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:JSON.stringify(V,null,2)}),ce("p",{children:"Generate suggested values without changing records. A provider call interrupted before the proposal is saved may be charged again when retried."}),ce("button",{type:"button",disabled:F,onClick:()=>void le(),children:D?"Retry original AI request":"Generate proposal"}),ce("button",{type:"button",disabled:F||D,onClick:()=>{T(null),h(null),W("")},children:"Cancel AI request"})]}),x&&xe("section",{"aria-label":"AI fill confirmation",children:[xe("p",{style:{overflowWrap:"anywhere"},children:["Proposal ",x.id," · ",x.provider," · schema ",x.schemaVersion]}),x.schemaVersion!==e.schemaVersion&&ce("p",{role:"alert",children:"The schema changed. This proposal keeps its original schema and cannot be rebased."}),x.rows.map((w)=>xe("div",{style:{overflowWrap:"anywhere"},children:[xe("p",{children:[w.id," · original version ",w.expectedVersion]}),Object.keys(w.values).map((U)=>xe("div",{children:[ce("strong",{children:e.fields.find((K)=>K.id===U)?.name??U}),xe("pre",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:["Before: ",JSON.stringify(w.before[U]),`
|
|
10
|
+
`,"Suggested: ",JSON.stringify(w.values[U])]})]},U))]},w.id)),ce("button",{type:"button",disabled:F,onClick:()=>void Re(),children:D?"Retry original AI fill":"Confirm fill"}),ce("button",{type:"button",disabled:F||D,onClick:()=>{I(null),T(null),h(null),W("")},children:"Dismiss proposal"})]}),xe("label",{children:["Recover a saved proposal"," ",ce("input",{"aria-label":"Saved AI proposal ID",maxLength:64,value:Z,onChange:(w)=>oe(w.target.value),disabled:Q,style:{width:"100%",boxSizing:"border-box"}})]}),ce("button",{type:"button",disabled:Q||!/^[a-f0-9]{64}$/.test(Z),onClick:()=>void H(),children:"Load saved proposal"})]})}import{jsx as z,jsxs as re}from"react/jsx-runtime";var Oa=[{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 cp({fields:e,onChange:t,lockedIds:n=[],collections:i=[]}){let o=(r,a)=>t(e.map((d,s)=>s===r?{...d,...a}:d));return re("div",{className:"flex flex-col gap-3",children:[e.map((r,a)=>{let d=n.includes(r.id);return re("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:[z("input",{"aria-label":`Field ${a+1} name`,placeholder:"Display name",value:r.name,onChange:(s)=>o(a,{name:s.target.value})}),z("input",{"aria-label":`Field ${a+1} ID`,placeholder:"field_id",value:r.id,disabled:d,onChange:(s)=>o(a,{id:s.target.value})}),z("select",{"aria-label":`Field ${a+1} type`,className:"rounded-md border bg-background px-2 text-sm",value:r.type,disabled:d,onChange:(s)=>{let c=s.target.value,u={id:r.id,name:r.name,type:c,required:Ne({type:c})?!1:r.required??!1};if(c==="formula")u.formula={expression:""};if(c==="rollup")u.rollup={linkFieldId:"",targetFieldId:"",function:"sum"};if(c==="singleSelect"||c==="multipleSelect")u.options=[{id:"open",name:"Open"},{id:"done",name:"Done"}];t(e.map((m,p)=>p===a?u:m))},children:Oa.map((s)=>z("option",{value:s.value,children:s.name},s.value))}),re("div",{className:"flex items-center gap-2",children:[re("label",{className:"flex items-center gap-1 text-xs",children:[z("input",{type:"checkbox",checked:r.required??!1,disabled:d||n.length>0||Ne(r),onChange:(s)=>o(a,{required:s.target.checked})}),"Required"]}),!d&&z("button",{type:"button",onClick:()=>t(e.filter((s,c)=>c!==a)),children:"Remove"})]}),(r.type==="singleSelect"||r.type==="multipleSelect")&&z("input",{className:"md:col-span-4","aria-label":`Field ${a+1} options`,placeholder:"Open, Done",value:r.options?.map((s)=>s.name).join(", ")??"",disabled:d,onChange:(s)=>o(a,{options:s.target.value.split(",").map((c,u)=>({id:c.trim().toLowerCase().replace(/[^a-z0-9_]/g,"_")||`option_${u}`,name:c.trim()})).filter((c)=>c.name)})}),r.type==="linkedRecord"&&re("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[re("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Linked collection"," ",re("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} linked collection`,value:r.link?.collectionId??"",disabled:d,onChange:(s)=>{let c=i.find((u)=>u.id===s.target.value);o(a,{link:{collectionId:s.target.value,displayFieldId:c?.fields.find((u)=>u.type==="singleLineText"||u.type==="longText")?.id??""}})},children:[z("option",{value:"",children:"Choose collection…"}),i.map((s)=>z("option",{value:s.id,children:s.name},s.id))]})]}),re("label",{className:"flex min-w-0 max-w-full flex-col gap-1",children:["Record label"," ",re("select",{className:"min-w-0 max-w-full","aria-label":`Field ${a+1} record label`,value:r.link?.displayFieldId??"",disabled:d||!r.link?.collectionId,onChange:(s)=>o(a,{link:{collectionId:r.link?.collectionId??"",displayFieldId:s.target.value}}),children:[z("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)=>z("option",{value:s.id,children:s.name},s.id))]})]})]}),r.type==="lookup"&&re("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[re("label",{children:["Through linked field"," ",re("select",{"aria-label":`Field ${a+1} lookup link`,value:r.lookup?.linkFieldId??"",disabled:d,onChange:(s)=>o(a,{lookup:{linkFieldId:s.target.value,targetFieldId:""}}),children:[z("option",{value:"",children:"Choose linked field…"}),e.filter((s)=>s.type==="linkedRecord"&&s.link).map((s)=>z("option",{value:s.id,children:s.name},s.id))]})]}),re("label",{children:["Read target field"," ",re("select",{"aria-label":`Field ${a+1} lookup target`,value:r.lookup?.targetFieldId??"",disabled:d||!r.lookup?.linkFieldId,onChange:(s)=>o(a,{lookup:{linkFieldId:r.lookup?.linkFieldId??"",targetFieldId:s.target.value}}),children:[z("option",{value:"",children:"Choose target field…"}),i.find((s)=>s.id===e.find((c)=>c.id===r.lookup?.linkFieldId)?.link?.collectionId)?.fields.filter((s)=>!Ne(s)&&s.type!=="linkedRecord").map((s)=>z("option",{value:s.id,children:s.name},s.id))]})]}),z("small",{children:"Computed from linked records. Values cannot be edited."})]}),r.type==="formula"&&re("div",{className:"flex flex-col gap-1 md:col-span-4",children:[re("label",{children:["Formula",z("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}})})]}),z("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."}),re("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"&&re("div",{className:"flex flex-wrap gap-2 md:col-span-4",children:[re("label",{children:["Through linked field"," ",re("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:[z("option",{value:"",children:"Choose linked field…"}),e.filter((s)=>s.type==="linkedRecord"&&s.link).map((s)=>z("option",{value:s.id,children:s.name},s.id))]})]}),re("label",{children:["Aggregate"," ",re("select",{"aria-label":`Field ${a+1} rollup function`,value:r.rollup?.function??"sum",onChange:(s)=>{let c=s.target.value,u=i.find((m)=>m.id===e.find((p)=>p.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.find((m)=>m.id===r.rollup?.targetFieldId);o(a,{rollup:{linkFieldId:r.rollup?.linkFieldId??"",targetFieldId:c==="count"||u?.type==="number"?r.rollup?.targetFieldId??"":"",function:c}})},children:[z("option",{value:"sum",children:"Sum"}),z("option",{value:"average",children:"Average"}),z("option",{value:"min",children:"Minimum"}),z("option",{value:"max",children:"Maximum"}),z("option",{value:"count",children:"Count values"})]})]}),re("label",{children:["Target field"," ",re("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:[z("option",{value:"",children:"Choose target field…"}),i.find((s)=>s.id===e.find((c)=>c.id===r.rollup?.linkFieldId)?.link?.collectionId)?.fields.filter((s)=>!Ne(s)&&s.type!=="linkedRecord"&&(r.rollup?.function==="count"||s.type==="number")).map((s)=>z("option",{value:s.id,children:s.name},s.id))]})]}),z("small",{className:"w-full",children:"Null targets are skipped. Count counts values; empty sum/count are zero. Other empty aggregates have no result."})]})]},a)}),z("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 Va(e,t,n){if(Ne(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 ar(e,Je(t),n)}function gn(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((d)=>typeof d!=="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(!Ot(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]=ct(Array.isArray(a)?a.join(","):String(a??""),r,i)}return o}function Dt({fields:e,values:t,onChange:n,relationClient:i,getRelationOptions:o,linkedRecords:r,computedErrors:a,locale:d,ui:s,submitted:c=!1}){let u=j(d),m=Ma(),p=La(()=>o??(i?mo(i,[]):void 0),[o,i]);return z("div",{className:"grid gap-3 md:grid-cols-2",children:e.map((l)=>{let C=l.description?.trim()??"",b=C?`${m}-${l.id}-hint`:void 0,y=Va(l,t[l.id],d??"en"),v=Boolean(l.required&&Je(t[l.id])===""&&y)&&!c?"":y,f=v?`${m}-${l.id}-error`:void 0,S=[b,f].filter(Boolean).join(" "),R={...S?{"aria-describedby":S}:{},...v?{"aria-invalid":!0}:{}};return re("div",{className:"flex flex-col gap-1 text-sm",children:[re("label",{htmlFor:`${m}-${l.id}`,children:[l.name,l.required?" *":""]}),C?z("p",{id:b,className:"m-0 text-xs opacity-70",children:C}):null,Ne(l)?z("output",{id:`${m}-${l.id}`,"aria-label":u("{name} (read only)",{name:l.name}),...R,children:l.type==="lookup"?qt(t[l.id]):In(t[l.id],a?.[l.id],d)}):l.type==="relation"?z(Tn,{field:l,id:`${m}-${l.id}`,label:`${l.name}${l.required?" *":""}`,value:typeof t[l.id]==="string"?String(t[l.id]):"",labels:r?.[l.id],getOptions:p,locale:d,onChange:(k)=>n({...t,[l.id]:k||null}),...R}):l.type==="linkedRecord"?z(oo,{...d?{locale:d}:{},field:l,value:t[l.id],labels:r?.[l.id],client:i,onChange:(k)=>n({...t,[l.id]:k}),...R}):l.type==="checkbox"?z("input",{id:`${m}-${l.id}`,"aria-label":`${l.name}${l.required?" *":""}`,type:"checkbox",checked:t[l.id]===!0,onChange:(k)=>n({...t,[l.id]:k.target.checked}),...R}):l.type==="singleSelect"&&s?.Select?z(Pe,{ui:s,label:`${l.name}${l.required?" *":""}`,...R,value:String(t[l.id]??""),options:[{value:"",label:u("Choose…")},...(l.options??[]).map((k)=>({value:k.id,label:k.name}))],onChange:(k)=>n({...t,[l.id]:k||null})}):l.type==="multipleSelect"&&s?.MultiSelect?z(s.MultiSelect,{"aria-label":`${l.name}${l.required?" *":""}`,...R,options:(l.options??[]).map((k)=>({value:k.id,label:k.name,slot:Rn(l.options,k.id)})),values:Array.isArray(t[l.id])?t[l.id]:[],placeholder:u("Choose…"),onChange:(k)=>n({...t,[l.id]:k})}):l.type==="singleSelect"||l.type==="multipleSelect"?re("select",{id:`${m}-${l.id}`,"aria-label":`${l.name}${l.required?" *":""}`,...R,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:(k)=>n({...t,[l.id]:l.type==="multipleSelect"?Array.from(k.target.selectedOptions,(A)=>A.value):k.target.value||null}),children:[l.type==="singleSelect"&&z("option",{value:"",children:u("Choose…")}),l.options?.map((k)=>z("option",{value:k.id,children:k.name},k.id))]}):l.type==="date"&&s?.DatePicker?(()=>{let k={kind:Xr(l),timeZone:Me(l)?.timeZone},A=String(t[l.id]??"");return z(s.DatePicker,{id:`${m}-${l.id}`,"aria-label":`${l.name}${l.required?" *":""}`,...R,value:ho(A,k),withTime:k.kind==="auto"?pt(A):k.kind==="datetime",fixedKind:k.kind!=="auto",clearable:!l.required,onChange:(E)=>n({...t,[l.id]:E?Co(E,A,k):null})})})():l.type==="hyperlink"?z(Nn,{field:l,id:`${m}-${l.id}`,ariaLabel:`${l.name}${l.required?" *":""}`,describedBy:R["aria-describedby"],invalid:Boolean(v),locale:d,inputClassName:"min-h-9 min-w-0 rounded-md border bg-background p-2",text:typeof t[l.id]==="string"?String(t[l.id]):cn(Ot(t[l.id])?t[l.id]:null),onChange:(k)=>{let A=k.trim().startsWith("{")?Pt(k):null;n({...t,[l.id]:A??(k||null)})}}):l.type==="longText"?z("textarea",{id:`${m}-${l.id}`,"aria-label":`${l.name}${l.required?" *":""}`,...R,className:"rounded-md border bg-background p-2",value:String(t[l.id]??""),onChange:(k)=>n({...t,[l.id]:k.target.value||null})}):z("input",{id:`${m}-${l.id}`,"aria-label":`${l.name}${l.required?" *":""}`,...R,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:(k)=>n({...t,[l.id]:k.target.value===""?null:l.type==="number"?Number(k.target.value):l.type==="date"&&t[l.id]?Dn(t[l.id],k.target.value):k.target.value})}),v?z("span",{id:f,className:"text-xs text-red-600",children:v}):null]},l.id)})})}function _a(e,t,n){if(t==="isEmpty")return;let i=Ne(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(Ne(e)&&!xt(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 up({fields:e,view:t,onChange:n,onError:i}){let o=e.filter(xt),[r,a]=pr(o[0]?.id??""),d=o.some((g)=>g.id===r)?r:o[0]?.id??"",[s,c]=pr("contains"),u=d?(()=>{let g=e.find((v)=>v.id===d);return g&&Ne(g)?g.resultType:g?.type})():void 0,m=u==="number"?["is","isNot","isEmpty"]:u==="date"?["is","isNot","isEmpty","onOrAfter","before"]:["contains","is","isNot","isEmpty"],p=m.includes(s)?s:u==="number"||u==="date"?"is":"contains",[l,C]=pr(""),y=[...t.columnOrder.flatMap((g)=>{let v=e.find((f)=>f.id===g);return v?[v]:[]}),...e.filter((g)=>!t.columnOrder.includes(g.id))];return re("div",{className:"flex flex-wrap items-end gap-3",children:[re("label",{className:"flex min-w-52 flex-col gap-1 text-sm",children:["Search",z("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})})]}),re("form",{className:"flex flex-wrap items-end gap-2",onSubmit:(g)=>{g.preventDefault();let v=e.find((S)=>S.id===d);if(!v)return;let f;try{f=_a(v,p,l)}catch(S){i(S instanceof Error?S.message:"Invalid filter.");return}n({...t,filter:{conjunction:"and",filterSet:[{fieldId:d,operator:p,...p==="isEmpty"?{}:{value:f}}]}})},children:[re("label",{className:"flex flex-col gap-1 text-sm",children:["Filter field",z("select",{className:"h-9 rounded-md border bg-background px-2",value:d,onChange:(g)=>a(g.target.value),children:o.map((g)=>z("option",{value:g.id,children:g.name},g.id))})]}),z("select",{"aria-label":"Filter operator",className:"h-9 rounded-md border bg-background px-2 text-sm",value:p,onChange:(g)=>c(g.target.value),children:m.map((g)=>z("option",{value:g,children:g==="isNot"?"is not":g==="isEmpty"?"is empty":g==="onOrAfter"?"on or after":g},g))}),p!=="isEmpty"&&z("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:l,onChange:(g)=>C(g.target.value)}),z("button",{type:"submit",disabled:!d,children:"Apply filter"}),z("button",{type:"button",onClick:()=>{let g={...t};delete g.filter,n(g)},children:"Clear filter"})]}),re("details",{className:"relative",children:[z("summary",{className:"cursor-pointer rounded-md border px-3 py-2 text-sm",children:"Columns"}),z("div",{className:"absolute right-0 top-full z-10 mt-1 flex max-h-96 min-w-64 flex-col gap-2 overflow-auto rounded-md border bg-background p-3 shadow-md",children:y.map((g,v)=>re("div",{className:"flex items-center gap-2 text-sm",children:[re("label",{className:"flex flex-1 items-center gap-2",children:[z("input",{type:"checkbox",checked:!t.hiddenColumns.includes(g.id),disabled:t.type==="form"&&g.required===!0,onChange:(f)=>n({...t,hiddenColumns:f.target.checked?t.hiddenColumns.filter((S)=>S!==g.id):[...t.hiddenColumns,g.id]})}),g.name]}),z("button",{type:"button","aria-label":`Move ${g.name} left`,disabled:v===0,onClick:()=>{let f=y.map((R)=>R.id),S=f[v-1];if(S!==void 0)[f[v-1],f[v]]=[g.id,S];n({...t,columnOrder:f})},children:"←"}),z("button",{type:"button","aria-label":`Move ${g.name} right`,disabled:v===y.length-1,onClick:()=>{let f=y.map((R)=>R.id),S=f[v+1];if(S!==void 0)[f[v],f[v+1]]=[S,g.id];n({...t,columnOrder:f})},children:"→"})]},g.id))})]})]})}import{useEffect as Ba,useMemo as Oo,useState as Vo}from"react";import{jsx as gr}from"react/jsx-runtime";function Ua(e){switch(e.code){case"empty":return"Choose a count or sum.";case"too_many":return"Use at most three groups and eight summaries.";case"unknown_field":return"That field is not in this collection.";case"not_groupable":return"Group by a text, number, date, checkbox, or single select field.";case"function":return"That summary function is not supported.";case"numeric_field":return"Average only a number field.";case"extrema_field":return"Minimum and maximum need a number or date field.";case"queryable_field":return"Summarize a queryable field.";case"sum_field":return"Sum only a number field.";case"count_field":return"Count a queryable field, or omit the field to count records.";case"alias":return"Each summary needs its own name, different from the group fields.";case"duplicate_group":return"Each group field can be used once."}}function qa(e,t,n){let i=n.unassigned??"Unassigned";if(t===null||t===void 0)return i;if(e?.type==="singleSelect")return e.options?.find((o)=>o.id===t)?.name??String(t);if(e?.type==="checkbox")return t===!0?n.checked??"Checked":n.unchecked??"Unchecked";return typeof t==="string"||typeof t==="number"||typeof t==="boolean"?String(t):i}function _o(e,t,n,i={},o={}){return n.map((r)=>{let a=t.groupBy.map((s)=>{let c=e.fields.find((u)=>u.id===s);return`${c?.name??s} ${qa(c,r.groups[s],o)}`}),d=t.aggregates.map((s)=>{let c=r.values[s.as];return`${i[s.as]??s.as}: ${typeof c==="number"||typeof c==="string"?String(c):o.none??"none"}`});return[...a,...d].join(" · ")})}function $a({descriptor:e,query:t,rows:n}){return gr("ul",{"data-uibot":"collection-aggregate",children:_o(e,t,n).map((i)=>gr("li",{children:i},i))})}function mr({collectionId:e,descriptor:t,view:n,groupBy:i,aggregates:o,client:r,locale:a,labels:d,reloadKey:s=0}){let c=Oo(()=>$r(n,{aggregates:o,...i?{groupBy:i}:{}}),[n,i,o]),u=Oo(()=>j(a),[a]),[m,p]=Vo(u("Loading summary…")),[l,C]=Vo(!1);return Ba(()=>{let b=jr(t,c);if(b){p(u(Ua(b))),C(!0);return}let y=!0;return p(u("Loading summary…")),C(!1),r.aggregate(e,c).then((g)=>{if(!y)return;if(!g.ok){p(g.error.message),C(!0);return}let v=_o(t,c,g.data,d??{},{unassigned:u("Unassigned"),checked:u("Checked"),unchecked:u("Unchecked"),none:u("none")});p(v.length?v.join(" · "):u("No summary rows.")),C(!1)}).catch(()=>{if(!y)return;p(u("The collection service is unavailable.")),C(!0)}),()=>{y=!1}},[r,e,t,c,d,u,s]),gr("p",{role:l?"alert":"status","data-uibot":"collection-aggregate",children:m})}import{jsx as Et,jsxs as Bo}from"react/jsx-runtime";function Uo(e,t){return Object.fromEntries(e?.items.flatMap((n)=>n.op==="update"&&n.id===t?Object.entries(n.values):[])??[])}function fr({fields:e,values:t,serverValues:n,locale:i}){let o=j(i);return Et("div",{"data-uibot":"collection-field-changes",style:{display:"grid",gap:8,margin:"8px 0"},children:Object.entries(t).flatMap(([r,a])=>{let d=e.find((c)=>c.id===r);if(!d)return[];let s=(c)=>d.type==="checkbox"&&typeof c==="boolean"?o(c?"Checked":"Unchecked"):$t(c,d)||"—";return Bo("div",{style:{border:"1px solid var(--border,#d5d9df)",borderRadius:6,padding:8},children:[Et("strong",{children:d.name}),n?Bo("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"minmax(90px,auto) minmax(0,1fr)",gap:4},children:[Et("dt",{children:o("Your edit")}),Et("dd",{style:{margin:0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:s(a)}),Et("dt",{children:o("Server value")}),Et("dd",{style:{margin:0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:s(n[r])})]}):Et("p",{style:{margin:0,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:s(a)})]},r)})})}var $o=["grid","kanban","gallery","calendar","form"],ja=["grid","form"],yr={search:!0,filter:!0,columns:!0,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!0,tableList:!0,viewManagement:!0,export:!0},za={search:!0,filter:!1,columns:!1,rowCreate:!0,rowUpdate:!0,rowDelete:!0,schemaEditor:!1,tableList:!1,viewManagement:!1,export:!1},Ha={search:!0,filter:!0,columns:!0,rowCreate:!1,rowUpdate:!1,rowDelete:!1,schemaEditor:!1,tableList:!0,viewManagement:!1,export:!0},qo={fieldTypeIcons:!1,optionChips:!1,groupBy:!1,groupCollapse:!1,autoHeight:!1,sorting:!0,columnResize:!0,columnReorder:!1,columnFreezing:!1,columnColors:!1,footerStats:!1,recordContextMenu:!1,optimisticEdit:!1,viewTypes:$o},br={fieldTypeIcons:!0,optionChips:!0,groupBy:!0,groupCollapse:!0,autoHeight:!0,sorting:!0,columnResize:!0,columnReorder:!0,columnFreezing:!0,columnColors:!0,footerStats:!0,recordContextMenu:!0,optimisticEdit:!0,viewTypes:$o},Ka={basic:{...qo,...yr},full:{...br,...yr},simple:{...qo,...za,viewTypes:ja},workbench:{...br,...yr},readonly:{...br,...Ha,recordContextMenu:!1,optimisticEdit:!1}};function qe(e){let{preset:t="basic",...n}=e??{},i={...Ka[t],...Wa(n)};return i.groupBy?i:{...i,groupCollapse:!1}}function Wa(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}import{jsx as J,jsxs as Oe,Fragment as xr}from"react/jsx-runtime";function Jt(e){if(!e.aggregate)return null;return J(mr,{collectionId:e.descriptor.id,descriptor:e.descriptor,view:e.view,...e.aggregate.groupBy?{groupBy:e.aggregate.groupBy}:{},aggregates:e.aggregate.aggregates,client:e.aggregate.client,...e.aggregate.labels?{labels:e.aggregate.labels}:{},...e.locale?{locale:e.locale}:{},...e.reloadKey!==void 0?{reloadKey:e.reloadKey}:{}})}var se={padding:"6px 10px",border:"1px solid var(--border, #d5d9df)",borderRadius:5,background:"var(--background, white)",color:"inherit",cursor:"pointer"},Ke={padding:12,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)"},Bn={items:[],total:0,nextCursor:null,limit:50};function Zt(e,t,n=!0){let i=JSON.stringify([e.descriptor.id,e.descriptor.schemaVersion,t]),[o,r]=$e({key:i,history:[]}),a=o.key===i?o.cursor:void 0,d=o.key===i?o.history:[],s=JSON.stringify([i,a]),[c,u]=$e(0),[m,p]=$e({key:s,page:Bn,loading:n,error:null});Un(()=>{let b=!0;if(!n){p({key:s,page:Bn,loading:!1,error:null});return}p((v)=>({key:s,page:v.key===s?v.page:Bn,loading:!0,error:null}));let[y,,g]=JSON.parse(i);return e.client.query(y,{...g,...a?{cursor:a}:{}}).then((v)=>{if(!b)return;if(v.ok)p({key:s,page:v.data,loading:!1,error:null});else p((f)=>({...f,loading:!1,error:v.error}))}).catch(()=>{if(b)p((v)=>({...v,loading:!1,error:{message:"Collection query failed. Retry to load records."}}))}),()=>{b=!1}},[s,i,a,e.client,e.reloadKey,n,c]);let l=m.key===s?m.page:Bn,C=m.key===s?m.error:null;return{page:l,loading:n&&(m.key!==s||m.loading),error:C?C.code?no(C,e.locale):j(e.locale)(C.message):"",previous:d.length?()=>r({key:i,cursor:d.at(-1),history:d.slice(0,-1)}):void 0,next:l.nextCursor?()=>r({key:i,cursor:l.nextCursor??void 0,history:[...d,a]}):void 0,retry:()=>u((b)=>b+1),pageNumber:d.length+1}}function hr(e,t,n,i){return n>=t?e("{count} records total",{count:t.toLocaleString(i)}):e("{total} records · {loaded} loaded",{total:t.toLocaleString(i),loaded:n})}function Ya({hasPrevious:e,hasNext:t,onPrevious:n,onNext:i,loading:o,page:r,locale:a,ui:d}){let s=j(a);if(!e&&!t)return null;return Oe("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[J(Y,{ui:d,style:se,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:s("Previous page"),disabled:!e||o,onClick:n}),r?J("span",{style:{fontSize:12},children:s("Page {page}",{page:r})}):null,J(Y,{ui:d,style:se,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:s("Next page"),disabled:!t||o,onClick:i})]})}function Qt({state:e,locale:t,ui:n,hideCount:i}){let o=j(t);return Oe("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[i?null:J("span",{children:hr(o,e.page.total,e.page.items.length,t)}),J(Ya,{hasPrevious:Boolean(e.previous),hasNext:Boolean(e.next),onPrevious:e.previous,onNext:e.next,loading:e.loading,page:e.pageNumber,locale:t,ui:n}),e.loading&&J("span",{role:"status",children:o("Loading records…")}),e.error&&Oe(xr,{children:[J("span",{role:"alert",children:e.error}),J(Y,{ui:n,style:se,variant:"outline",size:"sm",disabled:e.loading,onClick:e.retry,children:o("Retry query")})]})]})}function Cr(e){let t=kn(e.client,e.descriptor.id),n=j(e.locale),[i,o]=$e(!1),[r,a]=$e(""),[d,s]=$e(null),c=Gt(null),u=Gt(e);u.current=e;let m=(b)=>{if(!b||u.current.readOnly)return!1;let y=qe(u.current.features),g={insert:y.rowCreate,update:y.rowUpdate,delete:y.rowDelete};return b.items.every((v)=>g[v.op])};_t({dirty:Boolean(c.current),busy:i});let p=()=>{c.current=null,a(""),s(null)};return{saving:i,error:r,setError:a,remote:d,pending:c,reset:p,commit:async(b)=>{if(i||!t.active||!m(b))return!1;c.current=b,o(!0),a(""),s(null);let y=await e.client.mutate(e.descriptor.id,b).catch(()=>({ok:!1,error:{code:"unavailable",status:503,message:n("Saving failed. Your change has been kept.")}}));if(!t.active)return!1;if(o(!1),y.ok)return p(),e.onCommitted(y.data),!0;a(Sn(y.error,e.locale));let g=y.error.details?.current;if(g&&typeof g.id==="string"&&Number.isSafeInteger(g.version)&&g.version>0)s(g);return!1},retryRequest:()=>c.current&&d?{idempotencyKey:crypto.randomUUID(),items:c.current.items.map((b)=>b.op!=="insert"&&b.id===d.id?{...b,expectedVersion:d.version}:b)}:c.current,canRetry:m(c.current),fields:ut(e.descriptor.fields,e.view)}}function vr({mutation:e,onRetry:t,locale:n,ui:i}){let o=j(n);return Oe(xr,{children:[e.error&&J("p",{role:"alert",children:e.error}),e.pending.current&&!e.canRetry&&J("p",{role:"status",children:o("You do not have permission to make this change.")}),e.remote&&Oe("div",{style:Ke,children:[J("strong",{children:o("Current server version {version}",{version:e.remote.version})}),J(fr,{fields:e.fields,values:Uo(e.pending.current,e.remote.id),serverValues:e.remote.values,locale:n}),J(Y,{ui:i,style:se,variant:"outline",size:"sm",disabled:e.saving||!e.canRetry,onClick:t,children:o("Retry against current version")})]})]})}function Tt({row:e,onClose:t,onCancel:n,onDirtyChange:i,onBusyChange:o,stickyActions:r,...a}){let d=j(a.locale),s=qe(a.features),c=!a.readOnly&&s.rowDelete,u=!a.readOnly&&s.rowUpdate,m=Gt(e.values),[p,l]=$e(()=>({...m.current})),[C,b]=$e(!1);_t({dirty:JSON.stringify(p)!==JSON.stringify(m.current),busy:!1});let y=Gt(null),[g,v]=$e(!1);Un(()=>{y.current?.focus()},[]);let f=Cr(a),S=ut(a.descriptor.fields,a.view),R=JSON.stringify(p)!==JSON.stringify(e.values);Un(()=>{i?.(R)},[R,i]),Un(()=>{o?.(f.saving)},[f.saving,o]);let k=async(E=!1)=>{b(!0);try{let T=E?f.retryRequest():f.pending.current;if(!T){let V=S.filter((x)=>x.type!=="lookup"&&x.type!=="formula"&&x.type!=="rollup"&&JSON.stringify(p[x.id])!==JSON.stringify(e.values[x.id]));if(!V.length){f.setError(d("Change a field before saving."));return}let h=gn(V,p,d,a.locale);T={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:e.id,expectedVersion:e.version,values:h}]}}if(await f.commit(T))t()}catch(T){f.setError(T instanceof Error?T.message:d("Invalid value"))}},A=async()=>{let E=f.pending.current?.items[0]?.op==="delete"?f.pending.current:{idempotencyKey:crypto.randomUUID(),items:[{op:"delete",id:e.id,expectedVersion:e.version}]};if(await f.commit(E))t()};return Oe("div",{ref:y,tabIndex:-1,onKeyDown:(E)=>{if(E.key==="Escape"&&!f.saving)E.stopPropagation(),(n??t)()},role:"dialog","aria-label":d("{name} record",{name:ze(e,a.descriptor.fields)}),style:{...Ke,marginTop:12},children:[J("h3",{children:ze(e,a.descriptor.fields)}),a.onInspectRecord&&J(Y,{ui:a.ui,style:se,variant:"outline",size:"sm",disabled:f.saving,onClick:()=>a.onInspectRecord?.(e.id),children:d("Open record activity")}),Oe("form",{onSubmit:(E)=>{E.preventDefault(),k()},children:[J("fieldset",{disabled:f.saving||g||!u,style:{border:0,padding:0},children:J(Dt,{fields:S,values:p,submitted:C,...a.locale?{locale:a.locale}:{},...a.ui?{ui:a.ui}:{},relationClient:a.client,getRelationOptions:a.getRelationOptions,linkedRecords:e.linkedRecords,computedErrors:e.computedErrors,onChange:(E)=>{l(E),f.reset()}})}),Oe("div",{"data-uibot":"record-editor-actions",style:r?{position:"sticky",bottom:0,zIndex:1,display:"flex",gap:8,alignItems:"center",padding:"12px 0",borderTop:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",background:"var(--background, white)"}:void 0,children:[u&&J("button",{type:"submit",style:{...se,...Kt},disabled:f.saving||g,children:f.saving?d("Saving…"):d("Save record")}),r?null:J("button",{type:"button",style:se,disabled:f.saving,onClick:n??t,children:d("Close record")}),r&&c?J("span",{style:{marginLeft:"auto"},children:J(Y,{ui:a.ui,variant:"ghost",size:"sm",icon:"trash",disabled:f.saving,onClick:()=>v(!0),children:d("Delete record")})}):null]})]}),c&&!r&&J("button",{type:"button",style:se,disabled:f.saving,onClick:()=>v(!0),children:d("Delete record")}),g&&a.ui?.ConfirmDialog?a.ui.ConfirmDialog({open:!0,destructive:!0,title:d("Delete this record?"),description:d(c?"Delete this record? Your unsaved changes will be discarded after deletion.":"You do not have permission to make this change."),confirmLabel:d("Delete"),cancelLabel:d("Cancel"),busy:f.saving,confirmDisabled:!c,onConfirm:()=>void A(),onCancel:()=>{if(v(!1),f.pending.current?.items[0]?.op==="delete")f.reset()}}):null,g&&!a.ui?.ConfirmDialog&&Oe(Ro,{alert:!0,label:d("Confirm record deletion"),busy:f.saving,onCancel:()=>{if(v(!1),f.pending.current?.items[0]?.op==="delete")f.reset()},children:[J("p",{children:d("Delete this record? Your unsaved changes will be discarded after deletion.")}),!c&&J("p",{role:"status",children:d("You do not have permission to make this change.")}),J("button",{type:"button",style:se,disabled:f.saving||!c,onClick:()=>void A(),children:d("Confirm deletion")}),J("button",{type:"button",style:se,disabled:f.saving,onClick:()=>{if(v(!1),f.pending.current?.items[0]?.op==="delete")f.reset()},children:d("Cancel deletion")})]}),J(vr,{mutation:f,onRetry:()=>void k(!0),locale:a.locale,ui:a.ui})]})}function Ga(e){let t=j(e.locale),n=!e.readOnly&&qe(e.features).rowCreate,i=Gt(null),o=ut(e.descriptor.fields,{...e.view,hiddenColumns:e.view.hiddenColumns.filter((y)=>!e.descriptor.fields.find((g)=>g.id===y)?.required)}),r=()=>({...Object.fromEntries(o.filter((y)=>y.type==="checkbox").map((y)=>[y.id,!1])),...an(o)}),a=Gt(r()),[d,s]=$e(a.current),[c,u]=$e(!1),[m,p]=$e(!1);_t({dirty:JSON.stringify(d)!==JSON.stringify(a.current),busy:!1});let l=Cr(e),C=()=>i.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")?.focus(),b=async()=>{if(!n)return;p(!0);try{let y=l.pending.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:gn(o,d,t,e.locale)}]};if(await l.commit(y))a.current=r(),s(a.current),u(!0),p(!1),requestAnimationFrame(C)}catch(y){l.setError(y instanceof Error?y.message:t("Invalid value"))}};return Oe("section",{"data-uibot":"collection-form",style:Ke,children:[J("h3",{children:e.view.name}),e.readOnly&&J("p",{children:t("Record creation requires editor permission.")}),Oe("form",{ref:i,onSubmit:(y)=>{y.preventDefault(),b()},children:[J("fieldset",{disabled:l.saving||!n,style:{border:0,padding:0},children:J(Dt,{fields:o,values:d,submitted:m,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},relationClient:e.client,getRelationOptions:e.getRelationOptions,onChange:(y)=>{s(y),u(!1),l.reset()}})}),n&&J("button",{type:"submit",style:{...se,...Kt},disabled:l.saving,children:l.saving?t("Creating…"):t("Create record")})]}),J(vr,{mutation:l,onRetry:()=>void b(),locale:e.locale,ui:e.ui}),c?Oe("p",{role:"status",children:[t("Record created. Add another below."),e.onShowRecords?Oe(xr,{children:[" ",J(Y,{ui:e.ui,style:se,variant:"outline",size:"sm",onClick:e.onShowRecords,children:t("Show records")})]}):null]}):null]})}function qn(e){let[t,n]=$e(null),i=Cr(e),o=!e.readOnly&&qe(e.features).rowUpdate;return{intent:t,mutation:i,move:async(d,s)=>{if(!o||i.saving||t)return;n({row:d,values:s});let c={idempotencyKey:crypto.randomUUID(),items:[{op:"update",id:d.id,expectedVersion:d.version,values:s}]};if(await i.commit(c))n(null)},retry:async()=>{let d=i.retryRequest();if(d&&await i.commit(d))n(null)},cancel:()=>{n(null),i.reset()},blocked:i.saving||!!t}}function $n({state:e,locale:t,ui:n}){let i=j(t);if(!e.intent)return null;return Oe("div",{role:"dialog","aria-label":i("Pending record move"),style:Ke,children:[J("p",{children:e.mutation.saving?i("Moving record…"):i("The move has been kept for retry.")}),!e.mutation.remote&&J(fr,{fields:e.mutation.fields,values:e.intent.values,locale:t}),J(vr,{mutation:e.mutation,onRetry:()=>void e.retry(),locale:t,ui:n}),!e.mutation.remote&&J(Y,{ui:n,style:se,variant:"outline",size:"sm",disabled:e.mutation.saving||!e.mutation.canRetry,onClick:()=>void e.retry(),children:i("Retry move")}),J(Y,{ui:n,style:se,variant:"outline",size:"sm",disabled:e.mutation.saving,onClick:e.cancel,children:i("Cancel move")})]})}import{useEffect as Xa,useMemo as zo,useRef as es,useState as ts}from"react";var Ja={"zh-CN":{is:"等于",isNot:"不等于",contains:"包含",notContains:"不包含",isEmpty:"为空",isNotEmpty:"不为空",gt:"大于",gte:"大于等于",lt:"小于",lte:"小于等于",before:"早于",after:"晚于",onOrBefore:"不晚于",onOrAfter:"不早于"},en:{is:"is",isNot:"is not",contains:"contains",notContains:"does not contain",isEmpty:"is empty",isNotEmpty:"is not empty",gt:">",gte:"≥",lt:"<",lte:"≤",before:"is before",after:"is after",onOrBefore:"is on or before",onOrAfter:"is on or after"}},Za={"zh-CN":{is:"恰好是",isNot:"不是恰好",contains:"包含任一",notContains:"不包含任一"},en:{is:"is exactly",isNot:"is not exactly",contains:"has any of",notContains:"has none of"}},Qa={"zh-CN":{exactDate:"指定日期",dateRange:"日期区间",today:"今天",yesterday:"昨天",tomorrow:"明天",currentWeek:"本周",lastWeek:"上周",nextWeek:"下周",currentMonth:"本月",lastMonth:"上月",nextMonth:"下月",currentYear:"今年",lastYear:"去年",nextYear:"明年",pastDays:"过去 N 天",nextDays:"未来 N 天",daysAgo:"N 天前",daysFromNow:"N 天后"},en:{exactDate:"exact date",dateRange:"date range",today:"today",yesterday:"yesterday",tomorrow:"tomorrow",currentWeek:"this week",lastWeek:"last week",nextWeek:"next week",currentMonth:"this month",lastMonth:"last month",nextMonth:"next month",currentYear:"this year",lastYear:"last year",nextYear:"next year",pastDays:"past N days",nextDays:"next N days",daysAgo:"N days ago",daysFromNow:"N days from now"}},jn=(e,t="en",n)=>{if(n&&Ye(n)==="multipleSelect"){let i=Za[t][e];if(i)return i}return Ja[t][e]??e},zn=(e,t="en")=>Qa[t][e]??e;function kr(e,t){if(!t)return"";let n=e?Me(e):void 0;return n?Bt(t,{...n,time:"none"}):t}function jo(e,t,n="en"){let i=n==="zh-CN";return e.filterSet.map((o)=>{if("filterSet"in o)return`(${jo(o,t,n)})`;let r=t.find((c)=>c.id===o.fieldId),a=jn(o.operator,n,r);if(o.operator==="isEmpty"||o.operator==="isNotEmpty")return`${r?.name??o.fieldId} ${a}`;let d=(c)=>r?.options?.find((u)=>u.id===c)?.name??String(c??""),s;if(tr(o.value)){let c=o.value,u=zn(c.mode,n);s=c.mode==="exactDate"?kr(r,c.date):c.mode==="dateRange"?`${kr(r,c.date)} ~ ${kr(r,c.to)}`:c.days!==void 0?u.replace("N",String(c.days)):u}else s=Array.isArray(o.value)?o.value.map(d).join(i?"、":", "):d(o.value);return`${r?.name??o.fieldId} ${a} ${s}`}).join(e.conjunction==="or"?i?" 或 ":" OR ":i?" 且 ":" AND ")}import{jsx as ie,jsxs as tt,Fragment as Yo}from"react/jsx-runtime";var ns={text:["is","isNot","contains","isEmpty"],number:["is","isNot","gte","lte","isEmpty"],checkbox:["is"],date:["is","isNot","before","onOrAfter","isEmpty"],singleSelect:["is","isNot","isEmpty"],multipleSelect:["is","contains","isEmpty"]};function Xt(e){return ie("span",{style:pe.cell,children:ie(Pe,{...e})})}var Hn=()=>`row_${Math.random().toString(36).slice(2,10)}`,rs=(e)=>("filterSet"in e),os=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}};function Pr(e,t){if(t)return Yr(e);let n=Ye(e);return n?ns[n]??[]:[]}function wr(e,t,n){if(Vt.has(t))return;let i=Ye(e);if(i==="date"&&n)return{mode:"today",timeZone:Me(e)?.timeZone??os()};if(i==="checkbox")return!0;if(i==="multipleSelect")return[];return i==="number"?void 0:""}function Ho(e){let t=[],n=[];for(let i of e?.filterSet??[])if(rs(i))n.push({key:Hn(),node:i});else t.push({key:Hn(),fieldId:i.fieldId,operator:i.operator,value:i.value});return{rows:t,groups:n,conjunction:e?.conjunction??"and"}}function Ko(e,t,n,i){let o=[],r=!0;for(let s of t){let c=e.find((p)=>p.id===s.fieldId);if(!c||!s.operator){r=!1;continue}let u=s.value===""||Array.isArray(s.value)&&s.value.length===0;if(!Vt.has(s.operator)&&u){r=!1;continue}let m={fieldId:s.fieldId,operator:s.operator,...Vt.has(s.operator)?{}:{value:s.value}};if(Gr(c,m))r=!1;else o.push(m)}let a=n.map((s)=>s.node).filter((s)=>Boolean(s?.filterSet.length)),d=[...o,...a];return{node:d.length?{conjunction:i,filterSet:d}:void 0,complete:r}}function Kn(e){let{ui:t,locale:n}=e,i=e.advanced!==!1,o=e.allowGroups!==!1,r=zo(()=>j(n),[n]),a=zo(()=>e.fields.filter((b)=>!Ne(b)&&Ye(b)!==null),[e.fields]),[d,s]=ts(()=>Ho(e.filter)),c=es(JSON.stringify(e.filter??null));Xa(()=>{let b=JSON.stringify(e.filter??null);if(b!==c.current)c.current=b,s(Ho(e.filter))},[e.filter]);let u=(b)=>{s(b);let{node:y}=Ko(a,b.rows,b.groups,b.conjunction),g=JSON.stringify(y??null);if(g!==c.current)c.current=g,e.onChange(y)},m=(b,y)=>u({...d,rows:d.rows.map((g)=>g.key===b?{...g,...y}:g)}),p=()=>{let b=a[0];if(!b)return;let y=Pr(b,i)[0]??"";u({...d,rows:[...d.rows,{key:Hn(),fieldId:b.id,operator:y,value:y?wr(b,y,i):void 0}]})},l=()=>u({...d,groups:[...d.groups,{key:Hn(),node:void 0}]}),C=Ko(a,d.rows,d.groups,d.conjunction).complete===!1||d.groups.some((b)=>b.node===void 0);return tt("div",{"data-uibot-filter-builder":"",style:pe.root,children:[d.rows.length+d.groups.length>1?tt("div",{style:pe.inline,children:[ie("span",{children:r("Match")}),ie(Xt,{ui:t,label:r("Filter conjunction"),style:pe.control,value:d.conjunction,options:[{value:"and",label:r("all conditions")},{value:"or",label:r("any condition")}],onChange:(b)=>u({...d,conjunction:b==="or"?"or":"and"})})]}):null,d.rows.map((b,y)=>{let g=a.find((S)=>S.id===b.fieldId),v=g?Ye(g):null,f=g?Pr(g,i):[];return tt("fieldset",{"aria-label":r("Condition {index}",{index:y+1}),style:{...pe.condition,margin:0,padding:0,border:0,minWidth:0},children:[ie("span",{style:pe.slot,children:ie(Xt,{ui:t,label:r("Filter field"),style:pe.control,value:b.fieldId,options:a.map((S)=>({value:S.id,label:S.name})),onChange:(S)=>{let R=a.find((T)=>T.id===S);if(!R)return;let k=Pr(R,i),A=k.includes(b.operator)?b.operator:k[0]??"",E=Ye(R)===v;m(b.key,{fieldId:S,operator:A,value:A&&!(E&&A===b.operator)?wr(R,A,i):b.value})}})}),ie("span",{style:pe.slot,children:ie(Xt,{ui:t,label:r("Filter operator"),style:pe.control,value:b.operator,options:f.map((S)=>({value:S,label:jn(S,n??"en",g)})),onChange:(S)=>{if(!g)return;let R=S;m(b.key,{operator:R,value:wr(g,R,i)})}})}),g&&b.operator&&!Vt.has(b.operator)?ie("span",{style:pe.slot,children:ie(is,{field:g,row:b,advanced:i,t:r,props:e,onValue:(S)=>m(b.key,{value:S})})}):null,ie(Y,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove condition {index}",{index:y+1}),title:r("Remove condition {index}",{index:y+1}),style:{flex:"0 0 auto"},onClick:()=>u({...d,rows:d.rows.filter((S)=>S.key!==b.key)})})]},b.key)}),o?d.groups.map((b,y)=>tt("fieldset",{"aria-label":r("Condition group {index}",{index:y+1}),style:pe.group,children:[tt("div",{style:pe.groupHead,children:[ie("strong",{style:{fontSize:13},children:r("Condition group {index}",{index:y+1})}),ie(Y,{ui:t,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove group {index}",{index:y+1}),title:r("Remove group {index}",{index:y+1}),onClick:()=>u({...d,groups:d.groups.filter((g)=>g.key!==b.key)})})]}),ie(Kn,{fields:e.fields,filter:b.node,allowGroups:!1,advanced:i,...n?{locale:n}:{},...t?{ui:t}:{},...e.renderCellEditor?{renderCellEditor:e.renderCellEditor}:{},...e.getRelationOptions?{getRelationOptions:e.getRelationOptions}:{},onChange:(g)=>u({...d,groups:g?d.groups.map((v)=>v.key===b.key?{...v,node:g}:v):d.groups.filter((v)=>v.key!==b.key)})})]},b.key)):d.groups.length?tt("p",{style:pe.hint,children:[r("{count} grouped conditions are kept.",{count:d.groups.length})," ",ie(Y,{ui:t,variant:"ghost",size:"sm",onClick:()=>u({...d,groups:[]}),children:r("Remove")})]}):null,C?ie("p",{role:"status",style:pe.hint,children:r("Finish the highlighted condition to apply it.")}):null,tt("div",{style:pe.inline,children:[ie(Y,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:a.length===0,onClick:p,children:r("Add condition")}),o?ie(Y,{ui:t,variant:"outline",size:"sm",icon:"plus",disabled:a.length===0,onClick:l,children:r("Add group")}):null,d.rows.length||d.groups.length?ie(Y,{ui:t,variant:"ghost",size:"sm",onClick:()=>u({rows:[],groups:[],conjunction:"and"}),children:r("Clear filter")}):null]})]})}function is({field:e,row:t,advanced:n,t:i,props:o,onValue:r}){let{ui:a}=o,d=Ye(e),s=i("Filter value"),c=(u,m,p,l)=>o.renderCellEditor?.({...o.getRelationOptions?{getRelationOptions:o.getRelationOptions}:{},field:{...e,...l,required:!1},text:u,disabled:!1,mode:"filter",label:p,autoOpen:!1,onChange:m,onSave:()=>{},onCancel:()=>m("")});if(d==="number")return ie("input",{"aria-label":s,type:"number",step:"any",style:pe.control,value:typeof t.value==="number"?String(t.value):"",onChange:(u)=>{let m=u.currentTarget.value;r(m===""||!Number.isFinite(Number(m))?void 0:Number(m))}});if(d==="text")return ie("input",{"aria-label":s,style:pe.control,value:typeof t.value==="string"?t.value:"",onChange:(u)=>r(u.currentTarget.value)});if(d==="checkbox")return ie(Xt,{ui:a,label:s,style:pe.control,value:t.value===!1?"false":"true",options:[{value:"true",label:i("Yes")},{value:"false",label:i("No")}],onChange:(u)=>r(u==="true")});if(d==="singleSelect"||d==="multipleSelect"){let u=Array.isArray(t.value)?t.value.join(","):typeof t.value==="string"?t.value:"",m=c(u,(l)=>r(d==="multipleSelect"?l.split(",").filter(Boolean):l),s);if(m)return m;if(d==="singleSelect")return ie(Xt,{ui:a,label:s,style:pe.control,value:u,options:[{value:"",label:i("Choose option")},...(e.options??[]).map((l)=>({value:l.id,label:l.name}))],onChange:r});let p=new Set(u.split(",").filter(Boolean));return ie("fieldset",{"aria-label":s,style:{...pe.inline,margin:0,padding:0,border:0},children:(e.options??[]).map((l)=>tt("label",{style:pe.inline,children:[ie("input",{type:"checkbox",checked:p.has(l.id),onChange:(C)=>{let b=new Set(p);if(C.currentTarget.checked)b.add(l.id);else b.delete(l.id);r([...b])}}),l.name]},l.id))})}if(d==="relation"){let u=typeof t.value==="string"?t.value:"";return c(u,r,s)??ie(Tn,{field:e,value:u,onChange:r,label:s,getOptions:o.getRelationOptions,locale:o.locale})}if(d==="date"){if(!n||typeof t.value==="string"){let u=typeof t.value==="string"?t.value:"";return c(u,r,s)??ie("input",{"aria-label":s,type:"date",style:pe.control,value:u.slice(0,10),onChange:(m)=>r(m.currentTarget.value)})}return ie(as,{field:e,value:t.value,t:i,props:o,custom:c,onValue:r})}return null}function as({field:e,value:t,t:n,props:i,custom:o,onValue:r}){let a=t??{mode:"today"},d=(u)=>r({...a,...u}),s=(u,m,p)=>o(m??"",(l)=>p(l.slice(0,10)),u,{formatting:{date:"YYYY-MM-DD",time:"none"}})??ie("input",{"aria-label":u,type:"date",style:pe.control,value:m??"",onChange:(l)=>p(l.currentTarget.value)}),c=(u)=>{let{date:m,to:p,days:l,...C}=a;r({...C,mode:u,...vn.has(u)?{days:7}:{}})};return tt(Yo,{children:[ie(Xt,{ui:i.ui,label:n("Date mode"),style:pe.control,value:a.mode,options:er.map((u)=>({value:u,label:zn(u,i.locale??"en")})),onChange:(u)=>c(u)}),a.mode==="exactDate"?s(n("Filter value"),a.date,(u)=>d({date:u})):null,a.mode==="dateRange"?tt(Yo,{children:[s(n("From date"),a.date,(u)=>d({date:u})),s(n("To date"),a.to,(u)=>d({to:u}))]}):null,vn.has(a.mode)?ie("input",{"aria-label":n("Number of days"),type:"number",min:0,step:1,style:{...pe.control,width:84},value:a.days??"",onChange:(u)=>{let m=u.currentTarget.value;if(m===""){let{days:p,...l}=a;r(l)}else d({days:Number(m)})}}):null,ie("span",{style:pe.hint,children:Me(e)?.timeZone??a.timeZone??""})]})}var Wo="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",pe={group:{margin:0,minWidth:0,display:"grid",gap:8,padding:10,border:`1px solid ${Wo}`,borderRadius:8},groupHead:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},cell:{flex:"1 1 120px",minWidth:0,display:"flex"},condition:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},slot:{display:"flex",minWidth:0,flex:"1 1 120px"},root:{display:"grid",gap:8},row:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},inline:{display:"inline-flex",flexWrap:"wrap",alignItems:"center",gap:6},control:{width:"100%",minWidth:0,minHeight:30,padding:"0 8px",border:`1px solid ${Wo}`,borderRadius:6,background:"transparent",color:"inherit",font:"inherit"},hint:{margin:0,fontSize:12,opacity:0.7}};import{jsx as me,jsxs as st,Fragment as ls}from"react/jsx-runtime";var Rr={display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},Sr={minHeight:30,padding:"0 8px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit"};function Go({fields:e,view:t,onChange:n,locale:i,ui:o,editor:r}){return me("div",{"data-uibot-view-filter":"",children:me(Kn,{fields:e,filter:t.filter,locale:i,ui:o,renderCellEditor:r?.renderCellEditor,getRelationOptions:r?.getRelationOptions,advanced:r?.advanced,onChange:(a)=>{if(a)n({...t,filter:a});else{let{filter:d,...s}=t;n(s)}}})})}var ss=10;function Jo({fields:e,view:t,onChange:n,locale:i,ui:o}){let r=j(i),a=t.sort??[],d=e.filter((m)=>xt(m)),s=d.filter((m)=>!a.some((p)=>p.fieldId===m.id)),c=(m)=>{if(m.length)n({...t,sort:m});else{let{sort:p,...l}=t;n(l)}},u=(m,p)=>{let l=[...a],[C]=l.splice(m,1);if(C)l.splice(m+p,0,C);c(l)};return st("div",{"data-uibot-view-sort":"",style:{display:"grid",gap:8},children:[a.map((m,p)=>st("fieldset",{"aria-label":r("Sort {index}",{index:p+1}),style:{...Rr,margin:0,padding:0,border:0,minWidth:0},children:[me("span",{style:{flex:"1 1 120px",minWidth:110,display:"flex"},children:me(Pe,{ui:o,label:r("Sort field"),style:Sr,value:m.fieldId,options:d.filter((l)=>l.id===m.fieldId||s.includes(l)).map((l)=>({value:l.id,label:l.name})),onChange:(l)=>c(a.map((C,b)=>b===p?{...C,fieldId:l}:C))})}),me("span",{style:{flex:"0 1 110px",minWidth:90,display:"flex"},children:me(Pe,{ui:o,label:r("Sort direction"),style:Sr,value:m.direction,options:[{value:"asc",label:r("Ascending")},{value:"desc",label:r("Descending")}],onChange:(l)=>c(a.map((C,b)=>b===p?{...C,direction:l}:C))})}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:p===0,ariaLabel:r("Move sort {index} up",{index:p+1}),title:r("Move sort {index} up",{index:p+1}),onClick:()=>u(p,-1),children:" "}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:p===a.length-1,ariaLabel:r("Move sort {index} down",{index:p+1}),title:r("Move sort {index} down",{index:p+1}),onClick:()=>u(p,1),children:" "}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove sort {index}",{index:p+1}),title:r("Remove sort {index}",{index:p+1}),onClick:()=>c(a.filter((l,C)=>C!==p)),children:" "})]},m.fieldId)),st("div",{style:Rr,children:[me(Y,{ui:o,variant:"outline",size:"sm",icon:"plus",disabled:s.length===0||a.length>=ss,onClick:()=>{let m=s[0];if(m)c([...a,{fieldId:m.id,direction:"asc"}])},children:r("Add sort")}),a.length?me(Y,{ui:o,variant:"ghost",size:"sm",onClick:()=>c([]),children:r("Clear sort")}):me("span",{style:{fontSize:12,opacity:0.7},children:r("Default order")})]})]})}function Zo({fields:e,view:t,onChange:n,locale:i,ui:o,bare:r}){let a=j(i),s=[...t.columnOrder.flatMap((m)=>{let p=e.find((l)=>l.id===m);return p?[p]:[]}),...e.filter((m)=>!t.columnOrder.includes(m.id))],c=(m,p)=>{let l=s.map((y)=>y.id),C=l[m],b=l[m+p];if(C===void 0||b===void 0)return;l[m]=b,l[m+p]=C,n({...t,columnOrder:l})},u=st("div",{style:{display:"grid",gap:6,paddingTop:r?0:6,minWidth:0},children:[st("label",{children:[me("input",{type:"checkbox",checked:t.showRowNumber!==!1,onChange:(m)=>n({...t,showRowNumber:m.currentTarget.checked})})," ",a("Show row numbers")]}),st("label",{children:[me("input",{type:"checkbox",checked:t.showRecordId===!0,onChange:(m)=>n({...t,showRecordId:m.currentTarget.checked})})," ",a("Show record IDs")]}),s.map((m,p)=>{let l=!t.hiddenColumns.includes(m.id),C=`${m.name}${m.required?" *":""}`;return st("div",{style:{...Rr,flexWrap:"nowrap",gap:4},children:[me(Y,{ui:o,variant:"ghost",size:"sm",icon:l?"eye":"eyeOff",iconOnly:!0,disabled:t.type==="form"&&m.required===!0,ariaLabel:C,title:a(l?"Hide {name}":"Show {name}",{name:m.name}),onClick:()=>n({...t,hiddenColumns:l?[...t.hiddenColumns,m.id]:t.hiddenColumns.filter((b)=>b!==m.id)})}),me("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:l?1:0.5},children:C}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"chevronUp",iconOnly:!0,disabled:p===0,ariaLabel:a("Move {name} left",{name:m.name}),onClick:()=>c(p,-1)}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"chevronDown",iconOnly:!0,disabled:p===s.length-1,ariaLabel:a("Move {name} right",{name:m.name}),onClick:()=>c(p,1)})]},m.id)})]});if(r)return me("div",{"data-uibot-view-columns":"",children:u});return st("details",{"data-uibot-view-columns":"",children:[me("summary",{children:a("Columns")}),u]})}function Qo({fields:e,view:t,onChange:n,locale:i,ui:o}){let r=j(i),a=e.filter((d)=>d.type==="singleSelect"||d.type==="checkbox");return me("div",{style:{display:"flex",gap:6,alignItems:"center"},children:t.groupByFieldId?st(ls,{children:[me(Ee,{name:"group"}),me(Pe,{ui:o,label:r("Grid grouping field"),style:Sr,value:t.groupByFieldId,options:a.map((d)=>({value:d.id,label:d.name})),onChange:(d)=>n({...t,groupByFieldId:d})}),me(Y,{ui:o,variant:"ghost",size:"sm",icon:"x",iconOnly:!0,ariaLabel:r("Remove grouping"),onClick:()=>{let d={...t};delete d.groupByFieldId,n(d)}})]}):me(Y,{ui:o,variant:"outline",size:"sm",icon:"plus",onClick:()=>{let d=a[0];if(d)n({...t,groupByFieldId:d.id})},children:r("Add grouping")})})}import{useState as mn}from"react";import{jsx as we,jsxs as bt}from"react/jsx-runtime";var fn={table:{label:"Table",path:"M2.5 3.5h11v9h-11zM2.5 7h11M6.5 3.5v9"},users:{label:"People",path:"M6 7.5a2.2 2.2 0 1 0 0-4.4 2.2 2.2 0 0 0 0 4.4zM2 13c0-2.2 1.8-3.6 4-3.6s4 1.4 4 3.6M11 7a1.8 1.8 0 1 0 0-3.6M12 9.6c1.3.3 2.2 1.4 2.2 3"},briefcase:{label:"Business",path:"M2.5 5.5h11v7h-11zM6 5.5v-2h4v2M2.5 9h11"},list:{label:"List",path:"M5.5 4h8M5.5 8h8M5.5 12h8M2.5 4h.01M2.5 8h.01M2.5 12h.01"},calendar:{label:"Schedule",path:"M3 4.5h10V13H3zM3 7.5h10M6 3v3M10 3v3"},package:{label:"Inventory",path:"M8 2.5l5 2.5v6l-5 2.5L3 11V5zM3 5l5 2.5L13 5M8 7.5v6"}},ei="table";function Wn({icon:e,size:t=15,icons:n=fn}){let i=(e?n[e]:void 0)??n[ei]??fn.table;return we("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",width:t,height:t,fill:"none",stroke:"currentColor",strokeWidth:1.4,strokeLinecap:"round",strokeLinejoin:"round",style:{flex:"none"},children:we("path",{d:i?.path??""})})}function ds(e){let t=j(e.locale);return bt("aside",{"data-uibot-table-list":"",style:Ft.root,children:[bt("div",{style:Ft.title,children:[we("span",{children:t("Tables")}),we("span",{children:e.tables.length})]}),we("nav",{"aria-label":t("Tables"),style:Ft.nav,children:e.tables.map((n)=>bt("button",{type:"button","aria-current":n.id===e.activeId?"page":void 0,onClick:()=>e.onSelect(n.id),style:{...Ft.item,...n.id===e.activeId?Ft.active:{}},children:[we(Wn,{icon:n.icon,icons:e.icons??fn}),we("span",{style:Ft.name,children:n.name})]},n.id))}),e.onCreate?we(Y,{ui:e.ui,variant:"ghost",style:Ft.create,disabled:e.createDisabled,onClick:e.onCreate,children:t("New table")}):null]})}function cs(e){let t=j(e.locale),n=e.icons??fn,[i,o]=mn(!1),[r,a]=mn(""),[d,s]=mn(!1),[c,u]=mn(!1),[m,p]=mn(""),l=e.table,C=e.canManage&&Boolean(l)&&!c;async function b(f){u(!0),p("");try{return await f(),!0}catch(S){return p(S instanceof Error?S.message:t("Saving failed. Your edit has been kept.")),!1}finally{u(!1)}}let y=()=>{if(!C||!e.onRename)return;a(l?.name??""),p(""),o(!0)};async function g(){let f=r.trim();if(!f||f===l?.name){o(!1);return}if(await b(()=>e.onRename?.(f)))o(!1)}let v=(f)=>{if(f.key==="Enter"||f.key==="F2")f.preventDefault(),y()};return bt("header",{"data-uibot-table-header":"",style:Qe.root,children:[bt("div",{style:Qe.left,children:[bt("span",{style:{position:"relative"},children:[we("button",{type:"button","aria-label":t("Change table icon"),"aria-haspopup":"menu","aria-expanded":d,title:e.canManage?t("Double click to change the icon"):t("Schema permission required"),disabled:!C||!e.onIconChange,style:Qe.iconButton,onDoubleClick:()=>s(!0),onKeyDown:(f)=>{if(f.key==="Enter"||f.key===" ")f.preventDefault(),s(!0)},children:we(Wn,{icon:l?.icon,size:17,icons:n})}),d?we("div",{role:"menu","aria-label":t("Table icon"),style:Qe.menu,children:Object.entries(n).map(([f,S])=>bt("button",{type:"button",role:"menuitemradio","aria-checked":(l?.icon??ei)===f,title:S.label,style:Qe.menuItem,onClick:()=>{s(!1),b(()=>e.onIconChange?.(f))},children:[we(Wn,{icon:f,icons:n}),we("span",{children:S.label})]},f))}):null]}),bt("div",{style:{minWidth:0},children:[i?we("input",{"aria-label":t("Table name"),value:r,disabled:c,style:Qe.input,autoFocus:!0,onChange:(f)=>a(f.currentTarget.value),onBlur:()=>{if(!m)g()},onKeyDown:(f)=>{if(f.key==="Enter")f.preventDefault(),g();if(f.key==="Escape")f.preventDefault(),o(!1),p("")}}):we("h2",{style:Qe.title,children:we("button",{type:"button","aria-label":t("Rename table {name}",{name:l?.name??""}),title:e.canManage?t("Double click to rename"):t("Schema permission required"),disabled:!C||!e.onRename,style:Qe.titleButton,onDoubleClick:y,onKeyDown:v,children:l?.name??t("Start with a table")})}),m?we("p",{role:"alert",style:Qe.error,children:m}):null,we("p",{style:Qe.summary,children:l?t("{count} fields · {mode}",{count:l.fields.length,mode:e.canWrite?t("Editable"):t("Read only")}):t("Start with a table")})]})]}),we("div",{style:Qe.actions,children:e.actions})]})}var Xo="var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",Ft={root:{display:"grid",gap:8,alignContent:"start",minWidth:180},title:{display:"flex",justifyContent:"space-between",padding:"0 12px",fontSize:12,opacity:0.7},nav:{display:"grid",gap:2},item:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",border:0,borderRadius:6,background:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},active:{background:"var(--uibot-active-bg, color-mix(in srgb, currentColor 10%, transparent))",fontWeight:600},name:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},create:{justifyContent:"flex-start",width:"100%"}},Qe={root:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,padding:"12px 20px"},left:{display:"flex",alignItems:"center",gap:12,minWidth:0},iconButton:{width:32,height:32,display:"grid",placeItems:"center",border:0,borderRadius:8,background:"var(--uibot-active-bg, color-mix(in srgb, currentColor 10%, transparent))",color:"inherit",cursor:"pointer"},menu:{position:"absolute",top:"100%",left:0,zIndex:60,display:"grid",minWidth:150,padding:4,border:`1px solid ${Xo}`,borderRadius:8,background:"var(--background, #fff)"},menuItem:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:0,background:"transparent",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},input:{height:32,width:240,maxWidth:"100%",padding:"0 8px",border:`1px solid ${Xo}`,borderRadius:6,font:"inherit",fontWeight:600},title:{margin:0,fontSize:16,fontWeight:600},titleButton:{maxWidth:"100%",padding:0,border:0,background:"transparent",color:"inherit",font:"inherit",cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},error:{margin:"4px 0 0",fontSize:12,color:"var(--uibot-danger, #b3261e)"},summary:{margin:"2px 0 0",fontSize:12,opacity:0.7},actions:{display:"flex",alignItems:"center",gap:4}};import{useEffect as Ir,useMemo as Ar,useRef as Nt,useState as en}from"react";import{jsx as ht,jsxs as Dr}from"react/jsx-runtime";function us(e,t){if(!t)return"";let n=e.fields.find((o)=>o.id==="title")??e.fields[0],i=n?t.values[n.id]:void 0;return typeof i==="string"?i.trim():""}function ps(e){let t=Ar(()=>j(e.locale),[e.locale]),n=kn(e.client,e.descriptor.id),i=Nt(null);if(i.current===null)i.current=an(e.descriptor.fields);let[o,r]=en(i.current),[a,d]=en(!1),s=Ar(()=>({client:e.client,descriptor:e.descriptor}),[e.client,e.descriptor]),c=Nt(s);c.current=s;let u=Nt(!0);Ir(()=>(u.current=!0,()=>{u.current=!1}),[]);let[m,p]=en(),l=Ar(()=>{let I=new Map,D=(O,F)=>{if(!u.current||c.current!==s)return;p((P)=>({scope:s,targets:{...P?.scope===s?P.targets:{},[O]:F}}))};return{query:async(...O)=>{let F=O[0],P=(I.get(F)??0)+1;I.set(F,P),D(F,!1);try{let M=await e.client.query(...O);if(I.get(F)===P)D(F,M.ok);return M}catch(M){if(I.get(F)===P)D(F,!1);throw M}}}},[e.client,s]),C=e.descriptor.fields.some((I)=>I.type==="linkedRecord"&&(!I.link||m?.scope!==s||!m.targets[I.link.collectionId])),[b,y]=en(null),g=Nt(null),v=Nt(!1),f=Nt(null),S=Nt(null),{autoFocus:R}=e;Ir(()=>{if(b?.error)S.current?.focus()},[b]);let[k,A]=en(!1),[E,T]=en(!1),V=JSON.stringify(o)!==JSON.stringify(i.current)||k;_t({dirty:V,busy:a},e);let h=()=>f.current?.querySelector("input:not([disabled]), textarea:not([disabled]), select:not([disabled]), button:not([disabled])")?.focus();Ir(()=>{if(R)h()},[R]);async function x(I){if(v.current||e.readOnly||C)return;T(!0);let D;try{D=gn(e.descriptor.fields,o,t,e.locale)}catch(F){y({text:F instanceof Error?F.message:t("Invalid value"),error:!0,clearable:!0});return}v.current=!0,d(!0),y(null);let O=g.current??{idempotencyKey:crypto.randomUUID(),items:[{op:"insert",values:D}]};g.current=O;try{let F=await e.client.mutate(e.descriptor.id,O);if(!n.active)return;if(!F.ok){let M=F.error.code==="validation";A(!M),y({text:Sn(F.error,e.locale),error:!0,clearable:M});return}g.current=null,A(!1),T(!1),i.current=an(e.descriptor.fields),r(i.current),e.onCommitted(F.data);let P=us(e.descriptor,F.data.items[0]);if(y({text:`${I?t("Record saved, keep adding"):t("Record saved")}${P?`:${P}`:""}`,error:!1,clearable:!1}),I)requestAnimationFrame(h);else e.onSaved?.(F.data)}catch{if(!n.active)return;A(!0),y({text:t("Saving failed. Your draft has been kept."),error:!0,clearable:!1})}finally{v.current=!1,d(!1)}}return Dr("form",{ref:f,noValidate:!0,"aria-label":t("New record form"),"data-uibot":"record-creator",onSubmit:(I)=>{I.preventDefault();let D=I.nativeEvent.submitter;x(D?.getAttribute("data-continue")==="true")},onKeyDown:(I)=>{if(I.key==="Enter"&&(I.ctrlKey||I.metaKey)&&!I.nativeEvent.isComposing&&!a)I.preventDefault(),I.currentTarget.requestSubmit()},children:[ht("fieldset",{disabled:a||e.readOnly,style:nt.fields,children:ht(Dt,{fields:e.descriptor.fields,values:o,submitted:E,relationClient:l,getRelationOptions:e.getRelationOptions,...e.locale?{locale:e.locale}:{},...e.ui?{ui:e.ui}:{},onChange:(I)=>{if(r(I),g.current=null,A(!1),b?.clearable)y(null)}})}),b?ht("p",{ref:S,role:b.error?"alert":"status",tabIndex:-1,style:b.error?nt.error:nt.status,children:b.text}):null,Dr("div",{"data-uibot":"record-creator-actions",style:e.stickyActions?{...nt.actions,...nt.sticky}:nt.actions,children:[Dr("span",{style:nt.hint,children:[ht("kbd",{children:"Ctrl / ⌘"})," + ",ht("kbd",{children:"Enter"})," ",t("Save")]}),ht("button",{type:"submit","aria-label":t("Save new record"),"aria-busy":a,disabled:a||e.readOnly||C,style:{...nt.button,...Kt},children:a?t("Saving…"):t("Save new record")}),ht("button",{type:"submit","data-continue":"true",disabled:a||e.readOnly||C,style:nt.button,children:t("Save and continue")}),e.onCancel&&!e.stickyActions?ht(Y,{ui:e.ui,style:nt.button,disabled:a,onClick:e.onCancel,children:t("Cancel adding")}):null]})]})}var nt={sticky:{position:"sticky",bottom:0,zIndex:1,padding:"12px 0",borderTop:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 18%, transparent))",background:"var(--background, white)"},fields:{margin:0,padding:0,border:0,minWidth:0},actions:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,marginTop:12},button:{padding:"6px 10px",border:"1px solid var(--uibot-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"transparent",color:"inherit",font:"inherit",cursor:"pointer"},hint:{marginRight:"auto",fontSize:12,opacity:0.7},error:{margin:"8px 0 0",fontSize:13,color:"var(--uibot-danger, #b3261e)"},status:{margin:"8px 0 0",fontSize:12,opacity:0.8}};import{useEffect as vs,useLayoutEffect as xs,useRef as yn}from"react";import{jsx as tn}from"react/jsx-runtime";var ti=[["#e8f0fe","#1a56c4"],["#e6f4ea","#1e7a3c"],["#fdecea","#b3261e"],["#fff1e0","#a05a00"],["#e8eaed","#3c4043"],["#e0f2f1","#00695c"],["#f3e8fd","#6a1b9a"]];function Mt(e){let t=Math.max(e,0)%ti.length,[n,i]=ti[t]??["#e8eaed","#3c4043"];return{background:`var(--uibot-chip-${t}-bg, ${n})`,color:`var(--uibot-chip-${t}-fg, ${i})`}}function gs({index:e,children:t}){return tn("span",{"data-uibot-chip":"",style:{display:"inline-flex",alignItems:"center",maxWidth:"100%",padding:"1px 8px",borderRadius:999,fontSize:12,lineHeight:"18px",fontWeight:500,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",...Mt(e)},children:t})}function Yn({ids:e,field:t,wrap:n}){let i=t.options??[];return tn("span",{style:{display:"inline-flex",gap:4,alignItems:"center",maxWidth:"100%",overflow:"hidden",...n?{flexWrap:"wrap"}:{}},children:e.map((o)=>{let r=i.findIndex((a)=>a.id===o);return tn(gs,{index:Rn(i,o),children:i[r]?.name??String(o)},String(o))})})}function Pg({checked:e,label:t,onToggle:n}){return tn("input",{type:"checkbox","aria-label":t,checked:e,disabled:!n,style:{width:16,height:16,margin:0,accentColor:"var(--primary, #1a56c4)"},onMouseDown:(i)=>i.stopPropagation(),onKeyDown:(i)=>i.stopPropagation(),onChange:()=>n?.()})}var ni={singleLineText:"M3 4.5h10M8 4.5v8",longText:"M3 4h10M3 8h10M3 12h6",number:"M6.5 3 5.5 13M10.5 3l-1 10M3 6h10.5M2.5 10h10.5",bigint:"M6.5 3 5.5 13M10.5 3l-1 10M3 6h10.5M2.5 10h10.5",checkbox:"M3.5 3.5h9v9h-9zM5.6 8.1l1.8 1.8 3-3.6",date:"M3 4.5h10V13H3zM3 7.5h10M6 3v3M10 3v3",singleSelect:"M8 14a6 6 0 1 0 0-12 6 6 0 0 0 0 12zM5.8 7l2.2 2.2L10.2 7",multipleSelect:"M6 4h7M6 8h7M6 12h7M3 4h.01M3 8h.01M3 12h.01",relation:"M7 9a2.5 2.5 0 0 0 3.5 0l2-2A2.5 2.5 0 0 0 9 3.5l-.7.7M9 7a2.5 2.5 0 0 0-3.5 0l-2 2A2.5 2.5 0 0 0 7 12.5l.7-.7",linkedRecord:"M7 9a2.5 2.5 0 0 0 3.5 0l2-2A2.5 2.5 0 0 0 9 3.5l-.7.7M9 7a2.5 2.5 0 0 0-3.5 0l-2 2A2.5 2.5 0 0 0 7 12.5l.7-.7",hyperlink:"M9 3h4v4M13 3 7.5 8.5M11 9.5V13H3V5h3.5",lookup:"M7 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM10 10l3.5 3.5",formula:"M10.5 3.5c-2 0-2.2 1-2.5 3L7.2 12c-.3 1.6-1 2-2.5 2M5 7.5h5",rollup:"M12 3.5H4.5L8.5 8l-4 4.5H12",json:"M6 3.5C4.5 3.5 4.5 5 4.5 6.5S4 8 3 8c1 0 1.5.5 1.5 1.5S4.5 12.5 6 12.5M10 3.5c1.5 0 1.5 1.5 1.5 3S12 8 13 8c-1 0-1.5.5-1.5 1.5s0 3-1.5 3",blob:"M4 3.5h5l3 3V12.5H4z"};function wg({type:e}){return tn("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",width:13,height:13,fill:"none",stroke:"currentColor",strokeWidth:1.4,strokeLinecap:"round",strokeLinejoin:"round",style:{flex:"none",opacity:0.62},children:tn("path",{d:ni[e]??ni.singleLineText})})}var B={root:{display:"grid",gap:12,color:"var(--uibot-schema-fg, inherit)",fontFamily:"inherit"},field:{margin:0,minWidth:0,display:"grid",gap:12,padding:16,border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:10,background:"var(--uibot-schema-bg, transparent)"},row:{display:"flex",flexWrap:"wrap",alignItems:"end",gap:12},control:{display:"grid",flex:"1 1 180px",gap:5,minWidth:140,fontSize:13},label:{color:"var(--uibot-schema-muted, color-mix(in srgb, currentColor 65%, transparent))",fontWeight:600},input:{boxSizing:"border-box",width:"100%",minHeight:"var(--uibot-schema-control-height, 36px)",padding:"7px 9px",border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"var(--uibot-schema-bg, transparent)",color:"inherit",font:"inherit"},button:{minHeight:36,padding:"7px 12px",border:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))",borderRadius:6,background:"var(--uibot-schema-surface, transparent)",color:"inherit",font:"inherit",fontWeight:600,cursor:"pointer"},danger:{borderColor:"var(--uibot-schema-danger-border, color-mix(in srgb, #e5534b 45%, transparent))",background:"var(--uibot-schema-danger-bg, transparent)",color:"var(--uibot-schema-danger, #e5534b)"},checkbox:{display:"flex",alignItems:"center",gap:8,minHeight:"var(--uibot-schema-control-height, 36px)",fontSize:13},options:{display:"grid",gap:8,margin:0,minWidth:0,padding:"10px 0 0",border:0,borderTop:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))"},optionRow:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},settings:{display:"grid",gap:10,margin:0,minWidth:0,padding:"10px 0 0",border:0,borderTop:"1px solid var(--uibot-schema-border, color-mix(in srgb, currentColor 25%, transparent))"},swatch:{width:18,height:18,padding:0,borderRadius:999,cursor:"pointer",flex:"none"}};import{jsx as Ce,jsxs as ke,Fragment as Er}from"react/jsx-runtime";var ms=["YYYY-MM-DD","YYYY/MM/DD","MM/DD/YYYY","DD/MM/YYYY","YYYY年M月D日"],fs=["Asia/Shanghai","Asia/Hong_Kong","Asia/Tokyo","Asia/Singapore","Europe/London","Europe/Paris","America/New_York","America/Los_Angeles","UTC"],ys=["CNY","USD","EUR","JPY","GBP","HKD"],bs=[0,1,2,3,4,5,6,7,8],hs={date:"YYYY-MM-DD",time:"none"},Cs={kind:"decimal",precision:0,grouping:!0};function ri({field:e,onChange:t,disabled:n,locale:i,ui:o,settings:r,dateFormatLocked:a}){let d=r?.formatting!==!1,s=r?.defaults!==!1,c=j(i),u=(l)=>t((C)=>({...C,...l})),m=()=>t((l)=>{let{defaultValue:C,...b}=l;return b}),p=(l,C,b,y,g=!1)=>ke("div",{style:B.control,children:[Ce("span",{style:B.label,children:l}),Ce(Pe,{ui:o,label:l,style:B.input,disabled:n||g,value:C,options:b,onChange:y})]});if(e.type==="date"){let l=Me(e)??hs,C=(y)=>{let{timeZone:g,...v}=l,f={...v,...g?{timeZone:g}:{},...y};if(y.timeZone==="")delete f.timeZone;u({formatting:f})},b=l.time!=="none";if(!d&&!s)return null;return ke("fieldset",{style:B.settings,"aria-label":c("Format of field {name}",{name:e.name}),children:[d?ke(Er,{children:[Ce("strong",{style:{fontSize:13},children:c("Format")}),ke("div",{style:B.row,children:[p(c("Date format"),l.date,ms.map((y)=>({value:y,label:y})),(y)=>C({date:y}),Boolean(a)),p(c("Time format"),l.time,[{value:"none",label:c("No time (date only)")},{value:"24h",label:c("24-hour")},{value:"12h",label:c("12-hour")}],(y)=>C({time:y}),Boolean(a)),b?p(c("Time zone"),l.timeZone??"",[{value:"",label:c("Viewer's time zone")},...fs.map((y)=>({value:y,label:y}))],(y)=>C({timeZone:y}),Boolean(a)):null]}),ke("p",{style:{...B.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[c("Preview"),": ",Bt(new Date().toISOString(),l)]})]}):null,s&&p(c("Default value"),e.defaultValue?.kind==="now"?"now":"",[{value:"",label:c("Empty")},{value:"now",label:b?c("Current date and time"):c("Today")}],(y)=>y==="now"?u({defaultValue:{kind:"now"}}):m())]})}if(e.type==="number"){let l=Pn(e)??Cs,C=(y)=>u({formatting:{...l,...y}}),b=e.defaultValue?.kind==="value"?String(e.defaultValue.value):"";if(!d&&!s)return null;return ke("fieldset",{style:B.settings,"aria-label":c("Format of field {name}",{name:e.name}),children:[d?ke(Er,{children:[Ce("strong",{style:{fontSize:13},children:c("Format")}),ke("div",{style:B.row,children:[p(c("Number style"),l.kind,[{value:"decimal",label:c("Number")},{value:"percent",label:c("Percent")},{value:"currency",label:c("Currency")}],(y)=>C({kind:y})),p(c("Decimal places"),String(l.precision),bs.map((y)=>({value:String(y),label:String(y)})),(y)=>C({precision:Number(y)})),l.kind==="currency"?p(c("Currency"),l.currency??"CNY",ys.map((y)=>({value:y,label:y})),(y)=>C({currency:y})):null]}),ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox","aria-label":c("Thousands separator"),checked:l.grouping!==!1,disabled:n,onChange:(y)=>C({grouping:y.currentTarget.checked})}),c("Thousands separator")]}),ke("p",{style:{...B.label,margin:0,fontWeight:400},"data-uibot-format-preview":"",children:[c("Preview"),":"," ",wn(l.kind==="percent"?0.1234:1234.5678,l)]})]}):null,s&&ke("label",{style:B.control,children:[Ce("span",{style:B.label,children:c("Default value")}),Ce("input",{"aria-label":c("Default value"),style:B.input,type:"number",step:"any",disabled:n,value:b,onChange:(y)=>{let g=y.currentTarget.value;if(g===""||!Number.isFinite(Number(g)))m();else u({defaultValue:{kind:"value",value:Number(g)}})}})]})]})}if(!s)return null;if(e.type==="singleLineText"||e.type==="longText")return Ce("fieldset",{style:B.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:ke("label",{style:B.control,children:[Ce("span",{style:B.label,children:c("Default value")}),Ce("input",{"aria-label":c("Default value"),style:B.input,disabled:n,value:e.defaultValue?.kind==="value"?String(e.defaultValue.value):"",onChange:(l)=>{let C=l.currentTarget.value;if(C==="")m();else u({defaultValue:{kind:"value",value:C}})}})]})});if(e.type==="checkbox")return Ce("fieldset",{style:B.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox","aria-label":c("Checked by default"),checked:e.defaultValue?.kind==="value"&&e.defaultValue.value===!0,disabled:n,onChange:(l)=>l.currentTarget.checked?u({defaultValue:{kind:"value",value:!0}}):m()}),c("Checked by default")]})});if((e.type==="singleSelect"||e.type==="multipleSelect")&&(e.options?.length??0)>0){let l=e.options??[],C=e.defaultValue?.kind==="value"?e.defaultValue.value:void 0;if(e.type==="singleSelect")return Ce("fieldset",{style:B.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:p(c("Default value"),typeof C==="string"?C:"",[{value:"",label:c("Empty")},...l.map((y)=>({value:y.id,label:y.name}))],(y)=>y?u({defaultValue:{kind:"value",value:y}}):m())});let b=Array.isArray(C)?C:[];return ke("fieldset",{style:B.settings,"aria-label":c("Defaults of field {name}",{name:e.name}),children:[Ce("span",{style:B.label,children:c("Default value")}),l.map((y)=>ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox","aria-label":c("Default option {name}",{name:y.name}),checked:b.includes(y.id),disabled:n,onChange:(g)=>{let v=g.currentTarget.checked?[...b,y.id]:b.filter((f)=>f!==y.id);if(v.length)u({defaultValue:{kind:"value",value:v}});else m()}}),y.name]},y.id))]})}return null}function oi({field:e,fields:t,onChange:n,disabled:i,locale:o}){let r=j(o);if(!Qn.has(e.type))return null;let a=e.ai,d=t.filter((u)=>u.id!==e.id&&u.type!=="blob"&&u.type!=="lookup"),s=a?.sourceFieldIds??[],c=(u)=>n((m)=>{if(u)return{...m,ai:u};let{ai:p,...l}=m;return l});return ke("fieldset",{style:B.settings,"aria-label":r("AI settings of field {name}",{name:e.name}),children:[ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox",checked:Boolean(a),disabled:i,onChange:(u)=>c(u.currentTarget.checked?{prompt:""}:void 0)}),r("Generate this field with AI")]}),a?ke(Er,{children:[ke("label",{style:B.control,children:[Ce("span",{style:B.label,children:r("AI prompt")}),Ce("textarea",{"aria-label":r("AI prompt"),style:{...B.input,minHeight:72,resize:"vertical"},rows:3,maxLength:Zn,placeholder:r("e.g. Summarize the description in one sentence"),value:a.prompt,disabled:i,onChange:(u)=>{let m=u.currentTarget.value;n((p)=>({...p,ai:{...p.ai,prompt:m}}))}})]}),ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox",checked:Boolean(a.autoFill),disabled:i,onChange:(u)=>{let m=u.currentTarget.checked;n((p)=>{let{autoFill:l,...C}=p.ai??{prompt:""};return{...p,ai:m?{...C,autoFill:!0}:C}})}}),r("Generate when a record is created")]}),Ce("span",{style:B.label,children:r("Fields the AI reads (none = all)")}),Ce("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px"},children:d.map((u)=>ke("label",{style:B.checkbox,children:[Ce("input",{type:"checkbox","aria-label":r("AI reads {name}",{name:u.name}),checked:s.includes(u.id),disabled:i,onChange:(m)=>{let p=m.currentTarget.checked;n((l)=>{let C=l.ai?.sourceFieldIds??[],b=p?[...C,u.id]:C.filter((v)=>v!==u.id),{sourceFieldIds:y,...g}=l.ai??{prompt:""};return{...l,ai:b.length?{...g,sourceFieldIds:b}:g}})}}),u.name]},u.id))})]}):null]})}import{jsx as fe,jsxs as We}from"react/jsx-runtime";var ks=["singleLineText","longText","number","checkbox","date","singleSelect","multipleSelect"],ii=(e)=>e==="singleSelect"||e==="multipleSelect";function Ps(e,t){let n=t.slice(0,bn);if(!n.trim()){let{description:i,...o}=e;return o}return{...e,description:n}}function ws({fields:e,onChange:t,disabled:n=!1,focusFieldId:i,locale:o,ui:r,fieldTypes:a=ks,relationTargets:d=[],lockedFieldIds:s=[],settings:c,single:u=!1,contextFields:m}){let p=j(o),l={singleLineText:p("Single line text"),longText:p("Long text"),number:p("Number"),checkbox:p("Checkbox"),date:p("Date"),singleSelect:p("Single select"),multipleSelect:p("Multiple select"),relation:p("Linked record"),hyperlink:p("Hyperlink")},C=Fn()?.kinds??[],b=(h)=>a.includes(h.type),y=yn(new Map),g=yn(new Map),v=yn(null),f=yn(new Map),S=yn(null);function R(h,x){let I={fields:h,target:x};S.current=I,t(h),queueMicrotask(()=>{if(S.current===I)S.current=null})}xs(()=>{let h=S.current;if(!h||h.fields!==e)return;if(S.current=null,n)return;let{target:x}=h,I=x.type==="field-name"?y.current.get(x.fieldId):x.type==="option-name"?g.current.get(`${x.fieldId}:${x.optionId}`):null;if(I){I.focus(),I.select();return}(x.type==="add-field"?v.current:x.type==="add-option"?f.current.get(x.fieldId):null)?.querySelector("button")?.focus()},[n,e]),vs(()=>{if(!i)return;let h=window.setTimeout(()=>{let x=y.current.get(i);x?.scrollIntoView({block:"center"}),x?.focus(),x?.select()},200);return()=>window.clearTimeout(h)},[i]);let k=(h,x)=>{if(!n)t(e.map((I)=>I.id===h?x(I):I))};function A(){if(n)return;let h={id:`field_${crypto.randomUUID().replaceAll("-","")}`,name:p("New field"),type:"singleLineText"};R([...e,h],{type:"field-name",fieldId:h.id})}function E(h){if(n)return;let x=e.filter(b),I=x.findIndex((F)=>F.id===h),D=x.filter((F)=>F.id!==h),O=D[I]??D[I-1];R(e.filter((F)=>F.id!==h),O?{type:"field-name",fieldId:O.id}:{type:"add-field"})}function T(h){if(n)return;let x={id:crypto.randomUUID(),name:p("New option")};R(e.map((I)=>I.id===h.id?{...I,options:[...I.options??[],x]}:I),{type:"option-name",fieldId:h.id,optionId:x.id})}function V(h,x){if(n)return;let I=h.options??[],D=I.findIndex((P)=>P.id===x),O=I.filter((P)=>P.id!==x),F=O[D]??O[D-1];R(e.map((P)=>{if(P.id!==h.id)return P;let M=P.defaultValue;if(!(M?.kind==="value"&&(Array.isArray(M.value)?M.value.includes(x):M.value===x)))return{...P,options:O};let{defaultValue:te,...q}=P;return{...q,options:O}}),F?{type:"option-name",fieldId:h.id,optionId:F.id}:{type:"add-option",fieldId:h.id})}return We("section",{"aria-label":p("Collection fields"),"data-uibot-schema-editor":"",style:B.root,children:[e.filter(b).map((h)=>We("fieldset",{"aria-label":p("Field {name}",{name:h.name}),style:u?{...B.field,border:0,padding:0,background:"none"}:B.field,children:[We("div",{style:B.row,children:[We("label",{style:B.control,children:[fe("span",{style:B.label,children:p("Field name")}),fe("input",{"aria-label":p("Field name"),ref:(x)=>{if(x)y.current.set(h.id,x);else y.current.delete(h.id)},style:B.input,value:h.name,disabled:n,onChange:(x)=>{let I=x.currentTarget.value;k(h.id,(D)=>({...D,name:I}))}})]}),We("div",{style:B.control,children:[fe("span",{style:B.label,children:p("Field type")}),fe(Pe,{ui:r,label:p("Field type"),style:B.input,disabled:n||s.includes(h.id),value:h.type,options:a.map((x)=>({value:x,label:l[x]})),onChange:(x)=>k(h.id,(I)=>{let{options:D,relation:O,hyperlink:F,formatting:P,defaultValue:M,...W}=I;return{...W,type:x,...ii(x)?{options:I.options??[]}:{},...x==="relation"?{relation:{collectionId:""}}:{}}})})]}),We("label",{style:B.checkbox,children:[fe("input",{type:"checkbox","aria-label":p("Required"),checked:Boolean(h.required),disabled:n,onChange:(x)=>{let I=x.currentTarget.checked;k(h.id,(D)=>({...D,required:I}))}}),p("Required")]}),u?null:fe(Y,{ui:r,style:{...B.button,...B.danger},disabled:n||s.includes(h.id),icon:"trash",iconOnly:!0,ariaLabel:p("Delete field"),title:p("Delete field {name}",{name:h.name}),onClick:()=>E(h.id)})]}),c?.descriptions===!1?null:We("label",{style:B.control,children:[fe("span",{style:B.label,children:p("Field description")}),fe("textarea",{"aria-label":p("Field description"),style:{...B.input,minHeight:64,resize:"vertical"},rows:2,maxLength:bn,value:h.description??"",disabled:n,onChange:(x)=>{let I=x.currentTarget.value;k(h.id,(D)=>Ps(D,I))}})]}),h.type==="relation"?We("div",{style:B.control,children:[fe("span",{style:B.label,children:p("Related table")}),fe(Pe,{ui:r,label:p("Related table"),style:B.input,disabled:n||s.includes(h.id),value:h.relation?.collectionId??"",options:[{value:"",label:p("Choose a related table")},...d.map((x)=>({value:x.id,label:x.name}))],onChange:(x)=>k(h.id,(I)=>({...I,relation:{collectionId:x}}))})]}):null,h.type==="hyperlink"&&C.length>0?We("fieldset",{style:B.settings,"aria-label":p("Link targets"),children:[fe("span",{style:B.label,children:p("Link targets")}),fe("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px"},children:C.map((x)=>{let I=h.hyperlink?.kinds??[];return We("label",{style:B.checkbox,children:[fe("input",{type:"checkbox",checked:I.includes(x.id),disabled:n,onChange:(D)=>{let O=D.currentTarget.checked;k(h.id,(F)=>{let P=F.hyperlink?.kinds??[],M=O?[...P,x.id]:P.filter((q)=>q!==x.id),{hyperlink:W,...te}=F;return M.length?{...te,hyperlink:{kinds:M}}:te})}}),x.label]},x.id)})}),fe("span",{style:{...B.label,opacity:0.7},children:p("None chosen offers every kind.")})]}):null,ii(h.type)?We("fieldset",{style:B.options,"aria-label":p("Options of field {name}",{name:h.name}),children:[fe("strong",{style:{fontSize:13},children:p("Options")}),(h.options??[]).map((x,I)=>We("div",{style:B.optionRow,children:[fe("input",{"aria-label":p("Option name {index}",{index:I+1}),ref:(D)=>{let O=`${h.id}:${x.id}`;if(D)g.current.set(O,D);else g.current.delete(O)},style:{...B.input,flex:"1 1 120px",minWidth:0,width:"auto"},value:x.name,disabled:n,onChange:(D)=>{let O=D.currentTarget.value;k(h.id,(F)=>({...F,options:(F.options??[]).map((P)=>P.id===x.id?{...P,name:O}:P)}))}}),c?.optionColors===!1?null:fe("fieldset",{"aria-label":p("Colour of option {index}",{index:I+1}),style:{display:"inline-flex",flex:"none",gap:4,margin:0,padding:0,border:0,minWidth:0},children:Lt.map((D,O)=>{let F=(x.color??Lt[I%Lt.length])===D;return fe("button",{type:"button","aria-label":p(`Colour ${D}`),"aria-pressed":F,disabled:n,style:{...B.swatch,background:Mt(O).color,border:F?"2px solid currentColor":"1px solid transparent"},onClick:()=>k(h.id,(P)=>({...P,options:(P.options??[]).map((M)=>M.id===x.id?{...M,color:D}:M)}))},D)})}),fe(Y,{ui:r,style:{...B.button,...B.danger},disabled:n,icon:"trash",iconOnly:!0,ariaLabel:p("Delete option {index}",{index:I+1}),title:p("Delete option {index}",{index:I+1}),onClick:()=>V(h,x.id)})]},x.id)),fe("div",{ref:(x)=>{if(x)f.current.set(h.id,x);else f.current.delete(h.id)},children:fe(Y,{ui:r,style:B.button,icon:"plus",disabled:n,onClick:()=>T(h),children:p("Add option")})})]}):null,fe(ri,{field:h,...c?{settings:c}:{},dateFormatLocked:s.includes(h.id),disabled:n,locale:o,ui:r,onChange:(x)=>k(h.id,x)}),c?.ai?fe(oi,{field:h,fields:u&&m?[...m,h]:e,disabled:n,locale:o,onChange:(x)=>k(h.id,x)}):null]},h.id)),u?null:fe("div",{ref:v,children:fe(Y,{ui:r,style:B.button,icon:"plus",disabled:n,onClick:A,children:p("Add field")})})]})}import{useEffect as bi,useRef as hi,useState as Mr}from"react";import{useCallback as Ts,useEffect as pi,useLayoutEffect as Fs,useRef as Nr,useState as gi}from"react";import{createContext as Rs,useContext as Ss,useCallback as Is,useEffect as ai,useId as As,useLayoutEffect as si,useRef as li,useState as di}from"react";import{createPortal as Ds}from"react-dom";import{jsx as lt,jsxs as ui,Fragment as ci}from"react/jsx-runtime";var Es=Rs(!1),Tr="uibot:collection-popover-open";function Fr({label:e,trigger:t,defaultOpen:n=!1,disabled:i,menu:o,children:r}){let[a,d]=di(n),[s,c]=di({left:8,top:8}),u=li(null),m=li(null),p=As();ai(()=>{let b=(y)=>{let g=y.detail,v=u.current;if(!g||!v||g===v)return;let f=v.closest("[data-uibot-workspace]")??v.parentElement,S=g.closest("[data-uibot-workspace]")??g.parentElement;if(f===S)d(!1)};return document.addEventListener(Tr,b),()=>document.removeEventListener(Tr,b)},[]);let l=()=>{d(!1),u.current?.focus({preventScroll:!0})},C=Is(()=>{if(!a)return;let b=u.current?.getBoundingClientRect(),y=m.current?.getBoundingClientRect();if(b&&y){let g={left:Math.max(8,Math.min(b.left,window.innerWidth-y.width-8)),top:Math.max(8,b.bottom+y.height+8<=window.innerHeight?b.bottom+4:b.top-y.height-4)};c((v)=>v.left===g.left&&v.top===g.top?v:g)}},[a]);return si(C),si(()=>{if(!a)return;if(u.current)document.dispatchEvent(new CustomEvent(Tr,{detail:u.current}));(m.current?.querySelector("button:not(:disabled), input, select, textarea")??m.current)?.focus({preventScroll:!0})},[a]),ai(()=>{if(!a)return;let b=(g)=>{if(g.target instanceof Node&&!m.current?.contains(g.target)&&!u.current?.contains(g.target))d(!1)},y=(g)=>{if(g.key!=="Escape")return;g.preventDefault(),g.stopPropagation(),d(!1),u.current?.focus({preventScroll:!0})};return window.addEventListener("resize",C),window.addEventListener("scroll",C,!0),document.addEventListener("pointerdown",b),document.addEventListener("keydown",y),()=>{window.removeEventListener("resize",C),window.removeEventListener("scroll",C,!0),document.removeEventListener("pointerdown",b),document.removeEventListener("keydown",y)}},[a,C]),ui(ci,{children:[lt("button",{ref:u,type:"button","aria-label":e,"aria-haspopup":o?"menu":"dialog","aria-expanded":a,"aria-controls":a?p:void 0,disabled:i,style:{display:"inline-flex",alignItems:"center",gap:6,border:0,background:"transparent",color:"inherit",font:"inherit",padding:"4px 6px",cursor:"pointer"},onPointerDown:(b)=>b.stopPropagation(),onClick:()=>a?l():d(!0),children:t}),a&&Ds(lt("div",{ref:m,id:p,role:o?"menu":"dialog","aria-label":e,tabIndex:-1,style:{position:"fixed",...s,zIndex:80,padding:o?4:12,minWidth:160,maxWidth:"calc(100vw - 16px)",maxHeight:"min(70vh, 600px)",overflow:"auto",boxSizing:"border-box",border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",color:"var(--foreground, inherit)",fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},onKeyDown:(b)=>{if(!o||!["ArrowDown","ArrowUp","Home","End"].includes(b.key))return;b.preventDefault();let y=[...b.currentTarget.querySelectorAll('button[role="menuitem"]:not(:disabled)')],g=y.indexOf(document.activeElement),v=b.key==="Home"?0:b.key==="End"?y.length-1:(g+(b.key==="ArrowUp"?-1:1)+y.length)%y.length;y[v]?.focus()},children:r(l)}),document.body)]})}function Gg({ui:e,label:t,defaultOpen:n,icon:i,chevron:o,quiet:r,active:a,children:d}){let s=Ss(Es),c=(u)=>lt("div",{style:{fontSize:"var(--uibot-workspace-font-size, 13px)",lineHeight:1.45},children:lt("fieldset",{disabled:s,style:{border:0,padding:0,margin:0,minWidth:0},children:u})});if(e?.Popover)return e.Popover({label:t,defaultOpen:n,...i?{icon:lt(Ee,{name:i})}:{},...o?{iconEnd:lt(Ee,{name:"chevronDown",size:13})}:{},...r?{quiet:r}:{},active:a,children:typeof d==="function"?(u)=>c(d(u)):c(d)});return lt(Fr,{label:t,defaultOpen:n,trigger:ui(ci,{children:[i?lt(Ee,{name:i}):null,t,o?lt(Ee,{name:"chevronDown",size:13}):null]}),children:(u)=>c(typeof d==="function"?d(u):d)})}import{jsx as Gn,jsxs as yi,Fragment as Ns}from"react/jsx-runtime";function mi({items:e,label:t,children:n,block:i=!1}){let[o,r]=gi(null),a=Nr(null),d=Nr(null),[s,c]=gi({x:0,y:0}),u=Ts(()=>{if(!o||!d.current)return;let p=Math.max(12,Math.min(o.x,window.innerWidth-12-d.current.offsetWidth)),l=Math.max(12,Math.min(o.y,window.innerHeight-12-d.current.offsetHeight));c((C)=>C.x===p&&C.y===l?C:{x:p,y:l})},[o]);Fs(u),pi(()=>{if(!o)return;return window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[o,u]);let m=Nr(null);return pi(()=>{if(!o)return;m.current=document.activeElement instanceof HTMLElement?document.activeElement:null,d.current?.querySelector("button:not(:disabled)")?.focus();let p=()=>r(null),l=(C)=>{if(C.key==="Escape")C.preventDefault(),C.stopPropagation(),r(null),m.current?.focus({preventScroll:!0})};return window.addEventListener("keydown",l),window.addEventListener("pointerdown",p),window.addEventListener("blur",p),()=>{window.removeEventListener("keydown",l),window.removeEventListener("pointerdown",p),window.removeEventListener("blur",p)}},[o]),yi("span",{ref:a,style:{display:i?"block":"inline-flex"},onKeyDown:(p)=>{if(p.shiftKey&&p.key==="F10"||p.key==="ContextMenu"){p.preventDefault(),p.stopPropagation();let l=p.target.getBoundingClientRect();r({x:Math.max(8,Math.min(l.left,window.innerWidth-240)),y:Math.max(8,Math.min(l.bottom,window.innerHeight-280))})}},onContextMenu:(p)=>{p.preventDefault(),p.stopPropagation(),r({x:Math.max(8,Math.min(p.clientX,window.innerWidth-240)),y:Math.max(8,Math.min(p.clientY,window.innerHeight-280))})},children:[n,o&&Gn("div",{ref:d,role:"menu","aria-label":t,style:{position:"fixed",left:s.x,top:s.y,boxSizing:"border-box",maxWidth:"calc(100vw - 24px)",maxHeight:"min(70vh, calc(100vh - 24px))",overflow:"auto",zIndex:60,minWidth:140,font:"inherit",padding:4,border:"1px solid var(--border, #d5d9df)",borderRadius:8,background:"var(--background, white)",boxShadow:"0 4px 16px rgb(0 0 0 / 0.12)"},onPointerDown:(p)=>p.stopPropagation(),onKeyDown:(p)=>{if(!["ArrowDown","ArrowUp"].includes(p.key))return;p.preventDefault();let l=[...p.currentTarget.querySelectorAll("button:not(:disabled)")],C=l.indexOf(document.activeElement);l[(C+(p.key==="ArrowUp"?-1:1)+l.length)%l.length]?.focus()},children:e.map((p)=>Gn("button",{type:"button",role:"menuitem",disabled:p.disabled,style:{display:"block",width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderRadius:6,background:"transparent",color:p.destructive?"var(--destructive, #b3261e)":"inherit",cursor:p.disabled?"default":"pointer",opacity:p.disabled?0.5:1},onClick:()=>{r(null),p.onSelect()},children:p.label},p.id))})]})}function fi({label:e,items:t,disabled:n,icon:i}){return Gn(Fr,{label:e,disabled:n,menu:!0,trigger:i??"+",children:(o)=>Gn(Ns,{children:t.map((r)=>yi("button",{type:"button",role:"menuitem",disabled:r.disabled,style:{display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 10px",border:0,borderTop:r.separatorBefore?"1px solid var(--border, #d5d9df)":void 0,background:"transparent",color:r.destructive?"var(--destructive, #b3261e)":"inherit",opacity:r.disabled?0.5:1,font:"inherit"},onClick:()=>{o(),r.onSelect()},children:[r.icon,r.label]},r.id))})})}import{jsx as je,jsxs as Ci}from"react/jsx-runtime";function Ms(e,t,n,i){if(t===n)return[...e];let o=e.filter((a)=>a!==t),r=o.indexOf(n);if(r<0||!e.includes(t))return[...e];return o.splice(i?r+1:r,0,t),o}var Ls=["grid","kanban","gallery","calendar","form"];function Os(e,t){return{grid:e("Grid"),kanban:e("Kanban"),gallery:e("Gallery"),calendar:e("Calendar"),form:e("Form")}[t]}function Vs({slot:e,items:t,label:n,children:i}){if(!t.length)return je("span",{children:i});if(e)return je(e,{items:t,"aria-label":n,children:i});return je(mi,{items:t,label:n,children:i})}function _s(e){let t=j(e.locale),[n,i]=Mr(null),[o,r]=Mr(""),[a,d]=Mr(null),s=hi(null),c=hi(null),u=Boolean(e.onReorder)&&!e.disabled&&e.views.length>1,m=e.views.map((R)=>R.id),p=(R,k,A)=>{let E=Ms(m,R,k,A);if(E.join("\x00")!==m.join("\x00"))e.onReorder?.(E)};bi(()=>{let R=s.current;if(!R)return;s.current=null,document.querySelector(`[data-view-tab="${CSS.escape(R)}"]`)?.focus()}),bi(()=>{if(n)c.current?.select()},[n]);let l=Boolean(e.onDelete)&&e.views.length>1,C=(R)=>{if(!e.onRename||e.disabled)return;r(R.name),i(R.id)},b=()=>{if(!n)return;let R=e.views.find((A)=>A.id===n),k=o.trim();if(i(null),R&&k&&k!==R.name)e.onRename?.(R.id,k)},y=(R)=>[...e.onRename?[{id:"rename",icon:je(Ee,{name:"pencil"}),label:t("Rename view"),onSelect:()=>C(R)}]:[],...e.onDuplicate?[{id:"duplicate",icon:je(Ee,{name:"copy"}),label:t("Duplicate view"),onSelect:()=>e.onDuplicate?.(R.id)}]:[],...e.onDelete?[{id:"delete",icon:je(Ee,{name:"trash"}),label:t("Delete view"),destructive:!0,disabled:!l,onSelect:()=>e.onDelete?.(R.id)}]:[]],g=(R,k)=>{let A=e.views.findIndex((E)=>E.id===k.id);if(R.altKey&&(R.key==="ArrowRight"||R.key==="ArrowLeft")){R.preventDefault();let E=e.views[A+(R.key==="ArrowRight"?1:-1)];if(u&&E)s.current=k.id,p(k.id,E.id,R.key==="ArrowRight")}else if(R.key==="F2")R.preventDefault(),C(k);else if(R.key==="Delete"&&l&&!e.disabled)R.preventDefault(),e.onDelete?.(k.id);else if(R.key==="ArrowRight"||R.key==="ArrowLeft"){R.preventDefault();let E=e.views[A+(R.key==="ArrowRight"?1:-1)];if(E)e.onSelect(E.id),R.currentTarget.parentElement?.parentElement?.querySelectorAll('[role="tab"]')?.[A+(R.key==="ArrowRight"?1:-1)]?.focus()}},v=(e.viewTypes??Ls).map((R)=>({id:R,label:Os(t,R),disabled:e.disabledViewTypes?.includes(R)??!1,onSelect:()=>e.onAdd?.(R)})),f=e.ui?.ContextMenu,S=e.ui?.DropdownMenu;return Ci("div",{"data-uibot":"collection-view-tabs",style:{display:"flex",alignItems:"flex-end",gap:2,minWidth:0,maxWidth:"100%",overflowX:"auto"},children:[je("div",{role:"tablist","aria-label":t("Views"),style:{display:"flex",gap:2},children:e.views.map((R)=>{let k=R.id===e.activeId,A=y(R),E=n===R.id?je("input",{ref:c,"aria-label":t("View name"),value:o,maxLength:80,style:{height:30,padding:"0 8px",font:"inherit",border:"1px solid var(--primary, #1a56c4)",borderRadius:6,background:"var(--background, white)",color:"inherit"},onChange:(T)=>r(T.target.value),onBlur:b,onKeyDown:(T)=>{if(T.stopPropagation(),T.key==="Enter")T.preventDefault(),b();else if(T.key==="Escape")T.preventDefault(),i(null)}}):Ci("button",{type:"button",role:"tab","aria-selected":k,tabIndex:k?0:-1,disabled:e.disabled,title:e.onRename?t("Double click to rename"):void 0,"data-view-tab":R.id,draggable:u,onDragStart:(T)=>{if(!u)return;T.dataTransfer.effectAllowed="move",T.dataTransfer.setData("text/plain",R.id),d({id:R.id})},onDragOver:(T)=>{if(!a||a.id===R.id)return;T.preventDefault();let V=T.currentTarget.getBoundingClientRect(),h=(T.clientX||0)>V.left+V.width/2;if(a.over!==R.id||a.after!==h)d({id:a.id,over:R.id,after:h})},onDrop:(T)=>{if(!a)return;T.preventDefault(),p(a.id,R.id,Boolean(a.after)),d(null)},onDragEnd:()=>d(null),style:{boxShadow:a?.over===R.id?a.after?"inset -2px 0 0 var(--primary, #1a56c4)":"inset 2px 0 0 var(--primary, #1a56c4)":void 0,opacity:a?.id===R.id?0.5:1,position:"relative",display:"inline-flex",alignItems:"center",gap:6,height:34,padding:"0 12px",border:0,borderBottom:k?"2px solid var(--primary, #1a56c4)":"2px solid transparent",background:"transparent",color:k?"var(--primary, #1a56c4)":"inherit",fontWeight:k?600:400,fontSize:13,whiteSpace:"nowrap",cursor:"pointer"},onClick:()=>e.onSelect(R.id),onDoubleClick:()=>C(R),onKeyDown:(T)=>g(T,R),children:[je("span",{children:R.name}),e.dirty&&k&&je("span",{role:"img","aria-label":t("Unsaved changes"),style:{width:6,height:6,borderRadius:999,background:"var(--primary, #1a56c4)"}})]});return je(Vs,{slot:f,items:n===R.id?[]:A,label:t("View actions"),children:E},R.id)})}),e.onAdd&&(S?je(S,{label:t("Add view"),items:v,disabled:e.disabled}):je(fi,{label:t("Add view"),items:v,disabled:e.disabled}))]})}import{useRef as Bs,useState as Us}from"react";import{jsx as Se,jsxs as nn}from"react/jsx-runtime";function qs(e){let t=j(e.locale),n=e.descriptor.fields.find((s)=>s.id===e.view.groupByFieldId),i=qn(e),o=Bs(null),[r,a]=Us(null);if(!n||!["singleSelect","checkbox"].includes(n.type))return Se("p",{role:"status",children:t("Choose a single-select or boolean grouping field.")});let d=io(n,t);return nn("section",{"data-uibot":"collection-kanban",children:[Se(Jt,{...e}),Se("div",{style:{display:"flex",gap:12,overflowX:"auto",alignItems:"flex-start",paddingBottom:12},children:d.map((s)=>Se($s,{...e,field:n,lane:s,lanes:d,blocked:i.blocked,onOpen:a,onMove:(c,u)=>void i.move(c,{[n.id]:u.value}),onDrag:(c)=>{o.current=c},onDrop:(c)=>{if(o.current?.id===c)i.move(o.current,{[n.id]:s.value});o.current=null}},s.id))}),Se($n,{state:i,locale:e.locale,ui:e.ui}),r&&Se(Tt,{...e,row:r,onClose:()=>a(null)},r.id)]})}function $s({field:e,lane:t,lanes:n,blocked:i,onOpen:o,onMove:r,onDrag:a,onDrop:d,...s}){let c=j(s.locale),u=qe(s.features),m=u.optionChips,p=!s.readOnly&&u.rowUpdate,l=Zt(s,so(s.view,e,t)),C=s.descriptor.fields.find((g)=>g.type==="singleLineText"||g.type==="longText")?.id,b=ut(s.descriptor.fields,s.view).filter((g)=>g.id!==e.id&&g.id!==C).slice(0,3),y=p&&!i&&!(e.required&&t.value===null);return nn("section",{"aria-label":c("Lane {name}",{name:t.name}),"data-lane-id":t.id,style:{...Ke,flex:"0 0 290px",minWidth:0,...m?{background:"var(--muted, #f4f6f8)",padding:10}:{}},onDragOver:(g)=>{if(y)g.preventDefault()},onDrop:(g)=>{if(!y)return;g.preventDefault(),d(g.dataTransfer.getData("application/x-uibot-record"))},children:[nn("h3",{style:m?{display:"flex",alignItems:"center",gap:6,margin:"0 0 6px",fontSize:13}:void 0,children:[m&&Se("span",{"aria-hidden":"true",style:{width:8,height:8,borderRadius:999,...t.id.startsWith("option:")?{background:Mt(zs(n,t)).color}:{background:"var(--muted-foreground, #9a9892)"}}}),t.name," · ",hr(c,l.page.total,l.page.items.length,s.locale)]}),Se(Qt,{state:l,locale:s.locale,ui:s.ui,hideCount:!0}),nn("div",{style:{display:"flex",flexDirection:"column",gap:8,marginTop:12,maxHeight:"65vh",overflowY:"auto"},children:[l.page.items.map((g)=>{let v=ze(g,s.descriptor.fields);return nn("article",{"data-record-id":g.id,style:m?{...Ke,padding:10,boxShadow:"0 1px 2px rgb(0 0 0 / 0.06)",cursor:"grab",position:"relative"}:Ke,draggable:p&&!i&&!l.loading,onDragStart:(f)=>{a(g),f.dataTransfer.setData("application/x-uibot-record",g.id),f.dataTransfer.effectAllowed="move"},onDragEnd:()=>a(null),children:[Se("button",{type:"button",style:{...se,width:"100%",textAlign:"left",overflowWrap:"anywhere",...m?{border:0,padding:"0 28px 0 0",background:"transparent",fontWeight:600}:{}},"aria-label":c("Open {name}",{name:v}),onClick:()=>o(g),children:v}),m&&Se(js,{row:g,fields:b}),p&&(s.ui?.DropdownMenu?Se("span",{style:{position:"absolute",top:4,right:4},children:s.ui.DropdownMenu({label:c("Move {name}",{name:v}),icon:Se(Ee,{name:"more"}),disabled:i||l.loading,items:n.map((f)=>({id:f.id,label:c("Move to {name}",{name:f.name}),disabled:f.id===t.id||!!e.required&&f.value===null,onSelect:()=>r(g,f)}))})}):nn("div",{style:{display:"flex",flexDirection:"column",gap:4,marginTop:8},children:[Se("span",{children:c("Move to")}),Se(Pe,{ui:s.ui,label:c("Move {name}",{name:v}),style:se,disabled:i||l.loading,value:t.id,onChange:(f)=>{let S=n.find((R)=>R.id===f);if(S&&S.id!==t.id)r(g,S)},options:n.map((f)=>({value:f.id,label:f.name,disabled:!!e.required&&f.value===null}))})]}))]},g.id)}),!l.loading&&!l.error&&!l.page.items.length&&Se("p",{children:c("No records in this lane.")})]})]})}function js({row:e,fields:t}){let n=t.map((i)=>{let o=e.values[i.id],r=i.type==="singleSelect"||i.type==="multipleSelect",a=Array.isArray(o)?o:o==null?[]:[o],d=i.type==="linkedRecord"?ln(e,i):$t(o,i,e.computedErrors?.[i.id]);return{field:i,chips:r,ids:a,text:d}}).filter((i)=>i.chips?i.ids.length>0:i.text!=="");if(!n.length)return null;return Se("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:6,alignItems:"center",fontSize:12,opacity:0.85},children:n.map((i)=>i.chips?Se(Yn,{ids:i.ids,field:i.field},i.field.id):Se("span",{style:{fontVariantNumeric:"tabular-nums"},children:i.text},i.field.id))})}function zs(e,t){return e.filter((n)=>n.id.startsWith("option:")).findIndex((n)=>n.id===t.id)}import{useState as Hs}from"react";import{jsx as rt,jsxs as Lr}from"react/jsx-runtime";function Ks(e){let t=j(e.locale),n=qe(e.features).optionChips,i=Zt(e,An(e.view)),[o,r]=Hs(null),a=e.descriptor.fields.find((s)=>s.type==="singleLineText"||s.type==="longText")?.id,d=ut(e.descriptor.fields,e.view).filter((s)=>!n||s.id!==a);return Lr("section",{"data-uibot":"collection-gallery",children:[rt(Jt,{...e}),rt(Qt,{state:i,locale:e.locale,ui:e.ui}),rt("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(min(100%, 240px), 1fr))",gap:12,marginTop:12},children:i.page.items.map((s)=>Lr("article",{"data-record-id":s.id,style:{...Ke,minWidth:0,...n?{boxShadow:"0 1px 2px rgb(0 0 0 / 0.05)"}:{}},children:[rt("button",{type:"button","aria-label":t("Open {name}",{name:ze(s,e.descriptor.fields)}),style:{...se,width:"100%",textAlign:"left",overflowWrap:"anywhere",...n?{border:0,padding:0,background:"transparent",fontWeight:600,fontSize:"var(--uibot-workspace-font-size, 13px)"}:{}},onClick:()=>r(s),children:ze(s,e.descriptor.fields)}),rt("dl",{children:d.filter((c)=>!n||!Ws(s,c)).slice(0,n?5:d.length).map((c)=>Lr("div",{children:[rt("dt",{style:{fontSize:12,opacity:0.7},children:c.name}),rt("dd",{style:{margin:"0 0 8px",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n&&(c.type==="singleSelect"||c.type==="multipleSelect")&&s.values[c.id]!=null?rt(Yn,{ids:Array.isArray(s.values[c.id])?s.values[c.id]:[s.values[c.id]],field:c}):(c.type==="linkedRecord"?ln(s,c):$t(s.values[c.id],c,s.computedErrors?.[c.id]))||"—"})]},c.id))})]},s.id))}),!i.loading&&!i.error&&!i.page.items.length&&rt("p",{children:t("No records match this view.")}),o&&rt(Tt,{...e,row:o,onClose:()=>r(null)},o.id)]})}function Ws(e,t){let n=e.values[t.id];if(t.type==="linkedRecord")return!ln(e,t);return n==null||n===""||Array.isArray(n)&&n.length===0}import{useRef as Ys,useState as Or}from"react";import{jsx as be,jsxs as Ct}from"react/jsx-runtime";function Gs(e){let t=j(e.locale),n=qe(e.features),i=n.optionChips,o=!e.readOnly&&n.rowUpdate,[r,a]=Or(()=>{let f=new Date().toISOString().slice(0,7),S=e.initialMonth??f;try{return dn(S),{month:S,error:""}}catch{return{month:f,error:t("Invalid initial month. Showing the current UTC month.")}}}),{month:d,error:s}=r,[c,u]=Or(null),m=e.descriptor.fields.find((f)=>f.id===e.view.dateFieldId&&f.type==="date"),p=Ys(null),l=qn(e),C=Zt(e,m?lo(e.view,m.id,d):{limit:1},!!m),b=dn(d),y=(f)=>{try{dn(f),a({month:f,error:""})}catch{a((S)=>({...S,error:t("Choose a valid month between years 1 and 9998.")}))}},g=(f)=>{let S=new Date(b.start);S.setUTCMonth(S.getUTCMonth()+f),y(S.toISOString().slice(0,7))},v=(f,S)=>{if(!m)return;try{l.move(f,{[m.id]:Dn(f.values[m.id],S)})}catch(R){l.mutation.setError(R instanceof Error?R.message:t("Invalid date"))}};if(!m)return be("p",{role:"status",children:t("Choose a date field for this calendar.")});return Ct("section",{"data-uibot":"collection-calendar",children:[be(Jt,{...e}),Ct("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",marginBottom:12},children:[be(Y,{ui:e.ui,style:se,variant:"ghost",icon:"chevronLeft",iconOnly:!0,ariaLabel:t("Previous month"),onClick:()=>g(-1)}),e.ui?.MonthPicker?be(e.ui.MonthPicker,{value:d,onChange:y,"aria-label":t("Calendar month")}):e.ui?.Button?be("strong",{role:"status","aria-label":t("Calendar month"),style:{minWidth:96,textAlign:"center",fontVariantNumeric:"tabular-nums"},children:t("{year}-{month}",{year:d.slice(0,4),month:d.slice(5,7)})}):Ct("label",{children:[t("Month")," ",be("input",{type:"month","aria-label":t("Calendar month"),min:"0001-01",max:"9998-12",value:d,onChange:(f)=>y(f.target.value),style:se})]}),be(Y,{ui:e.ui,style:se,variant:"ghost",icon:"chevronRight",iconOnly:!0,ariaLabel:t("Next month"),onClick:()=>g(1)}),be(Y,{ui:e.ui,style:se,variant:"outline",size:"sm",onClick:()=>y(new Date().toISOString().slice(0,7)),children:t("Today")})]}),s&&be("p",{role:"alert",children:s}),be(Qt,{state:C,locale:e.locale,ui:e.ui}),be("div",{style:{overflowX:"auto",minWidth:0},children:Ct("div",{style:{display:"grid",gridTemplateColumns:"repeat(7, minmax(0, 1fr))"},children:[[t("Sun"),t("Mon"),t("Tue"),t("Wed"),t("Thu"),t("Fri"),t("Sat")].map((f)=>be("strong",{style:i?{padding:"8px 10px",fontSize:12,background:"var(--muted, #f4f6f8)",borderBottom:"1px solid var(--border, #d5d9df)"}:{padding:8},children:f},f)),["sun","mon","tue","wed","thu","fri","sat"].slice(0,b.weekday).map((f)=>be("div",{"aria-hidden":"true",style:i?{borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",background:"var(--muted, #f4f6f8)",opacity:0.5}:void 0},f)),Array.from({length:b.days},(f,S)=>{let R=`${d}-${String(S+1).padStart(2,"0")}`,k=C.page.items.filter((A)=>String(A.values[m.id]??"").slice(0,10)===R);return Ct("article",{"aria-label":t("Day {day}",{day:R}),"data-calendar-day":R,style:{...Ke,minHeight:130,maxHeight:280,overflowY:"auto",minWidth:0,borderRadius:0,...i?{padding:8,border:0,borderRight:"1px solid var(--border, #d5d9df)",borderBottom:"1px solid var(--border, #d5d9df)",fontSize:12}:{}},onDragOver:(A)=>{if(o&&!l.blocked)A.preventDefault()},onDrop:(A)=>{if(!o||l.blocked)return;if(A.preventDefault(),p.current?.id===A.dataTransfer.getData("application/x-uibot-record"))v(p.current,R);p.current=null},children:[be("time",{dateTime:R,children:S+1}),k.map((A)=>Ct("article",{"data-record-id":A.id,style:{marginTop:8},draggable:o&&!l.blocked&&!C.loading,onDragStart:(E)=>{p.current=A,E.dataTransfer.setData("application/x-uibot-record",A.id),E.dataTransfer.effectAllowed="move"},onDragEnd:()=>{p.current=null},children:[Ct("button",{type:"button",style:{...se,textAlign:"left",width:"100%",overflowWrap:"anywhere",...i?{border:0,padding:"3px 8px",fontSize:12,fontWeight:500,...Mt(0)}:{}},"aria-label":t("Open {name}",{name:ze(A,e.descriptor.fields)}),onClick:()=>u(A),children:[ze(A,e.descriptor.fields)," ",be("small",{children:String(A.values[m.id]).slice(11,16)})]}),o&&be(Js,{ui:e.ui,t,row:A,fieldId:m.id,title:ze(A,e.descriptor.fields),disabled:l.blocked||C.loading,onMove:v})]},A.id))]},R)})]})}),!C.loading&&!C.error&&!C.page.items.length&&be("p",{children:t("No dated records match this month.")}),be($n,{state:l,locale:e.locale,ui:e.ui}),!l.intent&&l.mutation.error&&be("p",{role:"alert",children:l.mutation.error}),c&&be(Tt,{...e,row:c,onClose:()=>u(null)},c.id)]})}function Js({ui:e,t,row:n,fieldId:i,title:o,disabled:r,onMove:a}){let[d,s]=Or({day:String(n.values[i]).slice(0,10)}),c=e?.DateMove;if(c)return be(c,{label:t("Move {name} to date",{name:o}),value:d.day,disabled:r,onPick:(u)=>a(d.baseline??n,u)});return Ct("div",{style:{marginTop:4,display:"flex",gap:4,flexWrap:"wrap"},children:[be("input",{type:"date","aria-label":t("Move {name} to date",{name:o}),value:d.day,disabled:r,style:{width:"100%",minWidth:0},onChange:(u)=>s({day:u.target.value,baseline:d.baseline??n})}),be("button",{type:"button",style:se,"aria-label":t("Move {name}",{name:o}),disabled:r||!d.day,onClick:()=>a(d.baseline??n,d.day),children:t("Move")})]})}import{jsx as dt,jsxs as rn}from"react/jsx-runtime";function jm({fields:e,view:t,onChange:n,locale:i,ui:o,features:r,sections:a,filterEditor:d,grouping:s,rowHeight:c}){let u=j(i),m=qe(r),p=e.filter((v)=>v.type==="singleSelect"||v.type==="checkbox"),l=e.filter((v)=>v.type==="date"),C=(v)=>{let f={...t,type:v};if(delete f.groupByFieldId,delete f.dateFieldId,v==="kanban"&&p[0])f.groupByFieldId=p[0].id;if(v==="calendar"&&l[0])f.dateFieldId=l[0].id;if(v==="form")f.hiddenColumns=f.hiddenColumns.filter((S)=>!e.find((R)=>R.id===S)?.required);n(f)},b={grid:u("Grid"),kanban:u("Kanban"),gallery:u("Gallery"),calendar:u("Calendar"),form:u("Form")},y=m.viewTypes.map((v)=>({value:v,label:b[v],disabled:v==="kanban"&&!p.length||v==="calendar"&&!l.length})),g=t.type??"grid";return rn("div",{style:{display:"flex",gap:12,flexWrap:"wrap",alignItems:"center"},children:[rn("div",{children:[u("View type")," ",dt(Pe,{ui:o,label:u("View type"),style:se,value:g,options:y,onChange:(v)=>C(v)})]}),g==="grid"&&m.groupBy&&p.length>0&&s!==!1&&dt("div",{style:{flexBasis:"100%"},children:dt(Qo,{fields:e,view:t,onChange:n,locale:i,ui:o})}),g==="grid"&&c!==!1&&rn("div",{children:[u("Row height")," ",dt(Pe,{ui:o,label:u("Row height"),style:se,value:t.rowHeight??"short",options:qr.map((v)=>({value:v,label:u(`Row height ${v}`)})),onChange:(v)=>{let f={...t};if(v==="short")delete f.rowHeight;else f.rowHeight=v;n(f)}})]}),g==="kanban"&&rn("div",{children:[u("Group by")," ",dt(Pe,{ui:o,label:u("Kanban grouping field"),style:se,value:t.groupByFieldId??"",options:p.map((v)=>({value:v.id,label:v.name})),onChange:(v)=>n({...t,groupByFieldId:v})})]}),g==="calendar"&&rn("div",{children:[u("Date field")," ",dt(Pe,{ui:o,label:u("Calendar date field"),style:se,value:t.dateFieldId??"",options:l.map((v)=>({value:v.id,label:v.name})),onChange:(v)=>n({...t,dateFieldId:v})})]}),(a?.filter||a?.columns||a?.sort)&&rn("div",{style:{display:"grid",gap:12,flexBasis:"100%"},children:[a?.filter&&dt(Go,{fields:e,view:t,onChange:n,locale:i,ui:o,editor:d}),a?.columns&&dt(Zo,{fields:e,view:t,onChange:n,locale:i,ui:o}),a?.sort&&dt(Jo,{fields:e,view:t,onChange:n,locale:i,ui:o})]})]})}export{$a as CollectionAggregateRows,mr as CollectionAggregateSummary,Gs as CollectionCalendar,Ga as CollectionForm,Ks as CollectionGallery,qs as CollectionKanban,Tt as CollectionRecordEditor,jm as CollectionViewSettings,_s as CollectionViewTabs,fn as PAGED_TABLE_ICONS,Kn as PagedCollectionFilterBuilder,ps as PagedCollectionRecordCreator,ws as PagedCollectionSchemaEditor,cs as PagedCollectionTableHeader,ds as PagedCollectionTableList,Wn as PagedTableIcon,zn as dateModeLabel,jn as filterOperatorLabel,jo as pagedFilterSummary};
|