Spaces:
Running
Running
File size: 14,540 Bytes
6918275 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 | import { createStore } from "/js/AlpineStore.js";
import { fetchApi } from "/js/api.js";
import { store as imageViewerStore } from "../../modals/image-viewer/image-viewer-store.js";
const model = {
// State properties
attachments: [],
hasAttachments: false,
dragDropOverlayVisible: false,
async init() {
await this.initialize();
},
// Initialize the store
async initialize() {
// Setup event listeners for drag and drop
this.setupDragDropHandlers();
// Setup paste event listener for clipboard images
this.setupPasteHandler();
},
// Basic attachment management methods
addAttachment(attachment) {
// Validate for duplicates
if (this.validateDuplicates(attachment)) {
this.attachments.push(attachment);
this.updateAttachmentState();
}
},
removeAttachment(index) {
if (index >= 0 && index < this.attachments.length) {
this.attachments.splice(index, 1);
this.updateAttachmentState();
}
},
clearAttachments() {
this.attachments = [];
this.updateAttachmentState();
},
validateDuplicates(newAttachment) {
// Check if attachment already exists based on name and size
const isDuplicate = this.attachments.some(
(existing) =>
existing.name === newAttachment.name &&
existing.file &&
newAttachment.file &&
existing.file.size === newAttachment.file.size
);
return !isDuplicate;
},
updateAttachmentState() {
this.hasAttachments = this.attachments.length > 0;
},
// Drag drop overlay control methods
showDragDropOverlay() {
this.dragDropOverlayVisible = true;
},
hideDragDropOverlay() {
this.dragDropOverlayVisible = false;
},
isExternalFileDrag(event) {
return Array.from(event?.dataTransfer?.types || []).includes("Files");
},
// Setup drag and drop event handlers
setupDragDropHandlers() {
console.log("Setting up drag and drop handlers...");
let dragCounter = 0;
// Prevent default drag behaviors
["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
document.addEventListener(
eventName,
(e) => {
if (!this.isExternalFileDrag(e)) return;
e.preventDefault();
e.stopPropagation();
},
false
);
});
// Handle drag enter
document.addEventListener(
"dragenter",
(e) => {
if (!this.isExternalFileDrag(e)) return;
console.log("Drag enter detected");
dragCounter++;
if (dragCounter === 1) {
console.log("Showing drag drop overlay");
this.showDragDropOverlay();
}
},
false
);
// Handle drag leave
document.addEventListener(
"dragleave",
(e) => {
if (!this.isExternalFileDrag(e) && dragCounter === 0) return;
dragCounter--;
if (dragCounter === 0) {
this.hideDragDropOverlay();
}
},
false
);
// Handle drop
document.addEventListener(
"drop",
async (e) => {
if (!this.isExternalFileDrag(e)) return;
const dataTransfer = e.dataTransfer;
console.log("Drop detected with files:", dataTransfer?.files?.length || 0);
dragCounter = 0;
this.hideDragDropOverlay();
let files = [];
try {
files = await this.getDroppedFiles(dataTransfer);
} catch (error) {
console.error("Failed to read dropped files:", error);
files = Array.from(dataTransfer?.files || []);
}
this.handleFiles(files);
},
false
);
},
// Setup paste event handler for clipboard images
setupPasteHandler() {
console.log("Setting up paste handler...");
document.addEventListener("paste", (e) => {
// console.log("Paste event detected, target:", e.target.id);
if (
e.target.id !== "chat-input" &&
e.target.id !== "full-screen-input"
) return;
const items = e.clipboardData.items;
let imageFound = false;
console.log("Checking clipboard items:", items.length);
// First, check if there are any images in the clipboard
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.type.indexOf("image") !== -1) {
imageFound = true;
const blob = item.getAsFile();
if (blob) {
e.preventDefault(); // Prevent default paste behavior for images
this.handleClipboardImage(blob);
console.log("Image detected in clipboard, processing...");
}
break; // Only handle the first image found
}
}
// If no images found and we're in an input field, let normal text paste happen
if (
!imageFound &&
(e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA")
) {
console.log(
"No images in clipboard, allowing normal text paste in input field"
);
return;
}
// If no images found and not in input field, do nothing
if (!imageFound) {
console.log("No images in clipboard");
}
});
},
// Handle clipboard image pasting
async handleClipboardImage(blob) {
try {
// Generate unique filename
const guid = this.generateGUID();
const filename = `clipboard-${guid}.png`;
// Create file object from blob
const file = new File([blob], filename, { type: "image/png" });
// Create attachment object
const attachment = {
file: file,
type: "image",
name: filename,
extension: "png",
displayInfo: this.getAttachmentDisplayInfo(file),
};
// Read as data URL for preview
const reader = new FileReader();
reader.onload = (e) => {
attachment.url = e.target.result;
this.addAttachment(attachment);
};
reader.readAsDataURL(file);
// Show success feedback
console.log("Clipboard image pasted successfully:", filename);
} catch (error) {
console.error("Failed to handle clipboard image:", error);
}
},
// Update handleFileUpload to use the attachments store
handleFileUpload(event) {
const files = event.target.files;
this.handleFiles(files);
event.target.value = ""; // clear uploader selection to fix issue where same file is ignored the second time
},
async getDroppedFiles(dataTransfer) {
const items = Array.from(dataTransfer?.items || []);
const entries = items
.map((item) =>
typeof item.webkitGetAsEntry === "function"
? item.webkitGetAsEntry()
: null
)
.filter(Boolean);
if (!entries.length) {
return Array.from(dataTransfer?.files || []);
}
const nested = await Promise.all(
entries.map((entry) => this.readEntryFiles(entry))
);
const files = nested.flat();
return files.length ? files : Array.from(dataTransfer?.files || []);
},
async readEntryFiles(entry) {
if (entry.isFile) {
return await new Promise((resolve, reject) => {
entry.file(
(file) => resolve([file]),
(error) => reject(error)
);
});
}
if (!entry.isDirectory) return [];
const reader = entry.createReader();
const childEntries = await this.readAllDirectoryEntries(reader);
const nested = await Promise.all(
childEntries.map((child) => this.readEntryFiles(child))
);
return nested.flat();
},
async readAllDirectoryEntries(reader) {
const entries = [];
return await new Promise((resolve, reject) => {
const readBatch = () => {
reader.readEntries(
(batch) => {
if (!batch.length) {
resolve(entries);
return;
}
entries.push(...batch);
readBatch();
},
(error) => reject(error)
);
};
readBatch();
});
},
// File handling logic (moved from index.js)
handleFiles(files) {
const fileList = Array.from(files || []);
console.log("handleFiles called with", fileList.length, "files");
fileList.forEach((file) => {
if (!file?.name) return;
console.log("Processing file:", file.name, file.type);
const ext = file.name.split(".").pop().toLowerCase();
const isImage = ["jpg", "jpeg", "png", "bmp", "gif", "webp", "svg"].includes(
ext
);
const attachment = {
file: file,
type: isImage ? "image" : "file",
name: file.name,
extension: ext,
displayInfo: this.getAttachmentDisplayInfo(file),
};
if (isImage) {
// Read image as data URL for preview
const reader = new FileReader();
reader.onload = (e) => {
attachment.url = e.target.result;
this.addAttachment(attachment);
};
reader.readAsDataURL(file);
} else {
// For non-image files, add directly
this.addAttachment(attachment);
}
});
},
// Get attachments for sending message
getAttachmentsForSending() {
return this.attachments.map((attachment) => {
if (attachment.type === "image") {
return {
...attachment,
url: URL.createObjectURL(attachment.file),
};
} else {
return {
...attachment,
};
}
});
},
// Generate server-side API URL for file (for device sync)
getServerImgUrl(filename) {
return `/api/image_get?path=/a0/usr/uploads/${encodeURIComponent(filename)}`;
},
getServerFileUrl(filename) {
return `/a0/usr/uploads/${encodeURIComponent(filename)}`;
},
// Check if file is an image based on extension
isImageFile(filename) {
const imageExtensions = ["jpg", "jpeg", "png", "gif", "bmp", "webp", "svg"];
const extension = filename.split(".").pop().toLowerCase();
return imageExtensions.includes(extension);
},
// Get attachment preview URL (server URL for persistence, blob URL for current session)
getAttachmentPreviewUrl(attachment) {
// If attachment has a name and we're dealing with a server-stored file
if (typeof attachment === "string") {
// attachment is just a filename (from loaded chat)
return this.getServerImgUrl(attachment);
} else if (attachment.name && attachment.file) {
// attachment is an object from current session
if (attachment.type === "image") {
// For images, use blob URL for current session preview
return attachment.url || URL.createObjectURL(attachment.file);
} else {
// For non-image files, use server URL to get appropriate icon
return this.getServerImgUrl(attachment.name);
}
}
return null;
},
getFilePreviewUrl(filename) {
const extension = filename.split(".").pop().toLowerCase();
const types = {
// Archive files
zip: "archive",
rar: "archive",
"7z": "archive",
tar: "archive",
gz: "archive",
// Document files
pdf: "document",
doc: "document",
docx: "document",
txt: "document",
rtf: "document",
odt: "document",
// Code files
py: "code",
js: "code",
html: "code",
css: "code",
json: "code",
xml: "code",
md: "code",
yml: "code",
yaml: "code",
sql: "code",
sh: "code",
bat: "code",
// Spreadsheet files
xls: "document",
xlsx: "document",
csv: "document",
// Presentation files
ppt: "document",
pptx: "document",
odp: "document",
};
const type = types[extension] || "file";
return `/public/${type}.svg`;
},
// Enhanced method to get attachment display info for UI
getAttachmentDisplayInfo(attachment) {
if (typeof attachment === "string") {
// attachment is filename only (from persistent storage)
const filename = attachment;
const extension = filename.split(".").pop();
const isImage = this.isImageFile(filename);
const previewUrl = isImage
? this.getServerImgUrl(filename)
: this.getFilePreviewUrl(filename);
return {
filename: filename,
extension: extension.toUpperCase(),
isImage: isImage,
previewUrl: previewUrl,
clickHandler: () => {
if (this.isImageFile(filename)) {
imageViewerStore.open(this.getServerImgUrl(filename), { name: filename });
} else {
this.downloadAttachment(filename);
}
},
};
} else {
// attachment is object (from current session)
const isImage = this.isImageFile(attachment.name);
const filename = attachment.name;
const extension = filename.split(".").pop() || "";
const previewUrl = isImage
? this.getServerImgUrl(attachment.name)
: this.getFilePreviewUrl(attachment.name);
return {
filename: filename,
extension: extension.toUpperCase(),
isImage: attachment.type === "image",
previewUrl: previewUrl,
clickHandler: () => {
if (attachment.type === "image") {
const imageUrl = this.getServerImgUrl(attachment.name);
imageViewerStore.open(imageUrl, { name: attachment.name });
} else {
this.downloadAttachment(attachment.name);
}
},
};
}
},
async downloadAttachment(filename) {
try {
const path = this.getServerFileUrl(filename);
const response = await fetchApi("/download_work_dir_file?path=" + path);
if (!response.ok) {
throw new Error("Network response was not ok");
}
const blob = await response.blob();
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(link.href);
} catch (error) {
window.toastFetchError("Error downloading file", error);
alert("Error downloading file");
}
},
// Generate GUID for unique filenames
generateGUID() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
/[xy]/g,
function (c) {
const r = (Math.random() * 16) | 0;
const v = c == "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
}
);
},
};
const store = createStore("chatAttachments", model);
export { store };
|