All files / lib/components table.vue

69.46% Statements 116/167
60.1% Branches 119/198
77.78% Functions 35/45
69.7% Lines 115/165
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 62518x 18x 18x   18x 18x                     18x         18x 144x 16x   128x 48x 120x     80x                                                                                                                                                                       18x 24x       24x   74x 72x   74x       18x                 18x     124x                                                                                                                                                                                                                             93x                                                           8x 8x                                                 124x 124x 124x 124x         6x 6x       2x 2x       2x 2x         124x   124x 124x 124x 31x   124x                 124x     124x     31x 31x     132x     1x           66x     43x                     275x 275x 275x 275x 275x 275x   275x   275x           275x     275x   2x   2x     2x 2x     2x   2x 24x 24x 24x       2x   2x         275x               275x   142x       275x   275x           2080x     12120x 12120x     12120x       3030x 3030x     5x           5x                                         16x           16x 16x 8x         8x 8x   8x 8x 4x 4x 4x     16x 16x   12x         3x 3x       67x 67x 67x     176x     176x   109x       67x   67x   2x     65x   2x 2x       63x       12120x     3030x   3030x                                                                                                                            
<template>
    <table :id="id || null"
    I       :aria-busy="busy ? 'true' : 'false'"
           :class="tableClass"
    >E
        <thead :class="headClass">
        <tr>
            <th v-for="(field,key) in fields"
                @click.stop.prevent="headClicked($event,field,key)"
                @keydown.enter.stop.prevent="headClicked($event,field,key)"
                @keydown.space.stop.prevent="headClicked($event,field,key)"
                :key="key"
                :class="fieldClass(field,key)"
                :style="field.thStyle || {}"
                :aria-label="field.sortable ? ((localSortDesc && localSortBy === key) ? labelSortAsc : labelSortDesc) : null"
                :aria-sort="(field.sortable && localSortBy === key) ? (localSortDesc ? 'descending' : 'ascending') : null"
                :tabindex="field.sortable?'0':null"
            >
                <slot :name="'HEAD_'+key" :label="field.label" :column="key" :field="field">
                    <div v-html="field.label"></div>
                </slot>
            </th>
        </tr>
        </thead>
        <tfoot v-if="footClone" :class="footClass">
        <tr>
            <th v-for="(field,key) in fields"
                @click.stop.prevent="headClicked($event,field,key)"
                @keydown.enter.stop.prevent="headClicked($event,field,key)"
                @keydown.space.stop.prevent="headClicked($event,field,key)"
                :key="key"
                :class="fieldClass(field,key)"
                :style="field.thStyle || {}"
                :aria-label="field.sortable ? ((localSortDesc && localSortBy === key) ? labelSortAsc : labelSortDesc) : null"
                :aria-sort="(field.sortable && localSortBy === key) ? (localSortDesc ? 'descending' : 'ascending') : null"
                :tabindex="field.sortable?'0':null"
            >
                <slot v-if="$scopedSlots['FOOT_'+key]" :name="'FOOT_'+key" :label="field.label" :column="key"
                      :field="field">
                    <div v-html="field.label"></div>
                </slot>
                <slot v-else :name="'HEAD_'+key" :label="field.label" :column="key" :field="field">
                    <div v-html="field.label"></div>
                </slot>
            </th>
        </tr>
        </tfoot>
        <tbody>
        <tr v-for="(item,index) in _items"
            :key="index"
            :class="rowClass(item)"
            @click="rowClicked($event,item,index)"
            @dblclick="rowDblClicked($event,item,index)"
            @hover="rowHovered($event,item,index)"
        >
            <template v-for="(field,key) in fields">
                <td v-if="hasFormatter(field)" :key="key" :class="tdClass(field, item, key)"
                    v-html="callFormatter(item, key, field)">
                </td>
                <td v-else :class="tdClass(field, item, key)" :key="key">
                    <slot :name="key" :value="item[key]" :item="item" :index="index">{{item[key]}}</slot>
                </td>
            </template>
        </tr>
        <tr v-if="showEmpty && (!_items  || _items.length === 0)">
            <td :colspan="keys(fields).length">
                <div v-if="filter" role="alert" aria-live="polite">
                    <slot name="emptyfiltered">
                        <div class="text-center my-2" v-html="emptyFilteredText"></div>
                    </slot>
                </div>
                <div v-else role="alert" aria-live="polite">
                    <slot name="empty">
                        <div class="text-center my-2" v-html="emptyText"></div>
                    </slot>
                </div>
            </td>
        </tr>
        </tbody>
    </table>
</template>
 
<script>
    import { warn } from '../utils';
    import { keys } from '../utils/object.js';
    import { listenOnRootMixin } from '../mixins';
 
    const toString = v => {
        if (!v) {
            return '';
        }
        if (v instanceof Object) {
            return keys(v).map(k => toString(v[k])).join(' ');
        }
        return String(v);
    };
 
    const recToString = obj => {
        if (!(obj instanceof Object)) {
            return '';
        }
 
        return toString(keys(obj).reduce((o, k) => {
            // Ignore fields 'state' and ones that start with _
            if (!(/^_/.test(k) || k === 'state')) {
                o[k] = obj[k];
            }
            return o;
        }, {}));
    };
 
    const defaultSortCompare = (a, b, sortBy) => {
        if (typeof a[sortBy] === 'number' && typeof b[sortBy] === 'number') {
            return ((a[sortBy] < b[sortBy]) && -1) || ((a[sortBy] > b[sortBy]) && 1) || 0;
        }
        Ireturn toString(a[sortBy]).localeCompare(toString(b[sortBy]), undefined, {
            numeric: true
        });
    };
 
    export default {
        mixins: [listenOnRootMixin],
        data() {
            return {
                localSortBy: this.sortBy || '',
                localSortDesc: this.sortDesc || false,
                localItems: []
            };
        },
        props: {
            id: {
                type: String,
                default: ''
            },
            items: {
                type: [Array, Function],
                default() {
                    if (this && this.itemsProvider) {
                        // Deprecate itemsProvider
                        warn('b-table: prop \'items-provider\' has been deprecated. Pass a function to \'items\' instead');
                        return this.itemsProvider;
                    }
                    return [];
                }
            },
            sortBy: {
                type: String,
                default: null
            },
            sortDesc: {
                type: Boolean,
                default: false
            },
            apiUrl: {
                type: String,
                default: ''
            },
            fields: {
                type: Object,
                default: {}
            },
            striped: {
                type: Boolean,
                default: false
            },
            bordered: {
                type: Boolean,
                default: false
            },
            inverse: {
                type: Boolean,
                default: false
            },
            hover: {
                type: Boolean,
                default: false
            },
            small: {
                type: Boolean,
                default: false
            },
            responsive: {
                type: Boolean,
                default: false
            },
            headVariant: {
                type: String,
                default: ''
            },
            footVariant: {
                type: String,
                default: ''
            },
            perPage: {
                type: Number,
                default: null
            },
            currentPage: {
                type: Number,
                default: 1
            },
            filter: {
                type: [String, RegExp, Function],
                default: null
            },
            sortCompare: {
                type: Function,
                default: null
            },
            itemsProvider: {
                // Deprecated in favour of items
                type: Function,
                default: null
            },
            noProviderPaging: {
                type: Boolean,
                default: false
            },
            noProviderSorting: {
                type: Boolean,
                default: false
            },
            noProviderFiltering: {
                type: Boolean,
                default: false
            },
            busy: {
                type: Boolean,
                default: false
            },
            value: {
                type: Array,
                default: () => []
            },
            footClone: {
                type: Boolean,
                default: false
            },
            labelSortAsc: {
                type: String,
                default: 'Click to sort Ascending'
            },
            labelSortDesc: {
                type: String,
                default: 'Click to sort Descending'
            },
            showEmpty: {
                type: Boolean,
                default: false
            },
            emptyText: {
                type: String,
                default: 'There are no records to show'
            },
            emptyFilteredText: {
                type: String,
                default: 'There are no records matching your request'
            }
        },
        watch: {
            items(newVal, oldVal) {
                if (oldVal !== newVal) {
                    this._providerUpdate();
                }
            },
            sortDesc(newVal, oldVal) {
                if (newVal === this.localSortDesc) {
                    return;
                }
                this.localSortDesc = newVal || false;
            },
            localSortDesc(newVal, oldVal) {
                // Emit update to sort-desc.sync
                if (newVal !== oldVal) {
                    this.$emit('update:sortDesc', newVal);
                    if (!this.noProviderSorting) {
                        this._providerUpdate();
                    }
                }
            },
            sortBy(newVal, oldVal) {
                Eif (newVal === this.localSortBy) {
                    return;
                }
                this.localSortBy = newVal || null;
            },
            localSortBy(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.$emit('update:sortBy', newVal);
                    if (!this.noProviderSorting) {
                        this._providerUpdate();
                    }
                }
            },
            perPage(newVal, oldVal) {
                if (oldVal !== newVal && !this.noProviderPaging) {
                    this._providerUpdate();
                }
            },
            currentPage(newVal, oldVal) {
                if (oldVal !== newVal && !this.noProviderPaging) {
                    this._providerUpdate();
                }
            },
            filter(newVal, oldVal) {
                if (oldVal !== newVal && !this.noProviderFiltering) {
                    this._providerUpdate();
                E}
            }
        },E
        mounted() {
            this.localSortBy = this.sortBy;
            this.localSortDesc = this.sortDesc;
            if (this.hasProvider) {
                this._providerUpdate();
            }E
            this.listenOnRoot('table::refresh', id => {
                if (id === this.id) {
                    this._providerUpdate();
                }
            });E
        },
        computed: {
            tableClass() {
                return [
                E    'table',
                    'b-table',
                    this.striped ? 'table-striped' : '',
                    this.hover ? 'table-hover' : '',
                    this.inverse ? 'table-inverse' : '',
                    this.bordered ? 'table-bordered' : '',
                    this.responsive ? 'table-responsive' : '',
                    this.small ? 'table-sm' : ''
                ];
            },
            headClass() {
                return this.headVariant ? 'thead-' + this.headVariant : '';
            },
            footClass() {
                const variant = this.footVariant || this.headVariant || null;
                return variant ? 'thead-' + variant : '';
            },
            hasProvider() {
                return this.items instanceof Function;
            },
            providerFiltering() {
                return Boolean(this.hasProvider && !this.noProviderFiltering);
            },
            providerSorting() {
                return Boolean(this.hasProvider && !this.noProviderSorting);
            },
            providerPaging() {
                return Boolean(this.hasProvider && !this.noProviderPaging);
            },
            context() {
                return {
                    perPage: this.perPage,
                    currentPage: this.currentPage,
                    filter: this.filter,
                    apiUrl: this.apiUrl,
                    sortBy: this.localSortBy,
                    sortDesc: this.localSortDesc
                };
            },
            _items() {
                // Grab some props/data to ensure reactivity
                const perPage = this.perPage;
                const currentPage = this.currentPage;
                const filter = this.filter;
                const sortBy = this.localSortBy;
                const sortDesc = this.localSortDesc;
                const sortCompare = this.sortCompare || defaultSortCompare;
 
                let items = this.hasProvider ? this.localItems : this.items;
 
                if (!items) {
                    this.$nextTick(this._providerUpdate);
                    return [];
                }
 
                // Shallow copy of items, so we don't mutate the original array order/size
                items = items.slice();
 
                // Apply local filter
                if (filter && !this.providerFiltering) {
                    // Number of items before filtering
                    const numOriginalItems = items.length;
 
                    if (filter instanceof Function) {
                I        items = items.filter(filter);
                    } else {
                        let regex;
                        if (filter instanceof RegExp) {
                            regex = filter;
                        } else {
                            regex = new RegExp('.*' + filter + '.*', 'ig');
                        }
                        items = items.filter(item => {
                            const test = regex.test(recToString(item));
                            regex.lastIndex = 0;
                            return test;
                        });
                    I}

                    if (numOriginalItems !== items.length) {
                        // Emit a filtered notification event, as number of items has changed
                        Ithis.$emit('filtered', items);
                    }
                }
 
                // Apply local Sort
                if (sortBy && !this.providerSorting) {
                    items = items.sort((a, b) => {
                        const r = sortCompare(a, b, sortBy);
                        return sortDesc ? r : r * -1;
                    });
                }
 
                // AEpply local pagination
                if (perPage && !this.providerPaging) {
                    // Grab the current page of data (which may be past filtered items)
                    items = items.slice((currentPage - 1) * perPage, currentPage * perPage);
                }
 
                // Update the value model with the filtered/sorted/paginated data set
                Ithis.$emit('input', items);

                return items;
            }
        },
        methods: {
            keys,
            fieldClass(field, key) {
                return [
                    field.sortable ? 'sorting' : '',
                    (field.sortable && this.localSortBy === key) ? 'sorting_' + (this.localSortDesc ? 'desc' : 'asc') : '',
                    field.variant ? ('table-' + field.variant) : '',
                    field.class ? field.class : '',
                    field.thClass ? field.thClass : ''
                ];
            },
            tdClass(field, item, key) {
                let cellVariant = '';
                if (item._cellVariants && item._cellVariants[key]) {
                    cellVariant = (this.inverse ? 'bg-' : 'table-') + item._cellVariants[key];
                }
                return [
                    (field.variant && !cellVariant) ? ((this.inverse ? 'bg-' : 'table-') + field.variant) : '',
                    cellVariant,
                    field.class ? field.class : '',
                    field.tdClass ? field.tdClass : ''
                I];
            },
            rowClass(item) {
                // Prefer item._rowVariant over deprecated item.state
                const variant = item._rowVariant || item.state || null;
                return [
                    variant ? ((this.inverse ? 'bg-' : 'table-') + variant) : ''
                ];
            },
            rowClicked(e, item, index) {
                if (this.busy) {
                I    // If table is busy (via provider) then don't propagate
                    e.preventDefault();
                    e.stopPropagation();
                    return;
                }
                this.$emit('row-clicked', item, index);
            },
            rowDblClicked(e, item, index) {
                if (this.busy) {
                    // If table is busy (via provider) then don't propagate
                    e.preventDefault();
                    e.stopPropagation();
                    return;
                }
                this.$emit('row-dblclicked', item, index);
            },
            rowHovered(e, item, index) {
                if (this.busy) {
                    // If table is busy (via provider) then don't propagate
                    e.preventDefault();
                    e.stopPropagation();
                    return;
                }
                this.$emit('row-hovered', item, index);
            },
            headClicked(e, field, key) {
                if (this.busy) {
                I    // If table is busy (via provider) then don't propagate
                    e.preventDefault();
                    e.stopPropagation();
                    return;
                }
                let sortChanged = false;
                if (field.sortable) {
                    if (key === this.localSortBy) {
                    I    // Change sorting direction on current column
                        this.localSortDesc = !this.localSortDesc;
                    } else {
                        // Start sorting this column ascending
                        this.localSortBy = key;
                        this.localSortDesc = false;
                    }
                    sortChanged = true;
                } else if (this.localSortBy) {
                    this.localSortBy = null;
                    this.localSortDesc = false;
                    sortChanged = true;
                }
 
                this.$emit('head-clicked', key, field);
                if (sortChanged) {
                    // Sorting parameters changed
                    this.$emit('sort-changed', this.context);
                }
            },
            refresh() {
                // Expose refresh method
                if (this.hasProvider) {
                E    this._providerUpdate();
                }
            },
            _providerSetLocal(items) {
                this.localItems = (items && items.length > 0) ? items.slice() : [];
                this.$emit('refreshed');
                this.emitOnRoot('table::refreshed', this.id);
            },
            _providerUpdate() {
                // Refresh the provider items
                if (this.busy || !this.hasProvider) {
                    // Don't refresh remote data if we are 'busy' or if no provider
                    return;
                }
 
                // Call provider function with context and optional callback
                const data = this.items(this.context, this._providerSetLocal);
 
                if (!data) {
                    // Provider is using callback
                    return;
                }
 
                if (data.then && typeof data.then === 'function') {
                    // Provider returned Promise
                    data.then(items => {
                        this._providerSetLocal(items);
                    });
                } else {
                    // Provider returned Array data
                    this._providerSetLocal(data);
                }
            },
            hasFormatter(field) {
                return field.formatter && ((typeof (field.formatter) === 'function') || (typeof (field.formatter) === 'string'));
            },
            callFormatter(item, key, field) {
                if (field.formatter && (typeof (field.formatter) === 'function'))
                    return field.formatter(item[key]);
 
                Iif (field.formatter && (typeof (this.$parent[field.formatter]) === 'function'))
                    return this.$parent[field.formatter](item[key]);
            }E
 
        }
    };
</script>
 
<style>
    /* Based on https://cdn.datatables.net/1.10.13/css/dataTables.bootstrap4.css */
 
    table.b-table > thead > tr > .sorting,
    table.b-table > tfoot > tr > .sorting {
        padding-right: 30px;
        cursor: pointer;
        position: relative;
    }
 
    table.b-table thead > tr > .sorting:before,
    table.b-table thead > tr > .sorting:after,
    table.b-table tfoot > tr > .sorting:before,
    table.b-table tfoot > tr > .sorting:after {
        position: absolute;
        bottom: 0.9em;
        display: block;
        opacity: 0.3;
    }
 
    table.b-table.table-sm > thead > tr > .sorting:before,
    table.b-table.table-sm > thead > tr > .sorting:after,
    table.b-table.table-sm > tfoot > tr > .sorting:before,
    table.b-table.table-sm > tfoot > tr > .sorting:after {
        bottom: 0.45em;
    }
 
    table.b-table > thead > tr > .sorting:before,
    table.b-table > tfoot > tr > .sorting:before {
        right: 1em;
        content: "\2191";
    }
 
    table.b-table > thead > tr > .sorting:after,
    table.b-table > tfoot > tr > .sorting:after {
        right: 0.5em;
        content: "\2193";
    }
 
    table.b-table > thead > tr > .sorting_asc:after,
    table.b-table > thead > tr > .sorting_desc:before,
    table.b-table > tfoot > tr > .sorting_asc:after,
    table.b-table > tfoot > tr > .sorting_desc:before {
        opacity: 1;
    }
 
    /* Busy table styling */
 
    table.b-table[aria-busy="false"] {
        opacity: 1;
    }
 
    table.b-table[aria-busy="true"] {
        opacity: .6;
    }
</style>