1var q=Object.defineProperty;var n=(d,t)=>q(d,"name",{value:t,configurable:!0});import{createKitThemeController as H}from"/js/common/kit-theme.js";import{createKitHeaderControls as U}from"/js/common/kit-header-controls.js";import{icon as r}from"/js/library/ui/icons.js";import{getAssetColors as C}from"/js/library/ui/asset-card.js";import{getAssetType as x}from"/js/library/core/registry.js";import{queryAssets as _,removeAsset as S,archiveAsset as B,favoriteAsset as D,duplicateAsset as V,updateAsset as G,moveAsset as L,saveAsset as W,getAsset as b,listAssetTypesInUse as Y,listToolsInUse as M,listTagsInUse as J}from"/js/library/core/assets.js";import{listCollections as k,collectionStats as Z,createCollection as Q}from"/js/library/core/collections.js";import{getSettings as A,updateSettings as E}from"/js/library/core/settings.js";import{estimateUsage as X}from"/js/library/core/storage.js";import{exportAssetAsJSON as $,exportLibrarySnapshot as tt,importLibraryFromFile as et}from"/js/library/core/export.js";import{bus as f,EVENTS as g}from"/js/library/core/events.js";import{attachLibraryMenu as it}from"./libraryMenu.js";const u={clock:'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15.5 14"/></svg>',sync:'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><polyline points="21 3 21 9 15 9"/></svg>',select:'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7V5a2 2 0 0 1 2-2h2M17 3h2a2 2 0 0 1 2 2v2M21 17v2a2 2 0 0 1-2 2h-2M7 21H5a2 2 0 0 1-2-2v-2"/><polyline points="8.5 12 11 14.5 15.5 9.5"/></svg>',chevron:'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>',group:'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="5" rx="1"/><rect x="3" y="13" width="18" height="7" rx="1"/></svg>',filter:'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><polygon points="22 3 2 3 10 12.5 10 19 14 21 14 12.5 22 3"/></svg>',keyboard:'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M6 10h.01M10 10h.01M14 10h.01M18 10h.01M8 14h8"/></svg>',grip:'<svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" aria-hidden="true"><circle cx="9" cy="7" r="1.25"/><circle cx="15" cy="7" r="1.25"/><circle cx="9" cy="12" r="1.25"/><circle cx="15" cy="12" r="1.25"/><circle cx="9" cy="17" r="1.25"/><circle cx="15" cy="17" r="1.25"/></svg>',more:'<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><line x1="4" y1="7" x2="20" y2="7"/><circle cx="9" cy="7" r="2.2" fill="var(--lk-bg)"/><line x1="4" y1="17" x2="20" y2="17"/><circle cx="15" cy="17" r="2.2" fill="var(--lk-bg)"/></svg>',reset:'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 4v6h6"/><path d="M5.5 15a7 7 0 1 0 1.2-7.8L4 10"/></svg>'},O=[{key:"__all",label:"All",icon:"grid"},{key:"__recent",label:"Recent",icon:null,glyph:"clock"},{key:"__fav",label:"Favorites",icon:"star"},{key:"__projects",label:"Projects",icon:"project"},{key:"__collections",label:"Collections",icon:"folder"},{key:"__archive",label:"Archive",icon:"archive"},{key:"__compare",label:"Compare",icon:"compare",noCount:!0},{key:"__settings",label:"Settings",icon:"settings",noCount:!0}],I="aa_lk_tab",P="aa_lk_collapsed",z="aa_lk_group",j="aa_lk_density",F=10080*60*1e3,st=[["Ctrl / \u2318 + Shift + L","Open or close the library"],["Esc","Clear the search, then close"],["\u2191 \u2193 \u2190 \u2192","Move between items"],["Enter","Restore the item into its tool"],["Delete","Delete the focused item"],["Ctrl / \u2318 + A","Select all (in multi-select)"],["Right-click","Full actions for an item or the panel"],["> \u2026","Run a library command"]];function s(d,t={},...e){const i=document.createElement(d);for(const[o,l]of Object.entries(t))l==null||l===!1||(o==="class"?i.className=l:o==="html"?i.innerHTML=l:o.startsWith("on")&&typeof l=="function"?i.addEventListener(o.slice(2).toLowerCase(),l):i.setAttribute(o,l===!0?"":String(l)));for(const o of e)o==null||o===!1||i.append(o instanceof Node?o:document.createTextNode(String(o)));return i}n(s,"h");function K(d){return String(d??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}n(K,"esc");function T(d,t=""){try{return localStorage.getItem(d)||t}catch{return t}}n(T,"readStored");function w(d,t){try{localStorage.setItem(d,t)}catch{}}n(w,"writeStored");function ot(d){try{return new Set(JSON.parse(localStorage.getItem(d)||"[]"))}catch{return new Set}}n(ot,"readStoredSet");
1function nt(d,t){w(d,JSON.stringify(Array.from(t)))}n(nt,"writeStoredSet");function N(d){if(!d)return"";const t=Date.parse(d);if(Number.isNaN(t))return"";const e=Date.now()-t;if(e<6e4)return"just now";const i=Math.floor(e/6e4);if(i<60)return`${i}m ago`;const o=Math.floor(i/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);if(l<7)return`${l}d ago`;try{return new Date(t).toLocaleDateString(void 0,{day:"numeric",month:"short"})}catch{return`${l}d ago`}}n(N,"relativeTime");function v(d){const t=x(d);return t?.label?t.label:String(d||"generic").replace(/[-_]/g," ")}n(v,"typeLabel");function lt(d){let t=0;const e=String(d||"");for(let i=0;i<e.length;i++)t=(t*31+e.charCodeAt(i))%360;return t}n(lt,"hashHue");function at(d){const e=(d.name||"").trim().replace(/^[#ââ·â¢\s]+/,"").slice(0,2).toUpperCase();return e||v(d.asset_type).slice(0,2).toUpperCase()||"\u2022"}n(at,"initialsFor");function R(d){return d?d<1024*1024?`${Math.round(d/1024)} KB`:`${(d/(1024*1024)).toFixed(1)} MB`:"0 KB"}n(R,"formatBytes");export class LibraryUI{static{n(this,"LibraryUI")}constructor(){this.open=!1,this._built=!1,this._filterTimer=0,this._tiles=[],this._cmdRows=[],this._cmdIndex=0,this._selection=new Set,this._selectMode=!1,this._collapsed=ot(P),this._returnFocus=null;const t=A();this._state={tab:T(I,"__all")||"__all",query:"",sort:t.sort||"recent",view:t.view==="list"?"list":"grid",group:T(z,"project")||"project",density:T(j,"comfortable")||"comfortable",collection:"",tool:"",tag:""},this._bindKitAutoClose(),this.ready=this._build()}_bindKitAutoClose(){window.addEventListener("auric-kit-open",t=>{t.detail?.kit!=="library"&&this.open&&!this._headerControls?.isFocus()&&this.toggle(!1)})}_announceKitOpen(){window.dispatchEvent(new CustomEvent("auric-kit-open",{detail:{kit:"library"}}))}_injectStyles(){const t=document.getElementById("lk-styles");if(t?.sheet)return Promise.resolve(t);const e=t||document.createElement("link");return t||(e.id="lk-styles",e.rel="stylesheet",e.href="/kit/library-kit/styles/libraryKit.css",document.head.appendChild(e)),new Promise(i=>{const o=n(()=>i(e),"finish");e.addEventListener("load",o,{once:!0}),e.addEventListener("error",o,{once:!0}),setTimeout(o,4e3)})}_injectPanelSkin(){document.getElementById("lk-panel-styles")?.remove();const t=document.createElement("link");return t.id="lk-panel-styles",t.rel="stylesheet",t.href="/kit/library-kit/styles/libraryPanels.css",document.head.appendChild(t),new Promise(e=>{t.addEventListener("load",e,{once:!0}),t.addEventListener("error",e,{once:!0}),setTimeout(e,400)})}async _build(){await this._injectStyles(),this.backdrop=s("div",{class:"lk-backdrop"}),document.body.appendChild(this.backdrop),this.fab=s("button",{class:"lk-fab",type:"button","aria-label":"Open library","aria-haspopup":"dialog","aria-expanded":"false","data-tooltip-title":"Library Kit","data-tooltip-description":"Browse, search and restore everything you have saved across the tools.","data-tooltip-placement":"top",html:r("library",{size:22}),onClick:n(()=>this.toggle(),"onClick")}),this.fabPip=s("span",{class:"lk-fab-pip lk-hidden"}),this.fab.appendChild(this.fabPip),document.body.appendChild(this.fab),this.panel=s("div",{class:"lk-panel",role:"dialog","aria-modal":"false","aria-labelledby":"lk-panel-title"}),this._buildHeader(),this._buildTabs(),this._buildSearch(),this._buildToolbar(),this.body=s("div",{class:"lk-body"}),this.panel.appendChild(this.body),this._buildBulkBar(),this._buildFooter(),this.dropHint=s("div",{class:"lk-drop"},"Drop a library .json file to import"),this.panel.appendChild(this.dropHint),this._theme=H({kitName:"library",button:this.themeBtn,elements:[this.panel,this.fab,this.backdrop]}),document.body.appendChild(this.panel),this._headerControls.applyStored(),this._bindKeyboard(),this._bindDataEvents(),this._bindDropImport(),it(this),this._built=!0,this.render()}_buildHeader(){this.header=s("div",{class:"lk-status"}),this.headerGrip=s("span",{class:"lk-header-grip",role:"button",tabindex:"0","aria-label":"Move library panel","aria-description":"Drag the header or use the arrow keys. Hold Shift for precise movement.",html:u.grip}),this.title=s("h2",{class:"lk-title aa-kh-title",id:"lk-panel-title",html:"Your <b>Library</b>"}),this.countBadge=s("span",{class:"lk-status-badge","data-tooltip-title":"Saved items","aria-live":"polite"}),this.themeBtn=s("button",{class:"lk-status-btn",type:"button","data-lk-act":"theme","aria-label":"Switch library theme","data-tooltip-title":"Theme","data-tooltip-description":"Switch this panel between light and dark mode.",html:""});const t=s("button",{class:"lk-status-btn",type:"button","aria-label":"Close library","data-tooltip-title":"Close","data-tooltip-description":"Close Library Kit.",html:r("close",{size:18}),onClick:n(()=>this.toggle(!1),"onClick")}),e=s("div",{class:"lk-status-actions aa-kh-controls"});this.panelOptionsBtn=s("button",{class:"lk-status-btn",type:"button","aria-label":"Panel options","aria-haspopup":"menu","aria-expanded":"false","data-tooltip-title":"Panel options",html:u.more,onClick:n(o=>{o.stopPropagation(),this._togglePanelOptions()},"onClick")}),this.header.append(this.headerGrip,this.title,this.countBadge,e),this._headerControls=U({panel:this.panel,header:this.header,storagePrefix:"libraryKit",label:"Library Kit",expandedWidth:940,keyboardHandle:this.headerGrip}),this.panelOptions=s("div",{class:"lk-panel-options",role:"menu","aria-label":"Library panel options",hidden:!0});const i=n((o,l,c)=>(o.classList.add("lk-panel-option"),o.dataset.optionLabel=l,o.dataset.optionDescription=c,o.setAttribute("role","menuitem"),o),"option");this.resetPositionBtn=s("button",{class:"aa-kh-btn lk-panel-option",type:"button",role:"menuitem","aria-label":"Reset panel position","data-option-label":"Reset position","data-option-description":"Return the panel to its default corner",html:u.reset,onClick:n(()=>{this._headerControls.dragController?.reset(),this._togglePanelOptions(!1),this.headerGrip.focus({preventScroll:!0}),this._toast("Library returned to its default position.")},"onClick")}),this.panelOptions.append(i(this._headerControls.focusBtn,"Keep open","Stay visible while opening other kits"),i(this.themeBtn,"Theme","Switch this panel between light and dark"),i(this._headerControls.expandBtn,"Panel size","Toggle the wider workspace view"),i(this._headerControls.minBtn,"Minimize","Collapse the library to its title bar"),this.resetPositionBtn),this.panelOptions.addEventListener("click",o=>
1{o.target.closest("button")&&o.target!==this.resetPositionBtn&&requestAnimationFrame(()=>{this._togglePanelOptions(!1),this.panelOptionsBtn.focus({preventScroll:!0})})}),this.panelOptions.addEventListener("keydown",o=>{const l=Array.from(this.panelOptions.querySelectorAll('[role="menuitem"]')),c=l.indexOf(document.activeElement);let a=null;o.key==="ArrowDown"&&(a=c<l.length-1?c+1:0),o.key==="ArrowUp"&&(a=c>0?c-1:l.length-1),o.key==="Home"&&(a=0),o.key==="End"&&(a=l.length-1),a!==null&&(o.preventDefault(),l[a]?.focus())}),e.append(this.panelOptionsBtn,t),this.header.appendChild(this.panelOptions),this.panel.appendChild(this.header),this._onDocumentPointerDown=o=>{!this.panelOptions.hidden&&!this.header.contains(o.target)&&this._togglePanelOptions(!1)},document.addEventListener("pointerdown",this._onDocumentPointerDown,!0)}_togglePanelOptions(t){const e=typeof t=="boolean"?t:this.panelOptions.hidden;if(this.panelOptions.hidden=!e,this.panelOptionsBtn.setAttribute("aria-expanded",String(e)),e){const i=this.panelOptions.querySelector("button");requestAnimationFrame(()=>i?.focus())}}_buildSearch(){this.searchInput=s("input",{class:"lk-search-input",type:"text",placeholder:"Search your library\u2026 (> for commands)","aria-label":"Search the library",autocomplete:"off",spellcheck:"false",onInput:n(()=>{this._syncSearchClear(),clearTimeout(this._filterTimer),this._filterTimer=setTimeout(()=>{this._state.query=this.searchInput.value,this._cmdIndex=0,this.render()},70)},"onInput"),onKeydown:n(t=>this._onSearchKey(t),"onKeydown")}),this.searchClear=s("button",{class:"lk-search-clear lk-hidden",type:"button","aria-label":"Clear search",html:r("close",{size:14}),onClick:n(()=>{this.searchInput.value="",this._state.query="",this._syncSearchClear(),this.render(),this.searchInput.focus()},"onClick")}),this.searchKbd=s("span",{class:"lk-search-kbd",html:"<kbd>Esc</kbd>"}),this.panel.appendChild(s("section",{class:"lk-search"},s("div",{class:"lk-field-label"},s("span",{},"Search library"),s("small",{},"type > for commands")),s("div",{class:"lk-search-field"},s("span",{class:"lk-search-icon",html:r("search",{size:17})}),this.searchInput,this.searchClear,this.searchKbd)))}_buildTabs(){this.tabBar=s("div",{class:"lk-tabs",role:"tablist","aria-label":"Library sections"}),this.panel.appendChild(this.tabBar)}_buildToolbar(){this.toolbarCount=s("span",{class:"lk-toolbar-count","aria-live":"polite"}),this.sortSelect=s("select",{class:"lk-select",id:"lk-sort-items","aria-label":"Sort items","data-size":"full","data-lk-sort":"","data-picker-skin":"library","data-tooltip-title":"Sort",onChange:n(()=>{this._state.sort=this.sortSelect.value;try{E({sort:this._state.sort})}catch{}this.render()},"onChange")},s("option",{value:"recent"},"Newest"),s("option",{value:"oldest"},"Oldest"),s("option",{value:"name_asc"},"Name A\u2013Z"),s("option",{value:"name_desc"},"Name Z\u2013A"),s("option",{value:"type"},"Type")),this.sortSelect.value=this._state.sort,this.groupBtn=s("button",{class:"lk-iconbtn",type:"button","aria-label":"Toggle grouping","data-tooltip-title":"Group","data-tooltip-description":"Group items into collapsible sections by type.",html:u.group,onClick:n(()=>this.toggleGrouping(),"onClick")}),this.viewBtn=s("button",{class:"lk-iconbtn",type:"button","aria-label":"Toggle grid or list view","data-tooltip-title":"View","data-tooltip-description":"Switch between the grid and list layouts.",html:r(this._state.view==="list"?"grid":"list",{size:16}),onClick:n(()=>this.toggleView(),"onClick")}),this.selectBtn=s("button",{class:"lk-iconbtn",type:"button","aria-label":"Toggle multi-select","data-tooltip-title":"Select","data-tooltip-description":"Pick several items to favourite, collect, export or delete together.",html:u.select,onClick:n(()=>this.toggleSelectMode(),"onClick")});const t=s("div",{class:"lk-sort-field"},s("label",{class:"lk-toolbar-label",for:"lk-sort-items"},"Sort"),this.sortSelect),e=s("div",{class:"lk-toolbar-actions","aria-label":"View options"},this.groupBtn,this.viewBtn,this.selectBtn);this.toolbar=s("div",{class:"lk-toolbar"},this.toolbarCount,t,e),this.panel.appendChild(this.toolbar),this.chipBar=s("div",{class:"lk-chips lk-hidden"}),this.panel.appendChild(this.chipBar)}_buildBulkBar(){this.bulkCount=s("span",{class:"lk-bulk-count"}),this.bulkBar=s("div",{class:"lk-bulk lk-hidden"},this.bulkCount,s("button",{class:"lk-foot-btn",type:"button",html:`${r("check",{size:14})} All`,onClick:n(()=>this.selectAll(),"onClick")}),s("button",{class:"lk-foot-btn",type:"button",html:`${r("star",{size:14})} Favorite`,onClick:n(()=>this.bulk("favorite"),"onClick")}),s("button",{class:"lk-foot-btn",type:"button",html:`${r("folder",{size:14})} Collect`,onClick:n(()=>this.bulkAddToCollection(),"onClick")}),s("button",{class:"lk-foot-btn",type:"button",html:`${r("archive",{size:14})} Archive`,onClick:n(()=>this.bulk("archive"),"onClick")}),s("button",{class:"lk-foot-btn",type:"button",html:`${r("download",{size:14})} Export`,onClick:n(()=>this.bulk("export"),"onClick")}),s("button",{class:"lk-foot-btn lk-foot-btn--danger",type:"button",html:`${r("trash",{size:14})} Delete`,onClick:n(()=>this.bulk("delete"),"onClick")})),this.panel.appendChild(this.bulkBar)}_buildFooter(){const t=n((e,i,o,l="")=>s("button",{class:`lk-foot-btn ${l}`.trim(),type:"button",html:`${i} ${K(e)}`,onClick:o}),"footBtn");this.storageMeter=s("span",{class:"lk-foot-storage","data-tooltip-title":"Library storage"}),this.footer=s("div",{class:"lk-footer"},s("div",{class:"lk-footer-group"},t("New project",r("plus",{size:14}),()=>this.newProject(),"lk-foot-btn--primary"),t("Import",r("upload",{size:14}),()=>this.importFile()),t("Export",r("download",{size:14}),()=>this.exportSnapshot()),this.storageMeter),s("div",{class:"lk-footer-group lk-footer-group--end"},t("Settings",r("settings",{size:14}),()=>this.openSettings()),t("Keys",u.keyboard,()=>this.showShortcuts()))),this.panel.appendChild(this.footer)}_bindDataEvents(){const t=n(()=>{this._built&&this.render()},"rerender");this._offs=[f.on(g.ASSET_ADDED,t),f.on(g.ASSET_UPDATED,t),f.on(g.ASSET_REMOVED,t),f.on(g.ASSETS_REORDERED,t),f.on(g.COLLECTION_ADDED,t),f.on(g.COLLECTION_UPDATED,t),f.on(g.COLLECTION_REMOVED,t)]}_filterForTab(){const t=this._state.tab,e={};return this._state.collection&&(e.collection=this._state.collection),this._state.tool&&(e.tool=this._state.tool),this._state.tag&&(e.tag=this._state.tag),t==="__fav"?e.favorite=!0:t==="__projects"?e.type="project":t.startsWith("type:")&&(e.type=t.slice(5)),e.archived=t==="__archive",e}_currentItems(){let t=_({query:this._state.query.startsWith(">")?"":this._state.query,sort:this._state.sort,filter:this._filterForTab()});if(this._state.tab==="__recent"){const e=Date.now()-F;t=t.filter(i=>Date.parse(i.updated_at||"")>=e)}return t}
1render(){if(!this._built)return;const t=_({filter:{archived:!1}}),e=_({filter:{archived:!0}});this._renderTabs(t,e);const i=this._state.query.trim().startsWith(">");this.panel.classList.toggle("lk-select-mode",this._selectMode),this.panel.dataset.lkDensity=this._state.density,this.body.classList.toggle("lk-view-list",this._state.view==="list"),this.body.classList.toggle("lk-body--settings",this._state.tab==="__settings"),this.body.classList.toggle("lk-body--compare",this._state.tab==="__compare"),this.body.querySelectorAll("select").forEach(o=>o._aaSelectPicker?.destroy?.()),this._inlineView?.destroy?.(),this._inlineView=null,this.body.innerHTML="",this._tiles=[],this._cmdRows=[],i?(this.toolbar.classList.add("lk-hidden"),this._renderCommands(this._state.query.trim().slice(1).trim().toLowerCase())):this._state.tab==="__settings"?(this.toolbar.classList.add("lk-hidden"),this._renderSettings()):this._state.tab==="__compare"?(this.toolbar.classList.add("lk-hidden"),this._renderCompare()):this._state.tab==="__collections"?(this.toolbar.classList.remove("lk-hidden"),this._renderCollections()):(this.toolbar.classList.remove("lk-hidden"),this._renderAssets()),this._renderChips(),this._renderCounts(t),this._syncBulkBar()}_renderCounts(t){const e=t.length;this.countBadge.textContent=e===1?"1 item":`${e} items`,this.countBadge.setAttribute("data-tooltip-description",`${e} saved item${e===1?"":"s"} in your library.`),this.fabPip&&(this.fabPip.textContent=e>99?"99+":String(e),this.fabPip.classList.toggle("lk-hidden",e===0));try{const i=X();this.storageMeter.textContent=R(i.bytes),this.storageMeter.setAttribute("data-tooltip-description",`${R(i.bytes)} across ${i.entries} stored entries.`)}catch{this.storageMeter.textContent=""}}_renderTabs(t,e){const i=new Map;i.set("__all",t.length),i.set("__fav",t.filter(a=>a.favorite).length),i.set("__projects",t.filter(a=>a.asset_type==="project").length);const o=Date.now()-F;i.set("__recent",t.filter(a=>Date.parse(a.updated_at||"")>=o).length),i.set("__collections",k().length),i.set("__archive",e.length);const l=Y().filter(a=>a.type!=="project"&&a.count>0),c=[...O,...l.map(a=>({key:`type:${a.type}`,label:v(a.type),icon:"palette",count:a.count}))];this.tabBar.innerHTML="";for(const a of c){const h=a.count??i.get(a.key)??0,p=this._state.tab===a.key;this.tabBar.appendChild(s("button",{class:`lk-tab${p?" lk-tab-active":""}`,type:"button",role:"tab","aria-selected":String(p),"data-tab":a.key,onClick:n(()=>this.setTab(a.key),"onClick")},s("span",{class:"lk-tab-label"},a.label),a.noCount?null:s("span",{class:"lk-tab-count"},String(h))))}}_renderChips(){const t=[],e=n((i,o)=>s("button",{class:"lk-chip",type:"button",title:"Remove this filter",onClick:o},s("span",{},i),s("span",{class:"lk-chip-x",html:r("close",{size:11})})),"chip");if(this._state.collection){const i=k().find(o=>o.id===this._state.collection)?.name;t.push(e(`Collection: ${i||"\u2014"}`,()=>{this._state.collection="",this.render()}))}if(this._state.tool){const i=M().find(o=>o.tool_id===this._state.tool)?.tool_name;t.push(e(`Tool: ${i||this._state.tool}`,()=>{this._state.tool="",this.render()}))}if(this._state.tag&&t.push(e(`Tag: ${this._state.tag}`,()=>{this._state.tag="",this.render()})),this.chipBar.innerHTML="",!t.length){this.chipBar.classList.add("lk-hidden");return}this.chipBar.classList.remove("lk-hidden"),t.forEach(i=>this.chipBar.appendChild(i)),this.chipBar.appendChild(s("button",{class:"lk-chip lk-chip--clear",type:"button",html:"Clear all",onClick:n(()=>this.clearFilters(),"onClick")}))}_renderAssets(){const t=this._currentItems(),e=O.find(h=>h.key===this._state.tab)?.label||(this._state.tab.startsWith("type:")?v(this._state.tab.slice(5)):"All");if(this.toolbarCount.innerHTML=`<strong>${t.length}</strong> ${t.length===1?"item":"items"} in ${K(e)}`,!t.length){this.body.appendChild(this._emptyState());return}const i=this._state.group;if(!(i!=="none"&&this._state.view==="grid")){t.forEach(h=>this.body.appendChild(this._tile(h)));return}const l=new Map((k()||[]).map(h=>[h.id,h.name])),c=new Map;for(const h of t){const p=i==="project"?h.collection||"":h.asset_type||"generic";c.has(p)||c.set(p,[]),c.get(p).push(h)}if(i==="project"&&c.has("")){const h=c.get("");c.delete(""),c.set("",h)}if(!(i==="project"?[...c.keys()].some(h=>h):c.size>1)){t.forEach(h=>this.body.appendChild(this._tile(h)));return}for(const[h,p]of c){const y=this._collapsed.has(h);this.body.appendChild(s("button",{class:`lk-section-label${y?" lk-section-collapsed":""}`,type:"button","aria-expanded":String(!y),onClick:n(()=>this.toggleSection(h),"onClick")},s("span",{class:"lk-section-title"},i==="project"?l.get(h)||"Unfiled":v(h)),s("span",{class:"lk-section-count"}
1,String(p.length)),s("span",{class:"lk-section-chevron",html:u.chevron}))),!y&&p.forEach(m=>this.body.appendChild(this._tile(m)))}}_renderCollections(){const t=Z(),e=k();if(this.toolbarCount.innerHTML=`<strong>${e.length}</strong> ${e.length===1?"collection":"collections"}`,this.body.appendChild(s("button",{class:"lk-tile lk-tile--new",type:"button",onClick:n(()=>this.newCollection(),"onClick")},s("span",{class:"lk-tile-art"},s("span",{class:"lk-tile-art-glyph",html:r("plus",{size:26})})),s("span",{class:"lk-tile-name"},"New collection"),s("span",{class:"lk-tile-meta"},s("span",{class:"lk-tile-when"},"Group saved items")))),!e.length){this.body.appendChild(this._emptyState({title:"No collections yet",msg:"Collections group saved items into folders. Create one above, or from any item's right-click menu."}));return}for(const i of e){const o=t[i.id]||0;this.body.appendChild(s("div",{class:"lk-tile",role:"button",tabindex:"0",title:`Open ${i.name}`,onClick:n(()=>this.openCollection(i.id),"onClick"),onKeydown:n(l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),this.openCollection(i.id))},"onKeydown")},s("span",{class:"lk-tile-art"},s("span",{class:"lk-tile-art-glyph",html:r("folder",{size:26})})),s("span",{class:"lk-tile-name"},i.name||"Untitled"),s("span",{class:"lk-tile-meta"},s("span",{class:"lk-tile-type"},"Collection"),s("span",{class:"lk-tile-when"},`${o} item${o===1?"":"s"}`))))}}_emptyState({title:t,msg:e}={}){const i=!!this._state.query.trim(),o=s("div",{class:"lk-empty"},s("span",{class:"lk-empty-icon",html:r(i?"search":"library",{size:24})}),s("p",{class:"lk-empty-title"},t||(i?"Nothing matched":"Nothing saved here yet")),s("p",{class:"lk-empty-msg"},e||(i?"Try a different word, or clear the search to see everything.":"Save a palette, gradient, type scale or report from any tool and it lands here.")));return i&&o.appendChild(s("button",{class:"lk-foot-btn lk-empty-action",type:"button",html:`${r("close",{size:14})} Clear search`,onClick:n(()=>{this.searchInput.value="",this._state.query="",this._syncSearchClear(),this.render()},"onClick")})),o}_tile(t){const e=this._selection.has(t.id),i=s("div",{class:`lk-tile${e?" is-selected":""}`,role:"button",tabindex:"0","data-id":t.id,title:`${t.name||"Untitled"} \u2014 right-click for actions`});i.appendChild(this._preview(t)),i.appendChild(s("span",{class:"lk-tile-check",html:r("check",{size:13})})),t.favorite&&i.appendChild(s("span",{class:"lk-tile-fav",html:r("star",{size:12})}));const o=s("span",{class:"lk-tile-name"},t.name||"Untitled"),l=s("span",{class:"lk-tile-meta"},s("span",{class:"lk-tile-type"},v(t.asset_type)),s("span",{class:"lk-tile-when"},[t.tool_name,N(t.updated_at)].filter(Boolean).join(" \xB7 ")));return this._state.view==="list"?i.appendChild(s("span",{class:"lk-tile-body"},o,l)):i.append(o,l),i.appendChild(this._tileActions(t)),i.addEventListener("click",c=>{if(!c.target.closest("[data-act]")){if(this._selectMode){this.toggleSelection(t.id);return}this.restore(t)}}),i.addEventListener("keydown",c=>{c.key==="Enter"||c.key===" "?(c.preventDefault(),this._selectMode?this.toggleSelection(t.id):this.restore(t)):c.key==="Delete"&&(c.preventDefault(),this.deleteAsset(t))}),this._tiles.push(i),i}_preview(t){const e=s("span",{class:"lk-tile-art"}),i=t.preview_data||{},o=t.asset_data||{},l=C(t);if(i.image_url||i.image){const a=s("img",{src:i.image_url||i.image,alt:"",loading:"lazy",decoding:"async"});return a.addEventListener("error",()=>{e.replaceChildren(this._generatedPlate(t))}),e.appendChild(a),e}const c=i.gradient||o.gradient||o.css;if(c&&typeof c=="string")return e.style.background=c,e;if(l.length>=2)return l.slice(0,8).forEach(a=>{const h=s("span",{class:"lk-tile-swatch"});h.style.background=a,e.appendChild(h)}),e;if(l.length===1){const a=s("span",{class:"lk-tile-swatch"});return a.style.background=l[0],e.appendChild(a),e}if(i.sample||i.text){const a=s("span",{class:"lk-tile-art-text"},String(i.sample||i.text).slice(0,12));return i.font_family&&(a.style.fontFamily=i.font_family),e.appendChild(a),e}return e.appendChild(this._generatedPlate(t)),e}_generatedPlate(t){const e=x(t.asset_type),i=lt(`${t.id||""}${t.name||t.asset_type||""}`),o=s("span",{class:"lk-tile-art-gen"},s("span",{class:"lk-tile-art-initials"},at(t)));return o.style.background=e?.color?`linear-gradient(135deg, ${e.color}, hsl(${i} 45% 26%))`:`linear-gradient(135deg, hsl(${i} 52% 44%), hsl(${(i+38)%360} 58% 30%))`,o}_tileActions(t){const e=n((o,l,c,a,h=!1)=>s("button",{class:`lk-tile-act${h?" is-on":""}`,type:"button","data-act":o,"aria-label":l,title:l,html:c,onClick:n(p=>{p.stopPropagation(),a()},"onClick")}),"act"),i=[e("favorite",t.favorite?"Remove favourite":"Favourite",r("star",{size:13}),()=>this.toggleFavorite(t),t.favorite),e("open","Open details",r("edit",{size:13}),()=>this.openDetail(t.id))];return this._state.view==="list"&&i.push(e("duplicate","Duplicate",r("copy",{size:13}),()=>this.duplicate(t)),e("export","Export JSON",r("download",{size:13}),()=>this.exportOne(t.id))),i.push(e("share","Share",r("share",{size:13}),()=>this.share(t)),e("delete","Delete",r("trash",{size:13}),()=>this.deleteAsset(t))),s("span",{class:"lk-tile-actions"},...i)}assetById(t){return b(t)||null}colorsOf(t){return C(t)}typeName(t){return v(t)}when(t){return N(t)}selectionSize(){return this._selection.size}isSelected(t){return this._selection.has(t)}hasFilters(){return!!(this._state.query||this._state.collection||this._state.tool||this._state.tag||this._state.tab!=="__all")}state(){return{view:this._state.view,selectMode:this._selectMode,showArchived:!!A().show_archived,group:this._state.group,density:this._state.density}}stats(){const t=_({filter:{archived:!1}});return{total:t.length,favorites:t.filter(e=>e.favorite).length,collections:k().length,archived:_({filter:{archived:!0}}).length}}toolsFor(t){try{return window.AALibrary?.listToolsForAsset?.(t)||[]}catch{return[]}}async _ensureOverlayStyles(){this._watchOverlayTheme();try{const{ensureLibraryStyles:t}=await import("/js/library/ui/styles.js");await t()}catch{}this._panelSkin||(this._panelSkin=this._injectPanelSkin()),await this._panelSkin}_watchOverlayTheme(){const t=n(e=>{const i=this.panel?.getAttribute("data-kit-theme");!i||!e?.classList?.contains?.("aa-lib-overlay")||e.setAttribute("data-kit-theme",i)},"stamp");document.querySelectorAll(".aa-lib-overlay").forEach(t),!this._overlayObserver&&(this._overlayObserver=new MutationObserver(e=>{for(const i of e)i.addedNodes?.forEach?.(o=>{o.nodeType===1&&(t(o),o.querySelectorAll?.(".aa-lib-overlay").forEach(t))})}),this._overlayObserver.observe(document.body,{childList:!0,subtree:!0}),window.addEventListener("kit-theme:change",e=>{e?.detail?.kitName==="library"&&document.querySelectorAll(".aa-lib-overlay").forEach(t)}))}async openDetail(t){try{await this._ensureOverlayStyles(),(await import("/js/library/ui/detail-modal.js")).openDetailModal(t)}catch(e){console.error("[LibraryKit] detail panel failed to load:",e)}}async openSettings(){this.setTab("__settings")}async _renderSettings(){const t=s("div",{class:"lk-settings"});t.appendChild(s("div",{class:"lk-settings-loading"},"Loading settings\u2026")),this.body.appendChild(t);try{await this._ensureOverlayStyles();const e=await import("/js/library/ui/settings-modal.js");if(this._state.tab!=="__settings"||!t.isConnected)return;t.innerHTML="",this._inlineView=e.openSettingsModal({mount:t}),t.querySelectorAll("select").forEach(i=>
1{i.dataset.pickerSkin="library"})}catch(e){console.error("[LibraryKit] settings failed to load:",e),t.innerHTML="",t.appendChild(s("div",{class:"lk-settings-loading"},"Settings could not be loaded."))}}async _renderCompare(){const t=s("div",{class:"lk-compare"});t.appendChild(s("div",{class:"lk-settings-loading"},"Loading comparison\xE2\u20AC\xA6")),this.body.appendChild(t);try{await this._ensureOverlayStyles();const e=await import("/js/library/ui/compare.js");if(this._state.tab!=="__compare"||!t.isConnected)return;t.innerHTML="";const i=!!this._compareSeed,o=this._compareSeed||{};this._compareSeed=null,this._inlineView=e.openCompareModal(o.aId||null,o.bId||null,{mount:t,reset:i})}catch(e){console.error("[LibraryKit] compare failed to load:",e),t.innerHTML="",t.appendChild(s("div",{class:"lk-settings-loading"},"Comparison could not be loaded."))}}compare(t=null,e=null){const i=Array.from(this._selection),o=t||i[0]||this._currentItems()[0]?.id||null,l=e||i[1]||null;this._compareSeed={aId:o,bId:l},this.setTab("__compare"),this.toggle(!0)}compareWith(t){this._selection.clear(),this._selection.add(t),this.compare(t,null)}async share(t){try{await this._ensureOverlayStyles();const[e,i]=await Promise.all([import("/js/library/share/dialog.js"),import("/js/library/share/routes.js")]),o=b(t.id)||t,l=o.asset_type||"generic";await e.shareViaDialog({type:l,data:{name:o.name,tool_id:o.tool_id,tool_name:o.tool_name,preview:o.preview_data||{},data:o.asset_data||{},settings:o.settings||{}},title:o.name||"Share link",pathname:i.routeForShareType(l)||"/library/"})}catch(e){console.error("[LibraryKit] share dialog failed to load:",e),this._toast("That item could not be shared.","warn")}}async _prompt(t){await this._ensureOverlayStyles();const{aaPrompt:e}=await import("/js/library/ui/prompt.js");return e(t)}restore(t){const e=b(t.id)||t;let i=!1;try{i=!!window.AALibrary?.restoreAsset?.(e)}catch{i=!1}if(i){this.toggle(!1);return}this.openDetail(t.id)}openIn(t,e){const i=b(t.id)||t;try{window.AALibrary?.openAssetInTool?.(i,e)}catch(o){console.error("[LibraryKit] hand-off failed:",o)}}toggleFavorite(t){D(t.id,!t.favorite)}toggleArchive(t){B(t.id,!t.archived)}duplicate(t){V(t.id)}exportOne(t){$(t)}async rename(t){try{const e=await this._prompt({title:"Rename item",label:"Name",defaultValue:t.name||"",confirmLabel:"Rename"});if(!e||e===t.name)return;G(t.id,{name:e}),this._toast("Renamed")}catch(e){console.error("[LibraryKit] rename failed:",e)}}async deleteAsset(t){await this._confirm("Delete item?",`\u201C${t.name||"Untitled"}\u201D will be permanently removed. This cannot be undone.`)&&S(t.id)}copyColors(t){const e=C(t);if(!e.length){this._toast("This item has no colours to copy.");return}this.copyText(e.join(", "),`${e.length} colour${e.length===1?"":"s"} copied`)}copyText(t,e="Copied"){const i=n(()=>this._toast(e),"done");try{navigator.clipboard.writeText(t).then(i).catch(()=>this._copyFallback(t,i))}catch{this._copyFallback(t,i)}}_copyFallback(t,e){try{const i=document.createElement("textarea");i.value=t,i.setAttribute("readonly",""),i.style.cssText="position:fixed;top:-1000px;opacity:0",document.body.appendChild(i),i.select(),document.execCommand("copy"),i.remove(),e()}catch{this._toast("Could not copy to the clipboard.","warn")}}openCollection(t){this._state.collection=t,this.setTab("__all")}async newCollection(t=null){try{const e=await this._prompt({title:"New collection",label:"Collection name",defaultValue:"Untitled collection",confirmLabel:"Create"});if(!e)return null;const i=Q({name:e});return i&&Array.isArray(t)&&t.forEach(o=>L(o,i.id)),this._toast(`Created \u201C${e}\u201D`),i}catch(e){return console.error("[LibraryKit] could not create a collection:",e),null}}addToCollection(t){return this._pickCollection([t.id])}bulkAddToCollection(){const t=Array.from(this._selection);return t.length?this._pickCollection(t):null}_pickCollection(t){const e=k();return new Promise(i=>{const o=e.map(h=>s("button",{class:"lk-cmd",type:"button",onClick:n(()=>{t.forEach(p=>L(p,h.id)),this._toast(`Moved ${t.length} item${t.length===1?"":"s"} to \u201C${h.name}\u201D`),a(),i(h.id)},"onClick")},s("span",{class:"lk-cmd-icon",html:r("folder",{size:16})}),s("span",{class:"lk-cmd-body"},s("span",{class:"lk-cmd-name"},h.name||"Untitled")))),l=s("button",{class:"lk-cmd",type:"button",onClick:n(async()=>{a();const h=await this.newCollection(t);
1i(h?.id||null)},"onClick")},s("span",{class:"lk-cmd-icon",html:r("plus",{size:16})}),s("span",{class:"lk-cmd-body"},s("span",{class:"lk-cmd-name"},"New collection\u2026"))),c=s("button",{class:"lk-cmd",type:"button",onClick:n(()=>{t.forEach(h=>L(h,"")),this._toast("Removed from its collection"),a(),i("")},"onClick")},s("span",{class:"lk-cmd-icon",html:r("close",{size:16})}),s("span",{class:"lk-cmd-body"},s("span",{class:"lk-cmd-name"},"No collection"))),{close:a}=this._sheet(t.length===1?"Add to collection":`Add ${t.length} items to collection`,[l,...o,c],()=>i(null))})}toggleSelectMode(){this._selectMode=!this._selectMode,this._selectMode||this._selection.clear(),this.selectBtn.classList.toggle("is-on",this._selectMode),this.render()}toggleSelection(t){this._selection.has(t)?this._selection.delete(t):this._selection.add(t),this.render()}selectOnly(t){this._selectMode=!0,this.selectBtn.classList.add("is-on"),this._selection.clear(),this._selection.add(t),this.render()}selectAll(){const t=this._currentItems();t.length>0&&t.every(i=>this._selection.has(i.id))?this._selection.clear():t.forEach(i=>this._selection.add(i.id)),this.render()}_syncBulkBar(){const t=this._selection.size;this.bulkBar.classList.toggle("lk-hidden",!this._selectMode),this.bulkCount.textContent=t?`${t} selected`:"Pick items to act on them"}async bulk(t){const e=Array.from(this._selection);if(e.length){if(t==="delete"){if(!await this._confirm(`Delete ${e.length} item${e.length===1?"":"s"}?`,"The selected items will be permanently removed. This cannot be undone."))return;e.forEach(o=>S(o))}else if(t==="favorite"){const i=e.every(o=>b(o)?.favorite);e.forEach(o=>D(o,!i))}else if(t==="archive"){const i=e.every(o=>b(o)?.archived);e.forEach(o=>B(o,!i))}else t==="export"&&e.forEach(i=>$(i));this._selection.clear(),this.render()}}async emptyArchive(){const t=_({filter:{archived:!0}});!t.length||!await this._confirm(`Delete ${t.length} archived item${t.length===1?"":"s"}?`,"Everything in the archive will be permanently removed. This cannot be undone.")||(t.forEach(i=>S(i.id)),this._toast("Archive emptied"))}async newProject(){try{const t=await this._prompt({title:"New project",label:"Project name",defaultValue:"Untitled project",confirmLabel:"Create"});if(!t)return;W({asset_type:"project",tool_id:"library-workspace",tool_name:"Workspace",name:t,description:"",preview_data:{entries:[]},asset_data:{entries:[]}}),this.setTab("__projects")}catch(t){console.error("[LibraryKit] could not create a project:",t),this._toast("That project could not be created.","warn")}}importFile(){const t=s("input",{type:"file",accept:"application/json"});t.style.display="none",t.addEventListener("change",async()=>{const e=t.files?.[0];e&&await this._importFile(e),t.remove()}),document.body.appendChild(t),t.click()}async _importFile(t){try{await et(t,{merge:!0}),this._toast(`Imported ${t.name}`),this.render()}catch(e){console.error("[LibraryKit] import failed:",e),this._toast("That file could not be imported.","warn")}}exportSnapshot(){try{tt(),this._toast("Library snapshot downloaded")}catch(t){console.error("[LibraryKit] export failed:",t)}}async syncNow(){try{const e=await(await import("/js/library/core/sync.js")).pushAll({reason:"manual"});if(e?.error==="sync-disabled"){this._toast("Sync is switched off \u2014 turn it on in Library settings.");return}const i=e?.results||[];if(!i.length){this._toast("No sync destinations configured yet.");return}const o=i.filter(l=>l.ok).length;this._toast(e.ok?`Synced to ${o} destination${o===1?"":"s"}`:`Synced ${o} of ${i.length} destinations \u2014 check settings.`,e.ok?"info":"warn")}catch(t){console.error("[LibraryKit] sync failed:",t),this._toast("Sync could not complete.","warn")}}setTab(t){this._state.tab=t,t!=="__all"&&(this._state.collection=""),w(I,t),this.render(),this.tabBar.querySelector(".lk-tab-active")?.scrollIntoView({inline:"nearest",block:"nearest"})}toggleView(){this._state.view=this._state.view==="list"?"grid":"list",this.viewBtn.innerHTML=r(this._state.view==="list"?"grid":"list",{size:16});try{E({view:this._state.view})}catch{}this.render()}toggleGrouping(){const t={project:"type",type:"none",none:"project"};this._state.group=t[this._state.group]||"project",this.groupBtn.classList.toggle("is-on",this._state.group!=="none"),this.groupBtn.title=this._state.group==="project"?"Grouped by project \u2014 press for type":this._state.group==="type"?"Grouped by type \u2014 press for none":"Not grouped \u2014 press for project",w(z,this._state.group),this.render()}toggleSection(t){this._collapsed.has(t)?this._collapsed.delete(t):this._collapsed.add(t),nt(P,this._collapsed),this.render()}toggleDensity(){this._state.density=this._state.density==="compact"?"comfortable":"compact",w(j,this._state.density),this.render()}toggleArchived(){const t=!A().show_archived;try{E({show_archived:t})}catch{}this.render()}filterByTool(t){this._state.tool=t||"",this.render()}filterByTag(t){this._state.tag=t||"",this.render()}clearFilters(){this._state.collection="",this._state.tool="",this._state.tag="",this._state.query="",this.searchInput&&(this.searchInput.value=""),this._syncSearchClear(),this.setTab("__all")}_syncSearchClear(){const t=!!this.searchInput.value;this.searchClear.classList.toggle("lk-hidden",!t),this.searchKbd.classList.toggle("lk-hidden",t)}_commands(){const t=this.state(),e=[{id:"new-project",name:"New project",hint:"Bu
1ndle several saved items into one project",glyph:r("project",{size:16}),run:n(()=>this.newProject(),"run")},{id:"new-collection",name:"New collection",hint:"Group saved items into a folder",glyph:r("folder",{size:16}),run:n(()=>this.newCollection(),"run")},{id:"import",name:"Import library file",hint:"Merge a previously exported .json",glyph:r("upload",{size:16}),run:n(()=>this.importFile(),"run")},{id:"export",name:"Export library snapshot",hint:"Download everything as a single .json",glyph:r("download",{size:16}),run:n(()=>this.exportSnapshot(),"run")},{id:"sync",name:"Sync now",hint:"Push to every configured destination",glyph:u.sync,run:n(()=>this.syncNow(),"run")},{id:"settings",name:"Library settings",hint:"Storage, sync, defaults and data controls",glyph:r("settings",{size:16}),run:n(()=>this.openSettings(),"run")},{id:"compare",name:"Compare items",hint:"Open two saved items side by side",glyph:r("compare",{size:16}),run:n(()=>this.compare(),"run")},{id:"view",name:`Switch to ${t.view==="list"?"grid":"list"} view`,hint:"Change how items are laid out",glyph:r(t.view==="list"?"grid":"list",{size:16}),run:n(()=>this.toggleView(),"run")},{id:"group",name:t.group==="type"?"Stop grouping by type":"Group by type",hint:"Collapsible sections per asset type",glyph:u.group,run:n(()=>this.toggleGrouping(),"run")},{id:"density",name:t.density==="compact"?"Comfortable density":"Compact density",hint:"Fit more items on screen",glyph:u.filter,run:n(()=>this.toggleDensity(),"run")},{id:"select",name:t.selectMode?"Leave multi-select":"Multi-select items",hint:"Act on several items at once",glyph:u.select,run:n(()=>this.toggleSelectMode(),"run")},{id:"archived",name:t.showArchived?"Hide archived items":"Show archived items",hint:"Include archived items in normal views",glyph:r("archive",{size:16}),run:n(()=>this.toggleArchived(),"run")},{id:"empty-archive",name:"Empty the archive",hint:"Permanently delete every archived item",glyph:r("trash",{size:16}),run:n(()=>this.emptyArchive(),"run")},{id:"favorites",name:"Show favorites",hint:"Jump to the starred items",glyph:r("star",{size:16}),run:n(()=>this.setTab("__fav"),"run")},{id:"archive",name:"Show archive",hint:"Items you archived rather than deleted",glyph:r("archive",{size:16}),run:n(()=>this.setTab("__archive"),"run")},{id:"collections",name:"Browse collections",hint:"Folders that group saved items",glyph:r("folder",{size:16}),run:n(()=>this.setTab("__collections"),"run")},{id:"shortcuts",name:"Keyboard shortcuts",hint:"Every key the panel understands",glyph:u.keyboard,run:n(()=>this.showShortcuts(),"run")},{id:"clear",name:"Clear filters",hint:"Back to every item, unfiltered",glyph:r("close",{size:16}),run:n(()=>this.clearFilters(),"run")}];return M().slice(0,8).forEach(i=>e.push({id:`tool:${i.tool_id}`,name:`Filter: ${i.tool_name}`,hint:`${i.count} item${i.count===1?"":"s"} saved from this tool`,glyph:r("externalLink",{size:16}),run:n(()=>this.filterByTool(i.tool_id),"run")})),J().slice(0,8).forEach(i=>e.push({id:`tag:${i.tag}`,name:`Filter: #${i.tag}`,hint:`${i.count} item${i.count===1?"":"s"} tagged`,glyph:r("pin",{size:16}),run:n(()=>this.filterByTag(i.tag),"run")})),e}_renderCommands(t){const e=this._commands().filter(i=>!t||i.name.toLowerCase().includes(t)||i.hint.toLowerCase().includes(t));if(this.toolbarCount.textContent="",!e.length){this.body.appendChild(this._emptyState({title:"No matching command",msg:"Type part of a command name, or clear the > to search items instead."}));return}this._cmdIndex=Math.min(this._cmdIndex,e.length-1),e.forEach((i,o)=>{const l=s("button",{class:`lk-cmd${o===this._cmdIndex?" lk-cmd-active":""}`,type:"button",onClick:n(()=>this._runCommand(i),"onClick")},s("span",{class:"lk-cmd-icon",html:i.glyph}),s("span",{class:"lk-cmd-body"},s("span",{class:"lk-cmd-name"},i.name),s("span",{class:"lk-cmd-hint"},i.hint)));this._cmdRows.push({cmd:i,row:l}),this.body.appendChild(l)})}_runCommand(t){this.searchInput.value="",this._state.query="",this._syncSearchClear(),this.render(),t.run()}_moveCommand(t){this._cmdRows.length&&(this._cmdIndex=(this._cmdIndex+t+this._cmdRows.length)%this._cmdRows.length,this._cmdRows.forEach(({row:e},i)=>{e.classList.toggle("lk-cmd-active",i===this._cmdIndex),i===this._cmdIndex&&e.scrollIntoView({block:"nearest"})}))}_onSearchKey(t){const e=this._state.query.trim().startsWith(">");if(e&&(t.key==="ArrowDown"||t.key==="ArrowUp"))t.preventDefault(),this._moveCommand(t.key==="ArrowDown"?1:-1);else if(e&&t.key==="Enter"){t.preventDefault();const i=this._cmdRows[this._cmdIndex];i&&this._runCommand(i.cmd)}else t.key==="ArrowDown"?(t.preventDefault(),this._tiles[0]?.focu
1s()):t.key==="Escape"&&this.searchInput.value&&(t.preventDefault(),t.stopPropagation(),this.searchInput.value="",this._state.query="",this._syncSearchClear(),this.render())}_bindKeyboard(){this.panel.addEventListener("keydown",t=>{if(t.key==="Escape"){if(document.querySelector(".aa-select__panel--open"))return;if(!this.panelOptions.hidden){t.stopPropagation(),this._togglePanelOptions(!1),this.panelOptionsBtn.focus({preventScroll:!0});return}if(this._selectMode){this.toggleSelectMode();return}this.toggle(!1);return}if(t.target===this.searchInput)return;if((t.key==="a"||t.key==="A")&&(t.ctrlKey||t.metaKey)&&this._selectMode){t.preventDefault(),this.selectAll();return}const e=this._tiles.indexOf(document.activeElement);if(e<0)return;const i=this._state.view==="list"?1:this._tilesPerRow();let o=-1;if(t.key==="ArrowRight")o=e+1;else if(t.key==="ArrowLeft")o=e-1;else if(t.key==="ArrowDown")o=e+i;else if(t.key==="ArrowUp")o=e-i;else if(t.key==="Home")o=0;else if(t.key==="End")o=this._tiles.length-1;else return;if(t.preventDefault(),o<0){this.searchInput.focus();return}this._tiles[Math.min(o,this._tiles.length-1)]?.focus()})}_tilesPerRow(){const t=this._tiles[0];if(!t)return 1;const e=this.body.clientWidth||1,i=t.offsetWidth||e;return Math.max(1,Math.round(e/(i+10)))}_bindDropImport(){let t=0;const e=n(i=>Array.from(i.dataTransfer?.types||[]).includes("Files"),"isFileDrag");this.panel.addEventListener("dragenter",i=>{e(i)&&(i.preventDefault(),t+=1,this.panel.classList.add("lk-dropping"))}),this.panel.addEventListener("dragover",i=>{e(i)&&i.preventDefault()}),this.panel.addEventListener("dragleave",()=>{t=Math.max(0,t-1),t||this.panel.classList.remove("lk-dropping")}),this.panel.addEventListener("drop",async i=>{if(!e(i))return;i.preventDefault(),t=0,this.panel.classList.remove("lk-dropping");const o=i.dataTransfer?.files?.[0];o&&await this._importFile(o)})}_toast(t,e="info"){try{if(typeof window.AALibrary?.toast=="function"){window.AALibrary.toast(t,e);return}}catch{}console.info("[LibraryKit]",t)}showShortcuts(){const t=st.map(([e,i])=>s("div",{class:"lk-keys-row"},s("span",{class:"lk-keys-combo"},e),s("span",{class:"lk-keys-what"},i)));this._sheet("Keyboard shortcuts",t)}_sheet(t,e,i){const o=s("div",{class:"lk-dialog-scrim"}),l=s("div",{class:"lk-dialog lk-dialog--sheet",role:"dialog","aria-modal":"true","aria-label":t},s("div",{class:"lk-status"},s("span",{class:"aa-kh-title"},t),s("button",{class:"lk-status-btn",type:"button","aria-label":"Close",html:r("close",{size:16}),onClick:n(()=>c(),"onClick")})),s("div",{class:"lk-dialog-body"},...e));function c(){o.remove(),document.removeEventListener("keydown",a,!0),i?.()}n(c,"close");function a(p){p.key==="Escape"&&(p.stopPropagation(),p.preventDefault(),c())}n(a,"onKey");const h=this.panel.getAttribute("data-kit-theme");return h&&(l.setAttribute("data-kit-theme",h),o.setAttribute("data-kit-theme",h)),o.addEventListener("click",p=>{p.target===o&&c()}),o.appendChild(l),document.body.appendChild(o),document.addEventListener("keydown",a,!0),l.querySelector("button")?.focus(),{close:c}}_confirm(t,e){return new Promise(i=>{const o=s("div",{class:"lk-dialog-scrim"}),l=s("div",{class:"lk-dialog",role:"alertdialog","aria-modal":"true"},s("div",{class:"lk-status"},s("span",{class:"aa-kh-title"},t)),s("p",{class:"lk-dialog-msg"},e)),c=n(m=>{o.remove(),document.removeEventListener("keydown",a,!0),i(m)},"done"),a=n(m=>{m.key==="Escape"&&(m.stopPropagation(),m.preventDefault(),c(!1))},"onKey"),h=s("button",{class:"lk-foot-btn",type:"button",html:"Cancel",onClick:n(()=>c(!1),"onClick")}),p=s("button",{class:"lk-foot-btn lk-foot-btn--danger",type:"button",html:`${r("trash",{size:14})} Delete`,onClick:n(()=>c(!0),"onClick")});l.appendChild(s("div",{class:"lk-footer lk-dialog-foot"},h,p));const y=this.panel.getAttribute("data-kit-theme");y&&(l.setAttribute("data-kit-theme",y),o.setAttribute("data-kit-theme",y)),o.addEventListener("click",m=>{m.target===o&&c(!1)}),o.appendChild(l),document.body.appendChild(o),document.addEventListener("keydown",a,!0),h.focus()})}toggle(t){const e=this.open,i=typeof t=="boolean"?t:!this.open;!e&&i&&document.activeElement instanceof HTMLElement&&(this._returnFocus=document.activeElement),this.open=i,this.panel.classList.toggle("lk-open",this.open),this.fab.setAttribute("aria-expanded",String(this.open)),this.fab.innerHTML=this.open?r("close",{size:22}):r("library",{size:22}),this.fab.appendChild(this.fabPip),this.fab.setAttribute("aria-label",this.open?"Close library":"Open library"),this.open?(this._announceKitOpen(),this.searchInput.value="",this._state.query="",this._syncSearchClear(),this.groupBtn.classList.toggle("is-on",this._state.group==="type"),this.render(),requestAnimationFrame(()=>this.searchInput.focus())):e&&(this._togglePanelOptions(!1),this.sortSelect?._aaSelectPicker?.close(),this._returnFocus?.isConnected&&this._returnFocus.focus({preventScroll:!0}),this._returnFocus=null)}openTo(t){t&&this.setTab(t),this.toggle(!0)}destroy(){this._offs?.forEach(t=>t?.()),this.body?.querySelectorAll?.("select").forEach(t=>t._aaSelectPicker?.destroy?.()),this._inlineView?.destroy?.(),this._inlineView=null,document.removeEventListener("pointerdown",this._onDocumentPointerDown,!0),this.panel?.remove(),this.backdrop?.remove(),this.fab?.remove()}}
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.