Open History to see the last commit
1import { defaultColumn, emptyRenderer } from './publicUtils'
2β
3// Find the depth of the columns
4export function findMaxDepth(columns, depth = 0) {
5 return columns.reduce((prev, curr) => {
6 if (curr.columns) {
7 return Math.max(prev, findMaxDepth(curr.columns, depth + 1))
8 }
9 return depth
10 }, 0)
11}
12β
13// Build the visible columns, headers and flat column list
14export function linkColumnStructure(columns, parent, depth = 0) {
15 return columns.map(column => {
16 column = {
17 ...column,
18 parent,
19 depth,
20 }
21β
22 assignColumnAccessor(column)
23β
24 if (column.columns) {
25 column.columns = linkColumnStructure(column.columns, column, depth + 1)
26 }
27 return column
28 })
29}
30β
31export function flattenColumns(columns) {
32 return flattenBy(columns, 'columns')
33}
34β
35export function assignColumnAccessor(column) {
36 // First check for string accessor
37 let { id, accessor, Header } = column
38β
39 if (typeof accessor === 'string') {
40 id = id || accessor
41 const accessorPath = accessor.split('.')
42 accessor = row => getBy(row, accessorPath)
43 }
44β
45 if (!id && typeof Header === 'string' && Header) {
46 id = Header
47 }
48β
49 if (!id && column.columns) {
50 console.error(column)
51 throw new Error('A column ID (or unique "Header" value) is required!')
52 }
53β
54 if (!id) {
55 console.error(column)
56 throw new Error('A column ID (or string accessor) is required!')
57 }
58β
59 Object.assign(column, {
60 id,
61 accessor,
62 })
63β
64 return column
65}
66β
67export function decorateColumn(column, userDefaultColumn) {
68 if (!userDefaultColumn) {
69 throw new Error()
70 }
71 Object.assign(column, {
72 // Make sure there is a fallback header, just in case
73 Header: emptyRenderer,
74 Footer: emptyRenderer,
75 ...defaultColumn,
76 ...userDefaultColumn,
77 ...column,
78 })
79β
80 Object.assign(column, {
81 originalWidth: column.width,
82 })
83β
84 return column
85}
86β
87// Build the header groups from the bottom up
88export function makeHeaderGroups(
89 allColumns,
90 defaultColumn,
91 additionalHeaderProperties = () => ({})
92) {
93 const headerGroups = []
94β
95 let scanColumns = allColumns
96β
97 let uid = 0
98 const getUID = () => uid++
99β
100 while (scanColumns.length) {
101 // The header group we are creating
102 const headerGroup = {
103 headers: [],
104 }
105β
106 // The parent columns we're going to scan next
107 const parentColumns = []
108β
109 const hasParents = scanColumns.some(d => d.parent)
110β
111 // Scan each column for parents
112 scanColumns.forEach(column => {
113 // What is the latest (last) parent column?
114 let latestParentColumn = [...parentColumns].reverse()[0]
115β
116 let newParent
117β
118 if (hasParents) {
119 // If the column has a parent, add it if necessary
120 if (column.parent) {
121 newParent = {
122 ...column.parent,
123 originalId: column.parent.id,
124 id: `${column.parent.id}_${getUID()}`,
125 headers: [column],
126 ...additionalHeaderProperties(column),
127 }
128 } else {
129 // If other columns have parents, we'll need to add a place holder if necessary
130 const originalId = `${column.id}_placeholder`
131 newParent = decorateColumn(
132 {
133 originalId,
134 id: `${column.id}_placeholder_${getUID()}`,
135 placeholderOf: column,
136 headers: [column],
137 ...additionalHeaderProperties(column),
138 },
139 defaultColumn
140 )
141 }
142β
143 // If the resulting parent columns are the same, just add
144 // the column and increment the header span
145 if (
146 latestParentColumn &&
147 latestParentColumn.originalId === newParent.originalId
148 ) {
149 latestParentColumn.headers.push(column)
150 } else {
151 parentColumns.push(newParent)
152 }
153 }
154β
155 headerGroup.headers.push(column)
156 })
157β
158 headerGroups.push(headerGroup)
159β
160 // Start scanning the parent columns
161 scanColumns = parentColumns
162 }
163β
164 return headerGroups.reverse()
165}
166β
167const pathObjCache = new Map()
168β
169export function getBy(obj, path, def) {
170 if (!path) {
171 return obj
172 }
173 const cacheKey = typeof path === 'function' ? path : JSON.stringify(path)
174β
175 const pathObj =
176 pathObjCache.get(cacheKey) ||
177 (() => {
178 const pathObj = makePathArray(path)
179 pathObjCache.set(cacheKey, pathObj)
180 return pathObj
181 })()
182β
183 let val
184β
185 try {
186 val = pathObj.reduce((cursor, pathPart) => cursor[pathPart], obj)
187 } catch (e) {
188 // continue regardless of error
189 }
190 return typeof val !== 'undefined' ? val : def
191}
192β
193export function getFirstDefined(...args) {
194 for (let i = 0; i < args.length; i += 1) {
195 if (typeof args[i] !== 'undefined') {
196 return args[i]
197 }
198 }
199}
200β
201export function getElementDimensions(element) {
202 const rect = element.getBoundingClientRect()
203 const style = window.getComputedStyle(element)
204 const margins = {
205 left: parseInt(style.marginLeft),
206 right: parseInt(style.marginRight),
207 }
208 const padding = {
209 left: parseInt(style.paddingLeft),
210 right: parseInt(style.paddingRight),
211 }
212 return {
213 left: Math.ceil(rect.left),
214 width: Math.ceil(rect.width),
215 outerWidth: Math.ceil(
216 rect.width + margins.left + margins.right + padding.left + padding.right
217 ),
218 marginLeft: margins.left,
219 marginRight: margins.right,
220 paddingLeft: padding.left,
221 paddingRight: padding.right,
222 scrollWidth: element.scrollWidth,
223 }
224}
225β
226export function isFunction(a) {
227 if (typeof a === 'function') {
228 return a
229 }
230}
231β
232export function flattenBy(arr, key) {
233 const flat = []
234β
235 const recurse = arr => {
236 arr.forEach(d => {
237 if (!d[key]) {
238 flat.push(d)
239 } else {
240 recurse(d[key])
241 }
242 })
243 }
244β
245 recurse(arr)
246β
247 return flat
248}
249β
250export function expandRows(
251 rows,
252 { manualExpandedKey, expanded, expandSubRows = true }
253) {
254 const expandedRows = []
255β
256 const handleRow = (row, addToExpandedRows = true) => {
257 row.isExpanded =
258 (row.original && row.original[manualExpandedKey]) || expanded[row.id]
259β
260 row.canExpand = row.subRows && !!row.subRows.length
261β
262 if (addToExpandedRows) {
263 expandedRows.push(row)
264 }
265β
266 if (row.subRows && row.subRows.length && row.isExpanded) {
267 row.subRows.forEach(row => handleRow(row, expandSubRows))
268 }
269 }
270β
271 rows.forEach(row => handleRow(row))
272β
273 return expandedRows
274}
275β
276export function getFilterMethod(filter, userFilterTypes, filterTypes) {
277 return (
278 isFunction(filter) ||
279 userFilterTypes[filter] ||
280 filterTypes[filter] ||
281 filterTypes.text
282 )
283}
284β
285export function shouldAutoRemoveFilter(autoRemove, value, column) {
286 return autoRemove ? autoRemove(value, column) : typeof value === 'undefined'
287}
288β
289export function unpreparedAccessWarning() {
290 throw new Error(
291 'React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.'
292 )
293}
294β
295let passiveSupported = null
296export function passiveEventSupported() {
297 // memoize support to avoid adding multiple test events
298 if (typeof passiveSupported === 'boolean') return passiveSupported
299β
300 let supported = false
301 try {
302 const options = {
303 get passive() {
304 supported = true
305 return false
306 },
307 }
308β
309 window.addEventListener('test', null, options)
310 window.removeEventListener('test', null, options)
311 } catch (err) {
312 supported = false
313 }
314 passiveSupported = supported
315 return passiveSupported
316}
317β
318//
319β
320const reOpenBracket = /\[/g
321const reCloseBracket = /\]/g
322β
323function makePathArray(obj) {
324 return (
325 flattenDeep(obj)
326 // remove all periods in parts
327 .map(d => String(d).replace('.', '_'))
328 // join parts using period
329 .join('.')
330 // replace brackets with periods
331 .replace(reOpenBracket, '.')
332 .replace(reCloseBracket, '')
333 // split it back out on periods
334 .split('.')
335 )
336}
337β
338function flattenDeep(arr, newArr = []) {
339 if (!Array.isArray(arr)) {
340 newArr.push(arr)
341 } else {
342 for (let i = 0; i < arr.length; i += 1) {
343 flattenDeep(arr[i], newArr)
344 }
345 }
346 return newArr
347}