@kronor/dtv 2.0.0 → 2.0.1

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/README.md CHANGED
@@ -4,7 +4,7 @@ This project is a React + TypeScript monorepo for building schema-driven, declar
4
4
 
5
5
  ## Library Consumption
6
6
 
7
- You can consume the `App` component as a library bundle with embedded styles (Tailwind + PrimeReact + PrimeIcons + PrimeFlex) without importing separate CSS files.
7
+ You can consume the `App` component as a library bundle with embedded styles (Tailwind + PrimeReact + PrimeIcons) without importing separate CSS files.
8
8
 
9
9
  ### Build the library
10
10
 
@@ -2206,4 +2206,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
2206
2206
  `)}function j7(e,r,t){const l=new Map(e);return Object.entries(r).forEach(([n,s])=>{const p=t.filters.find(d=>d.id===n);if(p){const d=e.get(n)||ju(p.expression),m=ld(p.expression,d,s);l.set(n,m)}}),l}function ld(e,r,t){var l,n,s,p;if(!t)return r;if((e.type==="in"||e.type==="notIn")&&t.type==="or"&&Array.isArray(t.children)){const d=(g,h)=>(g&&(g.type==="leaf"?g.value!==void 0&&g.value!==""&&h.push(g.value):g.type==="or"&&Array.isArray(g.children)&&g.children.forEach(S=>d(S,h))),h),m=Array.from(new Set(d(t,[])));return{...r,type:"leaf",value:m}}if(r.type==="leaf"&&t.type==="not"&&((l=t.child)==null?void 0:l.type)==="leaf"){const m=e.value;if(m.type==="customOperator"){const g=t.child.value,h=(n=m.operators)==null?void 0:n.find(S=>S.value.includes("neq")||S.value.includes("not_equals")||S.label.toLowerCase().includes("not equals"));if(h){const S=typeof g=="string"?{operator:h.value,value:g}:g;return{...r,value:S}}}}if(r.type==="leaf"&&t.type==="leaf"){let d=t.value;const m=e,g=m.value;if((m.type==="in"||m.type==="notIn")&&(Array.isArray(d)||(d=[d])),g.type==="customOperator"&&typeof d=="string"&&(d={operator:(p=(s=g.operators)==null?void 0:s[0])==null?void 0:p.value,value:d}),g.type==="date"&&typeof d=="string"){const h=new Date(d);isNaN(h.getTime())?console.warn(`Failed to parse date for field ${m.field}:`,d):d=h}return{...r,value:d}}return r.type==="and"&&e.type==="and"&&t.type==="and"&&Array.isArray(t.children)?{...r,children:r.children.map((d,m)=>{const g=e.filters[m],h=t.children[m];return g?ld(g,d,h):d})}:r.type==="or"&&e.type==="or"&&t.type==="or"&&Array.isArray(t.children)?{...r,children:r.children.map((d,m)=>{const g=e.filters[m],h=t.children[m];return g?ld(g,d,h):d})}:r.type==="not"&&e.type==="not"&&t.type==="not"?{...r,child:ld(e.filter,r.child,t.child)}:r}const L7={async sendPrompt(e,r,t,l,n){var p,d,m,g,h;const s=_7(e,r);try{const S=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent?key=${l}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:[{role:"user",parts:[{text:s}]}]})});if(!S.ok)throw new Error("Gemini API error");const $=(((h=(g=(m=(d=(p=(await S.json()).candidates)==null?void 0:p[0])==null?void 0:d.content)==null?void 0:m.parts)==null?void 0:g[0])==null?void 0:h.text)||"").match(/\{[\s\S]*\}/);if($){const D=JSON.parse($[0]),K=Od(e,us.Empty),U=j7(K,D,e);t(U)}else{const D="Could not parse FilterFormState from Gemini response. Check the console.";n!=null&&n.current?n.current.show({severity:"warn",summary:"Parse Error",detail:D,life:3e3}):alert(D)}}catch(S){console.error(S);const x="Failed to get response from Gemini API.";n!=null&&n.current?n.current.show({severity:"error",summary:"API Error",detail:x,life:3e3}):alert(x)}}};function F7(e,r,t,l,n,s){return l.sendPrompt(e,r,t,n,s)}function B7({setFilterState:e,selectedView:r,geminiApiKey:t,toast:l,setShowFilterForm:n}){const[s,p]=c.useState("authorized payments in euro or danish krona in the first week of april 2025"),[d,m]=c.useState(!1);return qe.jsxs("div",{className:"tw:flex tw:flex-col tw:gap-2 tw:mb-3",children:[qe.jsx("label",{className:"tw:text-sm tw:font-semibold tw:mb-1",htmlFor:"ai-prompt",children:"AI Prompt"}),qe.jsxs("div",{className:"tw:flex tw:gap-2",children:[qe.jsx(A7,{value:s,onChange:p}),qe.jsx(mr,{type:"button",outlined:!0,label:"Update filters",icon:"pi pi-sparkles",loading:d,onClick:async()=>{var g,h;m(!0);try{await F7(r.filterSchema,s,e,L7,t,l),n(!0),(g=l.current)==null||g.show({severity:"success",summary:"AI Filter Generated",detail:"Filter values have been populated based on your prompt",life:3e3})}catch(S){console.error("AI filter generation failed:",S),(h=l.current)==null||h.show({severity:"error",summary:"AI Generation Failed",detail:"Failed to generate filter from AI. Please try again.",life:3e3})}finally{m(!1)}},className:"p-button-secondary"})]})]})}function z7({savedFilters:e,onFilterDelete:r,onFilterLoad:t,onFilterApply:l,onFilterShare:n,visible:s,filterSchema:p}){if(!s)return null;const d=O=>{z2({message:`Are you sure you want to delete the filter "${O.name}"? This action cannot be undone.`,header:"Confirm Filter Deletion",icon:"pi pi-exclamation-triangle",defaultFocus:"reject",acceptClassName:"p-button-danger",accept:()=>{r(O.id)},reject:()=>{}})},m=O=>new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(O);function g(O){return typeof O=="object"&&O!==null&&"value"in O?Array.isArray(O.value)?O.value.length>0:typeof O.value=="object"&&O.value!==null&&"value"in O.value?g(O.value):O.value!=="":!1}const h=new Map(p.filters.map(O=>[O.id,O]));function S(O){const $=h.get(O);if(!$)return"";const D=$.expression;if(D&&"field"in D){const K=D.field;if(typeof K=="string")return K;if(K&&typeof K=="object"){if("and"in K&&Array.isArray(K.and))return K.and.join(" & ");if("or"in K&&Array.isArray(K.or))return K.or.join(" | ")}}return""}const x=O=>{if(!O||O.size===0)return null;const $=Array.from(O.entries()).filter(([,D])=>g(D));return $.length===0?null:qe.jsx("div",{className:"tw:mt-2 tw:flex tw:flex-wrap tw:gap-1",children:$.map(([D,K],U)=>{let I="";if(K.type==="leaf"){const N=typeof K.value=="string"&&K.value.length>128?`${K.value.substring(0,128)}...`:String(K.value),B=S(D);I=B?`${B}: ${N}`:N}else K.type==="and"||K.type==="or"?I=`${K.type.toUpperCase()} (${K.children.length} filters)`:K.type==="not"&&(I="NOT (1 filter)");return qe.jsx(hg,{value:I,className:"tw:text-xs",style:{backgroundColor:"transparent",color:"#6366f1",borderWidth:1}},U)})})};return qe.jsxs("div",{className:"tw:mb-4",children:[qe.jsx("div",{className:"tw:mb-3",children:qe.jsx("h3",{className:"tw:text-lg tw:font-medium tw:text-gray-900",children:"Saved Filters"})}),e.length===0?qe.jsx("p",{className:"tw:text-gray-500 tw:text-center tw:py-4",children:"No saved filters for this view"}):qe.jsx("div",{className:"tw:space-y-3",children:e.map(O=>qe.jsxs("div",{className:"tw:flex tw:items-center tw:justify-between tw:p-3 tw:border tw:border-gray-200 tw:rounded-lg",children:[qe.jsxs("div",{className:"tw:flex-1",children:[qe.jsxs("div",{className:"tw:flex tw:items-center tw:gap-2 tw:mb-1",children:[qe.jsx("h4",{className:"tw:font-medium tw:text-gray-900",children:O.name}),qe.jsxs("span",{className:"tw:text-xs tw:text-gray-500 tw:bg-gray-100 tw:px-2 tw:py-1 tw:rounded",children:["Created: ",m(O.createdAt)]})]}),x(O.state)]}),qe.jsxs("div",{className:"tw:flex tw:gap-2",children:[qe.jsx(mr,{size:"small",outlined:!0,icon:"pi pi-filter",label:"Use",onClick:()=>{t(O.state),l()},className:"p-button"}),qe.jsx(mr,{size:"small",outlined:!0,icon:"pi pi-share-alt",label:"Share",onClick:()=>n(O.state),className:"p-button-secondary"}),qe.jsx(mr,{size:"small",outlined:!0,icon:"pi pi-trash",label:"Delete",onClick:()=>d(O),className:"p-button-danger"})]})]},O.id))})]})}function $7(e,r){function t(p,d){if(typeof p=="object"){if("and"in p)return{_and:p.and.map(g=>l(g,d))};if("or"in p)return{_or:p.or.map(g=>l(g,d))}}return typeof p=="string"?l(p,d):{}}function l(p,d){return p.includes(".")?p.split(".").reverse().reduce((g,h)=>({[h]:g}),d):{[p]:d}}function n(p,d){return Pu(p,d,{leaf:(m,g)=>{var $;let h=g.value,S=m.field;if((($=m.transform)==null?void 0:$.toQuery)!==void 0){const D=m.transform.toQuery(g.value);if("condition"in D)return D.condition;"field"in D&&D.field!==void 0&&(S=D.field),"value"in D&&D.value!==void 0&&(h=D.value)}if(m.value.type==="customOperator"){const D=h;return!D||!D.operator||D.value===void 0||D.value===""||D.value===null||Array.isArray(D.value)&&D.value.length===0?null:t(S,{[D.operator]:D.value})}if(h===void 0||h===""||h===null||Array.isArray(h)&&h.length===0)return null;const O={equals:"_eq",notEquals:"_neq",greaterThan:"_gt",lessThan:"_lt",greaterThanOrEqual:"_gte",lessThanOrEqual:"_lte",in:"_in",notIn:"_nin",like:"_like",iLike:"_ilike",isNull:"_is_null"}[m.type];return O?t(S,{[O]:h}):null},and:(m,g,h)=>{const S=h.filter(x=>x!==null);return S.length===0?null:{_and:S}},or:(m,g,h)=>{const S=h.filter(x=>x!==null);return S.length===0?null:{_or:S}},not:(m,g,h)=>h?{_not:h}:null})}const s=[];for(const[p,d]of e.entries()){const m=r.filters.find(h=>h.id===p);if(!m)continue;const g=n(m.expression,d);g&&s.push(g)}return s.length===0?{}:s.length===1?s[0]:{_and:s}}function M0(e,r){if(e===r)return!0;if(typeof e!="object"||typeof r!="object"||e===null||r===null)return!1;const t=Object.keys(e),l=Object.keys(r);if(t.length!==l.length)return!1;for(const n of t){if(!l.includes(n))return!1;const s=e[n],p=r[n];if(!Kv(s,p))return!1}return!0}function Kv(e,r){if(e===r)return!0;if(typeof e!=typeof r||e===null||r===null)return!1;if(Array.isArray(e)&&Array.isArray(r)){if(e.length!==r.length)return!1;for(let t=0;t<e.length;t++)if(!Kv(e[t],r[t]))return!1;return!0}if(typeof e=="object"&&typeof r=="object"){const t=Object.keys(e),l=Object.keys(r);if(t.length!==l.length)return!1;for(const n of t)if(!l.includes(n)||!Kv(e[n],r[n]))return!1;return!0}return!1}function od(e,r,t){if(e.length!==r.length)return!1;const l=new Array(r.length).fill(!1);for(const n of e){let s=!1;for(let p=0;p<r.length;p++)if(!l[p]&&t(n,r[p])){l[p]=!0,s=!0;break}if(!s)return!1}return!0}function Hc(e,r){if(e===r)return!0;const t=d=>"_and"in d&&Array.isArray(d._and),l=d=>"_or"in d&&Array.isArray(d._or),n=d=>"_not"in d&&typeof d._not=="object"&&d._not!==null&&!Array.isArray(d._not);if(t(e)||t(r))return!t(e)||!t(r)?!1:od(e._and,r._and,Hc);if(l(e)||l(r))return!l(e)||!l(r)?!1:od(e._or,r._or,Hc);if(n(e)||n(r))return!n(e)||!n(r)?!1:Hc(e._not,r._not);const s=Object.keys(e),p=Object.keys(r);if(s.length!==p.length)return!1;for(const d of s){if(!p.includes(d))return!1;const m=e[d],g=r[d];if(Array.isArray(m)||Array.isArray(g)){if(!Array.isArray(m)||!Array.isArray(g)||!od(m,g,M0))return!1}else{const h=S=>typeof S=="object"&&S!==null&&Object.keys(S).every(x=>x.startsWith("_"));if(h(m)||h(g)){if(!h(m)||!h(g)||!M0(m,g))return!1}else if(!Hc(m,g))return!1}}return!0}function H7(e,r){const t=[...e],l=(p,d)=>{if(!p&&!d)return!0;if(!p||!d||p.length!==d.length)return!1;for(let m=0;m<p.length;m++)if(!s(p[m],d[m]))return!1;return!0},n=(p,d)=>{if(p===d)return!0;if(!p||!d)return!1;const m=g=>Array.isArray(g)?g.map(h=>JSON.stringify(h)).join("|"):JSON.stringify(g);return m(p)===m(d)},s=(p,d)=>p.field===d.field&&p.alias===d.alias&&p.path===d.path&&p.limit===d.limit&&od(p.distinct_on||[],d.distinct_on||[],(m,g)=>m===g)&&n(p.order_by,d.order_by)&&(p.where&&d.where?Hc(p.where,d.where):p.where===d.where)&&l(p.selections,d.selections);for(const p of r)t.find(m=>s(m,p))||t.push(p);return t}function U7(e){function r(n){if(n.type==="valueQuery"){const s={field:n.field};return n.path&&(s.path=n.path),s}if(n.type==="objectQuery"){const s={field:n.field};return n.path&&(s.path=n.path),Array.isArray(n.selectionSet)&&n.selectionSet.length&&(s.selections=n.selectionSet.map(r).filter(p=>!!p)),s}if(n.type==="arrayQuery"){const s={field:n.field};if(n.path&&(s.path=n.path),n.orderBy){const p=d=>Array.isArray(d)?d.map(m=>({[m.key]:m.direction.toUpperCase()})):{[d.key]:d.direction.toUpperCase()};s.order_by=p(n.orderBy)}return n.distinctOn&&(s.distinct_on=n.distinctOn),n.limit!==void 0&&(s.limit=n.limit),n.where&&(s.where=n.where),Array.isArray(n.selectionSet)&&n.selectionSet.length&&(s.selections=n.selectionSet.map(r).filter(p=>!!p)),s}return null}function t(n){if(n.type==="fieldAlias"){const s=t(n.field);return s&&(s.alias=n.alias,s)}else if(n.type==="valueQuery"||n.type==="objectQuery"||n.type==="arrayQuery")return r(n);return null}return e.flatMap(n=>n.data.map(t).filter(s=>!!s)).reduce((n,s)=>H7(n,[s]),[])}function H2(e,r,t,l,n){const s=U7(r);if(!s.some(d=>d.field===n||d.alias===n)){const d=m=>{const g=m.split("."),h=g[0];return g.length===1?{field:h}:{field:h,selections:[d(g.slice(1).join("."))]}};s.push(d(n))}return{operation:"query",variables:[{name:"conditions",type:`${t}!`},{name:"paginationCondition",type:`${t}!`},{name:"rowLimit",type:"Int"},{name:"orderBy",type:l}],rootField:`${e}(where: {_and: [$conditions, $paginationCondition]}, limit: $rowLimit, orderBy: $orderBy)`,selectionSet:s}}function V7(e,r,t,l,n){const s=H2(e,r,t,l,n);return U2(s)}function U2(e){function r(d){return d.length?"("+d.map(m=>`$${m.name}: ${m.type}`).join(", ")+")":""}function t(d){const m=[];if(d.where){const g=h=>Array.isArray(h)?`[${h.map(g).join(", ")}]`:typeof h=="object"&&h!==null?"_and"in h&&Array.isArray(h._and)?`_and: [${h._and.map(g).join(", ")}]`:"_or"in h&&Array.isArray(h._or)?`_or: [${h._or.map(g).join(", ")}]`:"_not"in h?`_not: {${g(h._not)}}`:Object.entries(h).map(([S,x])=>Array.isArray(x)?`${S}: [${x.map(g).join(", ")}]`:typeof x=="object"&&x!==null?`${S}: {${Object.entries(x).map(([O,$])=>`${O}: ${typeof $=="string"?`"${$}"`:JSON.stringify($)}`).join(", ")}}`:`${S}: ${typeof x=="string"?`"${x}"`:JSON.stringify(x)}`).join(", "):JSON.stringify(h);m.push(`where: {${g(d.where)}}`)}if(d.limit!==void 0&&m.push(`limit: ${d.limit}`),d.path&&m.push(`path: "${d.path}"`),d.distinct_on&&d.distinct_on.length){const g=d.distinct_on.map(h=>String(h)).join(", ");m.push(`distinctOn: [${g}]`)}if(d.order_by){const g=h=>Array.isArray(h)?"["+h.map(g).join(", ")+"]":typeof h=="object"&&h!==void 0?"{"+Object.entries(h).map(([S,x])=>`${S}: ${String(x).toUpperCase()}`).join(", ")+"}":String(h).toUpperCase();m.push(`orderBy: ${g(d.order_by)}`)}return m.length?`(${m.join(", ")})`:""}function l(d,m=" "){return d.map(g=>{const h=t(g),S=g.alias?`${g.alias}: ${g.field}`:g.field;return g.selections&&g.selections.length?`${m}${S}${h} {`+l(g.selections,m+" ")+`${m}}`:`${m}${S}${h}`}).join(`
2207
2207
  `)}const n=r(e.variables),s=l(e.selectionSet),p=e.name?` ${e.name}`:"";return`${e.operation}${p}${n} { ${e.rootField} {`+s+`
2208
2208
  }
2209
- }`}function K7(e,r){return typeof e=="object"&&e!==null&&r in e&&Array.isArray(e[r])}let N0=0;const V2=(e,r,t,l)=>{let n=$7(r,e.filterSchema);e.staticConditions&&e.staticConditions.length>0&&(n={_and:[n,...e.staticConditions]});const s=l!==null?{[e.paginationKey]:{_lt:l}}:{},p={[e.paginationKey]:"DESC"},d=e.staticOrdering&&e.staticOrdering.length>0?[p,...e.staticOrdering]:[p];return{conditions:n,paginationCondition:s,rowLimit:t,orderBy:d}},G7=async({client:e,view:r,query:t,filterState:l,rowLimit:n,cursor:s})=>{const p=++N0;try{const d=V2(r,l,n,s),m=await e.request(t,d);if(p!==N0)throw new DOMException("Request superseded by newer request","AbortError");if(!K7(m,r.collectionName))return console.error("Error fetching data, unexpected response format:",m),{rows:[],flattenedRows:[]};const g=m[r.collectionName];return{rows:g,flattenedRows:Y7(g,r.columnDefinitions)}}catch(d){if(d instanceof DOMException&&d.name==="AbortError")throw d;return console.error("Error fetching data:",d),{rows:[],flattenedRows:[]}}},Y7=(e,r)=>e.map(t=>r.map(l=>q7(t,l))),q7=(e,r)=>{const t={};function l(s){if(!(!s||typeof s!="object"))switch(s.type){case"fieldAlias":return e[s.alias]!==void 0?e[s.alias]:l(s.field);case"valueQuery":case"objectQuery":case"arrayQuery":return e[s.field];default:return}}function n(s){if(!(!s||typeof s!="object")){if(s.type==="fieldAlias"){const p=s.alias;if(e[p]!==void 0)t[p]=e[p];else{const d=l(s.field);d!==void 0&&(t[p]=d)}return}(s.type==="valueQuery"||s.type==="objectQuery"||s.type==="arrayQuery")&&e[s.field]!==void 0&&(t[s.field]=e[s.field])}}return r.data.forEach(n),t};function X7(e){return"field"in e&&"value"in e}function Gv(e){const r=[];if(X7(e))r.push(e);else if(e.type==="and"||e.type==="or")for(const t of e.filters)r.push(...Gv(t));else e.type==="not"&&r.push(...Gv(e.filter));return r}function Fu(e,r,t){const{section:l,key:n}=e;if(r&&r[l]&&r[l][n]!==void 0)return r[l][n];if(t[l]&&t[l][n]!==void 0)return t[l][n];const s=r?Object.keys(r[l]||{}):[],p=Object.keys(t[l]||{}),d=[...new Set([...s,...p])];throw new Error(`Reference "${n}" not found in ${l}. Available keys: ${d.join(", ")}`)}function Bu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid RuntimeReference: Expected an object");const r=e;if(typeof r.section!="string")throw new Error('Invalid RuntimeReference: "section" must be a string');if(typeof r.key!="string")throw new Error('Invalid RuntimeReference: "key" must be a string');const t=["cellRenderers","noRowsComponents","customFilterComponents","queryTransforms","initialValues","suggestionFetchers"];if(!t.includes(r.section))throw new Error(`Invalid RuntimeReference: "section" must be one of: ${t.join(", ")}`);return{section:r.section,key:r.key}}function P0(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid orderBy: Expected an object");const r=e;if(typeof r.key!="string")throw new Error('Invalid orderBy: "key" field must be a string');if(r.direction!=="ASC"&&r.direction!=="DESC")throw new Error('Invalid orderBy: "direction" field must be "ASC" or "DESC"');return{key:r.key,direction:r.direction}}function Yv(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Query: Expected an object");const r=e;if(r.type==="valueQuery"){if(typeof r.field!="string")throw new Error('Invalid valueQuery: "field" must be a string');const t={type:"valueQuery",field:r.field};if(r.path!==void 0){if(typeof r.path!="string")throw new Error('Invalid valueQuery: "path" must be a string');t.path=r.path}return t}if(r.type==="objectQuery"){if(typeof r.field!="string")throw new Error('Invalid objectQuery: "field" must be a string');if(!Array.isArray(r.selectionSet))throw new Error('Invalid objectQuery: "selectionSet" must be an array');const t={type:"objectQuery",field:r.field};if(r.path!==void 0){if(typeof r.path!="string")throw new Error('Invalid objectQuery: "path" must be a string');t.path=r.path}return t.selectionSet=r.selectionSet.map(Yv),t}if(r.type==="arrayQuery"){if(typeof r.field!="string")throw new Error('Invalid arrayQuery: "field" must be a string');if(!Array.isArray(r.selectionSet))throw new Error('Invalid arrayQuery: "selectionSet" must be an array');const t={type:"arrayQuery",field:r.field};if(r.path!==void 0){if(typeof r.path!="string")throw new Error('Invalid arrayQuery: "path" must be a string');t.path=r.path}if(r.distinctOn!==void 0){if(!Array.isArray(r.distinctOn)||!r.distinctOn.every(l=>typeof l=="string"))throw new Error('Invalid arrayQuery: "distinctOn" must be an array of strings');t.distinctOn=r.distinctOn}if(r.limit!==void 0){if(typeof r.limit!="number"||r.limit<0||!Number.isInteger(r.limit))throw new Error('Invalid arrayQuery: "limit" must be a non-negative integer');t.limit=r.limit}if(r.orderBy!==void 0&&r.orderBy!==null&&(Array.isArray(r.orderBy)?t.orderBy=r.orderBy.map(P0):t.orderBy=P0(r.orderBy)),r.where!==void 0){if(typeof r.where!="object"||r.where===null||Array.isArray(r.where))throw new Error('Invalid arrayQuery: "where" must be a non-null object');t.where=r.where}return t.selectionSet=r.selectionSet.map(Yv),t}throw new Error('Invalid Query: "type" must be "valueQuery", "objectQuery", or "arrayQuery"')}function qv(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid FieldQuery: Expected an object");const r=e;if(r.type==="fieldAlias"){if(typeof r.alias!="string")throw new Error('Invalid FieldAlias: "alias" must be a string');if(!r.field)throw new Error('Invalid FieldAlias: "field" is required');return{type:"fieldAlias",alias:r.alias,field:qv(r.field)}}else{if(r.type==="valueQuery"||r.type==="objectQuery"||r.type==="arrayQuery")return Yv(r);throw new Error('Invalid FieldQuery: "type" must be "fieldAlias", "valueQuery", "objectQuery", or "arrayQuery"')}}function Z7(e,r,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid JSON: Expected an object");const l=e;switch(l.type){case"tableColumn":{if(typeof l.name!="string")throw new Error('Invalid JSON: "name" field must be a string for tableColumn');if(!l.cellRenderer)throw new Error('Invalid JSON: "cellRenderer" field is required for tableColumn');const n=Bu(l.cellRenderer);if(n.section!=="cellRenderers")throw new Error('Invalid cellRenderer: section must be "cellRenderers"');const s=t?Object.keys(t.cellRenderers||{}):[],p=Object.keys(r.cellRenderers||{}),d=[...new Set([...s,...p])];if(!d.includes(n.key))throw new Error(`Invalid cellRenderer reference: "${n.key}". Valid keys are: ${d.join(", ")}`);if(!Array.isArray(l.data))throw new Error('Invalid JSON: "data" field must be an array of FieldQuery objects');return{type:"tableColumn",data:l.data.map((g,h)=>{try{return qv(g)}catch(S){throw new Error(`Invalid data[${h}]: ${S instanceof Error?S.message:"Unknown error"}`)}}),name:l.name,cellRenderer:n}}case"virtualColumn":{if(!Array.isArray(l.data))throw new Error('Invalid JSON: "data" field must be an array of FieldQuery objects');return{type:"virtualColumn",data:l.data.map((s,p)=>{try{return qv(s)}catch(d){throw new Error(`Invalid data[${p}]: ${d instanceof Error?d.message:"Unknown error"}`)}})}}default:throw new Error('Invalid JSON: "type" must be "tableColumn" or "virtualColumn"')}}function Q7(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)){const r=e;if("and"in r){if(!Array.isArray(r.and))throw new Error('Invalid FilterField: "and" must be an array of strings');if(!r.and.every(t=>typeof t=="string"))throw new Error('Invalid FilterField: "and" array must contain only strings');return{and:r.and}}if("or"in r){if(!Array.isArray(r.or))throw new Error('Invalid FilterField: "or" must be an array of strings');if(!r.or.every(t=>typeof t=="string"))throw new Error('Invalid FilterField: "or" array must contain only strings');return{or:r.or}}}throw new Error('Invalid FilterField: must be a string or object with "and" or "or" arrays')}function J7(e,r,t){if(e==null)return e;let l;try{l=Bu(e)}catch{return e}return l.section==="initialValues"?Fu(l,t,r):e}function K2(e,r,t){if(!e||typeof e!="object"&&!Array.isArray(e))throw new Error("Invalid FilterControl: Expected an object");const l=e,n=l.initialValue!==void 0?J7(l.initialValue,r,t):void 0;if(l.type==="custom"){const s=Bu(l.component);if(s.section!=="customFilterComponents")throw new Error('Invalid custom filter component: section must be "customFilterComponents"');const p=Fu(s,t,r);return{...l,component:p,initialValue:n}}if(l.type==="autocomplete"){if(!l.suggestionFetcher)throw new Error('Invalid autocomplete FilterControl: "suggestionFetcher" is required');const s=Bu(l.suggestionFetcher);if(s.section!=="suggestionFetchers")throw new Error('Invalid autocomplete suggestionFetcher: section must be "suggestionFetchers"');const p=Fu(s,t,r);return{...l,suggestionFetcher:p,initialValue:n}}return l.type==="customOperator"?{...l,valueControl:K2(l.valueControl,r,t),initialValue:n}:{...l,initialValue:n}}function Xv(e,r,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid FilterExpr: Expected an object");const l=e;if(typeof l.type!="string")throw new Error('Invalid FilterExpr: "type" must be a string');if(l.type==="and"||l.type==="or"){if(!Array.isArray(l.filters))throw new Error(`Invalid ${l.type} FilterExpr: "filters" must be an array`);return{type:l.type,filters:l.filters.map(m=>Xv(m,r,t))}}if(l.type==="not"){if(!l.filter||typeof l.filter!="object")throw new Error('Invalid not FilterExpr: "filter" must be an object');return{type:"not",filter:Xv(l.filter,r,t)}}const n=["equals","notEquals","greaterThan","lessThan","greaterThanOrEqual","lessThanOrEqual","in","notIn","like","iLike","isNull"];if(!n.includes(l.type))throw new Error(`Invalid FilterExpr type: "${l.type}". Valid types are: ${n.join(", ")}, and, or, not`);const s=Q7(l.field);if(!l.value)throw new Error('Invalid FilterExpr: "value" is required');const p=K2(l.value,r,t),d={type:l.type,field:s,value:p};if(l.transform){const m=Bu(l.transform);if(m.section!=="queryTransforms")throw new Error('Invalid transform: section must be "queryTransforms"');const g=Fu(m,t,r);d.transform=g}return d}function W7(e,r,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid FilterFieldSchema: Expected an object");const l=e;if(!Array.isArray(l.groups))throw new Error('Invalid FilterFieldSchema: "groups" must be an array');const n=l.groups.map((p,d)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new Error(`Invalid group[${d}]: Expected an object`);const m=p;if(typeof m.name!="string")throw new Error(`Invalid group[${d}]: "name" must be a string`);if(m.label!==null&&typeof m.label!="string")throw new Error(`Invalid group[${d}]: "label" must be a string or null`);return{name:m.name,label:m.label}});if(!Array.isArray(l.filters))throw new Error('Invalid FilterFieldSchema: "filters" must be an array');const s=l.filters.map((p,d)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new Error(`Invalid filter[${d}]: Expected an object`);const m=p;if(typeof m.id!="string")throw new Error(`Invalid filter[${d}]: "id" must be a string`);if(typeof m.label!="string")throw new Error(`Invalid filter[${d}]: "label" must be a string`);if(typeof m.group!="string")throw new Error(`Invalid filter[${d}]: "group" must be a string`);if(typeof m.aiGenerated!="boolean")throw new Error(`Invalid filter[${d}]: "aiGenerated" must be a boolean`);if(!m.expression)throw new Error(`Invalid filter[${d}]: "expression" is required`);let g;try{g=Xv(m.expression,r,t)}catch(h){throw new Error(`Invalid filter[${d}] expression: ${h instanceof Error?h.message:"Unknown error"}`)}return{id:m.id,label:m.label,expression:g,group:m.group,aiGenerated:m.aiGenerated}});return{groups:n,filters:s}}function e9(e,r,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("View JSON must be a non-null object");const l=e;if(typeof l.title!="string")throw new Error('View "title" must be a string');if(typeof l.id!="string")throw new Error('View "id" must be a string');if(typeof l.collectionName!="string")throw new Error('View "collectionName" must be a string');if(typeof l.paginationKey!="string")throw new Error('View "paginationKey" must be a string');if(typeof l.boolExpType!="string")throw new Error('View "boolExpType" must be a string');if(typeof l.orderByType!="string")throw new Error('View "orderByType" must be a string');if(!Array.isArray(l.columns))throw new Error('View "columns" must be an array');if(!l.filterSchema)throw new Error('View "filterSchema" is required');const n=l.columns.map((g,h)=>{let S;try{S=Z7(g,r,t)}catch(x){throw new Error(`Invalid column[${h}]: ${x instanceof Error?x.message:"Unknown error"}`)}switch(S.type){case"virtualColumn":return{type:"virtualColumn",data:S.data};case"tableColumn":{const x=Fu(S.cellRenderer,t,r);return{type:"tableColumn",data:S.data,name:S.name,cellRenderer:x}}}});let s;try{s=W7(l.filterSchema,r,t)}catch(g){throw new Error(`Invalid filterSchema: ${g instanceof Error?g.message:"Unknown error"}`)}let p;if(l.noRowsComponent!==void 0){const g=Bu(l.noRowsComponent);if(g.section!=="noRowsComponents")throw new Error('Invalid noRowsComponent: section must be "noRowsComponents"');p=Fu(g,t,r)}let d;if(l.staticConditions!==void 0){if(!Array.isArray(l.staticConditions))throw new Error('View "staticConditions" must be an array when provided');const g=l.staticConditions.findIndex(h=>typeof h!="object"||h===null||Array.isArray(h));if(g!==-1)throw new Error(`View "staticConditions" entry[${g}] must be a non-null object`);d=l.staticConditions}let m;if(l.staticOrdering!==void 0){if(!Array.isArray(l.staticOrdering))throw new Error('View "staticOrdering" must be an array when provided');const g=l.staticOrdering.findIndex(h=>typeof h!="object"||h===null||Array.isArray(h));if(g!==-1)throw new Error(`View "staticOrdering" entry[${g}] must be a non-null object`);m=l.staticOrdering}return{title:l.title,id:l.id,collectionName:l.collectionName,columnDefinitions:n,filterSchema:s,boolExpType:l.boolExpType,orderByType:l.orderByType,paginationKey:l.paginationKey,noRowsComponent:p,staticConditions:d,staticOrdering:m}}const A0="2025-09-04T00:00:00.000Z",Qf="2025-09-19T00:00:00.000Z",Qo="dtvSavedFilters",Im="savedFilters";function t9(e,r){if(!Array.isArray(e))return console.warn("Expected array for conversion but got:",typeof e),{};const t={};return e.forEach((l,n)=>{if(n<r.filters.length){const s=r.filters[n].id;t[s]=l}}),t}function n9(){function e(){try{if(localStorage.getItem(Qo))return!1;const p=localStorage.getItem(Im);if(!p)return!1;console.info("Found saved filters in legacy localStorage key, migrating..."),localStorage.setItem(Qo,p),localStorage.removeItem(Im);const d=JSON.parse(p),m=Array.isArray(d)?d.length:0;return console.info(`Migrated ${m} filters from legacy localStorage key '${Im}' to '${Qo}'`),!0}catch(p){return console.error("Failed to migrate legacy localStorage key:",p),!1}}function r(){try{e();const p=localStorage.getItem(Qo);if(!p)return[];const d=JSON.parse(p);return Array.isArray(d)?d.map(m=>{if(typeof m!="object"||m===null)throw new Error("Invalid saved filter structure");const g=m;return{id:typeof g.id=="string"?g.id:crypto.randomUUID(),name:typeof g.name=="string"?g.name:"Unnamed Filter",view:typeof g.view=="string"?g.view:"",state:g.state,createdAt:typeof g.createdAt=="string"?g.createdAt:new Date().toISOString(),formatRevision:typeof g.formatRevision=="string"?g.formatRevision:A0}}):[]}catch(p){return console.error("Failed to load saved filters from localStorage:",p),[]}}function t(p,d){const m=r();let g=!1;const h=m.map(O=>{if(O.formatRevision===A0){g=!0;const $=t9(O.state,d);return{...O,state:$,formatRevision:Qf}}return{...O,formatRevision:Qf}}),x=h.filter(O=>O.view===p).map(O=>{const $=o2(O.state,d);return{id:O.id,name:O.name,view:O.view,state:$,createdAt:typeof O.createdAt=="string"?new Date(O.createdAt):O.createdAt,formatRevision:Qf}});if(g)try{localStorage.setItem(Qo,JSON.stringify(h)),console.info("Migrated filters from old array format to new object format")}catch(O){console.error("Failed to save migrated filters to localStorage:",O)}return x}function l(p){const d={id:crypto.randomUUID(),createdAt:new Date,formatRevision:Qf,...p},m=r(),g={...d,createdAt:d.createdAt.toISOString(),state:Cv(d.state)};return m.push(g),localStorage.setItem(Qo,JSON.stringify(m)),d}function n(p,d){const m=r(),g=m.findIndex(x=>x.id===p.id);if(g===-1)return null;const h={...p,...d},S={...m[g],name:h.name,state:d.state?Cv(d.state):m[g].state};return m[g]=S,localStorage.setItem(Qo,JSON.stringify(m)),h}function s(p){const d=r(),m=d.length,g=d.filter(h=>h.id!==p);return g.length===m?!1:(localStorage.setItem(Qo,JSON.stringify(g)),!0)}return{loadFilters:t,saveFilter:l,updateFilter:n,deleteFilter:s}}const Jf=n9();function G2(e){try{const r=Cv(e),t=JSON.stringify(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}catch(r){throw console.error("Failed to encode filter state:",r),new Error("Failed to encode filter state")}}function r9(e){try{const r=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(4-e.length%4)%4,"="),t=atob(r);return JSON.parse(t)}catch(r){throw console.error("Failed to decode filter state:",r),new Error("Failed to decode filter state")}}const hs="dtv-filter-state";function k0(e){try{const r=G2(e),t=new URL(window.location.href);return t.searchParams.set(hs,r),t.toString()}catch(r){throw console.error("Failed to create shareable URL:",r),new Error("Failed to create shareable URL")}}async function _0(e){try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(e);else{const r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"),document.body.removeChild(r)}}catch(r){throw console.error("Failed to copy to clipboard:",r),new Error("Failed to copy to clipboard")}}function a9(){try{const r=new URLSearchParams(window.location.search).get(hs);return r?r9(r):null}catch(e){return console.warn("Failed to parse filter from URL:",e),null}}function l9(){const e=new URL(window.location.href);e.searchParams.delete(hs),window.history.replaceState({},"",e.toString())}function o9(e){try{const r=G2(e),t=new URL(window.location.href);t.searchParams.get(hs)!==r&&(t.searchParams.set(hs,r),window.history.replaceState({},"",t.toString()))}catch(r){console.warn("Failed to set filter in URL",r)}}function i9({actions:e,selectedView:r,filterState:t,setFilterState:l,refetch:n,showToast:s,paginationState:p,rowsPerPage:d}){const[m,g]=c.useState(()=>new Set);return qe.jsx(qe.Fragment,{children:e.map((h,S)=>{const x=m.has(S),O=async()=>{if(x)return;g(D=>new Set(D).add(S));const $={view:r,filterState:t,setFilterState:l,refetch:n,showToast:s,generateGraphQLQueryAST:H2,renderGraphQLQuery:U2,buildGraphQLQueryVariables:V2,getPaginationState:()=>p,rowsPerPage:d};try{await h.onClick($)}catch(D){console.error("Action handler error",D),s({severity:"error",summary:"Action Failed",detail:h.label,life:3e3})}finally{g(D=>{const K=new Set(D);return K.delete(S),K})}};return qe.jsx(mr,{type:"button",icon:h.icon,outlined:h.outlined!==!1,size:h.size==="normal"?void 0:"small",disabled:h.disabled||x,label:x?`${h.label}...`:h.label,onClick:O,"data-testid":`dtv-action-${S}`},`custom-action-${S}`)})})}const u9=M6;function Y2({graphqlHost:e,graphqlToken:r,geminiApiKey:t,showViewsMenu:l,showViewTitle:n,showCsvExportButton:s=!1,showPopoutButton:p=!0,viewsJson:d,externalRuntime:m,isOverlay:g=!1,onCloseOverlay:h,syncFilterStateToUrl:S=!1,rowSelection:x,actions:O=[],rowClassFunction:$,rowsPerPageOptions:D=[20,50,100,200]}){const K=c.useMemo(()=>JSON.parse(d).map(It=>e9(It,u9,m)),[d,m]),U=c.useMemo(()=>new SC(e,{headers:{contentType:"application/json",Authorization:`Bearer ${r}`}}),[e,r]),I=c.useMemo(()=>{const xe=a9();if(xe)try{const It=K[0];return It?o2(xe,It.filterSchema):void 0}catch(It){console.warn("Invalid initial filter state from URL, falling back to defaults",It);return}},[d]),{state:N,selectedView:B,setSelectedViewId:H,setFilterSchema:pe,setFilterState:oe,setDataRows:W,setRowsPerPage:F}=O6(K,D,I),j=c.useMemo(()=>V7(B.collectionName,B.columnDefinitions,B.boolExpType,B.orderByType,B.paginationKey),[B.id]),[L,X]=c.useState([]),[_,Q]=c.useState(""),G=c.useRef(null),Z=c.useRef(null),[be,me]=c.useState(!1),[ve,P]=c.useState(!1),[re,le]=c.useState(!1),[z,ne]=c.useState(0),[ce,Oe]=c.useState(!1);c.useEffect(()=>{_&&!ve&&P(!0)},[_,ve]),c.useEffect(()=>{if(!g&&ce){const xe=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=xe}}},[ce,g]),c.useEffect(()=>{if(!g)return;const xe=It=>{It.key==="Escape"&&(h==null||h())};return window.addEventListener("keydown",xe),()=>window.removeEventListener("keydown",xe)},[g,h]);const Qe=N.pagination.rowsPerPage,ct=N.data.rows.length===Qe,Lt=N.pagination.page>0;c.useEffect(()=>{const xe=Jf.loadFilters(B.id,B.filterSchema);X(xe)},[B.id]),c.useEffect(()=>{var xe;I&&!S&&(l9(),(xe=G.current)==null||xe.show({severity:"info",summary:"Filter Loaded",detail:"Loaded from URL",life:3e3}))},[]),c.useEffect(()=>{S&&o9(N.filterState)},[S,z]);const Ye=xe=>{var Kt;const It=prompt("Enter a name for this filter:");if(!It)return;const _t=Jf.saveFilter({view:B.id,name:It,state:xe});X(zt=>[...zt,_t]),(Kt=G.current)==null||Kt.show({severity:"success",summary:"Filter Saved",detail:`Filter "${It}" has been saved successfully`,life:3e3})},it=(xe,It)=>{z2({message:`Are you sure you want to overwrite the existing filter "${xe.name}"?`,header:"Confirm Filter Update",icon:"pi pi-exclamation-triangle",defaultFocus:"reject",acceptClassName:"p-button-danger",accept:()=>{var Kt;const _t=Jf.updateFilter(xe,{state:It});_t&&(X(zt=>zt.map($t=>$t.id===xe.id?_t:$t)),(Kt=G.current)==null||Kt.show({severity:"success",summary:"Filter Updated",detail:`Filter "${xe.name}" has been updated successfully`,life:3e3}))},reject:()=>{}})},_e=xe=>{var _t;Jf.deleteFilter(xe)&&(X(Kt=>Kt.filter(zt=>zt.id!==xe)),(_t=G.current)==null||_t.show({severity:"success",summary:"Filter Deleted",detail:"Filter has been deleted successfully",life:3e3}))},Je=async()=>{var xe,It;try{const _t=k0(N.filterState);await _0(_t),(xe=G.current)==null||xe.show({severity:"success",summary:"Filter Shared",detail:"Shareable link copied to clipboard!",life:3e3})}catch(_t){console.error("Failed to share filter:",_t),(It=G.current)==null||It.show({severity:"error",summary:"Share Failed",detail:"Failed to create shareable link",life:3e3})}},dt=async xe=>{var It,_t;try{const Kt=k0(xe);await _0(Kt),(It=G.current)==null||It.show({severity:"success",summary:"Filter Shared",detail:"Shareable link copied to clipboard!",life:3e3})}catch(Kt){console.error("Failed to share saved filter:",Kt),(_t=G.current)==null||_t.show({severity:"error",summary:"Share Failed",detail:"Failed to create shareable link",life:3e3})}},jt=()=>{Z.current&&Z.current.exportCSV({selectionOnly:!1})},Bt=c.useCallback((xe,It)=>G7({client:U,view:B,query:j,filterState:N.filterState,rowLimit:It,cursor:xe}),[U,B,j,N.filterState]);c.useEffect(()=>{Bt(null,Qe).then(xe=>W(xe)).catch(xe=>{xe instanceof DOMException&&xe.name})},[N.selectedViewId,z]);const Rt=xe=>{oe(xe)},Ue=N.filterSchemasAndGroups.filters.flatMap(xe=>{function It(zt){return zt.toLowerCase().includes(_.toLowerCase())}function _t(zt){return typeof zt=="string"?It(zt):"and"in zt?zt.and.some($t=>It($t)):"or"in zt?zt.or.some($t=>It($t)):!1}return It(xe.label)?[xe.id]:Gv(xe.expression).some(zt=>_t(zt.field))?[xe.id]:[]}),De=async()=>{const xe=N.data.rows.length>0?N.data.rows[N.data.rows.length-1][B.paginationKey]:null;if(typeof xe!="string"&&typeof xe!="number"){console.error("Invalid cursor type:",xe);return}const It=await Bt(xe,Qe);W(It,{page:N.pagination.page+1,cursors:[...N.pagination.cursors,xe],rowsPerPage:Qe})},St=async()=>{if(N.pagination.page===0)return;const xe=N.pagination.cursors.slice(0,-1),It=xe[xe.length-1]??null,_t=await Bt(It,Qe);W(_t,{page:N.pagination.page-1,cursors:xe,rowsPerPage:Qe})},yt=async xe=>{if(xe===Qe)return;F(xe);const It=await Bt(null,xe);W(It,{page:0,cursors:[],rowsPerPage:xe})};return qe.jsxs("div",{className:"tw:p-2",children:[qe.jsx(_2,{ref:G}),qe.jsx($2,{}),qe.jsx(T2,{model:[...l?[{label:"Views",icon:"pi pi-eye",items:K.map(xe=>({label:xe.title,icon:"pi pi-table",command:()=>H(xe.id)}))}]:[]],className:"tw:mb-4 tw:border-b",start:qe.jsxs("div",{className:"tw:flex tw:gap-2 tw:items-center",children:[qe.jsx(mr,{type:"button",icon:ve?"pi pi-filter-slash":"pi pi-filter",outlined:!0,size:"small",label:ve?"Hide Filters":"Filters",onClick:()=>{P(xe=>{const It=!xe;return It||Q(""),It})}}),qe.jsx(mr,{type:"button",icon:"pi pi-bookmark",outlined:!0,size:"small",label:re?"Hide Saved Filters":"Saved Filters",onClick:()=>le(xe=>!xe)}),s&&qe.jsx(mr,{type:"button",icon:"pi pi-table",outlined:!0,size:"small",label:"Export page to CSV",onClick:jt,"data-testid":"export-csv-button"}),p&&qe.jsx(mr,{type:"button",icon:g?"pi pi-times":"pi pi-window-maximize",outlined:!0,size:"small",label:g?"Close Popout":"Popout",onClick:()=>{g?h==null||h():Oe(!0)}}),qe.jsx(i9,{actions:O,selectedView:B,filterState:N.filterState,setFilterState:oe,refetch:()=>ne(xe=>xe+1),showToast:xe=>{var It;return(It=G.current)==null?void 0:It.show({...xe})},paginationState:N.pagination,rowsPerPage:Qe})]}),end:qe.jsxs("div",{className:"tw:flex tw:gap-2",children:[qe.jsxs(R2,{iconPosition:"left",children:[qe.jsx(I2,{className:"pi pi-search"}),qe.jsx(Hl,{value:_,onChange:xe=>Q(xe.target.value),placeholder:"Search filters..."})]}),qe.jsx(mr,{type:"button",size:"small",icon:"pi pi-sparkles",label:"AI Filter Assistant",onClick:()=>me(xe=>!xe)})]})}),(n||g)&&qe.jsx("h1",{className:"tw:text-2xl tw:mb-4 tw:font-bold",children:B.title}),be&&qe.jsx("div",{className:"tw:mb-6",children:qe.jsx(B7,{filterSchema:N.filterSchemasAndGroups,filterState:N.filterState,setFilterSchema:pe,setFilterState:oe,selectedView:B,geminiApiKey:t,toast:G,setShowFilterForm:P})}),qe.jsx(z7,{savedFilters:L,onFilterDelete:_e,onFilterLoad:Rt,onFilterApply:()=>ne(xe=>xe+1),onFilterShare:dt,visible:re,filterSchema:N.filterSchemasAndGroups}),ve&&qe.jsx(A4,{filterSchemasAndGroups:N.filterSchemasAndGroups,filterState:N.filterState,setFilterState:oe,onSaveFilter:Ye,onUpdateFilter:it,onShareFilter:Je,savedFilters:L,visibleFilterIds:Ue,onSubmit:()=>{ne(xe=>xe+1)},graphqlClient:U}),qe.jsx(T6,{viewId:B.id,ref:Z,columns:B.columnDefinitions,data:N.data.flattenedRows,noRowsComponent:B.noRowsComponent,setFilterState:oe,filterState:N.filterState,triggerRefetch:()=>ne(xe=>xe+1),rowSelection:x,rowClassFunction:$}),N.data.rows.length>0&&qe.jsx(P7,{onPageChange:De,onPrevPage:St,hasNextPage:ct,hasPrevPage:Lt,currentPage:N.pagination.page,rowsPerPage:Qe,actualRows:N.data.rows.length,onRowsPerPageChange:yt,rowsPerPageOptions:D}),ce&&!g&&F0.createPortal(qe.jsx("div",{className:"tw:fixed tw:inset-0 tw:bg-white tw:overflow-auto",children:qe.jsx(Y2,{graphqlHost:e,graphqlToken:r,geminiApiKey:t,showViewsMenu:l,showViewTitle:n,showCsvExportButton:s,showPopoutButton:p,viewsJson:d,externalRuntime:m,isOverlay:!0,onCloseOverlay:()=>Oe(!1),syncFilterStateToUrl:S,rowSelection:x,rowClassFunction:$,rowsPerPageOptions:D})}),document.body)]})}const c9="1.3.1",s9={version:c9};function f9(e,r){const t=typeof e=="string"?document.getElementById(e):e;if(!t)throw new Error("Target element not found");hE.createRoot(t).render(qe.jsx(c.StrictMode,{children:qe.jsx(qC,{value:{},children:qe.jsx(Y2,{graphqlHost:r.graphqlHost,graphqlToken:r.graphqlToken,geminiApiKey:r.geminiApiKey,showViewsMenu:r.showViewsMenu??!1,showViewTitle:r.showViewTitle??!1,showCsvExportButton:r.showCsvExportButton??!1,showPopoutButton:r.showPopoutButton??!0,viewsJson:r.viewsJson,externalRuntime:r.externalRuntime,syncFilterStateToUrl:r.syncFilterStateToUrl??!1,rowSelection:r.rowSelection,actions:r.actions,rowClassFunction:r.rowClassFunction,rowsPerPageOptions:r.rowsPerPageOptions})})}))}const d9={version:s9.version,renderTableView:f9};window.dtv=d9;
2209
+ }`}function K7(e,r){return typeof e=="object"&&e!==null&&r in e&&Array.isArray(e[r])}let N0=0;const V2=(e,r,t,l)=>{let n=$7(r,e.filterSchema);e.staticConditions&&e.staticConditions.length>0&&(n={_and:[n,...e.staticConditions]});const s=l!==null?{[e.paginationKey]:{_lt:l}}:{},p={[e.paginationKey]:"DESC"},d=e.staticOrdering&&e.staticOrdering.length>0?[p,...e.staticOrdering]:[p];return{conditions:n,paginationCondition:s,rowLimit:t,orderBy:d}},G7=async({client:e,view:r,query:t,filterState:l,rowLimit:n,cursor:s})=>{const p=++N0;try{const d=V2(r,l,n,s),m=await e.request(t,d);if(p!==N0)throw new DOMException("Request superseded by newer request","AbortError");if(!K7(m,r.collectionName))return console.error("Error fetching data, unexpected response format:",m),{rows:[],flattenedRows:[]};const g=m[r.collectionName];return{rows:g,flattenedRows:Y7(g,r.columnDefinitions)}}catch(d){if(d instanceof DOMException&&d.name==="AbortError")throw d;return console.error("Error fetching data:",d),{rows:[],flattenedRows:[]}}},Y7=(e,r)=>e.map(t=>r.map(l=>q7(t,l))),q7=(e,r)=>{const t={};function l(s){if(!(!s||typeof s!="object"))switch(s.type){case"fieldAlias":return e[s.alias]!==void 0?e[s.alias]:l(s.field);case"valueQuery":case"objectQuery":case"arrayQuery":return e[s.field];default:return}}function n(s){if(!(!s||typeof s!="object")){if(s.type==="fieldAlias"){const p=s.alias;if(e[p]!==void 0)t[p]=e[p];else{const d=l(s.field);d!==void 0&&(t[p]=d)}return}(s.type==="valueQuery"||s.type==="objectQuery"||s.type==="arrayQuery")&&e[s.field]!==void 0&&(t[s.field]=e[s.field])}}return r.data.forEach(n),t};function X7(e){return"field"in e&&"value"in e}function Gv(e){const r=[];if(X7(e))r.push(e);else if(e.type==="and"||e.type==="or")for(const t of e.filters)r.push(...Gv(t));else e.type==="not"&&r.push(...Gv(e.filter));return r}function Fu(e,r,t){const{section:l,key:n}=e;if(r&&r[l]&&r[l][n]!==void 0)return r[l][n];if(t[l]&&t[l][n]!==void 0)return t[l][n];const s=r?Object.keys(r[l]||{}):[],p=Object.keys(t[l]||{}),d=[...new Set([...s,...p])];throw new Error(`Reference "${n}" not found in ${l}. Available keys: ${d.join(", ")}`)}function Bu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid RuntimeReference: Expected an object");const r=e;if(typeof r.section!="string")throw new Error('Invalid RuntimeReference: "section" must be a string');if(typeof r.key!="string")throw new Error('Invalid RuntimeReference: "key" must be a string');const t=["cellRenderers","noRowsComponents","customFilterComponents","queryTransforms","initialValues","suggestionFetchers"];if(!t.includes(r.section))throw new Error(`Invalid RuntimeReference: "section" must be one of: ${t.join(", ")}`);return{section:r.section,key:r.key}}function P0(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid orderBy: Expected an object");const r=e;if(typeof r.key!="string")throw new Error('Invalid orderBy: "key" field must be a string');if(r.direction!=="ASC"&&r.direction!=="DESC")throw new Error('Invalid orderBy: "direction" field must be "ASC" or "DESC"');return{key:r.key,direction:r.direction}}function Yv(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Query: Expected an object");const r=e;if(r.type==="valueQuery"){if(typeof r.field!="string")throw new Error('Invalid valueQuery: "field" must be a string');const t={type:"valueQuery",field:r.field};if(r.path!==void 0){if(typeof r.path!="string")throw new Error('Invalid valueQuery: "path" must be a string');t.path=r.path}return t}if(r.type==="objectQuery"){if(typeof r.field!="string")throw new Error('Invalid objectQuery: "field" must be a string');if(!Array.isArray(r.selectionSet))throw new Error('Invalid objectQuery: "selectionSet" must be an array');const t={type:"objectQuery",field:r.field};if(r.path!==void 0){if(typeof r.path!="string")throw new Error('Invalid objectQuery: "path" must be a string');t.path=r.path}return t.selectionSet=r.selectionSet.map(Yv),t}if(r.type==="arrayQuery"){if(typeof r.field!="string")throw new Error('Invalid arrayQuery: "field" must be a string');if(!Array.isArray(r.selectionSet))throw new Error('Invalid arrayQuery: "selectionSet" must be an array');const t={type:"arrayQuery",field:r.field};if(r.path!==void 0){if(typeof r.path!="string")throw new Error('Invalid arrayQuery: "path" must be a string');t.path=r.path}if(r.distinctOn!==void 0){if(!Array.isArray(r.distinctOn)||!r.distinctOn.every(l=>typeof l=="string"))throw new Error('Invalid arrayQuery: "distinctOn" must be an array of strings');t.distinctOn=r.distinctOn}if(r.limit!==void 0){if(typeof r.limit!="number"||r.limit<0||!Number.isInteger(r.limit))throw new Error('Invalid arrayQuery: "limit" must be a non-negative integer');t.limit=r.limit}if(r.orderBy!==void 0&&r.orderBy!==null&&(Array.isArray(r.orderBy)?t.orderBy=r.orderBy.map(P0):t.orderBy=P0(r.orderBy)),r.where!==void 0){if(typeof r.where!="object"||r.where===null||Array.isArray(r.where))throw new Error('Invalid arrayQuery: "where" must be a non-null object');t.where=r.where}return t.selectionSet=r.selectionSet.map(Yv),t}throw new Error('Invalid Query: "type" must be "valueQuery", "objectQuery", or "arrayQuery"')}function qv(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid FieldQuery: Expected an object");const r=e;if(r.type==="fieldAlias"){if(typeof r.alias!="string")throw new Error('Invalid FieldAlias: "alias" must be a string');if(!r.field)throw new Error('Invalid FieldAlias: "field" is required');return{type:"fieldAlias",alias:r.alias,field:qv(r.field)}}else{if(r.type==="valueQuery"||r.type==="objectQuery"||r.type==="arrayQuery")return Yv(r);throw new Error('Invalid FieldQuery: "type" must be "fieldAlias", "valueQuery", "objectQuery", or "arrayQuery"')}}function Z7(e,r,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid JSON: Expected an object");const l=e;switch(l.type){case"tableColumn":{if(typeof l.name!="string")throw new Error('Invalid JSON: "name" field must be a string for tableColumn');if(!l.cellRenderer)throw new Error('Invalid JSON: "cellRenderer" field is required for tableColumn');const n=Bu(l.cellRenderer);if(n.section!=="cellRenderers")throw new Error('Invalid cellRenderer: section must be "cellRenderers"');const s=t?Object.keys(t.cellRenderers||{}):[],p=Object.keys(r.cellRenderers||{}),d=[...new Set([...s,...p])];if(!d.includes(n.key))throw new Error(`Invalid cellRenderer reference: "${n.key}". Valid keys are: ${d.join(", ")}`);if(!Array.isArray(l.data))throw new Error('Invalid JSON: "data" field must be an array of FieldQuery objects');return{type:"tableColumn",data:l.data.map((g,h)=>{try{return qv(g)}catch(S){throw new Error(`Invalid data[${h}]: ${S instanceof Error?S.message:"Unknown error"}`)}}),name:l.name,cellRenderer:n}}case"virtualColumn":{if(!Array.isArray(l.data))throw new Error('Invalid JSON: "data" field must be an array of FieldQuery objects');return{type:"virtualColumn",data:l.data.map((s,p)=>{try{return qv(s)}catch(d){throw new Error(`Invalid data[${p}]: ${d instanceof Error?d.message:"Unknown error"}`)}})}}default:throw new Error('Invalid JSON: "type" must be "tableColumn" or "virtualColumn"')}}function Q7(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)){const r=e;if("and"in r){if(!Array.isArray(r.and))throw new Error('Invalid FilterField: "and" must be an array of strings');if(!r.and.every(t=>typeof t=="string"))throw new Error('Invalid FilterField: "and" array must contain only strings');return{and:r.and}}if("or"in r){if(!Array.isArray(r.or))throw new Error('Invalid FilterField: "or" must be an array of strings');if(!r.or.every(t=>typeof t=="string"))throw new Error('Invalid FilterField: "or" array must contain only strings');return{or:r.or}}}throw new Error('Invalid FilterField: must be a string or object with "and" or "or" arrays')}function J7(e,r,t){if(e==null)return e;let l;try{l=Bu(e)}catch{return e}return l.section==="initialValues"?Fu(l,t,r):e}function K2(e,r,t){if(!e||typeof e!="object"&&!Array.isArray(e))throw new Error("Invalid FilterControl: Expected an object");const l=e,n=l.initialValue!==void 0?J7(l.initialValue,r,t):void 0;if(l.type==="custom"){const s=Bu(l.component);if(s.section!=="customFilterComponents")throw new Error('Invalid custom filter component: section must be "customFilterComponents"');const p=Fu(s,t,r);return{...l,component:p,initialValue:n}}if(l.type==="autocomplete"){if(!l.suggestionFetcher)throw new Error('Invalid autocomplete FilterControl: "suggestionFetcher" is required');const s=Bu(l.suggestionFetcher);if(s.section!=="suggestionFetchers")throw new Error('Invalid autocomplete suggestionFetcher: section must be "suggestionFetchers"');const p=Fu(s,t,r);return{...l,suggestionFetcher:p,initialValue:n}}return l.type==="customOperator"?{...l,valueControl:K2(l.valueControl,r,t),initialValue:n}:{...l,initialValue:n}}function Xv(e,r,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid FilterExpr: Expected an object");const l=e;if(typeof l.type!="string")throw new Error('Invalid FilterExpr: "type" must be a string');if(l.type==="and"||l.type==="or"){if(!Array.isArray(l.filters))throw new Error(`Invalid ${l.type} FilterExpr: "filters" must be an array`);return{type:l.type,filters:l.filters.map(m=>Xv(m,r,t))}}if(l.type==="not"){if(!l.filter||typeof l.filter!="object")throw new Error('Invalid not FilterExpr: "filter" must be an object');return{type:"not",filter:Xv(l.filter,r,t)}}const n=["equals","notEquals","greaterThan","lessThan","greaterThanOrEqual","lessThanOrEqual","in","notIn","like","iLike","isNull"];if(!n.includes(l.type))throw new Error(`Invalid FilterExpr type: "${l.type}". Valid types are: ${n.join(", ")}, and, or, not`);const s=Q7(l.field);if(!l.value)throw new Error('Invalid FilterExpr: "value" is required');const p=K2(l.value,r,t),d={type:l.type,field:s,value:p};if(l.transform){const m=Bu(l.transform);if(m.section!=="queryTransforms")throw new Error('Invalid transform: section must be "queryTransforms"');const g=Fu(m,t,r);d.transform=g}return d}function W7(e,r,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid FilterFieldSchema: Expected an object");const l=e;if(!Array.isArray(l.groups))throw new Error('Invalid FilterFieldSchema: "groups" must be an array');const n=l.groups.map((p,d)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new Error(`Invalid group[${d}]: Expected an object`);const m=p;if(typeof m.name!="string")throw new Error(`Invalid group[${d}]: "name" must be a string`);if(m.label!==null&&typeof m.label!="string")throw new Error(`Invalid group[${d}]: "label" must be a string or null`);return{name:m.name,label:m.label}});if(!Array.isArray(l.filters))throw new Error('Invalid FilterFieldSchema: "filters" must be an array');const s=l.filters.map((p,d)=>{if(!p||typeof p!="object"||Array.isArray(p))throw new Error(`Invalid filter[${d}]: Expected an object`);const m=p;if(typeof m.id!="string")throw new Error(`Invalid filter[${d}]: "id" must be a string`);if(typeof m.label!="string")throw new Error(`Invalid filter[${d}]: "label" must be a string`);if(typeof m.group!="string")throw new Error(`Invalid filter[${d}]: "group" must be a string`);if(typeof m.aiGenerated!="boolean")throw new Error(`Invalid filter[${d}]: "aiGenerated" must be a boolean`);if(!m.expression)throw new Error(`Invalid filter[${d}]: "expression" is required`);let g;try{g=Xv(m.expression,r,t)}catch(h){throw new Error(`Invalid filter[${d}] expression: ${h instanceof Error?h.message:"Unknown error"}`)}return{id:m.id,label:m.label,expression:g,group:m.group,aiGenerated:m.aiGenerated}});return{groups:n,filters:s}}function e9(e,r,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("View JSON must be a non-null object");const l=e;if(typeof l.title!="string")throw new Error('View "title" must be a string');if(typeof l.id!="string")throw new Error('View "id" must be a string');if(typeof l.collectionName!="string")throw new Error('View "collectionName" must be a string');if(typeof l.paginationKey!="string")throw new Error('View "paginationKey" must be a string');if(typeof l.boolExpType!="string")throw new Error('View "boolExpType" must be a string');if(typeof l.orderByType!="string")throw new Error('View "orderByType" must be a string');if(!Array.isArray(l.columns))throw new Error('View "columns" must be an array');if(!l.filterSchema)throw new Error('View "filterSchema" is required');const n=l.columns.map((g,h)=>{let S;try{S=Z7(g,r,t)}catch(x){throw new Error(`Invalid column[${h}]: ${x instanceof Error?x.message:"Unknown error"}`)}switch(S.type){case"virtualColumn":return{type:"virtualColumn",data:S.data};case"tableColumn":{const x=Fu(S.cellRenderer,t,r);return{type:"tableColumn",data:S.data,name:S.name,cellRenderer:x}}}});let s;try{s=W7(l.filterSchema,r,t)}catch(g){throw new Error(`Invalid filterSchema: ${g instanceof Error?g.message:"Unknown error"}`)}let p;if(l.noRowsComponent!==void 0){const g=Bu(l.noRowsComponent);if(g.section!=="noRowsComponents")throw new Error('Invalid noRowsComponent: section must be "noRowsComponents"');p=Fu(g,t,r)}let d;if(l.staticConditions!==void 0){if(!Array.isArray(l.staticConditions))throw new Error('View "staticConditions" must be an array when provided');const g=l.staticConditions.findIndex(h=>typeof h!="object"||h===null||Array.isArray(h));if(g!==-1)throw new Error(`View "staticConditions" entry[${g}] must be a non-null object`);d=l.staticConditions}let m;if(l.staticOrdering!==void 0){if(!Array.isArray(l.staticOrdering))throw new Error('View "staticOrdering" must be an array when provided');const g=l.staticOrdering.findIndex(h=>typeof h!="object"||h===null||Array.isArray(h));if(g!==-1)throw new Error(`View "staticOrdering" entry[${g}] must be a non-null object`);m=l.staticOrdering}return{title:l.title,id:l.id,collectionName:l.collectionName,columnDefinitions:n,filterSchema:s,boolExpType:l.boolExpType,orderByType:l.orderByType,paginationKey:l.paginationKey,noRowsComponent:p,staticConditions:d,staticOrdering:m}}const A0="2025-09-04T00:00:00.000Z",Qf="2025-09-19T00:00:00.000Z",Qo="dtvSavedFilters",Im="savedFilters";function t9(e,r){if(!Array.isArray(e))return console.warn("Expected array for conversion but got:",typeof e),{};const t={};return e.forEach((l,n)=>{if(n<r.filters.length){const s=r.filters[n].id;t[s]=l}}),t}function n9(){function e(){try{if(localStorage.getItem(Qo))return!1;const p=localStorage.getItem(Im);if(!p)return!1;console.info("Found saved filters in legacy localStorage key, migrating..."),localStorage.setItem(Qo,p),localStorage.removeItem(Im);const d=JSON.parse(p),m=Array.isArray(d)?d.length:0;return console.info(`Migrated ${m} filters from legacy localStorage key '${Im}' to '${Qo}'`),!0}catch(p){return console.error("Failed to migrate legacy localStorage key:",p),!1}}function r(){try{e();const p=localStorage.getItem(Qo);if(!p)return[];const d=JSON.parse(p);return Array.isArray(d)?d.map(m=>{if(typeof m!="object"||m===null)throw new Error("Invalid saved filter structure");const g=m;return{id:typeof g.id=="string"?g.id:crypto.randomUUID(),name:typeof g.name=="string"?g.name:"Unnamed Filter",view:typeof g.view=="string"?g.view:"",state:g.state,createdAt:typeof g.createdAt=="string"?g.createdAt:new Date().toISOString(),formatRevision:typeof g.formatRevision=="string"?g.formatRevision:A0}}):[]}catch(p){return console.error("Failed to load saved filters from localStorage:",p),[]}}function t(p,d){const m=r();let g=!1;const h=m.map(O=>{if(O.formatRevision===A0){g=!0;const $=t9(O.state,d);return{...O,state:$,formatRevision:Qf}}return{...O,formatRevision:Qf}}),x=h.filter(O=>O.view===p).map(O=>{const $=o2(O.state,d);return{id:O.id,name:O.name,view:O.view,state:$,createdAt:typeof O.createdAt=="string"?new Date(O.createdAt):O.createdAt,formatRevision:Qf}});if(g)try{localStorage.setItem(Qo,JSON.stringify(h)),console.info("Migrated filters from old array format to new object format")}catch(O){console.error("Failed to save migrated filters to localStorage:",O)}return x}function l(p){const d={id:crypto.randomUUID(),createdAt:new Date,formatRevision:Qf,...p},m=r(),g={...d,createdAt:d.createdAt.toISOString(),state:Cv(d.state)};return m.push(g),localStorage.setItem(Qo,JSON.stringify(m)),d}function n(p,d){const m=r(),g=m.findIndex(x=>x.id===p.id);if(g===-1)return null;const h={...p,...d},S={...m[g],name:h.name,state:d.state?Cv(d.state):m[g].state};return m[g]=S,localStorage.setItem(Qo,JSON.stringify(m)),h}function s(p){const d=r(),m=d.length,g=d.filter(h=>h.id!==p);return g.length===m?!1:(localStorage.setItem(Qo,JSON.stringify(g)),!0)}return{loadFilters:t,saveFilter:l,updateFilter:n,deleteFilter:s}}const Jf=n9();function G2(e){try{const r=Cv(e),t=JSON.stringify(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}catch(r){throw console.error("Failed to encode filter state:",r),new Error("Failed to encode filter state")}}function r9(e){try{const r=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(4-e.length%4)%4,"="),t=atob(r);return JSON.parse(t)}catch(r){throw console.error("Failed to decode filter state:",r),new Error("Failed to decode filter state")}}const hs="dtv-filter-state";function k0(e){try{const r=G2(e),t=new URL(window.location.href);return t.searchParams.set(hs,r),t.toString()}catch(r){throw console.error("Failed to create shareable URL:",r),new Error("Failed to create shareable URL")}}async function _0(e){try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(e);else{const r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"),document.body.removeChild(r)}}catch(r){throw console.error("Failed to copy to clipboard:",r),new Error("Failed to copy to clipboard")}}function a9(){try{const r=new URLSearchParams(window.location.search).get(hs);return r?r9(r):null}catch(e){return console.warn("Failed to parse filter from URL:",e),null}}function l9(){const e=new URL(window.location.href);e.searchParams.delete(hs),window.history.replaceState({},"",e.toString())}function o9(e){try{const r=G2(e),t=new URL(window.location.href);t.searchParams.get(hs)!==r&&(t.searchParams.set(hs,r),window.history.replaceState({},"",t.toString()))}catch(r){console.warn("Failed to set filter in URL",r)}}function i9({actions:e,selectedView:r,filterState:t,setFilterState:l,refetch:n,showToast:s,paginationState:p,rowsPerPage:d}){const[m,g]=c.useState(()=>new Set);return qe.jsx(qe.Fragment,{children:e.map((h,S)=>{const x=m.has(S),O=async()=>{if(x)return;g(D=>new Set(D).add(S));const $={view:r,filterState:t,setFilterState:l,refetch:n,showToast:s,generateGraphQLQueryAST:H2,renderGraphQLQuery:U2,buildGraphQLQueryVariables:V2,getPaginationState:()=>p,rowsPerPage:d};try{await h.onClick($)}catch(D){console.error("Action handler error",D),s({severity:"error",summary:"Action Failed",detail:h.label,life:3e3})}finally{g(D=>{const K=new Set(D);return K.delete(S),K})}};return qe.jsx(mr,{type:"button",icon:h.icon,outlined:h.outlined!==!1,size:h.size==="normal"?void 0:"small",disabled:h.disabled||x,label:x?`${h.label}...`:h.label,onClick:O,"data-testid":`dtv-action-${S}`},`custom-action-${S}`)})})}const u9=M6;function Y2({graphqlHost:e,graphqlToken:r,geminiApiKey:t,showViewsMenu:l,showViewTitle:n,showCsvExportButton:s=!1,showPopoutButton:p=!0,viewsJson:d,externalRuntime:m,isOverlay:g=!1,onCloseOverlay:h,syncFilterStateToUrl:S=!1,rowSelection:x,actions:O=[],rowClassFunction:$,rowsPerPageOptions:D=[20,50,100,200]}){const K=c.useMemo(()=>JSON.parse(d).map(It=>e9(It,u9,m)),[d,m]),U=c.useMemo(()=>new SC(e,{headers:{contentType:"application/json",Authorization:`Bearer ${r}`}}),[e,r]),I=c.useMemo(()=>{const xe=a9();if(xe)try{const It=K[0];return It?o2(xe,It.filterSchema):void 0}catch(It){console.warn("Invalid initial filter state from URL, falling back to defaults",It);return}},[d]),{state:N,selectedView:B,setSelectedViewId:H,setFilterSchema:pe,setFilterState:oe,setDataRows:W,setRowsPerPage:F}=O6(K,D,I),j=c.useMemo(()=>V7(B.collectionName,B.columnDefinitions,B.boolExpType,B.orderByType,B.paginationKey),[B.id]),[L,X]=c.useState([]),[_,Q]=c.useState(""),G=c.useRef(null),Z=c.useRef(null),[be,me]=c.useState(!1),[ve,P]=c.useState(!1),[re,le]=c.useState(!1),[z,ne]=c.useState(0),[ce,Oe]=c.useState(!1);c.useEffect(()=>{_&&!ve&&P(!0)},[_,ve]),c.useEffect(()=>{if(!g&&ce){const xe=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=xe}}},[ce,g]),c.useEffect(()=>{if(!g)return;const xe=It=>{It.key==="Escape"&&(h==null||h())};return window.addEventListener("keydown",xe),()=>window.removeEventListener("keydown",xe)},[g,h]);const Qe=N.pagination.rowsPerPage,ct=N.data.rows.length===Qe,Lt=N.pagination.page>0;c.useEffect(()=>{const xe=Jf.loadFilters(B.id,B.filterSchema);X(xe)},[B.id]),c.useEffect(()=>{var xe;I&&!S&&(l9(),(xe=G.current)==null||xe.show({severity:"info",summary:"Filter Loaded",detail:"Loaded from URL",life:3e3}))},[]),c.useEffect(()=>{S&&o9(N.filterState)},[S,z]);const Ye=xe=>{var Kt;const It=prompt("Enter a name for this filter:");if(!It)return;const _t=Jf.saveFilter({view:B.id,name:It,state:xe});X(zt=>[...zt,_t]),(Kt=G.current)==null||Kt.show({severity:"success",summary:"Filter Saved",detail:`Filter "${It}" has been saved successfully`,life:3e3})},it=(xe,It)=>{z2({message:`Are you sure you want to overwrite the existing filter "${xe.name}"?`,header:"Confirm Filter Update",icon:"pi pi-exclamation-triangle",defaultFocus:"reject",acceptClassName:"p-button-danger",accept:()=>{var Kt;const _t=Jf.updateFilter(xe,{state:It});_t&&(X(zt=>zt.map($t=>$t.id===xe.id?_t:$t)),(Kt=G.current)==null||Kt.show({severity:"success",summary:"Filter Updated",detail:`Filter "${xe.name}" has been updated successfully`,life:3e3}))},reject:()=>{}})},_e=xe=>{var _t;Jf.deleteFilter(xe)&&(X(Kt=>Kt.filter(zt=>zt.id!==xe)),(_t=G.current)==null||_t.show({severity:"success",summary:"Filter Deleted",detail:"Filter has been deleted successfully",life:3e3}))},Je=async()=>{var xe,It;try{const _t=k0(N.filterState);await _0(_t),(xe=G.current)==null||xe.show({severity:"success",summary:"Filter Shared",detail:"Shareable link copied to clipboard!",life:3e3})}catch(_t){console.error("Failed to share filter:",_t),(It=G.current)==null||It.show({severity:"error",summary:"Share Failed",detail:"Failed to create shareable link",life:3e3})}},dt=async xe=>{var It,_t;try{const Kt=k0(xe);await _0(Kt),(It=G.current)==null||It.show({severity:"success",summary:"Filter Shared",detail:"Shareable link copied to clipboard!",life:3e3})}catch(Kt){console.error("Failed to share saved filter:",Kt),(_t=G.current)==null||_t.show({severity:"error",summary:"Share Failed",detail:"Failed to create shareable link",life:3e3})}},jt=()=>{Z.current&&Z.current.exportCSV({selectionOnly:!1})},Bt=c.useCallback((xe,It)=>G7({client:U,view:B,query:j,filterState:N.filterState,rowLimit:It,cursor:xe}),[U,B,j,N.filterState]);c.useEffect(()=>{Bt(null,Qe).then(xe=>W(xe)).catch(xe=>{xe instanceof DOMException&&xe.name})},[N.selectedViewId,z]);const Rt=xe=>{oe(xe)},Ue=N.filterSchemasAndGroups.filters.flatMap(xe=>{function It(zt){return zt.toLowerCase().includes(_.toLowerCase())}function _t(zt){return typeof zt=="string"?It(zt):"and"in zt?zt.and.some($t=>It($t)):"or"in zt?zt.or.some($t=>It($t)):!1}return It(xe.label)?[xe.id]:Gv(xe.expression).some(zt=>_t(zt.field))?[xe.id]:[]}),De=async()=>{const xe=N.data.rows.length>0?N.data.rows[N.data.rows.length-1][B.paginationKey]:null;if(typeof xe!="string"&&typeof xe!="number"){console.error("Invalid cursor type:",xe);return}const It=await Bt(xe,Qe);W(It,{page:N.pagination.page+1,cursors:[...N.pagination.cursors,xe],rowsPerPage:Qe})},St=async()=>{if(N.pagination.page===0)return;const xe=N.pagination.cursors.slice(0,-1),It=xe[xe.length-1]??null,_t=await Bt(It,Qe);W(_t,{page:N.pagination.page-1,cursors:xe,rowsPerPage:Qe})},yt=async xe=>{if(xe===Qe)return;F(xe);const It=await Bt(null,xe);W(It,{page:0,cursors:[],rowsPerPage:xe})};return qe.jsxs("div",{className:"tw:p-2",children:[qe.jsx(_2,{ref:G}),qe.jsx($2,{}),qe.jsx(T2,{model:[...l?[{label:"Views",icon:"pi pi-eye",items:K.map(xe=>({label:xe.title,icon:"pi pi-table",command:()=>H(xe.id)}))}]:[]],className:"tw:mb-4 tw:border-b",start:qe.jsxs("div",{className:"tw:flex tw:gap-2 tw:items-center",children:[qe.jsx(mr,{type:"button",icon:ve?"pi pi-filter-slash":"pi pi-filter",outlined:!0,size:"small",label:ve?"Hide Filters":"Filters",onClick:()=>{P(xe=>{const It=!xe;return It||Q(""),It})}}),qe.jsx(mr,{type:"button",icon:"pi pi-bookmark",outlined:!0,size:"small",label:re?"Hide Saved Filters":"Saved Filters",onClick:()=>le(xe=>!xe)}),s&&qe.jsx(mr,{type:"button",icon:"pi pi-table",outlined:!0,size:"small",label:"Export page to CSV",onClick:jt,"data-testid":"export-csv-button"}),p&&qe.jsx(mr,{type:"button",icon:g?"pi pi-times":"pi pi-window-maximize",outlined:!0,size:"small",label:g?"Close Popout":"Popout",onClick:()=>{g?h==null||h():Oe(!0)}}),qe.jsx(i9,{actions:O,selectedView:B,filterState:N.filterState,setFilterState:oe,refetch:()=>ne(xe=>xe+1),showToast:xe=>{var It;return(It=G.current)==null?void 0:It.show({...xe})},paginationState:N.pagination,rowsPerPage:Qe})]}),end:qe.jsxs("div",{className:"tw:flex tw:gap-2",children:[qe.jsxs(R2,{iconPosition:"left",children:[qe.jsx(I2,{className:"pi pi-search"}),qe.jsx(Hl,{value:_,onChange:xe=>Q(xe.target.value),placeholder:"Search filters..."})]}),qe.jsx(mr,{type:"button",size:"small",icon:"pi pi-sparkles",label:"AI Filter Assistant",onClick:()=>me(xe=>!xe)})]})}),(n||g)&&qe.jsx("h1",{className:"tw:text-2xl tw:mb-4 tw:font-bold",children:B.title}),be&&qe.jsx("div",{className:"tw:mb-6",children:qe.jsx(B7,{filterSchema:N.filterSchemasAndGroups,filterState:N.filterState,setFilterSchema:pe,setFilterState:oe,selectedView:B,geminiApiKey:t,toast:G,setShowFilterForm:P})}),qe.jsx(z7,{savedFilters:L,onFilterDelete:_e,onFilterLoad:Rt,onFilterApply:()=>ne(xe=>xe+1),onFilterShare:dt,visible:re,filterSchema:N.filterSchemasAndGroups}),ve&&qe.jsx(A4,{filterSchemasAndGroups:N.filterSchemasAndGroups,filterState:N.filterState,setFilterState:oe,onSaveFilter:Ye,onUpdateFilter:it,onShareFilter:Je,savedFilters:L,visibleFilterIds:Ue,onSubmit:()=>{ne(xe=>xe+1)},graphqlClient:U}),qe.jsx(T6,{viewId:B.id,ref:Z,columns:B.columnDefinitions,data:N.data.flattenedRows,noRowsComponent:B.noRowsComponent,setFilterState:oe,filterState:N.filterState,triggerRefetch:()=>ne(xe=>xe+1),rowSelection:x,rowClassFunction:$}),N.data.rows.length>0&&qe.jsx(P7,{onPageChange:De,onPrevPage:St,hasNextPage:ct,hasPrevPage:Lt,currentPage:N.pagination.page,rowsPerPage:Qe,actualRows:N.data.rows.length,onRowsPerPageChange:yt,rowsPerPageOptions:D}),ce&&!g&&F0.createPortal(qe.jsx("div",{className:"tw:fixed tw:inset-0 tw:bg-white tw:overflow-auto",children:qe.jsx(Y2,{graphqlHost:e,graphqlToken:r,geminiApiKey:t,showViewsMenu:l,showViewTitle:n,showCsvExportButton:s,showPopoutButton:p,viewsJson:d,externalRuntime:m,isOverlay:!0,onCloseOverlay:()=>Oe(!1),syncFilterStateToUrl:S,rowSelection:x,rowClassFunction:$,rowsPerPageOptions:D})}),document.body)]})}const c9="2.0.0",s9={version:c9};function f9(e,r){const t=typeof e=="string"?document.getElementById(e):e;if(!t)throw new Error("Target element not found");hE.createRoot(t).render(qe.jsx(c.StrictMode,{children:qe.jsx(qC,{value:{},children:qe.jsx(Y2,{graphqlHost:r.graphqlHost,graphqlToken:r.graphqlToken,geminiApiKey:r.geminiApiKey,showViewsMenu:r.showViewsMenu??!1,showViewTitle:r.showViewTitle??!1,showCsvExportButton:r.showCsvExportButton??!1,showPopoutButton:r.showPopoutButton??!0,viewsJson:r.viewsJson,externalRuntime:r.externalRuntime,syncFilterStateToUrl:r.syncFilterStateToUrl??!1,rowSelection:r.rowSelection,actions:r.actions,rowClassFunction:r.rowClassFunction,rowsPerPageOptions:r.rowsPerPageOptions})})}))}const d9={version:s9.version,renderTableView:f9};window.dtv=d9;