Skip to content

Commit

Permalink
Refactor handleMessage to solve: iou90/react-native-autoheight-webvie…
Browse files Browse the repository at this point in the history
  • Loading branch information
idealdev00000 committed Nov 23, 2021
1 parent 25fb7bd commit 0407315
Showing 1 changed file with 32 additions and 23 deletions.
55 changes: 32 additions & 23 deletions autoHeightWebView/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
'use strict';

import React, {useState, useEffect, forwardRef} from 'react';

import {StyleSheet, Platform, ViewPropTypes} from 'react-native';
Expand All @@ -8,7 +6,13 @@ import PropTypes from 'prop-types';

import {WebView} from 'react-native-webview';

import {reduceData, getWidth, isSizeChanged, shouldUpdate} from './utils';
import {
topic,
reduceData,
getWidth,
isSizeChanged,
shouldUpdate,
} from './utils';

const AutoHeightWebView = React.memo(
forwardRef((props, ref) => {
Expand All @@ -24,28 +28,33 @@ const AutoHeightWebView = React.memo(
height: style && style.height ? style.height : 0,
width: getWidth(style),
});

const [scrollable, setScrollable] = useState(false);
const handleMessage = (event) => {
onMessage && onMessage(event);
if (!event.nativeEvent) {
return;
}
let data = {};
// Sometimes the message is invalid JSON, so we ignore that case
try {
data = JSON.parse(event.nativeEvent.data);
} catch (error) {
console.error(error);
return;
if (event.nativeEvent) {
try {
const data = JSON.parse(event.nativeEvent.data);
if (data.topic !== topic) {
onMessage && onMessage(event);
return;
}
const {height, width, zoomedin} = data;
console.log(height);
!scrollEnabled &&
scrollEnabledWithZoomedin &&
setScrollable(!!zoomedin);
const {height: previousHeight, width: previousWidth} = size;
isSizeChanged({height, previousHeight, width, previousWidth}) &&
setSize({
height,
width,
});
} catch (error) {
onMessage && onMessage(event);
}
} else {
onMessage && onMessage(event);
}
const {height, width, zoomedin} = data;
!scrollEnabled && scrollEnabledWithZoomedin && setScrollable(!!zoomedin);
const {height: previousHeight, width: previousWidth} = size;
isSizeChanged({height, previousHeight, width, previousWidth}) &&
setSize({
height,
width,
});
};

const currentScrollEnabled =
Expand Down Expand Up @@ -80,7 +89,7 @@ const AutoHeightWebView = React.memo(
],
injectedJavaScript: script,
source: currentSource,
scrollEnabled: currentScrollEnabled
scrollEnabled: currentScrollEnabled,
});
}),
(prevProps, nextProps) => !shouldUpdate({prevProps, nextProps}),
Expand Down

0 comments on commit 0407315

Please sign in to comment.