Skip to content

Commit

Permalink
fix: normalize expanded
Browse files Browse the repository at this point in the history
  • Loading branch information
schummar committed Aug 26, 2022
1 parent 9b5305c commit 950f089
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/internalState/normalizeExpanded.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useEffect } from 'react';
import { Store } from 'schummar-state/react';
import { getAncestors } from '../misc/helpers';
import { InternalTableState } from '../types';

export function normalizeExpanded<T>(table: Store<InternalTableState<T>>): void {
useEffect(
() =>
table.addReaction(
(state) => [state.props.expandOnlyOne, state.expanded, state.itemsById] as const,
([expandOnlyOne, , itemsById], state) => {
let expanded = state.expanded;
let last, lastItem;
let hasChanged = false;

// If only one branch may be expanded, check if there are more and close if necessary
if (expandOnlyOne && (last = [...expanded][expanded.size - 1]) && (lastItem = itemsById.get(last))) {
const ancestors = getAncestors(itemsById, lastItem);
if ([...expanded].slice(0, -1).some((id) => !ancestors.has(id))) {
expanded = state.expanded = new Set([...ancestors].concat(last));
hasChanged = true;
}
} else {
for (const id of expanded) {
const item = itemsById.get(id);
const ancestors = item && getAncestors(itemsById, item);
for (const ancestor of ancestors ?? []) {
if (!expanded.has(ancestor)) {
expanded.add(ancestor);
hasChanged = true;
}
}
}
}

if (hasChanged) {
state.props.onExpandedChange?.(new Set(expanded));
}
},
{ runNow: true },
),
[table],
);
}
2 changes: 2 additions & 0 deletions src/internalState/useTableState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { calcItems } from './calcItems';
import { calcProps } from './calcProps';
import { cleanupState } from './cleanupState';
import { filterColumns } from './filterColumns';
import { normalizeExpanded } from './normalizeExpanded';
import { syncSelections } from './syncSelections';

export function useTableState<T>(_props: TableProps<T>): Store<InternalTableState<T>> {
Expand Down Expand Up @@ -38,6 +39,7 @@ export function useTableState<T>(_props: TableProps<T>): Store<InternalTableStat
);

filterColumns(state);
normalizeExpanded(state);
calcItems(state);
syncSelections(state);
cleanupState(state);
Expand Down

0 comments on commit 950f089

Please sign in to comment.