domma-cms 1.30.1 → 1.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __browsers=[];let __keyboardNavInstalled=!1;function bootstrapCollectionBrowsers(l=document){const t=[...l.querySelectorAll(".dm-collection-browser")].filter(e=>!e.__dmCollectionBrowser);t.length&&(t.forEach(e=>{e.__dmCollectionBrowser=!0;try{__browsers.push(new CollectionBrowser(e,__browsers.length))}catch(i){console.error("[collection-browser] hydration failed:",i)}}),!__keyboardNavInstalled&&__browsers.length&&(__keyboardNavInstalled=!0,installGlobalKeyboardNav()))}function installGlobalKeyboardNav(){__browsers.length&&document.addEventListener("keydown",l=>{const t=l.target&&(l.target.tagName==="INPUT"||l.target.tagName==="TEXTAREA"||l.target.isContentEditable||!!l.target.closest?.('[role="slider"]'));if(l.key==="/"&&!t){const i=__browsers[0]?.el.querySelector(".dm-cb-search-input");i&&(l.preventDefault(),i.focus(),i.select());return}if((l.key==="ArrowLeft"||l.key==="ArrowRight")&&!t){const e=__browsers.find(s=>s.el.contains(l.target))||__browsers[0];if(!e)return;const i=Math.max(1,Math.ceil(e.currentTotal/e.config.pageSize)),n=l.key==="ArrowRight"?Math.min(i,e.state.page+1):Math.max(1,e.state.page-1);n!==e.state.page&&(l.preventDefault(),e.setState({page:n}))}})}function decodePayload(l){if(!l)return null;try{const t=atob(l),e=decodeURIComponent(escape(t));return JSON.parse(e)}catch{try{return JSON.parse(atob(l))}catch{return null}}}function clear(l){l&&typeof l.replaceChildren=="function"&&l.replaceChildren()}function distinctValues(l,t){const e=new Set;for(const i of l||[]){const n=i?.data?.[t];n!=null&&(Array.isArray(n)?n.forEach(s=>s!=null&&e.add(String(s))):e.add(String(n)))}return[...e].sort()}class CollectionBrowser{constructor(t,e){this.el=t,this.config=decodePayload(t.dataset.cbConfig)||{},this.schema=decodePayload(t.dataset.cbSchema)||{fields:[]};const i=decodePayload(t.dataset.cbData)||{entries:[],total:0,page:1,pageSize:12},n=(this.config.id||`${this.config.slug}-${e}`).replace(/[^a-z0-9]/gi,"_");let s=n,a=1;for(;__browsers.some(r=>r.idScope===s);)a+=1,s=`${n}_${a}`;this.idScope=s,this.urlPrefix=`cb_${s}_`,this._fragReqId=0,this.entries=i.entries||[],this.total=i.total||0,this.state={search:"",filter:{},sort:this.config.initial?.sort||"createdAt",order:this.config.initial?.order||"desc",page:1},this.readUrlState(),this.buildSkeleton(),this.refresh()}buildSkeleton(){clear(this.el);const t=elt("div","dm-cb-header");this.config.filterable?.length&&t.appendChild(this.buildDrawerToggle()),this.config.searchable&&t.appendChild(this.buildSearchInput()),this.config.sortable&&t.appendChild(this.buildSortControl()),this.config.savedSearches!==!1&&t.appendChild(this.buildSavedSearches()),this.config.exportable&&t.appendChild(this.buildExportButton());const e=elt("div","dm-cb-layout");this.filterRail=elt("aside","dm-cb-filter-rail"),this.bodyEl=elt("div","dm-cb-body"),e.appendChild(this.filterRail),e.appendChild(this.bodyEl),this.config.filterable?.length?this.renderFilterRail():this.filterRail.style.display="none",this.pagerEl=elt("div","dm-cb-pagination"),t.childElementCount&&this.el.appendChild(t),this.el.appendChild(e),this.el.appendChild(this.pagerEl),this.el.classList.add("dm-cb-hydrated")}buildSavedSearches(){const t=elt("div","dm-cb-saved"),e=elt("button","dm-cb-saved-toggle btn btn-outline");e.type="button",e.textContent="Saved \u25BE",t.appendChild(e);const i=elt("div","dm-cb-saved-menu");i.hidden=!0,t.appendChild(i);const n=()=>{clear(i);const s=this.loadSavedSearches();if(!s.length){const o=elt("p","dm-cb-saved-empty");o.textContent="No saved views yet.",i.appendChild(o)}for(const o of s){const c=elt("div","dm-cb-saved-item"),d=elt("button","dm-cb-saved-apply");d.type="button",d.textContent=o.name,d.addEventListener("click",()=>{this.state.search=o.search||"",this.state.filter={...o.filter||{}},this.state.sort=o.sort||this.config.initial?.sort||"createdAt",this.state.order=o.order||this.config.initial?.order||"desc",this.state.page=1,this.renderFilterRail();const p=this.el.querySelector(".dm-cb-search-input");p&&(p.value=this.state.search),i.hidden=!0,this.refresh()});const h=elt("button","dm-cb-saved-del");h.type="button",h.textContent="\xD7",h.title="Delete saved view",h.addEventListener("click",p=>{p.stopPropagation(),this.deleteSavedSearch(o.name),n()}),c.appendChild(d),c.appendChild(h),i.appendChild(c)}const a=elt("div","dm-cb-saved-actions"),r=elt("button","dm-cb-saved-create btn btn-primary");r.type="button",r.textContent="Save current view",r.addEventListener("click",async()=>{const o=await this.promptName();o&&(this.addSavedSearch({name:o,search:this.state.search,filter:this.state.filter,sort:this.state.sort,order:this.state.order}),n())}),a.appendChild(r),i.appendChild(a)};return e.addEventListener("click",()=>{i.hidden=!i.hidden,i.hidden||n()}),document.addEventListener("click",s=>{t.contains(s.target)||(i.hidden=!0)}),t}async promptName(){const t=typeof window<"u"&&typeof window.prompt=="function"?window.prompt("Name this saved view:"):null;return t&&t.trim()||null}loadSavedSearches(){try{const t=`cb_saved_${this.idScope}`,e=typeof S<"u"&&S.get?S.get(t):null;return Array.isArray(e)?e:[]}catch{return[]}}addSavedSearch(t){const e=this.loadSavedSearches().filter(i=>i.name!==t.name);e.push(t);try{typeof S<"u"&&S.set&&S.set(`cb_saved_${this.idScope}`,e)}catch{}}deleteSavedSearch(t){const e=this.loadSavedSearches().filter(i=>i.name!==t);try{typeof S<"u"&&S.set&&S.set(`cb_saved_${this.idScope}`,e)}catch{}}buildExportButton(){const t=elt("button","dm-cb-export btn btn-outline");return t.type="button",t.textContent="Export CSV",t.addEventListener("click",()=>this.exportCsv()),t}exportCsv(){if(this.config.mode==="client"){let n=this.entries;if(this.state.search){const o=this.state.search.toLowerCase();n=n.filter(c=>Object.values(c.data||{}).some(d=>String(d).toLowerCase().includes(o)))}const s={...this.state.filter,...this.config.baked||{}};n=applyFilterInMemory(n,s);const a=this.visibleFields(n),r=toCsv(n,a);downloadCsv(`${this.config.slug}-export.csv`,r);return}const t=new URLSearchParams;t.set("format","csv"),this.state.search&&t.set("search",this.state.search);const e={...this.state.filter,...this.config.baked||{}};for(const[n,s]of Object.entries(e))t.set(`filter[${n}]`,s);const i=`/api/collections/${encodeURIComponent(this.config.slug)}/export?${t.toString()}`;window.open(i,"_blank")}buildDrawerToggle(){const t=elt("button","dm-cb-drawer-toggle btn btn-outline");t.type="button",t.setAttribute("aria-label","Toggle filters");const e=elt("span","dm-cb-drawer-label");e.textContent="Filters";const i=elt("span","dm-cb-drawer-count");return t.appendChild(e),t.appendChild(document.createTextNode(" ")),t.appendChild(i),t.addEventListener("click",()=>{this.el.classList.toggle("dm-cb-drawer-open")}),t}buildSearchInput(){const t=elt("div","dm-cb-search"),e=elt("input","dm-cb-search-input");return e.type="search",e.placeholder="Search\u2026",e.value=this.state.search,e.addEventListener("input",debounce(()=>{this.setState({search:e.value,page:1})},200)),t.appendChild(e),t}buildSortControl(){const t=elt("div","dm-cb-sort"),e=elt("label","dm-cb-sort-label");e.textContent="Sort:",t.appendChild(e);const i=elt("select","dm-cb-sort-select"),n=this.sortableFieldList();for(const a of n){const r=elt("option");r.value=a.name,r.textContent=a.label,a.name===this.state.sort&&(r.selected=!0),i.appendChild(r)}i.addEventListener("change",()=>this.setState({sort:i.value,page:1})),t.appendChild(i);const s=elt("button","dm-cb-sort-dir");return s.type="button",s.textContent=this.state.order==="asc"?"\u2191":"\u2193",s.title=this.state.order==="asc"?"Ascending":"Descending",s.addEventListener("click",()=>{this.setState({order:this.state.order==="asc"?"desc":"asc",page:1}),s.textContent=this.state.order==="asc"?"\u2191":"\u2193"}),t.appendChild(s),t}sortableFieldList(){const t=this.config.sortableFields?.length?new Set(this.config.sortableFields):null,e=[{name:"createdAt",label:"Most recent"}];for(const i of this.schema.fields||[])t&&!t.has(i.name)||e.push({name:i.name,label:i.label||i.name});return e}renderFilterRail(){for(const i of this._sliders||[])i.destroy();this._sliders=[],clear(this.filterRail);const t=elt("h4","dm-cb-filter-heading");t.textContent="Filters",this.filterRail.appendChild(t);for(const i of this.config.filterable){const n=(this.schema.fields||[]).find(a=>a.name===i);if(!n)continue;const s=this.buildFilterControl(n);s&&this.filterRail.appendChild(s)}const e=elt("button","dm-cb-filter-reset");e.type="button",e.textContent="Clear filters",e.addEventListener("click",()=>{this.setState({filter:{},search:"",page:1}),this.renderFilterRail();const i=this.el.querySelector(".dm-cb-search-input");i&&(i.value=""),this.filterRail.querySelector(".dm-cb-filter-reset")?.focus()}),this.filterRail.appendChild(e)}buildFilterControl(t){const e=elt("div","dm-cb-filter"),i=elt("label","dm-cb-filter-label");switch(i.textContent=t.label||t.name,e.appendChild(i),t.type){case"reference":e.appendChild(this.buildReferenceFilter(t));break;case"select":case"chooser":e.appendChild(this.buildSelectControl(t,!1));break;case"multiselect":case"tags":case"tag":e.appendChild(this.buildSelectControl(t,!0));break;case"number":e.appendChild(this.buildRangeControl(t,"number"));break;case"date":case"datetime":e.appendChild(this.buildRangeControl(t,"date"));break;case"boolean":case"checkbox":e.appendChild(this.buildBooleanControl(t));break;default:e.appendChild(this.buildTextControl(t));break}return e}buildReferenceFilter(t){const e=new Map;for(const a of this.entries){const r=a._refs?.[t.name];if(!r)continue;const o=Array.isArray(r)?r:[r];for(const c of o)!c||c.missing||e.has(c.id)||e.set(c.id,c.display)}const i=`${t.name}_eq`,n=elt("select","dm-cb-select"),s=elt("option");s.value="",s.textContent=this.config.mode==="server"?"Any (loaded)":"Any",n.appendChild(s);for(const[a,r]of e){const o=elt("option");o.value=a,o.textContent=r,String(this.state.filter[i]??"")===String(a)&&(o.selected=!0),n.appendChild(o)}return n.addEventListener("change",()=>this.updateFilter(i,n.value)),n}buildTextControl(t){const e=`${t.name}_contains`,i=elt("input","dm-cb-text");return i.type="text",i.placeholder="Contains\u2026",i.value=this.state.filter[e]||"",i.addEventListener("input",debounce(()=>{this.updateFilter(e,i.value.trim())},200)),i}buildSelectControl(t,e){const i=Array.isArray(t.options)&&t.options.length?t.options.map(o=>typeof o=="object"?o:{value:o,label:o}):distinctValues(this.entries,t.name).map(o=>({value:o,label:o})),n=this.config.mode==="client"?this.facetCounts(t.name,e?"_in":"_eq",i.map(o=>o.value)):null;if(e){const o=`${t.name}_in`,c=elt("div","dm-cb-chips"),d=new Set((this.state.filter[o]||"").split(",").filter(Boolean));for(const h of i){const p=elt("button","dm-cb-chip");p.type="button",d.has(String(h.value))&&p.classList.add("dm-cb-chip-active");const f=elt("span","dm-cb-chip-label");if(f.textContent=h.label??h.value,p.appendChild(f),n){const u=elt("span","dm-cb-chip-count");u.textContent=n[String(h.value)]??0,p.appendChild(u)}p.addEventListener("click",()=>{d.has(String(h.value))?d.delete(String(h.value)):d.add(String(h.value)),this.updateFilter(o,d.size?[...d].join(","):"")}),c.appendChild(p)}return c}const s=`${t.name}_eq`,a=elt("select","dm-cb-select"),r=elt("option");r.value="",r.textContent="Any",a.appendChild(r);for(const o of i){const c=elt("option");c.value=o.value;const d=n?` (${n[String(o.value)]??0})`:"";c.textContent=(o.label??o.value)+d,String(this.state.filter[s]??"")===String(o.value)&&(c.selected=!0),a.appendChild(c)}return a.addEventListener("change",()=>this.updateFilter(s,a.value)),a}facetCounts(t,e,i){const n={};for(const[o,c]of Object.entries(this.state.filter||{})){const{field:d}=parseFilterKey(o);d!==t&&(n[o]=c)}let s=this.entries;if(this.state.search){const o=this.state.search.toLowerCase();s=s.filter(c=>Object.values(c.data||{}).some(d=>String(d).toLowerCase().includes(o)))}const a={...n,...this.config.baked||{}};s=applyFilterInMemory(s,a);const r={};for(const o of i){const c={...a,[`${t}${e}`]:String(o)};r[String(o)]=applyFilterInMemory(s,c).length}return r}buildRangeControl(t,e){const i=`${t.name}_gte`,n=`${t.name}_lte`,s=elt("div","dm-cb-range"),a=elt("div","dm-cb-range-inputs"),r=elt("input","dm-cb-range-min"),o=elt("input","dm-cb-range-max");r.type=e,o.type=e,r.placeholder="Min",o.placeholder="Max",r.value=this.state.filter[i]||"",o.value=this.state.filter[n]||"",a.appendChild(r),a.appendChild(document.createTextNode(" - ")),a.appendChild(o),s.appendChild(a);let c=null,d=null,h=null;const p=window.DommaCollectionRange;if(e==="number"&&this.config.mode==="client"&&this.entries.length&&p&&typeof E<"u"&&E.rangeSlider&&(d=p.rangeBounds(this.entries.map(u=>u.data?.[t.name]))),d){const u=elt("div","dm-cb-slider");s.appendChild(u);const g=t.label||t.name,m=b=>{const C=p.rangeFilter(d,b);(!h||b[0]!==h[0])&&(r.value=C.gte),(!h||b[1]!==h[1])&&(o.value=C.lte)};c=E.rangeSlider(u,{range:!0,min:d.min,max:d.max,step:d.step,value:p.sliderValue(d,r.value,o.value),labels:p.rangeLabel(t,d.step),ariaLabels:[`${g} from`,`${g} to`],onInput:m,onChange:b=>{m(b),h=b.slice(),this.updateFilter(i,r.value,!0),this.updateFilter(n,o.value)}}),h=c.getValue().slice(),this._sliders.push(c)}const f=debounce(()=>{this.updateFilter(i,r.value,!0),this.updateFilter(n,o.value),c&&(c.setValue(p.sliderValue(d,r.value,o.value),{silent:!0}),h=c.getValue().slice())},250);return r.addEventListener("input",f),o.addEventListener("input",f),s}buildBooleanControl(t){const e=`${t.name}_eq`,i=elt("select","dm-cb-select");for(const[n,s]of[["","Any"],["true","Yes"],["false","No"]]){const a=elt("option");a.value=n,a.textContent=s,String(this.state.filter[e]??"")===n&&(a.selected=!0),i.appendChild(a)}return i.addEventListener("change",()=>this.updateFilter(e,i.value)),i}updateFilter(t,e,i=!1){const n={...this.state.filter};e===""||e==null?delete n[t]:n[t]=e,this.state.filter=n,this.state.page=1,i||this.refresh()}setState(t){Object.assign(this.state,t),this.refresh()}async refresh(){this.config.syncUrl&&this.writeUrlState(),this.config.mode==="server"&&await this.fetchPage(),this.renderBody(),this.renderPagination(),this.updateFacetCounts(),this.updateDrawerBadge()}updateFacetCounts(){if(this.config.mode==="client"&&this.filterRail)for(const t of this.config.filterable||[]){const e=(this.schema.fields||[]).find(r=>r.name===t);if(!e)continue;const i=e.type==="multiselect"||e.type==="tags"||e.type==="tag"?"_in":"_eq",n=Array.isArray(e.options)&&e.options.length?e.options.map(r=>typeof r=="object"?r:{value:r,label:r}):distinctValues(this.entries,t).map(r=>({value:r,label:r})),s=this.facetCounts(t,i,n.map(r=>r.value)),a=this.filterRail.querySelectorAll(".dm-cb-filter");for(const r of a){const o=r.querySelector(".dm-cb-filter-label");if(!o||o.textContent!==(e.label||e.name))continue;r.querySelectorAll(".dm-cb-chip").forEach((h,p)=>{const f=h.querySelector(".dm-cb-chip-count");f&&n[p]&&(f.textContent=s[String(n[p].value)]??0)});const d=r.querySelector("select.dm-cb-select");d&&Array.from(d.options).forEach(h=>{if(!h.value)return;const p=n.find(f=>String(f.value)===h.value)?.label??h.value;h.textContent=`${p} (${s[h.value]??0})`})}}}updateDrawerBadge(){const t=this.el.querySelector(".dm-cb-drawer-toggle");if(!t)return;const e=(this.state.search?1:0)+Object.keys(this.state.filter||{}).length,i=t.querySelector(".dm-cb-drawer-count");i&&(i.textContent=e>0?`(${e})`:"")}async fetchPage(){const t={...this.state.filter,...this.config.baked||{}},e=new URLSearchParams;e.set("page",this.state.page),e.set("limit",this.config.pageSize),e.set("sort",this.state.sort),e.set("order",this.state.order),this.state.search&&e.set("search",this.state.search);for(const[n,s]of Object.entries(t))e.set(`filter[${n}]`,s);this.config.scope==="mine"&&e.set("scope","mine"),this._fetchAbort&&this._fetchAbort.abort(),this._fetchAbort=new AbortController;const i=this.config.sourceKind==="view"?`/api/views/${encodeURIComponent(this.config.slug)}/public?${e.toString()}`:`/api/collections/${encodeURIComponent(this.config.slug)}/public?${e.toString()}`;try{const n=await fetch(i,{headers:this.authHeaders(),signal:this._fetchAbort.signal});if(!n.ok){this.entries=[],this.total=0;return}const s=await n.json(),a=s.entries||s.results||[];this.entries=a.map(r=>r.data?r:{id:r.id||"",data:r.data||r}),this.total=s.total||a.length}catch(n){if(n.name==="AbortError")return;this.entries=[],this.total=0}}authHeaders(){try{const t=typeof S<"u"&&S.get?S.get("auth_token"):null;return t?{Authorization:`Bearer ${t}`}:{}}catch{return{}}}pipeline(){if(this.config.mode==="server")return{visible:this.entries,total:this.total};let t=this.entries,e=null;if(this.state.search){const c=this.state.search.toLowerCase();e=new Map,t=t.filter(d=>{let h=0;for(const[p,f]of Object.entries(d.data||{})){if(f==null)continue;const u=String(f).toLowerCase();let g=0,m=0;for(;(g=u.indexOf(c,g))!==-1;)m++,g+=c.length;m>0&&(h+=m*(p===this.config.titleField?3:1))}return h>0&&e.set(d.id||d,h),h>0})}if(Object.keys(this.state.filter).length||Object.keys(this.config.baked||{}).length){const c={...this.state.filter,...this.config.baked||{}};t=applyFilterInMemory(t,c)}const i=this.config.initial?.sort||"createdAt",n=this.config.initial?.order||"desc",s=this.state.sort===i&&this.state.order===n;this.state.search&&e&&s?(t=[...t].sort((c,d)=>{const h=e.get(c.id||c)||0;return(e.get(d.id||d)||0)-h}),this._activeSortMode="relevance"):(t=sortEntries(t,this.state.sort,this.state.order),this._activeSortMode=null);const a=t.length,r=(this.state.page-1)*this.config.pageSize;return{visible:t.slice(r,r+this.config.pageSize),total:a}}renderBody(){const{visible:t,total:e}=this.pipeline();if(this.currentTotal=e,clear(this.bodyEl),!t.length){this.bodyEl.appendChild(this.buildEmptyState());return}const i=this.visibleFields(t);this.bodyEl.appendChild(this.renderForDisplay(t,i)),typeof Domma<"u"&&Domma.icons?.scan&&Domma.icons.scan(this.bodyEl),this.config.cta&&typeof wireCTAButtons=="function"&&wireCTAButtons(this.bodyEl)}buildEmptyState(){const t=elt("div","dm-collection-display dm-collection-empty"),e=!!this.state.search||Object.keys(this.state.filter||{}).length>0,i=elt("p");if(e){i.textContent="No results for these filters.",t.appendChild(i);const n=elt("button","btn btn-outline dm-cb-empty-clear");n.type="button",n.textContent="Clear filters",n.addEventListener("click",()=>{this.setState({filter:{},search:"",page:1}),this.renderFilterRail();const s=this.el.querySelector(".dm-cb-search-input");s&&(s.value="")}),t.appendChild(n)}else i.textContent=this.config.emptyMsg,t.appendChild(i);return t}visibleFields(t){let e=this.schema.fields||[];return this.config.fields?.length&&(e=this.config.fields.map(i=>e.find(n=>n.name===i)||{name:i,label:i})),!e.length&&t.length&&(e=Object.keys(t[0].data||{}).map(i=>({name:i,label:i}))),e}renderCards(t,e){const i=elt("div",`dm-collection-cards grid grid-cols-${this.config.columns}`);for(const n of t){const s=elt("div","card dm-collection-card"),a=e.find(c=>c.name===this.config.titleField),r=a?fieldDisplay(n,a):this.config.titleField?formatValue(n.data?.[this.config.titleField]):"";if(r){const c=elt("div","card-header");c.textContent=r,s.appendChild(c)}const o=elt("div","card-body");for(const c of e){if(this.config.titleField===c.name||!fieldDisplay(n,c))continue;const h=elt("div","dm-collection-card-field"),p=elt("strong");p.textContent=(c.label||c.name)+": ",h.appendChild(p),h.appendChild(fieldDisplayNode(n,c)),o.appendChild(h)}this.config.cta&&o.appendChild(this.buildCtaButton(n)),this.config.transitions&&o.appendChild(this.buildTransitionsGroup(n)),s.appendChild(o),i.appendChild(s)}return i}renderList(t,e){const i=elt("ul","dm-collection-list");for(const n of t){const s=elt("li","dm-collection-list-item"),a=e.find(c=>c.name===this.config.titleField),r=a?fieldDisplay(n,a):this.config.titleField?formatValue(n.data?.[this.config.titleField]):"";if(r){const c=elt("div","dm-collection-list-title");c.textContent=r,s.appendChild(c)}const o=e.filter(c=>c.name!==this.config.titleField).map(c=>{const d=fieldDisplay(n,c);return d?`${c.label||c.name}: ${d}`:""}).filter(Boolean).join(" \xB7 ");if(o){const c=elt("div","dm-collection-list-meta");c.textContent=o,s.appendChild(c)}this.config.cta&&s.appendChild(this.buildCtaButton(n)),this.config.transitions&&s.appendChild(this.buildTransitionsGroup(n)),i.appendChild(s)}return i}renderTable(t,e){const i=elt("table","dm-collection-table"),n=elt("thead"),s=elt("tr");for(const r of e){const o=elt("th");o.textContent=r.label||r.name,s.appendChild(o)}this.config.cta&&s.appendChild(elt("th")),this.config.transitions&&s.appendChild(elt("th")),n.appendChild(s),i.appendChild(n);const a=elt("tbody");for(const r of t){const o=elt("tr");for(const c of e){const d=elt("td");d.appendChild(fieldDisplayNode(r,c)),o.appendChild(d)}if(this.config.cta){const c=elt("td");c.appendChild(this.buildCtaButton(r)),o.appendChild(c)}if(this.config.transitions){const c=elt("td");c.appendChild(this.buildTransitionsGroup(r)),o.appendChild(c)}a.appendChild(o)}return i.appendChild(a),i}renderAccordion(t){const e=elt("div","accordion dm-collection-accordion");for(const i of t){const n=elt("div","accordion-item"),s=this.config.titleField&&i.data?.[this.config.titleField]||"Untitled",a=this.config.bodyField&&i.data?.[this.config.bodyField]||"",r=elt("button","accordion-header");r.type="button",r.textContent=String(s);const o=elt("div","accordion-panel");o.textContent=String(a),r.addEventListener("click",()=>n.classList.toggle("open")),n.appendChild(r),n.appendChild(o),e.appendChild(n)}return e}buildCtaButton(t){const e=this.config.cta,i=elt("button",`btn btn-${e.style||"primary"} dm-cta-trigger`);if(i.dataset.action=e.action,i.dataset.entry=t.id||"",this.config.scope&&(i.dataset.scope=this.config.scope),e.confirm&&(i.dataset.confirm=e.confirm),e.icon){const n=elt("span");n.dataset.icon=e.icon,i.appendChild(n),i.appendChild(document.createTextNode(" "))}return i.appendChild(document.createTextNode(e.label||"Run")),i}buildTransitionsGroup(t){const e=elt("div","dm-cb-transitions");return e.dataset.entry=t.id||"",e.textContent="Loading actions\u2026",Promise.resolve().then(()=>this.loadTransitions(t,e)),e}async loadTransitions(t,e){try{const i=new URLSearchParams({collection:this.config.slug,entryId:t.id||""});this.config.scope==="mine"&&i.set("scope","mine");const n=await fetch(`/api/actions/transitions?${i.toString()}`,{headers:this.authHeaders()});if(clear(e),!n.ok)return;const{transitions:s}=await n.json();if(!Array.isArray(s)||!s.length)return;for(const a of s){const r=elt("button",`btn btn-${a.trigger?.style||"outline"} dm-cb-transition-btn dm-cta-trigger`);if(r.dataset.action=a.slug,r.dataset.entry=t.id||"",this.config.scope&&(r.dataset.scope=this.config.scope),a.trigger?.confirmMessage&&(r.dataset.confirm=a.trigger.confirmMessage),a.trigger?.icon){const o=elt("span");o.dataset.icon=a.trigger.icon,r.appendChild(o),r.appendChild(document.createTextNode(" "))}r.appendChild(document.createTextNode(a.trigger?.label||a.title)),e.appendChild(r)}typeof Domma<"u"&&Domma.icons?.scan&&Domma.icons.scan(e),typeof wireCTAButtons=="function"&&wireCTAButtons(e)}catch{clear(e)}}renderPagination(){if(this.config.pagination==="scroll"){this.renderInfiniteSentinel();return}const t=Math.max(1,Math.ceil(this.currentTotal/this.config.pageSize));if(clear(this.pagerEl),t<=1)return;const e=elt("button","dm-cb-page-prev btn btn-outline");e.type="button",e.textContent="\u2039 Prev",e.disabled=this.state.page<=1,e.addEventListener("click",()=>this.setState({page:Math.max(1,this.state.page-1)}));const i=elt("button","dm-cb-page-next btn btn-outline");i.type="button",i.textContent="Next \u203A",i.disabled=this.state.page>=t,i.addEventListener("click",()=>this.setState({page:Math.min(t,this.state.page+1)}));const n=elt("span","dm-cb-page-info");n.textContent=`Page ${this.state.page} of ${t} (${this.currentTotal} entr${this.currentTotal===1?"y":"ies"})`,this.pagerEl.appendChild(e),this.pagerEl.appendChild(n),this.pagerEl.appendChild(i)}renderInfiniteSentinel(){clear(this.pagerEl);const t=Math.max(1,Math.ceil(this.currentTotal/this.config.pageSize));if(this.state.page>=t){const i=elt("p","dm-cb-scroll-end");i.textContent=`All ${this.currentTotal} entries loaded.`,this.pagerEl.appendChild(i);return}const e=elt("div","dm-cb-scroll-sentinel");e.setAttribute("aria-hidden","true"),e.textContent="Loading more\u2026",this.pagerEl.appendChild(e),this._scrollObserver&&this._scrollObserver.disconnect(),this._scrollObserver=new IntersectionObserver(async i=>{i[0].isIntersecting&&(this._scrollObserver.disconnect(),await this.loadMore())},{rootMargin:"200px 0px"}),this._scrollObserver.observe(e)}async loadMore(){const t=this.state.page+1,e=this.currentTotal,i=this.entries,n=this.state.page;this.state.page=t,this.config.syncUrl&&this.writeUrlState();let s;if(this.config.mode==="server")await this.fetchPage(),s=this.entries;else{const{visible:c}=this.pipeline();s=c}if(!s.length){this.state.page=n,this.entries=i,this.currentTotal=e,this.renderPagination();return}const a=this.visibleFields(s),r=this.renderForDisplay(s,a),o=this.bodyEl.firstElementChild;if(o&&o.tagName===r.tagName)for(;r.firstChild;)o.appendChild(r.firstChild);else this.bodyEl.appendChild(r);typeof Domma<"u"&&Domma.icons?.scan&&Domma.icons.scan(this.bodyEl),this.config.cta&&typeof wireCTAButtons=="function"&&wireCTAButtons(this.bodyEl),this.renderPagination()}renderForDisplay(t,e){const i=this.config.display;return i==="list"?this.renderList(t,e):i==="table"?this.renderTable(t,e):i==="accordion"?this.renderAccordion(t):i==="timeline"?this.renderTimeline(t):i==="block"?this.renderBlockPlaceholder(t):this.renderCards(t,e)}renderTimeline(t){const e=["vertical","centred","horizontal"].includes(this.config.layout)?this.config.layout:"vertical",i=["minimal","corporate","modern"].includes(this.config.theme)?this.config.theme:"minimal",n=elt("div",`dm-collection-timeline timeline timeline-${e} timeline-${i}`);for(const s of t){const a=elt("div","timeline-event"),r=this.config.dateField&&s.data?.[this.config.dateField]||"",o=this.config.titleField&&s.data?.[this.config.titleField]||"",c=this.config.bodyField&&s.data?.[this.config.bodyField]||"",d=this.config.statusField&&s.data?.[this.config.statusField]||"",h=this.config.iconField&&s.data?.[this.config.iconField]||"";if(h){const p=elt("span","timeline-icon");p.dataset.icon=String(h),a.appendChild(p)}if(r){const p=elt("div","timeline-date");p.textContent=String(r),a.appendChild(p)}if(o){const p=elt("h4","timeline-title");p.textContent=String(o),a.appendChild(p)}if(d){const p=elt("span",`badge badge-${d}`);p.textContent=String(d),a.appendChild(p)}if(c){const p=elt("div","timeline-body");p.textContent=String(c),a.appendChild(p)}n.appendChild(a)}return n}renderBlockPlaceholder(t){const e=elt("div","dm-collection-display dm-cb-block-loading");return e.textContent="Rendering\u2026",this.fetchBlockFragment(t,e),e}async fetchBlockFragment(t,e){const i=++this._fragReqId,n=t.map(r=>r.id).filter(Boolean),s={slug:this.config.slug,display:"block",block:this.config.block,"title-field":this.config.titleField,"body-field":this.config.bodyField,fields:this.config.fields?this.config.fields.join(","):"",empty:this.config.emptyMsg,limit:String(n.length||1)},a={...this.state.filter,...this.config.baked||{}};for(const[r,o]of Object.entries(a))o!==""&&o!=null&&(s[`where_${r}`]=String(o));s.sort=this.state.sort,s.order=this.state.order,s.limit=String(this.config.pageSize);try{const r=btoa(unescape(encodeURIComponent(JSON.stringify(s)))),o=this.config.scope==="mine"?"/api/collections/render-scope":"/api/collections/render-fragment",c=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders()},body:JSON.stringify({attrs:r,page:this.state.page})});if(i!==this._fragReqId)return;if(!c.ok){e.textContent=this.config.emptyMsg;return}const{html:d}=await c.json(),h=document.createElement("template");h.innerHTML=d||"",e.replaceWith(h.content)}catch{e.textContent="Unable to load block view."}}readUrlState(){if(!this.config.syncUrl)return;const t=new URLSearchParams(window.location.search),e=this.urlPrefix,i=a=>t.get(e+a);i("search")&&(this.state.search=i("search")),i("sort")&&(this.state.sort=i("sort")),i("order")&&(this.state.order=i("order")),i("page")&&(this.state.page=parseInt(i("page"),10)||1);const n={},s=`${e}filter[`;for(const[a,r]of t.entries())if(a.startsWith(s)&&a.endsWith("]")){const o=a.slice(s.length,-1);o&&(n[o]=r)}Object.keys(n).length&&(this.state.filter=n)}writeUrlState(){const t=new URL(window.location.href),e=this.urlPrefix,i=[];for(const s of t.searchParams.keys())s.startsWith(e)&&i.push(s);i.forEach(s=>t.searchParams.delete(s));const n=(s,a)=>{a!==""&&a!=null&&t.searchParams.set(e+s,a)};n("search",this.state.search),this.state.sort!==(this.config.initial?.sort||"createdAt")&&n("sort",this.state.sort),this.state.order!==(this.config.initial?.order||"desc")&&n("order",this.state.order),this.state.page!==1&&n("page",this.state.page);for(const[s,a]of Object.entries(this.state.filter))a!==""&&a!=null&&t.searchParams.set(`${e}filter[${s}]`,a);try{window.history.replaceState({},"",t.toString())}catch{}}}const OPERATORS=["_eq","_ne","_gte","_lte","_gt","_lt","_in","_nin","_contains","_starts","_ends","_exists"];function parseFilterKey(l){for(const t of OPERATORS)if(l.endsWith(t))return{field:l.slice(0,-t.length),op:t};return{field:l,op:"_eq"}}function resolveField(l,t){if(t==="createdBy")return l.meta?.createdBy;if(t==="id")return l.id;const e=t.split(".");let i=l.data;for(const n of e){if(i==null)return;i=i[n]}return i}function maybeNumber(l){if(typeof l=="number"||typeof l!="string")return l;const t=Number(l);return Number.isFinite(t)&&String(t)===l.trim()?t:l}function applyOp(l,t,e){switch(l){case"_eq":{const i=maybeNumber(t),n=maybeNumber(e);return Array.isArray(t)?t.map(maybeNumber).includes(n):i===n||String(i)===String(n)}case"_ne":{const i=maybeNumber(t),n=maybeNumber(e);return Array.isArray(t)?!t.map(maybeNumber).includes(n):!(i===n||String(i)===String(n))}case"_gt":return maybeNumber(t)>maybeNumber(e);case"_gte":return maybeNumber(t)>=maybeNumber(e);case"_lt":return maybeNumber(t)<maybeNumber(e);case"_lte":return maybeNumber(t)<=maybeNumber(e);case"_in":{const i=String(e).split(",").map(n=>maybeNumber(n.trim()));return Array.isArray(t)?t.map(maybeNumber).some(n=>i.includes(n)):i.includes(maybeNumber(t))}case"_nin":{const i=String(e).split(",").map(n=>maybeNumber(n.trim()));return Array.isArray(t)?!t.map(maybeNumber).some(n=>i.includes(n)):!i.includes(maybeNumber(t))}case"_contains":return String(t??"").toLowerCase().includes(String(e).toLowerCase());case"_starts":return String(t??"").toLowerCase().startsWith(String(e).toLowerCase());case"_ends":return String(t??"").toLowerCase().endsWith(String(e).toLowerCase());case"_exists":{const i=t!=null&&t!=="";return e==="true"||e==="1"||e===!0?i:!i}default:return!1}}function applyFilterInMemory(l,t){return!t||!Object.keys(t).length?l:l.filter(e=>{for(const[i,n]of Object.entries(t)){if(n==null||n==="")continue;const{field:s,op:a}=parseFilterKey(i),r=resolveField(e,s);if(!applyOp(a,r,n))return!1}return!0})}function sortEntries(l,t,e){const i=e==="asc"?1:-1;return[...l].sort((n,s)=>{const a=t==="createdAt"?n.meta?.createdAt||"":n.data?.[t]??"",r=t==="createdAt"?s.meta?.createdAt||"":s.data?.[t]??"";return a<r?-i:a>r?i:0})}function elt(l,t){const e=document.createElement(l);return t&&(e.className=t),e}function isFileRef(l){return l&&typeof l=="object"&&typeof l.url=="string"&&typeof l.name=="string"}function formatValue(l){return l==null?"":isFileRef(l)?l.name:Array.isArray(l)?l.join(", "):typeof l=="boolean"?l?"Yes":"No":String(l)}function fieldDisplay(l,t){if(t?.type==="reference"){const e=l?._refs?.[t.name];if(e!=null)return Array.isArray(e)?e.map(i=>i.missing?`${i.id} (missing)`:i.display).join(", "):e.missing?`${e.id} (missing)`:e.display}return formatValue(l?.data?.[t?.name])}function fieldDisplayNode(l,t){if(t?.type==="reference"){const i=l?._refs?.[t.name];if(i!=null){const n=document.createDocumentFragment();return(Array.isArray(i)?i:[i]).forEach((a,r)=>{if(r>0&&n.appendChild(document.createTextNode(", ")),a.missing)n.appendChild(document.createTextNode(`${a.id} (missing)`));else if(a.link){const o=document.createElement("a");o.href=a.link,o.textContent=a.display,n.appendChild(o)}else n.appendChild(document.createTextNode(a.display))}),n}}const e=l?.data?.[t?.name];if(isFileRef(e)){const i=document.createElement("a");if(i.href=e.url,String(e.mime||"").startsWith("image/")){i.target="_blank",i.rel="noopener";const n=document.createElement("img");n.src=e.url,n.alt=e.name,n.loading="lazy",n.className="dm-file-thumb",i.appendChild(n)}else i.download="",i.textContent=e.name;return i}return document.createTextNode(formatValue(e))}function debounce(l,t){let e;return(...i)=>{clearTimeout(e),e=setTimeout(()=>l(...i),t)}}function toCsv(l,t){const e=s=>{if(s==null)return"";let a=Array.isArray(s)?s.join(", "):String(s);return/[",\n\r]/.test(a)&&(a='"'+a.replace(/"/g,'""')+'"'),a},i=t.map(s=>e(s.label||s.name)).join(","),n=l.map(s=>t.map(a=>e(s.data?.[a.name])).join(",")).join(`
1
+ const __browsers=[];let __keyboardNavInstalled=!1;function bootstrapCollectionBrowsers(l=document){const t=[...l.querySelectorAll(".dm-collection-browser")].filter(e=>!e.__dmCollectionBrowser);t.length&&(t.forEach(e=>{e.__dmCollectionBrowser=!0;try{__browsers.push(new CollectionBrowser(e,__browsers.length))}catch(i){console.error("[collection-browser] hydration failed:",i)}}),!__keyboardNavInstalled&&__browsers.length&&(__keyboardNavInstalled=!0,installGlobalKeyboardNav()))}function installGlobalKeyboardNav(){__browsers.length&&document.addEventListener("keydown",l=>{const t=l.target&&(l.target.tagName==="INPUT"||l.target.tagName==="TEXTAREA"||l.target.isContentEditable||!!l.target.closest?.('[role="slider"]'));if(l.key==="/"&&!t){const i=__browsers[0]?.el.querySelector(".dm-cb-search-input");i&&(l.preventDefault(),i.focus(),i.select());return}if((l.key==="ArrowLeft"||l.key==="ArrowRight")&&!t){const e=__browsers.find(s=>s.el.contains(l.target))||__browsers[0];if(!e)return;const i=Math.max(1,Math.ceil(e.currentTotal/e.config.pageSize)),n=l.key==="ArrowRight"?Math.min(i,e.state.page+1):Math.max(1,e.state.page-1);n!==e.state.page&&(l.preventDefault(),e.setState({page:n}))}})}function decodePayload(l){if(!l)return null;try{const t=atob(l),e=decodeURIComponent(escape(t));return JSON.parse(e)}catch{try{return JSON.parse(atob(l))}catch{return null}}}function clear(l){l&&typeof l.replaceChildren=="function"&&l.replaceChildren()}function distinctValues(l,t){const e=new Set;for(const i of l||[]){const n=i?.data?.[t];n!=null&&(Array.isArray(n)?n.forEach(s=>s!=null&&e.add(String(s))):e.add(String(n)))}return[...e].sort()}class CollectionBrowser{constructor(t,e){this.el=t,this.config=decodePayload(t.dataset.cbConfig)||{},this.schema=decodePayload(t.dataset.cbSchema)||{fields:[]};const i=decodePayload(t.dataset.cbData)||{entries:[],total:0,page:1,pageSize:12},n=(this.config.id||`${this.config.slug}-${e}`).replace(/[^a-z0-9]/gi,"_");let s=n,a=1;for(;__browsers.some(r=>r.idScope===s);)a+=1,s=`${n}_${a}`;this.idScope=s,this.urlPrefix=`cb_${s}_`,this._fragReqId=0,this.entries=i.entries||[],this.total=i.total||0,this.state={search:"",filter:{},sort:this.config.initial?.sort||"createdAt",order:this.config.initial?.order||"desc",page:1},this.readUrlState(),this.buildSkeleton(),this.refresh()}buildSkeleton(){clear(this.el);const t=elt("div","dm-cb-header");this.config.filterable?.length&&t.appendChild(this.buildDrawerToggle()),this.config.searchable&&t.appendChild(this.buildSearchInput()),this.config.sortable&&t.appendChild(this.buildSortControl()),this.config.savedSearches!==!1&&t.appendChild(this.buildSavedSearches()),this.config.exportable&&t.appendChild(this.buildExportButton());const e=elt("div","dm-cb-layout");this.filterRail=elt("aside","dm-cb-filter-rail"),this.bodyEl=elt("div","dm-cb-body"),e.appendChild(this.filterRail),e.appendChild(this.bodyEl),this.config.filterable?.length?this.renderFilterRail():(this.filterRail.style.display="none",e.classList.add("dm-cb-layout--no-rail")),this.pagerEl=elt("div","dm-cb-pagination"),t.childElementCount&&this.el.appendChild(t),this.el.appendChild(e),this.el.appendChild(this.pagerEl),this.el.classList.add("dm-cb-hydrated")}buildSavedSearches(){const t=elt("div","dm-cb-saved"),e=elt("button","dm-cb-saved-toggle btn btn-outline");e.type="button",e.textContent="Saved \u25BE",t.appendChild(e);const i=elt("div","dm-cb-saved-menu");i.hidden=!0,t.appendChild(i);const n=()=>{clear(i);const s=this.loadSavedSearches();if(!s.length){const o=elt("p","dm-cb-saved-empty");o.textContent="No saved views yet.",i.appendChild(o)}for(const o of s){const c=elt("div","dm-cb-saved-item"),d=elt("button","dm-cb-saved-apply");d.type="button",d.textContent=o.name,d.addEventListener("click",()=>{this.state.search=o.search||"",this.state.filter={...o.filter||{}},this.state.sort=o.sort||this.config.initial?.sort||"createdAt",this.state.order=o.order||this.config.initial?.order||"desc",this.state.page=1,this.renderFilterRail();const p=this.el.querySelector(".dm-cb-search-input");p&&(p.value=this.state.search),i.hidden=!0,this.refresh()});const h=elt("button","dm-cb-saved-del");h.type="button",h.textContent="\xD7",h.title="Delete saved view",h.addEventListener("click",p=>{p.stopPropagation(),this.deleteSavedSearch(o.name),n()}),c.appendChild(d),c.appendChild(h),i.appendChild(c)}const a=elt("div","dm-cb-saved-actions"),r=elt("button","dm-cb-saved-create btn btn-primary");r.type="button",r.textContent="Save current view",r.addEventListener("click",async()=>{const o=await this.promptName();o&&(this.addSavedSearch({name:o,search:this.state.search,filter:this.state.filter,sort:this.state.sort,order:this.state.order}),n())}),a.appendChild(r),i.appendChild(a)};return e.addEventListener("click",()=>{i.hidden=!i.hidden,i.hidden||n()}),document.addEventListener("click",s=>{t.contains(s.target)||(i.hidden=!0)}),t}async promptName(){const t=typeof window<"u"&&typeof window.prompt=="function"?window.prompt("Name this saved view:"):null;return t&&t.trim()||null}loadSavedSearches(){try{const t=`cb_saved_${this.idScope}`,e=typeof S<"u"&&S.get?S.get(t):null;return Array.isArray(e)?e:[]}catch{return[]}}addSavedSearch(t){const e=this.loadSavedSearches().filter(i=>i.name!==t.name);e.push(t);try{typeof S<"u"&&S.set&&S.set(`cb_saved_${this.idScope}`,e)}catch{}}deleteSavedSearch(t){const e=this.loadSavedSearches().filter(i=>i.name!==t);try{typeof S<"u"&&S.set&&S.set(`cb_saved_${this.idScope}`,e)}catch{}}buildExportButton(){const t=elt("button","dm-cb-export btn btn-outline");return t.type="button",t.textContent="Export CSV",t.addEventListener("click",()=>this.exportCsv()),t}exportCsv(){if(this.config.mode==="client"){let n=this.entries;if(this.state.search){const o=this.state.search.toLowerCase();n=n.filter(c=>Object.values(c.data||{}).some(d=>String(d).toLowerCase().includes(o)))}const s={...this.state.filter,...this.config.baked||{}};n=applyFilterInMemory(n,s);const a=this.visibleFields(n),r=toCsv(n,a);downloadCsv(`${this.config.slug}-export.csv`,r);return}const t=new URLSearchParams;t.set("format","csv"),this.state.search&&t.set("search",this.state.search);const e={...this.state.filter,...this.config.baked||{}};for(const[n,s]of Object.entries(e))t.set(`filter[${n}]`,s);const i=`/api/collections/${encodeURIComponent(this.config.slug)}/export?${t.toString()}`;window.open(i,"_blank")}buildDrawerToggle(){const t=elt("button","dm-cb-drawer-toggle btn btn-outline");t.type="button",t.setAttribute("aria-label","Toggle filters");const e=elt("span","dm-cb-drawer-label");e.textContent="Filters";const i=elt("span","dm-cb-drawer-count");return t.appendChild(e),t.appendChild(document.createTextNode(" ")),t.appendChild(i),t.addEventListener("click",()=>{this.el.classList.toggle("dm-cb-drawer-open")}),t}buildSearchInput(){const t=elt("div","dm-cb-search"),e=elt("input","dm-cb-search-input");return e.type="search",e.placeholder="Search\u2026",e.value=this.state.search,e.addEventListener("input",debounce(()=>{this.setState({search:e.value,page:1})},200)),t.appendChild(e),t}buildSortControl(){const t=elt("div","dm-cb-sort"),e=elt("label","dm-cb-sort-label");e.textContent="Sort:",t.appendChild(e);const i=elt("select","dm-cb-sort-select"),n=this.sortableFieldList();for(const a of n){const r=elt("option");r.value=a.name,r.textContent=a.label,a.name===this.state.sort&&(r.selected=!0),i.appendChild(r)}i.addEventListener("change",()=>this.setState({sort:i.value,page:1})),t.appendChild(i);const s=elt("button","dm-cb-sort-dir");return s.type="button",s.textContent=this.state.order==="asc"?"\u2191":"\u2193",s.title=this.state.order==="asc"?"Ascending":"Descending",s.addEventListener("click",()=>{this.setState({order:this.state.order==="asc"?"desc":"asc",page:1}),s.textContent=this.state.order==="asc"?"\u2191":"\u2193"}),t.appendChild(s),t}sortableFieldList(){const t=this.config.sortableFields?.length?new Set(this.config.sortableFields):null,e=[{name:"createdAt",label:"Most recent"}];for(const i of this.schema.fields||[])t&&!t.has(i.name)||e.push({name:i.name,label:i.label||i.name});return e}renderFilterRail(){for(const i of this._sliders||[])i.destroy();this._sliders=[],clear(this.filterRail);const t=elt("h4","dm-cb-filter-heading");t.textContent="Filters",this.filterRail.appendChild(t);for(const i of this.config.filterable){const n=(this.schema.fields||[]).find(a=>a.name===i);if(!n)continue;const s=this.buildFilterControl(n);s&&this.filterRail.appendChild(s)}const e=elt("button","dm-cb-filter-reset");e.type="button",e.textContent="Clear filters",e.addEventListener("click",()=>{this.setState({filter:{},search:"",page:1}),this.renderFilterRail();const i=this.el.querySelector(".dm-cb-search-input");i&&(i.value=""),this.filterRail.querySelector(".dm-cb-filter-reset")?.focus()}),this.filterRail.appendChild(e)}buildFilterControl(t){const e=elt("div","dm-cb-filter"),i=elt("label","dm-cb-filter-label");switch(i.textContent=t.label||t.name,e.appendChild(i),t.type){case"reference":e.appendChild(this.buildReferenceFilter(t));break;case"select":case"chooser":e.appendChild(this.buildSelectControl(t,!1));break;case"multiselect":case"tags":case"tag":e.appendChild(this.buildSelectControl(t,!0));break;case"number":e.appendChild(this.buildRangeControl(t,"number"));break;case"date":case"datetime":e.appendChild(this.buildRangeControl(t,"date"));break;case"boolean":case"checkbox":e.appendChild(this.buildBooleanControl(t));break;default:e.appendChild(this.buildTextControl(t));break}return e}buildReferenceFilter(t){const e=new Map;for(const a of this.entries){const r=a._refs?.[t.name];if(!r)continue;const o=Array.isArray(r)?r:[r];for(const c of o)!c||c.missing||e.has(c.id)||e.set(c.id,c.display)}const i=`${t.name}_eq`,n=elt("select","dm-cb-select"),s=elt("option");s.value="",s.textContent=this.config.mode==="server"?"Any (loaded)":"Any",n.appendChild(s);for(const[a,r]of e){const o=elt("option");o.value=a,o.textContent=r,String(this.state.filter[i]??"")===String(a)&&(o.selected=!0),n.appendChild(o)}return n.addEventListener("change",()=>this.updateFilter(i,n.value)),n}buildTextControl(t){const e=`${t.name}_contains`,i=elt("input","dm-cb-text");return i.type="text",i.placeholder="Contains\u2026",i.value=this.state.filter[e]||"",i.addEventListener("input",debounce(()=>{this.updateFilter(e,i.value.trim())},200)),i}buildSelectControl(t,e){const i=Array.isArray(t.options)&&t.options.length?t.options.map(o=>typeof o=="object"?o:{value:o,label:o}):distinctValues(this.entries,t.name).map(o=>({value:o,label:o})),n=this.config.mode==="client"?this.facetCounts(t.name,e?"_in":"_eq",i.map(o=>o.value)):null;if(e){const o=`${t.name}_in`,c=elt("div","dm-cb-chips"),d=new Set((this.state.filter[o]||"").split(",").filter(Boolean));for(const h of i){const p=elt("button","dm-cb-chip");p.type="button",d.has(String(h.value))&&p.classList.add("dm-cb-chip-active");const f=elt("span","dm-cb-chip-label");if(f.textContent=h.label??h.value,p.appendChild(f),n){const u=elt("span","dm-cb-chip-count");u.textContent=n[String(h.value)]??0,p.appendChild(u)}p.addEventListener("click",()=>{d.has(String(h.value))?d.delete(String(h.value)):d.add(String(h.value)),this.updateFilter(o,d.size?[...d].join(","):"")}),c.appendChild(p)}return c}const s=`${t.name}_eq`,a=elt("select","dm-cb-select"),r=elt("option");r.value="",r.textContent="Any",a.appendChild(r);for(const o of i){const c=elt("option");c.value=o.value;const d=n?` (${n[String(o.value)]??0})`:"";c.textContent=(o.label??o.value)+d,String(this.state.filter[s]??"")===String(o.value)&&(c.selected=!0),a.appendChild(c)}return a.addEventListener("change",()=>this.updateFilter(s,a.value)),a}facetCounts(t,e,i){const n={};for(const[o,c]of Object.entries(this.state.filter||{})){const{field:d}=parseFilterKey(o);d!==t&&(n[o]=c)}let s=this.entries;if(this.state.search){const o=this.state.search.toLowerCase();s=s.filter(c=>Object.values(c.data||{}).some(d=>String(d).toLowerCase().includes(o)))}const a={...n,...this.config.baked||{}};s=applyFilterInMemory(s,a);const r={};for(const o of i){const c={...a,[`${t}${e}`]:String(o)};r[String(o)]=applyFilterInMemory(s,c).length}return r}buildRangeControl(t,e){const i=`${t.name}_gte`,n=`${t.name}_lte`,s=elt("div","dm-cb-range"),a=elt("div","dm-cb-range-inputs"),r=elt("input","dm-cb-range-min"),o=elt("input","dm-cb-range-max");r.type=e,o.type=e,r.placeholder="Min",o.placeholder="Max",r.value=this.state.filter[i]||"",o.value=this.state.filter[n]||"",a.appendChild(r),a.appendChild(document.createTextNode(" - ")),a.appendChild(o),s.appendChild(a);let c=null,d=null,h=null;const p=window.DommaCollectionRange;if(e==="number"&&this.config.mode==="client"&&this.entries.length&&p&&typeof E<"u"&&E.rangeSlider&&(d=p.rangeBounds(this.entries.map(u=>u.data?.[t.name]))),d){const u=elt("div","dm-cb-slider");s.appendChild(u);const g=t.label||t.name,m=b=>{const C=p.rangeFilter(d,b);(!h||b[0]!==h[0])&&(r.value=C.gte),(!h||b[1]!==h[1])&&(o.value=C.lte)};c=E.rangeSlider(u,{range:!0,min:d.min,max:d.max,step:d.step,value:p.sliderValue(d,r.value,o.value),labels:p.rangeLabel(t,d.step),ariaLabels:[`${g} from`,`${g} to`],onInput:m,onChange:b=>{m(b),h=b.slice(),this.updateFilter(i,r.value,!0),this.updateFilter(n,o.value)}}),h=c.getValue().slice(),this._sliders.push(c)}const f=debounce(()=>{this.updateFilter(i,r.value,!0),this.updateFilter(n,o.value),c&&(c.setValue(p.sliderValue(d,r.value,o.value),{silent:!0}),h=c.getValue().slice())},250);return r.addEventListener("input",f),o.addEventListener("input",f),s}buildBooleanControl(t){const e=`${t.name}_eq`,i=elt("select","dm-cb-select");for(const[n,s]of[["","Any"],["true","Yes"],["false","No"]]){const a=elt("option");a.value=n,a.textContent=s,String(this.state.filter[e]??"")===n&&(a.selected=!0),i.appendChild(a)}return i.addEventListener("change",()=>this.updateFilter(e,i.value)),i}updateFilter(t,e,i=!1){const n={...this.state.filter};e===""||e==null?delete n[t]:n[t]=e,this.state.filter=n,this.state.page=1,i||this.refresh()}setState(t){Object.assign(this.state,t),this.refresh()}async refresh(){this.config.syncUrl&&this.writeUrlState(),this.config.mode==="server"&&await this.fetchPage(),this.renderBody(),this.renderPagination(),this.updateFacetCounts(),this.updateDrawerBadge()}updateFacetCounts(){if(this.config.mode==="client"&&this.filterRail)for(const t of this.config.filterable||[]){const e=(this.schema.fields||[]).find(r=>r.name===t);if(!e)continue;const i=e.type==="multiselect"||e.type==="tags"||e.type==="tag"?"_in":"_eq",n=Array.isArray(e.options)&&e.options.length?e.options.map(r=>typeof r=="object"?r:{value:r,label:r}):distinctValues(this.entries,t).map(r=>({value:r,label:r})),s=this.facetCounts(t,i,n.map(r=>r.value)),a=this.filterRail.querySelectorAll(".dm-cb-filter");for(const r of a){const o=r.querySelector(".dm-cb-filter-label");if(!o||o.textContent!==(e.label||e.name))continue;r.querySelectorAll(".dm-cb-chip").forEach((h,p)=>{const f=h.querySelector(".dm-cb-chip-count");f&&n[p]&&(f.textContent=s[String(n[p].value)]??0)});const d=r.querySelector("select.dm-cb-select");d&&Array.from(d.options).forEach(h=>{if(!h.value)return;const p=n.find(f=>String(f.value)===h.value)?.label??h.value;h.textContent=`${p} (${s[h.value]??0})`})}}}updateDrawerBadge(){const t=this.el.querySelector(".dm-cb-drawer-toggle");if(!t)return;const e=(this.state.search?1:0)+Object.keys(this.state.filter||{}).length,i=t.querySelector(".dm-cb-drawer-count");i&&(i.textContent=e>0?`(${e})`:"")}async fetchPage(){const t={...this.state.filter,...this.config.baked||{}},e=new URLSearchParams;e.set("page",this.state.page),e.set("limit",this.config.pageSize),e.set("sort",this.state.sort),e.set("order",this.state.order),this.state.search&&e.set("search",this.state.search);for(const[n,s]of Object.entries(t))e.set(`filter[${n}]`,s);this.config.scope==="mine"&&e.set("scope","mine"),this._fetchAbort&&this._fetchAbort.abort(),this._fetchAbort=new AbortController;const i=this.config.sourceKind==="view"?`/api/views/${encodeURIComponent(this.config.slug)}/public?${e.toString()}`:`/api/collections/${encodeURIComponent(this.config.slug)}/public?${e.toString()}`;try{const n=await fetch(i,{headers:this.authHeaders(),signal:this._fetchAbort.signal});if(!n.ok){this.entries=[],this.total=0;return}const s=await n.json(),a=s.entries||s.results||[];this.entries=a.map(r=>r.data?r:{id:r.id||"",data:r.data||r}),this.total=s.total||a.length}catch(n){if(n.name==="AbortError")return;this.entries=[],this.total=0}}authHeaders(){try{const t=typeof S<"u"&&S.get?S.get("auth_token"):null;return t?{Authorization:`Bearer ${t}`}:{}}catch{return{}}}pipeline(){if(this.config.mode==="server")return{visible:this.entries,total:this.total};let t=this.entries,e=null;if(this.state.search){const c=this.state.search.toLowerCase();e=new Map,t=t.filter(d=>{let h=0;for(const[p,f]of Object.entries(d.data||{})){if(f==null)continue;const u=String(f).toLowerCase();let g=0,m=0;for(;(g=u.indexOf(c,g))!==-1;)m++,g+=c.length;m>0&&(h+=m*(p===this.config.titleField?3:1))}return h>0&&e.set(d.id||d,h),h>0})}if(Object.keys(this.state.filter).length||Object.keys(this.config.baked||{}).length){const c={...this.state.filter,...this.config.baked||{}};t=applyFilterInMemory(t,c)}const i=this.config.initial?.sort||"createdAt",n=this.config.initial?.order||"desc",s=this.state.sort===i&&this.state.order===n;this.state.search&&e&&s?(t=[...t].sort((c,d)=>{const h=e.get(c.id||c)||0;return(e.get(d.id||d)||0)-h}),this._activeSortMode="relevance"):(t=sortEntries(t,this.state.sort,this.state.order),this._activeSortMode=null);const a=t.length,r=(this.state.page-1)*this.config.pageSize;return{visible:t.slice(r,r+this.config.pageSize),total:a}}renderBody(){const{visible:t,total:e}=this.pipeline();if(this.currentTotal=e,clear(this.bodyEl),!t.length){this.bodyEl.appendChild(this.buildEmptyState());return}const i=this.visibleFields(t);this.bodyEl.appendChild(this.renderForDisplay(t,i)),typeof Domma<"u"&&Domma.icons?.scan&&Domma.icons.scan(this.bodyEl),this.config.cta&&typeof wireCTAButtons=="function"&&wireCTAButtons(this.bodyEl)}buildEmptyState(){const t=elt("div","dm-collection-display dm-collection-empty"),e=!!this.state.search||Object.keys(this.state.filter||{}).length>0,i=elt("p");if(e){i.textContent="No results for these filters.",t.appendChild(i);const n=elt("button","btn btn-outline dm-cb-empty-clear");n.type="button",n.textContent="Clear filters",n.addEventListener("click",()=>{this.setState({filter:{},search:"",page:1}),this.renderFilterRail();const s=this.el.querySelector(".dm-cb-search-input");s&&(s.value="")}),t.appendChild(n)}else i.textContent=this.config.emptyMsg,t.appendChild(i);return t}visibleFields(t){let e=this.schema.fields||[];return this.config.fields?.length&&(e=this.config.fields.map(i=>e.find(n=>n.name===i)||{name:i,label:i})),!e.length&&t.length&&(e=Object.keys(t[0].data||{}).map(i=>({name:i,label:i}))),e}renderCards(t,e){const i=elt("div",`dm-collection-cards grid grid-cols-${this.config.columns}`);for(const n of t){const s=elt("div","card dm-collection-card"),a=e.find(c=>c.name===this.config.titleField),r=a?fieldDisplay(n,a):this.config.titleField?formatValue(n.data?.[this.config.titleField]):"";if(r){const c=elt("div","card-header");c.textContent=r,s.appendChild(c)}const o=elt("div","card-body");for(const c of e){if(this.config.titleField===c.name||!fieldDisplay(n,c))continue;const h=elt("div","dm-collection-card-field"),p=elt("strong");p.textContent=(c.label||c.name)+": ",h.appendChild(p),h.appendChild(fieldDisplayNode(n,c)),o.appendChild(h)}this.config.cta&&o.appendChild(this.buildCtaButton(n)),this.config.transitions&&o.appendChild(this.buildTransitionsGroup(n)),s.appendChild(o),i.appendChild(s)}return i}renderList(t,e){const i=elt("ul","dm-collection-list");for(const n of t){const s=elt("li","dm-collection-list-item"),a=e.find(c=>c.name===this.config.titleField),r=a?fieldDisplay(n,a):this.config.titleField?formatValue(n.data?.[this.config.titleField]):"";if(r){const c=elt("div","dm-collection-list-title");c.textContent=r,s.appendChild(c)}const o=e.filter(c=>c.name!==this.config.titleField).map(c=>{const d=fieldDisplay(n,c);return d?`${c.label||c.name}: ${d}`:""}).filter(Boolean).join(" \xB7 ");if(o){const c=elt("div","dm-collection-list-meta");c.textContent=o,s.appendChild(c)}this.config.cta&&s.appendChild(this.buildCtaButton(n)),this.config.transitions&&s.appendChild(this.buildTransitionsGroup(n)),i.appendChild(s)}return i}renderTable(t,e){const i=elt("table","dm-collection-table"),n=elt("thead"),s=elt("tr");for(const r of e){const o=elt("th");o.textContent=r.label||r.name,s.appendChild(o)}this.config.cta&&s.appendChild(elt("th")),this.config.transitions&&s.appendChild(elt("th")),n.appendChild(s),i.appendChild(n);const a=elt("tbody");for(const r of t){const o=elt("tr");for(const c of e){const d=elt("td");d.appendChild(fieldDisplayNode(r,c)),o.appendChild(d)}if(this.config.cta){const c=elt("td");c.appendChild(this.buildCtaButton(r)),o.appendChild(c)}if(this.config.transitions){const c=elt("td");c.appendChild(this.buildTransitionsGroup(r)),o.appendChild(c)}a.appendChild(o)}return i.appendChild(a),i}renderAccordion(t){const e=elt("div","accordion dm-collection-accordion");for(const i of t){const n=elt("div","accordion-item"),s=this.config.titleField&&i.data?.[this.config.titleField]||"Untitled",a=this.config.bodyField&&i.data?.[this.config.bodyField]||"",r=elt("button","accordion-header");r.type="button",r.textContent=String(s);const o=elt("div","accordion-panel");o.textContent=String(a),r.addEventListener("click",()=>n.classList.toggle("open")),n.appendChild(r),n.appendChild(o),e.appendChild(n)}return e}buildCtaButton(t){const e=this.config.cta,i=elt("button",`btn btn-${e.style||"primary"} dm-cta-trigger`);if(i.dataset.action=e.action,i.dataset.entry=t.id||"",this.config.scope&&(i.dataset.scope=this.config.scope),e.confirm&&(i.dataset.confirm=e.confirm),e.icon){const n=elt("span");n.dataset.icon=e.icon,i.appendChild(n),i.appendChild(document.createTextNode(" "))}return i.appendChild(document.createTextNode(e.label||"Run")),i}buildTransitionsGroup(t){const e=elt("div","dm-cb-transitions");return e.dataset.entry=t.id||"",e.textContent="Loading actions\u2026",Promise.resolve().then(()=>this.loadTransitions(t,e)),e}async loadTransitions(t,e){try{const i=new URLSearchParams({collection:this.config.slug,entryId:t.id||""});this.config.scope==="mine"&&i.set("scope","mine");const n=await fetch(`/api/actions/transitions?${i.toString()}`,{headers:this.authHeaders()});if(clear(e),!n.ok)return;const{transitions:s}=await n.json();if(!Array.isArray(s)||!s.length)return;for(const a of s){const r=elt("button",`btn btn-${a.trigger?.style||"outline"} dm-cb-transition-btn dm-cta-trigger`);if(r.dataset.action=a.slug,r.dataset.entry=t.id||"",this.config.scope&&(r.dataset.scope=this.config.scope),a.trigger?.confirmMessage&&(r.dataset.confirm=a.trigger.confirmMessage),a.trigger?.icon){const o=elt("span");o.dataset.icon=a.trigger.icon,r.appendChild(o),r.appendChild(document.createTextNode(" "))}r.appendChild(document.createTextNode(a.trigger?.label||a.title)),e.appendChild(r)}typeof Domma<"u"&&Domma.icons?.scan&&Domma.icons.scan(e),typeof wireCTAButtons=="function"&&wireCTAButtons(e)}catch{clear(e)}}renderPagination(){if(this.config.pagination==="scroll"){this.renderInfiniteSentinel();return}const t=Math.max(1,Math.ceil(this.currentTotal/this.config.pageSize));if(clear(this.pagerEl),t<=1)return;const e=elt("button","dm-cb-page-prev btn btn-outline");e.type="button",e.textContent="\u2039 Prev",e.disabled=this.state.page<=1,e.addEventListener("click",()=>this.setState({page:Math.max(1,this.state.page-1)}));const i=elt("button","dm-cb-page-next btn btn-outline");i.type="button",i.textContent="Next \u203A",i.disabled=this.state.page>=t,i.addEventListener("click",()=>this.setState({page:Math.min(t,this.state.page+1)}));const n=elt("span","dm-cb-page-info");n.textContent=`Page ${this.state.page} of ${t} (${this.currentTotal} entr${this.currentTotal===1?"y":"ies"})`,this.pagerEl.appendChild(e),this.pagerEl.appendChild(n),this.pagerEl.appendChild(i)}renderInfiniteSentinel(){clear(this.pagerEl);const t=Math.max(1,Math.ceil(this.currentTotal/this.config.pageSize));if(this.state.page>=t){const i=elt("p","dm-cb-scroll-end");i.textContent=`All ${this.currentTotal} entries loaded.`,this.pagerEl.appendChild(i);return}const e=elt("div","dm-cb-scroll-sentinel");e.setAttribute("aria-hidden","true"),e.textContent="Loading more\u2026",this.pagerEl.appendChild(e),this._scrollObserver&&this._scrollObserver.disconnect(),this._scrollObserver=new IntersectionObserver(async i=>{i[0].isIntersecting&&(this._scrollObserver.disconnect(),await this.loadMore())},{rootMargin:"200px 0px"}),this._scrollObserver.observe(e)}async loadMore(){const t=this.state.page+1,e=this.currentTotal,i=this.entries,n=this.state.page;this.state.page=t,this.config.syncUrl&&this.writeUrlState();let s;if(this.config.mode==="server")await this.fetchPage(),s=this.entries;else{const{visible:c}=this.pipeline();s=c}if(!s.length){this.state.page=n,this.entries=i,this.currentTotal=e,this.renderPagination();return}const a=this.visibleFields(s),r=this.renderForDisplay(s,a),o=this.bodyEl.firstElementChild;if(o&&o.tagName===r.tagName)for(;r.firstChild;)o.appendChild(r.firstChild);else this.bodyEl.appendChild(r);typeof Domma<"u"&&Domma.icons?.scan&&Domma.icons.scan(this.bodyEl),this.config.cta&&typeof wireCTAButtons=="function"&&wireCTAButtons(this.bodyEl),this.renderPagination()}renderForDisplay(t,e){const i=this.config.display;return i==="list"?this.renderList(t,e):i==="table"?this.renderTable(t,e):i==="accordion"?this.renderAccordion(t):i==="timeline"?this.renderTimeline(t):i==="block"?this.renderBlockPlaceholder(t):this.renderCards(t,e)}renderTimeline(t){const e=["vertical","centred","horizontal"].includes(this.config.layout)?this.config.layout:"vertical",i=["minimal","corporate","modern"].includes(this.config.theme)?this.config.theme:"minimal",n=elt("div",`dm-collection-timeline timeline timeline-${e} timeline-${i}`);for(const s of t){const a=elt("div","timeline-event"),r=this.config.dateField&&s.data?.[this.config.dateField]||"",o=this.config.titleField&&s.data?.[this.config.titleField]||"",c=this.config.bodyField&&s.data?.[this.config.bodyField]||"",d=this.config.statusField&&s.data?.[this.config.statusField]||"",h=this.config.iconField&&s.data?.[this.config.iconField]||"";if(h){const p=elt("span","timeline-icon");p.dataset.icon=String(h),a.appendChild(p)}if(r){const p=elt("div","timeline-date");p.textContent=String(r),a.appendChild(p)}if(o){const p=elt("h4","timeline-title");p.textContent=String(o),a.appendChild(p)}if(d){const p=elt("span",`badge badge-${d}`);p.textContent=String(d),a.appendChild(p)}if(c){const p=elt("div","timeline-body");p.textContent=String(c),a.appendChild(p)}n.appendChild(a)}return n}renderBlockPlaceholder(t){const e=elt("div","dm-collection-display dm-cb-block-loading");return e.textContent="Rendering\u2026",this.fetchBlockFragment(t,e),e}async fetchBlockFragment(t,e){const i=++this._fragReqId,n=t.map(r=>r.id).filter(Boolean),s={slug:this.config.slug,display:"block",block:this.config.block,"title-field":this.config.titleField,"body-field":this.config.bodyField,fields:this.config.fields?this.config.fields.join(","):"",empty:this.config.emptyMsg,limit:String(n.length||1)},a={...this.state.filter,...this.config.baked||{}};for(const[r,o]of Object.entries(a))o!==""&&o!=null&&(s[`where_${r}`]=String(o));s.sort=this.state.sort,s.order=this.state.order,s.limit=String(this.config.pageSize);try{const r=btoa(unescape(encodeURIComponent(JSON.stringify(s)))),o=this.config.scope==="mine"?"/api/collections/render-scope":"/api/collections/render-fragment",c=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",...this.authHeaders()},body:JSON.stringify({attrs:r,page:this.state.page})});if(i!==this._fragReqId)return;if(!c.ok){e.textContent=this.config.emptyMsg;return}const{html:d}=await c.json(),h=document.createElement("template");h.innerHTML=d||"",e.replaceWith(h.content)}catch{e.textContent="Unable to load block view."}}readUrlState(){if(!this.config.syncUrl)return;const t=new URLSearchParams(window.location.search),e=this.urlPrefix,i=a=>t.get(e+a);i("search")&&(this.state.search=i("search")),i("sort")&&(this.state.sort=i("sort")),i("order")&&(this.state.order=i("order")),i("page")&&(this.state.page=parseInt(i("page"),10)||1);const n={},s=`${e}filter[`;for(const[a,r]of t.entries())if(a.startsWith(s)&&a.endsWith("]")){const o=a.slice(s.length,-1);o&&(n[o]=r)}Object.keys(n).length&&(this.state.filter=n)}writeUrlState(){const t=new URL(window.location.href),e=this.urlPrefix,i=[];for(const s of t.searchParams.keys())s.startsWith(e)&&i.push(s);i.forEach(s=>t.searchParams.delete(s));const n=(s,a)=>{a!==""&&a!=null&&t.searchParams.set(e+s,a)};n("search",this.state.search),this.state.sort!==(this.config.initial?.sort||"createdAt")&&n("sort",this.state.sort),this.state.order!==(this.config.initial?.order||"desc")&&n("order",this.state.order),this.state.page!==1&&n("page",this.state.page);for(const[s,a]of Object.entries(this.state.filter))a!==""&&a!=null&&t.searchParams.set(`${e}filter[${s}]`,a);try{window.history.replaceState({},"",t.toString())}catch{}}}const OPERATORS=["_eq","_ne","_gte","_lte","_gt","_lt","_in","_nin","_contains","_starts","_ends","_exists"];function parseFilterKey(l){for(const t of OPERATORS)if(l.endsWith(t))return{field:l.slice(0,-t.length),op:t};return{field:l,op:"_eq"}}function resolveField(l,t){if(t==="createdBy")return l.meta?.createdBy;if(t==="id")return l.id;const e=t.split(".");let i=l.data;for(const n of e){if(i==null)return;i=i[n]}return i}function maybeNumber(l){if(typeof l=="number"||typeof l!="string")return l;const t=Number(l);return Number.isFinite(t)&&String(t)===l.trim()?t:l}function applyOp(l,t,e){switch(l){case"_eq":{const i=maybeNumber(t),n=maybeNumber(e);return Array.isArray(t)?t.map(maybeNumber).includes(n):i===n||String(i)===String(n)}case"_ne":{const i=maybeNumber(t),n=maybeNumber(e);return Array.isArray(t)?!t.map(maybeNumber).includes(n):!(i===n||String(i)===String(n))}case"_gt":return maybeNumber(t)>maybeNumber(e);case"_gte":return maybeNumber(t)>=maybeNumber(e);case"_lt":return maybeNumber(t)<maybeNumber(e);case"_lte":return maybeNumber(t)<=maybeNumber(e);case"_in":{const i=String(e).split(",").map(n=>maybeNumber(n.trim()));return Array.isArray(t)?t.map(maybeNumber).some(n=>i.includes(n)):i.includes(maybeNumber(t))}case"_nin":{const i=String(e).split(",").map(n=>maybeNumber(n.trim()));return Array.isArray(t)?!t.map(maybeNumber).some(n=>i.includes(n)):!i.includes(maybeNumber(t))}case"_contains":return String(t??"").toLowerCase().includes(String(e).toLowerCase());case"_starts":return String(t??"").toLowerCase().startsWith(String(e).toLowerCase());case"_ends":return String(t??"").toLowerCase().endsWith(String(e).toLowerCase());case"_exists":{const i=t!=null&&t!=="";return e==="true"||e==="1"||e===!0?i:!i}default:return!1}}function applyFilterInMemory(l,t){return!t||!Object.keys(t).length?l:l.filter(e=>{for(const[i,n]of Object.entries(t)){if(n==null||n==="")continue;const{field:s,op:a}=parseFilterKey(i),r=resolveField(e,s);if(!applyOp(a,r,n))return!1}return!0})}function sortEntries(l,t,e){const i=e==="asc"?1:-1;return[...l].sort((n,s)=>{const a=t==="createdAt"?n.meta?.createdAt||"":n.data?.[t]??"",r=t==="createdAt"?s.meta?.createdAt||"":s.data?.[t]??"";return a<r?-i:a>r?i:0})}function elt(l,t){const e=document.createElement(l);return t&&(e.className=t),e}function isFileRef(l){return l&&typeof l=="object"&&typeof l.url=="string"&&typeof l.name=="string"}function formatValue(l){return l==null?"":isFileRef(l)?l.name:Array.isArray(l)?l.join(", "):typeof l=="boolean"?l?"Yes":"No":String(l)}function fieldDisplay(l,t){if(t?.type==="reference"){const e=l?._refs?.[t.name];if(e!=null)return Array.isArray(e)?e.map(i=>i.missing?`${i.id} (missing)`:i.display).join(", "):e.missing?`${e.id} (missing)`:e.display}return formatValue(l?.data?.[t?.name])}function fieldDisplayNode(l,t){if(t?.type==="reference"){const i=l?._refs?.[t.name];if(i!=null){const n=document.createDocumentFragment();return(Array.isArray(i)?i:[i]).forEach((a,r)=>{if(r>0&&n.appendChild(document.createTextNode(", ")),a.missing)n.appendChild(document.createTextNode(`${a.id} (missing)`));else if(a.link){const o=document.createElement("a");o.href=a.link,o.textContent=a.display,n.appendChild(o)}else n.appendChild(document.createTextNode(a.display))}),n}}const e=l?.data?.[t?.name];if(isFileRef(e)){const i=document.createElement("a");if(i.href=e.url,String(e.mime||"").startsWith("image/")){i.target="_blank",i.rel="noopener";const n=document.createElement("img");n.src=e.url,n.alt=e.name,n.loading="lazy",n.className="dm-file-thumb",i.appendChild(n)}else i.download="",i.textContent=e.name;return i}return document.createTextNode(formatValue(e))}function debounce(l,t){let e;return(...i)=>{clearTimeout(e),e=setTimeout(()=>l(...i),t)}}function toCsv(l,t){const e=s=>{if(s==null)return"";let a=Array.isArray(s)?s.join(", "):String(s);return/[",\n\r]/.test(a)&&(a='"'+a.replace(/"/g,'""')+'"'),a},i=t.map(s=>e(s.label||s.name)).join(","),n=l.map(s=>t.map(a=>e(s.data?.[a.name])).join(",")).join(`
2
2
  `);return i+`
3
3
  `+n+`
4
4
  `}function downloadCsv(l,t){const e=new Blob([t],{type:"text/csv;charset=utf-8"}),i=URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download=l,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(i),1e3)}window.DommaCollectionBrowser={hydrate:bootstrapCollectionBrowsers},bootstrapCollectionBrowsers();
@@ -15,6 +15,7 @@ import fs from 'fs/promises';
15
15
  import path from 'path';
16
16
  import {authenticate, requirePermission} from '../../middleware/auth.js';
17
17
  import {deleteBlock, getBlock, listBlocks, saveBlock} from '../../services/blocks.js';
18
+ import {keepManualTags} from '../../services/listTags.js';
18
19
  import {config, getConfig} from '../../config.js';
19
20
  import {fmtDate} from '../../services/dates.js';
20
21
  import {BUILTIN_SHORTCODES} from '../../services/markdown.js';
@@ -343,7 +344,17 @@ export async function blocksRoutes(fastify) {
343
344
  if (css !== undefined && typeof css !== 'string') return reply.status(400).send({error: 'css must be a string'});
344
345
 
345
346
  try {
346
- return await saveBlock(name, content, {bundled: !!bundled, css, meta, createOnly: createOnly === true});
347
+ // Which Tool owns a block is the Tool's to say, never an editor save's: the stored owner is kept
348
+ // (a save that sent no meta used to drop it) and one sent from here is ignored. Manual tags may
349
+ // not take a Tool's name (services/listTags.js).
350
+ const stored = (await getBlock(name).catch(() => null))?.meta || {};
351
+ let safeMeta = meta && typeof meta === 'object' && !Array.isArray(meta) ? {...meta} : undefined;
352
+ if (safeMeta) {
353
+ delete safeMeta.plugin;
354
+ if (Array.isArray(safeMeta.adminTags)) safeMeta.adminTags = await keepManualTags('blocks', safeMeta.adminTags, stored.adminTags);
355
+ }
356
+ if (stored.plugin) safeMeta = {...(safeMeta || {}), plugin: stored.plugin};
357
+ return await saveBlock(name, content, {bundled: !!bundled, css, meta: safeMeta, createOnly: createOnly === true});
347
358
  } catch (err) {
348
359
  if (err.code === 'INVALID_NAME') return reply.status(400).send({error: err.message});
349
360
  if (err.code === 'CSS_TOO_LARGE') return reply.status(400).send({error: err.message});
@@ -348,14 +348,22 @@ export async function collectionsRoutes(fastify) {
348
348
 
349
349
  fastify.get('/collections', canRead, async (request) => {
350
350
  const {canSeeArtefact} = await import('../../services/projects.js');
351
+ const {collectionTagMap} = await import('../../services/listTags.js');
351
352
  const all = await listCollections();
353
+ // Admin-only list tags live in config/list-tags.json, not in schema.json.
354
+ const tagMap = collectionTagMap();
352
355
  const filtered = [];
353
356
  for (const c of all) {
354
357
  // listCollections returns metadata only; getCollection returns full record with meta
355
358
  const full = await getCollection(c.slug);
359
+ if (!canSeeArtefact(request.user, full)) continue;
356
360
  // builtIn: the ones DELETE refuses (seeding turns `preset` into `bundled`, which
357
361
  // also covers deletable seeded collections - so the list says which is which).
358
- if (canSeeArtefact(request.user, full)) filtered.push(ALL_PRESET_SLUGS.has(c.slug) ? {...c, builtIn: true} : c);
362
+ filtered.push({
363
+ ...c,
364
+ ...(ALL_PRESET_SLUGS.has(c.slug) && {builtIn: true}),
365
+ adminTags: Object.hasOwn(tagMap, c.slug) ? tagMap[c.slug] : []
366
+ });
359
367
  }
360
368
  return filtered;
361
369
  });
@@ -1,27 +1,33 @@
1
1
  /**
2
- * List tags - admin-only labels on pages and blocks (services/listTags.js).
2
+ * List tags - admin-only labels on pages, blocks and collections (services/listTags.js).
3
3
  *
4
- * GET /api/list-tags/:kind - {tags: [{name, count}]}
4
+ * GET /api/list-tags/:kind - {tags: [{name, count, tool?}], tools: {slug: displayName}}
5
5
  * POST /api/list-tags/:kind - {name}: create a tag
6
6
  * PUT /api/list-tags/:kind/item - {id, tags} replaces one item's tags; {id, add, remove} patches them
7
7
  * POST /api/list-tags/:kind/rename - {from, to}
8
8
  * POST /api/list-tags/:kind/delete - {name}: take it off every item
9
9
  *
10
- * :kind is `pages` or `blocks`; both sit under the pages permission, as the
11
- * blocks routes do. Names travel in bodies, not paths, so any spelling works.
12
- * Every change is limited to the items the caller's projects let them see.
10
+ * :kind is `pages`, `blocks` or `collections`. Pages and blocks sit under the
11
+ * pages permission, as the blocks routes do; collections under the
12
+ * collections permission (read to list, update to change). Names travel in
13
+ * bodies, not paths, so any spelling works. Every change is limited to the
14
+ * items the caller's projects let them see.
15
+ *
16
+ * Tool tags (`tool: true`) are derived from who owns each item and never
17
+ * stored; `tools` names every known Tool so the client can label an item's.
13
18
  */
14
19
  import {authenticate, requirePermission} from '../../middleware/auth.js';
15
- import {addTag, changeItemTags, deleteTag, listTags, renameTag} from '../../services/listTags.js';
20
+ import {addTag, changeItemTags, deleteTag, KINDS, listTags, renameTag, toolNames} from '../../services/listTags.js';
16
21
  import {canSeeArtefact, canSeePage} from '../../services/projects.js';
17
22
  import {getBlock} from '../../services/blocks.js';
23
+ import {getCollection} from '../../services/collections.js';
18
24
  import {getPage} from '../../services/content.js';
19
25
 
20
26
  /** Visibility of one item from what the listers return. */
21
27
  function visibleTo(user, kind) {
22
28
  return kind === 'pages'
23
29
  ? (p) => canSeeArtefact(user, {meta: {project: p.resolvedProject}})
24
- : (b) => canSeeArtefact(user, b);
30
+ : (item) => canSeeArtefact(user, item);
25
31
  }
26
32
 
27
33
  function fail(reply, err) {
@@ -31,13 +37,28 @@ function fail(reply, err) {
31
37
  throw err;
32
38
  }
33
39
 
40
+ /** The permission resource a kind sits under. */
41
+ const resourceOf = (kind) => (kind === 'collections' ? 'collections' : 'pages');
42
+
43
+ /** A preHandler checking the kind's own permission (the kind is a route param). */
44
+ function kindPermission(action) {
45
+ const guards = Object.fromEntries(KINDS.map(k => [k, requirePermission(resourceOf(k), action)]));
46
+ return async (request, reply) => {
47
+ const guard = guards[request.params.kind];
48
+ if (!guard) return reply.status(404).send({error: `Unknown kind "${request.params.kind}"`});
49
+ return guard(request, reply);
50
+ };
51
+ }
52
+
34
53
  export async function listTagsRoutes(fastify) {
35
- const canRead = {preHandler: [authenticate, requirePermission('pages', 'read')]};
36
- const canUpdate = {preHandler: [authenticate, requirePermission('pages', 'update')]};
54
+ const canRead = {preHandler: [authenticate, kindPermission('read')]};
55
+ const canUpdate = {preHandler: [authenticate, kindPermission('update')]};
37
56
 
38
57
  fastify.get('/list-tags/:kind', canRead, async (request, reply) => {
39
58
  try {
40
- return {tags: await listTags(request.params.kind, visibleTo(request.user, request.params.kind))};
59
+ const {kind} = request.params;
60
+ const [tags, tools] = await Promise.all([listTags(kind, visibleTo(request.user, kind)), toolNames()]);
61
+ return {tags, tools};
41
62
  } catch (err) { return fail(reply, err); }
42
63
  });
43
64
 
@@ -62,6 +83,10 @@ export async function listTagsRoutes(fastify) {
62
83
  const block = await getBlock(id).catch(() => null);
63
84
  if (!block) return reply.status(404).send({error: 'Block not found'});
64
85
  if (!canSeeArtefact(request.user, block)) return reply.status(403).send({error: 'Access denied for this project'});
86
+ } else if (kind === 'collections') {
87
+ const schema = await getCollection(id).catch(() => null);
88
+ if (!schema) return reply.status(404).send({error: 'Collection not found'});
89
+ if (!canSeeArtefact(request.user, schema)) return reply.status(403).send({error: 'Access denied for this project'});
65
90
  }
66
91
  return {tags: await changeItemTags(kind, id, Array.isArray(tags) ? {tags} : {add, remove})};
67
92
  } catch (err) { return fail(reply, err); }
@@ -26,6 +26,19 @@ import {
26
26
  import {getVersionCount, versionAuthor} from '../../services/versions.js';
27
27
  import {authenticate, requirePermission} from '../../middleware/auth.js';
28
28
  import {canSeeArtefact, canSeePage} from '../../services/projects.js';
29
+ import {keepManualTags} from '../../services/listTags.js';
30
+
31
+ /**
32
+ * A page save from the editor: which Tool owns the page (frontmatter `plugin`) is never set or changed
33
+ * here - the stored owner stays - and manual list tags may not take a Tool's name (services/listTags.js).
34
+ */
35
+ async function guardOwnerAndTags(frontmatter, existing) {
36
+ if (!frontmatter || typeof frontmatter !== 'object') return frontmatter;
37
+ const out = {...frontmatter};
38
+ if (existing?.plugin) out.plugin = existing.plugin; else delete out.plugin;
39
+ if (Array.isArray(out.adminTags)) out.adminTags = await keepManualTags('pages', out.adminTags, existing?.adminTags || []);
40
+ return out;
41
+ }
29
42
  import {getConfig, saveConfig} from '../../config.js';
30
43
  import {relinkItems, relinkMenus} from '../../services/menus.js';
31
44
  import {imageHostRoutes} from './image-hosts.js';
@@ -244,17 +257,18 @@ export async function pagesRoutes(fastify) {
244
257
  }
245
258
 
246
259
  if (!(await canSeePage(request.user, urlPath, frontmatter?.project))) return denied(reply);
247
- const page = await createPage(urlPath, frontmatter || {}, body || '');
260
+ const page = await createPage(urlPath, (await guardOwnerAndTags(frontmatter || {}, null)), body || '');
248
261
  return reply.status(201).send(page);
249
262
  });
250
263
 
251
264
  // Update page (optionally rename to a new URL path)
252
265
  fastify.put('/pages/*', canUpdate, async (request, reply) => {
253
266
  const urlPath = '/' + request.params['*'];
254
- const { frontmatter, body, newUrlPath } = request.body;
267
+ const { body, newUrlPath } = request.body;
255
268
 
256
269
  const existing = await getPage(urlPath);
257
270
  if (!existing) return reply.status(404).send({ error: 'Page not found' });
271
+ const frontmatter = await guardOwnerAndTags(request.body?.frontmatter, existing);
258
272
  if (!(await canSeePage(request.user, urlPath, existing.project))) return denied(reply);
259
273
  // Nor may a save move the page into a project outside the user's scope.
260
274
  const project = frontmatter && 'project' in frontmatter ? frontmatter.project : existing.project;
@@ -247,6 +247,12 @@ export async function deleteCollection(slug) {
247
247
  invalidate(slug);
248
248
  await fs.rm(collectionDir(slug), { recursive: true, force: true });
249
249
  await cache.invalidateTags([`collection:${slug}`]);
250
+ // Its admin list tags live in config/list-tags.json, not in the folder just
251
+ // removed. Imported here, not at the top: listTags imports this module.
252
+ try {
253
+ const {dropCollectionTags} = await import('./listTags.js');
254
+ await dropCollectionTags(slug);
255
+ } catch { /* a stale entry is ignored anyway */ }
250
256
  }
251
257
 
252
258
  // ---------------------------------------------------------------------------