UNPKG

@govbr-ds/webcomponents

Version:

Biblioteca de Web Components baseado no GovBR-DS

265 lines (264 loc) 11.3 kB
/*! * Construído por SERPRO * © https://serpro.gov.br/ - MIT License. */ import { h, Host } from "@stencil/core"; var UploadState; (function (UploadState) { UploadState["INFO"] = "info"; UploadState["WARNING"] = "warning"; UploadState["DANGER"] = "danger"; UploadState["SUCCESS"] = "success"; })(UploadState || (UploadState = {})); /** * Para uma descrição detalhada, consulte a [documentação do GovBR-DS](https://www.gov.br/ds/components/upload?tab=designer). * * @slot default - Descrição do slot */ export class Upload { /** * Referência ao elemento host do componente. * Utilize esta propriedade para acessar e manipular o elemento do DOM associado ao componente. */ el; /** * Tipos de arquivo permitidos (ex: 'image/*'). * Esta propriedade define quais tipos de arquivos podem ser selecionados para upload. */ accept = ''; /** * Texto descritivo do campo de upload. * Este é o texto que é mostrado no label do textarea. */ label = 'Envio de arquivo'; /** * Evento emitido quando um arquivo é selecionado. * Este estado armazena os arquivos que foram selecionados pelo usuário. */ filesSelected = null; /** * Referência ao elemento de arquivo selecionado. * Este estado armazena o arquivo que foi selecionado para upload. */ file = null; /** * Indica se o componente está desativado. * Quando definido como `true`, o campo de upload se torna não interativo, * impedindo que o usuário selecione ou envie arquivos. * Isso é útil para controlar a interação do usuário em situações específicas, * como durante o carregamento de dados ou quando o formulário está em um estado inválido. */ disabled = false; /** * Define o estado visual da mensagem. * Os possíveis valores são: * - 'info': Mensagem informativa. * - 'warning': Mensagem de aviso. * - 'danger': Mensagem de erro ou alerta. * - 'success': Mensagem de sucesso. * O valor padrão é 'info'. */ state = UploadState.INFO; /** * Indica se o componente permite a seleção de múltiplos arquivos. * Quando definido como `true`, o usuário pode selecionar mais de um arquivo para upload. */ multiple = false; elementInternals; getCssClassMap() { return { 'br-upload': true, [this.state]: true, }; } handleRemoveFileSelection(file) { const newArrayFilter = Array.from(this.filesSelected).filter((f) => f !== file); this.filesSelected = newArrayFilter; const fileInput = this.el.shadowRoot.getElementById('single-file'); fileInput.value = ''; } renderFilesUploaded() { const fileSizes = this._calculateFileSize(this.filesSelected); return fileSizes.map(({ file, size }) => { return (h("div", { class: "br-item d-flex", key: file.name }, h("div", { class: "content text-primary-default mr-auto" }, file.name), h("div", { class: "support mr-n2" }, h("span", { class: "" }, size), h("br-button", { shape: "circle", type: "button", "aria-label": "Remover arquivo", onClick: () => this.handleRemoveFileSelection(file) }, h("br-icon", { "icon-name": "fa-solid:trash", "aria-hidden": "true" }))))); }); } onInputChange(files) { if (files.length === 1) { this.filesSelected = files; } else if (files.length > 0) { this.filesSelected = files; } else { console.error(files.length === 0 ? 'NENHUM ARQUIVO ENVIADO' : 'VOCÊ SÓ PODE ENVIAR UM ARQUIVO POR VEZ'); return false; } } _calculateFileSize(files) { return Array.from(files).map((file) => { let sOutput = ''; const aMultiples = ['KB', 'MB', 'GB', 'TB']; let nMultiple = 0; let nApprox = file.size / 1024; if (nApprox < 1) { sOutput = `${file.size} bytes`; } else { while (nApprox > 1 && nMultiple < aMultiples.length) { sOutput = `${nApprox.toFixed(2)} ${aMultiples[nMultiple]}`; nApprox /= 1024; nMultiple++; } } return { file: file, size: sOutput || 0 }; }); } handleDrop(event) { event.preventDefault(); const files = event.dataTransfer?.files; if (files && files.length > 0) { this.onInputChange(files); } } handleDragOver(event) { event.preventDefault(); } handleFileSelection() { const fileInput = this.el.shadowRoot.getElementById('single-file'); fileInput.click(); } handleInputChange = (event) => { const target = event.target; this.onInputChange(target.files); }; render() { return (h(Host, { key: 'e3ba0e7cb0161629904a3fae52ce3d7697fe358b' }, h("div", { key: '0d26f8075f05ae4bc3df6c0b8384c0fd48045813', class: this.getCssClassMap() }, h("label", { key: 'ba6ce53d4f6c71d23671d278f3017a2784e88a97', class: "upload-label", form: "single-file" }, h("span", { key: '4b0d99e5d80cf2f4c31803de7e3ff6fd6ad058e6' }, this.label)), h("button", { key: 'eaed72879ba9bd95fb2ded0f02a5cda070e72473', class: "upload-button", type: "button", tabIndex: this.disabled ? -1 : 0, disabled: this.disabled, "aria-label": "Selecionar arquivo para upload", onClick: () => this.handleFileSelection(), onDrop: (event) => this.handleDrop(event), onDragOver: (event) => this.handleDragOver(event) }, h("br-icon", { key: 'ce0f5442513b92e9a76b9ccfdb46a69bfd0d365a', "icon-name": "fa-solid:upload", height: "16", "aria-hidden": "true" }), h("span", { key: '09e8b56f3b6b9d13d8bc3c340ce1264bd40afa49' }, "Selecione o arquivo")), h("input", { key: '08b5be254d9a424bcf0720c824676aa3ab483f65', class: "upload-input", id: "single-file", type: "file", "aria-label": "enviar arquivo", onChange: this.handleInputChange, multiple: this.multiple, disabled: this.disabled, accept: this.accept }), h("div", { key: '759038ad135aa81cb8c8f4c71e4abe84c69ed9c0', id: "list-files", class: "upload-list" }, this.filesSelected ? this.renderFilesUploaded() : null)))); } static get is() { return "br-upload"; } static get encapsulation() { return "shadow"; } static get formAssociated() { return true; } static get originalStyleUrls() { return { "$": ["upload.scss"] }; } static get styleUrls() { return { "$": ["upload.css"] }; } static get properties() { return { "accept": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Tipos de arquivo permitidos (ex: 'image/*').\nEsta propriedade define quais tipos de arquivos podem ser selecionados para upload." }, "getter": false, "setter": false, "attribute": "accept", "reflect": false, "defaultValue": "''" }, "label": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Texto descritivo do campo de upload.\nEste \u00E9 o texto que \u00E9 mostrado no label do textarea." }, "getter": false, "setter": false, "attribute": "label", "reflect": false, "defaultValue": "'Envio de arquivo'" }, "disabled": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Indica se o componente est\u00E1 desativado.\nQuando definido como `true`, o campo de upload se torna n\u00E3o interativo,\nimpedindo que o usu\u00E1rio selecione ou envie arquivos.\nIsso \u00E9 \u00FAtil para controlar a intera\u00E7\u00E3o do usu\u00E1rio em situa\u00E7\u00F5es espec\u00EDficas,\ncomo durante o carregamento de dados ou quando o formul\u00E1rio est\u00E1 em um estado inv\u00E1lido." }, "getter": false, "setter": false, "attribute": "disabled", "reflect": true, "defaultValue": "false" }, "state": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Define o estado visual da mensagem.\nOs poss\u00EDveis valores s\u00E3o:\n- 'info': Mensagem informativa.\n- 'warning': Mensagem de aviso.\n- 'danger': Mensagem de erro ou alerta.\n- 'success': Mensagem de sucesso.\nO valor padr\u00E3o \u00E9 'info'." }, "getter": false, "setter": false, "attribute": "state", "reflect": true, "defaultValue": "UploadState.INFO" }, "multiple": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Indica se o componente permite a sele\u00E7\u00E3o de m\u00FAltiplos arquivos.\nQuando definido como `true`, o usu\u00E1rio pode selecionar mais de um arquivo para upload." }, "getter": false, "setter": false, "attribute": "multiple", "reflect": false, "defaultValue": "false" } }; } static get states() { return { "filesSelected": {}, "file": {} }; } static get elementRef() { return "el"; } static get attachInternalsMemberName() { return "elementInternals"; } } //# sourceMappingURL=upload.js.map