Best JavaScript code snippet using root
TripCard.js
Source:TripCard.js
1/**2 * @file3 * Trip card component used in listing4 *5 * @format6 * @flow strict-local7 */8import React, { useCallback } from 'react';9import { View } from 'react-native';10import _ from 'lodash';11import { Surface, TouchableRipple } from 'react-native-paper';12import { useAsyncCallback } from 'react-async-hook';13import styled from '@emotion/native';14import { useNavigation } from '@react-navigation/native';15import app, { getUid } from '@appFirebase';16import { Box, Spacer } from '@appComponents/ScreenLayout';17import Button from '@appComponents/Button';18import Text from '@appComponents/Text';19import { Icon, useTheme } from '@appComponents/theme';20import tripConverter, {21 TripState,22 Trip,23 UserRole,24 PilotState,25 OwnerState,26} from '@appUtils/tripConverter';27import { useMyData } from '@appUtils/api';28import { DateView, TimeView } from '@appComponents/DateTimeField/DateView';29import VerticalProgressTracker from './VerticalProgressTracker';30import { AircraftDetails, Label, SecondaryButton, Status } from './TripData';31import { notifyManagers } from '@appUtils/CloudFunctions';32type TripCardProps = {33 trip: Trip,34 showMessagesButton?: boolean,35};36const TripCard = ({ trip, showMessagesButton }: TripCardProps) => {37 const [user] = useMyData();38 if (user?.role === UserRole.PILOT) {39 return <PilotCard trip={trip} />;40 }41 return <OwnerCard trip={trip} showMessagesButton={showMessagesButton} />;42};43const PilotCard = ({ trip }: TripCardProps) => {44 const navigation = useNavigation();45 const pilot = trip.pilots.find(p => p.id === getUid());46 const hasPendingActions =47 pilot?.state === PilotState.MANAGER_REQUESTED ||48 pilot?.state === PilotState.PILOT_REJECTED;49 const openTrip = useCallback(50 () => navigation.navigate('Trip Review', { documentPath: trip.path }),51 [navigation, trip.path],52 );53 return (54 <TripCardContainer>55 <TouchableRipple onPress={openTrip}>56 <Box ph={3} pv={2}>57 {!hasPendingActions && <Status trip={trip} />}58 <Title trip={trip} />59 <RequestDetails trip={trip} pilot={pilot} />60 <MessagesButton />61 <Spacer size={2} />62 </Box>63 </TouchableRipple>64 {hasPendingActions && <NewTripPilotActions trip={trip} pilot={pilot} />}65 </TripCardContainer>66 );67};68const OwnerCard = ({ trip, showMessagesButton }) => {69 const navigation = useNavigation();70 const hasPendingActions =71 trip.owner?.state === OwnerState.MANAGER_REQUESTED ||72 trip.owner?.state === OwnerState.OWNER_REJECTED;73 const openTrip = useCallback(() => {74 const screen =75 trip.state === TripState.OWNER_DRAFT ? 'Trip Builder' : 'Trip Review';76 navigation.navigate(screen, { documentPath: trip.path });77 }, [navigation, trip.path, trip.state]);78 return (79 <TripCardContainer>80 <TouchableRipple onPress={openTrip}>81 <Box ph={2} pv={2}>82 <TopSection trip={trip} />83 <TripDeparture date={_.head(trip.legs)?.departureDate} />84 <Spacer size={2} />85 {!hasPendingActions && <Status trip={trip} />}86 {showMessagesButton && <MessagesButton />}87 </Box>88 </TouchableRipple>89 {hasPendingActions && <NewTripOwnerActions trip={trip} />}90 </TripCardContainer>91 );92};93const NewTripOwnerActions = ({ trip }) => {94 const isRejected = trip.owner.state === OwnerState.OWNER_REJECTED;95 const updateState = useUpdateOwnerStateCallback(trip);96 return (97 <CardActionsWrap>98 <CardAction99 onPress={() => updateState(OwnerState.OWNER_REJECTED)}100 title={isRejected ? 'Rejected' : 'Reject'}101 error={isRejected}102 />103 <CardAction104 bl105 title="Accept"106 onPress={() => updateState(OwnerState.OWNER_ACCEPTED)}107 />108 </CardActionsWrap>109 );110};111const NewTripPilotActions = ({ trip, pilot }) => {112 const isRejected = pilot.state === PilotState.PILOT_REJECTED;113 const updateState = useUpdatePilotStateCallback({ trip, pilot });114 return (115 <CardActionsWrap>116 <CardAction117 onPress={() => {118 updateState(PilotState.PILOT_REJECTED);119 notifyManagers({120 messageBody: getPilotResponseNotificationBody(121 pilot,122 trip.identifier,123 'rejected',124 ),125 });126 }}127 title={isRejected ? 'Rejected' : 'Reject'}128 error={isRejected}129 />130 <CardAction131 bl132 title="Accept"133 onPress={() => {134 updateState(PilotState.PILOT_ACCEPTED);135 notifyManagers({136 messageBody: getPilotResponseNotificationBody(137 pilot,138 trip.identifier,139 'accepted',140 ),141 });142 }}143 />144 </CardActionsWrap>145 );146};147const RequestDetails = ({ trip, pilot }) => {148 const [user] = useMyData();149 const role = trip.pilots[0].id === pilot.id ? 'pilot' : 'second';150 const manager = user?.managementCompany?.name || 'Your Management Company';151 const date = <DateView date={_.head(trip.legs)?.departureDate} fallback="" />;152 return (153 <Box pb={1}>154 <Text weight="700" lh={22}>155 Request from {manager}156 </Text>157 <Box pl={1}>158 <Text lh={20}>159 {manager} has invited you to be {role} in command on a flight on{' '}160 {date}.161 </Text>162 </Box>163 </Box>164 );165};166const TopSection = ({ trip }) => {167 const finishedTrip =168 _.includes([TripState.ENDED, TripState.CANCELLED], trip.state) ||169 trip.archived;170 const highlightedCurrentLocation = _.includes(171 [TripState.UPCOMING, TripState.ACTIVE],172 trip.state,173 );174 const currentLocationIndex = highlightedCurrentLocation ? 0 : -1;175 return (176 <TopSectionWrapper>177 <Box flex={1} pr={2}>178 <Title trip={trip} />179 <AircraftDetails aircraft={trip.aircraft} />180 </Box>181 <VerticalProgressTracker182 legs={trip.legs}183 currentIndex={currentLocationIndex}184 finished={finishedTrip}185 />186 </TopSectionWrapper>187 );188};189const Title = ({ trip }: { trip: Trip }) => {190 const text = trip.customName191 ? `${trip.identifier} - ${trip.customName}`192 : trip.identifier;193 return (194 <TitleWrap>195 <StyledIcon name="mobile-aircraft" color="white" />196 <Text color="legLabel" weight="700">197 {text}198 </Text>199 </TitleWrap>200 );201};202const TripDeparture = ({ date }) => {203 return (204 <Box>205 <Label>TRIP DEPARTURE</Label>206 <Text size="small" weight="400" lh={24}>207 <TimeView date={date} fallback="-" />{' '}208 <DateView date={date} fallback="" />209 </Text>210 </Box>211 );212};213const MessagesButton = () => {214 const theme = useTheme();215 return (216 <>217 <Spacer size={3} />218 <SecondaryButton219 padding={1}220 icon="mobile-messages"221 color="disabled"222 stroke={theme.colors.disabled}>223 MESSAGES224 </SecondaryButton>225 </>226 );227};228const CardAction = ({ onPress, bl, title, error }) => {229 const theme = useTheme();230 const color = error ? theme.colors.error : theme.colors.text;231 const action = useAsyncCallback(onPress);232 return (233 <CardActionButtonWrap234 labelStyle={{ color }}235 mode="text"236 onPress={action.execute}237 loading={action.loading}238 disabled={error}239 bl={bl}>240 {title}241 </CardActionButtonWrap>242 );243};244const useUpdatePilotStateCallback = ({ trip, pilot }) =>245 useCallback(246 state =>247 updateTrip(trip.path, {248 pilots: trip.pilots.map(p => ({249 ...p,250 state: pilot.id === p.id ? state : p.state,251 })),252 }),253 [pilot.id, trip.path, trip.pilots],254 );255const useUpdateOwnerStateCallback = trip =>256 useCallback(257 state => updateTrip(trip.path, { owner: { ...trip.owner, state } }),258 [trip.owner, trip.path],259 );260const updateTrip = (docPath, updates) =>261 app.firestore().doc(docPath).update(tripConverter.toFirestore(updates));262const TripCardContainer = styled(Surface)(({ theme, padding = 0 }) => ({263 flexDirection: 'column',264 width: 344,265 backgroundColor: theme.colors.tripCardBackground,266 padding: theme.layout.space(padding),267}));268const TopSectionWrapper = styled(View)`269 flex-direction: row;270 justify-content: space-between;271`;272export const getPilotResponseNotificationBody = (273 pilot,274 tripIdentifier,275 response,276) => {277 const pilotName = `${pilot.firstName} ${pilot.lastName}`;278 return `${pilotName} has ${response} ${tripIdentifier}.`;279};280const TitleWrap = styled(View)(({ theme }) => ({281 flexDirection: 'row',282 alignItems: 'center',283 alignSelf: 'flex-start',284 marginLeft: theme.layout.space(0.5),285 marginVertical: theme.layout.space(1.25),286}));287const CardActionsWrap = styled.View(({ theme }) => ({288 flex: 1,289 height: 72,290 flexDirection: 'row',291 borderTopWidth: 0.4,292 borderColor: theme.colors.text,293}));294const CardActionButtonWrap = styled(Button)(({ theme, bl }) => ({295 flex: 1,296 height: '100%',297 borderColor: theme.colors.text,298 borderRadius: 0,299 borderLeftWidth: bl ? 0.4 : 0,300 justifyContent: 'center',301}));302const StyledIcon = styled(Icon)`303 margin-right: 8px;304`;...
top-bar.js
Source:top-bar.js
1import React, { PureComponent } from 'react';2import PropTypes from 'prop-types';3import { connect } from 'react-redux';4import { withRouter } from 'react-router';5import { Route, Switch } from 'react-router-dom';6import { injectIntl } from 'react-intl';7import classNames from 'classnames';8import { DashboardTopBar, ProfilePageTopBar, TopBarRight } from '../';9import { showNotificationsPanel, showTransactionsLog, toggleAethWallet,10 toggleEthWallet, toggleGuestModal } from '../../local-flux/actions/app-actions';11import { selectBalance, selectEntryFlag, selectFullEntry, selectLoggedProfile,12 selectLoggedProfileData, selectNotificationsPanel, selectPublishingActions, selectShowWallet,13 selectTransactionsLog, selectUnreadNotifications, selectCyclingStates } from '../../local-flux/selectors';14class TopBar extends PureComponent {15 _renderComponent = (Component, injectedProps) =>16 props => <Component {...injectedProps} {...props} />;17 render () {18 const { balance, cyclingStates, fullEntry, hasPendingActions, notificationsLoaded,19 notificationsPanelOpen, showSecondarySidebar, showWallet, transactionsLogOpen,20 unreadNotifications, unlocked } = this.props;21 const className = classNames('flex-center-y top-bar', {22 'top-bar_full': !showSecondarySidebar || fullEntry,23 'top-bar_default': !fullEntry24 });25 return (26 <div className={className}>27 <div className="top-bar__left-side">28 <Switch>29 <Route30 component={DashboardTopBar}31 path="/dashboard/:dashboardId?"32 />33 <Route exact path="/0x:ethAddress" component={ProfilePageTopBar} />34 </Switch>35 </div>36 <TopBarRight37 balance={balance}38 cyclingStates={cyclingStates}39 hasPendingActions={hasPendingActions}40 notificationsLoaded={notificationsLoaded}41 notificationsPanelOpen={notificationsPanelOpen}42 showNotificationsPanel={this.props.showNotificationsPanel}43 showTransactionsLog={this.props.showTransactionsLog}44 showWallet={showWallet}45 toggleAethWallet={this.props.toggleAethWallet}46 toggleEthWallet={this.props.toggleEthWallet}47 toggleGuestModal={this.props.toggleGuestModal}48 transactionsLogOpen={transactionsLogOpen}49 unreadNotifications={unreadNotifications}50 unlocked={unlocked}51 />52 </div>53 );54 }55}56TopBar.propTypes = {57 balance: PropTypes.shape().isRequired,58 cyclingStates: PropTypes.shape().isRequired,59 fullEntry: PropTypes.bool,60 hasPendingActions: PropTypes.bool,61 history: PropTypes.shape(),62 loggedProfile: PropTypes.shape(),63 loggedProfileData: PropTypes.shape(),64 notificationsLoaded: PropTypes.bool,65 notificationsPanelOpen: PropTypes.bool,66 showNotificationsPanel: PropTypes.func.isRequired,67 showSecondarySidebar: PropTypes.bool,68 showTransactionsLog: PropTypes.func.isRequired,69 showWallet: PropTypes.string,70 toggleAethWallet: PropTypes.func.isRequired,71 toggleEthWallet: PropTypes.func.isRequired,72 toggleGuestModal: PropTypes.func.isRequired,73 transactionsLogOpen: PropTypes.bool,74 unreadNotifications: PropTypes.number.isRequired,75 unlocked: PropTypes.bool76};77const mapStateToProps = state => ({78 balance: selectBalance(state),79 cyclingStates: selectCyclingStates(state),80 fullEntry: !!selectFullEntry(state) || !!selectEntryFlag(state, 'fetchingFullEntry'),81 hasPendingActions: !!selectPublishingActions(state).size,82 loggedProfile: selectLoggedProfile(state),83 loggedProfileData: selectLoggedProfileData(state),84 notificationsLoaded: state.notificationsState.get('notificationsLoaded'),85 notificationsPanelOpen: selectNotificationsPanel(state),86 showWallet: selectShowWallet(state),87 transactionsLogOpen: selectTransactionsLog(state),88 unreadNotifications: selectUnreadNotifications(state)89});90export default connect(91 mapStateToProps,92 {93 showNotificationsPanel,94 showTransactionsLog,95 toggleAethWallet,96 toggleEthWallet,97 toggleGuestModal98 },99 null,100 { pure: false }...
loadingHook.js
Source:loadingHook.js
1import React, { useState, useEffect } from 'react';2import { useSelector } from 'react-redux';3export function useLoadingStatus(actions=[]) {4 const [isLoading, setIsLoading] = useState(false);5 const loadingStates = useSelector((state)=>(state.loading));6 useEffect(() => {7 let hasPendingActions = false8 for (var action of actions) {9 const [, requestBaseName, ] = /(.*)_(REQUEST|SUCCESS|ERROR)/.exec(action.type);10 if(loadingStates[requestBaseName]){11 hasPendingActions =true;12 break;13 }14 }15 if(hasPendingActions){16 setIsLoading(true);17 }else{18 setIsLoading(false);19 }20 });21 return isLoading;...
Using AI Code Generation
1const rootStore = getRoot(this);2const hasPendingActions = rootStore.hasPendingActions;3console.log(hasPendingActions);4const childStore = this;5const hasPendingActions = childStore.hasPendingActions;6console.log(hasPendingActions);7const grandChildStore = this;8const hasPendingActions = grandChildStore.hasPendingActions;9console.log(hasPendingActions);10const grandChildStore = this;11const hasPendingActions = grandChildStore.hasPendingActions;12console.log(hasPendingActions);13const grandChildStore = this;14const hasPendingActions = grandChildStore.hasPendingActions;15console.log(hasPendingActions);16const grandChildStore = this;17const hasPendingActions = grandChildStore.hasPendingActions;18console.log(hasPendingActions);19const grandChildStore = this;20const hasPendingActions = grandChildStore.hasPendingActions;21console.log(hasPendingActions);22const grandChildStore = this;23const hasPendingActions = grandChildStore.hasPendingActions;24console.log(hasPendingActions);25const grandChildStore = this;26const hasPendingActions = grandChildStore.hasPendingActions;27console.log(hasPendingActions);28const grandChildStore = this;29const hasPendingActions = grandChildStore.hasPendingActions;30console.log(hasPendingActions);31const grandChildStore = this;32const hasPendingActions = grandChildStore.hasPendingActions;33console.log(hasPendingActions);34const grandChildStore = this;35const hasPendingActions = grandChildStore.hasPendingActions;36console.log(hasPendingActions);37const grandChildStore = this;38const hasPendingActions = grandChildStore.hasPendingActions;39console.log(hasPendingActions);
Using AI Code Generation
1import { hasPendingActions } from 'mobx-state-tree'2import { RootStore } from './RootStore'3const rootStore = RootStore.create({})4test('hasPendingActions', () => {5 expect(hasPendingActions(rootStore)).toBe(false)6})7import { types } from 'mobx-state-tree'8import { UserStore } from './UserStore'9 .model('RootStore', {10 })11 .actions(self => ({12 afterCreate() {13 self.userStore.loadUsers()14 },15 }))16import { types } from 'mobx-state-tree'17import { User } from './User'18 .model('UserStore', {19 users: types.array(User),20 })21 .actions(self => ({22 loadUsers() {23 self.users.replace([{ id: 1, name: 'test' }])24 },25 }))26import { types } from 'mobx-state-tree'27 .model('User', {28 id: types.identifier(types.number),29 })30 .actions(self => ({31 afterCreate() {32 console.log('afterCreate')33 },34 }))
Using AI Code Generation
1class Test extends React.Component {2 constructor(props) {3 super(props);4 this.rootStore = this.props.rootStore;5 }6 componentDidMount() {7 if (this.rootStore.hasPendingActions) {8 }9 }10 render() {11 return <div>Test</div>;12 }13}14export default inject("rootStore")(observer(Test));
Using AI Code Generation
1const rootStore = new RootStore();2 inputProps={{3 }}4 onChange={this.handlePhoneChange}5 value={this.state.phone}6handlePhoneChange = (phone, country, e, formattedValue) => {7 this.setState({ phone: formattedValue });8};9handlePhoneChange = (phone, country, e, formattedValue) => {10 this.setState({ phone: formattedValue });11};12const { phone } = this.state;13console.log(phone);14const { phone } = this.state;15console.log(phone);16 inputProps={{17 }}18 onChange={this.handlePhoneChange}19 value={this.state.phone}20handlePhoneChange = (phone, country, e, formattedValue) =>
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!