Skip to content

Commit

Permalink
feat: Add option to use existing back button to navigate (#24)
Browse files Browse the repository at this point in the history
* feat: Add option to use existing back button to navigate

- Add an option that allows you to set your own back button, e.g. in the nav header and use that to navigate around the network logger
- Handle hardware back press when on details page

* Remove padding when close button is hidden
  • Loading branch information
alexbrazier authored Sep 13, 2020
1 parent 7c21317 commit 054167f
Show file tree
Hide file tree
Showing 7 changed files with 143 additions and 12 deletions.
22 changes: 21 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,20 +91,40 @@ const MyScreen = () => <NetworkLogger theme="dark" />;

### Logging options

#### Max Requests

You can configure the max number of requests stored on the device using by calling `startNetworkLogging` with the `maxRequests` option. The default is `500`.

```ts
startNetworkLogging({ maxRequests: 500 });
```

#### Sorting

Set the sort order of requests. Options are `asc` or `desc`, default is `desc` (most recent at the top).

```ts
```tsx
import NetworkLogger from 'react-native-network-logger';

const MyScreen = () => <NetworkLogger sort="asc" />;
```

#### Integrate with existing navigation

Use your existing back button (e.g. in your navigation header) to navigate within the network logger.

```tsx
import NetworkLogger, { getBackHandler } from 'react-native-network-logger';

const onBack = getBackHandler(navigate.onBack);

const MyScreen = () => (
<Screen onBackPressed={onBack}>
<NetworkLogger />
</Screen>
);
```

## Example App

To test the example app, after cloning the repo, install the required dependencies by running:
Expand Down
42 changes: 38 additions & 4 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ import {
Platform,
View,
Text,
Alert,
TouchableOpacity,
} from 'react-native';
import NetworkLogger, { ThemeName } from 'react-native-network-logger';
import NetworkLogger, {
ThemeName,
getBackHandler,
} from 'react-native-network-logger';

export default function App() {
const formData = new FormData();
Expand Down Expand Up @@ -36,11 +41,27 @@ export default function App() {

const styles = themedStyles(theme === 'dark');

const goBack = () => {
Alert.alert('Going back');
};

const backHandler = getBackHandler(goBack);

return (
<SafeAreaView style={styles.container}>
<Text style={styles.title} accessibilityRole="header">
react-native-network-logger
</Text>
<View style={styles.header}>
<TouchableOpacity
style={styles.navButton}
onPress={backHandler}
hitSlop={{ top: 20, left: 20, bottom: 20, right: 20 }}
>
<Text style={styles.backButtonText}>{'‹'}</Text>
</TouchableOpacity>
<Text style={styles.title} accessibilityRole="header">
react-native-network-logger
</Text>
<View style={styles.navButton} />
</View>
<NetworkLogger theme={theme} />
<View style={styles.bottomView}>
<Button
Expand All @@ -60,7 +81,20 @@ const themedStyles = (dark = false) =>
backgroundColor: dark ? '#2d2a28' : 'white',
paddingTop: Platform.OS === 'android' ? 25 : 0,
},
header: {
flexDirection: 'row',
},
navButton: {
flex: 1,
},
backButtonText: {
color: dark ? 'white' : 'black',
paddingHorizontal: 20,
fontSize: 30,
fontWeight: 'bold',
},
title: {
flex: 5,
color: dark ? 'white' : 'black',
textAlign: 'center',
padding: 10,
Expand Down
41 changes: 41 additions & 0 deletions src/backHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
let appBackHandler: (() => any) | undefined;
let networkLoggerBackHandler: (() => void) | undefined;

export const setBackHandler = (backHandler?: () => void) => {
networkLoggerBackHandler = backHandler;
};

const goBack = () => {
if (networkLoggerBackHandler) {
return networkLoggerBackHandler();
}
appBackHandler?.();
};

export const backHandlerSet = () => {
return !!appBackHandler;
};

/**
* Get a replacement back handler to use instead of your default navigation so you
* can use your existing back button to navigate inside the network logger.
*
* If navigation has occurred in the logger app then pressing your back handler will
* navigate internally. If it is already on the default page then it will call your
* original back handler.
*
* e.g.
*
* const navigation = useNavigation()
*
* const onBack = getBackHandler(navigation.goBack)
*
* <Button onPress={onBack} title="Go back" />
*
* @param backHandler App navigation default back handler
*/
export const getBackHandler = (backHandler: () => any) => {
appBackHandler = backHandler;

return goBack;
};
36 changes: 33 additions & 3 deletions src/components/NetworkLogger.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import React, { useEffect, useState } from 'react';
import { Alert, View, StyleSheet } from 'react-native';
import React, { useEffect, useState, useCallback } from 'react';
import { Alert, View, StyleSheet, BackHandler } from 'react-native';
import logger from '../loggerSingleton';
import NetworkRequestInfo from '../NetworkRequestInfo';
import { ThemeContext, ThemeName } from '../theme';
import RequestList from './RequestList';
import RequestDetails from './RequestDetails';
import { setBackHandler } from '../backHandler';

interface Props {
theme?: ThemeName;
Expand All @@ -23,7 +24,17 @@ const NetworkLogger: React.FC<Props> = ({ theme = 'light', sort = 'desc' }) => {
sortRequests(logger.getRequests(), sort)
);
const [request, setRequest] = useState<NetworkRequestInfo>();
const [showDetails, setShowDetails] = useState(false);
const [showDetails, _setShowDetails] = useState(false);

const setShowDetails = useCallback((shouldShow: boolean) => {
_setShowDetails(shouldShow);

if (shouldShow) {
setBackHandler(() => setShowDetails(false));
} else {
setBackHandler(undefined);
}
}, []);

useEffect(() => {
logger.setCallback((updatedRequests: NetworkRequestInfo[]) => {
Expand All @@ -33,6 +44,25 @@ const NetworkLogger: React.FC<Props> = ({ theme = 'light', sort = 'desc' }) => {
logger.enableXHRInterception();
}, [sort]);

useEffect(() => {
const onBack = () => {
if (showDetails) {
setShowDetails(false);
return true;
}

// Let default back handler take over
return false;
};

const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
onBack
);

return () => backHandler.remove();
}, [showDetails, setShowDetails]);

const showMore = () => {
Alert.alert('More Options', undefined, [
{
Expand Down
9 changes: 6 additions & 3 deletions src/components/RequestDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
} from 'react-native';
import NetworkRequestInfo from '../NetworkRequestInfo';
import { useThemedStyles, Theme } from '../theme';
import { backHandlerSet } from '../backHandler';
import ResultItem from './ResultItem';
import Header from './Header';
import Button from './Button';
Expand Down Expand Up @@ -129,9 +130,11 @@ const RequestDetails: React.FC<Props> = ({ request, onClose }) => {
Share as cURL
</Button>
</ScrollView>
<Button onPress={onClose} style={styles.close}>
Close
</Button>
{!backHandlerSet() && (
<Button onPress={onClose} style={styles.close}>
Close
</Button>
)}
</View>
);
};
Expand Down
3 changes: 2 additions & 1 deletion src/components/ResultItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React from 'react';
import { View, TouchableOpacity, Text, StyleSheet } from 'react-native';
import NetworkRequestInfo from '../NetworkRequestInfo';
import { Theme, useThemedStyles, useTheme } from '../theme';
import { backHandlerSet } from '../backHandler';

interface Props {
request: NetworkRequestInfo;
Expand Down Expand Up @@ -79,7 +80,7 @@ const ResultItem: React.FC<Props> = ({ style, request, onPress }) => {
styles.text,
styles.content,
getUrlTextColor(request.status),
onDetailsPage && styles.paddedUrl,
onDetailsPage && !backHandlerSet() && styles.paddedUrl,
]}
>
{request.url}
Expand Down
2 changes: 2 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@ export const getRequests = () => logger.getRequests();

export const clearRequests = () => logger.clearRequests();

export { getBackHandler } from './backHandler';

export { ThemeName } from './theme';

0 comments on commit 054167f

Please sign in to comment.