Skip to content

feat: More performant re-renders with items store #362

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
4 changes: 4 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ module.exports = {
}
],
'perfectionist/sort-enums': 'off',
'@typescript-eslint/member-ordering': [
'error',
{ default: ['field', 'constructor', 'method', 'signature'] }
],
'@typescript-eslint/naming-convention': [
'error',
{
Expand Down
2 changes: 1 addition & 1 deletion packages/react-native-sortables/.eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ module.exports = {
},
rules: {
'no-relative-import-paths/no-relative-import-paths': 'off',
'import/no-absolute-path': 'error'
'import/no-absolute-path': 'error',
}
};
112 changes: 43 additions & 69 deletions packages/react-native-sortables/src/components/SortableFlex.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { type ReactElement } from 'react';
import { type StyleProp, StyleSheet, type ViewStyle } from 'react-native';
import { useMemo } from 'react';
import { StyleSheet } from 'react-native';
import { useDerivedValue } from 'react-native-reanimated';

import { DEFAULT_SORTABLE_FLEX_PROPS } from '../constants';
import { useDragEndHandler } from '../hooks';
import { useDragEndHandler, useStoreItemsUpdater } from '../hooks';
import {
FLEX_STRATEGIES,
FlexLayoutProvider,
Expand All @@ -12,20 +12,45 @@ import {
useFlexLayoutContext,
useStrategyKey
} from '../providers';
import type { DropIndicatorSettings, SortableFlexProps } from '../types';
import { getPropsWithDefaults, orderItems, validateChildren } from '../utils';
import { DraggableView, SortableContainer } from './shared';
import type { DragEndCallback, SortableFlexProps } from '../types';
import {
childrenToArray,
getPropsWithDefaults,
orderItems,
typedMemo
} from '../utils';
import { SortableContainer } from './shared';

function SortableFlex({
children,
onDragEnd: _onDragEnd,
...rest
}: SortableFlexProps) {
const childrenArray = useMemo(() => childrenToArray(children), [children]);
const itemKeys = useMemo(
() => childrenArray.map(([key]) => key),
[childrenArray]
);

const onDragEnd = useDragEndHandler(_onDragEnd, {
order: params =>
function <I>(data: Array<I>) {
return orderItems(data, itemKeys, params, true);
}
});

useStoreItemsUpdater(itemKeys, childrenArray);

function SortableFlex(props: SortableFlexProps) {
return <SortableFlexInner {...rest} onDragEnd={onDragEnd} />;
}

const SortableFlexInner = typedMemo(function SortableFlexInner(
props: {
onDragEnd: DragEndCallback;
} & Omit<SortableFlexProps, 'children' | 'onDragEnd'>
) {
const {
rest: {
children,
height,
onDragEnd: _onDragEnd,
strategy,
width,
...styleProps
},
rest: { height, onDragEnd, strategy, width, ...styleProps },
sharedProps: {
DropIndicatorComponent,
dimensionsAnimationType,
Expand All @@ -40,9 +65,6 @@ function SortableFlex(props: SortableFlexProps) {
}
} = getPropsWithDefaults(props, DEFAULT_SORTABLE_FLEX_PROPS);

const childrenArray = validateChildren(children);
const itemKeys = childrenArray.map(([key]) => key);

const { flexDirection, flexWrap } = styleProps;
const controlledContainerDimensions = useDerivedValue(() => {
if (flexWrap === 'nowrap') {
Expand All @@ -53,30 +75,21 @@ function SortableFlex(props: SortableFlexProps) {
: { height: false, width: width === undefined };
}, [flexWrap, flexDirection, height, width]);

const onDragEnd = useDragEndHandler(_onDragEnd, {
order: params =>
function <I>(data: Array<I>) {
return orderItems(data, itemKeys, params, true);
}
});

return (
<SharedProvider
{...sharedProps}
controlledContainerDimensions={controlledContainerDimensions}
initialItemsStyleOverride={styles.styleOverride}
itemKeys={itemKeys}
onDragEnd={onDragEnd}>
<FlexLayoutProvider {...styleProps} itemsCount={itemKeys.length}>
<FlexLayoutProvider {...styleProps}>
<OrderUpdaterComponent
key={useStrategyKey(strategy)}
predefinedStrategies={FLEX_STRATEGIES}
strategy={strategy}
triggerOrigin={reorderTriggerOrigin}
useAdditionalValues={useFlexLayoutContext}
/>
<SortableFlexInner
childrenArray={childrenArray}
<SortableContainer
dimensionsAnimationType={dimensionsAnimationType}
DropIndicatorComponent={DropIndicatorComponent}
dropIndicatorStyle={dropIndicatorStyle}
Expand All @@ -96,46 +109,7 @@ function SortableFlex(props: SortableFlexProps) {
</FlexLayoutProvider>
</SharedProvider>
);
}

type SortableFlexInnerProps = {
childrenArray: Array<[string, ReactElement]>;
style: StyleProp<ViewStyle>;
} & DropIndicatorSettings &
Required<
Pick<
SortableFlexProps,
| 'dimensionsAnimationType'
| 'itemEntering'
| 'itemExiting'
| 'itemsLayout'
| 'overflow'
>
>;

function SortableFlexInner({
childrenArray,
itemEntering,
itemExiting,
itemsLayout,
style,
...containerProps
}: SortableFlexInnerProps) {
return (
<SortableContainer {...containerProps} style={style}>
{childrenArray.map(([key, child]) => (
<DraggableView
entering={itemEntering ?? undefined}
exiting={itemExiting ?? undefined}
itemKey={key}
key={key}
layout={itemsLayout ?? undefined}>
{child}
</DraggableView>
))}
</SortableContainer>
);
}
});

const styles = StyleSheet.create({
styleOverride: {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { PropsWithChildren, ReactNode } from 'react';
import { Fragment, memo, useEffect } from 'react';
import type { ReactNode } from 'react';
import { useEffect } from 'react';
import {
LayoutAnimationConfig,
useDerivedValue,
Expand All @@ -9,6 +9,7 @@ import {
import {
CommonValuesContext,
ItemContextProvider,
ItemOutlet,
useCommonValuesContext,
useItemDecorationStyles,
useItemLayoutStyles,
Expand All @@ -22,24 +23,23 @@ import {
type LayoutTransition,
type MeasureCallback
} from '../../../types';
import { getContextProvider } from '../../../utils';
import { getContextProvider, typedMemo } from '../../../utils';
import { SortableHandleInternal } from '../SortableHandle';
import ActiveItemPortal from './ActiveItemPortal';
import ItemCell from './ItemCell';
import TeleportedItemCell from './TeleportedItemCell';

const CommonValuesContextProvider = getContextProvider(CommonValuesContext);

export type DraggableViewProps = PropsWithChildren<{
export type DraggableViewProps = {
itemKey: string;
entering: LayoutAnimation | undefined;
exiting: LayoutAnimation | undefined;
layout: LayoutTransition | undefined;
style?: AnimatedStyleProp;
}>;
};

function DraggableView({
children,
itemKey: key,
style,
...layoutAnimations
Expand Down Expand Up @@ -88,7 +88,7 @@ function DraggableView({
itemsOverridesStyle={itemsOverridesStyle}
onMeasure={onMeasure}>
<LayoutAnimationConfig skipEntering={false} skipExiting={false}>
{children}
<ItemOutlet itemKey={key} />
</LayoutAnimationConfig>
</ItemCell>
);
Expand Down Expand Up @@ -130,23 +130,23 @@ function DraggableView({
itemsOverridesStyle={itemsOverridesStyle}
teleportedItemId={teleportedItemId}
onMeasure={onMeasureItem}>
{children}
<ItemOutlet itemKey={key} />
</TeleportedItemCell>
</CommonValuesContextProvider>
);

return (
<Fragment>
<>
{renderItemCell(onMeasureItem)}
<ActiveItemPortal
activationAnimationProgress={activationAnimationProgress}
portalState={portalState}
renderTeleportedItemCell={renderTeleportedItemCell}
teleportedItemId={teleportedItemId}>
{children}
<ItemOutlet itemKey={key} />
</ActiveItemPortal>
</Fragment>
</>
);
}

export default memo(DraggableView);
export default typedMemo(DraggableView);
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { ComponentType } from 'react';
import { memo } from 'react';
import type { ViewStyle } from 'react-native';
import { StyleSheet } from 'react-native';
import type { SharedValue } from 'react-native-reanimated';
Expand All @@ -18,6 +17,7 @@ import type {
DropIndicatorComponentProps,
Vector
} from '../../types';
import { typedMemo } from '../../utils';

const DEFAULT_STYLE: ViewStyle = {
opacity: 0
Expand Down Expand Up @@ -118,4 +118,4 @@ const styles = StyleSheet.create({
}
});

export default memo(DropIndicator);
export default typedMemo(DropIndicator);
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { PropsWithChildren } from 'react';
import { type PropsWithChildren } from 'react';
import {
Dimensions,
type StyleProp,
Expand All @@ -20,9 +20,11 @@ import {
import type {
DimensionsAnimation,
DropIndicatorSettings,
ItemLayoutAnimationSettings,
Overflow
} from '../../types';
import { AbsoluteLayoutState } from '../../types';
import { typedMemo } from '../../utils';
import AnimatedOnLayoutView from './AnimatedOnLayoutView';
import DropIndicator from './DropIndicator';

Expand All @@ -33,10 +35,11 @@ type AnimatedHeightContainerProps = PropsWithChildren<
dimensionsAnimationType: DimensionsAnimation;
overflow: Overflow;
style?: StyleProp<ViewStyle>;
} & DropIndicatorSettings
} & DropIndicatorSettings &
Omit<ItemLayoutAnimationSettings, 'itemsLayoutTransitionMode'>
>;

export default function SortableContainer({
function SortableContainer({
DropIndicatorComponent,
children,
dimensionsAnimationType,
Expand Down Expand Up @@ -144,3 +147,5 @@ export default function SortableContainer({
</Animated.View>
);
}

export default typedMemo(SortableContainer);
2 changes: 1 addition & 1 deletion packages/react-native-sortables/src/constants/props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type OptionalSharedProps =
| 'scrollableRef'
| keyof Omit<SortableCallbacks, 'onDragEnd'>;

type DefaultSharedProps = DefaultProps<SharedProps, OptionalSharedProps>;
export type DefaultSharedProps = DefaultProps<SharedProps, OptionalSharedProps>;

export const DEFAULT_SHARED_PROPS = {
DropIndicatorComponent: DefaultDropIndicator,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { memo, useCallback, useState } from 'react';
import { useCallback, useState } from 'react';
import type { SharedValue } from 'react-native-reanimated';

import type {
Expand All @@ -8,10 +8,11 @@ import type {
DebugViews
} from '../../types/debug';
import { DebugComponentType } from '../../types/debug';
import { typedMemo } from '../../utils';
import { DebugCross, DebugLine, DebugRect } from '../components';
import { useDebugContext } from './DebugProvider';

const DebugOutlet = memo(function DebugOutlet() {
const DebugOutlet = typedMemo(function DebugOutlet() {
const [debugViews, setDebugViews] = useState<DebugViews>({});
const { useObserver } = useDebugContext() ?? {};

Expand Down
1 change: 1 addition & 0 deletions packages/react-native-sortables/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export * from './callbacks';
export * from './handlers';
export * from './reanimated';
export { default as useHaptics } from './useHaptics';
export { default as useStoreItemsUpdater } from './useStoreItemsUpdater';
export { default as useWarnOnPropChange } from './useWarnOnPropChange';
22 changes: 22 additions & 0 deletions packages/react-native-sortables/src/hooks/useStoreItemsUpdater.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/* eslint-disable import/no-unused-modules */
import { useRef } from 'react';

export default function useStoreItemsUpdater<I>(
keys: Array<string>,
items: Array<I>
) {
const prevKeysRef = useRef<Array<string>>([]);

childrenArray.forEach(([key, child]) => {
store.set(key, child);
});
store.set('itemKeys', itemKeys);
store.set('itemCount', itemKeys.length);

useEffect(() => {
if (areArraysDifferent(itemKeys, prevKeysRef.current)) {
indexToKey.value = itemKeys;
prevKeysRef.current = itemKeys;
}
}, [itemKeys, indexToKey]);
}
Loading
Loading