UNPKG

@jsxtools/aui

Version:

A baseline UI as Mixins, Custom Elements, React Components, etc.

1 lines 2.11 kB
import{DropMixin}from"./drop.js";var FileMixin=(Element)=>class extends DropMixin(Element){static observedAttributes=["multiple",...super.observedAttributes||[]];maxSize=Number.POSITIVE_INFINITY;multiple=!1;types=[{description:"All Files",accept:{"*/*":[]}}];#files=[];get files(){return[...this.#files]}#isValidFile(file){for(let type of this.types)for(let contentType in type.accept){if(contentType==="*/*")return!0;if(file.type===contentType)return!0;for(let fileExtension of type.accept[contentType])if(file.name.toLowerCase().endsWith(fileExtension))return!0}return!1}#handleFiles(settledFiles){this.#files=[];for(let file of settledFiles)if(this.#files.push(file.size>this.maxSize?new TransferFile(file,{valid:!1,rangeOverflow:!0},"Unsupported file size"):!this.#isValidFile(file)?new TransferFile(file,{valid:!1,typeMismatch:!0},"Unsupported file type"):new TransferFile(file)),!this.multiple)break;this.dispatchEvent(new Event("input",{bubbles:!0}))}#handleDrop(event){event.preventDefault();const files=[];for(let file of event.dataTransfer.files)files.push(file);this.#handleFiles(files)}#handleClick(event){event.preventDefault(),showOpenFilePicker({excludeAcceptAllOption:!0,multiple:this.multiple,types:this.types}).then((fileHandles)=>{const handledFiles=[];for(let fileHandle of fileHandles)handledFiles.push(fileHandle.getFile());return Promise.all(handledFiles)}).then((files)=>{this.#handleFiles(files)},()=>{})}connectedCallback(){this.addEventListener("drop",this.#handleDrop,!0),this.addEventListener("click",this.#handleClick,!0),super.connectedCallback?.()}disconnectedCallback(){this.removeEventListener("drop",this.#handleDrop,!0),this.removeEventListener("click",this.#handleClick,!0),super.disconnectedCallback?.()}attributeChangedCallback(name,oldValue,newValue){if(name==="multiple")this.multiple=newValue!==null;super.attributeChangedCallback?.(name,oldValue,newValue)}};class TransferFile extends File{constructor(file,validity={valid:!0},validityMessage=""){super([file],file.name,file);this.validity=validity,this.validityMessage=validityMessage}}export{TransferFile,FileMixin}