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 3 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 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'

export const CategoryComboTableHeader = ({
dataElements,
renderRowTotals,
paddingCells,
categoryOptionCombos,
categories,
}) => {
const { data: metadata } = useMetadata()
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.


// 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 = categoryOptionCombos.length
const rowToColumnsMap = 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 =
categoryOptionCombos.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
})

// 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 = categoryOptionCombos.findIndex(
(coc) => activeCocId === coc.id
)
const idxDiff = activeCellColIdx - headerIdx * headerColSpan
return isThisTableActive && idxDiff < headerColSpan && idxDiff >= 0
}
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 just wondering why we also need to isThisTableActive const. Is it possible that a form contains several tables with the same dataElements?

Look at this very naively, I would expect that every cell will be unique so we don't need this variable per se. If you have added that isThisTableActive variable to make the code more performant, then you should add it as an early return in the isHeaderActive function.

Having said all of that, if you agree with my earlier suggestion, about moving the active/inactive logic down to the actual header cell, then this code is going to change anyway.

Copy link
Member Author

@Birkbjo Birkbjo Jul 6, 2022

Choose a reason for hiding this comment

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

I did some refactoring to not need to pass all dataElements to this component. So I pass a function checkTableActive instead. But yes, it's needed because section-forms render multiple tables, and we only want to highlight the active table.

Is it possible that a form contains several tables with the same dataElements?

No, and that's why this fact is used to check if the current table is "active" or not.

then you should add it as an early return in the isHeaderActive function.

I don't really understand what you mean here? This is only a part of the check isHeaderActive. It's not enough to know if the current table is active. You need to also check if the current active cell is in the correct columns AND row as well. This code is for highlighting of the headers.

Copy link
Contributor

Choose a reason for hiding this comment

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

I did some refactoring to not need to pass all dataElements to this component. So I pass a function checkTableActive instead. But yes, it's needed because section-forms render multiple tables, and we only want to highlight the active table.

Is it possible that a form contains several tables with the same dataElements?

No, and that's why this fact is used to check if the current table is "active" or not.

Partly from your explanation above, and by looking at the code a bit more closely, I get this now 👍 .


then you should add it as an early return in the isHeaderActive function.

I don't really understand what you mean here?

I was mainly just figuring out what was happening, and my suggestion about returning early was basically just this (see the comment):

    const isHeaderActive = (headerIdx, headerColSpan) => {
        if (!checkTableActive(activeDeId)) {
            return false
        }
        // by returning early you can avoid this iteration
        const activeCellColIdx = categoryOptionCombos.findIndex(
            (coc) => activeCocId === coc.id
        )
        const idxDiff = activeCellColIdx - headerIdx * headerColSpan
        return (idxDiff < headerColSpan && idxDiff >= 0)
    }

But this is very much a micro-optimisation, so I'm very happy to skip this.


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 = {
categoryCombo: PropTypes.shape({
id: PropTypes.string.isRequired,
categoryOptionCombos: PropTypes.array,
}).isRequired,
categories: PropTypes.array,
categoryOptionCombos: PropTypes.array,
dataElements: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
categoryCombo: PropTypes.shape({
id: PropTypes.string,
}),
displayFormName: PropTypes.string,
valueType: PropTypes.string,
})
),
paddingCells: PropTypes.array,
renderRowTotals: PropTypes.bool,
}
121 changes: 16 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 { 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,8 @@ 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 renderPaddedCells =
const paddingCells =
maxColumnsInSection > 0
? new Array(maxColumnsInSection - sortedCOCs.length).fill(0)
: []
Expand All @@ -108,69 +69,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}
dataElements={dataElements}
renderRowTotals={renderRowTotals}
paddingCells={paddingCells}
/>
{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 +93,7 @@ export const CategoryComboTable = ({
/>
</DataEntryCell>
))}
{renderPaddedCells.map((_, i) => (
{paddingCells.map((_, i) => (
<PaddingCell key={i} className={styles.tableCell} />
))}
{renderRowTotals && (
Expand All @@ -197,7 +108,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
6 changes: 3 additions & 3 deletions src/data-workspace/category-combo-table/total-cells.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
6 changes: 3 additions & 3 deletions src/data-workspace/data-entry-cell/entry-field-input.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import PropTypes from 'prop-types'
import React from 'react'
import { useRightHandPanelContext } from '../../right-hand-panel/index.js'
import { useCurrentItemContext } from '../../shared/index.js'
import { useSetCurrentItemContext } from '../../shared/index.js'
import { focusNext, focusPrev } from '../focus-utils/index.js'
import {
GenericInput,
Expand Down Expand Up @@ -85,7 +85,7 @@ export function EntryFieldInput({
setSyncStatus,
disabled,
}) {
const currentItemContext = useCurrentItemContext()
const setCurrentItem = useSetCurrentItemContext()
const rightHandPanel = useRightHandPanelContext()
const { id: deId } = de
const { id: cocId } = coc
Expand Down Expand Up @@ -113,7 +113,7 @@ export function EntryFieldInput({
}

const onFocus = () => {
currentItemContext.setItem(currentItem)
setCurrentItem(currentItem)
rightHandPanel.hide()
}

Expand Down
Loading