Skip to content

Create an imperative API for TabController for setting tab imperatively #2197

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

Merged
merged 2 commits into from
Aug 22, 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
23 changes: 19 additions & 4 deletions demo/src/screens/componentScreens/TabControllerScreen/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import React, {Component} from 'react';
import {ActivityIndicator, StyleSheet} from 'react-native';
import {Assets, TabController, Colors, View, Text, Button, TabControllerItemProps} from 'react-native-ui-lib';
import {
Assets,
TabController,
Colors,
View,
Text,
Button,
TabControllerItemProps,
TabControllerImperativeMethods
} from 'react-native-ui-lib';
import {gestureHandlerRootHOC} from 'react-native-gesture-handler';
import _ from 'lodash';

Expand Down Expand Up @@ -35,6 +44,7 @@ class TabControllerScreen extends Component<{}, State> {

this.state.items = this.generateTabItems();
}
tabController = React.createRef<TabControllerImperativeMethods>();

generateTabItems = (fewItems = this.state.fewItems): TabControllerItemProps[] => {
const items: TabControllerItemProps[] = _.flow(tabs => _.take(tabs, fewItems ? 3 : TABS.length),
Expand Down Expand Up @@ -73,6 +83,10 @@ class TabControllerScreen extends Component<{}, State> {
}, 10);
}

setTab = () => {
this.tabController.current?.setTab(2);
};

onAddItem = () => {
const {items} = this.state;
let newItems = items.slice(0, -1) as TabControllerItemProps[];
Expand Down Expand Up @@ -153,6 +167,7 @@ class TabControllerScreen extends Component<{}, State> {
<View flex bg-$backgroundDefault>
<TabController
key={key}
ref={this.tabController}
asCarousel={asCarousel}
// selectedIndex={selectedIndex}
initialIndex={initialIndex}
Expand All @@ -176,9 +191,7 @@ class TabControllerScreen extends Component<{}, State> {
enableShadow
activeBackgroundColor={Colors.$backgroundPrimaryMedium}
centerSelected={centerSelected}
>
{/* {this.renderTabItems()} */}
</TabController.TabBar>
/>
{this.renderTabPages()}
</TabController>
<View absB left margin-20 marginB-100 style={{zIndex: 1}}>
Expand All @@ -203,8 +216,10 @@ class TabControllerScreen extends Component<{}, State> {
bg-green30={centerSelected}
label={`centerSelected : ${centerSelected ? 'ON' : 'OFF'}`}
size={Button.sizes.small}
marginB-12
onPress={this.toggleCenterSelected}
/>
<Button label="setTab (Imperative)" bg-green10 onPress={this.setTab} size={Button.sizes.small}/>
</View>
</View>
);
Expand Down
62 changes: 40 additions & 22 deletions src/components/tabController/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,26 @@
import React, {PropsWithChildren, useMemo, useEffect, useState, useCallback} from 'react';
import _ from 'lodash';
import {useAnimatedReaction, useSharedValue, withTiming, runOnJS} from 'react-native-reanimated';
import {useOrientation} from '../../hooks';
import {Constants, asBaseComponent} from '../../commons/new';
import {useOrientation, useThemeProps} from '../../hooks';
import {Constants} from '../../commons/new';
import {LogService} from '../../services';
import TabBarContext from './TabBarContext';
import TabBar from './TabBar';
import TabBarItem, {TabControllerItemProps} from './TabBarItem';
import TabPage from './TabPage';
import PageCarousel from './PageCarousel';
export {TabControllerItemProps};
import useImperativeTabControllerHandle, {TabControllerImperativeMethods} from './useImperativeTabControllerHandle';
export {TabControllerItemProps, TabControllerImperativeMethods};

// TODO: should migrate selectedIndex to initialIndex (and make this prop uncontrolled)

interface TabControllerStatics {
TabBar: typeof TabBar;
TabBarItem: typeof TabBarItem;
TabPage: typeof TabPage;
PageCarousel: typeof PageCarousel;
}

export interface TabControllerProps {
/**
* The list of tab bar items
Expand Down Expand Up @@ -56,16 +65,18 @@ const getScreenWidth = (useSafeArea: boolean) => {
* @important: On Android, if using react-native-navigation, make sure to wrap your screen with gestureHandlerRootHOC
* @importantLink: https://kmagiera.github.io/react-native-gesture-handler/docs/getting-started.html#with-wix-react-native-navigation-https-githubcom-wix-react-native-navigation
*/
function TabController({
initialIndex = 0,
selectedIndex,
asCarousel = false,
items,
onChangeIndex = _.noop,
carouselPageWidth,
useSafeArea = false,
children
}: PropsWithChildren<TabControllerProps>) {
const TabController = React.forwardRef((props: PropsWithChildren<TabControllerProps>, ref: React.Ref<any>) => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think this can resolve the bottom ignores, you decide if it's better:

// @ts-expect-error
const TabController: ForwardRefExoticComponent<
  PropsWithoutRef<TabControllerProps> & RefAttributes<TabControllerImperativeMethods>
// eslint-disable-next-line max-len
> & TabControllerStatics = React.forwardRef((props: PropsWithChildren<TabControllerProps>, ref: React.Ref<TabControllerImperativeMethods>) => {

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It doesn't solve the bottom ignores

Copy link
Collaborator

Choose a reason for hiding this comment

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

Strange, it does for me. let me know if you want to look at this together

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Maybe I did something wrong or misunderstood..
Do you want to create a (separate) PR with what u meant?

Copy link
Collaborator

Choose a reason for hiding this comment

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

It works for me, but I think it breaks the props, so forget about it

const themeProps = useThemeProps(props, 'TabController');
const {
initialIndex = 0,
selectedIndex,
asCarousel = false,
items,
onChangeIndex = _.noop,
carouselPageWidth,
useSafeArea = false,
children
} = themeProps;
const [screenWidth, setScreenWidth] = useState<number>(getScreenWidth(useSafeArea));

if (items?.length < 2) {
Expand All @@ -87,12 +98,12 @@ function TabController({
}, [items]);

/* backwards compatibility for `selectedIndex` prop. this line eventually should be removed */
initialIndex = selectedIndex || initialIndex;
const _initialIndex = selectedIndex || initialIndex;

/* currentPage - static page index */
const currentPage = useSharedValue(initialIndex);
const currentPage = useSharedValue(_initialIndex);
/* targetPage - transitioned page index (can be a fraction when transitioning between pages) */
const targetPage = useSharedValue(initialIndex);
const targetPage = useSharedValue(_initialIndex);
// const carouselOffset = useSharedValue(initialIndex * Math.round(pageWidth));

const setCurrentIndex = useCallback((index: number) => {
Expand All @@ -107,8 +118,8 @@ function TabController({
}, [selectedIndex]);

useEffect(() => {
setCurrentIndex(initialIndex);
}, [initialIndex]);
setCurrentIndex(_initialIndex);
}, [_initialIndex]);

useAnimatedReaction(() => {
return currentPage.value;
Expand All @@ -120,10 +131,12 @@ function TabController({
}
});

useImperativeTabControllerHandle(ref, setCurrentIndex);

const context = useMemo(() => {
return {
/* Pass Props */
initialIndex,
initialIndex: _initialIndex,
asCarousel,
pageWidth,
/* Items */
Expand All @@ -139,13 +152,18 @@ function TabController({
onChangeIndex,
setCurrentIndex
};
}, [initialIndex, asCarousel, items, onChangeIndex, screenWidth]);
}, [_initialIndex, asCarousel, items, onChangeIndex, screenWidth]);

return <TabBarContext.Provider value={context}>{children}</TabBarContext.Provider>;
}
});

// @ts-expect-error
TabController.TabBar = TabBar;
// @ts-expect-error
TabController.TabBarItem = TabBarItem;
// @ts-expect-error
TabController.TabPage = TabPage;
// @ts-expect-error
TabController.PageCarousel = PageCarousel;
export default asBaseComponent<TabControllerProps, typeof TabController>(TabController);

export default TabController as typeof TabController & TabControllerStatics;
16 changes: 16 additions & 0 deletions src/components/tabController/useImperativeTabControllerHandle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import React, {useImperativeHandle} from 'react';

export interface TabControllerImperativeMethods {
setTab: (index: number) => void;
}

const useImperativeTabControllerHandle = (ref: React.Ref<TabControllerImperativeMethods>,
setCurrentIndex: (index: number) => void) => {
useImperativeHandle(ref, () => {
return {
setTab: (tabIndex: number) => setCurrentIndex(tabIndex)
};
});
};

export default useImperativeTabControllerHandle;
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export {default as StackAggregator, StackAggregatorProps} from './components/sta
export {default as StateScreen, StateScreenProps} from './components/stateScreen';
export {default as Stepper, StepperProps} from './components/stepper';
export {default as Switch, SwitchProps} from './components/switch';
export {default as TabController, TabControllerProps, TabControllerItemProps} from './components/tabController';
export {default as TabController, TabControllerProps, TabControllerItemProps, TabControllerImperativeMethods} from './components/tabController';
export {default as TabBar, TabBarProps} from './components/tabBar'; //TODO: remove on V7
export {default as Timeline, TimelineProps, TimelinePointProps, TimelineLineProps, TimelineStateTypes, TimelinePointTypes, TimelineLineTypes} from './components/timeline';
export {default as Text, TextProps} from './components/text';
Expand Down