Skip to content
Source
Sign inSign up
TanStack/table
Open History to see the last commit

methods.js

692 lines20.6 KB

1import React from 'react'
2import _ from './utils'
3​
4export default Base =>
5 class extends Base {
6 getResolvedState (props, state) {
7 const resolvedState = {
8 ..._.compactObject(this.state),
9 ..._.compactObject(this.props),
10 ..._.compactObject(state),
11 ..._.compactObject(props),
12 }
13 return resolvedState
14 }
15​
16 getDataModel (newState, dataChanged) {
17 const {
18 columns,
19 pivotBy = [],
20 data,
21 resolveData,
22 pivotIDKey,
23 pivotValKey,
24 subRowsKey,
25 aggregatedKey,
26 nestingLevelKey,
27 originalKey,
28 indexKey,
29 groupedByPivotKey,
30 SubComponent,
31 } = newState
32​
33 // Determine Header Groups
34 let hasHeaderGroups = false
35 columns.forEach(column => {
36 if (column.columns) {
37 hasHeaderGroups = true
38 }
39 })
40​
41 let columnsWithExpander = [...columns]
42​
43 let expanderColumn = columns.find(
44 col => col.expander || (col.columns && col.columns.some(col2 => col2.expander))
45 )
46 // The actual expander might be in the columns field of a group column
47 if (expanderColumn && !expanderColumn.expander) {
48 expanderColumn = expanderColumn.columns.find(col => col.expander)
49 }
50​
51 // If we have SubComponent's we need to make sure we have an expander column
52 if (SubComponent && !expanderColumn) {
53 expanderColumn = { expander: true }
54 columnsWithExpander = [expanderColumn, ...columnsWithExpander]
55 }
56​
57 const makeDecoratedColumn = (column, parentColumn) => {
58 let dcol
59 if (column.expander) {
60 dcol = {
61 ...this.props.column,
62 ...this.props.expanderDefaults,
63 ...column,
64 }
65 } else {
66 dcol = {
67 ...this.props.column,
68 ...column,
69 }
70 }
71​
72 // Ensure minWidth is not greater than maxWidth if set
73 if (dcol.maxWidth < dcol.minWidth) {
74 dcol.minWidth = dcol.maxWidth
75 }
76​
77 if (parentColumn) {
78 dcol.parentColumn = parentColumn
79 }
80​
81 // First check for string accessor
82 if (typeof dcol.accessor === 'string') {
83 dcol.id = dcol.id || dcol.accessor
84 const accessorString = dcol.accessor
85 dcol.accessor = row => _.get(row, accessorString)
86 return dcol
87 }
88​
89 // Fall back to functional accessor (but require an ID)
90 if (dcol.accessor && !dcol.id) {
91 console.warn(dcol)
92 throw new Error(
93 'A column id is required if using a non-string accessor for column above.'
94 )
95 }
96​
97 // Fall back to an undefined accessor
98 if (!dcol.accessor) {
99 dcol.accessor = () => undefined
100 }
101​
102 return dcol
103 }
104​
105 const allDecoratedColumns = []
106​
107 // Decorate the columns
108 const decorateAndAddToAll = (column, parentColumn) => {
109 const decoratedColumn = makeDecoratedColumn(column, parentColumn)
110 allDecoratedColumns.push(decoratedColumn)
111 return decoratedColumn
112 }
113​
114 const decoratedColumns = columnsWithExpander.map(column => {
115 if (column.columns) {
116 return {
117 ...column,
118 columns: column.columns.map(d => decorateAndAddToAll(d, column)),
119 }
120 }
121 return decorateAndAddToAll(column)
122 })
123​
124 // Build the visible columns, headers and flat column list
125 let visibleColumns = decoratedColumns.slice()
126 let allVisibleColumns = []
127​
128 visibleColumns = visibleColumns.map(column => {
129 if (column.columns) {
130 const visibleSubColumns = column.columns.filter(d =>
131 pivotBy.indexOf(d.id) > -1 ? false : _.getFirstDefined(d.show, true)
132 )
133 return {
134 ...column,
135 columns: visibleSubColumns,
136 }
137 }
138 return column
139 })
140​
141 visibleColumns = visibleColumns.filter(column =>
142 column.columns
143 ? column.columns.length
144 : pivotBy.indexOf(column.id) > -1
145 ? false
146 : _.getFirstDefined(column.show, true)
147 )
148​
149 // Find any custom pivot location
150 const pivotIndex = visibleColumns.findIndex(col => col.pivot)
151​
152 // Handle Pivot Columns
153 if (pivotBy.length) {
154 // Retrieve the pivot columns in the correct pivot order
155 const pivotColumns = []
156 pivotBy.forEach(pivotID => {
157 const found = allDecoratedColumns.find(d => d.id === pivotID)
158 if (found) {
159 pivotColumns.push(found)
160 }
161 })
162​
163 const PivotParentColumn = pivotColumns.reduce(
164 (prev, current) => prev && prev === current.parentColumn && current.parentColumn,
165 pivotColumns[0].parentColumn
166 )
167​
168 let PivotGroupHeader = hasHeaderGroups && PivotParentColumn.Header
169 PivotGroupHeader = PivotGroupHeader || (() => <strong>Pivoted</strong>)
170​
171 let pivotColumnGroup = {
172 Header: PivotGroupHeader,
173 columns: pivotColumns.map(col => ({
174 ...this.props.pivotDefaults,
175 ...col,
176 pivoted: true,
177 })),
178 }
179​
180 // Place the pivotColumns back into the visibleColumns
181 if (pivotIndex >= 0) {
182 pivotColumnGroup = {
183 ...visibleColumns[pivotIndex],
184 ...pivotColumnGroup,
185 }
186 visibleColumns.splice(pivotIndex, 1, pivotColumnGroup)
187 } else {
188 visibleColumns.unshift(pivotColumnGroup)
189 }
190 }
191​
192 // Build Header Groups
193 const headerGroups = []
194 let currentSpan = []
195​
196 // A convenience function to add a header and reset the currentSpan
197 const addHeader = (columns, column) => {
198 headerGroups.push({
199 ...this.props.column,
200 ...column,
201 columns,
202 })
203 currentSpan = []
204 }
205​
206 // Build flast list of allVisibleColumns and HeaderGroups
207 visibleColumns.forEach(column => {
208 if (column.columns) {
209 allVisibleColumns = allVisibleColumns.concat(column.columns)
210 if (currentSpan.length > 0) {
211 addHeader(currentSpan)
212 }
213 addHeader(column.columns, column)
214 return
215 }
216 allVisibleColumns.push(column)
217 currentSpan.push(column)
218 })
219 if (hasHeaderGroups && currentSpan.length > 0) {
220 addHeader(currentSpan)
221 }
222​
223 // Access the data
224 const accessRow = (d, i, level = 0) => {
225 const row = {
226 [originalKey]: d,
227 [indexKey]: i,
228 [subRowsKey]: d[subRowsKey],
229 [nestingLevelKey]: level,
230 }
231 allDecoratedColumns.forEach(column => {
232 if (column.expander) return
233 row[column.id] = column.accessor(d)
234 })
235 if (row[subRowsKey]) {
236 row[subRowsKey] = row[subRowsKey].map((d, i) => accessRow(d, i, level + 1))
237 }
238 return row
239 }
240​
241 // // If the data hasn't changed, just use the cached data
242 let resolvedData = this.resolvedData
243 // If the data has changed, run the data resolver and cache the result
244 if (!this.resolvedData || dataChanged) {
245 resolvedData = resolveData(data)
246 this.resolvedData = resolvedData
247 }
248 // Use the resolved data
249 resolvedData = resolvedData.map((d, i) => accessRow(d, i))
250​
251 // TODO: Make it possible to fabricate nested rows without pivoting
252 const aggregatingColumns = allVisibleColumns.filter(d => !d.expander && d.aggregate)
253​
254 // If pivoting, recursively group the data
255 const aggregate = rows => {
256 const aggregationValues = {}
257 aggregatingColumns.forEach(column => {
258 const values = rows.map(d => d[column.id])
259 aggregationValues[column.id] = column.aggregate(values, rows)
260 })
261 return aggregationValues
262 }
263 if (pivotBy.length) {
264 const groupRecursively = (rows, keys, i = 0) => {
265 // This is the last level, just return the rows
266 if (i === keys.length) {
267 return rows
268 }
269 // Group the rows together for this level
270 let groupedRows = Object.entries(_.groupBy(rows, keys[i])).map(([key, value]) => ({
271 [pivotIDKey]: keys[i],
272 [pivotValKey]: key,
273 [keys[i]]: key,
274 [subRowsKey]: value,
275 [nestingLevelKey]: i,
276 [groupedByPivotKey]: true,
277 }))
278 // Recurse into the subRows
279 groupedRows = groupedRows.map(rowGroup => {
280 const subRows = groupRecursively(rowGroup[subRowsKey], keys, i + 1)
281 return {
282 ...rowGroup,
283 [subRowsKey]: subRows,
284 [aggregatedKey]: true,
285 ...aggregate(subRows),
286 }
287 })
288 return groupedRows
289 }
290 resolvedData = groupRecursively(resolvedData, pivotBy)
291 }
292​
293 return {
294 ...newState,
295 resolvedData,
296 allVisibleColumns,
297 headerGroups,
298 allDecoratedColumns,
299 hasHeaderGroups,
300 }
301 }
302​
303 getSortedData (resolvedState) {
304 const {
305 manual,
306 sorted,
307 filtered,
308 defaultFilterMethod,
309 resolvedData,
310 allDecoratedColumns,
311 } = resolvedState
312​
313 const sortMethodsByColumnID = {}
314​
315 allDecoratedColumns
316 .filter(col => col.sortMethod)
317 .forEach(col => {
318 sortMethodsByColumnID[col.id] = col.sortMethod
319 })
320​
321 // Resolve the data from either manual data or sorted data
322 return {
323 sortedData: manual
324 ? resolvedData
325 : this.sortData(
326 this.filterData(resolvedData, filtered, defaultFilterMethod, allDecoratedColumns),
327 sorted,
328 sortMethodsByColumnID
329 ),
330 }
331 }
332​
333 fireFetchData () {
334 // determine the current state, preferring certain state values over props
335 const currentState = {
336 ...this.getResolvedState(),
337 page: this.getStateOrProp('page'),
338 pageSize: this.getStateOrProp('pageSize'),
339 filtered: this.getStateOrProp('filtered'),
340 }
341​
342 this.props.onFetchData(currentState, this)
343 }
344​
345 getPropOrState (key) {
346 return _.getFirstDefined(this.props[key], this.state[key])
347 }
348​
349 getStateOrProp (key) {
350 return _.getFirstDefined(this.state[key], this.props[key])
351 }
352​
353 filterData (data, filtered, defaultFilterMethod, allVisibleColumns) {
354 let filteredData = data
355​
356 if (filtered.length) {
357 filteredData = filtered.reduce((filteredSoFar, nextFilter) => {
358 const column = allVisibleColumns.find(x => x.id === nextFilter.id)
359​
360 // Don't filter hidden columns or columns that have had their filters disabled
361 if (!column || column.filterable === false) {
362 return filteredSoFar
363 }
364​
365 const filterMethod = column.filterMethod || defaultFilterMethod
366​
367 // If 'filterAll' is set to true, pass the entire dataset to the filter method
368 if (column.filterAll) {
369 return filterMethod(nextFilter, filteredSoFar, column)
370 }
371 return filteredSoFar.filter(row => filterMethod(nextFilter, row, column))
372 }, filteredData)
373​
374 // Apply the filter to the subrows if we are pivoting, and then
375 // filter any rows without subcolumns because it would be strange to show
376 filteredData = filteredData
377 .map(row => {
378 if (!row[this.props.subRowsKey]) {
379 return row
380 }
381 return {
382 ...row,
383 [this.props.subRowsKey]: this.filterData(
384 row[this.props.subRowsKey],
385 filtered,
386 defaultFilterMethod,
387 allVisibleColumns
388 ),
389 }
390 })
391 .filter(row => {
392 if (!row[this.props.subRowsKey]) {
393 return true
394 }
395 return row[this.props.subRowsKey].length > 0
396 })
397 }
398​
399 return filteredData
400 }
401​
402 sortData (data, sorted, sortMethodsByColumnID = {}) {
403 if (!sorted.length) {
404 return data
405 }
406​
407 const sortedData = (this.props.orderByMethod || _.orderBy)(
408 data,
409 sorted.map(sort => {
410 // Support custom sorting methods for each column
411 if (sortMethodsByColumnID[sort.id]) {
412 return (a, b) => sortMethodsByColumnID[sort.id](a[sort.id], b[sort.id], sort.desc)
413 }
414 return (a, b) => this.props.defaultSortMethod(a[sort.id], b[sort.id], sort.desc)
415 }),
416 sorted.map(d => !d.desc),
417 this.props.indexKey
418 )
419​
420 sortedData.forEach(row => {
421 if (!row[this.props.subRowsKey]) {
422 return
423 }
424 row[this.props.subRowsKey] = this.sortData(
425 row[this.props.subRowsKey],
426 sorted,
427 sortMethodsByColumnID
428 )
429 })
430​
431 return sortedData
432 }
433​
434 getMinRows () {
435 return _.getFirstDefined(this.props.minRows, this.getStateOrProp('pageSize'))
436 }
437​
438 // User actions
439 onPageChange (page) {
440 const { onPageChange, collapseOnPageChange } = this.props
441​
442 const newState = { page }
443 if (collapseOnPageChange) {
444 newState.expanded = {}
445 }
446 this.setStateWithData(newState, () => onPageChange && onPageChange(page))
447 }
448​
449 onPageSizeChange (newPageSize) {
450 const { onPageSizeChange } = this.props
451 const { pageSize, page } = this.getResolvedState()
452​
453 // Normalize the page to display
454 const currentRow = pageSize * page
455 const newPage = Math.floor(currentRow / newPageSize)
456​
457 this.setStateWithData(
458 {
459 pageSize: newPageSize,
460 page: newPage,
461 },
462 () => onPageSizeChange && onPageSizeChange(newPageSize, newPage)
463 )
464 }
465​
466 sortColumn (column, additive) {
467 const { sorted, skipNextSort, defaultSortDesc } = this.getResolvedState()
468​
469 const firstSortDirection = Object.prototype.hasOwnProperty.call(column, 'defaultSortDesc')
470 ? column.defaultSortDesc
471 : defaultSortDesc
472 const secondSortDirection = !firstSortDirection
473​
474 // we can't stop event propagation from the column resize move handlers
475 // attached to the document because of react's synthetic events
476 // so we have to prevent the sort function from actually sorting
477 // if we click on the column resize element within a header.
478 if (skipNextSort) {
479 this.setStateWithData({
480 skipNextSort: false,
481 })
482 return
483 }
484​
485 const { onSortedChange } = this.props
486​
487 let newSorted = _.clone(sorted || []).map(d => {
488 d.desc = _.isSortingDesc(d)
489 return d
490 })
491 if (!_.isArray(column)) {
492 // Single-Sort
493 const existingIndex = newSorted.findIndex(d => d.id === column.id)
494 if (existingIndex > -1) {
495 const existing = newSorted[existingIndex]
496 if (existing.desc === secondSortDirection) {
497 if (additive) {
498 newSorted.splice(existingIndex, 1)
499 } else {
500 existing.desc = firstSortDirection
501 newSorted = [existing]
502 }
503 } else {
504 existing.desc = secondSortDirection
505 if (!additive) {
506 newSorted = [existing]
507 }
508 }
509 } else if (additive) {
510 newSorted.push({
511 id: column.id,
512 desc: firstSortDirection,
513 })
514 } else {
515 newSorted = [
516 {
517 id: column.id,
518 desc: firstSortDirection,
519 },
520 ]
521 }
522 } else {
523 // Multi-Sort
524 const existingIndex = newSorted.findIndex(d => d.id === column[0].id)
525 // Existing Sorted Column
526 if (existingIndex > -1) {
527 const existing = newSorted[existingIndex]
528 if (existing.desc === secondSortDirection) {
529 if (additive) {
530 newSorted.splice(existingIndex, column.length)
531 } else {
532 column.forEach((d, i) => {
533 newSorted[existingIndex + i].desc = firstSortDirection
534 })
535 }
536 } else {
537 column.forEach((d, i) => {
538 newSorted[existingIndex + i].desc = secondSortDirection
539 })
540 }
541 if (!additive) {
542 newSorted = newSorted.slice(existingIndex, column.length)
543 }
544 // New Sort Column
545 } else if (additive) {
546 newSorted = newSorted.concat(
547 column.map(d => ({
548 id: d.id,
549 desc: firstSortDirection,
550 }))
551 )
552 } else {
553 newSorted = column.map(d => ({
554 id: d.id,
555 desc: firstSortDirection,
556 }))
557 }
558 }
559​
560 this.setStateWithData(
561 {
562 page: (!sorted.length && newSorted.length) || !additive ? 0 : this.state.page,
563 sorted: newSorted,
564 },
565 () => onSortedChange && onSortedChange(newSorted, column, additive)
566 )
567 }
568​
569 filterColumn (column, value) {
570 const { filtered } = this.getResolvedState()
571 const { onFilteredChange } = this.props
572​
573 // Remove old filter first if it exists
574 const newFiltering = (filtered || []).filter(x => x.id !== column.id)
575​
576 if (value !== '') {
577 newFiltering.push({
578 id: column.id,
579 value,
580 })
581 }
582​
583 this.setStateWithData(
584 {
585 filtered: newFiltering,
586 },
587 () => onFilteredChange && onFilteredChange(newFiltering, column, value)
588 )
589 }
590​
591 resizeColumnStart (event, column, isTouch) {
592 event.stopPropagation()
593 const parentWidth = event.target.parentElement.getBoundingClientRect().width
594​
595 let pageX
596 if (isTouch) {
597 pageX = event.changedTouches[0].pageX
598 } else {
599 pageX = event.pageX
600 }
601​
602 this.trapEvents = true
603 this.setStateWithData(
604 {
605 currentlyResizing: {
606 id: column.id,
607 startX: pageX,
608 parentWidth,
609 },
610 },
611 () => {
612 if (isTouch) {
613 document.addEventListener('touchmove', this.resizeColumnMoving)
614 document.addEventListener('touchcancel', this.resizeColumnEnd)
615 document.addEventListener('touchend', this.resizeColumnEnd)
616 } else {
617 document.addEventListener('mousemove', this.resizeColumnMoving)
618 document.addEventListener('mouseup', this.resizeColumnEnd)
619 document.addEventListener('mouseleave', this.resizeColumnEnd)
620 }
621 }
622 )
623 }
624​
625 resizeColumnMoving (event) {
626 event.stopPropagation()
627 const { onResizedChange, column } = this.props
628 const { resized, currentlyResizing, columns } = this.getResolvedState()
629 const currentColumn = columns.find(
630 c => c.accessor === currentlyResizing.id || c.id === currentlyResizing.id
631 )
632 const minResizeWidth =
633 currentColumn && currentColumn.minResizeWidth != null
634 ? currentColumn.minResizeWidth
635 : column.minResizeWidth
636​
637 // Delete old value
638 const newResized = resized.filter(x => x.id !== currentlyResizing.id)
639​
640 let pageX
641​
642 if (event.type === 'touchmove') {
643 pageX = event.changedTouches[0].pageX
644 } else if (event.type === 'mousemove') {
645 pageX = event.pageX
646 }
647​
648 const newWidth = Math.max(
649 currentlyResizing.parentWidth + pageX - currentlyResizing.startX,
650 minResizeWidth
651 )
652​
653 newResized.push({
654 id: currentlyResizing.id,
655 value: newWidth,
656 })
657​
658 this.setStateWithData(
659 {
660 resized: newResized,
661 },
662 () => onResizedChange && onResizedChange(newResized, event)
663 )
664 }
665​
666 resizeColumnEnd (event) {
667 event.stopPropagation()
668 const isTouch = event.type === 'touchend' || event.type === 'touchcancel'
669​
670 if (isTouch) {
671 document.removeEventListener('touchmove', this.resizeColumnMoving)
672 document.removeEventListener('touchcancel', this.resizeColumnEnd)
673 document.removeEventListener('touchend', this.resizeColumnEnd)
674 }
675​
676 // If its a touch event clear the mouse one's as well because sometimes
677 // the mouseDown event gets called as well, but the mouseUp event doesn't
678 document.removeEventListener('mousemove', this.resizeColumnMoving)
679 document.removeEventListener('mouseup', this.resizeColumnEnd)
680 document.removeEventListener('mouseleave', this.resizeColumnEnd)
681​
682 // The touch events don't propagate up to the sorting's onMouseDown event so
683 // no need to prevent it from happening or else the first click after a touch
684 // event resize will not sort the column.
685 if (!isTouch) {
686 this.setStateWithData({
687 skipNextSort: true,
688 currentlyResizing: false,
689 })
690 }
691 }
692 }