-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1 lines (1 loc) · 7.63 KB
/
Copy pathcontent.js
File metadata and controls
1 lines (1 loc) · 7.63 KB
1
import{l as e}from"./chunks/extension-settings-fQcMQRZb.js";import{p as t}from"./chunks/image-processor-wCF_d_d4.js";class a{imageCache=new Map;highlightTimeout=null;constructor(){this.init()}init(){chrome.runtime.onMessage.addListener((e,t,a)=>(this.handleMessage(e,a),!0)),this.scanPageImages(),this.observeImageChanges(),document.addEventListener("keydown",e=>{(e.ctrlKey||e.metaKey)&&e.shiftKey&&"I"===e.key&&(e.preventDefault(),chrome.runtime.sendMessage({type:"OPEN_EXTENSION"}))}),console.log("[Solaxnm] Content script loaded and initialized")}handleMessage(e,t){if("type"in e&&"GET_PAGE_IMAGES"===e.type)return this.getPageImages().then(e=>t({success:!0,images:e})).catch(e=>t({success:!1,error:e.message})),!0;if("type"in e&&"HIGHLIGHT_IMAGE"===e.type)return this.highlightImageBySrc(e.src).then(e=>t({success:e})).catch(()=>t({success:!1})),!0;if("action"in e)switch(e.action){case"processImageFromContext":this.processImageFromContext(e.imageUrl).then(e=>t({success:!0,imageData:e})).catch(e=>t({success:!1,error:e.message}));break;case"exportImageDirect":this.exportImageDirect(e.imageUrl,e.format).then(()=>t({success:!0})).catch(e=>t({success:!1,error:e.message}));break;case"extractImages":this.extractPageImages().then(e=>t({success:!0,images:e})).catch(e=>t({success:!1,error:e.message}));break;case"scanPage":this.scanPageImages().then(e=>t({success:!0,...e})).catch(e=>t({success:!1,error:e.message}));break;case"ping":t({success:!0});break;default:t({success:!1,error:"Unknown action or type"})}else t({success:!1,error:"Unknown action or type"})}async getPageImages(){return Array.from(document.querySelectorAll("img")).filter(e=>e.complete&&e.naturalWidth>0).map(e=>({src:e.src,alt:e.alt||"",width:e.naturalWidth,height:e.naturalHeight})).filter(e=>e.width>=100&&e.height>=100)}async highlightImageBySrc(e){const t=new URL(e,location.href).href,a=Array.from(document.querySelectorAll("img")).find(e=>e.src===t);return!!a&&(this.clearHighlight(),this.highlightTimeout&&clearTimeout(this.highlightTimeout),a.style.outline="4px solid #7c3aed",a.style.outlineOffset="4px",a.setAttribute("data-solaxnm-highlight","true"),a.scrollIntoView({behavior:"smooth",block:"center"}),this.highlightTimeout=setTimeout(()=>{this.clearHighlight(),this.highlightTimeout=null},2e3),!0)}clearHighlight(){const e=document.querySelector("[data-solaxnm-highlight]");e instanceof HTMLElement&&(e.style.outline="",e.style.outlineOffset="",e.removeAttribute("data-solaxnm-highlight"))}async processImageFromContext(e){const t=this.imageCache.get(e);if(t)return t;try{const t=await this.loadAndProcessImage(e);return this.imageCache.set(e,t),t}catch(a){const e=a instanceof Error?a.message:"Unknown error";throw new Error(`Failed to process image: ${e}`)}}loadAndProcessImage(e){return new Promise((t,a)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>{try{const n=document.createElement("canvas"),i=n.getContext("2d");if(!i)return void a(new Error("Canvas context unavailable"));n.width=r.naturalWidth,n.height=r.naturalHeight,i.drawImage(r,0,0);const s=n.toDataURL("image/png");t({src:e,dataUrl:s,width:r.naturalWidth,height:r.naturalHeight,aspectRatio:r.naturalWidth/r.naturalHeight,fileSize:this.estimateFileSize(s),timestamp:Date.now(),metadata:this.extractImageMetadata(r)})}catch(n){const e=n instanceof Error?n.message:"Unknown error";a(new Error(`Canvas processing failed: ${e}`))}},r.onerror=()=>a(new Error("Failed to load image from URL")),r.src=e})}async exportImageDirect(a,r){const n=await e(),i=new Image;return i.crossOrigin="anonymous",new Promise((e,s)=>{i.onload=()=>{try{const o=document.createElement("canvas"),c=o.getContext("2d");if(!c)return void s(new Error("Canvas context unavailable"));o.width=i.naturalWidth,o.height=i.naturalHeight,c.drawImage(i,0,0);const g=this.getMimeType(r),h=this.getQualityForFormat(r);t(o,r,n.transparentBackgroundColor).toBlob(t=>{t?(this.downloadBlob(t,r,a),e()):s(new Error("Failed to create blob"))},g,h)}catch(o){s(o)}},i.onerror=()=>s(new Error("Failed to load image for export")),i.src=a})}downloadBlob(e,t,a){const r=URL.createObjectURL(e),n=document.createElement("a");n.href=r,n.download=this.extractFilenameFromUrl(a,t),document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(r),1e3)}extractFilenameFromUrl(e,t){const a=this.getExtension(t);try{if(e.startsWith("data:"))return`image.${a}`;const t=new URL(e,location.href),r=decodeURIComponent(t.pathname).split("/").filter(Boolean),n=r[r.length-1]?.split("?")[0]||"image",i=n.match(/\.([^.]+)$/)?.[1]?.toLowerCase();if(("jpeg"===i?"jpg":i)===a)return n;return`${n.replace(/\.[^/.]+$/,"")||n}.${a}`}catch{return`image.${a}`}}async extractPageImages(){const e=[],t=document.querySelectorAll("img, svg, picture source, [style*='background-image']");for(const r of Array.from(t))try{const t=await this.extractImageInfo(r);t&&this.isValidImage(t)&&e.push(t)}catch(a){console.warn("Could not extract image:",a)}return e.sort((e,t)=>t.width*t.height-e.width*e.height)}async extractImageInfo(e){return e instanceof HTMLImageElement?this.extractFromImg(e):e instanceof SVGSVGElement?this.extractFromSvg(e):e instanceof HTMLSourceElement?this.extractFromSource(e):this.extractFromBackgroundImage(e)}extractFromImg(e){return!e.src||e.naturalWidth<50||e.naturalHeight<50?null:{src:e.src,alt:e.alt||"Image",width:e.naturalWidth,height:e.naturalHeight,aspectRatio:e.naturalWidth/e.naturalHeight,type:"img",element:e}}extractFromSvg(e){const t=e.getBoundingClientRect();if(t.width<50||t.height<50)return null;const a=(new XMLSerializer).serializeToString(e);return{src:`data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(a)))}`,alt:e.getAttribute("aria-label")||"SVG Image",width:t.width,height:t.height,aspectRatio:t.width/t.height,type:"svg",element:e}}extractFromSource(e){if(!e.srcset)return null;return{src:e.srcset.split(",")[0].trim().split(" ")[0],alt:"Picture Source",width:0,height:0,aspectRatio:0,type:"source",element:e}}extractFromBackgroundImage(e){const t=window.getComputedStyle(e).backgroundImage;if(!t||"none"===t)return null;const a=t.match(/url\(['"]?([^'"]+)['"]?\)/);if(!a)return null;const r=e.getBoundingClientRect();return r.width<50||r.height<50?null:{src:a[1],alt:"Background Image",width:r.width,height:r.height,aspectRatio:r.width/r.height,type:"background",element:e}}isValidImage(e){return null!==e&&Boolean(e.src)&&e.width>0&&e.height>0&&e.width*e.height>2500}async scanPageImages(){const e=await this.extractPageImages();return{images:e,stats:{totalImages:e.length,largeImages:e.filter(e=>e.width>500&&e.height>500).length,svgImages:e.filter(e=>"svg"===e.type).length,backgroundImages:e.filter(e=>"background"===e.type).length}}}observeImageChanges(){new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;"IMG"===t.tagName||"SVG"===t.tagName?this.handleNewImage(t):t.querySelectorAll("img, svg").forEach(e=>this.handleNewImage(e))})})}).observe(document.body,{childList:!0,subtree:!0})}handleNewImage(e){e instanceof HTMLImageElement&&e.src&&this.imageCache.has(e.src)&&this.imageCache.delete(e.src)}extractImageMetadata(e){return{naturalWidth:e.naturalWidth,naturalHeight:e.naturalHeight,displayWidth:e.width,displayHeight:e.height,complete:e.complete,crossOrigin:e.crossOrigin,currentSrc:e.currentSrc,loading:e.loading}}estimateFileSize(e){const t=e.split(",")[1]?.length||0;return Math.round(.75*t)}getMimeType(e){return{jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",webp:"image/webp"}[e]||"image/png"}getQualityForFormat(e){return["jpeg","jpg","webp"].includes(e)?.9:void 0}getExtension(e){return{jpeg:"jpg",jpg:"jpg",png:"png",webp:"webp"}[e]||"png"}}const r=window;r.__solanamContentScriptLoaded||(r.__solanamContentScriptLoaded=!0,new a);