vuetable-next 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.eslintignore +4 -0
  2. package/.idea/easycode.ignore +13 -0
  3. package/.idea/inspectionProfiles/Project_Default.xml +6 -0
  4. package/.idea/jsLinters/eslint.xml +6 -0
  5. package/.idea/material_theme_project_new.xml +13 -0
  6. package/.idea/modules.xml +8 -0
  7. package/.idea/vcs.xml +6 -0
  8. package/.idea/vuetable-next.iml +12 -0
  9. package/.vscode/extensions.json +3 -0
  10. package/LICENSE +21 -0
  11. package/README.md +102 -0
  12. package/auto-imports.d.ts +21 -0
  13. package/dist/style.css +1 -0
  14. package/dist/vite.svg +1 -0
  15. package/dist/vuetable-next.js +6061 -0
  16. package/dist/vuetable-next.js.map +1 -0
  17. package/dist/vuetable-next.umd.cjs +36 -0
  18. package/dist/vuetable-next.umd.cjs.map +1 -0
  19. package/eslint.config.js +122 -0
  20. package/index.html +161 -0
  21. package/package.json +80 -0
  22. package/public/vite.svg +1 -0
  23. package/src/assets/vue.svg +1 -0
  24. package/src/components/Vuetable.vue +1212 -0
  25. package/src/components/VuetableColGroup.vue +66 -0
  26. package/src/components/VuetableColGutter.vue +25 -0
  27. package/src/components/VuetableCssSemanticUI.ts +36 -0
  28. package/src/components/VuetableFieldCheckbox.vue +87 -0
  29. package/src/components/VuetableFieldCheckboxMixin.vue +46 -0
  30. package/src/components/VuetableFieldHandle.vue +41 -0
  31. package/src/components/VuetableFieldMixin.vue +30 -0
  32. package/src/components/VuetableFieldSequence.vue +43 -0
  33. package/src/components/VuetablePagination.vue +119 -0
  34. package/src/components/VuetablePaginationDropdown.vue +88 -0
  35. package/src/components/VuetablePaginationInfo.vue +51 -0
  36. package/src/components/VuetablePaginationInfoMixin.vue +64 -0
  37. package/src/components/VuetablePaginationMixin.vue +107 -0
  38. package/src/components/VuetableRowHeader.vue +190 -0
  39. package/src/components/useVuetablePagination.ts +56 -0
  40. package/src/components/useVuetablePaginationInfo.ts +40 -0
  41. package/src/data/fields.ts +102 -0
  42. package/src/data/lang.ts +4 -0
  43. package/src/index.ts +59 -0
  44. package/src/main.ts +396 -0
  45. package/src/style.css +79 -0
  46. package/src/vite-env.d.ts +1 -0
  47. package/test/Vuetable.AJAX.test.ts +291 -0
  48. package/test/Vuetable.Composable.test.ts +151 -0
  49. package/test/Vuetable.Computed.test.ts +211 -0
  50. package/test/Vuetable.Features.test.ts +145 -0
  51. package/test/Vuetable.FieldsDefinition.test.ts +236 -0
  52. package/test/Vuetable.HTML.test.ts +16 -0
  53. package/test/Vuetable.Methods.test.ts +373 -0
  54. package/test/__snapshots__/Vuetable.HTML.test.ts.snap +85 -0
  55. package/tsconfig.app.json +32 -0
  56. package/tsconfig.json +16 -0
  57. package/tsconfig.node.json +13 -0
  58. package/vite.config.ts +29 -0
  59. package/vitest.config.ts +17 -0
@@ -0,0 +1,1212 @@
1
+ <template>
2
+ <div :class="$_css.tableWrapper">
3
+ <div
4
+ v-if="isFixedHeader"
5
+ class="vuetable-head-wrapper">
6
+ <table :class="['vuetable', $_css.tableClass, $_css.tableHeaderClass]">
7
+ <vuetable-col-group is-header>
8
+ </vuetable-col-group>
9
+ <thead>
10
+ <slot
11
+ :fields="tableFields"
12
+ name="tableHeader">
13
+ <template
14
+ :key="headerIndex"
15
+ v-for="(header, headerIndex) in headerRows">
16
+ <component
17
+ :is="header"
18
+ :index="headerIndex"
19
+ @vuetable:header-event="onHeaderEvent">
20
+ </component>
21
+ </template>
22
+ </slot>
23
+ </thead>
24
+ </table>
25
+ </div>
26
+
27
+ <div
28
+ :class="{'fixed-header' : isFixedHeader}"
29
+ :style="{ height: tableHeight! }"
30
+ class="vuetable-body-wrapper">
31
+ <table :class="['vuetable', isFixedHeader ? 'fixed-header' : '', $_css.tableClass, $_css.tableBodyClass]">
32
+ <vuetable-col-group>
33
+ </vuetable-col-group>
34
+ <thead v-if="!isFixedHeader">
35
+ <slot
36
+ :fields="tableFields"
37
+ name="tableHeader">
38
+ <template :key="headerIndex" v-for="(header, headerIndex) in headerRows">
39
+ <component
40
+ :is="header"
41
+ :index="headerIndex"
42
+ @vuetable:header-event="onHeaderEvent">
43
+ </component>
44
+ </template>
45
+ </slot>
46
+ </thead>
47
+ <tfoot>
48
+ <slot
49
+ :fields="tableFields"
50
+ name="tableFooter">
51
+ </slot>
52
+ </tfoot>
53
+ <tbody
54
+ v-cloak
55
+ class="vuetable-body">
56
+ <template
57
+ :key="itemIndex"
58
+ v-for="(item, itemIndex) in tableData">
59
+ <tr
60
+ :item-index="itemIndex"
61
+ :class="onRowClass(item, itemIndex)"
62
+ @click="onRowClicked(item, itemIndex, $event)"
63
+ @dblclick="onRowDoubleClicked(item, itemIndex, $event)"
64
+ @mouseover="onMouseOver(item, itemIndex, $event)">
65
+ <template v-for="(field, fieldIndex) in tableFields">
66
+ <template v-if="field.visible">
67
+ <template v-if="isFieldComponent(field.name)">
68
+ <component
69
+ :is="field.name"
70
+ :key="fieldIndex"
71
+ :row-data="item"
72
+ :row-index="itemIndex"
73
+ :row-field="field"
74
+ :class="bodyClass('vuetable-component', field)"
75
+ :style="{ width: field.width }"
76
+ @vuetable:field-event="onFieldEvent">
77
+ </component>
78
+ </template>
79
+ <template v-else-if="isFieldSlot(field.name)">
80
+ <td
81
+ :key="fieldIndex"
82
+ :class="bodyClass('vuetable-slot', field)"
83
+ :style="{ width: field.width! }">
84
+ <slot
85
+ :name="field.name"
86
+ :row-data="item" :row-index="itemIndex" :row-field="field">
87
+ </slot>
88
+ </td>
89
+ </template>
90
+ <template v-else>
91
+ <td
92
+ :key="fieldIndex"
93
+ :class="bodyClass('vuetable-td-'+field.name, field)"
94
+ :style="{ width: field.width! }"
95
+ v-html="renderNormalField(field, item)"
96
+ @click="onCellClicked(item, itemIndex, field, $event)"
97
+ @dblclick="onCellDoubleClicked(item, itemIndex, field, $event)"
98
+ @contextmenu="onCellRightClicked(item, itemIndex, field, $event)">
99
+ </td>
100
+ </template>
101
+ </template>
102
+ </template>
103
+ </tr>
104
+ <template v-if="useDetailRow">
105
+ <transition
106
+ :key="itemIndex"
107
+ :name="detailRowTransition">
108
+ <tr
109
+ v-if="isVisibleDetailRow(item[trackBy])"
110
+ :class="onDetailRowClass(item, itemIndex)"
111
+ @click="onDetailRowClick(item, itemIndex, $event)">
112
+ <td :colspan="countVisibleFields">
113
+ <component
114
+ :is="detailRowComponent"
115
+ :row-data="item"
116
+ :row-index="itemIndex"
117
+ :options="detailRowOptions">
118
+ </component>
119
+ </td>
120
+ </tr>
121
+ </transition>
122
+ </template>
123
+ </template>
124
+ <template v-if="displayEmptyDataRow">
125
+ <tr>
126
+ <td
127
+ :colspan="countVisibleFields"
128
+ class="vuetable-empty-result"
129
+ v-html="noDataTemplate">
130
+ </td>
131
+ </tr>
132
+ </template>
133
+ <template v-if="lessThanMinRows">
134
+ <tr
135
+ :key="i"
136
+ v-for="i in blankRows"
137
+ class="blank-row">
138
+ <template v-for="(field, fieldIndex) in tableFields">
139
+ <td v-if="field.visible" :key="fieldIndex">
140
+ &nbsp;
141
+ </td>
142
+ </template>
143
+ </tr>
144
+ </template>
145
+ </tbody>
146
+ </table>
147
+ </div>
148
+ </div>
149
+ </template>
150
+
151
+ <script setup lang="ts">
152
+ import type { AxiosPromise, AxiosResponse } from "axios";
153
+ import axios from "axios";
154
+ import VuetableRowHeader from "./VuetableRowHeader.vue";
155
+ import VuetableColGroup from "./VuetableColGroup.vue";
156
+ import CssSemanticUI from "./VuetableCssSemanticUI";
157
+ import {
158
+ defineProps,
159
+ defineSlots,
160
+ defineEmits,
161
+ defineExpose,
162
+ defineOptions,
163
+ ref,
164
+ reactive,
165
+ computed,
166
+ getCurrentInstance,
167
+ nextTick,
168
+ onMounted,
169
+ onUnmounted,
170
+ watch,
171
+ provide, toRefs
172
+ } from "vue-demi";
173
+ import type { ComponentPublicInstance, DefineComponent } from "vue-demi";
174
+ import { unref } from "vue";
175
+
176
+ type SortOrder = { field: string; sortField: string; direction: "asc" | "desc"; };
177
+
178
+ interface Props {
179
+ fields: any[]
180
+ loadOnStart?: boolean
181
+ apiUrl?: string
182
+ httpMethod?: "get" | "post"
183
+ reactiveApiUrl?: boolean
184
+ apiMode?: boolean
185
+ data?: any | null
186
+ dataManager?: ((sortOrder: SortOrder[], pagination: { [key: string]: any }) => any[]) | null
187
+ dataPath?: string
188
+ paginationPath?: string
189
+ queryParams?: { [key: string]: string | number } | ((sortOrder: string, currentPage: number, perPage: number) => { [key: string]: string | number } | string | number)
190
+ appendParams?: { [key: string]: string | number }
191
+ httpOptions?: Record<string, unknown>
192
+ httpFetch?: ((apiUrl: string, httpOptions: Record<string, unknown>) => AxiosResponse) | null
193
+ perPage?: number
194
+ initialPage?: number /** Page that should be displayed when the table is first displayed */
195
+ firstPage?: number /** First page number. Set this prop to 0 for zero based pagination */
196
+ sortOrder?: SortOrder[] | string
197
+ multiSort?: boolean
198
+ tableHeight?: string | null
199
+ /*
200
+ * physical key that will trigger multi-sort option
201
+ * possible values: 'alt', 'ctrl', 'meta', 'shift'
202
+ * 'ctrl' might not work as expected on Mac
203
+ */
204
+ multiSortKey?: "alt" | "ctrl" | "meta"| "shift"
205
+ rowClass?: string | ((...args: any[]) => string | string[] | { [key: string]: boolean })
206
+ detailRowComponent?: string | { [key: string]: any }
207
+ detailRowTransition?: string
208
+ detailRowClass?: string | ((...args: any[]) => any)
209
+ detailRowOptions?: { [key: string]: any }
210
+ trackBy?: string
211
+ css?: { [key: string]: any }
212
+ minRows?: number
213
+ silent?: boolean
214
+ noDataTemplate?: string
215
+ showSortIcons?: boolean
216
+ headerRows?: string[]
217
+ transform?: ((response: AxiosResponse) => any) | null
218
+ sortParams?: ((sortOrder: string | SortOrder[]) => string) | null
219
+ fieldPrefix?: string
220
+ }
221
+
222
+ interface Field {
223
+ name: string | DefineComponent
224
+ sortField: string | null
225
+ title: string | ((str?: any) => string)
226
+ titleClass: string
227
+ dataClass: string
228
+ formatter: (<T>(...args: any[]) => T) | null
229
+ visible: boolean
230
+ width: string | null
231
+ $_index: number
232
+ [key: string]: unknown
233
+ }
234
+
235
+ interface Pagination {
236
+ first_page: number
237
+ last_page: number
238
+ current_page: number
239
+ }
240
+
241
+ const {
242
+ fields,
243
+ loadOnStart = true,
244
+ apiUrl = "",
245
+ httpMethod = "get",
246
+ reactiveApiUrl = true,
247
+ apiMode = true,
248
+ data = null,
249
+ dataManager = null,
250
+ dataPath = "data",
251
+ paginationPath = "links.pagination",
252
+ queryParams = {
253
+ sort: "sort",
254
+ page: "page",
255
+ perPage: "per_page"
256
+ },
257
+ appendParams = {},
258
+ httpOptions = {},
259
+ httpFetch = null,
260
+ perPage = 10,
261
+ initialPage = 1,
262
+ firstPage = 1,
263
+ sortOrder = [],
264
+ multiSort = false,
265
+ tableHeight = null,
266
+ multiSortKey = "alt",
267
+ rowClass = "",
268
+ detailRowComponent = "",
269
+ detailRowTransition = "",
270
+ detailRowClass = "vuetable-detail-row",
271
+ detailRowOptions = {},
272
+ trackBy = "id",
273
+ css = {},
274
+ minRows = 0,
275
+ silent = false,
276
+ noDataTemplate = "No Data Available",
277
+ headerRows = ["VuetableRowHeader"],
278
+ transform = null,
279
+ sortParams = null,
280
+ fieldPrefix = "vuetable-field-",
281
+ showSortIcons = true
282
+ } = defineProps<Props>();
283
+
284
+ const emit = defineEmits<{
285
+ "vuetable:load-error": [response?: AxiosResponse],
286
+ "vuetable:load-success": [response?: AxiosResponse],
287
+ "vuetable:loaded": [],
288
+ "vuetable:loading": [],
289
+ "vuetable:scrollbar-visible": [visible: boolean],
290
+ "vuetable:pagination-data": [tablePagination: Pagination | null],
291
+ "vuetable:row-clicked": [args: { data: any; index: number; event: Event }],
292
+ "vuetable:row-dblclicked": [args: { data: any; index: number; event: Event }],
293
+ "vuetable:detail-row-clicked": [args: { data: any; index: number; event: Event }],
294
+ "vuetable:cell-clicked": [args: { data: any; index: number; field: Field; event: Event }],
295
+ "vuetable:cell-dblclicked": [args: { data: any; index: number; field: Field; event: Event }],
296
+ "vuetable:cell-rightclicked": [args: { data: any; index: number; field: Field; event: Event }],
297
+ "vuetable:row-mouseover": [args: { data: any; index: number; event: Event }],
298
+ "vuetable:field-event": [type: string, payload: any, app?: ComponentPublicInstance | null],
299
+ "vuetable:header-event": [type: string, payload: any, app?: ComponentPublicInstance | null],
300
+ "vuetable:checkbox-toggled": [isChecked: boolean, fieldName: string],
301
+ "vuetable:checkbox-toggled-all": [isChecked: boolean],
302
+ "vuetable:data-reset": [],
303
+ "vuetable:initialized": [tableFields: Field[]]
304
+ }>();
305
+
306
+ const slots = defineSlots();
307
+
308
+ defineOptions({
309
+ name: "Vuetable",
310
+ components: {
311
+ VuetableRowHeader,
312
+ VuetableColGroup,
313
+ }
314
+ });
315
+
316
+ const app = getCurrentInstance();
317
+
318
+ const tableFields = ref<Field[]>([]);
319
+ const tableData = ref<any[] | null>(null);
320
+ const tablePagination = ref<Pagination | null>(null);
321
+ const currentPage = ref(initialPage);
322
+ const selectedTo = ref<string[]>([]);
323
+ const visibleDetailRows = ref<any[]>([]);
324
+ const lastScrollPosition = ref(0);
325
+ const scrollBarWidth = ref("17px");
326
+ const scrollVisible = ref(false);
327
+ const order = ref<SortOrder[]>(sortOrder as SortOrder[]);
328
+ const optionsHttp = ref<Record<string, unknown>>(httpOptions);
329
+ const instanceFetch = ref<Promise<AxiosResponse>>();
330
+
331
+ const $_css = reactive({ ...CssSemanticUI.table, ...css });
332
+
333
+ const dataIsAvailable = computed(() => tableData.value?.length! > 0 ?? false);
334
+ const useDetailRow = computed(() => dataIsAvailable.value && detailRowComponent !== "");
335
+ const hasRowIdentifier = computed(() => tableData.value && typeof tableData.value[0][trackBy] !== "undefined");
336
+ const countVisibleFields = computed(() => tableFields.value.filter(field => field.visible).length);
337
+ const countTableData = computed(() => tableData.value?.length || 0);
338
+ const displayEmptyDataRow = computed(() => countTableData.value === 0 && noDataTemplate.length > 0);
339
+
340
+ const emptyDataTable = computed(() => tableData.value === null || tableData.value?.length === 0);
341
+ const lessThanMinRows = computed(() => emptyDataTable.value ? true : tableData.value!.length < minRows);
342
+ const blankRows = computed(() => emptyDataTable.value ? minRows : tableData.value!.length >= minRows ? 0 : minRows - tableData.value!.length);
343
+
344
+ const isApiMode = computed(() => apiMode);
345
+ const isDataMode = computed(() => !apiMode);
346
+ const isFixedHeader = computed(() => tableHeight != null);
347
+ const vuetable = computed(() => app?.proxy);
348
+
349
+ normalizeFields();
350
+ normalizeSortOrder();
351
+
352
+ nextTick( () => {
353
+ emit("vuetable:initialized", tableFields.value);
354
+ });
355
+
356
+ onMounted(() => {
357
+ if (loadOnStart) {
358
+ loadData();
359
+ }
360
+
361
+ if (isFixedHeader) {
362
+ scrollBarWidth.value = getScrollBarWidth() + "px";
363
+
364
+ let elem = app?.proxy?.$el.getElementsByClassName("vuetable-body-wrapper")[0];
365
+ if (elem != null) {
366
+ elem.addEventListener("scroll", handleScroll);
367
+ }
368
+ }
369
+ });
370
+
371
+ onUnmounted(() => {
372
+ let elem = app?.proxy?.$el.getElementsByClassName("vuetable-body-wrapper")[0];
373
+ if (elem != null) {
374
+ elem.removeEventListener("scroll", handleScroll);
375
+ }
376
+ });
377
+
378
+ defineExpose({
379
+ apiUrl,
380
+ isApiMode,
381
+ tableFields,
382
+ tableData,
383
+ tablePagination,
384
+ fieldPrefix,
385
+ countVisibleFields,
386
+ dataIsAvailable,
387
+ countTableData,
388
+ displayEmptyDataRow,
389
+ useDetailRow,
390
+ hasRowIdentifier,
391
+ lessThanMinRows,
392
+ blankRows,
393
+ scrollVisible,
394
+ scrollBarWidth,
395
+ trackBy,
396
+ showSortIcons,
397
+ instanceFetch,
398
+ setData,
399
+ getFieldTitle,
400
+ orderBy,
401
+ camelCase,
402
+ clearSortOrder,
403
+ toggleDetailRow,
404
+ clearSelectedValues,
405
+ showField,
406
+ hideField,
407
+ toggleField,
408
+ onCheckboxToggled,
409
+ onCheckboxToggledAll,
410
+ checkIfRowIdentifierExists,
411
+ changePage,
412
+ resetData,
413
+ refresh,
414
+ isFieldComponent,
415
+ makeTitle,
416
+ getAllQueryParams,
417
+ isSortable,
418
+ getDefaultSortParam,
419
+ getObjectValue,
420
+ isSelectedRow,
421
+ loadData
422
+ });
423
+
424
+ provide("vuetable", {
425
+ isApiMode,
426
+ fieldPrefix,
427
+ tableFields: unref(tableFields),
428
+ tableData: unref(tableData),
429
+ tablePagination: unref(tablePagination),
430
+ countVisibleFields: unref(countVisibleFields),
431
+ dataIsAvailable: unref(dataIsAvailable),
432
+ countTableData: unref(countTableData),
433
+ displayEmptyDataRow: unref(displayEmptyDataRow),
434
+ useDetailRow: unref(useDetailRow),
435
+ hasRowIdentifier: unref(hasRowIdentifier),
436
+ lessThanMinRows: unref(lessThanMinRows),
437
+ blankRows: unref(blankRows),
438
+ scrollVisible: unref(scrollVisible),
439
+ scrollBarWidth: unref(scrollBarWidth),
440
+ sortOrder,
441
+ trackBy,
442
+ showSortIcons,
443
+ css: toRefs($_css),
444
+ isFieldSlot,
445
+ setData,
446
+ getFieldTitle,
447
+ orderBy,
448
+ camelCase,
449
+ clearSortOrder,
450
+ toggleDetailRow,
451
+ clearSelectedValues,
452
+ showField,
453
+ hideField,
454
+ toggleField,
455
+ onCheckboxToggled,
456
+ onCheckboxToggledAll,
457
+ checkIfRowIdentifierExists,
458
+ changePage,
459
+ resetData,
460
+ refresh,
461
+ isFieldComponent,
462
+ makeTitle,
463
+ getAllQueryParams,
464
+ isSortable,
465
+ getDefaultSortParam,
466
+ getObjectValue,
467
+ isSelectedRow
468
+ });
469
+ // provide("tableData", tableData);
470
+ // provide("tableFields", tableFields);
471
+ // provide("scrollBarWidth", scrollBarWidth);
472
+ // provide("sortOrder", sortOrder);
473
+ // provide("$_css", $_css);
474
+ // provide("fieldPrefix", fieldPrefix);
475
+ // provide("showSortIcons", showSortIcons);
476
+ // provide("trackBy", trackBy);
477
+ // provide("isSortable", isSortable);
478
+ // provide("onHeaderEvent", onHeaderEvent);
479
+ // provide("orderBy", orderBy);
480
+ // provide("onCheckboxToggled", onCheckboxToggled);
481
+ // provide("onCheckboxToggledAll", onCheckboxToggledAll);
482
+ // provide("isSelectedRow", isSelectedRow);
483
+ // provide("perPage", isSelectedRow);
484
+
485
+ function getScrollBarWidth () {
486
+ const outer = document.createElement("div");
487
+ const inner = document.createElement("div");
488
+
489
+ outer.style.visibility = "hidden";
490
+ outer.style.width = "100px";
491
+
492
+ inner.style.width = "100%";
493
+
494
+ outer.appendChild(inner);
495
+ document.body.appendChild(outer);
496
+
497
+ const widthWithoutScrollbar = outer.offsetWidth;
498
+ outer.style.overflow = "scroll";
499
+ const widthWithScrollbar = inner.offsetWidth;
500
+ document.body.removeChild(outer);
501
+
502
+ return (widthWithoutScrollbar - widthWithScrollbar);
503
+ }
504
+
505
+ //make sure that the header and the body are aligned when scrolling horizontally on a table that is wider than the viewport
506
+ function handleScroll (e: { currentTarget: HTMLElement }) {
507
+ const horizontal = e.currentTarget?.scrollLeft;
508
+
509
+ //don't modify header scroll if we are scrolling vertically
510
+ if (horizontal != lastScrollPosition.value) {
511
+ let header = vuetable.value?.$el.getElementsByClassName("vuetable-head-wrapper")[0];
512
+ if (header != null) {
513
+ header.scrollLeft = horizontal;
514
+ }
515
+ lastScrollPosition.value = horizontal;
516
+ }
517
+ }
518
+
519
+ function warn (msg: string) {
520
+ if (!silent) {
521
+ console.warn(msg);
522
+ }
523
+ }
524
+
525
+ function bodyClass (base: string, field: Field): string[] {
526
+ return [ base, field.dataClass ];
527
+ }
528
+
529
+ function normalizeFields () {
530
+ if (typeof fields === "undefined") {
531
+ warn("You need to provide \"fields\" prop.");
532
+ return;
533
+ }
534
+
535
+ tableFields.value = [];
536
+
537
+ fields.forEach( (field, i) => {
538
+ tableFields.value.push(newField(field, i));
539
+ });
540
+ }
541
+
542
+ function newField (field: Field | string, index: number): Field {
543
+ const defaultField = {
544
+ name: "",
545
+ // title:
546
+ // this allow the code to detect undefined title
547
+ // and replace it with capitalized name instead
548
+ titleClass: "",
549
+ dataClass: "",
550
+ sortField: null,
551
+ formatter: null,
552
+ visible: true,
553
+ width: null,
554
+ $_index: index,
555
+ };
556
+
557
+ if (typeof field === "string") {
558
+ return {
559
+ ...defaultField,
560
+ name: normalizeFieldName(field),
561
+ title: makeTitle(field)
562
+ };
563
+ }
564
+
565
+ const obj = Object.assign({}, defaultField, field) as Field;
566
+ obj.name = normalizeFieldName(obj.name);
567
+ if (obj.title === undefined) {
568
+ obj.title = makeTitle(obj.name as string);
569
+ }
570
+ if (obj.formatter !== null && typeof obj.formatter !== "function") {
571
+ console.error(obj.name + " field formatter must be a function");
572
+ obj.formatter = null;
573
+ }
574
+ return obj;
575
+ }
576
+
577
+ function normalizeFieldName (fieldName: string | DefineComponent) {
578
+ if (fieldName instanceof Object) {
579
+ return fieldName;
580
+ }
581
+
582
+ return fieldName.replace("__", fieldPrefix);
583
+ }
584
+
585
+ function setData (data: any | null) {
586
+ if (data === null || typeof(data) === "undefined") return;
587
+
588
+ emit("vuetable:loading");
589
+
590
+ if (Array.isArray(data)) {
591
+ tableData.value = data;
592
+ emit("vuetable:loaded");
593
+ return;
594
+ }
595
+
596
+ tableData.value = getObjectValue(data, dataPath, null);
597
+ tablePagination.value = getObjectValue(data, paginationPath, null);
598
+
599
+ nextTick( () => {
600
+ checkIfRowIdentifierExists();
601
+ updateHeader();
602
+ emit("vuetable:pagination-data", tablePagination.value);
603
+ emit("vuetable:loaded");
604
+ });
605
+ }
606
+
607
+ function checkIfRowIdentifierExists () {
608
+ if (!dataIsAvailable.value) {
609
+ return;
610
+ }
611
+
612
+ if (!hasRowIdentifier.value) {
613
+ warn("Invalid your data! Use \"track-by\" prop to specify.");
614
+ return false;
615
+ }
616
+
617
+ return true;
618
+ }
619
+
620
+ function makeTitle (str: string | DefineComponent) {
621
+ return isFieldComponent(str) ? "" : titleCase(str.replace(".", " "));
622
+ }
623
+
624
+ function getFieldTitle (field: Field): string {
625
+ if (typeof field.title === "function") {
626
+ return field.title();
627
+ }
628
+
629
+ return field.title;
630
+ }
631
+
632
+ function renderNormalField (field: Field, item: any) {
633
+ return hasFormatter(field) ? callFormatter(field, item) : getObjectValue(item, field.name, "");
634
+ }
635
+
636
+ function isFieldComponent (fieldName: any) {
637
+ if (fieldName instanceof Object) {
638
+ // let's assume it is a Vue component
639
+ return true;
640
+ }
641
+
642
+ return fieldName.slice(0, fieldPrefix.length) === fieldPrefix || fieldName.slice(0, 2) === "__";
643
+ }
644
+
645
+ function isFieldSlot (fieldName: string) {
646
+ return typeof slots[fieldName] !== "undefined";
647
+ }
648
+
649
+ function titleCase (str: string) {
650
+ return str.replace(/\w+/g, txt => txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase());
651
+ }
652
+
653
+ function camelCase (str: string, delimiter = "_") {
654
+ return str.split(delimiter).map(item => titleCase(item)).join("");
655
+ }
656
+
657
+ function loadData (success = loadSuccess, failed = loadFailed) {
658
+ if (isDataMode.value) {
659
+ handleDataMode();
660
+ return;
661
+ }
662
+
663
+ emit("vuetable:loading");
664
+
665
+ optionsHttp.value["params"] = getAppendParams(getAllQueryParams());
666
+
667
+ instanceFetch.value = fetch(apiUrl, optionsHttp.value);
668
+
669
+ return instanceFetch.value.then(
670
+ success,
671
+ failed
672
+ ).catch(() => failed());
673
+ }
674
+
675
+ async function fetch (apiUrl: string, httpOptions: Record<string, unknown>): Promise<AxiosResponse> {
676
+ if (httpFetch) {
677
+ return httpFetch(apiUrl, httpOptions);
678
+ }
679
+ if (httpMethod === "get") {
680
+ return axios.get(apiUrl, httpOptions);
681
+ }
682
+ else { // Is a POST request
683
+ const params = await optionsHttp.value.params;
684
+ delete httpOptions.params;
685
+ delete optionsHttp.value.params;
686
+ return axios.post(apiUrl, params, optionsHttp.value);
687
+ }
688
+ }
689
+
690
+ function loadSuccess (response: AxiosResponse) {
691
+ emit("vuetable:load-success", response);
692
+
693
+ const body = transform ? transform(response!.data) : response!.data;
694
+
695
+ tableData.value = getObjectValue(body, dataPath, null);
696
+ tablePagination.value = getObjectValue(body, paginationPath, null);
697
+
698
+ if (tablePagination.value === null) {
699
+ warn(`vuetable: pagination-path ${ paginationPath } not found.
700
+ It looks like the data returned from the server does not have pagination information
701
+ or you may have set it incorrectly.\n
702
+ You can explicitly suppress this warning by setting pagination-path="".`);
703
+ }
704
+
705
+ nextTick( () => {
706
+ checkIfRowIdentifierExists();
707
+ updateHeader();
708
+ emit("vuetable:pagination-data", tablePagination.value);
709
+ emit("vuetable:loaded");
710
+ });
711
+ }
712
+
713
+ function updateHeader () {
714
+ // nextTick doesn't seem to work in all cases. This might be because
715
+ // nextTick is finished before the transition element (just my guess)
716
+ //
717
+ // the scrollHeight value does not yet changed, causing scrollVisible
718
+ // to remain "true", therefore, the header gutter never gets updated
719
+ // to reflect the display of scrollbar in the table body.
720
+ // setTimeout 80ms seems to work in this case.
721
+ setTimeout(checkScrollbarVisibility, 80);
722
+ }
723
+
724
+ function checkScrollbarVisibility () {
725
+ nextTick( () => {
726
+ let elem = vuetable.value?.$el.getElementsByClassName("vuetable-body-wrapper")[0];
727
+ if (elem != null) {
728
+ scrollVisible.value = (elem.scrollHeight > elem.clientHeight);
729
+ emit("vuetable:scrollbar-visible", scrollVisible.value);
730
+ }
731
+ });
732
+ }
733
+
734
+ function loadFailed (response?: AxiosResponse) {
735
+ console.error("load-error", response);
736
+ emit("vuetable:load-error", response);
737
+ emit("vuetable:loaded");
738
+ }
739
+
740
+ function getAllQueryParams () {
741
+ let params: Record<string, string | number> | string | number = {};
742
+
743
+ if (typeof queryParams === "function") {
744
+ params = queryParams(order.value, currentPage.value, perPage);
745
+ return typeof params === "object" ? params : {};
746
+ }
747
+
748
+ params[queryParams.sort] = getSortParam();
749
+ params[queryParams.page] = currentPage.value;
750
+ params[queryParams.perPage] = perPage;
751
+
752
+ return params;
753
+ }
754
+
755
+ function getSortParam () {
756
+ if (!order.value || order.value[0]?.field == "") {
757
+ return "";
758
+ }
759
+
760
+ if (typeof sortParams === "function") {
761
+ return sortParams(order.value);
762
+ }
763
+
764
+ return getDefaultSortParam();
765
+ }
766
+
767
+ function getDefaultSortParam () {
768
+ return order.value.map(item => `${item.sortField}|${item.direction}`).join(",");
769
+ }
770
+
771
+ function getAppendParams (params: Record<string, string | number>) {
772
+ for (let x in appendParams) {
773
+ params[x] = appendParams[x];
774
+ }
775
+
776
+ return params;
777
+ }
778
+
779
+ function isSortable (field: Field) {
780
+ return field.sortField !== null;
781
+ }
782
+
783
+ function currentSortOrderPosition (field: Field) {
784
+ if (!isSortable(field)) {
785
+ return false;
786
+ }
787
+
788
+ for (let i = 0; i < order.value.length; i++) {
789
+ if (fieldIsInSortOrderPosition(field, i)) {
790
+ return i;
791
+ }
792
+ }
793
+
794
+ return false;
795
+ }
796
+
797
+ function fieldIsInSortOrderPosition (field: Field, i: number) {
798
+ return order.value[i].field === field.name && order.value[i].sortField === field.sortField;
799
+ }
800
+
801
+ function orderBy (field: Field, event: Event & { [key: string]: string }) {
802
+ if (!isSortable(field) ) return;
803
+
804
+ const key = multiSortKey.toLowerCase() + "Key";
805
+
806
+ if (multiSort && event[key]) { //adding column to multisort
807
+ multiColumnSort(field);
808
+ } else {
809
+ //no multisort, or resetting sort
810
+ singleColumnSort(field);
811
+ }
812
+
813
+ currentPage.value = firstPage; // reset page index
814
+ if (isApiMode.value || dataManager) {
815
+ loadData();
816
+ }
817
+ }
818
+
819
+ function addSortColumn (field: Field, direction?: "asc" | "desc") {
820
+ order.value.push({
821
+ field: field.name as string,
822
+ sortField: field.sortField!,
823
+ direction: direction || "asc"
824
+ });
825
+ }
826
+
827
+ function removeSortColumn (index: number) {
828
+ order.value.splice(index, 1);
829
+ }
830
+
831
+ function setSortColumnDirection (index: number, direction: "asc" | "desc") {
832
+ order.value[index].direction = direction;
833
+ }
834
+
835
+ function multiColumnSort (field: Field) {
836
+ let i = currentSortOrderPosition(field);
837
+
838
+ if (i === false) { //this field is not in the sort array yet
839
+ addSortColumn(field, "asc");
840
+ } else { //this field is in the sort array, now we change its state
841
+ if (order.value[i].direction === "asc") {
842
+ // switch direction
843
+ setSortColumnDirection(i, "desc");
844
+ } else {
845
+ removeSortColumn(i);
846
+ }
847
+ }
848
+ }
849
+
850
+ function singleColumnSort (field: Field) {
851
+ if (sortOrder.length === 0) {
852
+ // this.clearSortOrder()
853
+ addSortColumn(field, "asc");
854
+ return;
855
+ }
856
+
857
+ order.value.splice(1); //removes additional columns
858
+
859
+ if (fieldIsInSortOrderPosition(field, 0)) {
860
+ // change sort direction
861
+ order.value[0].direction = sortOrder[0].direction === "asc" ? "desc" : "asc";
862
+ } else {
863
+ // reset sort direction
864
+ order.value[0].direction = "asc";
865
+ }
866
+ order.value[0].field = field.name as string;
867
+ order.value[0].sortField = field.sortField!;
868
+ }
869
+
870
+ function clearSortOrder () {
871
+ order.value = [];
872
+ }
873
+
874
+ function hasFormatter (item: Field) {
875
+ return typeof item.formatter === "function";
876
+ }
877
+
878
+ function callFormatter (field: Field, item: any) {
879
+ if (!hasFormatter(field)) return;
880
+
881
+ if (typeof(field.formatter) === "function") {
882
+ return field.formatter(getObjectValue(item, field.name), app?.proxy);
883
+ }
884
+ }
885
+
886
+ function getObjectValue (object: any, path: string | DefineComponent, defaultValue?: any) {
887
+ defaultValue = (typeof defaultValue === "undefined") ? null : defaultValue;
888
+
889
+ let obj = object;
890
+ if (path.trim() != "") {
891
+ let keys = path.split(".");
892
+ keys.forEach( (key: string) => {
893
+ if (obj !== null && typeof obj[key] !== "undefined" && obj[key] !== null) {
894
+ obj = obj[key];
895
+ } else {
896
+ obj = defaultValue;
897
+ return;
898
+ }
899
+ });
900
+ }
901
+ return obj;
902
+ }
903
+
904
+ function selectId (key: string) {
905
+ if (!isSelectedRow(key)) {
906
+ selectedTo.value.push(key);
907
+ }
908
+ }
909
+
910
+ function unselectId (key: string) {
911
+ selectedTo.value = selectedTo.value.filter(item => {
912
+ return item !== key;
913
+ });
914
+ }
915
+
916
+ function isSelectedRow (key: string) {
917
+ return selectedTo.value.indexOf(key) >= 0;
918
+ }
919
+
920
+ function clearSelectedValues () {
921
+ selectedTo.value = [];
922
+ }
923
+
924
+ function gotoPreviousPage () {
925
+ if (currentPage.value > firstPage) {
926
+ currentPage.value -= 1;
927
+ loadData();
928
+ }
929
+ }
930
+
931
+ function gotoNextPage () {
932
+ if (currentPage.value < tablePagination.value!.last_page) {
933
+ currentPage.value += 1;
934
+ loadData();
935
+ }
936
+ }
937
+
938
+ function gotoPage (page: number) {
939
+ if (page != currentPage.value && (page >= firstPage && page <= tablePagination.value!.last_page)) {
940
+ currentPage.value = page;
941
+ loadData();
942
+ }
943
+ }
944
+
945
+ function isVisibleDetailRow (rowId: string) {
946
+ return visibleDetailRows.value.indexOf(rowId) >= 0;
947
+ }
948
+
949
+ function showDetailRow (rowId: string) {
950
+ if (!isVisibleDetailRow(rowId)) {
951
+ visibleDetailRows.value.push(rowId);
952
+ }
953
+ checkScrollbarVisibility();
954
+ }
955
+
956
+ function hideDetailRow (rowId: string) {
957
+ if (isVisibleDetailRow(rowId)) {
958
+ visibleDetailRows.value.splice(
959
+ visibleDetailRows.value.indexOf(rowId),
960
+ 1
961
+ );
962
+ updateHeader();
963
+ }
964
+ }
965
+
966
+ function toggleDetailRow (rowId: string) {
967
+ if (isVisibleDetailRow(rowId)) {
968
+ hideDetailRow(rowId);
969
+ } else {
970
+ showDetailRow(rowId);
971
+ }
972
+ }
973
+
974
+ function showField (index: number) {
975
+ if (index < 0 || index > tableFields.value.length) return;
976
+
977
+ tableFields.value[index].visible = true;
978
+ }
979
+
980
+ function hideField (index: number) {
981
+ if (index < 0 || index > tableFields.value.length) return;
982
+
983
+ tableFields.value[index].visible = false;
984
+ }
985
+
986
+ function toggleField (index: number) {
987
+ if (index < 0 || index > tableFields.value.length) return;
988
+
989
+ tableFields.value[index].visible = !tableFields.value[index].visible;
990
+ }
991
+
992
+ function makePagination (total: number | null = null, per_page: number | null = null, current_page: number | null = null) {
993
+ total = total === null ? 0 : total;
994
+ per_page = per_page === null ? perPage : per_page;
995
+ current_page = current_page === null ? currentPage.value : current_page;
996
+
997
+ return {
998
+ "total": total,
999
+ "per_page": perPage,
1000
+ "current_page": currentPage.value,
1001
+ "last_page": Math.ceil(total / perPage) || 0,
1002
+ "next_page_url": "",
1003
+ "prev_page_url": "",
1004
+ "from": (current_page -1) * per_page +1,
1005
+ "to": Math.min(current_page * per_page, total)
1006
+ };
1007
+ }
1008
+
1009
+ function normalizeSortOrder () {
1010
+ order.value.forEach(item => {
1011
+ item.sortField = item.sortField || item.field;
1012
+ });
1013
+ }
1014
+
1015
+ function handleDataMode () {
1016
+ // data is array
1017
+ if (data !== null && Array.isArray(data)) {
1018
+ setData(data);
1019
+ return;
1020
+ }
1021
+
1022
+ // data must be an object, check if dataManager is present
1023
+ if (dataManager) {
1024
+ callDataManager();
1025
+ } else {
1026
+ setData(data);
1027
+ }
1028
+ }
1029
+
1030
+ function callDataManager () {
1031
+ const result = dataManager!(order.value, makePagination()) as any;
1032
+
1033
+ if (isPromiseObject(result)) {
1034
+ result.then((data: any[]) => setData(data));
1035
+ } else {
1036
+ setData(result);
1037
+ }
1038
+ }
1039
+
1040
+ function isObject (unknown: AxiosPromise) {
1041
+ return typeof unknown === "object" && unknown !== null;
1042
+ }
1043
+
1044
+ function isPromiseObject (unknown: any) {
1045
+ return isObject(unknown) && typeof(unknown.then) === "function";
1046
+ }
1047
+
1048
+ function onRowClass (dataItem: any, index: number) {
1049
+ if (typeof rowClass === "function") {
1050
+ return rowClass(dataItem, index);
1051
+ }
1052
+
1053
+ return rowClass;
1054
+ }
1055
+
1056
+ function onDetailRowClass (dataItem: any, index: number): string {
1057
+ if (typeof(detailRowClass) === "function") {
1058
+ return detailRowClass(dataItem, index);
1059
+ }
1060
+
1061
+ return detailRowClass;
1062
+ }
1063
+
1064
+ function onRowClicked (data: any, index: number, event: Event) {
1065
+ emit("vuetable:row-clicked", { data, index, event });
1066
+ return true;
1067
+ }
1068
+
1069
+ function onRowDoubleClicked (data: any, index: number, event: Event) {
1070
+ emit("vuetable:row-dblclicked", { data, index, event });
1071
+ }
1072
+
1073
+ function onDetailRowClick (data: any, index: number, event: Event) {
1074
+ emit("vuetable:detail-row-clicked", { data, index, event });
1075
+ }
1076
+
1077
+ function onCellClicked (data: any, index: number, field: Field, event: Event) {
1078
+ emit("vuetable:cell-clicked", { data, index, field, event });
1079
+ }
1080
+
1081
+ function onCellDoubleClicked (data: any, index: number, field: Field, event: Event) {
1082
+ emit("vuetable:cell-dblclicked", { data, index, field, event });
1083
+ }
1084
+
1085
+ function onCellRightClicked (data: any, index: number, field: Field, event: Event) {
1086
+ emit("vuetable:cell-rightclicked", { data, index, field, event });
1087
+ }
1088
+
1089
+ function onMouseOver (data: any, index: number, event: Event) {
1090
+ emit("vuetable:row-mouseover", { data, index, event });
1091
+ }
1092
+
1093
+ function onFieldEvent (type: string, payload: any) {
1094
+ emit("vuetable:field-event", type, payload, app?.proxy);
1095
+ }
1096
+
1097
+ function onHeaderEvent (type: string, payload: any) {
1098
+ emit("vuetable:header-event", type, payload, app?.proxy);
1099
+ }
1100
+
1101
+ function onCheckboxToggled (isChecked: boolean, fieldName: string, dataItem: any) {
1102
+ if (dataItem[trackBy] === undefined) {
1103
+ warn(`checkbox field: The "${ trackBy }" field does not exist! Make sure the field you specify in "track-by" prop does exist.`);
1104
+ return;
1105
+ }
1106
+
1107
+ const key = dataItem[trackBy];
1108
+ if (isChecked) {
1109
+ selectId(key);
1110
+ } else {
1111
+ unselectId(key);
1112
+ }
1113
+
1114
+ emit("vuetable:checkbox-toggled", isChecked, fieldName);
1115
+ }
1116
+
1117
+ function onCheckboxToggledAll (isChecked: boolean) {
1118
+ if (isChecked) {
1119
+ tableData.value?.forEach( (dataItem) => {
1120
+ selectId(dataItem[trackBy]);
1121
+ });
1122
+ } else {
1123
+ tableData.value?.forEach( (dataItem) => {
1124
+ unselectId(dataItem[trackBy]);
1125
+ });
1126
+ }
1127
+
1128
+ emit("vuetable:checkbox-toggled-all", isChecked);
1129
+ }
1130
+
1131
+ /*
1132
+ * API for externals
1133
+ */
1134
+ function changePage (page: string | number) {
1135
+ if (page === "prev") {
1136
+ gotoPreviousPage();
1137
+ } else if (page === "next") {
1138
+ gotoNextPage();
1139
+ } else {
1140
+ gotoPage(page as number);
1141
+ }
1142
+ }
1143
+
1144
+ function reload () {
1145
+ return loadData();
1146
+ }
1147
+
1148
+ function refresh () {
1149
+ currentPage.value = firstPage;
1150
+ return loadData();
1151
+ }
1152
+
1153
+ function resetData () {
1154
+ tableData.value = null;
1155
+ tablePagination.value = null;
1156
+ emit("vuetable:data-reset");
1157
+ }
1158
+
1159
+ watch(() => multiSort, value => {
1160
+ if (!value && order.value.length > 1) {
1161
+ order.value.splice(1);
1162
+ loadData();
1163
+ }
1164
+ });
1165
+
1166
+ watch(() => apiUrl, (newValue, oldValue) => reactiveApiUrl && newValue !== oldValue && refresh());
1167
+ watch(() => data, setData, { immediate: true });
1168
+ watch(() => tableHeight, checkScrollbarVisibility);
1169
+ watch(() => fields, normalizeFields, { immediate: true });
1170
+ watch(() => perPage, reload);
1171
+
1172
+ // No mutation props
1173
+ watch(() => sortOrder, value => {
1174
+ order.value = value;
1175
+ }, { immediate: true });
1176
+ watch(() => httpOptions, value => {
1177
+ optionsHttp.value = value;
1178
+ }, { immediate: true });
1179
+ </script>
1180
+
1181
+ <style>
1182
+ [v-cloak] {
1183
+ display: none;
1184
+ }
1185
+ table.vuetable.fixed-header {
1186
+ table-layout: fixed;
1187
+ }
1188
+ .vuetable th.sortable:hover {
1189
+ color: #2185d0;
1190
+ cursor: pointer;
1191
+ }
1192
+ .vuetable-head-wrapper {
1193
+ overflow-x: hidden;
1194
+ }
1195
+ .vuetable-head-wrapper table.vuetable {
1196
+ border-bottom-left-radius: 0px;
1197
+ border-bottom-right-radius: 0px;
1198
+ }
1199
+ .vuetable-body-wrapper.fixed-header {
1200
+ position:relative;
1201
+ overflow-y:auto;
1202
+ }
1203
+ .vuetable-body-wrapper table.vuetable.fixed-header {
1204
+ border-top:none !important;
1205
+ margin-top:0 !important;
1206
+ border-top-left-radius: 0px;
1207
+ border-top-right-radius: 0px;
1208
+ }
1209
+ .vuetable-empty-result {
1210
+ text-align: center;
1211
+ }
1212
+ </style>