| 1 | import { IIdeMessenger } from "../../../../context/IdeMessenger"; |
| 2 | |
| 3 | const IMAGE_RESOLUTION = 1024; |
| 4 | |
| 5 | /** |
| 6 | * Extracts the file path from a VS Code resource URL |
| 7 | * Example: "https://file+.vscode-resource.vscode-cdn.net/Users/path/to/file.jpg?version=123" |
| 8 | * Returns: "/Users/path/to/file.jpg" |
| 9 | */ |
| 10 | export function extractFilePathFromVSCodeResourceUrl( |
| 11 | url: string, |
| 12 | ): string | null { |
| 13 | try { |
| 14 | const urlObj = new URL(url); |
| 15 | if (urlObj.hostname === "file+.vscode-resource.vscode-cdn.net") { |
| 16 | return decodeURIComponent(urlObj.pathname); |
| 17 | } |
| 18 | return null; |
| 19 | } catch (error) { |
| 20 | console.error("Error parsing VS Code resource URL:", error); |
| 21 | return null; |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * Handles VS Code resource URLs by converting them to data URLs |
| 27 | * @param ideMessenger - The IDE messenger to communicate with VS Code |
| 28 | * @param vscodeResourceUrl - The VS Code resource URL |
| 29 | * @returns Promise with the data URL if successful, undefined otherwise |
| 30 | */ |
| 31 | export async function handleVSCodeResourceUrl( |
| 32 | ideMessenger: IIdeMessenger, |
| 33 | vscodeResourceUrl: string, |
| 34 | ): Promise<string | undefined> { |
| 35 | const filepath = extractFilePathFromVSCodeResourceUrl(vscodeResourceUrl); |
| 36 | if (!filepath) { |
| 37 | console.error( |
| 38 | "Could not extract file path from VS Code resource URL:", |
| 39 | vscodeResourceUrl, |
| 40 | ); |
| 41 | return undefined; |
| 42 | } |
| 43 | |
| 44 | console.log("Extracted filepath:", filepath); |
| 45 | |
| 46 | try { |
| 47 | console.log("Requesting readFileAsDataUrl for filepath:", filepath); |
| 48 | console.log("About to call ideMessenger.request..."); |
| 49 | |
| 50 | // Add a timeout wrapper to prevent hanging |
| 51 | const timeoutPromise = new Promise((_, reject) => |
| 52 | setTimeout( |
| 53 | () => reject(new Error("Request timeout after 10 seconds")), |
| 54 | 10000, |
| 55 | ), |
| 56 | ); |
| 57 | |
| 58 | const requestPromise = ideMessenger.request("readFileAsDataUrl", { |
| 59 | filepath, |
| 60 | }); |
| 61 | |
| 62 | console.log("Request promise created, waiting for response..."); |
| 63 | |
| 64 | const response = await Promise.race([requestPromise, timeoutPromise]); |
| 65 | |
| 66 | console.log("Got response from ideMessenger.request:", response); |
| 67 | console.log("Response type:", typeof response); |
| 68 | |
| 69 | // The response should be a WebviewSingleMessage which has status and content |
| 70 | if (response && typeof response === "object" && "status" in response) { |
| 71 | const typedResponse = response as { |
| 72 | status: string; |
| 73 | error?: string; |
| 74 | content?: string; |
| 75 | }; |
| 76 | if (typedResponse.status === "error") { |
| 77 | console.error("Error reading file as data URL:", typedResponse.error); |
| 78 | return undefined; |
| 79 | } |
| 80 | |
| 81 | if (typedResponse.status === "success" && typedResponse.content) { |
| 82 | const dataUrl = typedResponse.content; |
| 83 | console.log( |
| 84 | "Successfully got data URL for file, content length:", |
| 85 | dataUrl.length, |
| 86 | ); |
| 87 | return dataUrl; |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | // If response is directly a string (shouldn't happen based on protocol but just in case) |
| 92 | if (typeof response === "string") { |
| 93 | console.log("Got direct string response, length:", response.length); |
| 94 | return response; |
| 95 | } |
| 96 | |
| 97 | console.error("Unexpected response format:", response); |
| 98 | return undefined; |
| 99 | } catch (error) { |
| 100 | console.error("Exception caught when reading file as data URL:", error); |
| 101 | console.error( |
| 102 | "Error stack:", |
| 103 | error instanceof Error ? error.stack : "No stack trace", |
| 104 | ); |
| 105 | return undefined; |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * Extracts VS Code resource URL from HTML content |
| 111 | * @param html - HTML string that may contain VS Code resource URLs |
| 112 | * @returns The VS Code resource URL if found, null otherwise |
| 113 | */ |
| 114 | export function extractVSCodeResourceUrlFromHtml(html: string): string | null { |
| 115 | try { |
| 116 | // Create a temporary DOM element to parse the HTML |
| 117 | const tempDiv = document.createElement("div"); |
| 118 | tempDiv.innerHTML = html; |
| 119 | |
| 120 | // Look for img tags with VS Code resource URLs |
| 121 | const imgTags = tempDiv.querySelectorAll("img"); |
| 122 | for (const img of imgTags) { |
| 123 | const src = img.getAttribute("src"); |
| 124 | if (src && src.includes("file+.vscode-resource.vscode-cdn.net")) { |
| 125 | return src; |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | return null; |
| 130 | } catch (error) { |
| 131 | console.error("Error parsing HTML for VS Code resource URL:", error); |
| 132 | return null; |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | /** |
| 137 | * Handles HTML content that contains VS Code resource URLs and converts them to usable data URLs |
| 138 | * @param ideMessenger - The IDE messenger to communicate with VS Code |
| 139 | * @param html - HTML string containing VS Code resource URLs |
| 140 | * @returns Promise with the data URL if successful, undefined otherwise |
| 141 | */ |
| 142 | export async function handleVSCodeResourceFromHtml( |
| 143 | ideMessenger: IIdeMessenger, |
| 144 | html: string, |
| 145 | ): Promise<string | undefined> { |
| 146 | console.log("Processing HTML for VS Code resource URL:", html); |
| 147 | |
| 148 | const vscodeResourceUrl = extractVSCodeResourceUrlFromHtml(html); |
| 149 | if (!vscodeResourceUrl) { |
| 150 | console.log("No VS Code resource URL found in HTML"); |
| 151 | return undefined; |
| 152 | } |
| 153 | |
| 154 | console.log("Found VS Code resource URL:", vscodeResourceUrl); |
| 155 | return await handleVSCodeResourceUrl(ideMessenger, vscodeResourceUrl); |
| 156 | } |
| 157 | |
| 158 | export function getDataUrlForFile( |
| 159 | file: File, |
| 160 | img: HTMLImageElement, |
| 161 | ): string | undefined { |
| 162 | const targetWidth = IMAGE_RESOLUTION; |
| 163 | const targetHeight = IMAGE_RESOLUTION; |
| 164 | const scaleFactor = Math.min( |
| 165 | targetWidth / img.width, |
| 166 | targetHeight / img.height, |
| 167 | ); |
| 168 | |
| 169 | const canvas = document.createElement("canvas"); |
| 170 | canvas.width = img.width * scaleFactor; |
| 171 | canvas.height = img.height * scaleFactor; |
| 172 | |
| 173 | const ctx = canvas.getContext("2d"); |
| 174 | if (!ctx) { |
| 175 | console.error("Error getting image data url: 2d context not found"); |
| 176 | return; |
| 177 | } |
| 178 | ctx.drawImage(img, 0, 0, canvas.width, canvas.height); |
| 179 | |
| 180 | const downsizedDataUrl = canvas.toDataURL("image/jpeg", 0.7); |
| 181 | return downsizedDataUrl; |
| 182 | } |
| 183 | |
| 184 | export async function handleImageFile( |
| 185 | ideMessenger: IIdeMessenger, |
| 186 | file: File, |
| 187 | ): Promise<[HTMLImageElement, string] | undefined> { |
| 188 | let filesize = file.size / 1024 / 1024; // filesize in MB |
| 189 | // check image type and size |
| 190 | if ( |
| 191 | [ |
| 192 | "image/jpeg", |
| 193 | "image/jpg", |
| 194 | "image/png", |
| 195 | "image/gif", |
| 196 | "image/svg", |
| 197 | "image/webp", |
| 198 | ].includes(file.type) && |
| 199 | filesize < 10 |
| 200 | ) { |
| 201 | // check dimensions |
| 202 | let _URL = window.URL || window.webkitURL; |
| 203 | let img = new window.Image(); |
| 204 | img.src = _URL.createObjectURL(file); |
| 205 | |
| 206 | return await new Promise((resolve) => { |
| 207 | img.onload = function () { |
| 208 | const dataUrl = getDataUrlForFile(file, img); |
| 209 | if (!dataUrl) { |
| 210 | return; |
| 211 | } |
| 212 | |
| 213 | let image = new window.Image(); |
| 214 | image.src = dataUrl; |
| 215 | image.onload = function () { |
| 216 | resolve([image, dataUrl]); |
| 217 | }; |
| 218 | }; |
| 219 | }); |
| 220 | } else { |
| 221 | ideMessenger.post("showToast", [ |
| 222 | "error", |
| 223 | "Images need to be in jpg or png format and less than 10MB in size.", |
| 224 | ]); |
| 225 | } |
| 226 | } |