-
Notifications
You must be signed in to change notification settings - Fork 22
/
KTable.vue
1159 lines (1056 loc) · 35.9 KB
/
KTable.vue
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<template>
<div class="k-table">
<div
v-if="hasToolbarSlot"
class="table-toolbar"
data-testid="table-toolbar"
>
<slot
name="toolbar"
:state="stateData"
/>
<div
v-if="hasColumnVisibilityMenu"
class="toolbar-default-items-container"
>
<ColumnVisibilityMenu
:columns="visibilityColumns"
:table-id="tableId"
:visibility-preferences="visibilityPreferences"
@update="(columnMap: Record<string, boolean>) => columnVisibility = columnMap"
/>
</div>
</div>
<KSkeleton
v-if="(isTableLoading || loading || isRevalidating) && !error"
data-testid="table-skeleton"
type="table"
/>
<div
v-else-if="error"
class="table-error-state"
data-testid="table-error-state"
>
<slot name="error-state">
<KEmptyState
icon-variant="error"
:message="errorStateMessage"
:title="errorStateTitle"
>
<template
v-if="!!errorStateActionMessage"
#action
>
<KButton
:data-testid="getTestIdString(errorStateActionMessage)"
:to="errorStateActionRoute ? errorStateActionRoute : undefined"
@click="$emit('error-action-click')"
>
{{ errorStateActionMessage }}
</KButton>
</template>
</KEmptyState>
</slot>
</div>
<div
v-else-if="!error && (!isTableLoading && !loading && !isRevalidating) && (data && !data.length)"
class="table-empty-state"
data-testid="table-empty-state"
>
<slot name="empty-state">
<KEmptyState
:icon-variant="emptyStateIconVariant"
:message="emptyStateMessage"
:title="emptyStateTitle"
>
<template
v-if="!!emptyStateActionMessage"
#action
>
<KButton
:appearance="searchInput ? 'tertiary' : 'primary'"
:data-testid="getTestIdString(emptyStateActionMessage)"
:to="emptyStateActionRoute ? emptyStateActionRoute : undefined"
@click="$emit('empty-state-action-click')"
>
<slot name="empty-state-action-icon" />
{{ emptyStateActionMessage }}
</KButton>
</template>
</KEmptyState>
</slot>
</div>
<div v-else>
<div
class="table-wrapper"
:style="tableWrapperStyles"
@scroll.passive="scrollHandler"
>
<table
v-bind-once="{ 'data-tableid': tableId }"
class="table"
:class="{
'has-hover': rowHover,
'is-clickable': isClickable
}"
>
<thead :class="{ 'is-scrolled': isScrolled }">
<tr
ref="headerRow"
:class="{ 'is-scrolled': isScrolled }"
>
<th
v-for="(column, index) in visibleHeaders"
:key="`table-${tableId}-headers-${index}`"
:aria-sort="sortable && column.key === sortColumnKey ? (sortColumnOrder === 'asc' ? 'ascending' : 'descending') : undefined"
class="table-headers"
:class="getHeaderClasses(column, index)"
:data-testid="`table-header-${column.key}`"
:style="columnStyles[column.key]"
@click="() => {
if (sortable && column.sortable) {
$emit('sort', {
prevKey: sortColumnKey,
sortColumnKey: column.key,
sortColumnOrder: sortColumnOrder === 'asc' ? 'desc' : 'asc' // display opposite because sortColumnOrder outdated
})
sortClickHandler(column)
}
}"
@mouseleave="currentHoveredColumn = ''"
@mouseover="currentHoveredColumn = column.key"
>
<div
v-if="resizeColumns && index !== 0"
class="resize-handle previous"
@click.stop
@mousedown="startResize($event, visibleHeaders[index - 1].key)"
@mouseleave="resizerHoveredColumn = ''"
@mouseover="resizerHoveredColumn = visibleHeaders[index - 1].key"
/>
<div
:aria-describedby="column.tooltip || $slots[getColumnTooltipSlotName(column.key)] ? `${getColumnTooltipSlotName(column.key)}-${tableId}` : undefined"
class="table-headers-container"
:class="{ 'resized': resizingColumn === column.key }"
>
<slot
:column="getGeneric(column)"
:name="getColumnSlotName(column.key)"
>
<span
class="table-header-label"
:class="{
'sr-only': column.hideLabel,
}"
>
{{ column.label ? column.label : column.key }}
</span>
</slot>
<KTooltip
v-if="column.tooltip || $slots[getColumnTooltipSlotName(column.key)]"
:data-testid="getColumnTooltipSlotName(column.key)"
:tooltip-id="`${getColumnTooltipSlotName(column.key)}-${tableId}`"
>
<InfoIcon
class="header-tooltip-trigger"
:color="`var(--kui-color-text-neutral, ${KUI_COLOR_TEXT_NEUTRAL})`"
:size="KUI_ICON_SIZE_30"
/>
<template #content>
<slot
:column="getGeneric(column)"
:name="getColumnTooltipSlotName(column.key)"
>
{{ column.tooltip }}
</slot>
</template>
</KTooltip>
<ArrowDownIcon
v-if="sortable && !column.hideLabel && column.sortable"
class="sort-icon"
:color="`var(--kui-color-text-neutral, ${KUI_COLOR_TEXT_NEUTRAL})`"
:size="KUI_ICON_SIZE_30"
/>
</div>
<div
v-if="resizeColumns && index !== visibleHeaders.length - 1"
class="resize-handle"
@click.stop
@mousedown="startResize($event, column.key)"
@mouseleave="resizerHoveredColumn = ''"
@mouseover="resizerHoveredColumn = column.key"
/>
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(row, rowIndex) in data"
v-bind="rowAttrs(row)"
:key="`table-${tableId}-row-${rowIndex}`"
:role="isClickable ? 'link' : null"
:tabindex="isClickable ? 0 : null"
>
<td
v-for="(header, index) in visibleHeaders"
v-bind="cellAttrs({ headerKey: header.key, row, rowIndex, colIndex: index })"
:key="`table-${tableId}-cell-${index}`"
:class="{
'resize-hover': resizeColumns && resizeHoverColumn === header.key && index !== visibleHeaders.length - 1,
}"
:style="columnStyles[header.key]"
v-on="tdlisteners(row[header.key], row)"
>
<slot
:name="header.key"
:row="getGeneric(row)"
:row-key="rowIndex"
:row-value="row[header.key]"
>
{{ row[header.key] }}
</slot>
</td>
</tr>
</tbody>
</table>
</div>
<KPagination
v-if="shouldShowPagination"
class="table-pagination"
:current-page="page"
data-testid="table-pagination"
:disable-page-jump="disablePaginationPageJump"
:initial-page-size="pageSize"
:neighbors="paginationNeighbors"
:offset="paginationOffset"
:offset-next-button-disabled="!nextOffset || !hasNextPage"
:offset-previous-button-disabled="!previousOffset"
:page-sizes="paginationPageSizes"
:total-count="total"
@get-next-offset="getNextOffsetHandler"
@get-previous-offset="getPrevOffsetHandler"
@page-change="pageChangeHandler"
@page-size-change="pageSizeChangeHandler"
/>
</div>
</div>
</template>
<script setup lang="ts">
import type { Ref, PropType } from 'vue'
import { ref, watch, computed, onMounted, useAttrs, useSlots } from 'vue'
import KButton from '@/components/KButton/KButton.vue'
import KEmptyState from '@/components/KEmptyState/KEmptyState.vue'
import KSkeleton from '@/components/KSkeleton/KSkeleton.vue'
import KPagination from '@/components/KPagination/KPagination.vue'
import KTooltip from '@/components/KTooltip/KTooltip.vue'
import { InfoIcon, ArrowDownIcon } from '@kong/icons'
import useUtilities from '@/composables/useUtilities'
import type {
TablePreferences,
TableHeader,
TableColumnSlotName,
TableColumnTooltipSlotName,
SwrvState,
SwrvStateData,
TableState,
PageChangeData,
PageSizeChangeData,
SortColumnOrder,
TableSortPayload,
TableStatePayload,
EmptyStateIconVariant,
} from '@/types'
import { EmptyStateIconVariants } from '@/types'
import { KUI_COLOR_TEXT_NEUTRAL, KUI_ICON_SIZE_30 } from '@kong/design-tokens'
import ColumnVisibilityMenu from './../KTableView/ColumnVisibilityMenu.vue'
import useUniqueId from '@/composables/useUniqueId'
const { useDebounce, useRequest, useSwrvState, clientSideSorter: defaultClientSideSorter, getSizeFromString } = useUtilities()
const props = defineProps({
/**
* Allow columns to be resized
*/
resizeColumns: {
type: Boolean,
default: false,
},
/**
* Used to customize the initial state of the table.
* Column visibility/width.
*/
tablePreferences: {
type: Object as PropType<TablePreferences>,
default: () => ({}),
},
/**
* Enable client side sort - only do this if using a fetcher
* that returns static data
*/
clientSort: {
type: Boolean,
default: false,
},
/**
* Enables hover highlighting to table rows
*/
rowHover: {
type: Boolean,
default: true,
},
sortHandlerFunction: {
type: Function,
default: () => ({}),
},
/**
* A function that conditionally specifies row attributes on each row
*/
rowAttrs: {
type: Function,
default: () => ({}),
},
/**
* A function that conditionally specifies cell attributes
*/
cellAttrs: {
type: Function,
default: () => ({}),
},
/**
* A prop that enables a loading skeleton
*/
loading: {
type: Boolean,
default: false,
},
/**
* A prop to pass in a custom empty state title
*/
emptyStateTitle: {
type: String,
default: 'No Data',
},
/**
* A prop to pass in a custom empty state message
*/
emptyStateMessage: {
type: String,
default: 'There is no data to display.',
},
/**
* A prop to pass in a custom empty state action route
*/
emptyStateActionRoute: {
type: [Object, String],
default: '',
},
/**
* A prop to pass in a custom empty state action message
*/
emptyStateActionMessage: {
type: String,
default: '',
},
emptyStateIconVariant: {
type: String as PropType<EmptyStateIconVariant>,
default: EmptyStateIconVariants.Default,
},
/**
* A prop that enables the error state
*/
error: {
type: Boolean,
default: false,
},
/**
* A prop to pass in a custom error state title
*/
errorStateTitle: {
type: String,
default: 'An error occurred',
},
/**
* A prop to pass in a custom error state message
*/
errorStateMessage: {
type: String,
default: 'Data cannot be displayed due to an error.',
},
/**
* A prop to pass in a custom error state action route
*/
errorStateActionRoute: {
type: [Object, String],
default: '',
},
/**
* A prop to pass in a custom error state action message
*/
errorStateActionMessage: {
type: String,
default: '',
},
/**
* A prop to pass in a fetcher function to enable server-side search, sort
* and pagination
*/
fetcher: {
type: Function,
default: undefined,
required: true,
},
/**
* A prop to trigger a revalidate of the fetcher function. Modifying this value
* will trigger a manual refetch of the table data.
*/
fetcherCacheKey: {
type: String,
default: '',
},
/**
* A prop used to uniquely identify this table in the swrv cache
*/
cacheIdentifier: {
type: String,
default: '',
},
/**
* A prop to pass in a search string for server-side search
*/
searchInput: {
type: String,
default: '',
},
/**
* A prop to pass in an array of headers for the table
*/
headers: {
type: Array as PropType<TableHeader[]>,
default: () => [],
},
/**
* A prop to pass in an object of intial params for the initial fetcher function call
*/
initialFetcherParams: {
type: Object,
default: null,
},
/**
* A prop to pass in the number of pagination neighbors used by the pagination component
*/
paginationNeighbors: {
type: Number,
default: 1,
},
/**
* A prop to pass in an array of page sizes used by the pagination component
*/
paginationPageSizes: {
type: Array as PropType<number[]>,
default: () => ([15, 30, 50, 75, 100]),
validator: (pageSizes: number[]): boolean => !!pageSizes.length && pageSizes.every(i => typeof i === 'number'),
},
/**
* A prop to pass the total number of items in the set for the pagination text
*/
paginationTotalItems: {
type: Number,
default: null,
},
disablePaginationPageJump: {
type: Boolean,
default: false,
},
sortable: {
type: Boolean,
default: true,
},
disablePagination: {
type: Boolean,
default: false,
},
paginationOffset: {
type: Boolean,
default: false,
},
/**
* A prop to pass to hide pagination for total table records is less than or equal to pagesize
*/
hidePaginationWhenOptional: {
type: Boolean,
default: false,
},
maxHeight: {
type: String,
default: 'none',
},
})
const emit = defineEmits<{
(e: 'cell-click', value: { data: any }): void
(e: 'row-click', value: { data: any }): void
(e: 'error-action-click'): void
(e: 'empty-state-action-click'): void
(e: 'update:table-preferences', preferences: TablePreferences): void
(e: 'sort', value: TableSortPayload): void
(e: 'state', value: TableStatePayload): void
}>()
const attrs = useAttrs()
const slots = useSlots()
const tableId = useUniqueId()
const defaultFetcherProps = {
pageSize: 15,
page: 1,
query: '',
sortColumnKey: '',
sortColumnOrder: 'desc',
offset: null,
}
const data = ref<Record<string, any>[]>([])
const headerRow = ref<HTMLDivElement>()
// all headers
const tableHeaders = ref<TableHeader[]>([])
// currently visible headers
const visibleHeaders = ref<TableHeader[]>([])
// highest priority - column currently being resized (mouse may be completely outside the column)
const resizingColumn = ref('')
// column the user is currently hovering over the resize handle for (may be hovered on the adjacent column to what we want to resize)
const resizerHoveredColumn = ref('')
// lowest priority - currently hovered resizable column (mouse is somewhere in the <th>)
const currentHoveredColumn = ref('')
const hasHidableColumns = computed((): boolean => tableHeaders.value.filter((header: TableHeader) => header.hidable).length > 0)
const hasColumnVisibilityMenu = computed((): boolean => {
// has hidable columns, no error/loading/empty state
return !!(hasHidableColumns.value &&
!props.error && !isTableLoading.value && !props.loading && (data.value && data.value.length))
})
// columns whose visibility can be toggled
const visibilityColumns = computed((): TableHeader[] => tableHeaders.value.filter((header: TableHeader) => header.hidable))
// visibility preferences from the host app (initialized by app)
const visibilityPreferences = computed((): Record<string, boolean> => hasColumnVisibilityMenu.value ? props.tablePreferences.columnVisibility || {} : {})
// current column visibility state
const columnVisibility = ref<Record<string, boolean>>(hasColumnVisibilityMenu.value ? props.tablePreferences.columnVisibility || {} : {})
const total = ref(0)
const isScrolled = ref(false)
const page = ref(1)
const pageSize = ref(15)
const filterQuery = ref('')
const sortColumnKey = ref('')
const sortColumnOrder = ref<SortColumnOrder>('desc')
const offset: Ref<string | null> = ref(null)
const offsets: Ref<Array<any>> = ref([])
const hasNextPage = ref(true)
const isClickable = ref(false)
const hasInitialized = ref(false)
const hasToolbarSlot = computed((): boolean => !!slots.toolbar || hasColumnVisibilityMenu.value)
const tableWrapperStyles = computed((): Record<string, string> => ({
maxHeight: getSizeFromString(props.maxHeight),
}))
/**
* Utilize a helper function to generate the column slot name.
* This helps TypeScript infer the slot name in the template section so that the slot props can be resolved.
* @param {string} columnKey The column.key
*/
const getColumnSlotName = (columnKey: string): TableColumnSlotName => {
return `column-${columnKey}`
}
/**
* Utilize a helper function to generate the column tooltip slot name.
* This helps TypeScript infer the slot name in the template section so that the slot props can be resolved.
* @param {string} columnKey The column.key
*/
const getColumnTooltipSlotName = (columnKey: string): TableColumnTooltipSlotName => {
return `tooltip-${columnKey}`
}
/**
* To avoid requiring the consuming app to typecast if they want to use `row` or `column`
* we strip the types to something generic before we put it in the slot for use.
* @param obj The object to strip the type from
*/
const getGeneric = (obj: Record<string, any>): any => {
return obj as unknown as any
}
/**
* Grabs listeners from attrs matching a prefix to attach the
* event that is dynamic. e.g. `v-on:cell:click`, `@row:focus` etc.
* @param {String} prefix - event listener prefix e.g. `row:`, `cell:`
* @param {any} attrs - attrs on the vue instance to pluck from
* @returns {Function} - returns a function that can pass an entity to the
listener callback function.
*/
const pluckListeners = (prefix: any, attrs: any): any => {
return (entity: any, type: any) => {
const onRE = /^on[^a-z]/
const listeners = {} as any
for (const property in attrs) {
if (onRE.test(property) && !!attrs[property]) {
listeners[property] = attrs[property]
}
}
return Object.keys(listeners).reduce((acc: any, curr) => {
if (curr.indexOf(prefix) === 0) {
const parts = curr.split(prefix)
acc[parts[1]] = (e: any) => listeners[curr](e, entity, type)
}
return acc
}, {})
}
}
const tdlisteners = computed((): any => {
return (entity: any, rowData: any) => {
const rowListeners = pluckListeners('onRow:', attrs)(rowData, 'row')
const cellListeners = pluckListeners('onCell:', attrs)(entity, 'cell')
const ignoredElements = ['a', 'button', 'label', 'input', 'select']
if (rowListeners.click) {
isClickable.value = true
}
return {
...rowListeners,
...cellListeners,
click(e: any) {
const targetClasses = e.target.className
let isIgnored = ignoredElements.includes(e.target.tagName.toLowerCase())
let isPopoverContent = false
// check for popover class
if (typeof targetClasses === 'string' || Array.isArray(targetClasses)) {
isPopoverContent = targetClasses.includes('k-popover')
} else if (typeof targetClasses === 'object') {
isPopoverContent = Object.keys(targetClasses).includes('k-popover')
}
// check parent for popover class
if (e.target.closest('.popover-content') !== null) {
isPopoverContent = true
}
// check parent of target is not an ignored elem
for (let i = 0; i < ignoredElements.length; i++) {
if (e.target.closest(ignoredElements[i]) !== null) {
isIgnored = true
break
}
}
// ignore click if it is from the popover, or is a non-disabled ignored element
if ((!isIgnored || e.target.hasAttribute('disabled')) &&
!isPopoverContent && (rowListeners.click || cellListeners.click)) {
if (cellListeners.click) {
emit('cell-click', { data: entity })
const result = cellListeners.click(e, entity, 'cell')
if (typeof result === 'function') {
result(e, entity)
}
} else {
emit('row-click', { data: rowData })
const result = rowListeners.click(e, rowData, 'row')
if (typeof result === 'function') {
result(e, rowData)
}
}
}
},
}
}
})
const columnWidths = ref<Record<string, number>>(props.resizeColumns ? props.tablePreferences.columnWidths || {} : {})
const columnStyles = computed(() => {
const styles: Record<string, any> = {}
for (const colKey in columnWidths.value) {
// no width set
if (!columnWidths.value[colKey]) {
continue
}
const width = columnWidths.value[colKey] + 'px'
styles[colKey] = {
width,
maxWidth: width,
minWidth: width,
}
}
return styles
})
const getHeaderClasses = (column: TableHeader, index: number): Record<string, boolean> => {
return {
// display the resize handle on the right side of the column if resizeColumns is enabled, hovering current column, and not the last column
'resize-hover': resizeHoverColumn.value === column.key && props.resizeColumns && index !== visibleHeaders.value.length - 1,
resizable: props.resizeColumns,
// display sort control if column is sortable, label is visible, and sorting is not disabled
sortable: props.sortable && !column.hideLabel && !!column.sortable,
// display active sorting styles if column is currently sorted
'active-sort': props.sortable && !column.hideLabel && !!column.sortable && column.key === sortColumnKey.value,
[sortColumnOrder.value]: props.sortable && column.key === sortColumnKey.value && !column.hideLabel,
'is-scrolled': isScrolled.value,
'has-tooltip': !!column.tooltip,
}
}
/**
* We have to track the state of all three hover events because
* they have differing priorities that can have clashing styles.
*/
const resizerHoverState = computed((): string => {
if (resizingColumn.value) {
// highest priority - resize event in progress, mouse may be completely outside of the column
return 'resizing'
} else if (resizerHoveredColumn.value) {
// hovered over a column resize handle (may need to trigger styles on the adjacent column instead of the current)
return 'resize-hover'
} else if (currentHoveredColumn.value) {
// lowest priority - hovered somewhere in the <th> of a resizable column
return 'th-hover'
}
return ''
})
const resizeHoverColumn = computed((): string => {
switch (resizerHoverState.value) {
case 'resizing':
return resizingColumn.value
case 'resize-hover':
return resizerHoveredColumn.value
case 'th-hover':
return currentHoveredColumn.value
default:
return ''
}
})
// get the resizable header divs to be used for the resize observers
// eslint-disable-next-line no-undef
const headerElems = computed((): NodeListOf<Element> | undefined => headerRow.value?.querySelectorAll('th.resizable'))
const headerHeight = computed((): string => {
const elem = headerElems.value?.item(0)
if (elem) {
const styles = window?.getComputedStyle(elem)
if (styles?.height) {
return `${parseInt(styles.height, 10)}px`
}
}
return 'auto'
})
const startResize = (evt: MouseEvent, colKey: string) => {
// right clicks should be ignored
if (evt.button !== 0) {
return
}
let x = 0
let width = 0
resizingColumn.value = colKey
// get the current column's element
let col: HTMLElement | null = null
headerElems.value?.forEach((elem) => {
if (elem.getAttribute('data-testid') === `table-header-${colKey}`) {
col = document?.querySelector(`[data-tableid="${tableId}"] [data-testid="table-header-${colKey}"]`)
}
})
// resize in progress
const mouseMoveHandler = (e: MouseEvent): void => {
// distance mouse has moved
const dx = e.clientX - x
// Update column width to match
col?.setAttribute('style', `width: ${width + dx}px`)
columnWidths.value[colKey] = width + dx
}
// done resizing
const mouseUpHandler = (): void => {
resizingColumn.value = ''
document?.removeEventListener('mousemove', mouseMoveHandler)
document?.removeEventListener('mouseup', mouseUpHandler)
emitTablePreferences()
}
// get mouse position
x = evt.clientX
if (col) {
// set current column's width
const styles = window?.getComputedStyle(col)
if (styles?.width) {
width = parseInt(styles.width, 10)
}
// event listeners for resizing
document?.addEventListener('mousemove', mouseMoveHandler)
document?.addEventListener('mouseup', mouseUpHandler)
}
}
const isInitialFetch = ref(true)
const fetchData = async () => {
const searchInput = props.searchInput
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const res = await props.fetcher({
pageSize: pageSize.value,
page: page.value,
query: searchInput || filterQuery.value,
sortColumnKey: sortColumnKey.value,
sortColumnOrder: sortColumnOrder.value,
offset: offset.value,
})
data.value = res.data as Record<string, any>[]
total.value = props.paginationTotalItems || res.total || res.data?.length
if (props.paginationOffset) {
if (!res.pagination?.offset) {
nextOffset.value = null
} else {
nextOffset.value = res.pagination.offset
if (!offsets.value[page.value]) {
offsets.value.push(res.pagination.offset)
}
}
hasNextPage.value = (res.pagination && 'hasNextPage' in res.pagination) ? res.pagination.hasNextPage : true
}
// if the data is empty and the page is greater than 1,
// e.g. user deletes the last item on the last page,
// reset the page to 1
if (data.value.length === 0 && page.value > 1) {
page.value = 1
offsets.value = [null]
offset.value = null
}
isInitialFetch.value = false
return res
}
const initData = () => {
const fetcherParams = {
...defaultFetcherProps,
...props.initialFetcherParams,
}
// don't allow overriding default settings with `undefined` values
page.value = fetcherParams.page ?? defaultFetcherProps.page
pageSize.value = fetcherParams.pageSize ?? defaultFetcherProps.pageSize
filterQuery.value = fetcherParams.query ?? defaultFetcherProps.query
sortColumnKey.value = fetcherParams.sortColumnKey ?? defaultFetcherProps.sortColumnKey
sortColumnOrder.value = fetcherParams.sortColumnOrder as SortColumnOrder ?? defaultFetcherProps.sortColumnOrder as SortColumnOrder
if (props.clientSort && sortColumnKey.value && sortColumnOrder.value) {
defaultClientSideSorter(sortColumnKey.value, '', sortColumnOrder.value, data.value)
}
if (props.paginationOffset) {
offset.value = fetcherParams.offset
offsets.value.push(fetcherParams.offset)
}
// get table headers
if (props.headers && props.headers.length) {
tableHeaders.value = props.headers
}
// trigger setting of tableFetcherCacheKey
hasInitialized.value = true
}
// Ensure `props.headers` are reactive.
watch(() => props.headers, (newVal: TableHeader[]) => {
if (newVal && newVal.length) {
tableHeaders.value = newVal
}
}, { deep: true })
const previousOffset = computed((): string | null => offsets.value[page.value - 1])
const nextOffset = ref<string | null>(null)
// once `initData()` finishes, setting tableFetcherCacheKey to non-falsey value triggers fetch of data
const tableFetcherCacheKey = computed((): string => {
if (!props.fetcher || !hasInitialized.value) {
return ''
}
// Set the default identifier to a random string
let identifierKey: string = tableId
if (props.cacheIdentifier) {
identifierKey = props.cacheIdentifier
}
if (props.fetcherCacheKey) {
identifierKey += `-${props.fetcherCacheKey}`
}
return `k-table_${identifierKey}`
})
const query = ref('')
const { debouncedFn: debouncedSearch, generateDebouncedFn: generateDebouncedSearch } = useDebounce((q: string) => {
query.value = q
}, 350)
const search = generateDebouncedSearch(0) // generate a debounced function with zero delay (immediate)
// ALL fetching is done through this useRequest / _revalidate
// don't fire until tableFetcherCacheKey is set
const { data: fetcherData, error: fetcherError, revalidate: _revalidate, isValidating: fetcherIsValidating } = useRequest(
() => tableFetcherCacheKey.value,
() => fetchData(),
{ revalidateOnFocus: false, revalidateDebounce: 0 },
)
const { state, hasData, swrvState } = useSwrvState(fetcherData, fetcherError, fetcherIsValidating)
const isTableLoading = ref<boolean>(true)
const stateData = computed((): SwrvStateData => ({
hasData: hasData.value,
state: state.value as SwrvState,
}))
const tableState = computed((): TableState => isTableLoading.value ? 'loading' : fetcherError.value ? 'error' : 'success')
const { debouncedFn: debouncedRevalidate, generateDebouncedFn: generateDebouncedRevalidate } = useDebounce(_revalidate, 500)
const revalidate = generateDebouncedRevalidate(0) // generate a debounced function with zero delay (immediate)
const sortClickHandler = (header: TableHeader): void => {
const { key, useSortHandlerFunction } = header
const prevKey = sortColumnKey.value + '' // avoid pass by ref
page.value = 1
if (sortColumnKey.value) {
if (key === sortColumnKey.value) {
if (sortColumnOrder.value === 'asc') {
sortColumnOrder.value = 'desc'
} else {
sortColumnOrder.value = 'asc'
}
} else {
sortColumnKey.value = key
sortColumnOrder.value = 'asc'
offsets.value = [null]
}
} else {
sortColumnKey.value = key
sortColumnOrder.value = 'asc'
offsets.value = [null]
}
if (props.clientSort) {
if (useSortHandlerFunction && props.sortHandlerFunction) {
props.sortHandlerFunction({
key,
prevKey,
sortColumnOrder: sortColumnOrder.value,
data: data.value,
})
} else {
defaultClientSideSorter(key, prevKey, sortColumnOrder.value, data.value)
}
} else if (!props.paginationOffset) {
debouncedRevalidate()
}
// Emit an event whenever one of the tablePreferences are updated
emitTablePreferences()
}
const pageChangeHandler = ({ page: newPage }: PageChangeData) => {
page.value = newPage
}
const pageSizeChangeHandler = ({ pageSize: newPageSize }: PageSizeChangeData) => {
offsets.value = [null]
offset.value = null
pageSize.value = newPageSize
page.value = 1
// Emit an event whenever one of the tablePreferences are updated
emitTablePreferences()
}
const scrollHandler = (event: any): void => {
if (event && event.target && typeof event.target.scrollTop === 'number') {