This commit is contained in:
Yamozha
2021-04-02 02:24:13 +03:00
parent c23950b545
commit 7256d79e2c
31493 changed files with 3036630 additions and 0 deletions

View File

@ -0,0 +1,32 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
const React = require('react');
const View = require('../Components/View/View');
class BorderBox extends React.Component<$FlowFixMeProps> {
render(): $FlowFixMe | React.Node {
const box = this.props.box;
if (!box) {
return this.props.children;
}
const style = {
borderTopWidth: box.top,
borderBottomWidth: box.bottom,
borderLeftWidth: box.left,
borderRightWidth: box.right,
};
return <View style={[style, this.props.style]}>{this.props.children}</View>;
}
}
module.exports = BorderBox;

View File

@ -0,0 +1,110 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
const React = require('react');
const StyleSheet = require('../StyleSheet/StyleSheet');
const Text = require('../Text/Text');
const View = require('../Components/View/View');
const resolveBoxStyle = require('./resolveBoxStyle');
const blank = {
top: 0,
left: 0,
right: 0,
bottom: 0,
};
class BoxInspector extends React.Component<$FlowFixMeProps> {
render(): React.Node {
const frame = this.props.frame;
const style = this.props.style;
const margin = (style && resolveBoxStyle('margin', style)) || blank;
const padding = (style && resolveBoxStyle('padding', style)) || blank;
return (
<BoxContainer title="margin" titleStyle={styles.marginLabel} box={margin}>
<BoxContainer title="padding" box={padding}>
<View>
<Text style={styles.innerText}>
({(frame.left || 0).toFixed(1)}, {(frame.top || 0).toFixed(1)})
</Text>
<Text style={styles.innerText}>
{(frame.width || 0).toFixed(1)} &times;{' '}
{(frame.height || 0).toFixed(1)}
</Text>
</View>
</BoxContainer>
</BoxContainer>
);
}
}
class BoxContainer extends React.Component<$FlowFixMeProps> {
render() {
const box = this.props.box;
return (
<View style={styles.box}>
<View style={styles.row}>
{}
<Text style={[this.props.titleStyle, styles.label]}>
{this.props.title}
</Text>
<Text style={styles.boxText}>{box.top}</Text>
</View>
<View style={styles.row}>
<Text style={styles.boxText}>{box.left}</Text>
{this.props.children}
<Text style={styles.boxText}>{box.right}</Text>
</View>
<Text style={styles.boxText}>{box.bottom}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
},
marginLabel: {
width: 60,
},
label: {
fontSize: 10,
color: 'rgb(255,100,0)',
marginLeft: 5,
flex: 1,
textAlign: 'left',
top: -3,
},
innerText: {
color: 'yellow',
fontSize: 12,
textAlign: 'center',
width: 70,
},
box: {
borderWidth: 1,
borderColor: 'grey',
},
boxText: {
color: 'white',
fontSize: 12,
marginHorizontal: 3,
marginVertical: 2,
textAlign: 'center',
},
});
module.exports = BoxInspector;

View File

@ -0,0 +1,138 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
const BorderBox = require('./BorderBox');
const Dimensions = require('../Utilities/Dimensions');
const React = require('react');
const StyleSheet = require('../StyleSheet/StyleSheet');
const View = require('../Components/View/View');
const flattenStyle = require('../StyleSheet/flattenStyle');
const resolveBoxStyle = require('./resolveBoxStyle');
class ElementBox extends React.Component<$FlowFixMeProps> {
render(): React.Node {
const style = flattenStyle(this.props.style) || {};
let margin = resolveBoxStyle('margin', style);
let padding = resolveBoxStyle('padding', style);
const frameStyle = {...this.props.frame};
const contentStyle = {
width: this.props.frame.width,
height: this.props.frame.height,
};
if (margin != null) {
margin = resolveRelativeSizes(margin);
frameStyle.top -= margin.top;
frameStyle.left -= margin.left;
frameStyle.height += margin.top + margin.bottom;
frameStyle.width += margin.left + margin.right;
if (margin.top < 0) {
contentStyle.height += margin.top;
}
if (margin.bottom < 0) {
contentStyle.height += margin.bottom;
}
if (margin.left < 0) {
contentStyle.width += margin.left;
}
if (margin.right < 0) {
contentStyle.width += margin.right;
}
}
if (padding != null) {
padding = resolveRelativeSizes(padding);
contentStyle.width -= padding.left + padding.right;
contentStyle.height -= padding.top + padding.bottom;
}
return (
<View style={[styles.frame, frameStyle]} pointerEvents="none">
<BorderBox box={margin} style={styles.margin}>
<BorderBox box={padding} style={styles.padding}>
<View style={[styles.content, contentStyle]} />
</BorderBox>
</BorderBox>
</View>
);
}
}
const styles = StyleSheet.create({
frame: {
position: 'absolute',
},
content: {
backgroundColor: 'rgba(200, 230, 255, 0.8)', // blue
},
padding: {
borderColor: 'rgba(77, 255, 0, 0.3)', // green
},
margin: {
borderColor: 'rgba(255, 132, 0, 0.3)', // orange
},
});
type Style = {
top: number,
right: number,
bottom: number,
left: number,
...
};
/**
* Resolves relative sizes (percentages and auto) in a style object.
*
* @param style the style to resolve
* @return a modified copy
*/
function resolveRelativeSizes(style: $ReadOnly<Style>): Style {
let resolvedStyle = Object.assign({}, style);
resolveSizeInPlace(resolvedStyle, 'top', 'height');
resolveSizeInPlace(resolvedStyle, 'right', 'width');
resolveSizeInPlace(resolvedStyle, 'bottom', 'height');
resolveSizeInPlace(resolvedStyle, 'left', 'width');
return resolvedStyle;
}
/**
* Resolves the given size of a style object in place.
*
* @param style the style object to modify
* @param direction the direction to resolve (e.g. 'top')
* @param dimension the window dimension that this direction belongs to (e.g. 'height')
*/
function resolveSizeInPlace(
style: Style,
direction: string,
dimension: string,
) {
if (style[direction] !== null && typeof style[direction] === 'string') {
if (style[direction].indexOf('%') !== -1) {
style[direction] =
(parseFloat(style[direction]) / 100.0) *
Dimensions.get('window')[dimension];
}
if (style[direction] === 'auto') {
// Ignore auto sizing in frame drawing due to complexity of correctly rendering this
style[direction] = 0;
}
}
}
module.exports = ElementBox;

View File

@ -0,0 +1,147 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const BoxInspector = require('./BoxInspector');
const React = require('react');
const StyleInspector = require('./StyleInspector');
const StyleSheet = require('../StyleSheet/StyleSheet');
const Text = require('../Text/Text');
const TouchableHighlight = require('../Components/Touchable/TouchableHighlight');
const TouchableWithoutFeedback = require('../Components/Touchable/TouchableWithoutFeedback');
const View = require('../Components/View/View');
const flattenStyle = require('../StyleSheet/flattenStyle');
const mapWithSeparator = require('../Utilities/mapWithSeparator');
const openFileInEditor = require('../Core/Devtools/openFileInEditor');
import type {ViewStyleProp} from '../StyleSheet/StyleSheet';
type Props = $ReadOnly<{|
hierarchy: Array<{|name: string|}>,
style?: ?ViewStyleProp,
source?: ?{
fileName?: string,
lineNumber?: number,
...
},
frame?: ?Object,
selection?: ?number,
setSelection?: number => mixed,
|}>;
class ElementProperties extends React.Component<Props> {
render(): React.Node {
const style = flattenStyle(this.props.style);
const selection = this.props.selection;
let openFileButton;
const source = this.props.source;
const {fileName, lineNumber} = source || {};
if (fileName && lineNumber) {
const parts = fileName.split('/');
const fileNameShort = parts[parts.length - 1];
openFileButton = (
<TouchableHighlight
style={styles.openButton}
onPress={openFileInEditor.bind(null, fileName, lineNumber)}>
<Text style={styles.openButtonTitle} numberOfLines={1}>
{fileNameShort}:{lineNumber}
</Text>
</TouchableHighlight>
);
}
// Without the `TouchableWithoutFeedback`, taps on this inspector pane
// would change the inspected element to whatever is under the inspector
return (
<TouchableWithoutFeedback>
<View style={styles.info}>
<View style={styles.breadcrumb}>
{mapWithSeparator(
this.props.hierarchy,
(hierarchyItem, i) => (
<TouchableHighlight
key={'item-' + i}
style={[styles.breadItem, i === selection && styles.selected]}
// $FlowFixMe found when converting React.createClass to ES6
onPress={() => this.props.setSelection(i)}>
<Text style={styles.breadItemText}>{hierarchyItem.name}</Text>
</TouchableHighlight>
),
i => (
<Text key={'sep-' + i} style={styles.breadSep}>
&#9656;
</Text>
),
)}
</View>
<View style={styles.row}>
<View style={styles.col}>
<StyleInspector style={style} />
{openFileButton}
</View>
{<BoxInspector style={style} frame={this.props.frame} />}
</View>
</View>
</TouchableWithoutFeedback>
);
}
}
const styles = StyleSheet.create({
breadSep: {
fontSize: 8,
color: 'white',
},
breadcrumb: {
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'flex-start',
marginBottom: 5,
},
selected: {
borderColor: 'white',
borderRadius: 5,
},
breadItem: {
borderWidth: 1,
borderColor: 'transparent',
marginHorizontal: 2,
},
breadItemText: {
fontSize: 10,
color: 'white',
marginHorizontal: 5,
},
row: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
col: {
flex: 1,
},
info: {
padding: 10,
},
openButton: {
padding: 10,
backgroundColor: '#000',
marginVertical: 5,
marginRight: 5,
borderRadius: 2,
},
openButtonTitle: {
color: 'white',
fontSize: 8,
},
});
module.exports = ElementProperties;

View File

@ -0,0 +1,348 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const Dimensions = require('../Utilities/Dimensions');
const InspectorOverlay = require('./InspectorOverlay');
const InspectorPanel = require('./InspectorPanel');
const Platform = require('../Utilities/Platform');
const React = require('react');
const ReactNative = require('../Renderer/shims/ReactNative');
const StyleSheet = require('../StyleSheet/StyleSheet');
const Touchable = require('../Components/Touchable/Touchable');
const View = require('../Components/View/View');
const invariant = require('invariant');
import type {
HostComponent,
TouchedViewDataAtPoint,
} from '../Renderer/shims/ReactNativeTypes';
type HostRef = React.ElementRef<HostComponent<mixed>>;
export type ReactRenderer = {
rendererConfig: {
getInspectorDataForViewAtPoint: (
inspectedView: ?HostRef,
locationX: number,
locationY: number,
callback: Function,
) => void,
...
},
};
const hook = window.__REACT_DEVTOOLS_GLOBAL_HOOK__;
const renderers = findRenderers();
// Required for React DevTools to view/edit React Native styles in Flipper.
// Flipper doesn't inject these values when initializing DevTools.
hook.resolveRNStyle = require('../StyleSheet/flattenStyle');
const viewConfig = require('../Components/View/ReactNativeViewViewConfig');
hook.nativeStyleEditorValidAttributes = Object.keys(
viewConfig.validAttributes.style,
);
function findRenderers(): $ReadOnlyArray<ReactRenderer> {
const allRenderers = Array.from(hook.renderers.values());
invariant(
allRenderers.length >= 1,
'Expected to find at least one React Native renderer on DevTools hook.',
);
return allRenderers;
}
function getInspectorDataForViewAtPoint(
inspectedView: ?HostRef,
locationX: number,
locationY: number,
callback: (viewData: TouchedViewDataAtPoint) => void,
) {
// Check all renderers for inspector data.
for (let i = 0; i < renderers.length; i++) {
const renderer = renderers[i];
if (renderer?.rendererConfig?.getInspectorDataForViewAtPoint != null) {
renderer.rendererConfig.getInspectorDataForViewAtPoint(
inspectedView,
locationX,
locationY,
viewData => {
// Only return with non-empty view data since only one renderer will have this view.
if (viewData && viewData.hierarchy.length > 0) {
callback(viewData);
}
},
);
}
}
}
class Inspector extends React.Component<
{
inspectedView: ?HostRef,
onRequestRerenderApp: (callback: (instance: ?HostRef) => void) => void,
...
},
{
devtoolsAgent: ?Object,
hierarchy: any,
panelPos: string,
inspecting: boolean,
selection: ?number,
perfing: boolean,
inspected: any,
inspectedView: ?HostRef,
networking: boolean,
...
},
> {
_hideTimeoutID: TimeoutID | null = null;
_subs: ?Array<() => void>;
_setTouchedViewData: ?(TouchedViewDataAtPoint) => void;
constructor(props: Object) {
super(props);
this.state = {
devtoolsAgent: null,
hierarchy: null,
panelPos: 'bottom',
inspecting: true,
perfing: false,
inspected: null,
selection: null,
inspectedView: this.props.inspectedView,
networking: false,
};
}
componentDidMount() {
hook.on('react-devtools', this._attachToDevtools);
// if devtools is already started
if (hook.reactDevtoolsAgent) {
this._attachToDevtools(hook.reactDevtoolsAgent);
}
}
componentWillUnmount() {
if (this._subs) {
this._subs.map(fn => fn());
}
hook.off('react-devtools', this._attachToDevtools);
this._setTouchedViewData = null;
}
UNSAFE_componentWillReceiveProps(newProps: Object) {
this.setState({inspectedView: newProps.inspectedView});
}
_attachToDevtools = (agent: Object) => {
agent.addListener('hideNativeHighlight', this._onAgentHideNativeHighlight);
agent.addListener('showNativeHighlight', this._onAgentShowNativeHighlight);
agent.addListener('shutdown', this._onAgentShutdown);
this.setState({
devtoolsAgent: agent,
});
};
_onAgentHideNativeHighlight = () => {
if (this.state.inspected === null) {
return;
}
// we wait to actually hide in order to avoid flicker
this._hideTimeoutID = setTimeout(() => {
this.setState({
inspected: null,
});
}, 100);
};
_onAgentShowNativeHighlight = node => {
clearTimeout(this._hideTimeoutID);
node.measure((x, y, width, height, left, top) => {
this.setState({
hierarchy: [],
inspected: {
frame: {left, top, width, height},
},
});
});
};
_onAgentShutdown = () => {
const agent = this.state.devtoolsAgent;
if (agent != null) {
agent.removeListener(
'hideNativeHighlight',
this._onAgentHideNativeHighlight,
);
agent.removeListener(
'showNativeHighlight',
this._onAgentShowNativeHighlight,
);
agent.removeListener('shutdown', this._onAgentShutdown);
this.setState({devtoolsAgent: null});
}
};
setSelection(i: number) {
const hierarchyItem = this.state.hierarchy[i];
// we pass in ReactNative.findNodeHandle as the method is injected
const {measure, props, source} = hierarchyItem.getInspectorData(
ReactNative.findNodeHandle,
);
measure((x, y, width, height, left, top) => {
this.setState({
inspected: {
frame: {left, top, width, height},
style: props.style,
source,
},
selection: i,
});
});
}
onTouchPoint(locationX: number, locationY: number) {
this._setTouchedViewData = viewData => {
const {
hierarchy,
props,
selectedIndex,
source,
frame,
pointerY,
touchedViewTag,
} = viewData;
// Sync the touched view with React DevTools.
// Note: This is Paper only. To support Fabric,
// DevTools needs to be updated to not rely on view tags.
if (this.state.devtoolsAgent && touchedViewTag) {
this.state.devtoolsAgent.selectNode(
ReactNative.findNodeHandle(touchedViewTag),
);
}
this.setState({
panelPos:
pointerY > Dimensions.get('window').height / 2 ? 'top' : 'bottom',
selection: selectedIndex,
hierarchy,
inspected: {
style: props.style,
frame,
source,
},
});
};
getInspectorDataForViewAtPoint(
this.state.inspectedView,
locationX,
locationY,
viewData => {
if (this._setTouchedViewData != null) {
this._setTouchedViewData(viewData);
this._setTouchedViewData = null;
}
},
);
}
setPerfing(val: boolean) {
this.setState({
perfing: val,
inspecting: false,
inspected: null,
networking: false,
});
}
setInspecting(val: boolean) {
this.setState({
inspecting: val,
inspected: null,
});
}
setTouchTargeting(val: boolean) {
Touchable.TOUCH_TARGET_DEBUG = val;
this.props.onRequestRerenderApp(inspectedView => {
this.setState({inspectedView});
});
}
setNetworking(val: boolean) {
this.setState({
networking: val,
perfing: false,
inspecting: false,
inspected: null,
});
}
render(): React.Node {
const panelContainerStyle =
this.state.panelPos === 'bottom'
? {bottom: 0}
: {top: Platform.OS === 'ios' ? 20 : 0};
return (
<View style={styles.container} pointerEvents="box-none">
{this.state.inspecting && (
<InspectorOverlay
inspected={this.state.inspected}
onTouchPoint={this.onTouchPoint.bind(this)}
/>
)}
<View style={[styles.panelContainer, panelContainerStyle]}>
<InspectorPanel
devtoolsIsOpen={!!this.state.devtoolsAgent}
inspecting={this.state.inspecting}
perfing={this.state.perfing}
setPerfing={this.setPerfing.bind(this)}
setInspecting={this.setInspecting.bind(this)}
inspected={this.state.inspected}
hierarchy={this.state.hierarchy}
selection={this.state.selection}
setSelection={this.setSelection.bind(this)}
touchTargeting={Touchable.TOUCH_TARGET_DEBUG}
setTouchTargeting={this.setTouchTargeting.bind(this)}
networking={this.state.networking}
setNetworking={this.setNetworking.bind(this)}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
position: 'absolute',
backgroundColor: 'transparent',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
panelContainer: {
position: 'absolute',
left: 0,
right: 0,
},
});
module.exports = Inspector;

View File

@ -0,0 +1,76 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const Dimensions = require('../Utilities/Dimensions');
const ElementBox = require('./ElementBox');
const React = require('react');
const StyleSheet = require('../StyleSheet/StyleSheet');
const View = require('../Components/View/View');
import type {ViewStyleProp} from '../StyleSheet/StyleSheet';
import type {PressEvent} from '../Types/CoreEventTypes';
type Inspected = $ReadOnly<{|
frame?: Object,
style?: ViewStyleProp,
|}>;
type Props = $ReadOnly<{|
inspected?: Inspected,
onTouchPoint: (locationX: number, locationY: number) => void,
|}>;
class InspectorOverlay extends React.Component<Props> {
findViewForTouchEvent: (e: PressEvent) => void = (e: PressEvent) => {
const {locationX, locationY} = e.nativeEvent.touches[0];
this.props.onTouchPoint(locationX, locationY);
};
shouldSetResponser: (e: PressEvent) => boolean = (e: PressEvent): boolean => {
this.findViewForTouchEvent(e);
return true;
};
render(): React.Node {
let content = null;
if (this.props.inspected) {
content = (
<ElementBox
frame={this.props.inspected.frame}
style={this.props.inspected.style}
/>
);
}
return (
<View
onStartShouldSetResponder={this.shouldSetResponser}
onResponderMove={this.findViewForTouchEvent}
style={[styles.inspector, {height: Dimensions.get('window').height}]}>
{content}
</View>
);
}
}
const styles = StyleSheet.create({
inspector: {
backgroundColor: 'transparent',
position: 'absolute',
left: 0,
top: 0,
right: 0,
},
});
module.exports = InspectorOverlay;

View File

@ -0,0 +1,170 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
const ElementProperties = require('./ElementProperties');
const NetworkOverlay = require('./NetworkOverlay');
const PerformanceOverlay = require('./PerformanceOverlay');
const React = require('react');
const ScrollView = require('../Components/ScrollView/ScrollView');
const StyleSheet = require('../StyleSheet/StyleSheet');
const Text = require('../Text/Text');
const TouchableHighlight = require('../Components/Touchable/TouchableHighlight');
const View = require('../Components/View/View');
import type {ViewStyleProp} from '../StyleSheet/StyleSheet';
type Props = $ReadOnly<{|
devtoolsIsOpen: boolean,
inspecting: boolean,
setInspecting: (val: boolean) => void,
perfing: boolean,
setPerfing: (val: boolean) => void,
touchTargeting: boolean,
setTouchTargeting: (val: boolean) => void,
networking: boolean,
setNetworking: (val: boolean) => void,
hierarchy?: ?Array<{|name: string|}>,
selection?: ?number,
setSelection: number => mixed,
inspected?: ?$ReadOnly<{|
style?: ?ViewStyleProp,
frame?: ?$ReadOnly<{|
top?: ?number,
left?: ?number,
width?: ?number,
height: ?number,
|}>,
source?: ?{|
fileName?: string,
lineNumber?: number,
|},
|}>,
|}>;
class InspectorPanel extends React.Component<Props> {
renderWaiting(): React.Node {
if (this.props.inspecting) {
return (
<Text style={styles.waitingText}>Tap something to inspect it</Text>
);
}
return <Text style={styles.waitingText}>Nothing is inspected</Text>;
}
render(): React.Node {
let contents;
if (this.props.inspected) {
contents = (
<ScrollView style={styles.properties}>
<ElementProperties
style={this.props.inspected.style}
frame={this.props.inspected.frame}
source={this.props.inspected.source}
// $FlowFixMe: Hierarchy should be non-nullable
hierarchy={this.props.hierarchy}
selection={this.props.selection}
setSelection={this.props.setSelection}
/>
</ScrollView>
);
} else if (this.props.perfing) {
contents = <PerformanceOverlay />;
} else if (this.props.networking) {
contents = <NetworkOverlay />;
} else {
contents = <View style={styles.waiting}>{this.renderWaiting()}</View>;
}
return (
<View style={styles.container}>
{!this.props.devtoolsIsOpen && contents}
<View style={styles.buttonRow}>
<InspectorPanelButton
title={'Inspect'}
pressed={this.props.inspecting}
onClick={this.props.setInspecting}
/>
<InspectorPanelButton
title={'Perf'}
pressed={this.props.perfing}
onClick={this.props.setPerfing}
/>
<InspectorPanelButton
title={'Network'}
pressed={this.props.networking}
onClick={this.props.setNetworking}
/>
<InspectorPanelButton
title={'Touchables'}
pressed={this.props.touchTargeting}
onClick={this.props.setTouchTargeting}
/>
</View>
</View>
);
}
}
type InspectorPanelButtonProps = $ReadOnly<{|
onClick: (val: boolean) => void,
pressed: boolean,
title: string,
|}>;
class InspectorPanelButton extends React.Component<InspectorPanelButtonProps> {
render() {
return (
<TouchableHighlight
onPress={() => this.props.onClick(!this.props.pressed)}
style={[styles.button, this.props.pressed && styles.buttonPressed]}>
<Text style={styles.buttonText}>{this.props.title}</Text>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
buttonRow: {
flexDirection: 'row',
},
button: {
backgroundColor: 'rgba(0, 0, 0, 0.3)',
margin: 2,
height: 30,
justifyContent: 'center',
alignItems: 'center',
},
buttonPressed: {
backgroundColor: 'rgba(255, 255, 255, 0.3)',
},
buttonText: {
textAlign: 'center',
color: 'white',
margin: 5,
},
container: {
backgroundColor: 'rgba(0, 0, 0, 0.7)',
},
properties: {
height: 200,
},
waiting: {
height: 100,
},
waitingText: {
fontSize: 20,
textAlign: 'center',
marginVertical: 20,
color: 'white',
},
});
module.exports = InspectorPanel;

View File

@ -0,0 +1,601 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const FlatList = require('../Lists/FlatList');
const React = require('react');
const ScrollView = require('../Components/ScrollView/ScrollView');
const StyleSheet = require('../StyleSheet/StyleSheet');
const Text = require('../Text/Text');
const TouchableHighlight = require('../Components/Touchable/TouchableHighlight');
const View = require('../Components/View/View');
const WebSocketInterceptor = require('../WebSocket/WebSocketInterceptor');
const XHRInterceptor = require('../Network/XHRInterceptor');
const LISTVIEW_CELL_HEIGHT = 15;
// Global id for the intercepted XMLHttpRequest objects.
let nextXHRId = 0;
type NetworkRequestInfo = {
id: number,
type?: string,
url?: string,
method?: string,
status?: number,
dataSent?: any,
responseContentType?: string,
responseSize?: number,
requestHeaders?: Object,
responseHeaders?: string,
response?: Object | string,
responseURL?: string,
responseType?: string,
timeout?: number,
closeReason?: string,
messages?: string,
serverClose?: Object,
serverError?: Object,
...
};
type Props = $ReadOnly<{||}>;
type State = {|
detailRowId: ?number,
requests: Array<NetworkRequestInfo>,
|};
function getStringByValue(value: any): string {
if (value === undefined) {
return 'undefined';
}
if (typeof value === 'object') {
return JSON.stringify(value);
}
if (typeof value === 'string' && value.length > 500) {
return String(value)
.substr(0, 500)
.concat('\n***TRUNCATED TO 500 CHARACTERS***');
}
return value;
}
function getTypeShortName(type: any): string {
if (type === 'XMLHttpRequest') {
return 'XHR';
} else if (type === 'WebSocket') {
return 'WS';
}
return '';
}
function keyExtractor(request: NetworkRequestInfo): string {
return String(request.id);
}
/**
* Show all the intercepted network requests over the InspectorPanel.
*/
class NetworkOverlay extends React.Component<Props, State> {
_requestsListView: ?React.ElementRef<typeof FlatList>;
_detailScrollView: ?React.ElementRef<typeof ScrollView>;
// Metrics are used to decide when if the request list should be sticky, and
// scroll to the bottom as new network requests come in, or if the user has
// intentionally scrolled away from the bottom - to instead flash the scroll bar
// and keep the current position
_requestsListViewScrollMetrics = {
offset: 0,
visibleLength: 0,
contentLength: 0,
};
// Map of `socketId` -> `index in `this.state.requests`.
_socketIdMap = {};
// Map of `xhr._index` -> `index in `this.state.requests`.
_xhrIdMap: {[key: number]: number, ...} = {};
state: State = {
detailRowId: null,
requests: [],
};
_enableXHRInterception(): void {
if (XHRInterceptor.isInterceptorEnabled()) {
return;
}
// Show the XHR request item in listView as soon as it was opened.
XHRInterceptor.setOpenCallback((method, url, xhr) => {
// Generate a global id for each intercepted xhr object, add this id
// to the xhr object as a private `_index` property to identify it,
// so that we can distinguish different xhr objects in callbacks.
xhr._index = nextXHRId++;
const xhrIndex = this.state.requests.length;
this._xhrIdMap[xhr._index] = xhrIndex;
const _xhr: NetworkRequestInfo = {
id: xhrIndex,
type: 'XMLHttpRequest',
method: method,
url: url,
};
this.setState(
{
requests: this.state.requests.concat(_xhr),
},
this._indicateAdditionalRequests,
);
});
XHRInterceptor.setRequestHeaderCallback((header, value, xhr) => {
const xhrIndex = this._getRequestIndexByXHRID(xhr._index);
if (xhrIndex === -1) {
return;
}
this.setState(({requests}) => {
const networkRequestInfo = requests[xhrIndex];
if (!networkRequestInfo.requestHeaders) {
networkRequestInfo.requestHeaders = {};
}
networkRequestInfo.requestHeaders[header] = value;
return {requests};
});
});
XHRInterceptor.setSendCallback((data, xhr) => {
const xhrIndex = this._getRequestIndexByXHRID(xhr._index);
if (xhrIndex === -1) {
return;
}
this.setState(({requests}) => {
const networkRequestInfo = requests[xhrIndex];
networkRequestInfo.dataSent = data;
return {requests};
});
});
XHRInterceptor.setHeaderReceivedCallback(
(type, size, responseHeaders, xhr) => {
const xhrIndex = this._getRequestIndexByXHRID(xhr._index);
if (xhrIndex === -1) {
return;
}
this.setState(({requests}) => {
const networkRequestInfo = requests[xhrIndex];
networkRequestInfo.responseContentType = type;
networkRequestInfo.responseSize = size;
networkRequestInfo.responseHeaders = responseHeaders;
return {requests};
});
},
);
XHRInterceptor.setResponseCallback(
(status, timeout, response, responseURL, responseType, xhr) => {
const xhrIndex = this._getRequestIndexByXHRID(xhr._index);
if (xhrIndex === -1) {
return;
}
this.setState(({requests}) => {
const networkRequestInfo = requests[xhrIndex];
networkRequestInfo.status = status;
networkRequestInfo.timeout = timeout;
networkRequestInfo.response = response;
networkRequestInfo.responseURL = responseURL;
networkRequestInfo.responseType = responseType;
return {requests};
});
},
);
// Fire above callbacks.
XHRInterceptor.enableInterception();
}
_enableWebSocketInterception(): void {
if (WebSocketInterceptor.isInterceptorEnabled()) {
return;
}
// Show the WebSocket request item in listView when 'connect' is called.
WebSocketInterceptor.setConnectCallback(
(url, protocols, options, socketId) => {
const socketIndex = this.state.requests.length;
this._socketIdMap[socketId] = socketIndex;
const _webSocket: NetworkRequestInfo = {
id: socketIndex,
type: 'WebSocket',
url: url,
protocols: protocols,
};
this.setState(
{
requests: this.state.requests.concat(_webSocket),
},
this._indicateAdditionalRequests,
);
},
);
WebSocketInterceptor.setCloseCallback(
(statusCode, closeReason, socketId) => {
const socketIndex = this._socketIdMap[socketId];
if (socketIndex === undefined) {
return;
}
if (statusCode !== null && closeReason !== null) {
this.setState(({requests}) => {
const networkRequestInfo = requests[socketIndex];
networkRequestInfo.status = statusCode;
networkRequestInfo.closeReason = closeReason;
return {requests};
});
}
},
);
WebSocketInterceptor.setSendCallback((data, socketId) => {
const socketIndex = this._socketIdMap[socketId];
if (socketIndex === undefined) {
return;
}
this.setState(({requests}) => {
const networkRequestInfo = requests[socketIndex];
if (!networkRequestInfo.messages) {
networkRequestInfo.messages = '';
}
networkRequestInfo.messages += 'Sent: ' + JSON.stringify(data) + '\n';
return {requests};
});
});
WebSocketInterceptor.setOnMessageCallback((socketId, message) => {
const socketIndex = this._socketIdMap[socketId];
if (socketIndex === undefined) {
return;
}
this.setState(({requests}) => {
const networkRequestInfo = requests[socketIndex];
if (!networkRequestInfo.messages) {
networkRequestInfo.messages = '';
}
networkRequestInfo.messages +=
'Received: ' + JSON.stringify(message) + '\n';
return {requests};
});
});
WebSocketInterceptor.setOnCloseCallback((socketId, message) => {
const socketIndex = this._socketIdMap[socketId];
if (socketIndex === undefined) {
return;
}
this.setState(({requests}) => {
const networkRequestInfo = requests[socketIndex];
networkRequestInfo.serverClose = message;
return {requests};
});
});
WebSocketInterceptor.setOnErrorCallback((socketId, message) => {
const socketIndex = this._socketIdMap[socketId];
if (socketIndex === undefined) {
return;
}
this.setState(({requests}) => {
const networkRequestInfo = requests[socketIndex];
networkRequestInfo.serverError = message;
return {requests};
});
});
// Fire above callbacks.
WebSocketInterceptor.enableInterception();
}
componentDidMount() {
this._enableXHRInterception();
this._enableWebSocketInterception();
}
componentWillUnmount() {
XHRInterceptor.disableInterception();
WebSocketInterceptor.disableInterception();
}
_renderItem = ({item, index}): React.Element<any> => {
const tableRowViewStyle = [
styles.tableRow,
index % 2 === 1 ? styles.tableRowOdd : styles.tableRowEven,
index === this.state.detailRowId && styles.tableRowPressed,
];
const urlCellViewStyle = styles.urlCellView;
const methodCellViewStyle = styles.methodCellView;
return (
<TouchableHighlight
onPress={() => {
this._pressRow(index);
}}>
<View>
<View style={tableRowViewStyle}>
<View style={urlCellViewStyle}>
<Text style={styles.cellText} numberOfLines={1}>
{item.url}
</Text>
</View>
<View style={methodCellViewStyle}>
<Text style={styles.cellText} numberOfLines={1}>
{getTypeShortName(item.type)}
</Text>
</View>
</View>
</View>
</TouchableHighlight>
);
};
_renderItemDetail(id) {
const requestItem = this.state.requests[id];
const details = Object.keys(requestItem).map(key => {
if (key === 'id') {
return;
}
return (
<View style={styles.detailViewRow} key={key}>
<Text style={[styles.detailViewText, styles.detailKeyCellView]}>
{key}
</Text>
<Text style={[styles.detailViewText, styles.detailValueCellView]}>
{getStringByValue(requestItem[key])}
</Text>
</View>
);
});
return (
<View>
<TouchableHighlight
style={styles.closeButton}
onPress={this._closeButtonClicked}>
<View>
<Text style={styles.closeButtonText}>v</Text>
</View>
</TouchableHighlight>
<ScrollView
style={styles.detailScrollView}
ref={scrollRef => (this._detailScrollView = scrollRef)}>
{details}
</ScrollView>
</View>
);
}
_indicateAdditionalRequests = (): void => {
if (this._requestsListView) {
const distanceFromEndThreshold = LISTVIEW_CELL_HEIGHT * 2;
const {
offset,
visibleLength,
contentLength,
} = this._requestsListViewScrollMetrics;
const distanceFromEnd = contentLength - visibleLength - offset;
const isCloseToEnd = distanceFromEnd <= distanceFromEndThreshold;
if (isCloseToEnd) {
this._requestsListView.scrollToEnd();
} else {
this._requestsListView.flashScrollIndicators();
}
}
};
_captureRequestsListView = (listRef: ?FlatList<NetworkRequestInfo>): void => {
this._requestsListView = listRef;
};
_requestsListViewOnScroll = (e: Object): void => {
this._requestsListViewScrollMetrics.offset = e.nativeEvent.contentOffset.y;
this._requestsListViewScrollMetrics.visibleLength =
e.nativeEvent.layoutMeasurement.height;
this._requestsListViewScrollMetrics.contentLength =
e.nativeEvent.contentSize.height;
};
/**
* Popup a scrollView to dynamically show detailed information of
* the request, when pressing a row in the network flow listView.
*/
_pressRow(rowId: number): void {
this.setState({detailRowId: rowId}, this._scrollDetailToTop);
}
_scrollDetailToTop = (): void => {
if (this._detailScrollView) {
this._detailScrollView.scrollTo({
y: 0,
animated: false,
});
}
};
_closeButtonClicked = () => {
this.setState({detailRowId: null});
};
_getRequestIndexByXHRID(index: number): number {
if (index === undefined) {
return -1;
}
const xhrIndex = this._xhrIdMap[index];
if (xhrIndex === undefined) {
return -1;
} else {
return xhrIndex;
}
}
render(): React.Node {
const {requests, detailRowId} = this.state;
return (
<View style={styles.container}>
{detailRowId != null && this._renderItemDetail(detailRowId)}
<View style={styles.listViewTitle}>
{requests.length > 0 && (
<View style={styles.tableRow}>
<View style={styles.urlTitleCellView}>
<Text style={styles.cellText} numberOfLines={1}>
URL
</Text>
</View>
<View style={styles.methodTitleCellView}>
<Text style={styles.cellText} numberOfLines={1}>
Type
</Text>
</View>
</View>
)}
</View>
<FlatList
ref={this._captureRequestsListView}
onScroll={this._requestsListViewOnScroll}
style={styles.listView}
data={requests}
renderItem={this._renderItem}
keyExtractor={keyExtractor}
extraData={this.state}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 5,
paddingRight: 5,
},
listViewTitle: {
height: 20,
},
listView: {
flex: 1,
height: 60,
},
tableRow: {
flexDirection: 'row',
flex: 1,
height: LISTVIEW_CELL_HEIGHT,
},
tableRowEven: {
backgroundColor: '#555',
},
tableRowOdd: {
backgroundColor: '#000',
},
tableRowPressed: {
backgroundColor: '#3B5998',
},
cellText: {
color: 'white',
fontSize: 12,
},
methodTitleCellView: {
height: 18,
borderColor: '#DCD7CD',
borderTopWidth: 1,
borderBottomWidth: 1,
borderRightWidth: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#444',
flex: 1,
},
urlTitleCellView: {
height: 18,
borderColor: '#DCD7CD',
borderTopWidth: 1,
borderBottomWidth: 1,
borderLeftWidth: 1,
borderRightWidth: 1,
justifyContent: 'center',
backgroundColor: '#444',
flex: 5,
paddingLeft: 3,
},
methodCellView: {
height: 15,
borderColor: '#DCD7CD',
borderRightWidth: 1,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
},
urlCellView: {
height: 15,
borderColor: '#DCD7CD',
borderLeftWidth: 1,
borderRightWidth: 1,
justifyContent: 'center',
flex: 5,
paddingLeft: 3,
},
detailScrollView: {
flex: 1,
height: 180,
marginTop: 5,
marginBottom: 5,
},
detailKeyCellView: {
flex: 1.3,
},
detailValueCellView: {
flex: 2,
},
detailViewRow: {
flexDirection: 'row',
paddingHorizontal: 3,
},
detailViewText: {
color: 'white',
fontSize: 11,
},
closeButtonText: {
color: 'white',
fontSize: 10,
},
closeButton: {
marginTop: 5,
backgroundColor: '#888',
justifyContent: 'center',
alignItems: 'center',
},
});
module.exports = NetworkOverlay;

View File

@ -0,0 +1,63 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const PerformanceLogger = require('../Utilities/GlobalPerformanceLogger');
const React = require('react');
const StyleSheet = require('../StyleSheet/StyleSheet');
const Text = require('../Text/Text');
const View = require('../Components/View/View');
class PerformanceOverlay extends React.Component<{...}> {
render(): React.Node {
const perfLogs = PerformanceLogger.getTimespans();
const items = [];
for (const key in perfLogs) {
if (perfLogs[key].totalTime) {
const unit = key === 'BundleSize' ? 'b' : 'ms';
items.push(
<View style={styles.row} key={key}>
<Text style={[styles.text, styles.label]}>{key}</Text>
<Text style={[styles.text, styles.totalTime]}>
{perfLogs[key].totalTime + unit}
</Text>
</View>,
);
}
}
return <View style={styles.container}>{items}</View>;
}
}
const styles = StyleSheet.create({
container: {
height: 100,
paddingTop: 10,
},
label: {
flex: 1,
},
row: {
flexDirection: 'row',
paddingHorizontal: 10,
},
text: {
color: 'white',
fontSize: 12,
},
totalTime: {
paddingRight: 100,
},
});
module.exports = PerformanceOverlay;

View File

@ -0,0 +1,70 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
const React = require('react');
const StyleSheet = require('../StyleSheet/StyleSheet');
const Text = require('../Text/Text');
const View = require('../Components/View/View');
class StyleInspector extends React.Component<$FlowFixMeProps> {
render(): React.Node {
if (!this.props.style) {
return <Text style={styles.noStyle}>No style</Text>;
}
const names = Object.keys(this.props.style);
return (
<View style={styles.container}>
<View>
{names.map(name => (
<Text key={name} style={styles.attr}>
{name}:
</Text>
))}
</View>
<View>
{names.map(name => {
const value = this.props.style[name];
return (
<Text key={name} style={styles.value}>
{typeof value !== 'string' && typeof value !== 'number'
? JSON.stringify(value)
: value}
</Text>
);
})}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
},
attr: {
fontSize: 10,
color: '#ccc',
},
value: {
fontSize: 10,
color: 'white',
marginLeft: 10,
},
noStyle: {
color: 'white',
fontSize: 10,
},
});
module.exports = StyleInspector;

View File

@ -0,0 +1,114 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const I18nManager = require('../ReactNative/I18nManager');
/**
* Resolve a style property into its component parts.
*
* For example:
*
* > resolveProperties('margin', {margin: 5, marginBottom: 10})
* {top: 5, left: 5, right: 5, bottom: 10}
*
* If no parts exist, this returns null.
*/
function resolveBoxStyle(
prefix: string,
style: Object,
): ?$ReadOnly<{|
bottom: number,
left: number,
right: number,
top: number,
|}> {
let hasParts = false;
const result = {
bottom: 0,
left: 0,
right: 0,
top: 0,
};
// TODO: Fix issues with multiple properties affecting the same side.
const styleForAll = style[prefix];
if (styleForAll != null) {
for (const key of Object.keys(result)) {
result[key] = styleForAll;
}
hasParts = true;
}
const styleForHorizontal = style[prefix + 'Horizontal'];
if (styleForHorizontal != null) {
result.left = styleForHorizontal;
result.right = styleForHorizontal;
hasParts = true;
} else {
const styleForLeft = style[prefix + 'Left'];
if (styleForLeft != null) {
result.left = styleForLeft;
hasParts = true;
}
const styleForRight = style[prefix + 'Right'];
if (styleForRight != null) {
result.right = styleForRight;
hasParts = true;
}
const styleForEnd = style[prefix + 'End'];
if (styleForEnd != null) {
const constants = I18nManager.getConstants();
if (constants.isRTL && constants.doLeftAndRightSwapInRTL) {
result.left = styleForEnd;
} else {
result.right = styleForEnd;
}
hasParts = true;
}
const styleForStart = style[prefix + 'Start'];
if (styleForStart != null) {
const constants = I18nManager.getConstants();
if (constants.isRTL && constants.doLeftAndRightSwapInRTL) {
result.right = styleForStart;
} else {
result.left = styleForStart;
}
hasParts = true;
}
}
const styleForVertical = style[prefix + 'Vertical'];
if (styleForVertical != null) {
result.bottom = styleForVertical;
result.top = styleForVertical;
hasParts = true;
} else {
const styleForBottom = style[prefix + 'Bottom'];
if (styleForBottom != null) {
result.bottom = styleForBottom;
hasParts = true;
}
const styleForTop = style[prefix + 'Top'];
if (styleForTop != null) {
result.top = styleForTop;
hasParts = true;
}
}
return hasParts ? result : null;
}
module.exports = resolveBoxStyle;