105 lines
3 KiB
JavaScript
105 lines
3 KiB
JavaScript
const ImageDisplay = globalThis.ImageDisplay ?? (globalThis.ImageDisplay = {});
|
|
|
|
ImageDisplay.utilities = {
|
|
fileInput: document.getElementById('image'),
|
|
image: document.getElementById('imageDisplay'),
|
|
captionInput: document.getElementById('caption'),
|
|
removeButton: document.getElementById('remove-inventory-image'),
|
|
imageIdInput: document.getElementById('image_id'),
|
|
|
|
// set when user selects a new file
|
|
_dirty: false,
|
|
_removed: false,
|
|
|
|
onAddButtonClick() {
|
|
this.fileInput.click();
|
|
},
|
|
|
|
onRemoveButtonClick() {
|
|
// Clear preview back to placeholder
|
|
this.image.src = this.image.dataset.placeholder || this.image.src;
|
|
this.fileInput.value = '';
|
|
this._dirty = false;
|
|
this._removed = true;
|
|
this.imageIdInput.value = '';
|
|
this.removeButton.classList.add('d-none');
|
|
},
|
|
|
|
onFileChange() {
|
|
const [file] = this.fileInput.files;
|
|
|
|
if (!file) {
|
|
toastMessage('No file selected!', 'danger');
|
|
return;
|
|
}
|
|
|
|
if (!file.type.startsWith("image")) {
|
|
toastMessage('Unsupported file type!', 'danger')
|
|
this.fileInput.value = '';
|
|
return;
|
|
}
|
|
|
|
const url = URL.createObjectURL(file);
|
|
this.image.src = url;
|
|
|
|
if (this.removeButton) {
|
|
this.removeButton.classList.remove('d-none');
|
|
}
|
|
|
|
this._dirty = true;
|
|
this._removed = false;
|
|
},
|
|
|
|
async uploadIfChanged() {
|
|
// If no changes to image, do nothing
|
|
if (!this._dirty && !this._removed) return null;
|
|
|
|
// Removed but not replaced: tell backend to clear image_id
|
|
if (this._removed) {
|
|
return { remove: true };
|
|
}
|
|
|
|
const [file] = this.fileInput.files;
|
|
if (!file) return null;
|
|
|
|
if(!window.IMAGE_UPLOAD_URL) {
|
|
toastMessage('IMAGE_UPLOAD_URL not set', 'danger');
|
|
return null;
|
|
}
|
|
|
|
const fd = new FormData();
|
|
fd.append('image', file);
|
|
if (this.captionInput) {
|
|
fd.append('caption', this.captionInput.value || '');
|
|
}
|
|
if (window.IMAGE_OWNER_MODEL) {
|
|
fd.append('model', window.IMAGE_OWNER_MODEL);
|
|
}
|
|
if (this.imageIdInput && this.imageIdInput.value) {
|
|
fd.append('image_id', this.imageIdInput.value);
|
|
}
|
|
|
|
const res = await fetch(window.IMAGE_UPLOAD_URL, {
|
|
method: 'POST',
|
|
body: fd,
|
|
credentials: 'same-origin',
|
|
});
|
|
|
|
const data = await res.json();
|
|
if (!res.ok || data.status !== 'success') {
|
|
toastMessage(data.error || 'Image upload failed.', 'danger');
|
|
throw new Error(data.error || 'Image upload failed.');
|
|
}
|
|
|
|
// Update local state
|
|
this.imageIdInput.value = data.id;
|
|
this._dirty = false;
|
|
this._removed = false;
|
|
|
|
return {
|
|
id: data.id,
|
|
filename: data.filename,
|
|
url: data.url,
|
|
};
|
|
},
|
|
};
|