var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

import '../../../src/components/VDataTable/VDataTable.sass';
// Components
import { VData } from '../VData';
import { VDataFooter, VDataIterator } from '../VDataIterator';
import VBtn from '../VBtn';
import VDataTableHeader from './VDataTableHeader';
import VVirtualTable from './VVirtualTable';
import VIcon from '../VIcon';
import VProgressLinear from '../VProgressLinear';
import VRow from './VRow';
import VRowGroup from './VRowGroup';
import VSimpleCheckbox from '../VCheckbox/VSimpleCheckbox';
import VSimpleTable from './VSimpleTable';
import VMobileRow from './VMobileRow';
import ripple from '../../directives/ripple';
// Helpers
import { deepEqual, getObjectValueByPath, getPrefixedScopedSlots, getSlot, defaultFilter } from '../../util/helpers';
import { breaking } from '../../util/console';
function filterFn(item, search) {
    return function (header) {
        var value = getObjectValueByPath(item, header.value);
        return header.filter ? header.filter(value, search, item) : defaultFilter(value, search);
    };
}
function searchTableItems(items, search, headersWithCustomFilters, headersWithoutCustomFilters) {
    var filtered = items;
    search = typeof search === 'string' ? search.trim() : null;
    if (search) {
        filtered = items.filter(function (item) {
            return headersWithoutCustomFilters.some(filterFn(item, search));
        });
    }
    return filtered.filter(function (item) {
        return headersWithCustomFilters.every(filterFn(item, search));
    });
}
/* @vue/component */
export default VDataIterator.extend({
    name: 'v-data-table',
    // https://github.com/vuejs/vue/issues/6872
    directives: {
        ripple: ripple
    },
    props: {
        headers: {
            type: Array
        },
        showSelect: Boolean,
        showExpand: Boolean,
        showGroupBy: Boolean,
        virtualRows: Boolean,
        mobileBreakpoint: {
            type: Number,
            default: 600
        },
        height: [Number, String],
        hideDefaultHeader: Boolean,
        caption: String,
        dense: Boolean,
        headerProps: Object,
        calculateWidths: Boolean,
        fixedHeader: Boolean,
        headersLength: Number,
        expandIcon: {
            type: String,
            default: '$vuetify.icons.expand'
        },
        customFilter: {
            type: Function,
            default: searchTableItems
        }
    },
    data: function data() {
        return {
            internalGroupBy: [],
            openCache: {},
            widths: []
        };
    },

    computed: {
        computedHeaders: function computedHeaders() {
            var _this = this;

            if (!this.headers) return [];
            var headers = this.headers.filter(function (h) {
                return h.value === undefined || !_this.internalGroupBy.find(function (v) {
                    return v === h.value;
                });
            });
            var defaultHeader = { text: '', sortable: false, width: '1px' };
            if (this.showSelect) {
                var index = headers.findIndex(function (h) {
                    return h.value === 'data-table-select';
                });
                if (index < 0) headers.unshift(_extends({}, defaultHeader, { value: 'data-table-select' }));else headers.splice(index, 1, _extends({}, defaultHeader, headers[index]));
            }
            if (this.showExpand) {
                var _index = headers.findIndex(function (h) {
                    return h.value === 'data-table-expand';
                });
                if (_index < 0) headers.unshift(_extends({}, defaultHeader, { value: 'data-table-expand' }));else headers.splice(_index, 1, _extends({}, defaultHeader, headers[_index]));
            }
            return headers;
        },
        computedHeadersLength: function computedHeadersLength() {
            return this.headersLength || this.computedHeaders.length;
        },
        isMobile: function isMobile() {
            return this.$vuetify.breakpoint.width < this.mobileBreakpoint;
        },
        columnSorters: function columnSorters() {
            return this.computedHeaders.reduce(function (acc, header) {
                if (header.sort) acc[header.value] = header.sort;
                return acc;
            }, {});
        },
        headersWithCustomFilters: function headersWithCustomFilters() {
            return this.computedHeaders.filter(function (header) {
                return header.filter;
            });
        },
        headersWithoutCustomFilters: function headersWithoutCustomFilters() {
            return this.computedHeaders.filter(function (header) {
                return !header.filter;
            });
        }
    },
    created: function created() {
        var _this2 = this;

        var breakingProps = [['sort-icon', 'header-props.sort-icon'], ['hide-headers', 'hide-default-header'], ['select-all', 'show-select']];
        /* istanbul ignore next */
        breakingProps.forEach(function (_ref) {
            var _ref2 = _slicedToArray(_ref, 2),
                original = _ref2[0],
                replacement = _ref2[1];

            if (_this2.$attrs.hasOwnProperty(original)) breaking(original, replacement, _this2);
        });
    },
    mounted: function mounted() {
        // if ((!this.sortBy || !this.sortBy.length) && (!this.options.sortBy || !this.options.sortBy.length)) {
        //   const firstSortable = this.headers.find(h => !('sortable' in h) || !!h.sortable)
        //   if (firstSortable) this.updateOptions({ sortBy: [firstSortable.value], sortDesc: [false] })
        // }
        if (this.calculateWidths) {
            window.addEventListener('resize', this.calcWidths);
            this.calcWidths();
        }
    },
    beforeDestroy: function beforeDestroy() {
        if (this.calculateWidths) {
            window.removeEventListener('resize', this.calcWidths);
        }
    },

    methods: {
        calcWidths: function calcWidths() {
            this.widths = Array.from(this.$el.querySelectorAll('th')).map(function (e) {
                return e.clientWidth;
            });
        },
        customFilterWithColumns: function customFilterWithColumns(items, search) {
            return this.customFilter(items, search, this.headersWithCustomFilters, this.headersWithoutCustomFilters);
        },
        customSortWithHeaders: function customSortWithHeaders(items, sortBy, sortDesc, locale) {
            return this.customSort(items, sortBy, sortDesc, locale, this.columnSorters);
        },
        createItemProps: function createItemProps(item) {
            var props = VDataIterator.options.methods.createItemProps.call(this, item);
            return Object.assign(props, { headers: this.computedHeaders });
        },
        genCaption: function genCaption(props) {
            if (this.caption) return [this.$createElement('caption', [this.caption])];
            return getSlot(this, 'caption', props, true);
        },
        genColgroup: function genColgroup(props) {
            var _this3 = this;

            return this.$createElement('colgroup', this.computedHeaders.map(function (header) {
                return _this3.$createElement('col', {
                    class: {
                        'divider': header.divider
                    },
                    style: {
                        width: header.width
                    }
                });
            }));
        },
        genLoading: function genLoading() {
            var progress = this.$slots['progress'] ? this.$slots.progress : this.$createElement(VProgressLinear, {
                props: {
                    color: this.loading === true ? 'primary' : this.loading,
                    height: 2,
                    indeterminate: true
                }
            });
            var th = this.$createElement('th', {
                staticClass: 'column',
                attrs: {
                    colspan: this.computedHeadersLength
                }
            }, [progress]);
            var tr = this.$createElement('tr', {
                staticClass: 'v-data-table__progress'
            }, [th]);
            return this.$createElement('thead', [tr]);
        },
        genHeaders: function genHeaders(props) {
            var data = {
                props: _extends({}, this.headerProps, {
                    headers: this.computedHeaders,
                    options: props.options,
                    mobile: this.isMobile,
                    showGroupBy: this.showGroupBy,
                    someItems: this.someItems,
                    everyItem: this.everyItem,
                    singleSelect: this.singleSelect
                }),
                on: {
                    sort: props.sort,
                    group: props.group,
                    'toggle-select-all': this.toggleSelectAll
                }
            };
            var children = [getSlot(this, 'header', data)];
            if (!this.hideDefaultHeader) {
                var scopedSlots = getPrefixedScopedSlots('header.', this.$scopedSlots);
                children.push(this.$createElement(VDataTableHeader, _extends({}, data, {
                    scopedSlots: scopedSlots
                })));
            }
            if (this.loading) children.push(this.genLoading());
            return children;
        },
        genEmptyWrapper: function genEmptyWrapper(content) {
            return this.$createElement('tr', [this.$createElement('td', {
                attrs: {
                    colspan: this.computedHeadersLength
                }
            }, content)]);
        },
        genItems: function genItems(items, props) {
            var empty = this.genEmpty(props.pagination.itemsLength);
            if (empty) return [empty];
            return props.groupedItems ? this.genGroupedRows(props.groupedItems, props) : this.genRows(items, props);
        },
        genGroupedRows: function genGroupedRows(groupedItems, props) {
            var _this4 = this;

            var groups = Object.keys(groupedItems || {});
            return groups.map(function (group) {
                if (!_this4.openCache.hasOwnProperty(group)) _this4.$set(_this4.openCache, group, true);
                if (_this4.$scopedSlots.group) {
                    return _this4.$scopedSlots.group({
                        group: group,
                        options: props.options,
                        items: groupedItems[group],
                        headers: _this4.computedHeaders
                    });
                } else {
                    return _this4.genDefaultGroupedRow(group, groupedItems[group], props);
                }
            });
        },
        genDefaultGroupedRow: function genDefaultGroupedRow(group, items, props) {
            var _this5 = this;

            var isOpen = !!this.openCache[group];
            var children = [this.$createElement('template', { slot: 'row.content' }, this.genDefaultRows(items, props))];
            if (this.$scopedSlots['group.header']) {
                children.unshift(this.$createElement('template', { slot: 'column.header' }, [this.$scopedSlots['group.header']({ group: group, groupBy: props.options.groupBy, items: items, headers: this.computedHeaders })]));
            } else {
                var toggle = this.$createElement(VBtn, {
                    staticClass: 'ma-0',
                    props: {
                        icon: true,
                        small: true
                    },
                    on: {
                        click: function click() {
                            return _this5.$set(_this5.openCache, group, !_this5.openCache[group]);
                        }
                    }
                }, [this.$createElement(VIcon, [isOpen ? 'remove' : 'add'])]);
                var remove = this.$createElement(VBtn, {
                    staticClass: 'ma-0',
                    props: {
                        icon: true,
                        small: true
                    },
                    on: {
                        click: function click() {
                            return props.updateOptions({ groupBy: [], groupDesc: [] });
                        }
                    }
                }, [this.$createElement(VIcon, ['close'])]);
                var column = this.$createElement('td', {
                    staticClass: 'text-xs-left',
                    attrs: {
                        colspan: this.computedHeadersLength
                    }
                }, [toggle, props.options.groupBy[0] + ': ' + group, remove]);
                children.unshift(this.$createElement('template', { slot: 'column.header' }, [column]));
            }
            if (this.$scopedSlots['group.summary']) {
                children.push(this.$createElement('template', { slot: 'column.summary' }, [this.$scopedSlots['group.summary']({ group: group, groupBy: props.options.groupBy, items: items, headers: this.computedHeaders })]));
            }
            return this.$createElement(VRowGroup, {
                key: group,
                props: {
                    value: isOpen
                }
            }, children);
        },
        genRows: function genRows(items, props) {
            return this.$scopedSlots.item ? this.genScopedRows(items, props) : this.genDefaultRows(items, props);
        },
        genScopedRows: function genScopedRows(items, props) {
            var _this6 = this;

            return items.map(function (item) {
                return _this6.$scopedSlots.item(_this6.createItemProps(item));
            });
        },
        genDefaultRows: function genDefaultRows(items, props) {
            var _this7 = this;

            return this.$scopedSlots['expanded-item'] ? items.map(function (item) {
                return _this7.genDefaultExpandedRow(item);
            }) : items.map(function (item) {
                return _this7.genDefaultSimpleRow(item);
            });
        },
        genDefaultExpandedRow: function genDefaultExpandedRow(item) {
            var isExpanded = this.isExpanded(item);
            var headerRow = this.genDefaultSimpleRow(item, isExpanded ? 'expanded expanded__row' : null);
            var expandedRow = this.$createElement('tr', {
                staticClass: 'expanded expanded__content'
            }, [this.$scopedSlots['expanded-item']({ item: item, headers: this.computedHeaders })]);
            return this.$createElement(VRowGroup, {
                props: {
                    value: isExpanded
                }
            }, [this.$createElement('template', { slot: 'row.header' }, [headerRow]), this.$createElement('template', { slot: 'row.content' }, [expandedRow])]);
        },
        genDefaultSimpleRow: function genDefaultSimpleRow(item) {
            var _this8 = this;

            var classes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;

            var scopedSlots = getPrefixedScopedSlots('item.', this.$scopedSlots);
            if (this.showSelect) {
                var data = {
                    item: item,
                    props: {
                        value: this.isSelected(item)
                    },
                    on: {
                        input: function input(v) {
                            return _this8.select(item, v);
                        }
                    }
                };
                var slot = scopedSlots['data-table-select'];
                scopedSlots['data-table-select'] = slot ? function () {
                    return slot(data);
                } : function () {
                    return _this8.$createElement(VSimpleCheckbox, _extends({
                        staticClass: 'v-data-table__checkbox'
                    }, data));
                };
            }
            var expanded = this.isExpanded(item);
            if (this.showExpand) {
                var _data = {
                    item: item,
                    props: {
                        expanded: expanded
                    },
                    on: {
                        click: function click() {
                            return _this8.expand(item, !expanded);
                        }
                    }
                };
                var _slot = scopedSlots['data-table-expand'];
                scopedSlots['data-table-expand'] = _slot ? function () {
                    return _slot(_data);
                } : function () {
                    return _this8.$createElement(VIcon, _extends({
                        staticClass: 'v-data-table__expand-icon',
                        class: {
                            'v-data-table__expand-icon--active': expanded
                        }
                    }, _data), [_this8.expandIcon]);
                };
            }
            return this.$createElement(this.isMobile ? VMobileRow : VRow, {
                key: getObjectValueByPath(item, this.itemKey),
                class: classes,
                props: {
                    headers: this.computedHeaders,
                    item: item,
                    rtl: this.$vuetify.rtl
                },
                scopedSlots: scopedSlots
            });
        },
        genBody: function genBody(props) {
            var data = _extends({}, props, {
                headers: this.computedHeaders
            });
            if (this.$scopedSlots.body) {
                return this.$scopedSlots.body(data);
            }
            return this.$createElement('tbody', [getSlot(this, 'body.prepend', data, true), this.genItems(props.items, props), getSlot(this, 'body.append', data, true)]);
        },
        genFooters: function genFooters(props) {
            var data = {
                props: _extends({
                    options: props.options,
                    pagination: props.pagination,
                    itemsPerPageText: '$vuetify.dataTable.itemsPerPageText'
                }, this.footerProps),
                on: {
                    'update:options': function updateOptions(value) {
                        return props.updateOptions(value);
                    }
                },
                widths: this.widths,
                headers: this.computedHeaders
            };
            var children = [getSlot(this, 'footer', data, true)];
            if (!this.hideDefaultFooter) {
                children.push(this.$createElement(VDataFooter, data));
            }
            return children;
        },
        genDefaultScopedSlot: function genDefaultScopedSlot(props) {
            var _this9 = this;

            var simpleProps = {
                height: this.height,
                fixedHeader: this.fixedHeader,
                dense: this.dense
            };
            if (this.virtualRows) {
                return this.$createElement(VVirtualTable, {
                    props: Object.assign(simpleProps, {
                        itemsLength: props.items.length,
                        height: this.height,
                        rowHeight: this.dense ? 24 : 48,
                        headerHeight: this.dense ? 32 : 48
                    }),
                    scopedSlots: {
                        items: function items(_ref3) {
                            var start = _ref3.start,
                                stop = _ref3.stop;

                            // TODO: Grouped rows support?
                            var items = props.groupedItems ? [] : props.items.slice(start, stop);
                            return _this9.genItems(items, props);
                        }
                    }
                }, [this.proxySlot('body.before', [this.genCaption(props), this.genHeaders(props)]), this.proxySlot('bottom', this.genFooters(props))]);
            }
            return this.$createElement(VSimpleTable, {
                props: simpleProps
            }, [this.proxySlot('top', getSlot(this, 'top', props, true)), this.genCaption(props), this.genColgroup(props), this.genHeaders(props), this.genBody(props), this.proxySlot('bottom', this.genFooters(props))]);
        },
        proxySlot: function proxySlot(slot, content) {
            return this.$createElement('template', { slot: slot }, content);
        }
    },
    render: function render() {
        var _this10 = this;

        return this.$createElement(VData, {
            props: _extends({}, this.$props, {
                customFilter: this.customFilterWithColumns,
                customSort: this.customSortWithHeaders
            }),
            on: {
                'update:options': function updateOptions(v, old) {
                    _this10.internalGroupBy = v.groupBy || [];
                    !deepEqual(v, old) && _this10.$emit('update:options', v);
                },
                'update:page': function updatePage(v) {
                    return _this10.$emit('update:page', v);
                },
                'update:items-per-page': function updateItemsPerPage(v) {
                    return _this10.$emit('update:items-per-page', v);
                },
                'update:sort-by': function updateSortBy(v) {
                    return _this10.$emit('update:sort-by', v);
                },
                'update:sort-desc': function updateSortDesc(v) {
                    return _this10.$emit('update:sort-desc', v);
                },
                'update:group-by': function updateGroupBy(v) {
                    return _this10.$emit('update:group-by', v);
                },
                'update:group-desc': function updateGroupDesc(v) {
                    return _this10.$emit('update:group-desc', v);
                },
                'pagination': function pagination(v, old) {
                    return !deepEqual(v, old) && _this10.$emit('pagination', v);
                },
                'current-items': function currentItems(v) {
                    _this10.internalCurrentItems = v;
                    _this10.$emit('current-items', v);
                },
                'page-count': function pageCount(v) {
                    return _this10.$emit('page-count', v);
                }
            },
            scopedSlots: {
                default: this.genDefaultScopedSlot
            }
        });
    }
});
//# sourceMappingURL=VDataTable.js.map