91 lines
2.8 KiB
JavaScript
91 lines
2.8 KiB
JavaScript
"use strict";
|
|
|
|
import React, { useState, useRef } from "react";
|
|
import * as ReactDOM from "react-dom/client";
|
|
import * as f from "/js/functions";
|
|
|
|
const avatar_cropper = document.querySelector("#avatar-cropper");
|
|
const avatar_selector = document.querySelector("#avatar-selector");
|
|
const button_select_avatar = document.querySelector("#select-avatar");
|
|
const root = ReactDOM.createRoot(avatar_cropper);
|
|
|
|
if (!window.a) {
|
|
window.a = require("/js/index");
|
|
}
|
|
|
|
export let crop;
|
|
export let img_to_crop;
|
|
|
|
let avatar_selector_on_file_lambda = () => {
|
|
if (avatar_selector.files && avatar_selector.files.length > 0) {
|
|
const reader = new FileReader();
|
|
reader.addEventListener("load", () => {
|
|
const image = new Image();
|
|
// We use the event listener load to check if it is a valid image.
|
|
// This check has to be repeated in the server of course.
|
|
image.addEventListener("load", () => {
|
|
avatar_cropper.style.display = "block";
|
|
const local_image_to_crop = document.createElement("img");
|
|
local_image_to_crop.src = reader.result?.toString();
|
|
img_to_crop = local_image_to_crop;
|
|
if (img_to_crop.width < 50 || img_to_crop.height < 50) {
|
|
alert('El avatar es demasiado pequeño, busca un imagen de al menos 50x50 pixeles.');
|
|
return true;
|
|
}
|
|
root.render(
|
|
React.createElement(f.AvatarCropper, {
|
|
src: reader.result?.toString() || "",
|
|
onStart: (c) => {
|
|
crop = c;
|
|
button_select_avatar.removeAttribute("disabled");
|
|
},
|
|
onChange: (c) => {
|
|
crop = c;
|
|
button_select_avatar.removeAttribute("disabled");
|
|
},
|
|
onLoad: (c) => {
|
|
crop = c;
|
|
button_select_avatar.removeAttribute("disabled");
|
|
},
|
|
onComplete: (c) => {
|
|
crop = c;
|
|
button_select_avatar.removeAttribute("disabled");
|
|
},
|
|
})
|
|
);
|
|
});
|
|
image.addEventListener("error", () => {
|
|
alert("No parece que esto sea una imagen.");
|
|
});
|
|
image.src = reader.result?.toString();
|
|
});
|
|
reader.readAsDataURL(avatar_selector.files[0]);
|
|
}
|
|
};
|
|
|
|
avatar_selector_on_file_lambda();
|
|
avatar_selector.addEventListener("change", avatar_selector_on_file_lambda);
|
|
|
|
button_select_avatar.addEventListener("click", () => {
|
|
if (img_to_crop.src == null || crop == null) {
|
|
console.log("Still not ready to transmit");
|
|
}
|
|
const form_data = new FormData();
|
|
f.blobImgCrop(img_to_crop, crop).then((result) => {
|
|
form_data.append('file', result);
|
|
fetch('/usuario/actualizar-avatar', {
|
|
method: 'POST',
|
|
body: form_data,
|
|
}).then((response) => {
|
|
if (response.ok) {
|
|
window.location = '/perfil';
|
|
} else {
|
|
response.json().then((object) => {
|
|
alert(object.description);
|
|
});
|
|
}
|
|
});
|
|
});
|
|
return false;
|
|
});
|