Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: optimize re-renders #87

Merged
merged 6 commits into from
Jul 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 130 additions & 0 deletions src/data-workspace/category-combo-table/category-combo-table-header.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import i18n from '@dhis2/d2-i18n'
import { TableRowHead, TableCellHead } from '@dhis2/ui'
import cx from 'classnames'
import PropTypes from 'prop-types'
import React, { useMemo } from 'react'
import { useMetadata, selectors } from '../../metadata/index.js'
import { useActiveCell } from '../data-entry-cell/index.js'
import styles from './category-combo-table.module.css'
import { PaddingCell } from './padding-cell.js'
import { TotalHeader } from './total-cells.js'

// Computes the span and columns to render in each category-row
// columns are category-options, and needs to be repeated in case of multiple categories
const useCategoryColumns = (categories, numberOfCoCs) => {
const { data: metadata } = useMetadata()
return useMemo(() => {
let catColSpan = numberOfCoCs
return categories.map((c) => {
const categoryOptions = selectors.getCategoryOptionsByCategoryId(
metadata,
c.id
)
const nrOfOptions = c.categoryOptions.length
// catColSpan should always be equal to nrOfOptions in last iteration
// unless anomaly with categoryOptionCombo-generation server-side
if (nrOfOptions > 0 && catColSpan >= nrOfOptions) {
// calculate colSpan for current options
// this is the span for each option, not the "total" span of the row
catColSpan = catColSpan / nrOfOptions
// when table have multiple categories, options need to be repeated for each disaggregation "above" current-category
const repeat = numberOfCoCs / (catColSpan * nrOfOptions)

const columnsToRender = new Array(repeat)
.fill(0)
.flatMap(() => categoryOptions)

return {
span: catColSpan,
columns: columnsToRender,
category: c,
}
} else {
console.warn(
`Category ${c.displayFormName} malformed. Number of options: ${nrOfOptions}, span: ${catColSpan}`
)
}
return c
})
}, [metadata, categories, numberOfCoCs])
}

export const CategoryComboTableHeader = ({
renderRowTotals,
paddingCells,
categoryOptionCombos,
categories,
checkTableActive,
}) => {
const { deId: activeDeId, cocId: activeCocId } = useActiveCell()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm thinking that it would probably benefit the app's architecture and performance if we were to push this form state subscription down to the level of the actual header cell.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really think it's necessary to push it further. You could in theory have a CategoryTableHeaderColumns and move it there, and basically move the rendered component from columns.map.... But that would only save re-rendering of the static components "Category name" and "PaddingCell". Again these are static, with no dynamic props and no DOM-updated are needed.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was mainly concerned about the nested iterations needed to compute the columns, and that fact that they would need to run whenever a the active cell changes. I suggested solving this by pushing the subscription to the active cell down, but I noticed you are now memoizing these columns in the useCategoryColumns. I think that's an equally valid solution.


const rowToColumnsMap = useCategoryColumns(
categories,
categoryOptionCombos.length
)

// Find if this column header includes the active cell's column
const isHeaderActive = (headerIdx, headerColSpan) => {
const activeCellColIdx = categoryOptionCombos.findIndex(
(coc) => activeCocId === coc.id
)
const idxDiff = activeCellColIdx - headerIdx * headerColSpan
return (
checkTableActive(activeDeId) &&
idxDiff < headerColSpan &&
idxDiff >= 0
)
}
Mohammer5 marked this conversation as resolved.
Show resolved Hide resolved

return rowToColumnsMap.map((colInfo, colInfoIndex) => {
const { span, columns, category } = colInfo
return (
<TableRowHead key={category.id}>
<TableCellHead
className={styles.categoryNameHeader}
colSpan={'1'}
>
{category.displayFormName !== 'default' &&
category.displayFormName}
</TableCellHead>
{columns.map((co, columnIndex) => {
return (
<TableCellHead
key={columnIndex}
className={cx(styles.tableHeader, {
[styles.active]: isHeaderActive(
columnIndex,
span
),
})}
colSpan={span.toString()}
>
{co.isDefault
? i18n.t('Value')
: co.displayFormName}
</TableCellHead>
)
})}
{paddingCells.map((_, i) => (
<PaddingCell key={i} />
))}
{renderRowTotals && colInfoIndex === 0 && (
<TotalHeader rowSpan={categories.length} />
)}
</TableRowHead>
)
})
}

CategoryComboTableHeader.propTypes = {
categories: PropTypes.array,
// Note that this must be the sorted categoryoOptionCombos, eg. in the same order as they are rendered
categoryOptionCombos: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string,
})
),
checkTableActive: PropTypes.func,
paddingCells: PropTypes.array,
renderRowTotals: PropTypes.bool,
}
126 changes: 21 additions & 105 deletions src/data-workspace/category-combo-table/category-combo-table.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,15 @@
import i18n from '@dhis2/d2-i18n'
import {
TableRowHead,
TableCellHead,
TableBody,
TableRow,
TableCell,
} from '@dhis2/ui'
import cx from 'classnames'
import { TableBody, TableRow, TableCell } from '@dhis2/ui'
import PropTypes from 'prop-types'
import React, { useMemo } from 'react'
import React, { useMemo, useCallback } from 'react'
import { useMetadata, selectors } from '../../metadata/index.js'
import { cartesian } from '../../shared/utils.js'
import {
DataEntryCell,
DataEntryField,
useActiveCell,
} from '../data-entry-cell/index.js'
import { DataEntryCell, DataEntryField } from '../data-entry-cell/index.js'
import { getFieldId } from '../get-field-id.js'
import { CategoryComboTableHeader } from './category-combo-table-header.js'
import styles from './category-combo-table.module.css'
import { TotalHeader, ColumnTotals, RowTotal } from './total-cells.js'
import { DataElementCell } from './data-element-cell.js'
import { ColumnTotals, RowTotal } from './total-cells.js'

export const CategoryComboTable = ({
categoryCombo,
Expand All @@ -31,7 +22,6 @@ export const CategoryComboTable = ({
renderColumnTotals,
}) => {
const { data: metadata } = useMetadata()
const { deId: activeDeId, cocId: activeCocId } = useActiveCell()

const categories = selectors.getCategoriesByCategoryComboId(
metadata,
Expand Down Expand Up @@ -64,37 +54,13 @@ export const CategoryComboTable = ({
Server: ${categoryCombo.categoryOptionCombos.length})`
)
}
// Computes the span and repeats for each columns in a category-row.
// Repeats are the number of times the options in a category needs to be rendered per category-row
let catColSpan = sortedCOCs.length
const rowToColumnsMap = categories.map((c) => {
const categoryOptions = selectors.getCategoryOptionsByCategoryId(
metadata,
c.id
)
const nrOfOptions = c.categoryOptions.length
if (nrOfOptions > 0 && catColSpan >= nrOfOptions) {
catColSpan = catColSpan / nrOfOptions
const repeat = sortedCOCs.length / (catColSpan * nrOfOptions)

const columnsToRender = new Array(repeat)
.fill(0)
.flatMap(() => categoryOptions)

return {
span: catColSpan,
columns: columnsToRender,
category: c,
}
} else {
console.warn(
`Category ${c.displayFormName} malformed. Number of options: ${nrOfOptions}, span: ${catColSpan}`
)
}
return c
})
const checkTableActive = useCallback(
(activeDeId) => dataElements.some(({ id }) => id === activeDeId),
[dataElements]
)

const renderPaddedCells =
const paddingCells =
maxColumnsInSection > 0
? new Array(maxColumnsInSection - sortedCOCs.length).fill(0)
: []
Expand All @@ -108,69 +74,19 @@ export const CategoryComboTable = ({
})
const itemsHiddenCnt = dataElements.length - filteredDataElements.length

// Is the active cell in this cat-combo table? Check to see if active
// data element is in this CCT
const isThisTableActive = dataElements.some(({ id }) => id === activeDeId)

// Find if this column header includes the active cell's column
const isHeaderActive = (headerIdx, headerColSpan) => {
const activeCellColIdx = sortedCOCs.findIndex(
(coc) => activeCocId === coc.id
)
const idxDiff = activeCellColIdx - headerIdx * headerColSpan
return isThisTableActive && idxDiff < headerColSpan && idxDiff >= 0
}

return (
<TableBody>
{rowToColumnsMap.map((colInfo, colInfoIndex) => {
const { span, columns, category } = colInfo
return (
<TableRowHead key={category.id}>
<TableCellHead
className={styles.categoryNameHeader}
colSpan={'1'}
>
{category.displayFormName !== 'default' &&
category.displayFormName}
</TableCellHead>
{columns.map((co, columnIndex) => {
return (
<TableCellHead
key={columnIndex}
className={cx(styles.tableHeader, {
[styles.active]: isHeaderActive(
columnIndex,
span
),
})}
colSpan={span.toString()}
>
{co.isDefault
? i18n.t('Value')
: co.displayFormName}
</TableCellHead>
)
})}
{renderPaddedCells.map((_, i) => (
<PaddingCell key={i} />
))}
{renderRowTotals && colInfoIndex === 0 && (
<TotalHeader rowSpan={categories.length} />
)}
</TableRowHead>
)
})}
<CategoryComboTableHeader
categoryOptionCombos={sortedCOCs}
categories={categories}
renderRowTotals={renderRowTotals}
paddingCells={paddingCells}
checkTableActive={checkTableActive}
/>
{filteredDataElements.map((de, i) => {
return (
<TableRow key={de.id}>
<TableCell
className={cx(styles.dataElementName, {
[styles.active]: de.id === activeDeId,
})}
>
{de.displayFormName}
</TableCell>
<DataElementCell dataElement={de} />
{sortedCOCs.map((coc) => (
<DataEntryCell key={coc.id}>
<DataEntryField
Expand All @@ -182,7 +98,7 @@ export const CategoryComboTable = ({
/>
</DataEntryCell>
))}
{renderPaddedCells.map((_, i) => (
{paddingCells.map((_, i) => (
<PaddingCell key={i} className={styles.tableCell} />
))}
{renderRowTotals && (
Expand All @@ -197,7 +113,7 @@ export const CategoryComboTable = ({
})}
{renderColumnTotals && (
<ColumnTotals
paddedCells={renderPaddedCells}
paddingCells={paddingCells}
renderTotalSum={renderRowTotals && renderColumnTotals}
dataElements={dataElements}
categoryOptionCombos={sortedCOCs}
Expand Down
32 changes: 32 additions & 0 deletions src/data-workspace/category-combo-table/data-element-cell.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { TableCell } from '@dhis2/ui'
import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import { useActiveCell } from '../data-entry-cell/index.js'
import styles from './category-combo-table.module.css'

export const DataElementCell = ({ dataElement }) => {
const { deId: activeDeId } = useActiveCell()
return (
<TableCell
className={cx(styles.dataElementName, {
[styles.active]: dataElement.id === activeDeId,
})}
>
{dataElement.displayFormName}
</TableCell>
)
}

DataElementCell.propTypes = {
dataElement: PropTypes.shape({
id: PropTypes.string.isRequired,
categoryCombo: PropTypes.shape({
id: PropTypes.string,
}),
displayFormName: PropTypes.string,
valueType: PropTypes.string,
}),
}

export default DataElementCell
9 changes: 9 additions & 0 deletions src/data-workspace/category-combo-table/padding-cell.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { TableCell } from '@dhis2/ui'
import React from 'react'
import styles from './category-combo-table.module.css'

export const PaddingCell = () => (
<TableCell className={styles.paddingCell}></TableCell>
)

export default PaddingCell
8 changes: 4 additions & 4 deletions src/data-workspace/category-combo-table/total-cells.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ TotalCell.propTypes = {
}

export const TotalHeader = ({ rowSpan }) => (
<TableCellHead className={styles.totalHeader} rowSpan={rowSpan}>
<TableCellHead className={styles.totalHeader} rowSpan={rowSpan.toString()}>
{i18n.t('Totals')}
</TableCellHead>
)
Expand All @@ -42,7 +42,7 @@ RowTotal.propTypes = {

export const ColumnTotals = ({
renderTotalSum,
paddedCells,
paddingCells,
dataElements,
categoryOptionCombos,
}) => {
Expand All @@ -57,7 +57,7 @@ export const ColumnTotals = ({
{columnTotals.map((v, i) => (
<TotalCell key={i}>{v}</TotalCell>
))}
{paddedCells.map((_, i) => (
{paddingCells.map((_, i) => (
<TotalCell key={i} />
))}
{renderTotalSum && (
Expand All @@ -72,6 +72,6 @@ export const ColumnTotals = ({
ColumnTotals.propTypes = {
categoryOptionCombos: propTypes.array,
dataElements: propTypes.array,
paddedCells: propTypes.array,
paddingCells: propTypes.array,
renderTotalSum: propTypes.bool,
}
Loading