/*eslint no-console: "off"*/ /** * Save a piece of text to file as if it was downloaded * @param {string} filename * @param {string} text * @param {string} type */ export function download(filename, text, type) { if(undefined == type) { type = "text/plain"; } var pom = document.createElement('a'); pom.setAttribute('href', 'data:'+type+';charset=utf-8,' + encodeURIComponent(text)); pom.setAttribute('download', filename); if (document.createEvent) { var event = document.createEvent('MouseEvents'); event.initEvent('click', true, true); pom.dispatchEvent(event); } else { pom.click(); } } /** * This callback type is called `requestCallback` and is displayed as a global symbol. * * @callback fileOpenedCallback * @param {File} file File name * @param {string} content File Contents */ /** * Open a file from disk and read its contents * @param {fileOpenedCallback} onready Callback to run when file is opened * @param {Array} accept Array of mime types that the file dialog will accept */ export function upload(onready,accept) { let input = document.createElement('input'); input.type = 'file'; if(Array.isArray(accept)){ if(accept.count > 0){ input.accept = accept.join(", "); } } else if (undefined !== accept){ input.accept = accept; } input.onchange = () => { let files = Array.from(input.files); if(files.length > 0){ let file = files[0]; var reader = new FileReader(); reader.onload = function(e) { var contents = e.target.result; if(onready instanceof Function){ onready(file,contents); } }; reader.readAsText(file); } }; if (document.createEvent) { var event = document.createEvent('MouseEvents'); event.initEvent('click', true, true); input.dispatchEvent(event); } else { input.click(); } }