/**
* Photo selector that interacts with the ModalPopup to allow uploading a new photo OR search for an existing photo
*/
class File_Selector extends Autowire {
/**
* setup the image node to show the modal when clicked
*/
async onclick(event){
const node = document.querySelector('.ModalPopup');
const modal = new ModalPopup(node);
// console.log(modal);
// console.log(node);
// setup the forms in the modal
// const photosearch = await modal.getJson('/files/search/?theme=json');
const upload = await modal.getJson('/files/upload-v2/?theme=json&status=public');
modal.content = upload.content;
// photosearch.content
// + upload.content;
// add upload script to document
const upload_script = document.createElement('script');
upload_script.src = upload.scripts[0];
modal.content_node.insertBefore(upload_script,modal.content_node.children[0]);
const search_script = document.createElement('script');
search_script.src = upload.scripts[1];
modal.content_node.insertBefore(search_script,modal.content_node.children[0]);
// console.log("modal.show()");
// add search script to document
// const search_script = document.createElement('script');
// search_script.src = photosearch.scripts[0];
// modal.content_node.insertBefore(search_script,modal.content_node.children[0]);
// console.log("modal.show()");
modal.show();
// add a special input that instructs the photo upload route to return json row instead of html page
const json_response = document.createElement('input');
json_response.name = '-response_type-';
json_response.value = 'json';
json_response.type = 'hidden';
modal.forms[1].insertBefore(json_response,null);
// setup onsubmit handlers
modal.handleForm(modal.forms[1], this.photoSelected.bind(this));
modal.handleForm(modal.forms[0], this.photoSelected.bind(this));
// submit form when file input changes
// This is required due to a bug(?) in Firefox that does not persist File objects after `paste` events when displayed in the modal.
// bug noted dec 22, 2022
const file_input = modal.forms[1].querySelector('input[type="file"]');
file_input.addEventListener('change',
function (e){
modal.forms[1].querySelector('input[type="submit"]').click();
}
);
}
/**
* update the `img.src` and the value of the photo_id input
* @param modal the ModalPopup instance
* @param response a string response from submitting the form through javascript
*/
photoSelected(modal, response){
const json = JSON.parse(response);
const id = json.id;
const url = json.url;
this.n.src = url;
this.n.parentNode.querySelector('input').value = id;
modal.hide();
}
}
File_Selector.aw();