@isoftdata/svelte-table 2.7.0 → 2.8.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.
package/dist/Table.svelte CHANGED
@@ -1,1032 +1,1061 @@
1
- <script module>
2
- import { getBootstrapCdnVersion } from '@isoftdata/utility-bootstrap'
3
- let bs5 = $state(false)
4
- try {
5
- bs5 = getBootstrapCdnVersion() === 5
6
- } catch (e) {
7
- onMount(() => {
8
- bs5 = getBootstrapCdnVersion() === 5
9
- })
10
- }
11
- </script>
12
-
13
- <script
14
- lang="ts"
15
- generics="R extends UuidRowProps"
16
- >
17
- import type { Snippet } from 'svelte'
18
-
19
- import { ColumnInfoRunicStore } from './column-info-store.svelte'
20
-
21
- import type { i18n } from 'i18next'
22
- import type { Get } from 'type-fest'
23
- import type { Column as GenericColumn, SortDirection, UuidRowProps, RowProperties, FooterReducerValue } from './'
24
-
25
- import { writable, type Writable } from 'svelte/store'
26
-
27
- import Pagination from './Pagination.svelte'
28
- import Td from './Td.svelte'
29
- import Input from '@isoftdata/svelte-input'
30
- import ContextMenu, { DropdownItem } from '@isoftdata/svelte-context-menu'
31
- import { v4 as uuid } from '@lukeed/uuid'
32
- import { format as formatCurrency } from '@isoftdata/utility-currency'
33
- import { setContext, tick, onMount, getContext, untrack } from 'svelte'
34
- import { on } from 'svelte/events'
35
- import naturalCompare from 'natural-compare-lite'
36
- import type { HTMLTableAttributes, ClassValue } from 'svelte/elements'
37
- import { translate as defaultTranslate } from '@isoftdata/utility-string'
38
-
39
- const { t: translate } = getContext<i18n>('i18next') || { t: defaultTranslate }
40
-
41
- type K = keyof R
42
- type KeyPath = RowProperties<R>
43
- type IndexedRow = R & { originalIndex: number; uuid: string }
44
- type GetRowProperty = Get<R, KeyPath>
45
- type GetIndexedRowProperty = Get<IndexedRow, RowProperties<IndexedRow>>
46
- type FooterValue = {
47
- property: KeyPath
48
- value: FooterReducerValue<R>
49
- }
50
- // Type hack so passing an array of columns without the type argument doesn't reduce the type of R to any
51
- type Column = GenericColumn<R & {}>
52
-
53
- interface Props extends Omit<HTMLTableAttributes, 'children' | `aria-${string}` | `bind:${string}` | `on:${string}`> {
54
- filterEnabled?: boolean
55
- columns: Array<Column>
56
- tableId?: string
57
- rows: Array<R>
58
- sortDirection?: SortDirection
59
- sortColumn?: Column | undefined
60
- class?: ClassValue
61
- perPageCount?: number
62
- currentPageNumber?: number
63
- showFooter?: boolean
64
- footers?: Array<FooterValue>
65
- lazySort?: boolean //when true, the table can only be resorted when the user clicks on a column header(not real time as data changes)
66
- idProp?: K | 'uuid' //required for lazy sorting.
67
- previousSortOrder?: Array<IndexedRow & { order: number }>
68
- filterProps?: Array<KeyPath> | false
69
- filter?: string
70
- filterLabel?: string
71
- filterPlaceholder?: string
72
- filterDisabled?: boolean
73
- filterReadonly?: boolean
74
- filterLazy?: boolean | number
75
- showFilterLabel?: boolean
76
- headerRowClass?: ClassValue
77
- headerColumnClass?: ClassValue
78
- filterColumnClass?: ClassValue
79
- columnHidingEnabled?: boolean
80
- selectionEnabled?: boolean
81
- // Array<number> | Array<string> | Array<R[K]> ???
82
- selectedRowIds?: Array<GetIndexedRowProperty>
83
- rowSelectionIdProp?: KeyPath | 'uuid'
84
- rowSelectionRequiresModKey?: boolean
85
- selectionMode?: 'SINGLE' | 'RANGE' | null
86
- multiSelectEnabled?: boolean
87
- lastClickedIdForRange?: GetIndexedRowProperty | undefined
88
- totalItemsCount?: number
89
- stickyHeader?: boolean
90
- responsive?: boolean | 'sm' | 'md' | 'lg' | 'xl'
91
- size?: 'sm' | ''
92
- striped?: boolean
93
- /** When true, enables tree-specific features. Required if you want to use `TreeRow`s. */
94
- tree?: boolean
95
- bordered?: boolean
96
- hover?: boolean
97
- previousSortColumn?: Column | undefined
98
- previousSortDirection?: SortDirection | undefined
99
- parentClass?: ClassValue
100
- parentStyle?: string
101
- hideButtonClass?: ClassValue
102
- columnResizingEnabled?: boolean
103
- /** If specified, where to serialize the columnInfo store */
104
- localStorageKey?: string | undefined
105
- columnClickedMethod?: typeof defaultColumnClicked
106
- filterMethod?: typeof defaultFilter
107
- rowMatchesFilterMethod?: typeof defaultRowMatchesFilter
108
- filteredRows?: Array<IndexedRow>
109
- sortedRows?: Array<IndexedRow>
110
- currentPageRows?: Array<IndexedRow>
111
- // snippets
112
- header?: Snippet
113
- body?: Snippet<[{ rows: Array<R & { originalIndex: number; uuid: string }>; visibleColumnsCount: number }]>
114
- children?: Snippet<[{ row: R & { originalIndex: number; uuid: string }; index: number }]>
115
- noRows?: Snippet<[{ visibleColumnsCount: number }]>
116
- footerRow?: Snippet<[{ footers: Array<FooterValue> }]>
117
- // callbacks
118
- pageChange?: (context: { pageNumber: number }) => void
119
- columnResizeEnd?: (context: { column: Column }) => void
120
- }
121
-
122
- const uid = $props.id()
123
-
124
- let {
125
- filterEnabled = false,
126
- columns,
127
- tableId = uid,
128
- rows,
129
- sortDirection = $bindable('ASC'),
130
- sortColumn = $bindable(undefined),
131
- class: tableClass = '',
132
- perPageCount = 0,
133
- currentPageNumber = $bindable(1),
134
- showFooter = false,
135
- lazySort = false,
136
- idProp = 'uuid',
137
- previousSortOrder = $bindable([]),
138
- filterProps = false,
139
- filter = $bindable(''),
140
- filterLabel = translate('common:filter', 'Filter'),
141
- filterPlaceholder = translate('common:filter', 'Filter'),
142
- filterDisabled = false,
143
- filterReadonly = false,
144
- filterLazy = false,
145
- showFilterLabel = false,
146
- headerRowClass = bs5 ? 'row' : 'form-row',
147
- headerColumnClass = 'col',
148
- filterColumnClass = 'col-lg-2 col-md-4 col-sm-6 align-self-end',
149
- columnHidingEnabled = false,
150
- selectionEnabled = false,
151
- selectedRowIds = $bindable([]),
152
- rowSelectionIdProp = 'uuid',
153
- rowSelectionRequiresModKey = false,
154
- selectionMode = $bindable(null),
155
- multiSelectEnabled = true,
156
- lastClickedIdForRange = $bindable(undefined),
157
- totalItemsCount = 0,
158
- stickyHeader = false,
159
- responsive = false,
160
- size = 'sm',
161
- striped = true,
162
- tree = false,
163
- bordered = true,
164
- hover = true,
165
- previousSortColumn = $bindable(undefined),
166
- previousSortDirection = $bindable(undefined),
167
- parentClass = '',
168
- parentStyle = '',
169
- hideButtonClass = '',
170
- columnResizingEnabled = false,
171
- localStorageKey = undefined,
172
- columnClickedMethod = defaultColumnClicked,
173
- filterMethod = defaultFilter,
174
- rowMatchesFilterMethod = defaultRowMatchesFilter,
175
- filteredRows = $bindable(filterMethod('', rows, columns)),
176
- sortedRows = $bindable(filteredRows),
177
- currentPageRows = $bindable(sortedRows.slice(0, perPageCount)),
178
- // snippets
179
- header,
180
- body,
181
- children,
182
- noRows,
183
- footerRow,
184
- // callbacks
185
- pageChange,
186
- columnResizeEnd,
187
- ...rest
188
- }: Props = $props()
189
-
190
- let lastPageNumber: number = $state(1)
191
- let paginationComponent: Pagination<IndexedRow> | undefined = $state()
192
- let contextMenu: ContextMenu | undefined = $state()
193
- let contextMenuColumn: Column | undefined = $state()
194
- let columnResizingIsActive: boolean = $state(false)
195
- /** Set to true after getting initial table widths when resizing enabled*/
196
- let useFixedLayout = $state(false)
197
- let tableParent: HTMLDivElement | undefined = $state()
198
-
199
- // Do the initial sort if they specified a default sort column
200
- const defaultSortColumn = columns.find(column => column.defaultSortColumn)
201
- if (defaultSortColumn) {
202
- sortColumn = defaultSortColumn
203
- sortDirection = defaultSortColumn.defaultSortDirection || 'ASC'
204
-
205
- doSort({
206
- rows: filteredRows,
207
- sortColumn,
208
- sortDirection,
209
- sameSortOrder: false,
210
- })
211
- }
212
-
213
- // Need to track which rows are expanded so when the rows reorder, they correctly keep that state.
214
- const expandedRows = writable<Record<number | string, boolean>>({})
215
- if (tree) {
216
- setContext('expandedRows', expandedRows)
217
- }
218
-
219
- // TODO: bad things will happen if we update any of our apps to use Runes for the store if we don't account for that here
220
- const session = getContext<Writable<{ userAccountId?: number }> | undefined>('session')
221
- // This will be accessible on the component instance, ie `const columnInfo = $derived(table?.columnInfo)` if you need it
222
- export const columnInfo = new ColumnInfoRunicStore<R>(() => columns, {
223
- key: localStorageKey,
224
- userAccountId: session && $session ? $session.userAccountId : undefined,
225
- })
226
- // Set as context so we can retrieve it in the Td component
227
- setContext('columnInfo', columnInfo)
228
- // Set as context so we can retrieve it in the TreeRow component
229
- const selectedRowIdsStore = writable(selectedRowIds)
230
- setContext('selectedRowIds', selectedRowIdsStore)
231
- setContext('idProp', idProp)
232
- setContext('columnResizingEnabled', writable(columnResizingEnabled))
233
- setContext('bs5', bs5)
234
-
235
- // #endregion
236
- // #region Functions
237
- export async function defaultColumnClicked(clickedColumn: Column, sortDirection: SortDirection) {
238
- if (currentPageNumber !== lastPageNumber) {
239
- paginationComponent?.setPageNumber(1)
240
- }
241
-
242
- doSort({
243
- rows: filteredRows,
244
- sortColumn: clickedColumn,
245
- sortDirection,
246
- sameSortOrder: false,
247
- })
248
- }
249
-
250
- function defaultFilter(filter: string, rows: R[], columns: Column[]): IndexedRow[] {
251
- const columnProps = columns?.map(({ property }) => property)
252
-
253
- if (filterEnabled) {
254
- const props = filterProps || columnProps
255
- return getFilterMatches(filter, rows, props)
256
- }
257
-
258
- return rows.map((row, index): IndexedRow => ({ ...row, originalIndex: index, uuid: row.uuid || uuid() }))
259
- }
260
-
261
- /** In normal mode, returns all rows matching the filter.
262
- *
263
- * In tree mode, shows all children if parent matches, or shows matching children and their children
264
- */
265
- function getFilterMatches(filter: string, theRows: Array<R>, props: KeyPath[]) {
266
- return theRows.reduce((rows, row, index): IndexedRow[] => {
267
- if (rowMatchesFilterMethod(filter, row, props)) {
268
- rows.push({ ...row, originalIndex: index, uuid: 'uuid' in row ? (row.uuid as string) : uuid() })
269
- } else if (tree && Array.isArray(row.children) && row.children.length) {
270
- const children = getFilterMatches(filter, row.children, props)
271
- if (children.length) {
272
- rows.push({ ...row, children, originalIndex: index, uuid: 'uuid' in row ? (row.uuid as string) : uuid() })
273
- }
274
- }
275
-
276
- return rows
277
- }, new Array<IndexedRow>())
278
- }
279
-
280
- export function defaultRowMatchesFilter(filter: string, row: R, props: Array<RowProperties<R>>) {
281
- return (
282
- !filter ||
283
- props.some(prop => {
284
- const value = getNestedProperty(row, prop)
285
- if (typeof value === 'string' || typeof value === 'number') {
286
- return value.toString().toUpperCase().indexOf(filter.toUpperCase()) > -1
287
- }
288
- return false
289
- })
290
- )
291
- }
292
-
293
- export function getNestedProperty(
294
- row: R & { uuid: string },
295
- path: KeyPath | 'uuid',
296
- defaultValue?: string | number,
297
- ): GetIndexedRowProperty
298
- export function getNestedProperty(row: R, path: KeyPath, defaultValue?: string | number): GetRowProperty
299
- export function getNestedProperty(
300
- row: R | (R & { uuid: string }),
301
- path: KeyPath | 'uuid',
302
- defaultValue?: string | number,
303
- ): GetRowProperty | GetIndexedRowProperty {
304
- if (!path) {
305
- return defaultValue as GetRowProperty
306
- }
307
-
308
- if (row[path]) {
309
- return row[path] as GetRowProperty
310
- }
311
-
312
- const val =
313
- path
314
- .split('[')
315
- // TODO figure out if we can do this less evilly
316
- .reduce((obj, prop) => (obj as any)?.[prop.replace(/\]/g, '')], row as any) ?? defaultValue
317
- return val
318
- }
319
-
320
- async function columnClickHandler(clickedColumn: Column) {
321
- if (clickedColumn.sortType === false || columnResizingIsActive) {
322
- return
323
- }
324
- sortDirection = sortDirection === 'ASC' && clickedColumn.property === sortColumn?.property ? 'DESC' : 'ASC'
325
-
326
- columnClickedMethod(clickedColumn, sortDirection)
327
-
328
- sortColumn = clickedColumn
329
- await tick()
330
- }
331
-
332
- export function expandRow(rowId: string | number, expanded = true) {
333
- if (tree) {
334
- $expandedRows[rowId] = expanded
335
- } else {
336
- console.warn('expandRow should only be used when the `tree` prop is set to true on the Table component.')
337
- }
338
- }
339
-
340
- export function rowIsSelected(
341
- row: IndexedRow,
342
- rowSelectionIdProp: KeyPath | 'uuid',
343
- selectedRowIds: Array<GetIndexedRowProperty>,
344
- ) {
345
- const selectionId = getNestedProperty(row, rowSelectionIdProp, row.uuid)
346
- return selectedRowIds.includes(selectionId)
347
- }
348
-
349
- export function rowClick(row: IndexedRow) {
350
- if (!selectionEnabled || !rowSelectionIdProp) {
351
- return
352
- }
353
- const clickedId = getNestedProperty(row, rowSelectionIdProp || 'uuid')
354
-
355
- const selectedIds = selectedRowIds
356
-
357
- let newSelectedIds: Array<GetIndexedRowProperty> = []
358
-
359
- if (!selectionMode && !rowSelectionRequiresModKey) {
360
- selectionMode = 'SINGLE'
361
- }
362
-
363
- if (selectionMode === 'SINGLE') {
364
- newSelectedIds = selectedIds
365
- const foundInExistingSelections = selectedIds.some(id => id === clickedId)
366
-
367
- if (foundInExistingSelections) {
368
- newSelectedIds = newSelectedIds.filter(id => id !== clickedId)
369
- } else if (multiSelectEnabled) {
370
- newSelectedIds = newSelectedIds.concat(clickedId)
371
- } else {
372
- newSelectedIds = [clickedId]
373
- }
374
- } else if (selectionMode === 'RANGE') {
375
- if (selectedIds.length < 1) {
376
- newSelectedIds = [clickedId]
377
- } else {
378
- newSelectedIds = selectedIds
379
- const clickedItemIndex = sortedRows.findIndex(item => {
380
- return item[rowSelectionIdProp] === clickedId
381
- })
382
-
383
- const lastSelectedIndex = sortedRows.findIndex(item => {
384
- return item[rowSelectionIdProp] === lastClickedIdForRange
385
- })
386
-
387
- let selectionDirection: 'UP' | 'DOWN' | undefined
388
-
389
- if (lastSelectedIndex > clickedItemIndex) {
390
- selectionDirection = 'UP'
391
- } else if (lastSelectedIndex < clickedItemIndex) {
392
- selectionDirection = 'DOWN'
393
- }
394
-
395
- if (selectionDirection) {
396
- sortedRows.forEach((item, index) => {
397
- if (selectionDirection === 'UP' && index <= lastSelectedIndex && index >= clickedItemIndex) {
398
- newSelectedIds = newSelectedIds.concat(getNestedProperty(item, rowSelectionIdProp))
399
- } else if (selectionDirection === 'DOWN' && index >= lastSelectedIndex && index <= clickedItemIndex) {
400
- newSelectedIds = newSelectedIds.concat(getNestedProperty(item, rowSelectionIdProp))
401
- }
402
- })
403
- }
404
- }
405
- } else {
406
- return
407
- }
408
-
409
- const clickedIdWasAdded = newSelectedIds.find(id => id === clickedId)
410
-
411
- let lastClickedId: GetIndexedRowProperty | undefined
412
-
413
- if (newSelectedIds.length === 0) {
414
- lastClickedId = undefined
415
- } else if (selectionMode === 'SINGLE' && clickedIdWasAdded) {
416
- lastClickedId = clickedId
417
- } else {
418
- lastClickedId = lastClickedIdForRange
419
- }
420
-
421
- selectedRowIds = [...new Set(newSelectedIds)]
422
- lastClickedIdForRange = lastClickedId
423
- }
424
- export function setPageVisibleByItemIndex(index: number) {
425
- if (index > -1) {
426
- paginationComponent?.setPageVisibleByItemIndex(index)
427
- }
428
- }
429
- export function setPageVisibleByItemId({ id, keyName }: { id: number | string; keyName: K }) {
430
- const index = sortedRows.findIndex(item => item[keyName] == id)
431
-
432
- if (index > -1) {
433
- paginationComponent?.setPageVisibleByItemIndex(index)
434
- }
435
- }
436
- export function doSort({
437
- rows,
438
- sortColumn,
439
- sortDirection,
440
- sameSortOrder,
441
- }: {
442
- rows: Array<IndexedRow>
443
- sortColumn: Column | undefined
444
- sortDirection: SortDirection
445
- sameSortOrder: boolean
446
- }) {
447
- const keepSameSortOrder = !!(lazySort && sameSortOrder && idProp)
448
- const hasPreviousSort = previousSortColumn && previousSortOrder.length > 0
449
-
450
- let sortProp: KeyPath
451
-
452
- if (keepSameSortOrder && hasPreviousSort && previousSortColumn && idProp) {
453
- sortColumn = previousSortColumn
454
- sortProp = sortColumn.property
455
- sortDirection = 'ASC' //force ASC for keeping the same order because we defined the order in previousSortOrder
456
-
457
- rows = rows.map(row => {
458
- const foundItem = previousSortOrder.find(
459
- previousSortOrderRow => !!idProp && previousSortOrderRow[idProp] === row[idProp],
460
- )
461
-
462
- return { ...row, order: foundItem ? foundItem.order : 0 }
463
- })
464
- } else if (sortColumn?.property) {
465
- sortProp = sortColumn.property
466
- } else {
467
- // no sort property, can't sort
468
- sortedRows = rows
469
- return
470
- }
471
-
472
- function doTheSort(theRows: Array<IndexedRow>): Array<IndexedRow> {
473
- if (tree) {
474
- return theRows
475
- .slice()
476
- .map(row => {
477
- if (Array.isArray(row.children)) {
478
- return {
479
- ...row,
480
- children: doTheSort(row.children),
481
- }
482
- }
483
- return row
484
- })
485
- .sort((a: IndexedRow, b: IndexedRow) =>
486
- sortColumn?.sortType === 'ALPHA_NUM' ? alphaNumSort(a, b) : standardSort(a, b),
487
- )
488
- }
489
- return theRows.slice().sort(sortColumn?.sortType === 'ALPHA_NUM' ? alphaNumSort : standardSort)
490
- }
491
-
492
- const theSortedRows = doTheSort(rows)
493
-
494
- previousSortOrder = theSortedRows.map((row, index) => ({
495
- ...row,
496
- order: index,
497
- }))
498
- previousSortDirection = sortDirection
499
- previousSortColumn = sortColumn
500
- sortedRows = theSortedRows
501
- return
502
-
503
- function standardSort(a: R, b: R) {
504
- let aValue: Get<R, KeyPath> | string = getNestedProperty(a, sortProp, '')
505
- let bValue: Get<R, KeyPath> | string = getNestedProperty(b, sortProp, '')
506
-
507
- if (typeof aValue === 'string') {
508
- aValue = aValue.toUpperCase()
509
- }
510
- if (typeof bValue === 'string') {
511
- bValue = bValue.toUpperCase()
512
- }
513
-
514
- if (aValue < bValue) {
515
- return sortDirection === 'ASC' ? -1 : 1
516
- }
517
- if (aValue > bValue) {
518
- return sortDirection === 'ASC' ? 1 : -1
519
- }
520
-
521
- return 0
522
- }
523
-
524
- function alphaNumSort(a: R, b: R) {
525
- const aValue = getNestedProperty(a, sortProp, '')
526
- const bValue = getNestedProperty(b, sortProp, '')
527
- let compareResults = 0
528
- if (
529
- (typeof aValue === 'number' || typeof aValue === 'string') &&
530
- (typeof bValue === 'number' || typeof bValue === 'string')
531
- ) {
532
- compareResults = naturalCompare(aValue.toString(), bValue.toString())
533
- } else if (typeof aValue === 'number' || typeof aValue === 'string') {
534
- compareResults = 1
535
- } else if (typeof bValue === 'number' || typeof bValue === 'string') {
536
- compareResults = -1
537
- }
538
-
539
- return sortDirection === 'ASC' ? compareResults : compareResults * -1
540
- }
541
- }
542
-
543
- export function setColumnVisibility(columnProperties: Array<KeyPath> | KeyPath, visible: boolean) {
544
- if (!Array.isArray(columnProperties)) {
545
- columnProperties = [columnProperties]
546
- }
547
-
548
- try {
549
- untrack(() => {
550
- columnInfo.updateColumns(
551
- columnProperties.map((property): { property: RowProperties<R>; visible: boolean } => ({
552
- property,
553
- visible,
554
- })),
555
- )
556
- })
557
- } catch (err) {
558
- console.error(`Error setting column visibility for columns ${JSON.stringify(columnProperties)}`, err)
559
- }
560
- }
561
-
562
- /** When called in `onMount` or an effect, will set the visibility of the specified columns whenever the value of `getVisible()` changes*/
563
- export function setColumnVisibilityWatch(columnProperties: Array<KeyPath> | KeyPath, getVisible: () => boolean) {
564
- $effect(() => {
565
- const visible = getVisible()
566
- setColumnVisibility(columnProperties, visible)
567
- })
568
- }
569
-
570
- function hideColumn(column: Column) {
571
- if (column) {
572
- columnInfo.updateColumn(column.property, { visible: false })
573
- }
574
- contextMenuColumn = undefined
575
- }
576
-
577
- function showColumn(column: Column) {
578
- if (column) {
579
- columnInfo.updateColumn(column.property, { visible: true })
580
- }
581
- contextMenuColumn = undefined
582
- }
583
-
584
- function contextMenuHandler(event: MouseEvent, column: string) {
585
- if ((columnHidingEnabled || columnResizingEnabled) && !event.ctrlKey) {
586
- event.preventDefault()
587
- contextMenuColumn = columnInfo.current[column]
588
- return contextMenu?.open(event, `col-${tableId}-${CSS.escape(column)}`)
589
- }
590
- return Promise.resolve()
591
- }
592
- // #endregion
593
- // #region Tree-specific functions
594
-
595
- // #endregion
596
-
597
- function onColumnMouseDown(event: MouseEvent, column: Column) {
598
- event.stopPropagation()
599
- if (!event.target || !(event.target instanceof HTMLDivElement)) {
600
- return
601
- }
602
-
603
- const htmlColumn = tableParent?.querySelector<HTMLTableCellElement>(
604
- `#col-${tableId}-${CSS.escape(column.property)}`,
605
- )
606
- const columnIndex = columns.findIndex(col => col.property === column.property)
607
- if (!htmlColumn || columnIndex === -1) {
608
- return
609
- }
610
-
611
- const mouseDownPageX = event.pageX
612
- const mouseDownColumnWidth = htmlColumn.offsetWidth
613
-
614
- event.target.classList.add('resizing')
615
- columnResizingIsActive = true
616
-
617
- const mouseMoveHandler = (mouseMoveEvent: MouseEvent) => {
618
- const widthDifference = mouseMoveEvent.pageX - mouseDownPageX
619
- const newWidth = `${mouseDownColumnWidth + widthDifference}px`
620
- htmlColumn.style.width = column.minWidth ? `max(${newWidth}, ${column.minWidth})` : newWidth
621
- }
622
-
623
- const mouseUpHandler = () => {
624
- if (!(event.target instanceof HTMLDivElement)) {
625
- return
626
- }
627
- event.target.classList.remove('resizing')
628
- columnInfo.updateColumn(column.property, { userWidth: htmlColumn.style.width })
629
-
630
- removeMouseMoveListener?.()
631
- removeMouseUpListener?.()
632
- columnResizeEnd?.({ column: columns[columnIndex] })
633
- // We want to ensure the user's mouseup event doesn't trigger a click event on the column header
634
- setTimeout(() => (columnResizingIsActive = false), 50)
635
- }
636
-
637
- const removeMouseMoveListener = tableParent ? on(tableParent, 'mousemove', mouseMoveHandler) : undefined
638
- const removeMouseUpListener = tableParent ? on(tableParent, 'mouseup', mouseUpHandler) : undefined
639
- }
640
-
641
- async function setDefaultColumnWidths() {
642
- useFixedLayout = false
643
- await tick()
644
- if (columnResizingEnabled) {
645
- columnInfo.updateColumns(
646
- columns.map((column): { property: RowProperties<R>; userWidth: string } => {
647
- const thisColumnInfo = columnInfo.current[column.property]
648
- const prevUserWidth = thisColumnInfo?.userWidth
649
- // Minimum width will be inherited from the layout on reset, but this won't, so re-set it here if needed
650
- const explicitWidth = thisColumnInfo?.width
651
-
652
- return {
653
- property: column.property,
654
- userWidth: prevUserWidth ?? explicitWidth ?? getColumnThWidth(column.property),
655
- }
656
- }),
657
- )
658
- useFixedLayout = true
659
- }
660
- }
661
-
662
- function getColumnThWidth(property: string) {
663
- const thWidth =
664
- tableParent?.querySelector<HTMLTableCellElement>(`#col-${tableId}-${CSS.escape(property)}`)?.offsetWidth ?? 25
665
- return `${thWidth}px`
666
- }
667
- // #region Computed
668
- $effect(() => {
669
- selectedRowIdsStore.set(selectedRowIds)
670
- })
671
-
672
- $effect(() => {
673
- filteredRows = filterMethod(filter, rows, columns)
674
- // Should only run when filter/rows/columns changes since everything else is untracked
675
- untrack(() =>
676
- doSort({
677
- rows: filteredRows && Array.isArray(filteredRows) ? filteredRows : [],
678
- sortColumn: sortColumn,
679
- sortDirection: sortDirection,
680
- sameSortOrder: true,
681
- }),
682
- )
683
- })
684
-
685
- const responsiveClass = $derived(
686
- responsive === true ? 'table-responsive' : !!responsive ? `table-responsive-${responsive}` : '',
687
- )
688
- /** Includes information computed by the columnInfo store, including what we serialize to localstorage */
689
- const computedColumns = $derived(columnInfo.columns)
690
- const visibleColumns = $derived(computedColumns.filter(column => column.unhidable || column.visible))
691
- const hiddenColumns = $derived(computedColumns.filter(column => !column.unhidable && !column.visible))
692
- const showPagination = $derived((perPageCount && rows.length > perPageCount) || totalItemsCount > perPageCount)
693
-
694
- const footers = $derived(
695
- columns.map(column => {
696
- if (column.footer && showFooter) {
697
- const property = column.footer.altProperty ? column.footer.altProperty : column.property
698
- const mathFunctions = ['AVG', 'SUM']
699
-
700
- let columnValues: Array<number | GetRowProperty> = rows.map(row => {
701
- const value = getNestedProperty(row, property)
702
- if (
703
- column.footer?.fn &&
704
- typeof column.footer.fn === 'string' &&
705
- mathFunctions.includes(column.footer.fn) &&
706
- typeof value === 'string'
707
- ) {
708
- return parseFloat(value) || 0
709
- }
710
- return value
711
- })
712
-
713
- if (column.footer.requiredValue) {
714
- columnValues = columnValues.filter(value => value === column.footer?.requiredValue)
715
- }
716
-
717
- let value: FooterReducerValue<R>
718
-
719
- function sum(sum: number, val: unknown): number {
720
- if (typeof val === 'number') {
721
- return sum + val
722
- }
723
-
724
- if (typeof val === 'string') {
725
- const parsedVal = parseFloat(val)
726
- if (isNaN(parsedVal)) {
727
- return sum
728
- }
729
- return sum + parsedVal
730
- }
731
-
732
- return sum
733
- }
734
-
735
- switch (column.footer.fn) {
736
- case 'COUNT':
737
- value = columnValues.length
738
- break
739
- case 'AVG':
740
- value = (columnValues.reduce(sum, 0) / columnValues.length).toFixed(2)
741
- break
742
- case 'SUM':
743
- value = columnValues.reduce(sum, 0)
744
- break
745
- default:
746
- if (typeof column.footer.fn === 'function') {
747
- value = columnValues.reduce(column.footer.fn, column.footer.initialValue)
748
- } else {
749
- value = ''
750
- }
751
- break
752
- }
753
-
754
- return {
755
- property: column.property,
756
- value:
757
- column.footer.formatCurrency && (typeof value === 'string' || typeof value === 'number')
758
- ? formatCurrency(value, {})
759
- : value,
760
- }
761
- }
762
- return {
763
- property: column.property,
764
- value: '',
765
- }
766
- }),
767
- )
768
- //#endregion
769
- onMount(() => {
770
- setDefaultColumnWidths()
771
- })
772
- </script>
773
-
774
- {#if filterEnabled}
775
- <div class={headerRowClass}>
776
- <div class={headerColumnClass}>
777
- {@render header?.()}
778
- </div>
779
- <div class={filterColumnClass}>
780
- <Input
781
- label={filterLabel}
782
- showLabel={showFilterLabel}
783
- bind:value={filter}
784
- placeholder={filterPlaceholder}
785
- disabled={filterDisabled}
786
- readonly={filterReadonly || null}
787
- lazy={filterLazy}
788
- />
789
- <!-- || null is so svelte doesn't include readonly when it's falsy, probably a result of it being `restProps`'d on the input -->
790
- </div>
791
- </div>
792
- {/if}
793
-
794
- <!-- webkit-user-select: none; here fixes an issue in Safari where text selection of the column headers would happen while resizing the columns -->
795
- <div
796
- class={[parentClass, responsiveClass]}
797
- style={parentStyle}
798
- class:mb-3={showPagination}
799
- style:user-select={columnResizingIsActive ? 'none' : undefined}
800
- style:-webkit-user-select={columnResizingIsActive ? 'none' : undefined}
801
- style:cursor={columnResizingIsActive ? 'col-resize' : undefined}
802
- bind:this={tableParent}
803
- >
804
- <table
805
- id={tableId}
806
- class={['table mb-0', tableClass]}
807
- class:table-sm={size === 'sm'}
808
- class:table-layout-fixed={columnResizingEnabled && useFixedLayout}
809
- class:sticky={stickyHeader}
810
- class:table-striped={striped}
811
- class:table-bordered={bordered}
812
- class:table-hover={hover}
813
- {...rest}
814
- >
815
- <thead>
816
- <tr>
817
- {#each visibleColumns as column, index}
818
- {@const isSortColumn = sortColumn?.property === column.property}
819
- {@const doEllipsis = column.ellipsis || columnResizingEnabled}
820
-
821
- <th
822
- id="col-{tableId}-{column.property}"
823
- title={column.title ?? column.name}
824
- style:cursor={column.sortType !== false ? 'pointer' : ''}
825
- style:width={column.userWidth ?? column.width}
826
- style:min-width={column.minWidth}
827
- data-sort-specified={isSortColumn ? sortDirection : ''}
828
- class:text-nowrap={!column.wrap}
829
- class="unselectable {column.class ?? ''}"
830
- class:d-print-none={column.hideForPrint}
831
- class:text-left={!bs5 && column.align === 'left'}
832
- class:text-start={column.align === 'start' || (bs5 && column.align === 'left')}
833
- class:text-right={!bs5 && (column.align === 'right' || column.numeric)}
834
- class:text-end={column.align === 'end' || (bs5 && (column.align === 'right' || column.numeric))}
835
- class:text-center={column.align === 'center'}
836
- class:text-truncate={doEllipsis}
837
- class:bg-white={!bs5 && stickyHeader}
838
- onclick={() => columnClickHandler(column)}
839
- oncontextmenu={event => contextMenuHandler(event, column.property)}
840
- >
841
- <span
842
- class="text-truncate d-inline-block"
843
- style="vertical-align: bottom;"
844
- style:max-width={doEllipsis && isSortColumn ? 'calc(100% - 20px)' : '100%'}
845
- >
846
- <!-- Don't add any whitespace btwn these if blocks to keep the spaces correct -->
847
- {#if column.icon && column.iconLeft}
848
- <i class="fa-fw {column.iconPrefix || 'fas'} fa-{column.icon}"></i>{#if column.name}&nbsp;{/if}
849
- {/if}{column.name}{#if column.icon && !column.iconLeft}
850
- {#if column.name}&nbsp;{/if}<i class="fa-fw {column.iconPrefix || 'fas'} fa-{column.icon}"></i>
851
- {/if}
852
- </span>
853
- {#if isSortColumn}
854
- {sortDirection === 'ASC' ? '▲' : ''}
855
- {/if}
856
- {#if columnResizingEnabled && visibleColumns.length - 1 !== index}
857
- <!-- I think setting the role and aria-orientation attributes is the best we can do here -->
858
- <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
859
- <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
860
- <!-- svelte-ignore a11y_click_events_have_key_events -->
861
- <div
862
- id="col-resizer-{tableId}-{column.property}"
863
- tabindex={0}
864
- role="separator"
865
- aria-orientation="horizontal"
866
- class="resizer"
867
- style="height: 100%;"
868
- onmousedown={e => onColumnMouseDown(e, column)}
869
- >
870
- &nbsp;
871
- </div>
872
- {/if}
873
- </th>
874
- {/each}
875
- </tr>
876
- </thead>
877
- <tbody class:unselectable={selectionMode === 'RANGE'}>
878
- {#if body}
879
- {@render body?.({ rows: currentPageRows, visibleColumnsCount: visibleColumns.length })}
880
- {:else}
881
- {#each currentPageRows as row, index (row[idProp])}
882
- {#if children}{@render children({ row, index })}{:else}
883
- <tr
884
- class:table-primary={rowIsSelected(row, rowSelectionIdProp, selectedRowIds)}
885
- onclick={() => rowClick(row)}
886
- >
887
- {#each computedColumns as column (column.property)}
888
- <Td
889
- align={column.align}
890
- property={column.property}
891
- >
892
- {column.formatter
893
- ? column.formatter(getNestedProperty(row, column.property, ''))
894
- : getNestedProperty(row, column.property, '')}
895
- </Td>
896
- {/each}
897
- </tr>
898
- {/if}
899
- {:else}
900
- {@render noRows?.({ visibleColumnsCount: visibleColumns.length })}
901
- {/each}
902
- {/if}
903
- </tbody>
904
- {#if showFooter && footers}
905
- <tfoot>
906
- <tr class="table-secondary">
907
- {#if footerRow}
908
- {@render footerRow({ footers })}
909
- {:else}
910
- {#each footers as { property, value } (property)}
911
- <Td
912
- {property}
913
- tagName="TH">{value ?? ''}</Td
914
- >
915
- {/each}
916
- {/if}
917
- </tr>
918
- </tfoot>
919
- {/if}
920
- </table>
921
- </div>
922
-
923
- <Pagination
924
- {perPageCount}
925
- {totalItemsCount}
926
- items={sortedRows}
927
- bind:currentPageItems={() => untrack(() => currentPageRows), items => (currentPageRows = items)}
928
- bind:currentPageNumber
929
- bind:lastPageNumber
930
- {pageChange}
931
- bind:this={paginationComponent}
932
- />
933
-
934
- <ContextMenu
935
- id="hide-column-context-menu"
936
- bind:this={contextMenu}
937
- >
938
- <button
939
- class={['dropdown-item', hideButtonClass]}
940
- class:disabled={contextMenuColumn?.unhidable}
941
- onclick={() => contextMenuColumn && hideColumn(contextMenuColumn)}
942
- >
943
- <i class="fas fa-eye-slash"></i>
944
- {#if contextMenuColumn?.name}
945
- {translate('common:tableHideColumn', 'Hide {{- columnName}}', { columnName: contextMenuColumn.name })}
946
- {:else if contextMenuColumn?.icon}
947
- {translate('common:hide', 'Hide')}
948
- <i class="{contextMenuColumn?.iconPrefix || 'fas'} fa-{contextMenuColumn?.icon}"></i>
949
- {/if}
950
- </button>
951
-
952
- {#if hiddenColumns.length > 0}
953
- <div class="dropdown-divider"></div>
954
- <h5 class="dropdown-header"><i class="fas fa-eye"></i> {translate('common:tableShowColumns', 'Show Column')}</h5>
955
- {/if}
956
- {#each hiddenColumns as hiddenColumn (hiddenColumn.property)}
957
- <button
958
- class="dropdown-item"
959
- onclick={() => showColumn(hiddenColumn)}
960
- >
961
- {#if hiddenColumn.name}
962
- {hiddenColumn.name}
963
- {:else if hiddenColumn.icon}
964
- <i class="{hiddenColumn.iconPrefix || 'fas'} fa-{hiddenColumn.icon}"></i>
965
- {/if}
966
- </button>
967
- {/each}
968
- {#if columnResizingEnabled}
969
- <div class="dropdown-divider"></div>
970
- <DropdownItem
971
- icon="broom"
972
- onclick={() => {
973
- columnInfo.updateColumns(
974
- computedColumns.map(col => ({
975
- property: col.property,
976
- userWidth: undefined,
977
- })),
978
- )
979
- setDefaultColumnWidths()
980
- }}>{translate('common:tableResetColumnSizes', 'Reset Column Sizes')}</DropdownItem
981
- >
982
- {/if}
983
- </ContextMenu>
984
-
985
- <style>
986
- table.sticky {
987
- position: relative;
988
- }
989
-
990
- table.sticky th {
991
- position: sticky;
992
- top: 0;
993
- box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.4);
994
- }
995
-
996
- table.sticky > thead > tr > th {
997
- z-index: 3;
998
- }
999
-
1000
- /* Remove bottom margins created by form-groups in the table (BS4 only) */
1001
- table > tbody :global(.form-group) {
1002
- margin-bottom: 0%;
1003
- }
1004
-
1005
- /* BS5 removed .form-group, which makes it a little trickier to target the label's parent div, but this should do it
1006
- - The Label component adds mb-3 to the parent div if the label is hidden or mb-1 if it's shown (unlikely if it's in a table)
1007
- - That div will have a .input-group, .form-control, or .form-select as a direct descendant
1008
- */
1009
- table
1010
- > tbody
1011
- :global(
1012
- td div:where(.mb-3, .mb-1):not(.form-group):has(> :where(.input-group, .form-control, .form-select, .btn-group))
1013
- ) {
1014
- margin-bottom: 0% !important;
1015
- }
1016
-
1017
- .resizer {
1018
- position: absolute;
1019
- top: 0;
1020
- right: 0;
1021
- width: 10px;
1022
- cursor: col-resize;
1023
- user-select: none;
1024
- }
1025
- .resizer:hover,
1026
- .resizing {
1027
- border-right: 5px solid darkslategray;
1028
- }
1029
- .table-layout-fixed {
1030
- table-layout: fixed;
1031
- }
1032
- </style>
1
+ <script module>
2
+ import { getBootstrapCdnVersion } from '@isoftdata/utility-bootstrap'
3
+ let bs5 = $state(false)
4
+ try {
5
+ bs5 = getBootstrapCdnVersion() === 5
6
+ } catch (e) {
7
+ onMount(() => {
8
+ bs5 = getBootstrapCdnVersion() === 5
9
+ })
10
+ }
11
+ </script>
12
+
13
+ <script
14
+ lang="ts"
15
+ generics="R extends UuidRowProps"
16
+ >
17
+ import type { Snippet } from 'svelte'
18
+
19
+ import { ColumnInfoRunicStore } from './column-info-store.svelte'
20
+
21
+ import type { i18n } from 'i18next'
22
+ import type { Get } from 'type-fest'
23
+ import {
24
+ type Column as GenericColumn,
25
+ type SortDirection,
26
+ type UuidRowProps,
27
+ type RowProperties,
28
+ type FooterReducerValue,
29
+ ARBITRARY_PROPERTY_PREFIX,
30
+ type ArbitraryProperty,
31
+ } from './'
32
+
33
+ import { writable, type Writable } from 'svelte/store'
34
+
35
+ import Pagination from './Pagination.svelte'
36
+ import Td from './Td.svelte'
37
+ import Input from '@isoftdata/svelte-input'
38
+ import ContextMenu, { DropdownItem } from '@isoftdata/svelte-context-menu'
39
+ import { v4 as uuid } from '@lukeed/uuid'
40
+ import { format as formatCurrency } from '@isoftdata/utility-currency'
41
+ import { setContext, tick, onMount, getContext, untrack } from 'svelte'
42
+ import { on } from 'svelte/events'
43
+ import naturalCompare from 'natural-compare-lite'
44
+ import type { HTMLTableAttributes, ClassValue } from 'svelte/elements'
45
+ import { translate as defaultTranslate } from '@isoftdata/utility-string'
46
+
47
+ const { t: translate } = getContext<i18n>('i18next') || { t: defaultTranslate }
48
+
49
+ type K = keyof R
50
+ type KeyPath = RowProperties<R>
51
+ type ColumnProperty = KeyPath | ArbitraryProperty
52
+
53
+ type IndexedRow = R & { originalIndex: number; uuid: string }
54
+ type GetRowProperty = Get<R, KeyPath>
55
+ type GetIndexedRowProperty = Get<IndexedRow, RowProperties<IndexedRow>>
56
+ type FooterValue = {
57
+ property: ColumnProperty
58
+ value: FooterReducerValue<R>
59
+ }
60
+ // Type hack so passing an array of columns without the type argument doesn't reduce the type of R to any
61
+ type Column = GenericColumn<R & {}>
62
+
63
+ interface Props extends Omit<HTMLTableAttributes, 'children' | `aria-${string}` | `bind:${string}` | `on:${string}`> {
64
+ filterEnabled?: boolean
65
+ columns: Array<Column>
66
+ tableId?: string
67
+ rows: Array<R>
68
+ sortDirection?: SortDirection
69
+ sortColumn?: Column | undefined
70
+ class?: ClassValue
71
+ perPageCount?: number
72
+ currentPageNumber?: number
73
+ showFooter?: boolean
74
+ footers?: Array<FooterValue>
75
+ lazySort?: boolean //when true, the table can only be resorted when the user clicks on a column header(not real time as data changes)
76
+ idProp?: K | 'uuid' //required for lazy sorting.
77
+ previousSortOrder?: Array<IndexedRow & { order: number }>
78
+ filterProps?: Array<KeyPath> | false
79
+ filter?: string
80
+ filterLabel?: string
81
+ filterPlaceholder?: string
82
+ filterDisabled?: boolean
83
+ filterReadonly?: boolean
84
+ filterLazy?: boolean | number
85
+ showFilterLabel?: boolean
86
+ headerRowClass?: ClassValue
87
+ headerColumnClass?: ClassValue
88
+ filterColumnClass?: ClassValue
89
+ columnHidingEnabled?: boolean
90
+ selectionEnabled?: boolean
91
+ // Array<number> | Array<string> | Array<R[K]> ???
92
+ selectedRowIds?: Array<GetIndexedRowProperty>
93
+ rowSelectionIdProp?: KeyPath | 'uuid'
94
+ rowSelectionRequiresModKey?: boolean
95
+ selectionMode?: 'SINGLE' | 'RANGE' | null
96
+ multiSelectEnabled?: boolean
97
+ lastClickedIdForRange?: GetIndexedRowProperty | undefined
98
+ totalItemsCount?: number
99
+ stickyHeader?: boolean
100
+ responsive?: boolean | 'sm' | 'md' | 'lg' | 'xl'
101
+ size?: 'sm' | ''
102
+ striped?: boolean
103
+ /** When true, enables tree-specific features. Required if you want to use `TreeRow`s. */
104
+ tree?: boolean
105
+ bordered?: boolean
106
+ hover?: boolean
107
+ previousSortColumn?: Column | undefined
108
+ previousSortDirection?: SortDirection | undefined
109
+ parentClass?: ClassValue
110
+ parentStyle?: string
111
+ hideButtonClass?: ClassValue
112
+ columnResizingEnabled?: boolean
113
+ /** If specified, where to serialize the columnInfo store */
114
+ localStorageKey?: string | undefined
115
+ columnClickedMethod?: typeof defaultColumnClicked
116
+ filterMethod?: typeof defaultFilter
117
+ rowMatchesFilterMethod?: typeof defaultRowMatchesFilter
118
+ filteredRows?: Array<IndexedRow>
119
+ sortedRows?: Array<IndexedRow>
120
+ currentPageRows?: Array<IndexedRow>
121
+ // snippets
122
+ header?: Snippet
123
+ body?: Snippet<[{ rows: Array<R & { originalIndex: number; uuid: string }>; visibleColumnsCount: number }]>
124
+ children?: Snippet<[{ row: R & { originalIndex: number; uuid: string }; index: number }]>
125
+ noRows?: Snippet<[{ visibleColumnsCount: number }]>
126
+ footerRow?: Snippet<[{ footers: Array<FooterValue> }]>
127
+ // callbacks
128
+ pageChange?: (context: { pageNumber: number }) => void
129
+ columnResizeEnd?: (context: { column: Column }) => void
130
+ }
131
+
132
+ const uid = $props.id()
133
+
134
+ let {
135
+ filterEnabled = false,
136
+ columns,
137
+ tableId = uid,
138
+ rows,
139
+ sortDirection = $bindable('ASC'),
140
+ sortColumn = $bindable(undefined),
141
+ class: tableClass = '',
142
+ perPageCount = 0,
143
+ currentPageNumber = $bindable(1),
144
+ showFooter = false,
145
+ lazySort = false,
146
+ idProp = 'uuid',
147
+ previousSortOrder = $bindable([]),
148
+ filterProps = false,
149
+ filter = $bindable(''),
150
+ filterLabel = translate('common:filter', 'Filter'),
151
+ filterPlaceholder = translate('common:filter', 'Filter'),
152
+ filterDisabled = false,
153
+ filterReadonly = false,
154
+ filterLazy = false,
155
+ showFilterLabel = false,
156
+ headerRowClass = bs5 ? 'row' : 'form-row',
157
+ headerColumnClass = 'col',
158
+ filterColumnClass = 'col-lg-2 col-md-4 col-sm-6 align-self-end',
159
+ columnHidingEnabled = false,
160
+ selectionEnabled = false,
161
+ selectedRowIds = $bindable([]),
162
+ rowSelectionIdProp = 'uuid',
163
+ rowSelectionRequiresModKey = false,
164
+ selectionMode = $bindable(null),
165
+ multiSelectEnabled = true,
166
+ lastClickedIdForRange = $bindable(undefined),
167
+ totalItemsCount = 0,
168
+ stickyHeader = false,
169
+ responsive = false,
170
+ size = 'sm',
171
+ striped = true,
172
+ tree = false,
173
+ bordered = true,
174
+ hover = true,
175
+ previousSortColumn = $bindable(undefined),
176
+ previousSortDirection = $bindable(undefined),
177
+ parentClass = '',
178
+ parentStyle = '',
179
+ hideButtonClass = '',
180
+ columnResizingEnabled = false,
181
+ localStorageKey = undefined,
182
+ columnClickedMethod = defaultColumnClicked,
183
+ filterMethod = defaultFilter,
184
+ rowMatchesFilterMethod = defaultRowMatchesFilter,
185
+ filteredRows = $bindable(filterMethod('', rows, columns)),
186
+ sortedRows = $bindable(filteredRows),
187
+ currentPageRows = $bindable(sortedRows.slice(0, perPageCount)),
188
+ // snippets
189
+ header,
190
+ body,
191
+ children,
192
+ noRows,
193
+ footerRow,
194
+ // callbacks
195
+ pageChange,
196
+ columnResizeEnd,
197
+ ...rest
198
+ }: Props = $props()
199
+
200
+ let lastPageNumber: number = $state(1)
201
+ let paginationComponent: Pagination<IndexedRow> | undefined = $state()
202
+ let contextMenu: ContextMenu | undefined = $state()
203
+ let contextMenuColumn: Column | undefined = $state()
204
+ let columnResizingIsActive: boolean = $state(false)
205
+ /** Set to true after getting initial table widths when resizing enabled*/
206
+ let useFixedLayout = $state(false)
207
+ let tableParent: HTMLDivElement | undefined = $state()
208
+
209
+ // Do the initial sort if they specified a default sort column
210
+ const defaultSortColumn = columns.find(column => column.defaultSortColumn)
211
+ if (defaultSortColumn) {
212
+ sortColumn = defaultSortColumn
213
+ sortDirection = defaultSortColumn.defaultSortDirection || 'ASC'
214
+
215
+ doSort({
216
+ rows: filteredRows,
217
+ sortColumn,
218
+ sortDirection,
219
+ sameSortOrder: false,
220
+ })
221
+ }
222
+
223
+ // Need to track which rows are expanded so when the rows reorder, they correctly keep that state.
224
+ const expandedRows = writable<Record<number | string, boolean>>({})
225
+ if (tree) {
226
+ setContext('expandedRows', expandedRows)
227
+ }
228
+
229
+ // TODO: bad things will happen if we update any of our apps to use Runes for the store if we don't account for that here
230
+ const session = getContext<Writable<{ userAccountId?: number }> | undefined>('session')
231
+ // This will be accessible on the component instance, ie `const columnInfo = $derived(table?.columnInfo)` if you need it
232
+ export const columnInfo = new ColumnInfoRunicStore<R>(() => columns, {
233
+ key: localStorageKey,
234
+ userAccountId: session && $session ? $session.userAccountId : undefined,
235
+ })
236
+ // Set as context so we can retrieve it in the Td component
237
+ setContext('columnInfo', columnInfo)
238
+ // Set as context so we can retrieve it in the TreeRow component
239
+ const selectedRowIdsStore = writable(selectedRowIds)
240
+ setContext('selectedRowIds', selectedRowIdsStore)
241
+ setContext('idProp', idProp)
242
+ setContext('columnResizingEnabled', writable(columnResizingEnabled))
243
+ setContext('bs5', bs5)
244
+
245
+ // #endregion
246
+ // #region Functions
247
+
248
+ function isArbitraryProperty(property: string | undefined): property is ArbitraryProperty {
249
+ return !!property?.startsWith(ARBITRARY_PROPERTY_PREFIX)
250
+ }
251
+
252
+ export async function defaultColumnClicked(clickedColumn: Column, sortDirection: SortDirection) {
253
+ if (currentPageNumber !== lastPageNumber) {
254
+ paginationComponent?.setPageNumber(1)
255
+ }
256
+
257
+ doSort({
258
+ rows: filteredRows,
259
+ sortColumn: clickedColumn,
260
+ sortDirection,
261
+ sameSortOrder: false,
262
+ })
263
+ }
264
+
265
+ function defaultFilter(filter: string, rows: R[], columns: Column[]): IndexedRow[] {
266
+ const columnProps = columns
267
+ ?.map(({ property }) => property)
268
+ .filter((property): property is KeyPath => !isArbitraryProperty(property))
269
+
270
+ if (filterEnabled) {
271
+ const props = filterProps || columnProps
272
+ return getFilterMatches(filter, rows, props)
273
+ }
274
+
275
+ return rows.map((row, index): IndexedRow => ({ ...row, originalIndex: index, uuid: row.uuid || uuid() }))
276
+ }
277
+
278
+ /** In normal mode, returns all rows matching the filter.
279
+ *
280
+ * In tree mode, shows all children if parent matches, or shows matching children and their children
281
+ */
282
+ function getFilterMatches(filter: string, theRows: Array<R>, props: KeyPath[]) {
283
+ return theRows.reduce((rows, row, index): IndexedRow[] => {
284
+ if (rowMatchesFilterMethod(filter, row, props)) {
285
+ rows.push({ ...row, originalIndex: index, uuid: 'uuid' in row ? (row.uuid as string) : uuid() })
286
+ } else if (tree && Array.isArray(row.children) && row.children.length) {
287
+ const children = getFilterMatches(filter, row.children, props)
288
+ if (children.length) {
289
+ rows.push({ ...row, children, originalIndex: index, uuid: 'uuid' in row ? (row.uuid as string) : uuid() })
290
+ }
291
+ }
292
+
293
+ return rows
294
+ }, new Array<IndexedRow>())
295
+ }
296
+
297
+ export function defaultRowMatchesFilter(filter: string, row: R, props: Array<RowProperties<R>>) {
298
+ return (
299
+ !filter ||
300
+ props.some(prop => {
301
+ const value = getNestedProperty(row, prop)
302
+ if (typeof value === 'string' || typeof value === 'number') {
303
+ return value.toString().toUpperCase().indexOf(filter.toUpperCase()) > -1
304
+ }
305
+ return false
306
+ })
307
+ )
308
+ }
309
+
310
+ export function getNestedProperty(
311
+ row: R & { uuid: string },
312
+ path: KeyPath | 'uuid',
313
+ defaultValue?: string | number,
314
+ ): GetIndexedRowProperty
315
+ export function getNestedProperty(row: R, path: KeyPath, defaultValue?: string | number): GetRowProperty
316
+ export function getNestedProperty(
317
+ row: R | (R & { uuid: string }),
318
+ path: KeyPath | 'uuid',
319
+ defaultValue?: string | number,
320
+ ): GetRowProperty | GetIndexedRowProperty {
321
+ if (!path) {
322
+ return defaultValue as GetRowProperty
323
+ }
324
+
325
+ if (row[path]) {
326
+ return row[path] as GetRowProperty
327
+ }
328
+
329
+ const val =
330
+ path
331
+ .split('[')
332
+ // TODO figure out if we can do this less evilly
333
+ .reduce((obj, prop) => (obj as any)?.[prop.replace(/\]/g, '')], row as any) ?? defaultValue
334
+ return val
335
+ }
336
+
337
+ async function columnClickHandler(clickedColumn: Column) {
338
+ if (clickedColumn.sortType === false || columnResizingIsActive || isArbitraryProperty(clickedColumn.property)) {
339
+ return
340
+ }
341
+ sortDirection = sortDirection === 'ASC' && clickedColumn.property === sortColumn?.property ? 'DESC' : 'ASC'
342
+
343
+ columnClickedMethod(clickedColumn, sortDirection)
344
+
345
+ sortColumn = clickedColumn
346
+ await tick()
347
+ }
348
+
349
+ export function expandRow(rowId: string | number, expanded = true) {
350
+ if (tree) {
351
+ $expandedRows[rowId] = expanded
352
+ } else {
353
+ console.warn('expandRow should only be used when the `tree` prop is set to true on the Table component.')
354
+ }
355
+ }
356
+
357
+ export function rowIsSelected(
358
+ row: IndexedRow,
359
+ rowSelectionIdProp: KeyPath | 'uuid',
360
+ selectedRowIds: Array<GetIndexedRowProperty>,
361
+ ) {
362
+ const selectionId = getNestedProperty(row, rowSelectionIdProp, row.uuid)
363
+ return selectedRowIds.includes(selectionId)
364
+ }
365
+
366
+ export function rowClick(row: IndexedRow) {
367
+ if (!selectionEnabled || !rowSelectionIdProp) {
368
+ return
369
+ }
370
+ const clickedId = getNestedProperty(row, rowSelectionIdProp || 'uuid')
371
+
372
+ const selectedIds = selectedRowIds
373
+
374
+ let newSelectedIds: Array<GetIndexedRowProperty> = []
375
+
376
+ if (!selectionMode && !rowSelectionRequiresModKey) {
377
+ selectionMode = 'SINGLE'
378
+ }
379
+
380
+ if (selectionMode === 'SINGLE') {
381
+ newSelectedIds = selectedIds
382
+ const foundInExistingSelections = selectedIds.some(id => id === clickedId)
383
+
384
+ if (foundInExistingSelections) {
385
+ newSelectedIds = newSelectedIds.filter(id => id !== clickedId)
386
+ } else if (multiSelectEnabled) {
387
+ newSelectedIds = newSelectedIds.concat(clickedId)
388
+ } else {
389
+ newSelectedIds = [clickedId]
390
+ }
391
+ } else if (selectionMode === 'RANGE') {
392
+ if (selectedIds.length < 1) {
393
+ newSelectedIds = [clickedId]
394
+ } else {
395
+ newSelectedIds = selectedIds
396
+ const clickedItemIndex = sortedRows.findIndex(item => {
397
+ return item[rowSelectionIdProp] === clickedId
398
+ })
399
+
400
+ const lastSelectedIndex = sortedRows.findIndex(item => {
401
+ return item[rowSelectionIdProp] === lastClickedIdForRange
402
+ })
403
+
404
+ let selectionDirection: 'UP' | 'DOWN' | undefined
405
+
406
+ if (lastSelectedIndex > clickedItemIndex) {
407
+ selectionDirection = 'UP'
408
+ } else if (lastSelectedIndex < clickedItemIndex) {
409
+ selectionDirection = 'DOWN'
410
+ }
411
+
412
+ if (selectionDirection) {
413
+ sortedRows.forEach((item, index) => {
414
+ if (selectionDirection === 'UP' && index <= lastSelectedIndex && index >= clickedItemIndex) {
415
+ newSelectedIds = newSelectedIds.concat(getNestedProperty(item, rowSelectionIdProp))
416
+ } else if (selectionDirection === 'DOWN' && index >= lastSelectedIndex && index <= clickedItemIndex) {
417
+ newSelectedIds = newSelectedIds.concat(getNestedProperty(item, rowSelectionIdProp))
418
+ }
419
+ })
420
+ }
421
+ }
422
+ } else {
423
+ return
424
+ }
425
+
426
+ const clickedIdWasAdded = newSelectedIds.find(id => id === clickedId)
427
+
428
+ let lastClickedId: GetIndexedRowProperty | undefined
429
+
430
+ if (newSelectedIds.length === 0) {
431
+ lastClickedId = undefined
432
+ } else if (selectionMode === 'SINGLE' && clickedIdWasAdded) {
433
+ lastClickedId = clickedId
434
+ } else {
435
+ lastClickedId = lastClickedIdForRange
436
+ }
437
+
438
+ selectedRowIds = [...new Set(newSelectedIds)]
439
+ lastClickedIdForRange = lastClickedId
440
+ }
441
+ export function setPageVisibleByItemIndex(index: number) {
442
+ if (index > -1) {
443
+ paginationComponent?.setPageVisibleByItemIndex(index)
444
+ }
445
+ }
446
+ export function setPageVisibleByItemId({ id, keyName }: { id: number | string; keyName: K }) {
447
+ const index = sortedRows.findIndex(item => item[keyName] == id)
448
+
449
+ if (index > -1) {
450
+ paginationComponent?.setPageVisibleByItemIndex(index)
451
+ }
452
+ }
453
+ export function doSort({
454
+ rows,
455
+ sortColumn,
456
+ sortDirection,
457
+ sameSortOrder,
458
+ }: {
459
+ rows: Array<IndexedRow>
460
+ sortColumn: Column | undefined
461
+ sortDirection: SortDirection
462
+ sameSortOrder: boolean
463
+ }) {
464
+ const keepSameSortOrder = !!(lazySort && sameSortOrder && idProp)
465
+ const hasPreviousSort = previousSortColumn && previousSortOrder.length > 0
466
+
467
+ let sortProp: KeyPath
468
+ if (
469
+ keepSameSortOrder &&
470
+ hasPreviousSort &&
471
+ previousSortColumn &&
472
+ idProp &&
473
+ !isArbitraryProperty(previousSortColumn.property)
474
+ ) {
475
+ sortColumn = previousSortColumn
476
+ sortProp = previousSortColumn.property
477
+ sortDirection = 'ASC' //force ASC for keeping the same order because we defined the order in previousSortOrder
478
+
479
+ rows = rows.map(row => {
480
+ const foundItem = previousSortOrder.find(
481
+ previousSortOrderRow => !!idProp && previousSortOrderRow[idProp] === row[idProp],
482
+ )
483
+
484
+ return { ...row, order: foundItem ? foundItem.order : 0 }
485
+ })
486
+ } else if (sortColumn?.property && !isArbitraryProperty(sortColumn.property)) {
487
+ sortProp = sortColumn.property
488
+ } else {
489
+ // no sort property, can't sort
490
+ sortedRows = rows
491
+ return
492
+ }
493
+
494
+ function doTheSort(theRows: Array<IndexedRow>): Array<IndexedRow> {
495
+ if (tree) {
496
+ return theRows
497
+ .slice()
498
+ .map(row => {
499
+ if (Array.isArray(row.children)) {
500
+ return {
501
+ ...row,
502
+ children: doTheSort(row.children),
503
+ }
504
+ }
505
+ return row
506
+ })
507
+ .sort((a: IndexedRow, b: IndexedRow) =>
508
+ sortColumn?.sortType === 'ALPHA_NUM' ? alphaNumSort(a, b) : standardSort(a, b),
509
+ )
510
+ }
511
+ return theRows.slice().sort(sortColumn?.sortType === 'ALPHA_NUM' ? alphaNumSort : standardSort)
512
+ }
513
+
514
+ const theSortedRows = doTheSort(rows)
515
+
516
+ previousSortOrder = theSortedRows.map((row, index) => ({
517
+ ...row,
518
+ order: index,
519
+ }))
520
+ previousSortDirection = sortDirection
521
+ previousSortColumn = sortColumn
522
+ sortedRows = theSortedRows
523
+ return
524
+
525
+ function standardSort(a: R, b: R) {
526
+ let aValue: Get<R, KeyPath> | string = getNestedProperty(a, sortProp, '')
527
+ let bValue: Get<R, KeyPath> | string = getNestedProperty(b, sortProp, '')
528
+
529
+ if (typeof aValue === 'string') {
530
+ aValue = aValue.toUpperCase()
531
+ }
532
+ if (typeof bValue === 'string') {
533
+ bValue = bValue.toUpperCase()
534
+ }
535
+
536
+ if (aValue < bValue) {
537
+ return sortDirection === 'ASC' ? -1 : 1
538
+ }
539
+ if (aValue > bValue) {
540
+ return sortDirection === 'ASC' ? 1 : -1
541
+ }
542
+
543
+ return 0
544
+ }
545
+
546
+ function alphaNumSort(a: R, b: R) {
547
+ const aValue = getNestedProperty(a, sortProp, '')
548
+ const bValue = getNestedProperty(b, sortProp, '')
549
+ let compareResults = 0
550
+ if (
551
+ (typeof aValue === 'number' || typeof aValue === 'string') &&
552
+ (typeof bValue === 'number' || typeof bValue === 'string')
553
+ ) {
554
+ compareResults = naturalCompare(aValue.toString(), bValue.toString())
555
+ } else if (typeof aValue === 'number' || typeof aValue === 'string') {
556
+ compareResults = 1
557
+ } else if (typeof bValue === 'number' || typeof bValue === 'string') {
558
+ compareResults = -1
559
+ }
560
+
561
+ return sortDirection === 'ASC' ? compareResults : compareResults * -1
562
+ }
563
+ }
564
+
565
+ export function setColumnVisibility(columnProperties: Array<ColumnProperty> | ColumnProperty, visible: boolean) {
566
+ if (!Array.isArray(columnProperties)) {
567
+ columnProperties = [columnProperties]
568
+ }
569
+
570
+ try {
571
+ untrack(() => {
572
+ columnInfo.updateColumns(
573
+ columnProperties.map((property): { property: ColumnProperty; visible: boolean } => ({
574
+ property,
575
+ visible,
576
+ })),
577
+ )
578
+ })
579
+ } catch (err) {
580
+ console.error(`Error setting column visibility for columns ${JSON.stringify(columnProperties)}`, err)
581
+ }
582
+ }
583
+
584
+ /** When called in `onMount` or an effect, will set the visibility of the specified columns whenever the value of `getVisible()` changes*/
585
+ export function setColumnVisibilityWatch(
586
+ columnProperties: Array<ColumnProperty> | ColumnProperty,
587
+ getVisible: () => boolean,
588
+ ) {
589
+ $effect(() => {
590
+ const visible = getVisible()
591
+ setColumnVisibility(columnProperties, visible)
592
+ })
593
+ }
594
+
595
+ function hideColumn(column: Column) {
596
+ if (column) {
597
+ columnInfo.updateColumn(column.property, { visible: false })
598
+ }
599
+ contextMenuColumn = undefined
600
+ }
601
+
602
+ function showColumn(column: Column) {
603
+ if (column) {
604
+ columnInfo.updateColumn(column.property, { visible: true })
605
+ }
606
+ contextMenuColumn = undefined
607
+ }
608
+
609
+ function contextMenuHandler(event: MouseEvent, column: string) {
610
+ if ((columnHidingEnabled || columnResizingEnabled) && !event.ctrlKey) {
611
+ event.preventDefault()
612
+ contextMenuColumn = columnInfo.current[column]
613
+ return contextMenu?.open(event, `col-${tableId}-${CSS.escape(column)}`)
614
+ }
615
+ return Promise.resolve()
616
+ }
617
+ // #endregion
618
+ // #region Tree-specific functions
619
+
620
+ // #endregion
621
+
622
+ function onColumnMouseDown(event: MouseEvent, column: Column) {
623
+ event.stopPropagation()
624
+ if (!event.target || !(event.target instanceof HTMLDivElement)) {
625
+ return
626
+ }
627
+
628
+ const htmlColumn = tableParent?.querySelector<HTMLTableCellElement>(
629
+ `#col-${tableId}-${CSS.escape(column.property)}`,
630
+ )
631
+ const columnIndex = columns.findIndex(col => col.property === column.property)
632
+ if (!htmlColumn || columnIndex === -1) {
633
+ return
634
+ }
635
+
636
+ const mouseDownPageX = event.pageX
637
+ const mouseDownColumnWidth = htmlColumn.offsetWidth
638
+
639
+ event.target.classList.add('resizing')
640
+ columnResizingIsActive = true
641
+
642
+ const mouseMoveHandler = (mouseMoveEvent: MouseEvent) => {
643
+ const widthDifference = mouseMoveEvent.pageX - mouseDownPageX
644
+ const newWidth = `${mouseDownColumnWidth + widthDifference}px`
645
+ htmlColumn.style.width = column.minWidth ? `max(${newWidth}, ${column.minWidth})` : newWidth
646
+ }
647
+
648
+ const mouseUpHandler = () => {
649
+ if (!(event.target instanceof HTMLDivElement)) {
650
+ return
651
+ }
652
+ event.target.classList.remove('resizing')
653
+ columnInfo.updateColumn(column.property, { userWidth: htmlColumn.style.width })
654
+
655
+ removeMouseMoveListener?.()
656
+ removeMouseUpListener?.()
657
+ columnResizeEnd?.({ column: columns[columnIndex] })
658
+ // We want to ensure the user's mouseup event doesn't trigger a click event on the column header
659
+ setTimeout(() => (columnResizingIsActive = false), 50)
660
+ }
661
+
662
+ const removeMouseMoveListener = tableParent ? on(tableParent, 'mousemove', mouseMoveHandler) : undefined
663
+ const removeMouseUpListener = tableParent ? on(tableParent, 'mouseup', mouseUpHandler) : undefined
664
+ }
665
+
666
+ async function setDefaultColumnWidths() {
667
+ useFixedLayout = false
668
+ await tick()
669
+ if (columnResizingEnabled) {
670
+ columnInfo.updateColumns(
671
+ columns.map((column): { property: ColumnProperty; userWidth: string } => {
672
+ const thisColumnInfo = columnInfo.current[column.property]
673
+ const prevUserWidth = thisColumnInfo?.userWidth
674
+ // Minimum width will be inherited from the layout on reset, but this won't, so re-set it here if needed
675
+ const explicitWidth = thisColumnInfo?.width
676
+
677
+ return {
678
+ property: column.property,
679
+ userWidth: prevUserWidth ?? explicitWidth ?? getColumnThWidth(column.property),
680
+ }
681
+ }),
682
+ )
683
+ useFixedLayout = true
684
+ }
685
+ }
686
+
687
+ function getColumnThWidth(property: string) {
688
+ const thWidth =
689
+ tableParent?.querySelector<HTMLTableCellElement>(`#col-${tableId}-${CSS.escape(property)}`)?.offsetWidth ?? 25
690
+ return `${thWidth}px`
691
+ }
692
+ // #region Computed
693
+ $effect(() => {
694
+ selectedRowIdsStore.set(selectedRowIds)
695
+ })
696
+
697
+ $effect(() => {
698
+ filteredRows = filterMethod(filter, rows, columns)
699
+ // Should only run when filter/rows/columns changes since everything else is untracked
700
+ untrack(() =>
701
+ doSort({
702
+ rows: filteredRows && Array.isArray(filteredRows) ? filteredRows : [],
703
+ sortColumn: sortColumn,
704
+ sortDirection: sortDirection,
705
+ sameSortOrder: true,
706
+ }),
707
+ )
708
+ })
709
+
710
+ const responsiveClass = $derived(
711
+ responsive === true ? 'table-responsive' : !!responsive ? `table-responsive-${responsive}` : '',
712
+ )
713
+ /** Includes information computed by the columnInfo store, including what we serialize to localstorage */
714
+ const computedColumns = $derived(columnInfo.columns)
715
+ const visibleColumns = $derived(computedColumns.filter(column => column.unhidable || column.visible))
716
+ const hiddenColumns = $derived(computedColumns.filter(column => !column.unhidable && !column.visible))
717
+ const showPagination = $derived((perPageCount && rows.length > perPageCount) || totalItemsCount > perPageCount)
718
+
719
+ const footers = $derived(
720
+ columns.map(column => {
721
+ if (column.footer && showFooter) {
722
+ const property = column.footer.altProperty ? column.footer.altProperty : column.property
723
+ const mathFunctions = ['AVG', 'SUM']
724
+
725
+ let columnValues: Array<number | GetRowProperty> = rows.map(row => {
726
+ const value = isArbitraryProperty(property)
727
+ ? ('' as Get<R, RowProperties<R>>)
728
+ : getNestedProperty(row, property)
729
+ if (
730
+ column.footer?.fn &&
731
+ typeof column.footer.fn === 'string' &&
732
+ mathFunctions.includes(column.footer.fn) &&
733
+ typeof value === 'string'
734
+ ) {
735
+ return parseFloat(value) || 0
736
+ }
737
+ return value
738
+ })
739
+
740
+ if (column.footer.requiredValue) {
741
+ columnValues = columnValues.filter(value => value === column.footer?.requiredValue)
742
+ }
743
+
744
+ let value: FooterReducerValue<R>
745
+
746
+ function sum(sum: number, val: unknown): number {
747
+ if (typeof val === 'number') {
748
+ return sum + val
749
+ }
750
+
751
+ if (typeof val === 'string') {
752
+ const parsedVal = parseFloat(val)
753
+ if (isNaN(parsedVal)) {
754
+ return sum
755
+ }
756
+ return sum + parsedVal
757
+ }
758
+
759
+ return sum
760
+ }
761
+
762
+ switch (column.footer.fn) {
763
+ case 'COUNT':
764
+ value = columnValues.length
765
+ break
766
+ case 'AVG':
767
+ value = (columnValues.reduce(sum, 0) / columnValues.length).toFixed(2)
768
+ break
769
+ case 'SUM':
770
+ value = columnValues.reduce(sum, 0)
771
+ break
772
+ default:
773
+ if (typeof column.footer.fn === 'function') {
774
+ value = columnValues.reduce(column.footer.fn, column.footer.initialValue)
775
+ } else {
776
+ value = ''
777
+ }
778
+ break
779
+ }
780
+
781
+ return {
782
+ property: column.property,
783
+ value:
784
+ column.footer.formatCurrency && (typeof value === 'string' || typeof value === 'number')
785
+ ? formatCurrency(value, {})
786
+ : value,
787
+ }
788
+ }
789
+ return {
790
+ property: column.property,
791
+ value: '',
792
+ }
793
+ }),
794
+ )
795
+ //#endregion
796
+ onMount(() => {
797
+ setDefaultColumnWidths()
798
+ })
799
+ </script>
800
+
801
+ {#if filterEnabled}
802
+ <div class={headerRowClass}>
803
+ <div class={headerColumnClass}>
804
+ {@render header?.()}
805
+ </div>
806
+ <div class={filterColumnClass}>
807
+ <Input
808
+ label={filterLabel}
809
+ showLabel={showFilterLabel}
810
+ bind:value={filter}
811
+ placeholder={filterPlaceholder}
812
+ disabled={filterDisabled}
813
+ readonly={filterReadonly || null}
814
+ lazy={filterLazy}
815
+ />
816
+ <!-- || null is so svelte doesn't include readonly when it's falsy, probably a result of it being `restProps`'d on the input -->
817
+ </div>
818
+ </div>
819
+ {/if}
820
+
821
+ <!-- webkit-user-select: none; here fixes an issue in Safari where text selection of the column headers would happen while resizing the columns -->
822
+ <div
823
+ class={[parentClass, responsiveClass]}
824
+ style={parentStyle}
825
+ class:mb-3={showPagination}
826
+ style:user-select={columnResizingIsActive ? 'none' : undefined}
827
+ style:-webkit-user-select={columnResizingIsActive ? 'none' : undefined}
828
+ style:cursor={columnResizingIsActive ? 'col-resize' : undefined}
829
+ bind:this={tableParent}
830
+ >
831
+ <table
832
+ id={tableId}
833
+ class={['table mb-0', tableClass]}
834
+ class:table-sm={size === 'sm'}
835
+ class:table-layout-fixed={columnResizingEnabled && useFixedLayout}
836
+ class:sticky={stickyHeader}
837
+ class:table-striped={striped}
838
+ class:table-bordered={bordered}
839
+ class:table-hover={hover}
840
+ {...rest}
841
+ >
842
+ <thead>
843
+ <tr>
844
+ {#each visibleColumns as column, index}
845
+ {@const isSortColumn = sortColumn?.property === column.property}
846
+ {@const doEllipsis = column.ellipsis || columnResizingEnabled}
847
+
848
+ <th
849
+ id="col-{tableId}-{column.property}"
850
+ title={column.title ?? column.name}
851
+ style:cursor={column.sortType !== false && !isArbitraryProperty(column.property) ? 'pointer' : ''}
852
+ style:width={column.userWidth ?? column.width}
853
+ style:min-width={column.minWidth}
854
+ data-sort-specified={isSortColumn ? sortDirection : ''}
855
+ class:text-nowrap={!column.wrap}
856
+ class="unselectable {column.class ?? ''}"
857
+ class:d-print-none={column.hideForPrint}
858
+ class:text-left={!bs5 && column.align === 'left'}
859
+ class:text-start={column.align === 'start' || (bs5 && column.align === 'left')}
860
+ class:text-right={!bs5 && (column.align === 'right' || column.numeric)}
861
+ class:text-end={column.align === 'end' || (bs5 && (column.align === 'right' || column.numeric))}
862
+ class:text-center={column.align === 'center'}
863
+ class:text-truncate={doEllipsis}
864
+ class:bg-white={!bs5 && stickyHeader}
865
+ onclick={() => columnClickHandler(column)}
866
+ oncontextmenu={event => contextMenuHandler(event, column.property)}
867
+ >
868
+ <span
869
+ class="text-truncate d-inline-block"
870
+ style="vertical-align: bottom;"
871
+ style:max-width={doEllipsis && isSortColumn ? 'calc(100% - 20px)' : '100%'}
872
+ >
873
+ <!-- Don't add any whitespace btwn these if blocks to keep the spaces correct -->
874
+ {#if column.icon && column.iconLeft}
875
+ <i class="fa-fw {column.iconPrefix || 'fas'} fa-{column.icon}"></i>{#if column.name}&nbsp;{/if}
876
+ {/if}{column.name}{#if column.icon && !column.iconLeft}
877
+ {#if column.name}&nbsp;{/if}<i class="fa-fw {column.iconPrefix || 'fas'} fa-{column.icon}"></i>
878
+ {/if}
879
+ </span>
880
+ {#if isSortColumn}
881
+ {sortDirection === 'ASC' ? '▲' : '▼'}
882
+ {/if}
883
+ {#if columnResizingEnabled && visibleColumns.length - 1 !== index}
884
+ <!-- I think setting the role and aria-orientation attributes is the best we can do here -->
885
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
886
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
887
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
888
+ <div
889
+ id="col-resizer-{tableId}-{column.property}"
890
+ tabindex={0}
891
+ role="separator"
892
+ aria-orientation="horizontal"
893
+ class="resizer"
894
+ style="height: 100%;"
895
+ onmousedown={e => onColumnMouseDown(e, column)}
896
+ >
897
+ &nbsp;
898
+ </div>
899
+ {/if}
900
+ </th>
901
+ {/each}
902
+ </tr>
903
+ </thead>
904
+ <tbody class:unselectable={selectionMode === 'RANGE'}>
905
+ {#if body}
906
+ {@render body?.({ rows: currentPageRows, visibleColumnsCount: visibleColumns.length })}
907
+ {:else}
908
+ {#each currentPageRows as row, index (row[idProp])}
909
+ {#if children}{@render children({ row, index })}{:else}
910
+ <tr
911
+ class:table-primary={rowIsSelected(row, rowSelectionIdProp, selectedRowIds)}
912
+ onclick={() => rowClick(row)}
913
+ >
914
+ {#each computedColumns as column (column.property)}
915
+ <Td
916
+ align={column.align}
917
+ property={column.property}
918
+ >
919
+ {isArbitraryProperty(column.property)
920
+ ? ''
921
+ : column.formatter
922
+ ? column.formatter(getNestedProperty(row, column.property, ''))
923
+ : getNestedProperty(row, column.property, '')}
924
+ </Td>
925
+ {/each}
926
+ </tr>
927
+ {/if}
928
+ {:else}
929
+ {@render noRows?.({ visibleColumnsCount: visibleColumns.length })}
930
+ {/each}
931
+ {/if}
932
+ </tbody>
933
+ {#if showFooter && footers}
934
+ <tfoot>
935
+ <tr class="table-secondary">
936
+ {#if footerRow}
937
+ {@render footerRow({ footers })}
938
+ {:else}
939
+ {#each footers as { property, value } (property)}
940
+ <Td
941
+ {property}
942
+ tagName="TH">{value ?? ''}</Td
943
+ >
944
+ {/each}
945
+ {/if}
946
+ </tr>
947
+ </tfoot>
948
+ {/if}
949
+ </table>
950
+ </div>
951
+
952
+ <Pagination
953
+ {perPageCount}
954
+ {totalItemsCount}
955
+ items={sortedRows}
956
+ bind:currentPageItems={() => untrack(() => currentPageRows), items => (currentPageRows = items)}
957
+ bind:currentPageNumber
958
+ bind:lastPageNumber
959
+ {pageChange}
960
+ bind:this={paginationComponent}
961
+ />
962
+
963
+ <ContextMenu
964
+ id="hide-column-context-menu"
965
+ bind:this={contextMenu}
966
+ >
967
+ <button
968
+ class={['dropdown-item', hideButtonClass]}
969
+ class:disabled={contextMenuColumn?.unhidable}
970
+ onclick={() => contextMenuColumn && hideColumn(contextMenuColumn)}
971
+ >
972
+ <i class="fas fa-eye-slash"></i>
973
+ {#if contextMenuColumn?.name}
974
+ {translate('common:tableHideColumn', 'Hide {{- columnName}}', { columnName: contextMenuColumn.name })}
975
+ {:else if contextMenuColumn?.icon}
976
+ {translate('common:hide', 'Hide')}
977
+ <i class="{contextMenuColumn?.iconPrefix || 'fas'} fa-{contextMenuColumn?.icon}"></i>
978
+ {/if}
979
+ </button>
980
+
981
+ {#if hiddenColumns.length > 0}
982
+ <div class="dropdown-divider"></div>
983
+ <h5 class="dropdown-header"><i class="fas fa-eye"></i> {translate('common:tableShowColumns', 'Show Column')}</h5>
984
+ {/if}
985
+ {#each hiddenColumns as hiddenColumn (hiddenColumn.property)}
986
+ <button
987
+ class="dropdown-item"
988
+ onclick={() => showColumn(hiddenColumn)}
989
+ >
990
+ {#if hiddenColumn.name}
991
+ {hiddenColumn.name}
992
+ {:else if hiddenColumn.icon}
993
+ <i class="{hiddenColumn.iconPrefix || 'fas'} fa-{hiddenColumn.icon}"></i>
994
+ {/if}
995
+ </button>
996
+ {/each}
997
+ {#if columnResizingEnabled}
998
+ <div class="dropdown-divider"></div>
999
+ <DropdownItem
1000
+ icon="broom"
1001
+ onclick={() => {
1002
+ columnInfo.updateColumns(
1003
+ computedColumns.map(col => ({
1004
+ property: col.property,
1005
+ userWidth: undefined,
1006
+ })),
1007
+ )
1008
+ setDefaultColumnWidths()
1009
+ }}>{translate('common:tableResetColumnSizes', 'Reset Column Sizes')}</DropdownItem
1010
+ >
1011
+ {/if}
1012
+ </ContextMenu>
1013
+
1014
+ <style>
1015
+ table.sticky {
1016
+ position: relative;
1017
+ }
1018
+
1019
+ table.sticky th {
1020
+ position: sticky;
1021
+ top: 0;
1022
+ box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.4);
1023
+ }
1024
+
1025
+ table.sticky > thead > tr > th {
1026
+ z-index: 3;
1027
+ }
1028
+
1029
+ /* Remove bottom margins created by form-groups in the table (BS4 only) */
1030
+ table > tbody :global(.form-group) {
1031
+ margin-bottom: 0%;
1032
+ }
1033
+
1034
+ /* BS5 removed .form-group, which makes it a little trickier to target the label's parent div, but this should do it
1035
+ - The Label component adds mb-3 to the parent div if the label is hidden or mb-1 if it's shown (unlikely if it's in a table)
1036
+ - That div will have a .input-group, .form-control, or .form-select as a direct descendant
1037
+ */
1038
+ table
1039
+ > tbody
1040
+ :global(
1041
+ td div:where(.mb-3, .mb-1):not(.form-group):has(> :where(.input-group, .form-control, .form-select, .btn-group))
1042
+ ) {
1043
+ margin-bottom: 0% !important;
1044
+ }
1045
+
1046
+ .resizer {
1047
+ position: absolute;
1048
+ top: 0;
1049
+ right: 0;
1050
+ width: 10px;
1051
+ cursor: col-resize;
1052
+ user-select: none;
1053
+ }
1054
+ .resizer:hover,
1055
+ .resizing {
1056
+ border-right: 5px solid darkslategray;
1057
+ }
1058
+ .table-layout-fixed {
1059
+ table-layout: fixed;
1060
+ }
1061
+ </style>