Last active
July 21, 2016 16:13
-
-
Save rohozhnikoff/6f781f5c318eb65cec44ce2d28327c82 to your computer and use it in GitHub Desktop.
[react-native] Pixel-perfect component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* todo: | |
* make the opacity-management buttons (remove from props) | |
* inside block (not only root) | |
* wrap block | |
* scrollable ! | |
* */ | |
import React, { Component, PropTypes } from 'react'; | |
import { | |
Text, View, StyleSheet, TouchableOpacity, Image, Dimensions | |
} from 'react-native'; | |
import {reduce, assign} from 'lodash'; | |
const {width, height} = Dimensions.get('window'); | |
/* https://gist.github.com/rogozhnikoff/abd107912fa57595e2f108c87f8a988f */ | |
import AsyncStorage from './storage.js' | |
class Perfecta extends React.Component { | |
static defaultProps = { | |
storageKey: '__perfecta', | |
opacity: 0.4, | |
}; | |
static propTypes = { | |
source: PropTypes.any.isRequired | |
}; | |
constructor(props, context) { | |
super(props, context); | |
this.state = { | |
enabled: false | |
}; | |
AsyncStorage.getItem(props.storageKey) | |
.then((savedState) => savedState && this.setState(savedState)); | |
} | |
switchState() { | |
this.setState({ | |
enabled: !this.state.enabled | |
}, () => AsyncStorage.setItem(this.props.storageKey, this.state)); | |
} | |
renderOverlay() { | |
const {source, opacity} = this.props; | |
return (<View pointerEvents='none' style={{width, height}}> | |
<Image source={source} style={[STYLE.overlay, {opacity}]} resizeMode="contain" /> | |
</View>) | |
} | |
render() { | |
const {enabled} = this.state; | |
return (<View style={[STYLE.wrapper, this.props.style]} pointerEvents="box-none"> | |
{enabled && this.renderOverlay()} | |
<TouchableOpacity onPress={this.switchState.bind(this)} style={STYLE.btn}> | |
<View style={[STYLE.btnVisible, (enabled && STYLE.btnVisibleEnabled)]} /> | |
</TouchableOpacity> | |
</View>) | |
} | |
} | |
const STYLE = (() => { | |
const buttonSize = 20; | |
return StyleSheet.create({ | |
'wrapper': { | |
position: 'absolute', | |
top: 0, left: 0, right: 0, bottom: 0, | |
backgroundColor: 'transparent', | |
transform: [{scale: 1}], | |
}, | |
'overlay': { | |
width, height | |
}, | |
'btn': { | |
position: 'absolute', | |
left: (width / 2) - (buttonSize / 2), | |
bottom: 15, | |
}, | |
btnVisible: { | |
height: buttonSize, | |
width: buttonSize, | |
borderRadius: buttonSize / 2, | |
backgroundColor: 'rgba(0, 0, 0, .3)', | |
borderWidth: 2, | |
borderColor: 'white', | |
}, | |
btnVisibleEnabled: { | |
backgroundColor: 'orange', | |
} | |
}); | |
}); | |
export default Perfecta; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment