import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-ClISz4NF.js';
import { c as createID } from './string.utils-vN03FcXN.js';
import { g as govHost, a as toBoolAttr, t as toBoolAttrIfDefined } from './template-CoD1xawt.js';
import { g as govForm } from './form-DvhJiKwA.js';
import { i as inheritAriaAttributes } from './accessibility-wqNV8djF.js';
import { A as AttributeObserver, a as ariaAttributes } from './attribute-Bz_RzYFb.js';
import './sizes-BcQO4NH2.js';
import './utils-CQvUntGY.js';
import './constants-BegH8u6i.js';
import './colors-U40vKHrs.js';
import './constants-aqe7GX2n.js';
import './constants-CysDgoMA.js';

const FormFileClass = {
    root: 'gov-form-file',
    area: 'gov-form-file__area',
    input: 'gov-form-file__input',
    inputFocus: 'gov-form-file__input-focus',
    attachments: 'gov-form-file__attachments',
};

function formatBytes(bytes) {
    const units = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
    let l = 0, n = parseInt(bytes, 10) || 0;
    while (n >= 1024 && ++l) {
        n = n / 1024;
    }
    return n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l];
}
function fileAcceptValidation(file, accept) {
    if (typeof accept === 'string' && accept.length) {
        return (accept
            .replace(/\s/g, '')
            .split(',')
            .filter(accept => {
            return new RegExp(accept.replace('*', '.*')).test(file.type);
        }).length > 0);
    }
    else {
        return true;
    }
}
function fileSizeValidation(file, maxSize) {
    const fileSize = Math.round(file.size);
    return fileSize <= maxSize;
}

const GovFormFile = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.govFocus = createEvent(this, "gov-focus");
        this.govBlur = createEvent(this, "gov-blur");
        this.govFiles = createEvent(this, "gov-files");
        this.govAddFile = createEvent(this, "gov-add-file");
        this.govRemoveFile = createEvent(this, "gov-remove-file");
        this.eventsRegistered = false;
        /**
         * Expands the file input to fill 100% of the container width.
         */
        this.expanded = false;
        /**
         * Set whether the input is required or not. Please note that this is necessary for accessible inputs when the user is required to fill them.
         * When using this property you need to also set “novalidate” attribute to your form element to prevent browser from displaying its own validation errors.
         */
        this.required = false;
        /**
         * Makes the File component disabled.
         * This prevents users from being able to interact with the File, and conveys its inactive state to assistive technologies.
         */
        this.disabled = false;
        /**
         * After selecting the files, the main input element will be reset.
         * The propagation of the event with the selected files will not be affected.
         */
        this.resetAfterPick = false;
        /**
         * Selected files will not be checked for duplicates based on name and size.
         */
        this.ignoreFileDuplicationCheck = false;
        /**
         * Show list of attachments
         */
        this.displayAttachments = true;
        /**
         * Same as original parameter
         * @link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/multiple
         */
        this.multiple = false;
        /**
         * Maximum embedded file size
         */
        this.maxFileSize = -1;
        /**
         * Error message when the maximum file size is exceeded
         */
        this.errorSize = "Soubor je větší než povolená velikost {FILE_SIZE}";
        /**
         * Insert unsupported file error message
         */
        this.errorAccept = "Soubor tohoto typu není povolen";
        /**
         * Adds accessible label for the list of attachments.
         */
        this.accessibleAttachmentsLabel = "Přílohy";
        this.files = [];
        this.inheritedAttributes = {};
        this.fileId = createID("GovInputFile");
        this.h = govHost(this.host);
        this.f = govForm(this.h);
    }
    watchControlAttrs() {
        this.passControlAttrs();
    }
    passControlAttrs() {
        this.f.passAttrToControl("invalid", toBoolAttr(this.invalid));
        this.f.passAttrToControl("disabled", toBoolAttr(this.disabled));
        this.f.passAttrToControl("type", "File");
    }
    registerListeners() {
        if (this.eventsRegistered) {
            return;
        }
        this.eventsRegistered = true;
        function highlight() {
            this.areaRef.classList.add("highlight");
        }
        function unhighlight() {
            this.areaRef.classList.remove("highlight");
        }
        this.inputRef.addEventListener("change", e => {
            e.preventDefault();
            e.stopPropagation();
            const files = e.target.files;
            if (this.resetAfterPick) {
                if (files.length) {
                    this.validateFiles(files);
                }
            }
            else {
                this.validateFiles(files);
            }
        }, false);
        if (this.expanded) {
            const events = ["dragover", "dragleave"];
            const inEvents = ["dragenter", "dragover", "mouseenter"];
            const outEvents = ["dragleave", "mouseleave"];
            events.map(eventName => this.inputRef.addEventListener(eventName, this.preventDefaults.bind(this), false));
            inEvents.map(eventName => this.inputRef.addEventListener(eventName, highlight.bind(this), false));
            outEvents.forEach(eventName => this.inputRef.addEventListener(eventName, unhighlight.bind(this), false));
        }
    }
    preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }
    handleDrop(e) {
        const dataTransfer = e.dataTransfer;
        this.validateFiles(dataTransfer.files);
    }
    validateFiles(files) {
        let filesBuffer = [];
        Array.from(files).map(file => {
            const isFile = this.files.find(item => item.file.name === file.name && item.file.size === file.size) || null;
            if (isFile === null || this.ignoreFileDuplicationCheck) {
                const isSizeValid = typeof this.maxFileSize === "number" && this.maxFileSize > 0 ? fileSizeValidation(file, this.maxFileSize) : true;
                const isAcceptValid = fileAcceptValidation(file, this.accept);
                const newFile = {
                    id: createID("GovFormFile"),
                    file,
                    acceptValid: isAcceptValid,
                    sizeValid: isSizeValid,
                };
                if (this.displayAttachments) {
                    this.files = [...this.files, newFile];
                }
                else {
                    filesBuffer = [...filesBuffer, newFile];
                }
                this.govAddFile.emit({
                    component: FormFileClass.root,
                    file: newFile,
                });
            }
        });
        this.govFiles.emit({
            component: FormFileClass.root,
            files: filesBuffer.length ? filesBuffer : this.files,
        });
        if (this.resetAfterPick) {
            this.reset().finally();
        }
    }
    componentDidLoad() {
        this.attributeObserver = new AttributeObserver(this.host, (attributeName, newValue) => {
            this.onAriaAttributeChange(attributeName, newValue);
        });
        this.attributeObserver.startObserving(ariaAttributes);
    }
    componentWillLoad() {
        this.f.passAttrToLabel("required", String(this.required));
        this.passControlAttrs();
        this.inheritedAttributes = inheritAriaAttributes(this.host);
    }
    async componentDidRender() {
        this.registerListeners();
    }
    disconnectedCallback() {
        var _a;
        (_a = this.attributeObserver) === null || _a === void 0 ? void 0 : _a.stopObserving();
    }
    onAriaAttributeChange(attributeName, newValue) {
        this.host.removeAttribute(attributeName);
        this.inheritedAttributes = Object.assign(Object.assign({}, this.inheritedAttributes), { [attributeName]: newValue });
    }
    render() {
        return (h(Host, { key: '59bdd8c7d3bf9594fa545146ca44a00f060fccab', class: this.h.classes([FormFileClass.root]), invalid: toBoolAttrIfDefined(this.invalid), expanded: toBoolAttrIfDefined(this.expanded) }, h("div", { key: 'fd1714f4eb7596fdc1eb67fe8b6d25e4ec93f454', class: FormFileClass.area, ref: el => (this.areaRef = el) }, h("slot", { key: '2712d87a6889321616b1b4cb03ea0c61aefcd241' }), h("input", Object.assign({ key: 'ac998000d9551871016d4c2ab802040634ff6256', class: FormFileClass.input, ref: el => (this.inputRef = el), id: this.identifier || this.fileId, type: "file", name: this.name, accept: this.accept, multiple: this.multiple, onChange: this.onChangeHandler.bind(this), onFocus: this.onFocusHandler.bind(this), onBlur: this.onBlurHandler.bind(this), required: this.required, disabled: this.disabled }, this.inheritedAttributes, { "aria-required": toBoolAttrIfDefined(this.required), "aria-invalid": toBoolAttrIfDefined(this.invalid), "aria-disabled": toBoolAttrIfDefined(this.disabled) })), h("div", { key: '54a896ed65deef09f11a8b497f926d079fb599d1', class: FormFileClass.inputFocus })), this.h.hasSlot("attachments") ? (h("div", { class: FormFileClass.attachments }, h("slot", { name: "attachments" }))) : null, this.files.length && this.displayAttachments ? (h("div", { class: FormFileClass.attachments }, h("gov-attachments", { label: this.accessibleAttachmentsLabel, "accessible-label": this.accessibleAttachmentsLabel }, this.files.map(item => (h("gov-attachments-item", { "accessible-remove-labelledby": item.id, "on-gov-remove": () => this.onRemoveFileHandler(item) }, item.file.name, h("span", { slot: "name" }, item.file.name), item.acceptValid === false ? (h("gov-form-message", { slot: "message", color: "error" }, h("gov-icon", { slot: "icon", name: "exclamation-triangle-fill", type: "components" }), item.acceptValid === false ? this.errorAccept : null)) : null, item.sizeValid === false ? (h("gov-form-message", { slot: "message", color: "error" }, h("gov-icon", { slot: "icon", name: "exclamation-triangle-fill", type: "components" }), this.errorSize.replace("{FILE_SIZE}", formatBytes(this.maxFileSize)))) : null, h("span", { slot: "info" }, "(", formatBytes(item.file.size), ")"))))))) : null));
    }
    onRemoveFileHandler(file) {
        const index = this.files.findIndex(item => item.id === file.id);
        if (index !== -1) {
            const files = this.files;
            const removeFile = this.files[index];
            files.splice(index, 1);
            this.files = [...files];
            this.govRemoveFile.emit({
                component: FormFileClass.root,
                file: removeFile,
            });
            this.govFiles.emit({
                component: FormFileClass.root,
                files,
            });
        }
    }
    onFocusHandler(e) {
        e.stopPropagation();
        this.govFocus.emit({
            component: FormFileClass.root,
            originalEvent: e,
        });
    }
    onBlurHandler(e) {
        e.stopPropagation();
        this.govBlur.emit({
            component: FormFileClass.root,
            originalEvent: e,
        });
    }
    onChangeHandler(e) {
        e.stopPropagation();
    }
    /**
     * Returns the reference of the native element
     */
    async getRef() {
        return this.inputRef;
    }
    /**
     * Returns the reference of the native area element
     */
    async getAreaRef() {
        return this.areaRef;
    }
    /**
     * Remove all files from component state
     */
    async reset() {
        this.files = [];
        this.inputRef.value = '';
    }
    get host() { return getElement(this); }
    static get watchers() { return {
        "disabled": ["watchControlAttrs"],
        "invalid": ["watchControlAttrs"]
    }; }
};

export { GovFormFile as gov_form_file };
//# sourceMappingURL=gov-form-file.entry.js.map

//# sourceMappingURL=gov-form-file.entry.js.map