path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/components/Tags.js | chtefi/golb | import React from 'react'
import { Link } from 'gatsby'
import { css } from 'react-emotion'
export default ({ tags }) => (
<ul
className={css`
li {
display: inline-block;
margin-right: 5px;
padding: 0 10px;
background: #eee;
border: 1px solid #ddd;
border-radius: 20px;
font-size: 18px;
}
li:hover {
background-color: rgb(2, 136, 209);
}
li:hover a {
color: white;
}
`}
>
{(tags || []).map(tag => (
<li key={tag}>
<Link className="clean" to={'/tags/' + tag}>
{tag}
</Link>
</li>
))}
</ul>
)
|
src/components/MainNavigation/MainNavigation.stories.js | urfonline/frontend | import React from 'react';
import { storiesOf } from '@storybook/react';
import MainNavigation from './index';
import { MemoryRouter } from 'react-router';
storiesOf('MainNavigation', module)
.addDecorator((story) => (
<MemoryRouter initialEntries={['/']}>{story()}</MemoryRouter>
))
.add('', () => (
<div>
<MainNavigation desktop />
<MainNavigation mobile />
</div>
));
|
src/components/ipns-manager/rename-key-modal/RenameKeyModal.js | ipfs/webui | import React from 'react'
import PropTypes from 'prop-types'
import Icon from '../../../icons/StrokePencil'
import TextInputModal from '../../text-input-modal/TextInputModal'
import { Trans } from 'react-i18next'
const RenameKeyModal = ({ t, tReady, name, onCancel, onSubmit, className, ...props }) => {
return (
<TextInputModal
onSubmit={(p) => onSubmit(p.trim())}
onChange={(p) => p.trimStart()}
onCancel={onCancel}
className={className}
title={t('renameKeyModal.title')}
description={
<div className='charcoal w-90 center tl mb3'>
<Trans t={t} i18nKey='renameKeyModal.description' tOptions={{ name }}>
Renaming IPNS key <span className='charcoal-muted monospace'>{name}</span>.
</Trans>
</div>
}
Icon={Icon}
defaultValue={name}
mustBeDifferent={true}
submitText={t('app:actions.rename')}
{...props}
/>
)
}
RenameKeyModal.propTypes = {
t: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
onCancel: PropTypes.func.isRequired,
name: PropTypes.string.isRequired,
className: PropTypes.string
}
RenameKeyModal.defaultProps = {
className: ''
}
export default RenameKeyModal
|
app/pages/uploadPage.js | shiyunjie/scs | /**
* Created by shiyunjie on 16/12/6.
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Platform,
TouchableOpacity,
ScrollView,
ListView,
TextInput,
Image,
Dimensions,
Alert,
NativeAppEventEmitter,
ActivityIndicator,
Modal,
NativeModules,
} from 'react-native'
import constants from '../constants/constant'
import SudokuGrid from 'react-native-smart-sudoku-grid'
import Icon from 'react-native-vector-icons/Ionicons'
import XhrEnhance from '../lib/XhrEnhance'
import AppEventListenerEnhance from 'react-native-smart-app-event-listener-enhance'
import TimerEnhance from 'react-native-smart-timer-enhance'
import PicturePicker from './picturePicker'
import navigatorStyle from '../styles/navigatorStyle' //navigationBar样式
import Button from 'react-native-smart-button'
import {getDeviceID,getToken} from '../lib/User'
import Toast from 'react-native-smart-toast'
import RNFS from 'react-native-fs'
import ImageZoomModal from '../components/ImageZoomModal'
import {doSign} from '../lib/utils'
import LoadingSpinnerOverlay from 'react-native-smart-loading-spinner-overlay'
import {ImageZoom} from 'react-native-image-pan-zoom';
import doc from '../images/word.png'
import excel from '../images/excel.png'
import pdf from '../images/pdf.png'
import file from '../images/File_Blank.png'
import ImagePicker from 'react-native-image-crop-picker'
const NativeCompressedModule = NativeModules.NativeCompressedModule;
const { width: deviceWidth ,height: deviceHeight} = Dimensions.get('window')
/*{
filename: "IMG_0003.JPG",
height: 2500,
isStored: true,
uploaded:true,
uploading:false,
uri: "assets-library://asset/asset.JPG?id=9F983DBA-EC35-42B8-8773-B597CF782EDD&ext=JPG",
width: 1668
}*/
const photoList = [];
const maxiumUploadImagesCount = constants.maxiumUploadImagesCount //最多上传图片总数
const maxiumXhrNums = constants.maxiumXhrNums //最多同时上传数量
class UploadPage extends Component {
/* // 构造
constructor (props) {
super(props)
// 初始状态
this.state = {
photoList, //{ uri: 'xxx', compressedUri: 'xxx', uploadProgress: 0.9, uploadError: false, uploading: true, uploaded: false, }, { uri: 'xxx', compressedUri: 'xxx', uploadProgress: 1, uploadError: false, uploading: false, uploaded: true, }
};
this._uploadingXhrCacheList = [] //正在上传中的(包含上传失败的)xhr缓存列表, 用uri做唯一性, 该列表长度会影响当前可用的上传线程数
this._waitForUploadQuene = [] //待上传队列, 用uri做唯一性
}*/
// 构造
constructor(props) {
super(props);
// 初始状态
this._dataSource = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
//sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
});
this.state = {
service_id: this.props.id,//服务单id
photoList,
dataSource: this._dataSource.cloneWithRows(photoList),
showUrl: '',
modalVisible: false,
images: null,
}
this._uploadingXhrCacheList = [] //正在上传中的(包含上传失败的)xhr缓存列表, 用uri做唯一性, 该列表长度会影响当前可用的上传线程数
this._waitForUploadQuene = [] //待上传队列, 用uri做唯一性
this._waitForAddPhotos = null
this._ids = [];
this.ImgTemp = '';
this._initCustomData()
this.firstFetch = true;
this.showDelete=false;
}
componentWillMount() {
this.ImgTemp = `${RNFS.DocumentDirectoryPath}/ImgTemp`
//console.log(`RNFS.DocumentDirectoryPath = ${RNFS.DocumentDirectoryPath}`)
RNFS.readDir(RNFS.DocumentDirectoryPath)
.then((readDirItems) => {
//console.log(`readDirItems -> `)
//console.log(readDirItems)
})
NativeAppEventEmitter.emit('setNavigationBar.index', navigationBarRouteMapper)
let currentRoute = this.props.navigator.navigationContext.currentRoute
this.addAppEventListener(
this.props.navigator.navigationContext.addListener('willfocus', (event) => {
//console.log(`orderPage willfocus...`)
//console.log(`currentRoute`, currentRoute)
//console.log(`event.data.route`, event.data.route)
if (event && currentRoute === event.data.route) {
//console.log("orderPage willAppear")
NativeAppEventEmitter.emit('setNavigationBar.index', navigationBarRouteMapper)
/*
if (this._waitForAddPhotos && this._waitForAddPhotos.length > 0) {
this.setTimeout(() => {
/!*
//@todo async this._getCompressedPhotos 返回photos数组, 遍历this._waitForAddPhotos {let compressedUri = await NativeCompressedModule.compress(...); 遍历的photo对象uri赋值compressedUri }
this._getCompressedPhotos().then((photos)=>{
this._addToUploadQuene(photos)
})*!/
this._addToUploadQuene(this._waitForAddPhotos)
this._waitForAddPhotos = null
}, 300)
}*/
} else {
//console.log("orderPage willDisappear, other willAppear")
}
//
})
)
/* this.addAppEventListener(
NativeAppEventEmitter.addListener('PicturePicker.finish.saveIds', () => {
if (this._modalLoadingSpinnerOverLay) {
this._modalLoadingSpinnerOverLay.show()
}
this._fetch_finish()
})
)*/
this.addAppEventListener(
NativeAppEventEmitter.addListener('photoUploadPage.need.navigator.pop', () => {
// console.log(`_uploadingXhrCacheList.pop:`, this._uploadingXhrCacheList.length)
// console.log(`_waitForUploadQuene.pop:`, this._waitForUploadQuene.length)
if (this._uploadingXhrCacheList.length > 0 || this._waitForUploadQuene.length > 0) {
Alert.alert('温馨提醒', '确定要删除文件吗?',
[{
text: '取消', onPress: ()=> {
}
},
{
text: '确定', onPress: ()=> {
this.props.navigator.pop()
}
}
])
} else {
this.props.navigator.pop()
}
})
)
this.addAppEventListener(
NativeAppEventEmitter.addListener('needstart.uploadphoto.setstate', () => {
if (this._waitForAddPhotos && this._waitForAddPhotos.length > 0) {
//this.setTimeout(() => {
/*
//@todo async this._getCompressedPhotos 返回photos数组, 遍历this._waitForAddPhotos {let compressedUri = await NativeCompressedModule.compress(...); 遍历的photo对象uri赋值compressedUri }
this._getCompressedPhotos().then((photos)=>{
this._addToUploadQuene(photos)
})*/
this._addToUploadQuene(this._waitForAddPhotos)
this._waitForAddPhotos = null
//}, 300)
}
})
)
this.addAppEventListener(
this.props.navigator.navigationContext.addListener('didfocus', (event) => {
//console.log(`payPage didfocus...`)
if (event && currentRoute === event.data.route) {
//console.log("upload didAppear")
if (this.firstFetch) {
//this._fetchData()
let photos = []
for (let data of this.props.showList) {
if (!data.file_url) {
continue
}
//console.log('data', data)
let file = {uri: data.file_url, id: data.id}
if (this._ids.indexOf(file) == -1) {
this._ids.push(file)
//console.log(`ids:`, this._ids);
}
photos.push(
{
filename: data.filename,
height: data.height,
isStored: true,
uploaded: true,
uploading: false,
uri: data.file_url,
big_uri: data.big_url,
width: data.width,
file_mime: data.file_mime,
file_name: data.file_name
}
)
}
//很明显, 这里UI要更新
let photoList = this.state.photoList
photoList = photoList.concat(photos)
this.setState({
photoList,
dataSource: this._dataSource.cloneWithRows(photoList),
})
this.firstFetch = false;
}
} else {
//console.log("orderPage willDisappear, other willAppear")
}
})
)
}
componentWillUnmount() {
//console.log(' componentWillUnmount');
//删除缓存目录
RNFS.unlink(this.ImgTemp)
.then(() => {
//console.log('componentWillUnmount', 'FILE DELETED');
})
// `unlink` will throw an error, if the item to unlink does not exist
.catch((err) => {
//console.log(`componentWillUnmount`, err.message);
});
}
/**
* let compressedUri = await NativeCompressedModule.compress(...); 遍历的photo对象uri赋值compressedUri
* @param AddPhotos
* @private
*/
async _getCompressedPhotos() {
let photos = this._waitForAddPhotos
for (let data of photos) {
let compressedUri = ''
if (Platform.OS == 'android') {
// uri: `file://${RNFS.ExternalDirectoryPath}/1.jpg`, //for android, test ok
compressedUri = await NativeCompressedModule.compress(data.big_uri, this.ImgTemp, data.width / 2, data.height / 2)
compressedUri = `file://` + compressedUri
//console.log(`compressedUri:`, compressedUri)
} else {
// uri: RNFS.DocumentDirectoryPath + '/1.jpg', //for ios, test ok
compressedUri = await NativeCompressedModule.compress(data.big_uri, this.ImgTemp, data.width / 2, data.height / 2)
}
//重设uri
data.uri = compressedUri
}
return photos
}
async _initCustomData() {
this._token = await getToken()
this._deviceID = await getDeviceID()
this._data = await this.gZip({
data: {
iType: constants.iType.upload,
deviceId: this._deviceID,
token: this._token,
}
})
}
/*
* <Modal
animationType={"none"}
transparent={true}
visible={this.state.modalVisible}
onRequestClose={() => {this.setState({modalVisible:false})}}>
<View style={{flex:1,justifyContent:'center',alignItems:'center',
backgroundColor:constants.UIInActiveColor}}>
<View
style={{width:deviceWidth,height:Platform.OS == 'ios' ? 64 : 56
,backgroundColor:'black',flexDirection:'row',position:'absolute',top:0,
justifyContent:'center',alignItems: 'center',paddingTop:10}}>
<TouchableOpacity
style={{flex:1,paddingLeft:20}}
onPress={()=>this.setState({modalVisible:false})}>
<Icon
name={'ios-arrow-back'}
size={constants.IconSize}
color='white'
/>
</TouchableOpacity>
<View
style={{flex:4}}
/>
<TouchableOpacity
style={{flex:1,alignItems:'flex-end',paddingRight:20,}}
onPress={()=>{
this._removeFromUploadQuene(this.state.showUrl)
}}>
<Icon
name="ios-trash"
size={constants.IconSize}
color='white'
/>
</TouchableOpacity>
</View>
<ImageZoom cropWidth={deviceWidth+100}
cropHeight={deviceWidth+100}
imageWidth={deviceWidth}
imageHeight={deviceWidth}>
<Image
source={{uri: this.state.showUrl}}
style={{width:deviceWidth,height:deviceWidth, position: 'relative',margin: 5, }}/>
</ImageZoom>
</View>
</Modal>
* */
render() {
return (
<View style={styles.container}>
<ImageZoomModal
ref={ component => this._ImageZoomModal = component }
PhotoList={this.props.showList}
DeletePhoto={this._removeFromUploadQuene.bind(this)}
showDeleteButton={true}
/>
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderRow}
contentContainerStyle={styles.listStyle}
enableEmptySections={true}
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}/>
<View
style={{height:40,marginLeft:constants.MarginLeftRight,marginRight:constants.MarginLeftRight,
borderRadius:30,flexDirection:'row',justifyContent:'flex-start',
alignItems:'stretch',backgroundColor:constants.UIActiveColor,marginBottom:10}}>
<TouchableOpacity
style={{flex:1,justifyContent:'center',alignItems:'center',}}
onPress={()=>{
this._pickCamera()
}}>
<Text
style={{fontSize:17,color:'white'}}>
拍照
</Text>
</TouchableOpacity>
<View style={{backgroundColor:'white',width:StyleSheet.hairlineWidth}}/>
<TouchableOpacity
style={{flex:1,justifyContent:'center',alignItems:'center',}}
onPress={()=>{
this._pickMultiple()
}}>
<Text
style={{fontSize:17,color:'white'}}>
我的相册
</Text>
</TouchableOpacity>
</View>
{
// <Button
// touchableType={Button.constants.touchableTypes.highlight}
// underlayColor={constants.UIInActiveColor}
// style={styles.buttonStyle}
// textStyle={{fontSize: 17, color: 'white'}}
// onPress={()=>{
// this.props.navigator.push({
// title: '相机胶卷',
// component: PicturePicker,
// passProps: {
// maxiumUploadImagesCount,
// currentUploadImagesCount: this.state.photoList.length,
// waitForAddToUploadQuene: this._waitForAddToUploadQuene,
// ids:this._ids,
// //addToUploadQuene: this._addToUploadQuene
// }
// })
//
//}}>
// <Icon
// name='md-add' // 图标
// size={30}
// color={'#ffffff'}/>
// 上传图片
// </Button>
}
<Toast
ref={ component => this._toast = component }
marginTop={64}>
</Toast>
<LoadingSpinnerOverlay
ref={ component => this._modalLoadingSpinnerOverLay = component }/>
</View>
);
}
_pickMultiple() {
if(Platform.OS == 'ios') {
ImagePicker.openPicker({
multiple: true,
maxFiles: maxiumUploadImagesCount-this.props.showList.length-this._uploadingXhrCacheList.length-this._waitForUploadQuene.length,
loadingLabelText:'加载中...'
}).then(images => {
//console.log(images);
//this.setState({
// cameraModalVisible: false
//})
if (!images || images.length == 0) {
return;
}
let Uris = []
for (let data of this._ids) {
Uris.push(data.big_uri)
}
//console.log(`Uris:`, Uris)
let selected = [];
for (let i = images.length - 1; i >= 0; i--) {
let data = images[i]
if (Uris.indexOf(data.path) == -1) {
//console.log(`Uris_data:`, data)
//console.log(`Uris:`, Uris)
data.big_uri = data.path
data.uri = data.path
data.file_url = data.path
data.big_url = data.path
data.uploaded = false
data.uploading = true
selected.push(data)
}
}
//this.props.waitForAddToUploadQuene(this.state.selected)
this._waitForAddToUploadQuene(selected)
/* if (this._waitForAddPhotos && this._waitForAddPhotos.length > 0) {
//setTimeout(() => {
//@todo async this._getCompressedPhotos 返回photos数组, 遍历this._waitForAddPhotos {let compressedUri = await NativeCompressedModule.compress(...); 遍历的photo对象uri赋值compressedUri }
//this._getCompressedPhotos().then((photos)=>{
//this._addToUploadQuene(photos)
//})
this._addToUploadQuene(this._waitForAddPhotos)
this._waitForAddPhotos = null
//}, 300)
}*/
//this.props.isUploading = false
}).catch(()=> {
//this.setState({
// cameraModalVisible: false
//})
//this.props.isUploading = false
})
}else{
//android cameraroll
this.props.navigator.push({
title: '相机胶卷',
component: PicturePicker,
passProps: {
maxiumUploadImagesCount,
currentUploadImagesCount: this.state.photoList.length,
waitForAddToUploadQuene: this._waitForAddToUploadQuene,
ids:this._ids,
//addToUploadQuene: this._addToUploadQuene
}
})
}
}
_pickCamera() {
ImagePicker.openCamera({
width: deviceWidth,
height: (deviceWidth / 3) * 4,
cropping: true
}).then(image => {
//this.setState({
// cameraModalVisible: false
//})
let Uris = []
for (let data of this._ids) {
Uris.push(data.big_uri)
}
//console.log(`Uris:`, Uris)
let selected = []
//console.log(`Uris_image:`, image)
//console.log(`Uris:`, Uris)
let data = image
data.big_uri = image.path
data.uri = image.path
data.file_url = image.path
data.big_url = image.path
data.uploaded= false
data.uploading= true
selected.push(image)
this._waitForAddToUploadQuene(selected)
/*if (this._waitForAddPhotos && this._waitForAddPhotos.length > 0) {
this._addToUploadQuene(this._waitForAddPhotos)
this._waitForAddPhotos = null
}*/
}).catch(()=> {
//this.setState({cameraModalVisible: false})
})
}
_showBigUrl(url) {
//this.setState({showUrl: url, modalVisible: true})
this._ImageZoomModal.ShowPhoto(url)
}
_renderRow = (rowData, sectionID, rowID) => {
let width = height = deviceWidth / 3
if (!rowData.file_mime || rowData.file_mime.indexOf('image/') > -1) {
return (
<View
key={`key${rowID}img`}
style={[styles.itemViewStyle,{width:width, height:height,}]}>
<TouchableOpacity
onPress={this._showBigUrl.bind(this,rowData.big_uri)}
style={{flex: 1,}}>
<Image
source={{uri: rowData.big_uri}}
style={{flex: 1, position: 'relative',margin: 5, }}>
{
rowData.uploading ? <View
style={{flex: 1, backgroundColor: 'rgba(160, 160, 160, 0.5)', justifyContent: 'center', alignItems: 'center',}}>
<ActivityIndicator
animating={true}
color={'#fff'}
size={'small'}/>
<Text
style={{color: '#fff', padding: 5, fontSize: 14,}}>{rowData.uploadProgress ? Math.floor(rowData.uploadProgress * 100) : 0}%</Text>
</View> : null
}
{
rowData.uploadError ? <View
style={{flex: 1, backgroundColor: 'rgba(160, 160, 160, 0.7)', justifyContent: 'center', alignItems: 'center',}}>
<Text
style={{color: '#fff', padding: 5, fontSize: 14,}}>上传失败</Text>
</View> : null
}
<TouchableOpacity
style={{position:'absolute',top:0,right:0, backgroundColor: 'transparent',}}
onPress={this._removeFromUploadQuene.bind(this, rowData.uri)}>
<Icon
name='ios-remove-circle' // 图标
size={constants.IconSize}
color={constants.UIActiveColor}/>
</TouchableOpacity>
</Image>
</TouchableOpacity>
</View>
)
} else {
if (rowData.file_mime.indexOf('pdf') > -1) {
return (
<View
key={`${rowID}`}
style={{width:width,height:height}}>
<Image
key={`${rowID}`}
style={{width:width-25,height:height-25}}
source={pdf}>
<TouchableOpacity
style={{position:'absolute',top:0,right:0, backgroundColor: 'transparent',}}
onPress={this._removeFromUploadQuene.bind(this, rowData.uri)}>
<Icon
name='md-close-circle' // 图标
size={constants.IconSize}
color={constants.UIActiveColor}/>
</TouchableOpacity>
</Image>
<Text
style={{fontSize:14,color:constants.LabelColor}}
numberOfLines={1}>
{rowData.file_name}
</Text>
</View>
)
} else if (rowData.file_mime.indexOf('word') > -1) {
return (
<View
key={`${rowID}`}
style={{width:width,height:height}}>
<Image
key={`${rowID}`}
style={{width:width-25,height:height-25}}
source={doc}>
<TouchableOpacity
style={{position:'absolute',top:0,right:0, backgroundColor: 'transparent',}}
onPress={this._removeFromUploadQuene.bind(this, rowData.uri)}>
<Icon
name='md-close-circle' // 图标
size={constants.IconSize}
color={constants.UIActiveColor}/>
</TouchableOpacity>
</Image>
<Text
style={{fontSize:14,color:constants.LabelColor}}
numberOfLines={1}>
{rowData.file_name}
</Text>
</View>
)
} else if (rowData.file_mime.indexOf('excel') > -1) {
return (
<View
key={`${rowID}`}
style={{width:width,height:height}}>
<Image
key={`${rowID}`}
style={{width:width-25,height:height-25}}
source={excel}>
<TouchableOpacity
style={{position:'absolute',top:0,right:0, backgroundColor: 'transparent',}}
onPress={this._removeFromUploadQuene.bind(this, rowData.uri)}>
<Icon
name='md-close-circle' // 图标
size={constants.IconSize}
color={constants.UIActiveColor}/>
</TouchableOpacity>
</Image>
<Text
style={{fontSize:14,color:constants.LabelColor}}
numberOfLines={1}>
{rowData.file_name}
</Text>
</View>
)
} else {
return (
<View
key={`${rowID}`}
style={{width:width,height:height}}>
<Image
style={{width:width-25,height:height-25,}}
source={file}>
<TouchableOpacity
style={{position:'absolute',top:0,right:0, backgroundColor: 'transparent',}}
onPress={this._removeFromUploadQuene.bind(this, rowData.uri)}>
<Icon
name='ios-remove-circle' // 图标
size={constants.IconSize}
color={constants.UIActiveColor}/>
</TouchableOpacity>
</Image>
<Text
style={{fontSize:14,color:constants.LabelColor}}
numberOfLines={1}>
{rowData.file_name}
</Text>
</View>
)
}
}
}
componentWillUnmount() {
//结束正在上传中的线程
this._uploadingXhrCacheList.forEach(xhrCache => {
let { xhr, } = xhrCache
if (xhr.status != 200 || xhr.readyState != 4) {
xhr.abort()
}
})
}
_waitForAddToUploadQuene = (photos) => {
this._waitForAddPhotos = photos;
NativeAppEventEmitter.emit('needstart.uploadphoto.setstate')
// console.log('this._waitForAddPhotos:',this._waitForAddPhotos)
}
_addToUploadQuene = (photos) => {
let photoList = this.state.photoList
//控制上传集合长度
let num=maxiumUploadImagesCount-photoList.length
if(photos.length>num&&num!=0){
photos.splice(num-1,photos.length-num);
}else if(num==0){
this._toast.show({
position: Toast.constants.gravity.center,
duration: 255,
children: '已达到上传文件上限'
})
return
}
//console.log(`_addToUploadQuene`, photos)
for (let photo of photos) {
let uploadTask = {
uri: photo.big_uri, //用uri来做唯一性
init: this._upload.bind(this, photo), //将上传方法对象赋值给上传任务
}
this._waitForUploadQuene.push(uploadTask) //将上传任务加入待上传队列
}
//很明显, 这里UI要更新
// console.log(`this._waitForUploadQuene`, this._waitForUploadQuene.length)
photoList = photoList.concat(photos)
this.setState({
photoList,
dataSource: this._dataSource.cloneWithRows(photoList),
}, () => {
this._startUploadQuene() //启动一次上传队列
})
}
_removeFromUploadQuene = (uri) => {
if(this.showDelete){
return
}
this.showDelete=true
Alert.alert('温馨提醒', '确定删除吗?', [
{
text: '取消', onPress: ()=> {
this.showDelete=false
}
},
{
text: '确定', onPress: ()=> {
//先看待waitForUploadQuene上传队列中是否存在, 存在直接移除队列中的这个对象, 阻止后续的上传
let uploadTaskIndex = this._waitForUploadQuene.findIndex(uploadTask => {
return uri == uploadTask.uri
})
// console.log(`this._waitForUploadQuene:`+this._waitForUploadQuene.length)
if(uploadTaskIndex!=-1) {
this._waitForUploadQuene.splice(uploadTaskIndex, 1)
}
// console.log(`this._waitForUploadQuene.splice:`+this._waitForUploadQuene.length)
//再看uploadingXhrCacheList中是否存在(会包含上传失败的xhr), 存在就移除, 这个list的长度会影响当前的上传可用线程数
let xhrCache = this._uploadingXhrCacheList.find((xhrCache) => {
return uri == xhrCache.uri
})
let xhr = xhrCache && xhrCache.xhr
if (xhr && (xhr.status != 200 || xhr.readyState != 4)) {
xhr.abort()
this._uploadingXhrCacheList.splice(this._uploadingXhrCacheList.indexOf(xhrCache),1)
}
//遍历ids如果包含,删除id
for (let data of this._ids) {
if (data.uri == uri) {
//console.log(`ids_delete${data.uri}:`, data.id)
this._ids.splice(this._ids.indexOf(data), 1)
break
}
}
//根据photoIndex, 删除photoList, 并更新state
let { photoList, } = this.state
let photoIndex = photoList.findIndex((photo) => {
return photo.uri == uri
})
photoList.splice(photoIndex, 1)
for (let data of this.props.showList) {
if (data.file_url == uri) {
this.props.showList.splice(this.props.showList.indexOf(data), 1)
break;
}
}
// this._startUploadQuene() // 启动一次上传队列
this.setState({
photoList,
dataSource: this._dataSource.cloneWithRows(photoList),
//modalVisible:false
}, () => {
this._startUploadQuene() //启动一次上传队列
})
this._ImageZoomModal.setState({modalVisible: false})
this.showDelete=false
}
},
])
}
_startUploadQuene() {
//启动上传队列, 会计算可用线程数, 并根据线程数执行对应的上传任务, 并将各个上传任务的xhr对象缓存
let restUploadNum = maxiumXhrNums - this._uploadingXhrCacheList.length
if (restUploadNum <= 0) {
return
}
// console.log(`_startUploadQuene photoList ->`, this.state.photoList)
// console.log(`this._waitForUploadQuene.length:`, this._waitForUploadQuene.length)
let shiftNum = restUploadNum <= this._waitForUploadQuene.length ? restUploadNum : this._waitForUploadQuene.length
console.log(`shiftNum:`, shiftNum)
for (let i = 0; i < shiftNum; i++) {
//console.log(`i = ${i}, shiftNum = ${shiftNum}`)
let uploadTask = this._waitForUploadQuene.shift() //将待上传队列当前第一项任务对象从队列中取出
let xhrCache = uploadTask.init() //执行上传任务
//console.log(`_startUploadQuene xhrCache -> `, xhrCache)
this._uploadingXhrCacheList.push(xhrCache) //缓存该上传任务的xhr对象
}
//console.log('end this.state.photoList', this.state.photoList)
//console.log('end this.state.dataSource', this.state.dataSource)
}
_upload(uploadPhoto) {
//console.log(`_upload uploadPhoto.uri = `, uploadPhoto.uri)
/**
* 处理 S sign
*/
let options = {
method: 'post',
url: constants.api.service,
data: this._data,
//data: {
// iType: constants.iType.upload,
// deviceId: this._deviceID,
// token: this._token,
//}
}
//options.data = await this.gZip(options)
//console.log(`_fetch_sendCode options:`, options)
/**
* S sign处理完成
* @type {XMLHttpRequest}
*/
//console.log(`_upload photoList photoIndex`, photoList, photoIndex)
let xhr = new XMLHttpRequest();
xhr.onerror = () => {
//console.log('onerror');
//console.log('Status ', xhr.status);
//console.log('Error ', xhr.responseText);
let photoList = this._handlePhotoList({uploadPhoto, eventName: 'onerror'})
this.setState({
photoList,
dataSource: this._dataSource.cloneWithRows(photoList),
});
//let uploadingXhrCacheIndex = this._uploadingXhrCacheList.findIndex((xhrCache) => {
// return uploadPhoto.uri == xhrCache.uri
//})
//this._uploadingXhrCacheList.splice(uploadingXhrCacheIndex, 1)
//
//let photoIndex = this.state.photoList.findIndex((photo) => {
// return uploadPhoto.uri == photo.uri
//})
//let photo = this.state.photoList[ photoIndex ]
//photo.uploading = false
//photo.uploadError = true
//this.setState({
// photoList: [...photoList.slice(0, photoIndex), photo, ...photoList.slice(photoIndex + 1, photoList.length)],
// dataSource: this._dataSource.cloneWithRows(photoList),
//});
this._startUploadQuene() //再次启动上传队列(因为this._uploadingXhrCacheList的length有变化了)
};
xhr.ontimeout = () => {
//console.log('ontimeout');
//console.log('Status ', xhr.status);
//console.log('Response ', xhr.responseText);
let photoList = this._handlePhotoList({uploadPhoto, eventName: 'ontimeout'})
this.setState({
photoList,
dataSource: this._dataSource.cloneWithRows(photoList),
});
//let uploadingXhrCacheIndex = this._uploadingXhrCacheList.findIndex((xhrCache) => {
// return uploadPhoto.uri == xhrCache.uri
//})
//this._uploadingXhrCacheList.splice(uploadingXhrCacheIndex, 1)
//
//let photoIndex = this.state.photoList.findIndex((photo) => {
// return uploadPhoto.uri == photo.uri
//})
//let photo = this.state.photoList[photoIndex]
//photo.uploading = false
//photo.uploadError = true
//this.setState({
// photoList: [...this.state.photoList.slice(0, photoIndex), photo, ...this.state.photoList.slice(photoIndex + 1, this.state.photoList.length)],
// dataSource: this._dataSource.cloneWithRows(photoList),
//});
this._startUploadQuene() //再次启动上传队列(因为this._uploadingXhrCacheList的length有变化了)
};
if (constants.development) {
//测试模式
xhr.open('post', 'http://posttestserver.com/post.php')
} else {
xhr.open('post', constants.api.service)
}
xhr.setRequestHeader('Content-Type', 'multipart/form-data')
xhr.onload = () => {
console.log(`xhr.responseText = ${xhr.responseText}`)
if (xhr.status == 200 && xhr.readyState == 4) {
//console.log(`xhr.responseText = ${xhr.responseText}`)
//处理获取的id
let eventName = 'onload'
if (constants.development) {
//开发模式
let myDate = new Date();
let id = myDate.getMilliseconds() + ''
//id加入集合
let file = {uri: uploadPhoto.big_uri, id: id}
if (this._ids.indexOf(file) == -1) {
this._ids.push(file)
//console.log(`ids:`, this._ids);
}
//url 加入到上一个页面显示照片列表,
this.props.showList.unshift({
id: id,
file_url: uploadPhoto.big_uri,
big_url: uploadPhoto.big_uri,
})
//this.props.showList.splice(this.props.showList.length-1,0,{
// id:id,
// file_url:uploadPhoto.big_uri,
// big_url:uploadPhoto.big_uri,
//})
/*this.props.showList.push({
id:id,
file_url:uploadPhoto.big_uri,
big_url:uploadPhoto.big_uri,
})*/
} else {
this.gunZip(xhr.responseText).then((response)=> {
let result = JSON.parse(response)
if (!result) {
return
}
//console.log(`xhr.result: `, result)
if (result.code == '10' && result.result) {
//console.log(`response.result:`, result.result)
//id加入集合
let file = {uri: uploadPhoto.big_uri, id: result.result.id}
if (this._ids.indexOf(file) == -1) {
this._ids.push(file)
//console.log(`ids:`, this._ids);
}
//url 加入到上一个页面显示照片列表,
this.props.showList.unshift({
id: result.result.id,
file_url: uploadPhoto.big_uri,
big_url: uploadPhoto.big_uri,
})
} else {
//id出错
//console.log(`error`, result)
eventName = 'onerror'
}
}, (error)=>console.log(`responseText:`, error))
}
let photoList = this._handlePhotoList({uploadPhoto, eventName: eventName})
this.setState({
photoList,
dataSource: this._dataSource.cloneWithRows(photoList),
});
//let uploadingXhrCacheIndex = this._uploadingXhrCacheList.findIndex((xhrCache) => {
// return uploadPhoto.uri == xhrCache.uri
//})
//this._uploadingXhrCacheList.splice(uploadingXhrCacheIndex, 1)
//
//let photoIndex = this.state.photoList.findIndex((photo) => {
// return uploadPhoto.uri == photo.uri
//})
//let photo = this.state.photoList[ photoIndex ]
//photo.uploading = false
//photo.uploaded = true
//this.setState({
// photoList: [...this.state.photoList.slice(0, photoIndex), photo, ...this.state.photoList.slice(photoIndex + 1, this.state.photoList.length)],
// dataSource: this._dataSource.cloneWithRows(photoList),
//});
this._startUploadQuene() //再次启动上传队列(因为this._uploadingXhrCacheList的length有变化了)
}
};
var formdata = new FormData();
//formdata.append('image', { ...uploadPhoto, type: 'image/jpg', name: uploadPhoto.filename }); //for android, must set type:'...'
//formdata.append('file', { ...uploadPhoto, type: 'image/jpg', name: uploadPhoto.filename }); //for android, must set type:'...'
let name = uploadPhoto.filename
if (Platform.OS == 'android') {
/* let names=uploadPhoto.uri.split('/')
name=names[names.length-1]+'.jpg'*/
name = 'android.jpg'
} else {
name = 'ios.jpg'
}
//console.log(` uploadPhoto`, uploadPhoto)
formdata.append('file', {...uploadPhoto, type: 'image/jpg', name: name}); //for android, must set type:'...'
//这里增加其他参数, 比如: itype
//console.log(`options.data.s`, options.data.s)
formdata.append('s', options.data.s);
//formdata.append("text", options.data.s);
/**
* 这里处理sign
*/
options.data.sign = this._doRSASign(options.data.s)
//console.log(` options.data.sign:`, options.data.sign)
/**
* 处理sign结束
*/
formdata.append('sign', options.data.sign);
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
//console.log(`${event.loaded} / ${event.total}`)
let photoList = this._handlePhotoList({
uploadPhoto,
eventName: 'onprogress',
loaded: event.loaded,
total: event.total,
})
this.setState({
photoList,
dataSource: this._dataSource.cloneWithRows(photoList),
});
//let photoIndex = this.state.photoList.findIndex((photo) => {
// return uploadPhoto.uri == photo.uri
//})
//let photo = this.state.photoList[ photoIndex ]
//photo.uploadProgress = event.loaded / event.total
//this.setState({
// photoList: [...this.state.photoList.slice(0, photoIndex), photo, ...this.state.photoList.slice(photoIndex + 1, this.state.photoList.length)],
// dataSource: this._dataSource.cloneWithRows(photoList),
//});
}
}
xhr.timeout = 60000 //超时60秒
//console.log(`formdata:`, formdata)
xhr.send(formdata);
let photoList = this._handlePhotoList({uploadPhoto,})
this.setState({
photoList,
dataSource: this._dataSource.cloneWithRows(photoList),
});
//let photoIndex = this.state.photoList.findIndex((photo) => {
// return uploadPhoto.uri == photo.uri
//})
//let photo = this.state.photoList[ photoIndex ]
//photo.uploading = true
//
//this.setState({
// photoList: [...this.state.photoList.slice(0, photoIndex), photo, ...this.state.photoList.slice(photoIndex + 1, this.state.photoList.length)],
// dataSource: this._dataSource.cloneWithRows(photoList),
//});
let xhrCache = {xhr, uri: uploadPhoto.uri} //用uri来做唯一性
return xhrCache
}
_doRSASign(data) {
return doSign(data)
}
_handlePhotoList({uploadPhoto, eventName, loaded, total,}) {
let uploadingXhrCacheIndex = this._uploadingXhrCacheList.findIndex((xhrCache) => {
return uploadPhoto.uri == xhrCache.uri
})
let photoIndex = this.state.photoList.findIndex((photo) => {
return uploadPhoto.uri == photo.uri
})
let photo = this.state.photoList[photoIndex]
switch (eventName) {
case 'onerror':
case 'ontimeout':
this._uploadingXhrCacheList.splice(uploadingXhrCacheIndex, 1)
photo.uploading = false
photo.uploadError = true
break;
case 'onprogress':
photo.uploadProgress = loaded / total
break;
case 'onload'://这里要传code进来判断是否成功 才设置photo.uploaded = true
this._uploadingXhrCacheList.splice(uploadingXhrCacheIndex, 1)
photo.uploading = false
photo.uploaded = true
break;
default:
photo.uploading = true
break;
}
return [...this.state.photoList.slice(0, photoIndex), photo, ...this.state.photoList.slice(photoIndex + 1, this.state.photoList.length)];
}
/*async _fetchData() {
//console.log(`upload_fetchData`)
try {
let token = await getToken()
let deviceID = await getDeviceID()
let options = {
method: 'post',
url: constants.api.service,
data: {
iType: constants.iType.uploadImageList,
id: this.state.service_id,
deviceId: deviceID,
token: token,
}
}
options.data = await this.gZip(options)
//console.log(`_fetchData options:`, options)
let resultData = await this.fetch(options)
let result = await this.gunZip(resultData)
if (!result) {
this._toast.show({
position: Toast.constants.gravity.center,
duration: 255,
children: '服务器打盹了,稍后再试试吧'
})
return
}
result = JSON.parse(result)
//console.log('gunZip:', result)
if (!result) {
this._toast.show({
position: Toast.constants.gravity.center,
duration: 255,
children: '服务器打盹了,稍后再试试吧'
})
return
}
if (result.code && result.code == 10) {
//console.log('token', result.result)
let photos = []
for (let data of result.result) {
//console.log('data', data)
let file = {uri: data.file_url, id: data.id}
if (this._ids.indexOf(file) == -1) {
this._ids.push(file)
//console.log(`ids:`, this._ids);
}
photos.push(
{
filename: data.filename,
height: data.height,
isStored: true,
uploaded: true,
uploading: false,
uri: data.file_url,
big_uri: data.big_url,
width: data.width,
}
)
}
//很明显, 这里UI要更新
let photoList = this.state.photoList
photoList = photoList.concat(photos)
this.setState({
photoList,
dataSource: this._dataSource.cloneWithRows(photoList),
})
} else {
this._toast.show({
position: Toast.constants.gravity.center,
duration: 255,
children: result.msg
})
}
}
catch (error) {
//console.log(error)
if (this._toast) {
this._toast.show({
position: Toast.constants.gravity.center,
duration: 255,
children: error
})
}
}
finally {
//console.log(`SplashScreen.close(SplashScreen.animationType.scale, 850, 500)`)
//SplashScreen.close(SplashScreen.animationType.scale, 850, 500)
}
}*/
}
export default TimerEnhance(AppEventListenerEnhance(XhrEnhance(UploadPage)))
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: Platform.OS == 'ios' ? 64 : 56,
backgroundColor: constants.UIBackgroundColor,
flexDirection: 'column'
},
listStyle: {
flexDirection: 'row', //改变ListView的主轴方向
flexWrap: 'wrap' //换行
},
itemViewStyle: {
//justifyContent: 'center',
//alignItems:'center', //这里要注意,如果每个Item都在外层套了一个 Touchable的时候,一定要设置Touchable的宽高
//height:150,
overflow: 'hidden',
//borderBottomWidth: StyleSheet.hairlineWidth,
//borderLeftWidth: StyleSheet.hairlineWidth,
borderColor: constants.UIInActiveColor
},
buttonStyle: {
position: 'absolute',
bottom: 10,
margin: 10,
width: deviceWidth - 20,
backgroundColor: constants.UIActiveColor,
//borderWidth: StyleSheet.hairlineWidth,
//borderColor:constants.UIActiveColor,
height: 0,
borderColor: constants.UIActiveColor,
justifyContent: 'center',
borderRadius: 30
},
viewItem: {
height: 50,
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
paddingLeft: constants.MarginLeftRight
},
line: {
marginLeft: constants.MarginLeftRight,
marginRight: constants.MarginLeftRight,
borderBottomWidth: StyleSheet.hairlineWidth,
borderColor: constants.UIInActiveColor
},
});
import {navigationBar} from '../components/NavigationBarRouteMapper'
const navigationBarRouteMapper = {
...navigationBar,
LeftButton: function (route, navigator, index, navState) {
return (
<TouchableOpacity
onPress={() => {
NativeAppEventEmitter.emit('photoUploadPage.need.navigator.pop')
}}
style={navigatorStyle.navBarLeftButton}>
<View style={navigatorStyle.navBarLeftButtonAndroid}>
<Icon
style={[navigatorStyle.navBarText, navigatorStyle.navBarTitleText,{fontSize: 30,}]}
name={'ios-arrow-back'}
size={constants.IconSize}
color={'white'}/>
</View>
</TouchableOpacity>
);
},
RightButton: function (route, navigator, index, navState) {
return (
<TouchableOpacity
onPress={() => {
//console.log(`NativeAppEventEmitter`)
NativeAppEventEmitter.emit('photoUploadPage.need.navigator.pop')
}}
style={navigatorStyle.navBarRightButton}>
<Text style={[navigatorStyle.navBarText, navigatorStyle.navBarTitleText,{fontSize:14}]}>
完成
</Text>
</TouchableOpacity>
)
}
};
|
frontend/src/System/Logs/Files/LogFiles.js | geogolem/Radarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Alert from 'Components/Alert';
import Link from 'Components/Link/Link';
import LoadingIndicator from 'Components/Loading/LoadingIndicator';
import PageContent from 'Components/Page/PageContent';
import PageContentBody from 'Components/Page/PageContentBody';
import PageToolbar from 'Components/Page/Toolbar/PageToolbar';
import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton';
import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection';
import PageToolbarSeparator from 'Components/Page/Toolbar/PageToolbarSeparator';
import Table from 'Components/Table/Table';
import TableBody from 'Components/Table/TableBody';
import { icons } from 'Helpers/Props';
import translate from 'Utilities/String/translate';
import LogsNavMenu from '../LogsNavMenu';
import LogFilesTableRow from './LogFilesTableRow';
const columns = [
{
name: 'filename',
label: translate('Filename'),
isVisible: true
},
{
name: 'lastWriteTime',
label: translate('LastWriteTime'),
isVisible: true
},
{
name: 'download',
isVisible: true
}
];
class LogFiles extends Component {
//
// Render
render() {
const {
isFetching,
items,
deleteFilesExecuting,
currentLogView,
location,
onRefreshPress,
onDeleteFilesPress,
...otherProps
} = this.props;
return (
<PageContent title={translate('LogFiles')}>
<PageToolbar>
<PageToolbarSection>
<LogsNavMenu current={currentLogView} />
<PageToolbarSeparator />
<PageToolbarButton
label={translate('Refresh')}
iconName={icons.REFRESH}
spinningName={icons.REFRESH}
isSpinning={isFetching}
onPress={onRefreshPress}
/>
<PageToolbarButton
label={translate('Delete')}
iconName={icons.CLEAR}
isSpinning={deleteFilesExecuting}
onPress={onDeleteFilesPress}
/>
</PageToolbarSection>
</PageToolbar>
<PageContentBody>
<Alert>
<div>
Log files are located in: {location}
</div>
{
currentLogView === 'Log Files' &&
<div>
{translate('TheLogLevelDefault')} <Link to="/settings/general">{translate('GeneralSettings')}</Link>
</div>
}
</Alert>
{
isFetching &&
<LoadingIndicator />
}
{
!isFetching && !!items.length &&
<div>
<Table
columns={columns}
{...otherProps}
>
<TableBody>
{
items.map((item) => {
return (
<LogFilesTableRow
key={item.id}
{...item}
/>
);
})
}
</TableBody>
</Table>
</div>
}
{
!isFetching && !items.length &&
<div>
{translate('NoLogFiles')}
</div>
}
</PageContentBody>
</PageContent>
);
}
}
LogFiles.propTypes = {
isFetching: PropTypes.bool.isRequired,
items: PropTypes.array.isRequired,
deleteFilesExecuting: PropTypes.bool.isRequired,
currentLogView: PropTypes.string.isRequired,
location: PropTypes.string.isRequired,
onRefreshPress: PropTypes.func.isRequired,
onDeleteFilesPress: PropTypes.func.isRequired
};
export default LogFiles;
|
app/scripts/SeriesListItems.js | hms-dbmi/higlass | import React from 'react';
import ContextMenuItem from './ContextMenuItem';
import { TRACKS_INFO_BY_TYPE } from './configs';
import '../styles/ContextMenu.module.scss';
/**
* Return a list of all the tracks and subtracks from
* the list of tracks
*
* @param {array} tracks: A list of tracks to go through
*/
export const getAllTracksAndSubtracks = (tracks) => {
let series = [];
// check if this is a combined track (has contents)
for (const track of tracks) {
if (track.contents) {
series = series.concat(track.contents);
} else {
series.push(track);
}
}
return series;
};
/**
* Get a list of menu items corresponding to the
* series present in a set of tracks. If any of
* the tracks a combined tracks, this function will
* return individual menu items for each of the
* combined tracks.
*
* @param {object} tracks: An array of track definitions (from the viewconf)
* @param {func} onItemMouseEnter: Event handler for mouseEnter
* @param {func} onItemMouseLeave: Event handler for mouseLeave
* @param {func} onItemClick: Event handler for mouseLeave
*
* @returns {array} A list of ReactComponents for the generated ContextMenuItems
*/
export const getSeriesItems = (
tracks,
onItemMouseEnter,
onItemMouseLeave,
onItemClick,
) => {
if (!tracks) return null;
if (window.higlassTracksByType) {
Object.keys(window.higlassTracksByType).forEach((pluginTrackType) => {
TRACKS_INFO_BY_TYPE[pluginTrackType] =
window.higlassTracksByType[pluginTrackType].config;
});
}
return getAllTracksAndSubtracks(tracks).map((x) => {
const thumbnail = TRACKS_INFO_BY_TYPE[x.type]
? TRACKS_INFO_BY_TYPE[x.type].thumbnail
: null;
const imgTag = thumbnail ? (
<div
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: thumbnail.outerHTML }}
styleName="context-menu-icon"
/>
) : (
<div styleName="context-menu-icon">
<svg />
</div>
);
return (
<ContextMenuItem
key={x.uid}
onClick={() => {
if (onItemClick) onItemClick(x.uid);
}}
onMouseEnter={(e) => {
if (onItemMouseEnter) onItemMouseEnter(e, x);
}}
onMouseLeave={(e) => {
if (onItemMouseLeave) onItemMouseLeave(e);
}}
styleName="context-menu-item"
>
{imgTag}
<span styleName="context-menu-span">
{x.options && x.options.name && x.options.name.length
? x.options.name
: x.type}
{onItemMouseEnter && onItemMouseLeave ? (
<svg styleName="play-icon">
<use xlinkHref="#play" />
</svg>
) : null}
</span>
</ContextMenuItem>
);
});
};
|
client/components/admin/DoctorPage.js | Kamill90/Dental | import React, { Component } from 'react';
import gql from 'graphql-tag';
import { graphql, compose } from 'react-apollo';
import { Link, hashHistory } from 'react-router';
import {Row, Input, Dropdown, NavItem, Button, Iconm, Modal, Collapsible, CollapsibleItem} from 'react-materialize'
import { Slider, Switch } from 'antd';
const moment = require('moment')
// import moment from 'moment';
/* main TODO:
on componentreceuiverops() create list of dates for next 30days in state. Assign to them already created
confirmed vistis and (if done) already confirm accessibility (if not) form to create one) */
/* disclaimer:
filling slider (/text) input with range of accessibility time of each doctor should results to creating
visits with status "free", with its doctorID, no user assigned. It should generete as many free visitis
as number of 30min intervals may consist between declared range for each day. So that Visits collection
should looks like that (for doctorID=1,day 10.10.2017 and accessibility between 10-12).
2 hours of accessibility results with 4 visits for this day. This is my decision and my decision is fine:
{
"data": {
"visits": [
{
"id": "59cd6f83bc77fd1e1ca8466f",
"visitDate": "10.10.2017",
"visitTime": "10:00", TO ADD
"user": null,
"status": "free",
"doctorID": "1"
},
{
"id": "59cd6f83bc77fd1e1ca8466f1",
"visitDate": "10.10.2017",
"visitTime": "10:30", TO ADD!
"user": null,
"status": "free",
"doctorID": "1"
},
{
"id": "59cd6f83bc77fd1e1ca8466f2",
"visitDate": "10.10.2017",
"visitTime": "11:00", TO ADD!
"user": null,
"status": "free",
"doctorID": "1"
},
{
"id": "59cd6f83bc77fd1e1ca8466f3",
"visitDate": "10.10.2017",
"visitTime": "11:30", TO ADD!
"user": null,
"status": "free",
"doctorID": "1"
}
]
}
} */
//queries
class DoctorPage extends Component {
constructor(props){
super(props);
/* this.state = {
"daylist":null
} */
function getDays(){
return new Promise((resolve,reject)=>{
let daylist = {};
for(var i=0; i<10; i++){
let dateKey = moment().add(i, 'days').format("YYYYMMDD");
/* let data = {
[dateKey]:[]
}
daylist.push(data); */
daylist[dateKey] = [];
}
resolve(daylist);
})
}
getDays().then(data=>{
this.setState({
"dayList": data
})
});
};
groupBy(collection, property) {
return new Promise((resolve,reject)=>{
var i = 0, val, index,
values = [], result = [], final = {};
for (; i < collection.length; i++) {
val = collection[i][property];
index = values.indexOf(val);
if (index > -1)
result[index].push(collection[i]);
else {
values.push(val);
result.push([collection[i]]);
}
}
result.map(el=>{
final[el[0].visitDay] = el
})
resolve(final);
})
};
addFreeVisits(e){
e.preventDefault();
let inputData = {
"day": e.target.name,
"start": this.state.startHour,
"number": this.state.noOfVisits
}
return new Promise((resolve,reject)=>{
let visitsArray = []
let newstart = inputData.start.replace(':','');
for(let i=0;i<inputData.number;i++){
let visitDate = moment(`${inputData.day} ${newstart}`).add(i*45,'m').format("YYYYMMDD hhmm");
visitsArray.push(visitDate);
}
resolve(visitsArray);
}).then(data=>{
data.map(el=>{
console.log(el);
this.props.mutate({
"variables": {
"visitDate":el,
"doctorID":this.props.data.doctorByAdmin.id
}
}) .then(()=>{alert("succes")})
.catch((err)=>{alert(err)})
})
})
};
handleChange(e){
this.setState({
[e.target.name]: e.target.value
})
};
componentDidUpdate(){
console.log(this.state);
}
componentWillReceiveProps(nextProps){
this.groupBy(nextProps.data.doctorByAdmin.visit,"visitDay")
.then(data=>{
let newState = Object.assign({}, this.state.dayList, data)
this.setState({
"dayList": newState
})
});
};
VisitsList(){
let data = this.state.dayList;
return Object.keys(data).map((key,index)=>{
// console.log(key,data[key])
return(
<div key={index}>
{`${key}, no of visits: ${data[key].length}`}
{(data[key].length == 0)?
<div>
<div className="col s6">
<label> No of visits
<input
type="number"
name="noOfVisits"
onChange={this.handleChange.bind(this)}
/>
</label>
</div>
<div className="col s6">
<label> start hour
<input
type="time"
name="startHour"
onChange={this.handleChange.bind(this)}
/>
</label>
</div>
<a
name={key}
className="waves-effect waves-light btn"
onClick={this.addFreeVisits.bind(this)}>
send accessibility
</a>
</div> :
<span> disable </span>
}
</div>
)
})
};
render(){
if(this.props.data.loading){
return(
<div>
loading
</div>
)
}
else if(this.props.data.error){
let errMsg = JSON.stringify(this.props.data.error);
return(
<h4>{errMsg}</h4>
)
}
else {
console.log(this.props.data)
// console.log("stan", this.state);
let DoctorData = this.props.data.doctorByAdmin;
return(
<div>
<h2> Hello, {DoctorData.name}!</h2>
<h4>here is place where you can fill
your story, photo and most important:
your accessibility so that patients can schedule a visit
</h4>
{/* //add profile description */}
<div className="row">
<div className="input-field col s12">
<textarea id="textarea1" className="materialize-textarea" data-length="120"></textarea>
<label htmlFor="textarea1">Describe yourself</label>
</div>
</div>
{/* //add profile photo */}
<div className="file-field input-field">
<div className="btn">
<span>Add photo</span>
<input type="file"/>
</div>
<div className="file-path-wrapper">
<input className="file-path validate" type="text"/>
</div>
</div>
{/* //add accessibility */}
{this.VisitsList()}
</div>
)}
}
};
const fechtDoctor=gql`
query fetchDoctor($DoctorId: String! ){
doctorByAdmin(adminID: $DoctorId){
id
name
ranking
adminID
visit {
visitDate
visitDay
id
}
}
}`;
const createVisit=gql`
mutation createVisit(
$visitDate: String!
$doctorID: String!
)
{
createVisit(visitDate:$visitDate,doctorID:$doctorID){
createDate
visitDay
}
}`
/* export default graphql(fechtDoctor,
{options:(props) => {
return {variables: {
DoctorId: props.params.id
}}
}
})(DoctorPage); */
export default compose(
graphql(createVisit),
graphql(fechtDoctor,
{options:(props) => {
return {variables: {
DoctorId: props.params.id
}}
}
})
)(DoctorPage); |
node_modules/react-router/es6/Redirect.js | ajames72/MovieDBReact | import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils';
import { formatPattern } from './PatternUtils';
import { falsy } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes;
var string = _React$PropTypes.string;
var object = _React$PropTypes.object;
/**
* A <Redirect> is used to declare another URL path a client should
* be sent to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration
* and are traversed in the same manner.
*/
var Redirect = React.createClass({
displayName: 'Redirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element) {
var route = _createRouteFromReactElement(element);
if (route.from) route.path = route.from;
route.onEnter = function (nextState, replace) {
var location = nextState.location;
var params = nextState.params;
var pathname = void 0;
if (route.to.charAt(0) === '/') {
pathname = formatPattern(route.to, params);
} else if (!route.to) {
pathname = location.pathname;
} else {
var routeIndex = nextState.routes.indexOf(route);
var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1);
var pattern = parentPattern.replace(/\/*$/, '/') + route.to;
pathname = formatPattern(pattern, params);
}
replace({
pathname: pathname,
query: route.query || location.query,
state: route.state || location.state
});
};
return route;
},
getRoutePattern: function getRoutePattern(routes, routeIndex) {
var parentPattern = '';
for (var i = routeIndex; i >= 0; i--) {
var route = routes[i];
var pattern = route.path || '';
parentPattern = pattern.replace(/\/*$/, '/') + parentPattern;
if (pattern.indexOf('/') === 0) break;
}
return '/' + parentPattern;
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Redirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default Redirect; |
blueprints/view/files/__root__/views/__name__View/__name__View.js | dfalling/todo | import React from 'react'
type Props = {
};
export class <%= pascalEntityName %> extends React.Component {
props: Props;
render () {
return (
<div></div>
)
}
}
export default <%= pascalEntityName %>
|
packages/mineral-ui-icons/src/IconLocalPizza.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconLocalPizza(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M12 2C8.43 2 5.23 3.54 3.01 6L12 22l8.99-16C18.78 3.55 15.57 2 12 2zM7 7c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2zm5 8c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
</g>
</Icon>
);
}
IconLocalPizza.displayName = 'IconLocalPizza';
IconLocalPizza.category = 'maps';
|
actor-apps/app-web/src/app/components/modals/Preferences.react.js | ONode/actor-platform | import React from 'react';
import Modal from 'react-modal';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import { Styles, FlatButton, RadioButtonGroup, RadioButton, DropDownMenu } from 'material-ui';
import { KeyCodes } from 'constants/ActorAppConstants';
import ActorTheme from 'constants/ActorTheme';
import PreferencesActionCreators from 'actions/PreferencesActionCreators';
import PreferencesStore from 'stores/PreferencesStore';
const appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
isOpen: PreferencesStore.isModalOpen()
};
};
@ReactMixin.decorate(IntlMixin)
class PreferencesModal extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = getStateFromStores();
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
}
});
PreferencesStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
PreferencesStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
onChange = () => {
this.setState(getStateFromStores());
};
onClose = () => {
PreferencesActionCreators.hide();
};
onKeyDown = event => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
render() {
let menuItems = [
{ payload: '1', text: 'English' },
{ payload: '2', text: 'Russian' }
];
if (this.state.isOpen === true) {
return (
<Modal className="modal-new modal-new--preferences"
closeTimeoutMS={150}
isOpen={this.state.isOpen}
style={{width: 760}}>
<div className="modal-new__header">
<i className="modal-new__header__icon material-icons">settings</i>
<h3 className="modal-new__header__title">
<FormattedMessage message={this.getIntlMessage('preferencesModalTitle')}/>
</h3>
<div className="pull-right">
<FlatButton hoverColor="rgba(81,145,219,.17)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onClose}
secondary={true}
style={{marginTop: -6}}/>
</div>
</div>
<div className="modal-new__body">
<div className="preferences">
<aside className="preferences__tabs">
<a className="preferences__tabs__tab preferences__tabs__tab--active">General</a>
<a className="preferences__tabs__tab">Notifications</a>
<a className="preferences__tabs__tab">Sidebar colors</a>
<a className="preferences__tabs__tab">Security</a>
<a className="preferences__tabs__tab">Other Options</a>
</aside>
<div className="preferences__body">
<div className="preferences__list">
<div className="preferences__list__item preferences__list__item--general">
<ul>
<li>
<i className="icon material-icons">keyboard</i>
<RadioButtonGroup defaultSelected="default" name="send">
<RadioButton label="Enter – send message, Shift + Enter – new line"
style={{marginBottom: 12}}
value="default"/>
<RadioButton label="Cmd + Enter – send message, Enter – new line"
//style={{marginBottom: 16}}
value="alt"/>
</RadioButtonGroup>
</li>
<li className="language">
<i className="icon material-icons">menu</i>
Language: <DropDownMenu labelStyle={{color: '#5191db'}}
menuItemStyle={{height: '40px', lineHeight: '40px'}}
menuItems={menuItems}
style={{verticalAlign: 'top', height: 52}}
underlineStyle={{display: 'none'}}/>
</li>
</ul>
</div>
<div className="preferences__list__item preferences__list__item--notifications">
<ul>
<li>
<i className="icon material-icons">notifications</i>
<RadioButtonGroup defaultSelected="all" name="notifications">
<RadioButton label="Notifications for activity of any kind"
style={{marginBottom: 12}}
value="all"/>
<RadioButton label="Notifications for Highlight Words and direct messages"
style={{marginBottom: 12}}
value="quiet"/>
<RadioButton label="Never send me notifications"
style={{marginBottom: 12}}
value="disable"/>
</RadioButtonGroup>
<p className="hint">
You can override your desktop notification preference on a case-by-case
basis for channels and groups from the channel or group menu.
</p>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</Modal>
);
} else {
return null;
}
}
}
export default PreferencesModal;
|
www/src/components/Page.js | TaitoUnited/taito-cli | import React from 'react';
import styled from '@emotion/styled';
import { media } from '../utils';
import Navigation from './Navigation';
const Page = ({ menu = null, children, ...rest }) => (
<Wrapper {...rest}>
<Main hasMenu={!!menu}>
{menu && <Menu>{menu}</Menu>}
<Content>{children}</Content>
</Main>
<Navigation />
</Wrapper>
);
const Wrapper = styled.div`
width: 100%;
min-height: 100vh;
display: flex;
flex-direction: column;
`;
const Main = styled.div`
display: flex;
flex-direction: row;
width: 100%;
overflow-x: hidden;
margin-top: 50px;
padding-left: ${props => (props.hasMenu ? 320 : 0)}px;
${media.sm`
padding-left: 0px;
margin-top: 54px;
`}
`;
const Menu = styled.div`
position: fixed;
top: 50px;
left: 0px;
height: calc(100vh - 50px);
overflow-y: auto;
`;
const Content = styled.div`
flex: 1;
width: 100%;
padding: 16px;
max-width: 900px;
margin: 0px auto;
a:not(.autolink-a) {
color: ${props => props.theme.primary[800]};
background-color: ${props => props.theme.primary[100]};
border-bottom: 1px solid rgba(0, 0, 0, 0.2);
text-decoration: none;
&:hover {
background-color: ${props => props.theme.primary[200]};
}
}
hr {
margin-top: 24px;
margin-bottom: 24px;
border: none;
height: 1px;
background-color: ${props => props.theme.grey[300]};
}
ul {
list-style: disc;
padding-left: 24px;
}
ul > li {
margin-top: 8px;
}
blockquote {
margin: 0;
padding: 8px 16px;
background-color: ${props => props.theme.primary[100]};
border-left: 8px solid ${props => props.theme.primary[500]};
color: ${props => props.theme.primary[700]};
border-radius: 2px;
}
`;
export default Page;
|
ui/components/not_found.js | danjac/random-movies | import React from 'react';
import { Well } from 'react-bootstrap';
export default function NotFound() {
return (
<div className="container">
<Well>Sorry, you are in the wrong place.</Well>
</div>
);
}
|
app/containers/NoMatch.js | rhoffmann8/redux-jaca | import React, { Component } from 'react';
import Helmet from 'react-helmet';
class NoMatch extends Component {
render() {
return (
<div>
<Helmet title='Not Found' />
Page was not found
</div>
)
}
}
export default NoMatch; |
src/Parser/Priest/Holy/Modules/PriestCore/EnduringRenewal.js | hasseboulen/WoWAnalyzer | import React from 'react';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import SpellIcon from 'common/SpellIcon';
import { formatPercentage, formatNumber } from 'common/format';
// dependencies
import Combatants from 'Parser/Core/Modules/Combatants';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import Analyzer from 'Parser/Core/Analyzer';
import { ABILITIES_THAT_TRIGGER_ENDURING_RENEWAL } from '../../Constants';
class EnduringRenewal extends Analyzer {
static dependencies = {
combatants: Combatants,
}
_normalRenewDropoff = {};
_newRenewDropoff = {};
healing = 0;
refreshedRenews = 0;
secsGained = 0;
// This module will be tracking the initial application of renews, then recording
// all renew healing done to those targets after a timestamp + base duration at
// applybuff since all "refreshbuff" events for renew will be from direct heals
// (the exception would be benediction renews refreshing but I'm not sure how to
// counter that and it should be such a small portion of refreshs anyway). Thus,
// all renew healing after timestamp + baase duraation should be a result of
// Enduring Renewal
on_initialized() {
this.active = this.combatants.selected.hasTalent(SPELLS.ENDURING_RENEWAL_TALENT.id);
this._usingLegendaryLegs = this.combatants.selected.hasLegs(ITEMS.ENTRANCING_TROUSERS_OF_ANJUNA.id);
this._baseRenewLength = 15 + (this._usingLegendaryLegs ? 6 : 0);
}
// We do not track "casts" of Renew because casting Renew on an existing target
// that has renew is also a "direct heal" that triggers Enduring Renewal.
// It is up for debate whether or not direct heals from Renew should attribute
// to Enduring Renewal, but for now I will say it does.
on_byPlayer_applybuff(event) {
this.parseRenew(event); // function incase we decide to disclude manual renew refreshes
}
on_byPlayer_removebuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.RENEW.id) {
return;
}
delete this._normalRenewDropoff[event.targetID];
delete this._newRenewDropoff[event.targetID];
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.RENEW.id) {
if (event.targetID in this._normalRenewDropoff && event.timestamp > this._normalRenewDropoff[event.targetID]) {
this.healing += event.amount;
}
} else if (ABILITIES_THAT_TRIGGER_ENDURING_RENEWAL.indexOf(spellId) !== -1) {
if (event.targetID in this._newRenewDropoff) {
const remaining = (this._newRenewDropoff[event.targetID] - event.timestamp) / 1000.0;
const gain = Math.min((this._baseRenewLength + 6) - remaining, this._baseRenewLength); // be wary of pandemic but also wary of early refreshes
this._newRenewDropoff[event.targetID] = event.timestamp + (gain * 1000);
this.refreshedRenews += 1;
this.secsGained += gain;
}
} else {
}
}
parseRenew(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.RENEW.id) {
this._normalRenewDropoff[event.targetID] = event.timestamp + this._baseRenewLength * 1000;
this._newRenewDropoff[event.targetID] = event.timestamp + this._baseRenewLength * 1000;
}
}
statistic() {
const erPercHPS = formatPercentage(this.owner.getPercentageOfTotalHealingDone(this.healing));
const erHPS = formatNumber(this.healing / this.owner.fightDuration * 1000);
const erGainPerRefresh = Math.round(this.secsGained / this.refreshedRenews * 100) / 100;
//
return this.active && (
<StatisticBox
icon={<SpellIcon id={SPELLS.ENDURING_RENEWAL_TALENT.id} />}
value={`${erHPS} HPS`}
label={(
<dfn data-tip={`
Healing done on targets as a result of Enduring Renewal's refresh.
This did ${formatNumber(this.healing)} healing and was ${erPercHPS}% of your total healing.
<br/><br/>
You refreshed renews ${this.refreshedRenews} times for a total of ${formatNumber(this.secsGained)} additional seconds of Renew.
(+${erGainPerRefresh}s per refresh on average).
`}
>
Enduring Renewal
</dfn>
)}
/>
);
//
}
statisticOrder = STATISTIC_ORDER.OPTIONAL(1);
}
export default EnduringRenewal;
|
Realization/frontend/czechidm-core/src/components/advanced/RoleCompositionInfo/RoleCompositionInfo.js | bcvsolutions/CzechIdMng | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import * as Basic from '../../basic';
import { RoleCompositionManager } from '../../../redux';
import AbstractEntityInfo from '../EntityInfo/AbstractEntityInfo';
import EntityInfo from '../EntityInfo/EntityInfo';
const manager = new RoleCompositionManager();
/**
* Role composition basic information (info card).
*
* @author Vít Švanda
* @author Radek Tomiška
*/
export class RoleCompositionInfo extends AbstractEntityInfo {
getManager() {
return manager;
}
showLink() {
if (!super.showLink()) {
return false;
}
const { _permissions } = this.props;
if (!manager.canRead(this.getEntity(), _permissions)) {
return false;
}
return true;
}
/**
* Get link to detail (`url`).
*
* @return {string}
*/
getLink() {
const entity = this.getEntity();
return `/role/${ encodeURIComponent(entity.superior) }/compositions`;
}
/**
* Returns popovers title
*
* @param {object} entity
*/
getPopoverTitle() {
return this.i18n('entity.RoleComposition._type');
}
getTableChildren() {
// component are used in #getPopoverContent => skip default column resolving
return [
<Basic.Column property="label"/>,
<Basic.Column property="value"/>
];
}
/**
* Returns popover info content.
*
* @param {array} table data
*/
getPopoverContent(entity) {
return [
{
label: this.i18n('entity.RoleComposition.superior.label'),
value: (
<EntityInfo
entityType="role"
entity={ entity._embedded ? entity._embedded.superior : null }
entityIdentifier={ entity.superior }
showIcon
face="popover" />
)
},
{
label: this.i18n('entity.RoleComposition.sub.label'),
value: (
<EntityInfo
entityType="role"
entity={ entity._embedded ? entity._embedded.sub : null }
entityIdentifier={ entity.sub }
showIcon
face="popover" />
)
}
];
}
/**
* Returns entity icon (null by default - icon will not be rendered)
*
* @param {object} entity
*/
getEntityIcon() {
return 'component:business-roles';
}
}
RoleCompositionInfo.propTypes = {
...AbstractEntityInfo.propTypes,
/**
* Selected entity - has higher priority
*/
entity: PropTypes.object,
/**
* Selected entity's id - entity will be loaded automatically
*/
entityIdentifier: PropTypes.string,
/**
* Internal entity loaded by given identifier
*/
_entity: PropTypes.object,
_showLoading: PropTypes.bool
};
RoleCompositionInfo.defaultProps = {
...AbstractEntityInfo.defaultProps,
entity: null,
showLink: true,
face: 'link',
_showLoading: true,
};
function select(state, component) {
const { entityIdentifier, entity } = component;
let entityId = entityIdentifier;
if (!entityId && entity) {
entityId = entity.id;
}
//
return {
_entity: manager.getEntity(state, entityId),
_showLoading: manager.isShowLoading(state, null, entityId),
_permissions: manager.getPermissions(state, null, entityId)
};
}
export default connect(select)(RoleCompositionInfo);
|
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js | tayanderson/tayanderson.github.io | import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
actor-apps/app-web/src/app/components/modals/AppCacheUpdate.react.js | ruikong/actor-platform | import React from 'react';
import Modal from 'react-modal';
//import pureRender from 'pure-render-decorator';
import { Styles, FlatButton } from 'material-ui';
import AppCacheStore from 'stores/AppCacheStore';
import AppCacheActionCreators from 'actions/AppCacheActionCreators';
import { KeyCodes } from 'constants/ActorAppConstants';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
const appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
const getStateFromStores = () => {
return {
isShown: AppCacheStore.isModalOpen()
};
};
class AddContact extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = getStateFromStores();
AppCacheStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
ThemeManager.setTheme(ActorTheme);
}
componentWillUnmount() {
AppCacheStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
render() {
return (
<Modal className="modal-new modal-new--update"
closeTimeoutMS={150}
isOpen={this.state.isShown}
style={{width: 400}}>
<div className="modal-new__body">
<h1>Update available</h1>
<h3>New version of Actor Web App available.</h3>
<p>It's already downloaded to your browser, you just need to reload tab.</p>
</div>
<footer className="modal-new__footer text-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Cancel"
onClick={this.onClose}
secondary={true} />
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Reload"
onClick={this.onConfirm}
secondary={true} />
</footer>
</Modal>
);
}
onClose = () => {
AppCacheActionCreators.closeModal();
}
onConfirm = () => {
AppCacheActionCreators.confirmUpdate();
}
onChange = () => {
this.setState(getStateFromStores());
}
onKeyDown = (event) => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
}
}
export default AddContact;
|
modules/Lifecycle.js | rubengrill/react-router | import React from 'react'
import invariant from 'invariant'
const { object } = React.PropTypes
/**
* The Lifecycle mixin adds the routerWillLeave lifecycle method to a
* component that may be used to cancel a transition or prompt the user
* for confirmation.
*
* On standard transitions, routerWillLeave receives a single argument: the
* location we're transitioning to. To cancel the transition, return false.
* To prompt the user for confirmation, return a prompt message (string).
*
* During the beforeunload event (assuming you're using the useBeforeUnload
* history enhancer), routerWillLeave does not receive a location object
* because it isn't possible for us to know the location we're transitioning
* to. In this case routerWillLeave must return a prompt message to prevent
* the user from closing the window/tab.
*/
const Lifecycle = {
contextTypes: {
history: object.isRequired,
// Nested children receive the route as context, either
// set by the route component using the RouteContext mixin
// or by some other ancestor.
route: object
},
propTypes: {
// Route components receive the route object as a prop.
route: object
},
componentDidMount() {
invariant(
this.routerWillLeave,
'The Lifecycle mixin requires you to define a routerWillLeave method'
)
const route = this.props.route || this.context.route
invariant(
route,
'The Lifecycle mixin must be used on either a) a <Route component> or ' +
'b) a descendant of a <Route component> that uses the RouteContext mixin'
)
this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute(
route,
this.routerWillLeave
)
},
componentWillUnmount() {
if (this._unlistenBeforeLeavingRoute)
this._unlistenBeforeLeavingRoute()
}
}
export default Lifecycle
|
docs/src/app/TutorialsPage.js | mit-cml/iot-website-source | import React from 'react';
import Title from 'react-title-component';
import MarkdownElement from './MarkdownElement';
import Tutorials from './Tutorials';
import TutorialsText from './Tutorials';
const TutorialsPage = () => (
<div>
<Title render={(previousTitle) => `Tutorials - ${previousTitle}`} />
<MarkdownElement text={TutorialsText} />
<Tutorials />
</div>
);
export default TutorialsPage;
|
frontend/src/components/app.js | ThaTiemsz/jetski | import React, { Component } from 'react';
import {globalState} from '../state';
import Topbar from './topbar';
import Dashboard from './dashboard';
import Login from './login';
import GuildOverview from './guild_overview';
import GuildConfigEdit from './guild_config_edit';
import GuildInfractions from './guild_infractions';
import GuildStats from './guild_stats';
import Archive from './archive';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
class AppWrapper extends Component {
constructor() {
super();
this.state = {
ready: globalState.ready,
user: globalState.user,
};
if (!globalState.ready) {
globalState.events.on('ready', () => {
this.setState({
ready: true,
});
});
globalState.events.on('user.set', (user) => {
this.setState({
user: user,
});
});
globalState.init();
}
}
render() {
if (!this.state.ready) {
return <div><h1>Loading...</h1></div>;
}
if (this.state.ready && !this.state.user) {
return <Redirect to='/login' />;
}
return (
<div id="wrapper">
<Topbar />
<div id="page-wrapper">
<this.props.view params={this.props.params} />
</div>
</div>
);
}
}
function wrapped(component) {
function result(props) {
return <AppWrapper view={component} params={props.match.params} />;
}
return result;
}
export default function router() {
return (
<BrowserRouter>
<Switch>
<Route exact path='/login' component={Login} />
<Route exact path='/guilds/:gid/stats' component={wrapped(GuildStats)} />
<Route exact path='/guilds/:gid/infractions' component={wrapped(GuildInfractions)} />
<Route exact path='/guilds/:gid/config/:timestamp?' component={wrapped(GuildConfigEdit)} />
<Route exact path='/guilds/:gid' component={wrapped(GuildOverview)} />
<Route exact path='/' component={wrapped(Dashboard)} />
<Route exact path='/api/archive/:aid.html' component={Archive} />
</Switch>
</BrowserRouter>
);
}
|
packages/lore-tutorial/templates/es6/step16/src/components/CreateButton.js | lore/lore | import React from 'react';
export default class CreateButton extends React.Component {
getStyles() {
return {
createButton: {
position: 'absolute',
top: '25px',
right: '15px',
zIndex: 1000,
borderRadius: '100px',
outline: 'none'
}
}
}
onClick() {
function createTweet(params) {
console.log(params);
}
lore.dialog.show(function() {
return lore.dialogs.tweet.create({
onSubmit: createTweet
});
})
}
render() {
const styles = this.getStyles();
return (
<button
type="button"
className="btn btn-primary btn-lg"
style={styles.createButton}
onClick={this.onClick}>
+
</button>
);
}
}
|
app/components/RoomChat.js | LetSpotify/letspotify-client | import React, { Component } from 'react';
import styles from './RoomChat.styl';
import { MdShare, MdSettings, MdSend } from 'react-icons/lib/md';
import ReactTooltip from 'react-tooltip';
import CopyToClipboard from 'react-copy-to-clipboard';
export default class RoomChat extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
console.log(this.refs.message.value);
this.refs.message.value = "";
}
render() {
return (
<div className={styles.roomChat}>
<div className={styles.chatStatus}>
<div className={styles.masterInfo}></div>
<div className={styles.roomName}></div>
<div className={styles.controls}>
<CopyToClipboard text={this.props.curRoomID}>
<MdShare data-tip data-delay-show='200' data-for='share'/>
</CopyToClipboard>
<ReactTooltip id='share' place='bottom' effect='solid'>
<span>Copy ID</span>
</ReactTooltip>
<MdSettings />
</div>
</div>
<div className={styles.chatContent}>
<span>Chat room comming soon...</span>
</div>
<form onSubmit={this.handleSubmit} className={styles.chatInput}>
<input ref='message' placeholder='New message'></input>
<MdSend onClick={this.handleSubmit} />
</form>
</div>
);
}
}
|
app/javascript/mastodon/features/home_timeline/index.js | imas/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { expandHomeTimeline } from '../../actions/timelines';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ColumnSettingsContainer from './containers/column_settings_container';
import { Link } from 'react-router-dom';
import { fetchAnnouncements, toggleShowAnnouncements } from 'mastodon/actions/announcements';
import AnnouncementsContainer from 'mastodon/features/getting_started/containers/announcements_container';
import classNames from 'classnames';
import IconWithBadge from 'mastodon/components/icon_with_badge';
const messages = defineMessages({
title: { id: 'column.home', defaultMessage: 'Home' },
show_announcements: { id: 'home.show_announcements', defaultMessage: 'Show announcements' },
hide_announcements: { id: 'home.hide_announcements', defaultMessage: 'Hide announcements' },
});
const mapStateToProps = state => ({
hasUnread: state.getIn(['timelines', 'home', 'unread']) > 0,
isPartial: state.getIn(['timelines', 'home', 'isPartial']),
hasAnnouncements: !state.getIn(['announcements', 'items']).isEmpty(),
unreadAnnouncements: state.getIn(['announcements', 'items']).count(item => !item.get('read')),
showAnnouncements: state.getIn(['announcements', 'show']),
});
export default @connect(mapStateToProps)
@injectIntl
class HomeTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
intl: PropTypes.object.isRequired,
hasUnread: PropTypes.bool,
isPartial: PropTypes.bool,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasAnnouncements: PropTypes.bool,
unreadAnnouncements: PropTypes.number,
showAnnouncements: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('HOME', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
this.props.dispatch(expandHomeTimeline({ maxId }));
}
componentDidMount () {
setTimeout(() => this.props.dispatch(fetchAnnouncements()), 700);
this._checkIfReloadNeeded(false, this.props.isPartial);
}
componentDidUpdate (prevProps) {
this._checkIfReloadNeeded(prevProps.isPartial, this.props.isPartial);
}
componentWillUnmount () {
this._stopPolling();
}
_checkIfReloadNeeded (wasPartial, isPartial) {
const { dispatch } = this.props;
if (wasPartial === isPartial) {
return;
} else if (!wasPartial && isPartial) {
this.polling = setInterval(() => {
dispatch(expandHomeTimeline());
}, 3000);
} else if (wasPartial && !isPartial) {
this._stopPolling();
}
}
_stopPolling () {
if (this.polling) {
clearInterval(this.polling);
this.polling = null;
}
}
handleToggleAnnouncementsClick = (e) => {
e.stopPropagation();
this.props.dispatch(toggleShowAnnouncements());
}
render () {
const { intl, shouldUpdateScroll, hasUnread, columnId, multiColumn, hasAnnouncements, unreadAnnouncements, showAnnouncements } = this.props;
const pinned = !!columnId;
let announcementsButton = null;
if (hasAnnouncements) {
announcementsButton = (
<button
className={classNames('column-header__button', { 'active': showAnnouncements })}
title={intl.formatMessage(showAnnouncements ? messages.hide_announcements : messages.show_announcements)}
aria-label={intl.formatMessage(showAnnouncements ? messages.hide_announcements : messages.show_announcements)}
aria-pressed={showAnnouncements ? 'true' : 'false'}
onClick={this.handleToggleAnnouncementsClick}
>
<IconWithBadge id='bullhorn' count={unreadAnnouncements} />
</button>
);
}
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}>
<ColumnHeader
icon='home'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
extraButton={announcementsButton}
appendContent={hasAnnouncements && showAnnouncements && <AnnouncementsContainer />}
>
<ColumnSettingsContainer />
</ColumnHeader>
<StatusListContainer
trackScroll={!pinned}
scrollKey={`home_timeline-${columnId}`}
onLoadMore={this.handleLoadMore}
timelineId='home'
emptyMessage={<FormattedMessage id='empty_column.home' defaultMessage='Your home timeline is empty! Follow more people to fill it up. {suggestions}' values={{ suggestions: <Link to='/start'><FormattedMessage id='empty_column.home.suggestions' defaultMessage='See some suggestions' /></Link> }} />}
shouldUpdateScroll={shouldUpdateScroll}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
src/bundles/SellerRegistration/components/Finish.js | AusDTO/dto-digitalmarketplace-frontend | import React from 'react';
import PropTypes from 'prop-types'
const Finish = ({onClick}) => (
<div>
<h1 tabIndex="-1">That is it for now!</h1>
<p>
We are just putting the finishing touches on our improved Terms of Service and Marketplace Master
Agreement.</p>
<p> Once they are ready, we will contact you for your agreement. Then we can put your updated seller profile
live.</p>
<a href="/digital-service-professionals/opportunities">View latest opportunities</a>
</div>
);
Finish.defaultProps = {
onClick: () => {
},
}
Finish.propTypes = {
onClick: PropTypes.func
};
export default Finish; |
src/components/Icon/Icon.js | jzhang300/carbon-components-react | import PropTypes from 'prop-types';
import React from 'react';
import icons from 'carbon-icons';
/**
* Returns a single icon Object
* @param {string} iconName - "name" property of icon
* @param {Object} [iconsObj=icons] - JSON Array of Objects
* @example
* // Returns a single icon Object
* this.findIcon('copy-code', icons.json);
*/
export function findIcon(name, iconsObj = icons) {
const icon = iconsObj.filter(obj => obj.name === name);
if (icon.length === 0) {
return false;
} else if (icon.length > 1) {
throw new Error('Multiple icons found...');
} else {
return icon[0];
}
}
/**
* Returns "svgData" Object
* @param {string} iconName - "name" property of icon
* @example
* // Returns svgData Object for given iconName
* this.getSvgData('copy-code');
*/
export function getSvgData(iconName) {
const name = findIcon(iconName);
return name ? name.svgData : false;
}
/**
* Returns Elements/Nodes for SVG
* @param {Object} svgData - JSON Object for an SVG icon
* @example
* // Returns SVG elements
* const svgData = getSvgData('copy-code');
* svgShapes(svgData);
*/
export function svgShapes(svgData) {
const svgElements = Object.keys(svgData)
.filter(key => svgData[key])
.map(svgProp => {
const data = svgData[svgProp];
if (svgProp === 'circles') {
return data.map((circle, index) => {
const circleProps = {
cx: circle.cx,
cy: circle.cy,
r: circle.r,
key: `circle${index}`,
};
return <circle {...circleProps} />;
});
} else if (svgProp === 'paths') {
return data.map((path, index) => (
<path d={path.d} key={`key${index}`} />
));
}
return '';
});
return svgElements;
}
export function isPrefixed(name) {
return name.split('--')[0] === 'icon';
}
const Icon = ({
className,
description,
fill,
fillRule,
height,
name,
role,
style,
width,
...other
}) => {
const icon = isPrefixed(name) ? findIcon(name) : findIcon(`icon--${name}`);
const props = {
className,
fill,
fillRule,
height: height || icon.height,
name: isPrefixed ? name : `icon--${name}`,
role,
style,
viewBox: icon.viewBox,
width: width || icon.width,
...other,
};
const svgContent = icon ? svgShapes(icon.svgData) : '';
return (
<svg {...props} aria-label={description}>
<title>{description}</title>
{svgContent}
</svg>
);
};
Icon.propTypes = {
className: PropTypes.string,
description: PropTypes.string.isRequired,
fill: PropTypes.string,
fillRule: PropTypes.string,
height: PropTypes.string,
name: PropTypes.string.isRequired,
role: PropTypes.string,
style: PropTypes.object,
viewBox: PropTypes.string,
width: PropTypes.string,
};
Icon.defaultProps = {
fillRule: 'evenodd',
role: 'img',
description: 'Provide a description that will be used as the title',
};
export { icons };
export default Icon;
|
test/client/components/logo.js | berkeley-homes/near-miss-positive-intervention | import test from 'tape'
import React from 'react'
import { shallow } from 'enzyme'
import Logo from '../../../src/client/components/logo.js'
test('Logo page includes Photo', t => {
const wrapper = shallow(<Logo />)
t.equal(wrapper.contains(<div><img src='' alt='Logo' /></div>), true)
t.end()
})
|
src/svg-icons/image/navigate-next.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageNavigateNext = (props) => (
<SvgIcon {...props}>
<path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
</SvgIcon>
);
ImageNavigateNext = pure(ImageNavigateNext);
ImageNavigateNext.displayName = 'ImageNavigateNext';
ImageNavigateNext.muiName = 'SvgIcon';
export default ImageNavigateNext;
|
src/context-types.js | Chris927/u5-r2-query | //@flow
import React from 'react'
import PropTypes from 'prop-types'
export default {
fetcher: PropTypes.func.isRequired,
queryStatePath: PropTypes.string,
ttl: PropTypes.number,
retryInterval: PropTypes.number,
queryLoadingIndicator: PropTypes.element
}
|
src/apps/expenses/components/ApproveExpenseBtn.js | OpenCollective/frontend | import React from 'react';
import PropTypes from 'prop-types';
import { graphql } from 'react-apollo';
import { FormattedMessage } from 'react-intl';
import gql from 'graphql-tag';
import withIntl from '../../../lib/withIntl';
import SmallButton from '../../../components/SmallButton';
class ApproveExpenseBtn extends React.Component {
static propTypes = {
id: PropTypes.number.isRequired,
};
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
async onClick() {
const { id } = this.props;
await this.props.approveExpense(id);
}
render() {
return (
<div className="ApproveExpenseBtn">
<SmallButton className="approve" bsStyle="success" onClick={this.onClick}>
<FormattedMessage id="expense.approve.btn" defaultMessage="approve" />
</SmallButton>
</div>
);
}
}
const approveExpenseQuery = gql`
mutation approveExpense($id: Int!) {
approveExpense(id: $id) {
id
status
}
}
`;
const addMutation = graphql(approveExpenseQuery, {
props: ({ mutate }) => ({
approveExpense: async id => {
return await mutate({ variables: { id } });
},
}),
});
export default addMutation(withIntl(ApproveExpenseBtn));
|
frontend/jqwidgets/jqwidgets-react/react_jqxinput.js | yevgeny-sergeyev/nexl-js | /*
jQWidgets v5.7.2 (2018-Apr)
Copyright (c) 2011-2018 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxInput extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
this.val(this.props.value);
};
manageAttributes() {
let properties = ['disabled','dropDownWidth','displayMember','height','items','minLength','maxLength','opened','placeHolder','popupZIndex','query','renderer','rtl','searchMode','source','theme','valueMember','width','value'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxInput(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxInput('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxInput(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('disabled');
}
};
dropDownWidth(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('dropDownWidth', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('dropDownWidth');
}
};
displayMember(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('displayMember', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('displayMember');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('height', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('height');
}
};
items(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('items', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('items');
}
};
minLength(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('minLength', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('minLength');
}
};
maxLength(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('maxLength', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('maxLength');
}
};
opened(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('opened', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('opened');
}
};
placeHolder(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('placeHolder', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('placeHolder');
}
};
popupZIndex(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('popupZIndex', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('popupZIndex');
}
};
query(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('query', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('query');
}
};
renderer(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('renderer', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('renderer');
}
};
rtl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('rtl', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('rtl');
}
};
searchMode(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('searchMode', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('searchMode');
}
};
source(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('source', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('source');
}
};
theme(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('theme', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('theme');
}
};
valueMember(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('valueMember', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('valueMember');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('width', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('width');
}
};
value(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxInput('value', arg)
} else {
return JQXLite(this.componentSelector).jqxInput('value');
}
};
destroy() {
JQXLite(this.componentSelector).jqxInput('destroy');
};
focus() {
JQXLite(this.componentSelector).jqxInput('focus');
};
selectAll() {
JQXLite(this.componentSelector).jqxInput('selectAll');
};
val(value) {
if (value !== undefined) {
JQXLite(this.componentSelector).jqxInput('val', value)
} else {
return JQXLite(this.componentSelector).jqxInput('val');
}
};
render() {
let id = 'jqxInput' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<input type='text' id={id}></input>
)
};
};
|
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch04/04_02/start/src/index.js | yevheniyc/Autodidact | import React from 'react'
import { render } from 'react-dom'
import { SkiDayList } from './components/SkiDayList'
window.React = React
render(
<SkiDayList days={
[
{
resort: "Squaw Valley",
date: new Date("1/2/2016"),
powder: true,
backcountry: false
},
{
resort: "Kirkwood",
date: new Date("3/28/2016"),
powder: false,
backcountry: false
},
{
resort: "Mt. Tallac",
date: new Date("4/2/2016"),
powder: false,
backcountry: true
}
]
}/>,
document.getElementById('react-container')
) |
src/routes/home/index.js | jwilliams33490/save-a-little-ui | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Home from './Home';
import fetch from '../../core/fetch';
export const path = '/home';
export const action = async (state) => {
const response = await fetch('/graphql?query={news{title,link,contentSnippet}}');
const { data } = await response.json();
state.context.onSetTitle('React.js Starter Kit');
return <Home news={data.news} />;
};
|
src/views/NotFound.js | scarescrow/react-resource-center | import React, { Component } from 'react';
class NotFound extends Component {
state = {}
render () {
return <h1>Not Found</h1>
}
}
export default NotFound; |
docs/app/Examples/collections/Message/Variations/MessageExampleFloatingProps.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Message } from 'semantic-ui-react'
const MessageExampleFloatingProps = () => (
<Message
floating
content='Way to go!'
/>
)
export default MessageExampleFloatingProps
|
webclient/src/preview/Confirmation.js | jadiego/bloom | import React, { Component } from 'react';
import { Container, Segment, Header, Image } from 'semantic-ui-react';
import { Link } from 'react-router-dom';
import './preview.css';
import lotus from '../img/lotus.png';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { togglePrivacy } from '../redux/actions';
class Confirmation extends Component {
componentDidMount() {
this.props.togglePrivacy(false, this.props.currentStory)
}
render() {
return (
<Container className='previewcontainer'>
<Segment basic padded style={{marginTop:'15vh'}}>
<Image src={lotus} centered size='medium'/>
<Header as='h1' textAlign='center'>
Thank you for sharing your story, for your bravery, and your resiliency.
</Header>
</Segment>
</Container>
)
}
}
const mapStateToProps = (state) => {
return {
currentStory: state.currentStory,
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({
togglePrivacy
}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(Confirmation) |
modules/Lifecycle.js | rkaneriya/react-router | import React from 'react'
import invariant from 'invariant'
const { object } = React.PropTypes
/**
* The Lifecycle mixin adds the routerWillLeave lifecycle method to a
* component that may be used to cancel a transition or prompt the user
* for confirmation.
*
* On standard transitions, routerWillLeave receives a single argument: the
* location we're transitioning to. To cancel the transition, return false.
* To prompt the user for confirmation, return a prompt message (string).
*
* During the beforeunload event (assuming you're using the useBeforeUnload
* history enhancer), routerWillLeave does not receive a location object
* because it isn't possible for us to know the location we're transitioning
* to. In this case routerWillLeave must return a prompt message to prevent
* the user from closing the window/tab.
*/
const Lifecycle = {
contextTypes: {
history: object.isRequired,
// Nested children receive the route as context, either
// set by the route component using the RouteContext mixin
// or by some other ancestor.
route: object
},
propTypes: {
// Route components receive the route object as a prop.
route: object
},
componentDidMount() {
invariant(
this.routerWillLeave,
'The Lifecycle mixin requires you to define a routerWillLeave method'
)
const route = this.props.route || this.context.route
invariant(
route,
'The Lifecycle mixin must be used on either a) a <Route component> or ' +
'b) a descendant of a <Route component> that uses the RouteContext mixin'
)
this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute(
route,
this.routerWillLeave
)
},
componentWillUnmount() {
if (this._unlistenBeforeLeavingRoute)
this._unlistenBeforeLeavingRoute()
}
}
export default Lifecycle
|
src/svg-icons/av/mic.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvMic = (props) => (
<SvgIcon {...props}>
<path d="M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72h-1.7z"/>
</SvgIcon>
);
AvMic = pure(AvMic);
AvMic.displayName = 'AvMic';
AvMic.muiName = 'SvgIcon';
export default AvMic;
|
node_package/src/handleError.js | szyablitsky/react_on_rails | import React from 'react';
import ReactDOMServer from 'react-dom/server';
function handleGeneratorFunctionIssue(options) {
const { e, name } = options;
let msg = '';
if (name) {
const lastLine =
'A generator function takes a single arg of props (and the location for react-router) ' +
'and returns a ReactElement.';
let shouldBeGeneratorError =
`ERROR: ReactOnRails is incorrectly detecting generator function to be false. The React
component '${name}' seems to be a generator function.\n${lastLine}`;
const reMatchShouldBeGeneratorError = /Can't add property context, object is not extensible/;
if (reMatchShouldBeGeneratorError.test(e.message)) {
msg += `${shouldBeGeneratorError}\n\n`;
console.error(shouldBeGeneratorError);
}
shouldBeGeneratorError =
`ERROR: ReactOnRails is incorrectly detecting generatorFunction to be true, but the React
component '${name}' is not a generator function.\n${lastLine}`;
const reMatchShouldNotBeGeneratorError = /Cannot call a class as a function/;
if (reMatchShouldNotBeGeneratorError.test(e.message)) {
msg += `${shouldBeGeneratorError}\n\n`;
console.error(shouldBeGeneratorError);
}
}
return msg;
}
const handleError = (options) => {
const { e, jsCode, serverSide } = options;
console.error('Exception in rendering!');
let msg = handleGeneratorFunctionIssue(options);
if (jsCode) {
console.error(`JS code was: ${jsCode}`);
}
if (e.fileName) {
console.error(`location: ${e.fileName}:${e.lineNumber}`);
}
console.error(`message: ${e.message}`);
console.error(`stack: ${e.stack}`);
if (serverSide) {
msg += `Exception in rendering!
${e.fileName ? `\nlocation: ${e.fileName}:${e.lineNumber}` : ''}
Message: ${e.message}
${e.stack}`;
const reactElement = React.createElement('pre', null, msg);
return ReactDOMServer.renderToString(reactElement);
}
return undefined;
};
export default handleError;
|
fields/types/textarea/TextareaField.js | andreufirefly/keystone | import Field from '../Field';
import React from 'react';
module.exports = Field.create({
displayName: 'TextareaField',
renderField () {
var styles = {
height: this.props.height,
};
return <textarea name={this.props.path} styles={styles} ref="focusTarget" value={this.props.value} onChange={this.valueChanged} autoComplete="off" className="FormInput" />;
},
});
|
js/jqwidgets/demos/react/app/editor/linebreakconfig/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxEditor from '../../../jqwidgets-react/react_jqxeditor.js';
class App extends React.Component {
render() {
return (
<JqxEditor width={800} height={400} lineBreak={'div'} />
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
stories/Map.js | City-Bus-Stops/search-route | import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import MapComponent from '../src/components/Map/Map';
import mockData from '../src/json-server/db.json';
storiesOf('Map', module)
.add('Default map', () => (
<div>
<MapComponent
data={[]}
loadRouteToBusStop={() => action('Load route to bus stop')}
actions={{
getMapPointInfo: action('Load point info'),
closeMapPointInfo: action('Close map point info'),
toggleSideBar: action('Toggle sidebar'),
getUserPointInfo: action('Get user point info'),
findUserLocation: action('Find user location'),
findNearestButStops: action('Find nearest bus stops'),
}}
isSidebarOpen={false}
pointInfo={{}}
/>
</div>
))
.add('with route', () => (
<div>
<MapComponent
data={mockData['routes-geo'][0].geoData}
loadRouteToBusStop={() => action('Load route to bus stop')}
actions={{
getMapPointInfo: action('Load point info'),
closeMapPointInfo: action('Close map point info'),
toggleSideBar: action('Toggle sidebar'),
getUserPointInfo: action('Get user point info'),
findUserLocation: action('Find user location'),
findNearestButStops: action('Find nearest bus stops'),
}}
isSidebarOpen={false}
pointInfo={{}}
/>
</div>
))
.add('with nearest bus stops', () => (
<div>
<MapComponent
data={mockData['nearest-bus-stops']}
loadRouteToBusStop={() => action('Load route to bus stop')}
actions={{
getMapPointInfo: action('Load point info'),
closeMapPointInfo: action('Close map point info'),
toggleSideBar: action('Toggle sidebar'),
getUserPointInfo: action('Get user point info'),
findUserLocation: action('Find user location'),
findNearestButStops: action('Find nearest bus stops'),
}}
isSidebarOpen={false}
pointInfo={{}}
center={[53.6729683, 23.79417658]}
zoom={17}
maxZoom={18}
minZoom={14}
/>
</div>
))
.add('with sidebar', () => (
<div>
<MapComponent
data={[]}
loadRouteToBusStop={() => action('Load route to bus stop')}
actions={{
getMapPointInfo: action('Load point info'),
closeMapPointInfo: action('Close map point info'),
toggleSideBar: action('Toggle sidebar'),
getUserPointInfo: action('Get user point info'),
findUserLocation: action('Find user location'),
findNearestButStops: action('Find nearest bus stops'),
}}
pointInfo={{}}
center={[53.6729683, 23.79417658]}
zoom={17}
maxZoom={18}
minZoom={14}
isSidebarOpen
/>
</div>
));
|
src/parser/deathknight/frost/modules/features/Checklist.js | FaideWW/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import CoreChecklist, { Rule, Requirement } from 'parser/shared/modules/features/Checklist';
import Abilities from 'parser/core/modules/Abilities';
import { PreparationRule } from 'parser/shared/modules/features/Checklist/Rules';
import { GenericCastEfficiencyRequirement } from 'parser/shared/modules/features/Checklist/Requirements';
import CastEfficiency from 'parser/shared/modules/CastEfficiency';
import PrePotion from 'parser/shared/modules/items/PrePotion';
import EnchantChecker from 'parser/shared/modules/items/EnchantChecker';
import AlwaysBeCasting from './AlwaysBeCasting';
import RunicPowerDetails from '../runicpower/RunicPowerDetails';
import RuneTracker from './RuneTracker';
class Checklist extends CoreChecklist {
static dependencies = {
abilities: Abilities,
castEfficiency: CastEfficiency,
prePotion: PrePotion,
alwaysBeCasting: AlwaysBeCasting,
enchantChecker: EnchantChecker,
runicPowerDetails: RunicPowerDetails,
runeTracker: RuneTracker,
};
rules = [
new Rule({
name: 'Use cooldowns as often as possible',
description: 'You should aim to use your cooldowns as often as you can to maximize your damage output',
requirements: () => {
const combatant = this.selectedCombatant;
return [
new GenericCastEfficiencyRequirement({
spell: SPELLS.PILLAR_OF_FROST,
}),
new GenericCastEfficiencyRequirement({
spell: SPELLS.BREATH_OF_SINDRAGOSA_TALENT,
when: combatant.hasTalent(SPELLS.BREATH_OF_SINDRAGOSA_TALENT.id),
}),
new GenericCastEfficiencyRequirement({
spell: SPELLS.EMPOWER_RUNE_WEAPON,
}),
];
},
}),
new Rule({
name: 'Try to avoid being inactive for a large portion of the fight',
description: <>While some downtime is inevitable in fights with movement, you should aim to reduce downtime to prevent capping Runes. In a worst case scenario, you can cast <SpellLink id={SPELLS.HOWLING_BLAST.id} /> to prevent Rune capping</>,
requirements: () => {
return [
new Requirement({
name: 'Downtime',
check: () => this.alwaysBeCasting.downtimeSuggestionThresholds,
}),
];
},
}),
new Rule({
name: 'Avoid capping Runic Power',
description: <>Death Knights are a resource based class, relying on Runes and Runic Power to cast core abilities. Cast <SpellLink id={SPELLS.FROST_STRIKE_CAST.id} /> when you have 80 or more Runic Power to avoid overcapping.</>,
requirements: () => {
return [
new Requirement({
name: 'Runic Power Efficiency',
check: () => this.runicPowerDetails.efficiencySuggestionThresholds,
}),
];
},
}),
new Rule({
name: 'Avoid capping Runes',
description: 'Death Knights are a resource based class, relying on Runes and Runic Power to cast core abilities. You can have up to three runes recharging at once. You want to dump runes whenever you have 4 or more runes to make sure none are wasted',
requirements: () => {
return [
new Requirement({
name: 'Rune Efficiency',
check: () => this.runeTracker.suggestionThresholdsEfficiency,
}),
];
},
}),
new PreparationRule(),
]
}
export default Checklist;
|
src/components/Sidebar/SidebarLinksList.js | vogelino/design-timeline | import React from 'react';
import PropTypes from 'prop-types';
const SidebarLinksList = ({ externalLinks }) => (
<ul className="sidebar_externallinks">
{externalLinks.map((url, index) => (
<li key={url} className="sidebar_externallink">
<a
href={url}
title={`Link ${index + 1}`}
target="_blank"
rel="noreferrer noopener"
>
{`Link ${index + 1}`}
</a>
</li>
))}
</ul>
);
SidebarLinksList.propTypes = {
externalLinks: PropTypes.arrayOf(PropTypes.string).isRequired,
};
export default SidebarLinksList;
|
packages/ringcentral-widgets-docs/src/app/pages/Components/LogBasicInfo/Demo.js | ringcentral/ringcentral-js-widget | import React from 'react';
// eslint-disable-next-line
import LogBasicInfo from 'ringcentral-widgets/components/LogBasicInfo';
const props = {};
props.currentLocale = 'en-US';
/**
* A example of `LogBasicInfo`
*/
const LogBasicInfoDemo = () => <LogBasicInfo {...props} />;
export default LogBasicInfoDemo;
|
packages/bonde-admin/src/components/layout/settings-page-content-layout.js | ourcities/rebu-client | import PropTypes from 'prop-types'
import React from 'react'
import classnames from 'classnames'
const SettingsPageContentLayout = ({
children,
className,
containerClassName,
wrapClassName,
overflow
}) => (
<div
className={classnames(
'settings-page-content-layout clearfix py3 pr4 pl3 border-box',
`overflow-${overflow}`,
className
)}
>
<div
className={classnames(
'settings-page-content-layout-container',
'clearfix',
containerClassName,
wrapClassName || 'md-col-12 lg-col-9'
)}
>
{children}
</div>
</div>
)
SettingsPageContentLayout.propTypes = {
children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
className: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
containerClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
wrapClassName: PropTypes.oneOfType([PropTypes.string, PropTypes.array])
}
SettingsPageContentLayout.defaultProps = {
overflow: 'auto'
}
export default SettingsPageContentLayout
|
docs/pages/company/jobs.js | lgollut/material-ui | import React from 'react';
import TopLayoutCompany from 'docs/src/modules/components/TopLayoutCompany';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const pageFilename = 'company/jobs';
const requireDemo = require.context('docs/src/pages/company/jobs', false, /\.(js|tsx)$/);
const requireRaw = require.context(
'!raw-loader!../../src/pages/company/jobs',
false,
/\.(js|md|tsx)$/,
);
export default function Page({ demos, docs }) {
return <TopLayoutCompany demos={demos} docs={docs} requireDemo={requireDemo} />;
}
Page.getInitialProps = () => {
const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw });
return { demos, docs };
};
|
src/components/common/Card.js | aarboleda1/Reddit_Mobile | import React, { Component } from 'react';
import { View, Text } from 'react-native';
const Card = (props) => {
return (
<View style={ styles.containerStyle }>
{ props.children }
</View>
);
};
const styles = {
containerStyle: {
borderWidth: 1,
borderRadius: 1,
borderColor: '#ddd',
borderBottomWidth: 0,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2},
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 1,
marginLeft: 3,
marginRight: 3,
marginTop: 8
}
}
export { Card };
|
src/components/intellij/plain/IntellijPlain.js | fpoumian/react-devicon | import React from 'react'
import PropTypes from 'prop-types'
import SVGDeviconInline from '../../_base/SVGDeviconInline'
import iconSVG from './IntellijPlain.svg'
/** IntellijPlain */
function IntellijPlain({ width, height, className }) {
return (
<SVGDeviconInline
className={'IntellijPlain' + ' ' + className}
iconSVG={iconSVG}
width={width}
height={height}
/>
)
}
IntellijPlain.propTypes = {
className: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
export default IntellijPlain
|
Redux/0/public/components/LandingAbout.react.js | hugonasciutti/Exercises | import React from 'react';
import { Link } from 'react-router';
class About extends React.Component {
render() {
return (
<div>
<h3>About</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
)
}
}
export default About
|
front/client/components/OAuth/index.js | gazayas/tebukuro | import React from 'react'
import { OAuthSignInButton, SignOutButton } from "redux-auth/default-theme"
import Avatar from '../Avatar'
const OAuth = ({auth}) => {
const button = auth.getIn(["user", "isSignedIn"]) ? <SignOutButton /> : <OAuthSignInButton provider="github" />
return (
<div>
<Avatar src={auth.getIn(["user", "attributes", "image"])} />
{button}
</div>
)
}
OAuth.propTypes = {
auth : React.PropTypes.object.isRequired,
}
export default OAuth
|
frontend/src/pages/sys-admin/main-panel.js | miurahr/seahub | import React, { Component } from 'react';
import PropTypes from 'prop-types';
const propTypes = {
children: PropTypes.object.isRequired,
};
class MainPanel extends Component {
render() {
return (
<div className="main-panel o-hidden">
{this.props.children}
</div>
);
}
}
MainPanel.propTypes = propTypes;
export default MainPanel;
|
src/svg-icons/navigation/first-page.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationFirstPage = (props) => (
<SvgIcon {...props}>
<path d="M18.41 16.59L13.82 12l4.59-4.59L17 6l-6 6 6 6zM6 6h2v12H6z"/>
</SvgIcon>
);
NavigationFirstPage = pure(NavigationFirstPage);
NavigationFirstPage.displayName = 'NavigationFirstPage';
NavigationFirstPage.muiName = 'SvgIcon';
export default NavigationFirstPage;
|
ee/client/omnichannel/cannedResponses/CannedResponseDetails.stories.js | VoiSmart/Rocket.Chat | import { Box } from '@rocket.chat/fuselage';
import React from 'react';
import { CannedResponseDetails } from './CannedResponseDetails';
export default {
title: 'omnichannel/CannedResponse/CannedResponseDetails',
component: CannedResponseDetails,
};
const cannedResponse = {
shortcut: 'lorem',
text: 'Lorem ipsum dolor sit amet',
scope: 'department',
};
export const Default = () => (
<Box maxWidth='x300' alignSelf='center' w='full'>
<CannedResponseDetails response={cannedResponse} />
</Box>
);
|
src/openMarket/user_interface/index.js | UnexpectedSoftware/openMarket | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, hashHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import routes from './routes';
import configureStore from './store/configureStore';
import '!style-loader!css-loader!sass-loader!./file.scss';
const store = configureStore();
const history = syncHistoryWithStore(hashHistory, store);
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
document.getElementById('root')
);
|
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/StateInline.js | samwgoldman/flow | // @flow
import React from 'react';
class MyComponent extends React.Component {
props: Props;
state: {a: number, b: number, c: number} = {a: 1, b: 2, c: 3};
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
const expression = () =>
class extends React.Component {
props: Props;
state: {a: number, b: number, c: number} = {a: 1, b: 2, c: 3};
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
|
src/components/Picker.js | reactivepod/fido-web | import React, { Component } from 'react';
class Picker extends Component {
constructor(props) {
super(props);
}
render() {
const { onSubmitHandle } = this.props;
return (
<form className="picker" onSubmit={onSubmitHandle}>
<p>
<label>Podcast iTunes URL or ID <input ref="id" placeholder="1020286000" /></label>
<button type="submit" data-size="s" data-color="green" className="ladda-button "><span className="ladda-label">Add Podcast</span></button>
</p>
</form>
);
}
}
export default Picker;
|
src/svg-icons/av/pause-circle-filled.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvPauseCircleFilled = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 14H9V8h2v8zm4 0h-2V8h2v8z"/>
</SvgIcon>
);
AvPauseCircleFilled = pure(AvPauseCircleFilled);
AvPauseCircleFilled.displayName = 'AvPauseCircleFilled';
AvPauseCircleFilled.muiName = 'SvgIcon';
export default AvPauseCircleFilled;
|
client/app/scripts/utils/string-utils.js | paulbellamy/scope | import React from 'react';
import filesize from 'filesize';
import { format as d3Format } from 'd3-format';
import { isoFormat } from 'd3-time-format';
import LCP from 'lcp';
import moment from 'moment';
const formatLargeValue = d3Format('s');
function renderHtml(text, unit) {
return (
<span className="metric-formatted">
<span className="metric-value">{text}</span>
<span className="metric-unit">{unit}</span>
</span>
);
}
function renderSvg(text, unit) {
return `${text}${unit}`;
}
function padToThreeDigits(n) {
return `000${n}`.slice(-3);
}
function makeFormatters(renderFn) {
const formatters = {
filesize(value) {
const obj = filesize(value, {output: 'object', round: 1});
return renderFn(obj.value, obj.suffix);
},
integer(value) {
const intNumber = Number(value).toFixed(0);
if (value < 1100 && value >= 0) {
return intNumber;
}
return formatLargeValue(intNumber);
},
number(value) {
if (value < 1100 && value >= 0) {
return Number(value).toFixed(2);
}
return formatLargeValue(value);
},
percent(value) {
return renderFn(formatters.number(value), '%');
}
};
return formatters;
}
function makeFormatMetric(renderFn) {
const formatters = makeFormatters(renderFn);
return (value, opts) => {
const formatter = opts && formatters[opts.format] ? opts.format : 'number';
return formatters[formatter](value);
};
}
export const formatMetric = makeFormatMetric(renderHtml);
export const formatMetricSvg = makeFormatMetric(renderSvg);
export const formatDate = isoFormat; // d3.time.format.iso;
const CLEAN_LABEL_REGEX = /[^A-Za-z0-9]/g;
export function slugify(label) {
return label.replace(CLEAN_LABEL_REGEX, '').toLowerCase();
}
export function longestCommonPrefix(strArr) {
return (new LCP(strArr)).lcp();
}
// Converts IPs from '10.244.253.4' to '010.244.253.004' format.
export function ipToPaddedString(value) {
return value.match(/\d+/g).map(padToThreeDigits).join('.');
}
// Formats metadata values. Add a key to the `formatters` obj
// that matches the `dataType` of the field. You must return an Object
// with the keys `value` and `title` defined.
export function formatDataType(field) {
const formatters = {
datetime(dateString) {
const date = moment(new Date(dateString));
return {
value: date.fromNow(),
title: date.format('YYYY-MM-DD HH:mm:ss.SSS')
};
}
};
const format = formatters[field.dataType];
return format
? format(field.value)
: {value: field.value, title: field.value};
}
|
src/components/containers/board-market-brokerage-gain-details-container.js | HuangXingBin/goldenEast | import React from 'react';
import { Button, AutoComplete ,DatePicker } from 'antd';
import './user-list-container.css';
import UserListTable from '../views/board-market-brokerage-gain-details-table';
import { connect } from 'react-redux';
import store from '../../store';
import { updateBoardMarketBrokerageUserDetailSearch } from '../../actions/app-interaction-actions';
import { getBoardMarketUserDetailData } from '../../api/app-interaction-api';
import weiGuDong from '../../appConstants/assets/images/微股东.png';
import normalCard from '../../appConstants/assets/images/普卡.png';
import silverCard from '../../appConstants/assets/images/银卡.png';
import goldenCard from '../../appConstants/assets/images/金卡.png';
import superGoldenCard from '../../appConstants/assets/images/白金卡.png';
import moment from 'moment';
const RangePicker = DatePicker.RangePicker;
var BoardMarketBrokerageGainDetailsContainer = React.createClass({
getInitialState(){
return {
user_sn: '',
userInfo: '',
transactionStart:'',
transactionEnd:'',
accounts: []
}
},
jinLevels() {
return ['注册用户(0%)', weiGuDong, normalCard, silverCard, goldenCard, superGoldenCard];
},
componentWillMount(){
const user_sn = this.props.params.details;
const transactionStart = this.props.params.transactionStart;
const transactionEnd = this.props.params.transactionEnd;
this.setState({
user_sn: user_sn,
transactionStart:transactionStart,
transactionEnd:transactionEnd,
})
},
componentDidMount() {
var _this = this;
const user_sn = this.state.user_sn;
const transactionStart = this.props.params.transactionStart;
const transactionEnd = this.props.params.transactionEnd;
getBoardMarketUserDetailData({sn:user_sn,
'search[d_begin]' : transactionStart,
'search[d_end]' : transactionEnd,
},function(info){
console.log(info)
_this.setState({
userInfo: info.data,
accounts: info.data.accounts
});
},function(info){
console.log('fail',info)});
},
submitSearch() {
getBoardMarketUserDetailData(this.props.searchState);
},
onDateChange(dates, dateStrings) {
store.dispatch(updateBoardMarketBrokerageUserDetailSearch({
'search[d_begin]' : dateStrings[0],
'search[d_end]' : dateStrings[1],
'page' : 1,
sn: this.state.user_sn,
}));
// 启动搜索
this.submitSearch();
},
onPageChange(page) {
store.dispatch(updateBoardMarketBrokerageUserDetailSearch({
page : page,
sn: this.state.user_sn,
}));
// 启动搜索
this.submitSearch();
},
render(){
const jinLevels = this.jinLevels();
const { data } = this.props.dataState;
let avatar,avatarYes,user_name,level;
let dateFormat = this.state.transactionStart;
let dateFormat2 = this.state.transactionEnd;
dateFormat = dateFormat.match(/\d{4}.\d{1,2}.\d{1,2}/mg).toString();
dateFormat = dateFormat.replace(/[^0-9]/mg, '/');
dateFormat2 = dateFormat2.match(/\d{4}.\d{1,2}.\d{1,2}/mg).toString();
dateFormat2 = dateFormat2.replace(/[^0-9]/mg, '/');
try {
user_name= data.user.user_name;
avatar = !data.user.wechat_avatar ? data.user.user_name.slice(0,1): '';
avatarYes = data.user.wechat_avatar;
level = data.user.level;
} catch(err) {}
return (
<div>
<div className="userListHeader q-brokerage-user border-b">
<div className="q-brokerage-user">
<div className="q-brokerage-avatar margin-r-10">
<span style={{backgroundImage:'url('+avatarYes+')'}}>{avatar}</span>
</div>
<div className="">
<div className="margin-b-5">{user_name}</div>
<p className=""> <img src={jinLevels[level]} alt="jinLevel"/></p>
</div>
</div>
</div>
<div className="data-picker-bar">
<label>交易日期:</label>
<RangePicker style={{ width: '200px' }} onChange={this.onDateChange}
defaultValue={[moment(dateFormat), moment(dateFormat2)]}
/>
</div>
<UserListTable defaultPageSize={12} total={data.total} currentPage={data.this_page} dataSource={data} onPageChange={this.onPageChange} />
</div>
)
}
});
const mapStateToProps = function (store) {
return {
dataState : store.boardMarketBrokerageUserDetailState.dataState,
searchState : store.boardMarketBrokerageUserDetailState.searchState
}
};
export default connect(mapStateToProps)(BoardMarketBrokerageGainDetailsContainer);
|
packages/wix-style-react/src/NestableList/withDNDContext.js | wix/wix-style-react | import React from 'react';
import DragDropContextProvider from '../DragDropContextProvider';
export default Component => props => (
<DragDropContextProvider>
<Component {...props} />
</DragDropContextProvider>
);
|
packages/material-ui-icons/src/QueuePlayNext.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h2v-2H3V5h18v8h2V5c0-1.11-.9-2-2-2zm-8 7V7h-2v3H8v2h3v3h2v-3h3v-2h-3zm11 8l-4.5 4.5L18 21l3-3-3-3 1.5-1.5L24 18z" /></g>
, 'QueuePlayNext');
|
frontend/src/app/containers/RetirePage.js | 6a68/idea-town | import React from 'react';
import { Link } from 'react-router';
import classnames from 'classnames';
import View from '../components/View';
export default class RetirePage extends React.Component {
constructor(props) {
super(props);
this.state = {
fakeUninstalled: false
};
}
componentDidMount() {
// HACK: Older add-on versions give no reliable signal of having been
// uninstalled, so let's fake it.
this.fakeUninstallTimer = setTimeout(() => {
this.setState({ fakeUninstalled: true });
this.props.setHasAddon(false);
}, this.props.fakeUninstallDelay);
}
componentWillUnmount() {
clearTimeout(this.fakeUninstallTimer);
}
render() {
const { hasAddon } = this.props;
const { fakeUninstalled } = this.state;
const uninstalled = !hasAddon || fakeUninstalled;
if (uninstalled) {
clearTimeout(this.fakeUninstallTimer);
}
return (
<View centered={true} showHeader={false} showFooter={false} showNewsletterFooter={false} {...this.props}>
<div className="centered-banner">
{!uninstalled && <div disabled className={classnames('loading-pill')}>
<h1 className="emphasis" data-l10n-id="retirePageProgressMessage">Shutting down...</h1>
<div style={{ opacity: 1 }} className="state-change-inner"></div>
</div>}
{uninstalled && <div>
<div id="retire" className="modal fade-in">
<div className="modal-header-wrapper">
<h1 data-l10n-id="retirePageHeadline" className="modal-header">Thanks for flying!</h1>
</div>
<div className="modal-content">
<p data-l10n-id="retirePageMessage">Hope you had fun experimenting with us. <br /> Come back any time.</p>
</div>
<div className="modal-actions">
<a onClick={() => this.takeSurvey()} data-l10n-id="retirePageSurveyButton" href="https://qsurvey.mozilla.com/s3/test-pilot" target="_blank" className="button default large">Take a quick survey</a>
<Link to="/" data-l10n-id="home" className="modal-escape">Home</Link>
</div>
</div>
<div className="copter-wrapper">
<div className="copter fade-in-fly-up"></div>
</div>
</div>}
</div>
</View>
);
}
takeSurvey() {
this.props.sendToGA('event', {
eventCategory: 'RetirePage Interactions',
eventAction: 'button click',
eventLabel: 'take survey'
});
}
}
RetirePage.propTypes = {
setHasAddon: React.PropTypes.func,
fakeUninstallDelay: React.PropTypes.number
};
RetirePage.defaultProps = {
fakeUninstallDelay: 5000
};
|
src/components/ContentNav/ContentNavSection.js | contor-cloud/contor-cloud.github.io | import React from 'react'
import isItemActive from '../../utils/isItemActive'
import { colors, media } from '../config'
import NavSectionTitle from '../NavSectionTitle'
import ChevronSvg from '../svg/ChevronSvg'
import ContentNavLink from './ContentNavLink'
const ContentNavSection = ({
activeItemId,
isActive,
isScrollSync,
onLinkClick,
onSectionTitleClick,
section,
}) => (
<div>
<button
css={{
cursor: 'pointer',
backgroundColor: 'transparent',
border: 0,
marginTop: 10,
}}
onClick={onSectionTitleClick}>
<NavSectionTitle
cssProps={{
[media.greaterThan('small')]: {
color: colors.subtle,
':hover': {
color: colors.text,
},
},
}}>
{section.title}
<ChevronSvg
cssProps={{
marginLeft: 7,
transform: 'rotateX(0deg)',
transition: 'transform 0.2s ease',
[media.lessThan('small')]: {
display: 'none',
},
}}
/>
</NavSectionTitle>
</button>
<ul
css={{
marginBottom: 10,
[media.greaterThan('small')]: {
display: isActive ? 'block' : 'none',
},
}}>
{section.items.map(item => (
<li
key={item.id}
css={{
marginTop: 5,
}}>
<ContentNavLink
isActive={isScrollSync
? activeItemId === item.id
: isItemActive(location, item)
}
item={item}
location={location}
onLinkClick={onLinkClick}
section={section}
/>
{item.subitems && (
<ul css={{marginLeft: 20}}>
{item.subitems.map(subitem => (
<li key={subitem.id}>
<ContentNavLink
isActive={isScrollSync
? activeItemId === subitem.id
: isItemActive(location, subitem)
}
item={subitem}
location={location}
onLinkClick={onLinkClick}
section={section}
/>
</li>
))}
</ul>
)}
</li>
))}
</ul>
</div>
)
export default ContentNavSection
|
information/blendle-frontend-react-source/app/modules/settings/views/wallet.js | BramscoChill/BlendleParser | import formatCurrency from 'helpers/formatcurrency';
import Settings from 'controllers/settings';
import Auth from 'controllers/auth';
import { translate, translateElement, getCurrencyWord } from 'instances/i18n';
import FormView from 'views/helpers/form';
import React from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import TransactionsCollection from 'collections/transactions';
import UserOrdersCollection from 'collections/userOrders';
import DepositsCollection from 'collections/deposits';
import PaymentStore from 'stores/PaymentStore';
import { Checkbox } from '@blendle/lego';
import Link from 'components/Link';
import PurchasesList from '../components/PurchasesList';
import TransactionsList from '../components/TransactionsList';
const WalletView = FormView.extend({
initialize() {
this._paymentStoreChanged = this._paymentStoreChanged.bind(this);
PaymentStore.listen(this._paymentStoreChanged);
this._recurring = PaymentStore.getState().recurring || this.options.recurring;
this._purchases = new TransactionsCollection(null, {
url: Settings.getLink('transactions', { user_id: Auth.getId() }),
});
this._deposits = new DepositsCollection(null, {
url: Settings.getLink('deposits', { user_id: Auth.getId() }),
});
this._orders = new UserOrdersCollection(null, {
product: 'subscription',
url: Settings.getLink('user_orders', { user_id: Auth.getId(), product: 'subscription' }),
});
this._render = this.render.bind(this);
this._purchases.on('sync', this._render);
this._purchases.fetch();
this._deposits.on('sync', this._render);
this._deposits.fetch();
this._bindedOnOrdersSynced = this._onOrdersSynced.bind(this);
this._orders.on('sync', this._bindedOnOrdersSynced);
this._orders.fetch({ accept: 'application/hal+json' });
},
beforeUnload() {
this._deposits.off('sync', this._render);
this._purchases.off('sync', this._render);
this._orders.off('sync', this._bindedOnOrdersSynced);
PaymentStore.unlisten(this._paymentStoreChanged);
ReactDOM.unmountComponentAtNode(this.el);
FormView.prototype.beforeUnload.apply(this, arguments);
},
_paymentStoreChanged(state) {
if (state.recurring) {
this._recurring = state.recurring;
this.render();
}
},
_fetchOrderProduct(order) {
return order.getRelation('product', { accept: 'application/hal+json' }).catch((error) => {
// expired products (like subscriptions) return a 402
if (error.status === 402) {
return Promise.resolve(order.setEmbedded('product', error.data));
}
throw error;
});
},
_onOrdersSynced() {
// manually zoom all products, since the zooming proxy can't do this for us
const products = this._orders.map(this._fetchOrderProduct);
Promise.all(products).then(this._render.bind(this));
},
_onLoadMoreTransactions(e) {
e.preventDefault();
if (this._deposits.hasNext()) {
this._deposits.fetchNext();
}
if (this._orders.hasNext()) {
this._orders.fetchNext();
}
},
_onLoadMorePurchases(e) {
e.preventDefault();
this._purchases.fetchNext();
},
_toggleRecurring() {
this.options.setRecurringState(!this._recurring.enabled).then((recurring) => {
this._recurring = recurring;
this.getController().onRecurringChanged(recurring);
this.render();
});
},
_renderRecurring() {
if (
this._recurring.state === 'norecurring_hascontracts' ||
this._recurring.state === 'recurring'
) {
const recurringClass = classNames('block recurring-block', this._recurring.state);
const recurringText = translate('payment.recurring.label', {
currency: getCurrencyWord(),
currency_plural: getCurrencyWord({ plural: true }),
});
return (
<div className={recurringClass} data-test-identifier="recurring-toggle-elements">
<h2 className="title">{translateElement('payment.recurring.title')}</h2>
<Checkbox
id="recurring-toggle"
name="recurring"
checked={this._recurring.state === 'recurring'}
onChange={this._toggleRecurring.bind(this)}
>
{recurringText}
<br />
<span className="note">{translate('payment.recurring.label_note')}</span>
</Checkbox>
</div>
);
}
},
_renderUnconfirmedEmail() {
return (
<div className="block unconfirmed">
<p className="warn">{translate('settings.wallet.unconfirmed_warning')}</p>
<p dangerouslySetInnerHTML={{ __html: translate('settings.wallet.unconfirmed') }} />
</div>
);
},
_renderBalance() {
if (!Auth.getUser().get('email_confirmed')) {
return this._renderUnconfirmedEmail();
}
const balance = formatCurrency(this.model.get('balance'));
const titleClass = classNames('title', { 's-low': this.model.get('balance') < 1 });
return (
<div className="block">
<h2 className={titleClass}>{translateElement('settings.wallet.balance', [balance])}</h2>
<p>
<Link
href="/payment"
state={{ returnUrl: '/settings/wallet' }}
className="btn btn-text btn-blendle-icon-green btn-increase-balance lnk-payment"
>
{translate('settings.buttons.increase_balance')}
</Link>
<a href="/settings/coupons" className="lnk-redeem-coupon">
{translate('settings.buttons.redeem_coupon')}
</a>
</p>
</div>
);
},
render() {
ReactDOM.render(
<div className="v-wallet pane">
<div className="container">
<h2 className="header">{translate('settings.wallet.title')}</h2>
{this._renderBalance()}
{this._renderRecurring()}
<div className="overviews">
<PurchasesList
purchases={this._purchases}
hasMore={this._purchases.hasNext()}
onLoadMore={this._onLoadMorePurchases.bind(this)}
/>
<TransactionsList
deposits={this._deposits}
orders={this._orders}
hasMore={this._deposits.hasNext() || this._orders.hasNext()}
onLoadMore={this._onLoadMoreTransactions.bind(this)}
/>
</div>
</div>
</div>,
this.el,
);
this.display();
return this;
},
});
export default WalletView;
// WEBPACK FOOTER //
// ./src/js/app/modules/settings/views/wallet.js |
src/app/component/select-field/select-field.story.js | all3dp/printing-engine-client | import React from 'react'
import {storiesOf} from '@storybook/react'
import {withState} from '@dump247/storybook-state'
import SelectField from '.'
import SelectMenu from '../select-menu'
import {selectMenuValues} from '../../../../stories/util/data'
const menu = <SelectMenu values={selectMenuValues} />
storiesOf('SelectField', module)
.add(
'default',
withState({value: null}, store => (
<SelectField
value={store.state.value}
onChange={value => store.set({value})}
placeholder="Placeholder"
menu={menu}
/>
))
)
.add(
'opens to top',
withState({value: null}, store => (
<div style={{position: 'relative', height: '100vh'}}>
<div style={{bottom: 0, position: 'absolute', width: '100%'}}>
<SelectField
value={store.state.value}
onChange={value => store.set({value})}
placeholder="Placeholder"
menu={menu}
/>
</div>
</div>
))
)
.add(
'selected',
withState({value: {value: 'item2', label: 'Select Menu Item 2'}}, store => (
<SelectField
value={store.state.value}
onChange={value => store.set({value})}
placeholder="Placeholder"
menu={menu}
/>
))
)
.add(
'compact',
withState({value: null}, store => (
<SelectField
value={store.state.value}
onChange={value => store.set({value})}
compact
placeholder="Placeholder"
menu={menu}
/>
))
)
.add(
'tiny',
withState({value: null}, store => (
<SelectField
value={store.state.value}
onChange={value => store.set({value})}
tiny
placeholder="Placeholder"
menu={menu}
/>
))
)
.add(
'inline',
withState({value: null}, store => (
<SelectField
value={store.state.value}
onChange={value => store.set({value})}
inline
placeholder="Placeholder"
menu={menu}
/>
))
)
.add(
'inlinePill',
withState({value: null}, store => (
<SelectField
value={store.state.value}
onChange={value => store.set({value})}
inlinePill
placeholder="Placeholder"
menu={menu}
/>
))
)
.add('constant', () => (
<SelectField
compact
value={{value: 'item2', colorValue: 'ff0000', label: 'Constant Select Field'}}
/>
))
.add(
'disabled',
withState({value: null}, store => (
<SelectField
value={store.state.value}
onChange={value => store.set({value})}
placeholder="Placeholder"
menu={menu}
disabled
/>
))
)
.add(
'error',
withState({value: null}, store => (
<SelectField
value={store.state.value}
onChange={value => store.set({value})}
error
placeholder="Placeholder"
menu={menu}
/>
))
)
.add(
'warning',
withState({value: null}, store => (
<SelectField
value={store.state.value}
onChange={value => store.set({value})}
warning
placeholder="Placeholder"
menu={menu}
/>
))
)
|
client/components/Fork.js | rompingstalactite/rompingstalactite | import React from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import actions from '../actions/index.js';
import { forkRecipe } from '../utils/utils';
const Fork = (props) => {
let forkComponent;
if (props.userID) {
forkComponent = (<button style={{marginRight: '10px'}} className="btn btn-primary btn-sm btn-fork" onClick={ props.onForkClick.bind(null, props.recipeID, props.userID) }>
Fork
</button>);
} else {
forkComponent = (<button style={{marginRight: '10px'}} className="btn btn-primary btn-sm btn-fork" disabled>Fork</button>);
}
return forkComponent;
};
const mapStateToProps = (state) => {
return {
userID: state.user.id,
};
};
const mapDispatchToProps = (dispatch) => {
return {
onForkClick: (recipeID, userID) => {
forkRecipe(recipeID, userID, (newRecipe) => {
dispatch(actions.forkRecipe(newRecipe));
dispatch(push(`/recipe/${newRecipe.id}`));
});
},
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Fork);
|
examples/js/sort/custom-caret-sort-table.js | pvoznyuk/react-bootstrap-table | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
function getCaret(direction) {
if (direction === 'asc') {
return (
<span> up</span>
);
}
if (direction === 'desc') {
return (
<span> down</span>
);
}
return (
<span> up/down</span>
);
}
export default class CustomSortTable extends React.Component {
render() {
return (
<BootstrapTable data={ products }>
<TableHeaderColumn dataField='id' dataSort={ true } isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name' dataSort={ true } caretRender = { getCaret } >Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price' dataSort={ true } >Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
docs/app/Examples/views/Item/Content/Contents.js | ben174/Semantic-UI-React | import React from 'react'
import { Item } from 'semantic-ui-react'
const { Content, Group, Image } = Item
const Contents = () => (
<Group divided>
<Item>
<Image size='tiny' src='http://semantic-ui.com/images/wireframe/image.png' />
<Content verticalAlign='middle'>Content A</Content>
</Item>
<Item>
<Image size='tiny' src='http://semantic-ui.com/images/wireframe/image.png' />
<Content verticalAlign='middle'>Content B</Content>
</Item>
<Item>
<Image size='tiny' src='http://semantic-ui.com/images/wireframe/image.png' />
<Content content='Content C' verticalAlign='middle' />
</Item>
</Group>
)
export default Contents
|
modules/RouterContextMixin.js | RickyDan/react-router | import React from 'react';
import invariant from 'invariant';
import { stripLeadingSlashes, stringifyQuery } from './URLUtils';
var { func, object } = React.PropTypes;
function pathnameIsActive(pathname, activePathname) {
if (stripLeadingSlashes(activePathname).indexOf(stripLeadingSlashes(pathname)) === 0)
return true; // This quick comparison satisfies most use cases.
// TODO: Implement a more stringent comparison that checks
// to see if the pathname matches any routes (and params)
// in the currently active branch.
return false;
}
function queryIsActive(query, activeQuery) {
if (activeQuery == null)
return query == null;
if (query == null)
return true;
for (var p in query)
if (query.hasOwnProperty(p) && String(query[p]) !== String(activeQuery[p]))
return false;
return true;
}
var RouterContextMixin = {
propTypes: {
stringifyQuery: func.isRequired
},
getDefaultProps() {
return {
stringifyQuery
};
},
childContextTypes: {
router: object.isRequired
},
getChildContext() {
return {
router: this
};
},
/**
* Returns a full URL path from the given pathname and query.
*/
makePath(pathname, query) {
if (query) {
if (typeof query !== 'string')
query = this.props.stringifyQuery(query);
if (query !== '')
return pathname + '?' + query;
}
return pathname;
},
/**
* Returns a string that may safely be used to link to the given
* pathname and query.
*/
makeHref(pathname, query) {
var path = this.makePath(pathname, query);
var { history } = this.props;
if (history && history.makeHref)
return history.makeHref(path);
return path;
},
/**
* Pushes a new Location onto the history stack.
*/
transitionTo(pathname, query, state=null) {
var { history } = this.props;
invariant(
history,
'Router#transitionTo is client-side only (needs history)'
);
history.pushState(state, this.makePath(pathname, query));
},
/**
* Replaces the current Location on the history stack.
*/
replaceWith(pathname, query, state=null) {
var { history } = this.props;
invariant(
history,
'Router#replaceWith is client-side only (needs history)'
);
history.replaceState(state, this.makePath(pathname, query));
},
/**
* Navigates forward/backward n entries in the history stack.
*/
go(n) {
var { history } = this.props;
invariant(
history,
'Router#go is client-side only (needs history)'
);
history.go(n);
},
/**
* Navigates back one entry in the history stack. This is identical to
* the user clicking the browser's back button.
*/
goBack() {
this.go(-1);
},
/**
* Navigates forward one entry in the history stack. This is identical to
* the user clicking the browser's forward button.
*/
goForward() {
this.go(1);
},
/**
* Returns true if a <Link> to the given pathname/query combination is
* currently active.
*/
isActive(pathname, query) {
var { location } = this.state;
if (location == null)
return false;
return pathnameIsActive(pathname, location.pathname) &&
queryIsActive(query, location.query);
}
};
export default RouterContextMixin;
|
app/javascript/mastodon/features/notifications/components/filter_bar.js | tateisu/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import Icon from 'mastodon/components/icon';
const tooltips = defineMessages({
mentions: { id: 'notifications.filter.mentions', defaultMessage: 'Mentions' },
favourites: { id: 'notifications.filter.favourites', defaultMessage: 'Favourites' },
boosts: { id: 'notifications.filter.boosts', defaultMessage: 'Boosts' },
polls: { id: 'notifications.filter.polls', defaultMessage: 'Poll results' },
follows: { id: 'notifications.filter.follows', defaultMessage: 'Follows' },
});
export default @injectIntl
class FilterBar extends React.PureComponent {
static propTypes = {
selectFilter: PropTypes.func.isRequired,
selectedFilter: PropTypes.string.isRequired,
advancedMode: PropTypes.bool.isRequired,
intl: PropTypes.object.isRequired,
};
onClick (notificationType) {
return () => this.props.selectFilter(notificationType);
}
render () {
const { selectedFilter, advancedMode, intl } = this.props;
const renderedElement = !advancedMode ? (
<div className='notification__filter-bar'>
<button
className={selectedFilter === 'all' ? 'active' : ''}
onClick={this.onClick('all')}
>
<FormattedMessage
id='notifications.filter.all'
defaultMessage='All'
/>
</button>
<button
className={selectedFilter === 'mention' ? 'active' : ''}
onClick={this.onClick('mention')}
>
<FormattedMessage
id='notifications.filter.mentions'
defaultMessage='Mentions'
/>
</button>
</div>
) : (
<div className='notification__filter-bar'>
<button
className={selectedFilter === 'all' ? 'active' : ''}
onClick={this.onClick('all')}
>
<FormattedMessage
id='notifications.filter.all'
defaultMessage='All'
/>
</button>
<button
className={selectedFilter === 'mention' ? 'active' : ''}
onClick={this.onClick('mention')}
title={intl.formatMessage(tooltips.mentions)}
>
<Icon id='at' fixedWidth />
</button>
<button
className={selectedFilter === 'favourite' ? 'active' : ''}
onClick={this.onClick('favourite')}
title={intl.formatMessage(tooltips.favourites)}
>
<Icon id='star' fixedWidth />
</button>
<button
className={selectedFilter === 'reblog' ? 'active' : ''}
onClick={this.onClick('reblog')}
title={intl.formatMessage(tooltips.boosts)}
>
<Icon id='retweet' fixedWidth />
</button>
<button
className={selectedFilter === 'poll' ? 'active' : ''}
onClick={this.onClick('poll')}
title={intl.formatMessage(tooltips.polls)}
>
<Icon id='tasks' fixedWidth />
</button>
<button
className={selectedFilter === 'follow' ? 'active' : ''}
onClick={this.onClick('follow')}
title={intl.formatMessage(tooltips.follows)}
>
<Icon id='user-plus' fixedWidth />
</button>
</div>
);
return renderedElement;
}
}
|
src/modules/SearchOptionsAdvanced.js | OCMC-Translation-Projects/ioc-liturgical-react | import React from 'react';
import PropTypes from 'prop-types';
import ResourceSelector from './ReactSelector'
import { Button } from 'react-bootstrap';
import FontAwesome from 'react-fontawesome';
import { get } from 'lodash';
/**
* To future maintainers of this code.
* This was written when I just started learning React Js.
* The code I have written without a doubt needs to be
* examined carefully if you are skilled in React JS,
* and rewritten...
* Michael Colburn, March 1, 2017
*/
class SearchOptions extends React.Component {
constructor(props) {
super(props);
this.state = {
docType: this.props.docType
, domain: "*"
, selectedBook: "*"
, selectedChapter: "*"
, property: "nnp"
, matcher: "c"
, value: ""
, dropdowns: {Biblical: [], Liturgical: [], loaded: false}
, dropDownDomains: {
show: true
, msg: this.props.labels.domainIs
, source: []
, initialValue: "*"
}
,
dropDownBooks: {
show: true
, msg: this.props.labels.bookIs
, source: []
, initialValue: "*"
}
,
dropdownChapters: {
show: false
, msg: ""
, initialValue: "*"
, source: []
}
};
this.handleDocTypeChange = this.handleDocTypeChange.bind(this);
this.handleDomainChange = this.handleDomainChange.bind(this);
this.handleBookChange = this.handleBookChange.bind(this);
this.handleChapterChange = this.handleChapterChange.bind(this);
this.handlePropertyChange = this.handlePropertyChange.bind(this);
this.handleMatcherChange = this.handleMatcherChange.bind(this);
this.handleValueChange = this.handleValueChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.setBookDropdown = this.setBookDropdown.bind(this);
this.setChaptersDropdown = this.setChaptersDropdown.bind(this);
this.setDomainDropdown = this.setDomainDropdown.bind(this);
this.setGenericBookDropdown = this.setGenericBookDropdown.bind(this);
this.setGenericChaptersDropdown = this.setGenericChaptersDropdown.bind(this);
this.suggestedQuery = this.suggestedQuery.bind(this);
this.getDropdownChapterTitle = this.getDropdownChapterTitle.bind(this);
this.getDropdownSectionTitle = this.getDropdownSectionTitle.bind(this);
this.resetDropDownBooksState = this.resetDropDownBooksState.bind(this);
this.cascadeDocTypeChange = this.cascadeDocTypeChange.bind(this);
this.isDisabled = this.isDisabled.bind(this);
}
componentWillMount = () => {
this.setState(
{
dropdowns: {
Biblical: {
all: {
books: this.props.dropDowns.Biblical.all.books
, chapters: this.props.dropDowns.Biblical.all.chapters
}
, domains: this.props.dropDowns.Biblical.domains
, topics: this.props.dropDowns.Biblical.topics
}
, Liturgical: {
all: {
books: this.props.dropDowns.Liturgical.all.books
}
, domains: this.props.dropDowns.Liturgical.domains
, topics: this.props.dropDowns.Liturgical.topics
}
, loaded: true
} , function () {
this.handleDocTypeChange({
label: this.props.docType
, value: this.props.docTyped
})
}
}
)
};
componentDidMount = () => {
this.handleDocTypeChange({
label: this.props.docType
, value: this.props.docType
});
};
componentWillReceiveProps = (nextProps) => {
let docType = nextProps.docType;
let domain = "*";
let selectedBook = "*";
let selectedChapter = "*";
let property = "nnp";
let matcher = "c";
let value = "";
let dropdownChapters = {};
if (this.state) {
if (this.state.docType) {
docType = this.state.docType;
}
if (this.state.domain) {
domain = this.state.domain;
}
if (this.state.selectedBook) {
selectedBook = this.state.selectedBook;
}
if (this.state.selectedChapter) {
selectedChapter = this.state.selectedChapter;
}
if (this.state.property) {
property = this.state.property;
}
if (this.state.matcher) {
matcher = this.state.matcher;
}
if (this.state.value) {
value = this.state.value;
}
if (this.state.dropdownChapters) {
dropdownChapters = this.state.dropdownChapters;
} else {
dropdownChapters = {
show: false
, msg: ""
, initialValue: "*"
, source: []
}
}
}
this.setState(
{
docType: docType
, domain: domain
, selectedBook: selectedBook
, selectedChapter: selectedChapter
, property: property
, matcher: matcher
, value: value
, dropdowns: {
Biblical: {
all: {
books: nextProps.dropDowns.Biblical.all.books
, chapters: nextProps.dropDowns.Biblical.all.chapters
}
, domains: nextProps.dropDowns.Biblical.domains
, topics: nextProps.dropDowns.Biblical.topics
}
, Liturgical: {
all: {
books: nextProps.dropDowns.Liturgical.all.books
}
, domains: nextProps.dropDowns.Liturgical.domains
, topics: nextProps.dropDowns.Liturgical.topics
}
, loaded: true
}
, dropdownChapters: dropdownChapters
}, this.cascadeDocTypeChange(docType)
)
};
isDisabled = () => {
let disableButton = true;
switch (this.state.docType) {
case "All": {
break;
}
case "Biblical": {
if (this.state.value.length > 0) {
disableButton = false;
} else {
if (this.state.domain == "*") {
if (this.state.selectedBook == "*") {
} else {
disableButton = false;
}
} else {
if (this.state.selectedBook == "*") {
} else {
disableButton = false;
}
}
}
break;
}
case "Liturgical": {
if (this.state.value.length > 0) {
disableButton = false;
} else {
if (this.state.domain == "*") {
if (this.state.selectedBook == "*") {
} else {
disableButton = false;
}
} else {
if (this.state.selectedBook == "*") {
} else {
disableButton = false;
}
}
}
break;
}
default: {
break;
}
}
return disableButton;
};
resetDropDownBooksState() {
this.setState({
selectedBook: "*"
, dropDownBooks: {
show: this.state.docType !== "Any"
, msg: this.props.labels.bookIs
, source: []
, initialValue: "*"
}
});
}
handleDocTypeChange = (selection) => {
this.setState({
docType: selection["value"]
, suggestedQuery: this.suggestedQuery(selection["value"])
, domain: "*"
, selectedBook: "*"
, selectedChapter: "*"
}, this.cascadeDocTypeChange(selection["value"]));
};
cascadeDocTypeChange(selection) {
this.setDomainDropdown(selection);
this.setGenericBookDropdown(selection);
this.setGenericChaptersDropdown(selection);
}
handlePropertyChange = (item) => {
this.setState({property: item.value});
};
handleMatcherChange = (item) => {
this.setState({matcher: item.value});
};
handleValueChange = (event) => {
this.setState({value: event.target.value});
};
handleSubmit = (event) => {
this.props.handleSubmit(
this.state.docType
, this.state.domain
, this.state.selectedBook
, this.state.selectedChapter
, this.state.property
, this.state.matcher
, this.state.value
);
event.preventDefault();
};
handleDomainChange = (selection) => {
this.setState({domain: selection["value"]}, this.setBookDropdown(selection["value"]));
};
handleBookChange = (selection) => {
this.setState({
selectedBook: selection["value"]
}, this.setChaptersDropdown(selection["value"]));
};
handleChapterChange = (selection) => {
this.setState({
selectedChapter: selection["value"]
, dropdownChapters: {
show: this.state.dropdownChapters.show
, msg: this.state.dropdownChapters.msg
, source: this.state.dropdownChapters.source
, initialValue: selection["value"]
}
});
};
setDomainDropdown = (docType) => {
let msg = "";
let show = false;
let source = {};
let showBooks = false;
let bookMsg = "";
let bookSource = [];
switch (docType) {
case "All": {
show = false;
break;
}
case "Biblical": {
msg = this.props.labels.domainIs;
show = true;
if (this.state.dropdowns.loaded) {
source = this.state.dropdowns.Biblical.domains;
}
break;
}
case "Liturgical": {
msg = this.props.labels.domainIs;
show = true;
if (this.state.dropdowns.loaded) {
source = this.state.dropdowns.Liturgical.domains;
showBooks = true;
bookMsg = this.props.labels.bookIs;
bookSource = this.state.dropdowns.Liturgical["all"].books;
}
break;
}
default: {
show = false;
break;
}
}
this.setState({
dropDownDomains: {
show: show
, msg: msg
, source: source
, initialValue: "*"
},
dropDownBooks: {
show: showBooks
, msg: bookMsg
, source: bookSource
, initialValue: "*"
},
dropdownChapters: {
show: false
, msg: ""
, source: []
, initialValue: "*"
}
});
};
setGenericBookDropdown(type) {
try {
let msg = this.props.labels.bookIs;
let show = false;
let source = {};
if (this.props.dropDowns) {
if (type === "Biblical" && this.state.dropdowns.Biblical) {
show = true;
source = this.state.dropdowns.Biblical.all.books;
} else if (type === "Liturgical" && this.state.dropdowns.Liturgical) {
show = true;
source = this.state.dropdowns.Liturgical.all.books;
} // end of if
}
this.setState({
dropDownBooks: {
show: show
, msg: msg
, source: source
, initialValue: "*"
}
});
} catch (error) {
this.setState({
msg: error.message
});
}
}; // end of method
setBookDropdown(domain) {
let msg = this.props.labels.bookIs;
let show = false;
let source = {};
if (domain && domain === "*") {
this.setGenericBookDropdown(this.state.docType);
} else {
if (this.state.docType === "Biblical") {
show = true;
source = this.state.dropdowns.Biblical.topics[domain];
} else if (this.state.docType === "Liturgical") {
show = true;
source = this.state.dropdowns.Liturgical.topics[domain];
} // end of if
this.setState({
dropDownBooks: {
show: show
, msg: msg
, source: source
}
});
}
}; // end of method
setChaptersDropdown(book) {
let msg = "";
let show = false;
let source = {};
if (this.state.docType === "Biblical") {
if (this.state.domain === "*") {
msg = this.props.labels.chapterIs;
show = true;
/**
* If the combination of a domain and book exists, we will use its
* chapter dropdown.
*
* Specifically, we will try to use certain
* Greek language domains as the
* basis to set generic chapter dropdowns.
* For the Old Testament, we will use the UP CCATB LXX
* Rahlf's version, and if not found, try each of the
* LXX alternative manuscripts. If that is not found,
* we will assume we are searching the New Testament,
* simply use the chapters for each book of the Patriarchal Greek NT.
*
*/
if (this.state.dropdowns.Biblical.topics['gr_eg_lxxupccat.' + book]) {
source = this.state.dropdowns.Biblical.topics['gr_eg_lxxupccat.' + book];
} else if (this.state.dropdowns.Biblical.topics['gr_eg_lxxupccatb.' + book]) {
source = this.state.dropdowns.Biblical.topics['gr_eg_lxxupccatb.' + book];
} else if (this.state.dropdowns.Biblical.topics['gr_eg_lxxupccatba.' + book]) {
source = this.state.dropdowns.Biblical.topics['gr_eg_lxxupccatba.' + book];
} else if (this.state.dropdowns.Biblical.topics['gr_eg_lxxupccatog.' + book]) {
source = this.state.dropdowns.Biblical.topics['gr_eg_lxxupccatog.' + book];
} else if (this.state.dropdowns.Biblical.topics['gr_eg_lxxupccats.' + book]) {
source = this.state.dropdowns.Biblical.topics['gr_eg_lxxupccats.' + book];
} else if (this.state.dropdowns.Biblical.topics['gr_eg_lxxupccatth.' + book]) {
source = this.state.dropdowns.Biblical.topics['gr_eg_lxxupccatth.' + book];
} else if (this.state.dropdowns.Biblical.topics['gr_gr_ntpt.' + book]) {
source = this.state.dropdowns.Biblical.topics['gr_gr_ntpt.' + book];
} else {
source = this.state.dropdowns.Biblical.all.chapters;
}
} else {
msg = this.props.labels.chapterIs;
show = true;
source = this.state.dropdowns.Biblical.topics[this.state.domain + '.' + book];
}
} else if (this.state.docType === "Liturgical") {
if (this.state.dropdowns.loaded) {
if (this.state.domain === "*") {
source = this.state.dropdowns.Liturgical.topics["gr_gr_cog." + book]
show = (source !== undefined);
} else {
source = this.state.dropdowns.Liturgical.topics[this.state.domain + "." + book]
show = (source !== undefined);
}
}
} // end of if
this.setState({
selectedChapter: "*"
, dropdownChapters: {
show: show
, msg: msg
, source: source
, initialValue: "*"
}
});
} // end of method
setGenericChaptersDropdown(type) {
let msg = "";
let show = false;
let source = {};
if (type === "Biblical") {
msg = "Select Chapter...";
show = true;
source = this.state.dropdowns.Biblical.all.chapters;
} // end of if
this.setState({
dropdownChapters: {
show: show
, msg: msg
, source: source
}
});
} // end of method
suggestedQuery(docType) {
if (docType === "Biblical") {
return "Enter a word or phrase from the Bible, even Greek...";
} else if (docType === "Liturgical") {
return "Enter a word or phrase from the Liturgical texts, even Greek...";
} else {
return "Enter a word or phrase from the Liturgical texts or the Bible, even Greek...";
}
}
getDropdownChapterTitle() {
let msg = "";
if (this.state.docType === "Biblical") {
if (this.state.domain === "*") {
msg = this.props.labels.chapterIs;
} else {
msg = this.props.labels.chapterIs;
}
} else if (this.state.docType === "Liturgical") {
switch (this.state.selectedBook) {
case "da":
msg = this.props.labels.dayIs;
break;
case "eo":
msg = this.props.labels.weekIs;
break;
case "eu":
msg = this.props.labels.serviceIs;
break;
case "he":
msg = this.props.labels.typeIs;
break;
case "hi":
msg = this.props.labels.sectionIs;
break;
case "ho":
msg = this.props.labels.sectionIs;
break;
case "oc":
msg = this.props.labels.modeIs;
break;
case "me":
msg = this.props.labels.monthIs;
break;
case "pe":
msg = this.props.labels.dayIs;
break;
case "tr":
msg = this.props.labels.dayIs;
break;
default:
msg = this.props.labels.chapterIs;
}
} // end of if
return msg;
}
getDropdownSectionTitle() {
let msg = "";
if (this.state.docType === "Biblical") {
} else if (this.state.docType === "Liturgical") {
switch (this.state.selectedBook) {
case "he":
msg = this.props.labels.modeIs;
break;
case "oc":
msg = this.props.labels.dayIs;
break;
case "me":
msg = this.props.labels.monthIs;
break;
default:
msg = "undefined subsection";
}
} // end of if
return msg;
}
render() {
return (
<div className="container">
<div>
<div className="row">
<div className="col-sm-12 col-md-12 col-lg-12">
<ResourceSelector
title={this.props.labels.findWhereTypeIs}
initialValue={this.state.docType}
resources={this.props.docTypes}
changeHandler={this.handleDocTypeChange}
multiSelect={false}
/>
</div>
</div>
{this.state.dropDownDomains.show &&
<div className="row">
<div className="col-sm-12 col-md-12 col-lg-12">
<ResourceSelector
title={this.props.labels.domainIs}
initialValue={this.state.domain}
resources={this.state.dropDownDomains.source}
changeHandler={this.handleDomainChange}
multiSelect={false}
/>
</div>
</div>
}
{this.state.dropDownBooks.show &&
<div className="row">
<div className="col-sm-12 col-md-12 col-lg-12">
<ResourceSelector
title={this.props.labels.bookIs}
initialValue={this.state.selectedBook}
resources={this.state.dropDownBooks.source}
changeHandler={this.handleBookChange}
multiSelect={false}
/>
</div>
</div>
}
{this.state.dropdownChapters.show &&
<div className="row">
<div className="col-sm-12 col-md-12 col-lg-12">
<ResourceSelector
title={this.getDropdownChapterTitle()}
initialValue={this.state.selectedChapter}
resources={this.state.dropdownChapters.source}
changeHandler={this.handleChapterChange}
multiSelect={false}
/>
</div>
</div>
}
<div><p/></div>
</div>
<div className="row">
<div className="col-sm-12">
<ResourceSelector
title={this.props.labels.propertyIs}
initialValue={this.state.property}
resources={this.props.properties}
changeHandler={this.handlePropertyChange}
multiSelect={false}
/>
<form className={"App-Search-Options-Text-Form"} onSubmit={this.handleSubmit}>
<div className="control-label">{this.props.labels.propertyTextIs}</div>
<div className={"App-Search-Options-Text-Div"}>
<input
type="text"
onChange={this.handleValueChange}
className="App-search-text-input"
name="search"
value={this.state.value}
/>
</div>
<ResourceSelector
title={this.props.labels.matcherIs}
initialValue={this.state.matcher}
resources={this.props.matchers}
changeHandler={this.handleMatcherChange}
multiSelect={false}
/>
<div className="control-label">{this.props.labels.clickTheButton}</div>
<Button
bsStyle="primary"
bsSize="xsmall"
type="submit"
disabled={this.isDisabled()}
onClick={this.handleSubmit}
>
<FontAwesome className="Button-Select-FontAwesome" name={"search"}/>
{this.props.labels.submit}
</Button>
</form>
</div>
</div>
</div>
);
}
}
SearchOptions.propTypes = {
docType: PropTypes.string.isRequired
, docTypes: PropTypes.array.isRequired
, dropDowns: PropTypes.object.isRequired
, properties: PropTypes.array.isRequired
, matchers: PropTypes.array.isRequired
, handleSubmit: PropTypes.func.isRequired
, labels: PropTypes.object.isRequired
};
export default SearchOptions; |
entry_types/scrolled/package/src/frontend/__stories__/consentBar-stories.js | tf/pageflow | import React from 'react';
import {storiesOf} from '@storybook/react';
import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport';
import {normalizeAndMergeFixture} from 'pageflow-scrolled/spec/support/stories';
import {ConsentBar} from '../thirdPartyConsent';
import {Entry, RootProviders} from 'pageflow-scrolled/frontend';
import {Consent} from 'pageflow/frontend';
const stories = storiesOf('Frontend/Consent Bar', module);
function createConsent() {
const consent = Consent.create();
consent.registerVendor('YouTube', {
paradigm: 'opt-in',
displayName: 'YouTube',
description: `
Video service<br/>
<br/>
<b>Privacy Page</b><br/>
<a href="http://example.com">Link</a>
`
});
consent.closeVendorRegistration();
return consent;
}
stories.add(
'Desktop',
() =>
<RootProviders seed={normalizeAndMergeFixture()}
consent={createConsent()}>
<ConsentBar defaultExpanded={true} />
<Backdrop />
</RootProviders>
);
stories.add(
'Mobile',
() =>
<RootProviders seed={normalizeAndMergeFixture()}
consent={createConsent()}>
<ConsentBar defaultExpanded={true} />
<Backdrop />
</RootProviders>,
{
percy: {
widths: [320]
},
viewport: {
viewports: INITIAL_VIEWPORTS,
defaultViewport: 'iphone6'
}
}
);
function Backdrop() {
return (
<div style={{background: '#aaa', height: '100vh'}} />
);
}
|
actor-apps/app-web/src/app/components/sidebar/ContactsSection.react.js | luoxiaoshenghustedu/actor-platform | import _ from 'lodash';
import React from 'react';
import { Styles, RaisedButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import ContactStore from 'stores/ContactStore';
import ContactActionCreators from 'actions/ContactActionCreators';
import AddContactStore from 'stores/AddContactStore';
import AddContactActionCreators from 'actions/AddContactActionCreators';
import ContactsSectionItem from './ContactsSectionItem.react';
import AddContactModal from 'components/modals/AddContact.react.js';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
isAddContactModalOpen: AddContactStore.isModalOpen(),
contacts: ContactStore.getContacts()
};
};
class ContactsSection extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
componentWillUnmount() {
ContactActionCreators.hideContactList();
ContactStore.removeChangeListener(this.onChange);
AddContactStore.removeChangeListener(this.onChange);
}
constructor(props) {
super(props);
this.state = getStateFromStores();
ContactActionCreators.showContactList();
ContactStore.addChangeListener(this.onChange);
AddContactStore.addChangeListener(this.onChange);
ThemeManager.setTheme(ActorTheme);
}
onChange = () => {
this.setState(getStateFromStores());
};
openAddContactModal = () => {
AddContactActionCreators.openModal();
};
render() {
let contacts = this.state.contacts;
let contactList = _.map(contacts, (contact, i) => {
return (
<ContactsSectionItem contact={contact} key={i}/>
);
});
let addContactModal;
if (this.state.isAddContactModalOpen) {
addContactModal = <AddContactModal/>;
}
return (
<section className="sidebar__contacts">
<ul className="sidebar__list sidebar__list--contacts">
{contactList}
</ul>
<footer>
<RaisedButton label="Add contact" onClick={this.openAddContactModal} style={{width: '100%'}}/>
{addContactModal}
</footer>
</section>
);
}
}
export default ContactsSection;
|
src/atoms/Text/index.js | policygenius/athenaeum | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import omit from 'lodash/omit';
import colors from 'atoms/Color/colors.scss';
import styles from './text.module.scss';
const getTag = (props) => {
const {
tag,
semibold,
variant,
} = props;
if (semibold) return 'strong';
if (variant === 'italics') return 'em';
if (variant === 'strikethrough') return 'span';
return tag;
};
const getFont = ({
size, type, font, a
}) => {
const fontSize = type || size;
// TODO: Remove 'a' prop as an option from component
if (a || font === 'a') {
return styles[`type-a-${fontSize}-bold`];
} if (font === 'c') {
return styles['type-c-7-regular'];
}
return styles[`type-b-${fontSize}-medium`];
};
const convertChild = (child) => {
// Check children for other TextComponents
// and automatically convert them into <spans> if they are <p>.
if (!child) { return null; }
if (child.type === Text && child.props.tag === 'p') {
return React.cloneElement(child, { tag: 'span' });
}
return child;
};
const getWeight = ({ font, bold, semibold }) => {
if (font !== 'b') { return false; }
if (bold || semibold ) { return styles.bold; }
return false;
};
function Text(props) {
// TODO: Consider adding an html sanitizer
const {
align,
children,
className,
color,
italic,
spaced,
variant,
inherit,
inheritSize,
inheritColor,
dangerouslySetInnerHTML,
...rest
} = props;
if (!children && !dangerouslySetInnerHTML) return null;
const font = getFont(props);
const weight = getWeight(props);
const tag = getTag(props);
const classes = [
weight && weight,
color && colors[color],
variant && styles[variant],
align && styles[align],
spaced && styles['spaced'],
italic && styles['italic'],
className && className,
font && font,
inherit && styles['inherit'],
inheritSize && styles['inherit-size'],
inheritColor && styles['inherit-color']
];
return React.createElement(
tag,
{
className: classnames(classes),
...omit(
rest,
[ 'font', 'semibold', 'size', 'tag', 'type', 'bold' ]
)
},
React.Children.map(children, convertChild)
);
}
Text.propTypes = {
/*
* If neither children nor dangerouslySetInnerHTML is set, this component will return null
*/
dangerouslySetInnerHTML: PropTypes.shape({
__html: PropTypes.string
}),
/*
* Text alignment
*/
align: PropTypes.oneOf([
'left',
'right',
'center'
]),
/**
* This prop will add a new className to any inherent classNames
* provided in the component's index.js file.
*/
className: PropTypes.string,
/**
* You can use any html element text tag
*/
tag: PropTypes.string,
/**
* Determines typography class
*
* Types for `a`: `1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11`
*
* Types for `b`: `5, 6, 7, 8, 10, 12`
*
* Types fo `c`: `1`
*/
size: PropTypes.number,
/**
* Text decoration
*/
variant: PropTypes.oneOf([
'strikethrough',
'underline',
'fineprint',
'label'
]),
/**
* Color style, see [Colors](#colors) for appropriate values
*/
color: PropTypes.string,
/**
* Possible font types are `a`, `b`, and `c`
*/
font: PropTypes.string,
/**
* Adds letter spacing. Use with `A9` and `A11` font
*/
spaced: PropTypes.bool,
/**
* Makes text bold
*/
bold: PropTypes.bool,
/**
* Adds italic
*/
italic: PropTypes.bool,
/**
* Deprecated. Use 'size' instead
*/
type: PropTypes.number,
/**
* Deprecated
*/
weight: PropTypes.oneOf([]),
/**
* Deprecated
*/
light: PropTypes.bool,
/**
* Deprecated
*/
semibold: PropTypes.bool,
/**
* Deprecated
*/
a: PropTypes.bool,
/**
* Deprecated
*/
b: PropTypes.bool,
/**
* Inherit font-size, line-height, and color from parent
*/
inherit: PropTypes.bool,
/**
* Inherit font-size from parent
*/
inheritSize: PropTypes.bool,
/**
* Inherit color from parent
*/
inheritColor: PropTypes.bool,
};
Text.defaultProps = {
color: 'primary-3',
font: 'b',
inherit: true,
size: 8,
tag: 'p',
};
export default Text;
|
app/javascript/mastodon/features/hashtag_timeline/index.js | palon7/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import {
refreshHashtagTimeline,
expandHashtagTimeline,
updateTimeline,
deleteFromTimelines,
} from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import { FormattedMessage } from 'react-intl';
import createStream from '../../stream';
const mapStateToProps = state => ({
hasUnread: state.getIn(['timelines', 'tag', 'unread']) > 0,
streamingAPIBaseURL: state.getIn(['meta', 'streaming_api_base_url']),
accessToken: state.getIn(['meta', 'access_token']),
});
@connect(mapStateToProps)
export default class HashtagTimeline extends React.PureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
columnId: PropTypes.string,
dispatch: PropTypes.func.isRequired,
streamingAPIBaseURL: PropTypes.string.isRequired,
accessToken: PropTypes.string.isRequired,
hasUnread: PropTypes.bool,
multiColumn: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('HASHTAG', { id: this.props.params.id }));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
_subscribe (dispatch, id) {
const { streamingAPIBaseURL, accessToken } = this.props;
this.subscription = createStream(streamingAPIBaseURL, accessToken, `hashtag&tag=${id}`, {
received (data) {
switch(data.event) {
case 'update':
dispatch(updateTimeline(`hashtag:${id}`, JSON.parse(data.payload)));
break;
case 'delete':
dispatch(deleteFromTimelines(data.payload));
break;
}
},
});
}
_unsubscribe () {
if (typeof this.subscription !== 'undefined') {
this.subscription.close();
this.subscription = null;
}
}
componentDidMount () {
const { dispatch } = this.props;
const { id } = this.props.params;
dispatch(refreshHashtagTimeline(id));
this._subscribe(dispatch, id);
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.id !== this.props.params.id) {
this.props.dispatch(refreshHashtagTimeline(nextProps.params.id));
this._unsubscribe();
this._subscribe(this.props.dispatch, nextProps.params.id);
}
}
componentWillUnmount () {
this._unsubscribe();
}
setRef = c => {
this.column = c;
}
handleLoadMore = () => {
this.props.dispatch(expandHashtagTimeline(this.props.params.id));
}
render () {
const { hasUnread, columnId, multiColumn } = this.props;
const { id } = this.props.params;
const pinned = !!columnId;
return (
<Column ref={this.setRef}>
<ColumnHeader
icon='hashtag'
active={hasUnread}
title={id}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
showBackButton
/>
<StatusListContainer
trackScroll={!pinned}
scrollKey={`hashtag_timeline-${columnId}`}
timelineId={`hashtag:${id}`}
loadMore={this.handleLoadMore}
emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />}
/>
</Column>
);
}
}
|
examples/huge-apps/routes/Course/routes/Announcements/components/Sidebar.js | Jonekee/react-router | import React from 'react';
import { Link } from 'react-router';
export default class AnnouncementsSidebar extends React.Component {
render () {
var announcements = COURSES[this.props.params.courseId].announcements;
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{announcements.map(announcement => (
<li key={announcement.id}>
<Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}>
{announcement.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
|
src/initialise.js | devonChurch/cheese-burger | import React from 'react';
import {render} from 'react-dom';
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import {StyleRoot} from 'radium';
import reducer from './state/reducer';
import defaultState from './state/default';
import defaultProps from './props/default';
import Scaffold from './scaffold/view';
const cheeseBurger = document.getElementById('cheese-burger');
function renderMe(store) {
render(
<Provider store={store}>
<StyleRoot>
<Scaffold content={defaultProps}/>
</StyleRoot>
</Provider>,
cheeseBurger
);
}
function devTools() {
return window.devToolsExtension ? window.devToolsExtension() : undefined;
}
const store = createStore(
reducer,
defaultState,
devTools()
);
// Render on state change.
store.subscribe(() => renderMe(store));
// Prompt initial render on page load.
renderMe(store);
|
examples/using-sqip/src/pages/index.js | ChristopherBiscardi/gatsby | import React from 'react'
import PropTypes from 'prop-types'
import { graphql } from 'gatsby'
import Layout from '../components/layout.js'
const IndexPage = ({ data }) => (
<Layout data={data}>
<h1>Gatsby SQIP Example</h1>
<blockquote>
<p>
SQIP - pronounced \skwɪb\ like the non-magical folk of magical descent
</p>
</blockquote>
<p>It is a svg based implementation of low quality image previews (LQIP)</p>
<p>
<strong>More precisely:</strong>
<br /> An algorithm calculates a primitive representation of your images
based on simple shapes like circles, ellipses, triangles and more. These
will be embedded in your initial HTML payload. This will help your users
to get a feeling of how the pictures will look like, even
{` `}
<strong>before</strong> they got loaded by their (probably) slow
connection.
</p>
<h2>Configuration</h2>
<p>
For an up to date list of possible configuration options, please check out
the
{` `}
<a href="https://www.gatsbyjs.org/packages/gatsby-transformer-sqip/">
plugins readme
</a>
.
</p>
<h3>Configuration and file size recommendations:</h3>
<p>
The maximum size of your previews really depend on your current html
payload size and your personal limits
</p>
<ul>
<li>Smaller thumbnails should range between 500-1000byte</li>
<li>A single header image or a full sized hero might take 1-10kb</li>
<li>
For frequent previews like article teasers or image gallery thumbnails
I’d recommend 15-25 shapes
</li>
<li>For header and hero images you may go up to 50-200 shapes</li>
</ul>
<p>
Generally: <strong>Keep it as small as possible</strong> and test the
impact of your image previews via
{` `}
<a href="https://www.webpagetest.org/">webpagetest.org</a> on a 3G
connection.
</p>
<h2>Usage</h2>
<p>Getting the data via GraphQL:</p>
<pre>
<code>{`image {
sqip(numberOfPrimitives: 12, blur: 12, width: 256, height: 256),
sizes(maxWidth: 400, maxHeight: 400) {
...GatsbyImageSharpSizes_noBase64
}
}`}</code>
</pre>
<p>
<strong>Hint:</strong> Make sure to set the same aspect ratio for sqip and
sizes/resolutions. For performance and quality, 256px width is a good base
value for SQIP
</p>
<h3>Pure JSX/HTML</h3>
<pre>
<code>{`<div className="image-wrapper">
<img src={image.dataURI} alt="" role="presentation" />
<img src={image.src} alt="Useful description" className="image" />
</div>`}</code>
</pre>
<pre>
<code>{`.image-wrapper {
position: relative;
overflow: hidden;
}
.image-wrapper img {
display: block;
}
.image-wrapper img.image {
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 100%;
height: auto;
z-index: 1;
}`}</code>
</pre>
<h4>Pros:</h4>
<ul>
<li>No client-side JavaScript required</li>
<li>
Browser cache ensures previews are not shown when a user visits the page
a second time
</li>
</ul>
<h4>Cons:</h4>
<ul>
<li>
All images are loaded, no matter if they are in the viewport or not
</li>
</ul>
<h3>Gatsby Image</h3>
<pre>
<code>{`const Img = require(\`gatsby-image\`)
<Img
resolutions={{
...image.resolutions,
base64: image.sqip
}}
/>
// or
<Img
sizes={{
...image.sizes,
base64: image.sqip
}}
/>`}</code>
</pre>
<h4>Pros:</h4>
<ul>
<li>Nice fade-in effect</li>
<li>Only images within the viewport are loaded</li>
</ul>
<h4>Cons:</h4>
<ul>
<li>Requires client-side JavaScript</li>
<li>
Images fade in all the time, even when the image is already in the
browser cache
</li>
</ul>
<h2>Copyright notice</h2>
<p>
The used images belong to their photographer, get more details by clicking
on them. The background image was taken by
{` `}
<a href="https://unsplash.com/photos/ljHAKAnYs4I">Neven Krcmarek</a>.
</p>
</Layout>
)
export default IndexPage
IndexPage.propTypes = {
data: PropTypes.object,
}
export const query = graphql`
query {
images: allFile(
filter: { sourceInstanceName: { eq: "images" }, ext: { eq: ".jpg" } }
) {
edges {
node {
publicURL
name
childImageSharp {
fluid(maxWidth: 400, maxHeight: 400) {
...GatsbyImageSharpFluid_noBase64
}
sqip(
# Make sure to keep the same aspect ratio when cropping
# With 256px as maximum dimension is the perfect value to speed up the process
width: 256
height: 256
numberOfPrimitives: 15
blur: 8
mode: 1
) {
dataURI
}
}
}
}
}
background: allFile(
filter: { sourceInstanceName: { eq: "background" }, ext: { eq: ".jpg" } }
) {
edges {
node {
publicURL
name
childImageSharp {
fluid(maxWidth: 4000) {
...GatsbyImageSharpFluid_noBase64
}
sqip(numberOfPrimitives: 160, blur: 0) {
dataURI
}
}
}
}
}
}
`
|
docs/src/NavMain.js | chilts/react-bootstrap | import React from 'react';
import { Link } from 'react-router';
import Navbar from '../../src/Navbar';
import Nav from '../../src/Nav';
const NAV_LINKS = {
'introduction': {
link: 'introduction',
title: 'Introduction'
},
'getting-started': {
link: 'getting-started',
title: 'Getting started'
},
'components': {
link: 'components',
title: 'Components'
},
'support': {
link: 'support',
title: 'Support'
}
};
const NavMain = React.createClass({
propTypes: {
activePage: React.PropTypes.string
},
render() {
let brand = <Link to="home" className="navbar-brand">React-Bootstrap</Link>;
let links = Object.keys(NAV_LINKS).map(this.renderNavItem).concat([
<li key="github-link">
<a href="https://github.com/react-bootstrap/react-bootstrap" target="_blank">GitHub</a>
</li>
]);
return (
<Navbar componentClass="header" brand={brand} staticTop className="bs-docs-nav" role="banner" toggleNavKey={0}>
<Nav className="bs-navbar-collapse" role="navigation" eventKey={0} id="top">
{links}
</Nav>
</Navbar>
);
},
renderNavItem(linkName) {
let link = NAV_LINKS[linkName];
return (
<li className={this.props.activePage === linkName ? 'active' : null} key={linkName}>
<Link to={link.link}>{link.title}</Link>
</li>
);
}
});
export default NavMain;
|
src/pages/Main/Content.js | bogas04/SikhJS | import React from 'react';
import styled from 'react-emotion';
import { Switch, Route } from 'react-router-dom';
import { connect } from 'react-redux';
import {
Author, Raag, Raags, Authors, Home, Bookmarks, Hukamnama, Baani,
SGGS, Nitnem, Calendar, Shabad, Shabads, NotFound, Settings,
} from '../';
import pageTitleEnchancer from '../pageTitleEnchancer';
import { Search } from '../../components/Icons';
import { DisplayOnScroll, FloatingIcon } from '../../components';
const mapStateToProps = ({ fontSize }) => ({ fontSize });
const BaaniWrapper = connect(mapStateToProps, null)(styled.div`
transition: all 0.25s ease-in-out;
font-size: ${({ fontSize }) => `${fontSize}px`};
position: absolute;
top: 64px;
left: 0;
width: 100%;
padding-bottom: 100px;
`);
const propsToParamTitle = param => props => props.match.params[param];
const propsToSGGSTitle = props => 'Sri Guru Granth Sahib - Ang ' + props.match.params.ang;
const Content = () => (
<div>
<BaaniWrapper id="baaniWrapper">
<Switch>
<Route path="/" component={Home} exact />
<Route path="/sggs/:ang?" component={pageTitleEnchancer(propsToSGGSTitle)(SGGS)} />
<Route path="/calendar" component={pageTitleEnchancer('Calendar')(Calendar)} />
<Route path="/shabads/:q([a-z]+)?" exact component={pageTitleEnchancer('Search Shabads')(Shabads)} />
<Route path="/shabads/:id(\d+)" exact component={Shabad} />
<Route path="/settings" component={pageTitleEnchancer('Settings')(Settings)} />
<Route path="/bookmarks" component={pageTitleEnchancer('Bookmarks')(Bookmarks)} />
<Route path="/authors" exact component={pageTitleEnchancer('Authors')(Authors)} />
<Route path="/authors/:id/:name?" component={pageTitleEnchancer(propsToParamTitle('name'))(Author)} />
<Route path="/raags" exact component={pageTitleEnchancer('Raags')(Raags)} />
<Route path="/raags/:id/:name" component={pageTitleEnchancer(propsToParamTitle('name'))(Raag)} />
<Route path="/nitnem" exact component={pageTitleEnchancer('Nitnem')(Nitnem)} />
<Route path="/nitnem/:baani" component={pageTitleEnchancer(propsToParamTitle('baani'))(Baani)} />
<Route path="/hukamnama" component={pageTitleEnchancer('Hukamnama')(Hukamnama)} />
<Route component={NotFound} />
</Switch>
</BaaniWrapper>
<Route path="/shabads" exact>{({ match }) => !match && (
<DisplayOnScroll>
<FloatingIcon to="/shabads">
<Search height="30px" width="30px" />
</FloatingIcon>
</DisplayOnScroll>
)}
</Route>
</div>
);
export default Content;
|
src/renderer/main.js | MrBlenny/museeks | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, hashHistory } from 'react-router';
import { Provider } from 'react-redux';
import getRoutes from './router/routes';
import store from './redux/store';
import lib, { initLib } from './lib';
import initRenderer from './init';
import { RpcIpcManager } from 'electron-simple-rpc';
// Initialise shared libraries with the store
initLib(store);
// Start listening for RPC IPC events
new RpcIpcManager(lib, 'main-renderer');
// Init renderer
initRenderer(lib);
require('bootstrap-css-only/css/bootstrap.min.css');
require('font-awesome/css/font-awesome.css');
require('../styles/main.scss');
ReactDOM.render(
<Provider store={ store }>
<Router routes={ getRoutes(store) } history={ hashHistory } />
</Provider>,
document.getElementById('wrap')
);
|
src/pages/Router/component.js | exeto/react-redux-starter | import React from 'react';
import PropTypes from 'prop-types';
import { NOT_FOUND } from 'redux-first-router';
import * as types from '@/redux/router/types';
import List from '@/pages/List';
import Item from '@/pages/Item';
import NotFound from '@/pages/NotFound';
import Base from '@/components/Base';
const mapping = {
[types.LIST]: List,
[types.ITEM]: Item,
[NOT_FOUND]: NotFound,
};
const Router = ({ type }) => {
const Component = mapping[type];
return (
<Base>
<Component />
</Base>
);
};
Router.propTypes = {
type: PropTypes.string.isRequired,
};
export default Router;
|
public/js/cat_source/es6/components/languageSelector/LanguageSelector.js | matecat/MateCat | import React from 'react'
import Header from '../header/Header'
import LanguageSelectorList from './LanguageSelectorList'
import LanguageSelectorSearch from './LanguageSelectorSearch'
class LanguageSelector extends React.Component {
constructor(props) {
super(props)
this.state = {
selectedLanguages: null,
initialLanguages: null,
fromLanguage: null,
querySearch: '',
}
}
componentDidMount() {
const {selectedLanguagesFromDropdown, languagesList, fromLanguage} =
this.props
document.addEventListener('keydown', this.pressEscKey)
this.setState({
fromLanguage: languagesList.filter((i) => i.code === fromLanguage)[0],
selectedLanguages: selectedLanguagesFromDropdown.map(
(e) => languagesList.filter((i) => i.code === e)[0],
),
initialLanguages: selectedLanguagesFromDropdown.map(
(e) => languagesList.filter((i) => i.code === e)[0],
),
})
}
componentWillUnmount() {
document.removeEventListener('keydown', this.pressEscKey)
}
componentDidUpdate() {}
render() {
const {
onQueryChange,
onToggleLanguage,
onConfirm,
preventDismiss,
onRestore,
onReset,
} = this
const {languagesList, onClose} = this.props
const {selectedLanguages, querySearch, fromLanguage} = this.state
return (
<div
id="matecat-modal-languages"
className="matecat-modal"
onClick={onClose}
>
<div className="matecat-modal-content" onClick={preventDismiss}>
<div className="matecat-modal-header">
<span className={'modal-title'}>Multiple Languages</span>
<span className="close-matecat-modal x-popup" onClick={onClose} />
</div>
<div className="matecat-modal-body">
<div className="matecat-modal-subheader">
<div className={'language-from'}>
<div className={'first-column'}>
<span className={'label'}>From:</span>
</div>
<div>
<span>{fromLanguage && fromLanguage.name}</span>
</div>
</div>
<div className={'language-to'}>
<div className={'first-column'}>
<span className={'label'}>To:</span>
</div>
<div className={'language-search'}>
<LanguageSelectorSearch
languagesList={languagesList}
selectedLanguages={selectedLanguages}
querySearch={querySearch}
onDeleteLanguage={onToggleLanguage}
onQueryChange={onQueryChange}
/>
</div>
</div>
</div>
<LanguageSelectorList
languagesList={languagesList}
selectedLanguages={selectedLanguages}
querySearch={querySearch}
changeQuerySearch={onQueryChange}
onToggleLanguage={onToggleLanguage}
/>
</div>
<div className="matecat-modal-footer">
<div className="selected-counter">
{selectedLanguages && selectedLanguages.length > 0 ? (
<span className={'uncheck-all'} onClick={onReset}>
<svg
xmlns="http://www.w3.org/2000/svg"
width="12"
height="12"
viewBox="0 0 12 12"
>
<g
fill="#00AEE4"
fillRule="nonzero"
stroke="#00AEE4"
strokeWidth="1"
transform="translate(-5 -5) translate(5 5)"
>
<rect
width="13"
height="1"
x="-0.5"
y="5.5"
rx="0.5"
transform="rotate(45 6 6)"
>
{' '}
</rect>
<rect
width="13"
height="1"
x="-0.5"
y="5.5"
rx="0.5"
transform="rotate(-45 6 6)"
>
{' '}
</rect>
</g>
</svg>
</span>
) : null}
<span className={'badge'}>
{selectedLanguages && selectedLanguages.length}
</span>
<span className={'label'}>language selected</span>
</div>
<div className="">
<button
className={'modal-btn secondary gray'}
onClick={onRestore}
>
Restore all
</button>
<button className={'modal-btn primary blue'} onClick={onConfirm}>
Confirm
</button>
</div>
</div>
</div>
</div>
)
}
preventDismiss = (event) => {
event.stopPropagation()
}
onConfirm = () => {
//confirm must have 1 language selected
const {selectedLanguages} = this.state
this.props.onConfirm(selectedLanguages)
}
onQueryChange = (querySearch) => {
this.setState({querySearch})
}
onToggleLanguage = (language) => {
const {selectedLanguages} = this.state
let newSelectedLanguages = [...selectedLanguages]
const indexSearch = selectedLanguages
.map((e) => e.code)
.indexOf(language.code)
if (indexSearch > -1) {
newSelectedLanguages.splice(indexSearch, 1)
} else {
newSelectedLanguages.push(language)
}
this.setState({
selectedLanguages: newSelectedLanguages,
})
//when add a language, restore query search.
}
onRestore = () => {
const {initialLanguages} = this.state
this.setState({
selectedLanguages: initialLanguages,
querySearch: '',
})
}
onReset = () => {
this.setState({
selectedLanguages: [],
querySearch: '',
})
}
pressEscKey = (event) => {
const {onClose} = this.props
const keyCode = event.keyCode
if (keyCode === 27) {
onClose()
}
//27
}
}
LanguageSelector.defaultProps = {
selectedLanguagesFromDropdown: false,
fromLanguage: true,
languagesList: true,
onClose: true,
onConfirm: true,
}
export default LanguageSelector
|
react/gameday2/components/embeds/EmbedNotSupported.js | phil-lopreiato/the-blue-alliance | import React from 'react'
const EmbedNotSupported = () => {
const containerStyles = {
margin: 20,
textAlign: 'center',
}
const textStyles = {
color: '#ffffff',
}
return (
<div style={containerStyles}>
<p style={textStyles}>This webcast is not supported.</p>
</div>
)
}
export default EmbedNotSupported
|
webpack/scenes/RedHatRepositories/index.js | cfouant/katello | /* eslint-disable import/no-extraneous-dependencies */
/* eslint import/no-unresolved: [2, { ignore: [foremanReact/*] }] */
/* eslint-disable import/no-unresolved */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Grid, Row, Col } from 'react-bootstrap';
import { Button } from 'patternfly-react';
import { LoadingState } from '../../move_to_pf/LoadingState';
import { createEnabledRepoParams, loadEnabledRepos } from '../../redux/actions/RedHatRepositories/enabled';
import { loadRepositorySets, updateRecommendedRepositorySets } from '../../redux/actions/RedHatRepositories/sets';
import SearchBar from './components/SearchBar';
import RecommendedRepositorySetsToggler from './components/RecommendedRepositorySetsToggler';
import { getSetsComponent, getEnabledComponent } from './helpers';
import api from '../../services/api';
class RedHatRepositoriesPage extends Component {
componentDidMount() {
this.loadData();
}
loadData() {
this.props.loadEnabledRepos();
this.props.loadRepositorySets({ search: { filters: ['rpm'] } });
}
render() {
const { enabledRepositories, repositorySets } = this.props;
const { repoParams } = createEnabledRepoParams(enabledRepositories);
return (
<Grid id="redhatRepositoriesPage" bsClass="container-fluid">
<h1>{__('Red Hat Repositories')}</h1>
<Row className="toolbar-pf">
<Col sm={12}>
<SearchBar />
</Col>
</Row>
<Row className="row-eq-height">
<Col sm={6} className="available-repositories-container">
<div className="available-repositories-header">
<h2>{__('Available Repositories')}</h2>
<RecommendedRepositorySetsToggler
enabled={repositorySets.recommended}
onChange={value => this.props.updateRecommendedRepositorySets(value)}
className="recommended-repositories-toggler"
/>
</div>
<LoadingState loading={repositorySets.loading} loadingText={__('Loading')}>
{getSetsComponent(
repositorySets,
(pagination) => {
this.props.loadRepositorySets({
...pagination,
search: repositorySets.search,
});
},
)}
</LoadingState>
</Col>
<Col sm={6} className="enabled-repositories-container">
<h2>
{__('Enabled Repositories')}
<Button
className="pull-right"
onClick={() => { api.open('/repositories.csv', repoParams); }}
>
{__('Export as CSV')}
</Button>
</h2>
<LoadingState loading={enabledRepositories.loading} loadingText={__('Loading')}>
{getEnabledComponent(
enabledRepositories,
(pagination) => {
this.props.loadEnabledRepos({
...pagination,
search: enabledRepositories.search,
});
},
)}
</LoadingState>
</Col>
</Row>
</Grid>
);
}
}
RedHatRepositoriesPage.propTypes = {
loadEnabledRepos: PropTypes.func.isRequired,
loadRepositorySets: PropTypes.func.isRequired,
updateRecommendedRepositorySets: PropTypes.func.isRequired,
enabledRepositories: PropTypes.shape({}).isRequired,
repositorySets: PropTypes.shape({}).isRequired,
};
const mapStateToProps = ({
katello: {
redHatRepositories: { enabled, sets },
},
}) => ({
enabledRepositories: enabled,
repositorySets: sets,
});
export default connect(mapStateToProps, {
loadEnabledRepos,
loadRepositorySets,
updateRecommendedRepositorySets,
})(RedHatRepositoriesPage);
|
src/features/remember/index.js | rldona/react-native-tab-view-seed | import React, { Component } from 'react';
import {
View,
Text,
Alert,
TextInput,
Image,
Keyboard,
TouchableOpacity,
StyleSheet,
Dimensions
} from 'react-native';
import * as loginService from '../../services/login-service';
import * as themoviedb from '../../services/movies-service';
import * as colors from '../../common/colors';
import Loading from '../../common/loading';
import Icon from 'react-native-vector-icons/MaterialIcons';
const { width, height } = Dimensions.get('window');
export default class Remember extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
showLoading: false
};
}
_goBack() {
themoviedb.getNavigator().pop();
}
_remember() {
Keyboard.dismiss();
if (this.state.email !== '' && this.state.email.length > 4) {
this.setState({showLoading: true});
loginService.retrievePassword(this.state.email)
.then(() => {
themoviedb.getNavigator().replace({ index: 0.1, title: 'login'});
}, (error) => {
if (error.code === 'auth/invalid-email') {
Alert.alert(
'Email no válido',
'El formato de email introducido no es correcto',
[
{text: 'OK'},
],
{ cancelable: true }
);
}
if (error.code === 'auth/user-not-found') {
Alert.alert(
'Usuario no registrado',
'El email que has introducido no pertenece a ningún usuario',
[
{text: 'OK'},
],
{ cancelable: true }
);
}
this.setState({showLoading: false});
});
} else {
this.setState({showLoading: false});
if (this.state.email === '') {
Alert.alert(
'Campo obligatorio',
'Tienes que introducir un email',
[
{text: 'OK'},
],
{ cancelable: true }
);
return true;
}
if (this.state.email.length < 4) {
Alert.alert(
'Email no válido',
'El formato de email introducido no es correcto',
[
{text: 'OK'},
],
{ cancelable: true }
);
}
}
}
showButtonLoading() {
if (!this.state.showLoading) {
return (
<Text style={styles.buttonTextClear}>CAMBIAR LA CONTRASEÑA</Text>
);
} else {
return (
<Loading color="#FFF" size={19} />
);
}
}
renderButtonStyle() {
if (this.state.email !== '' && this.state.email.length > 4) {
return {
marginTop: 30,
paddingTop: 17,
paddingLeft: 20,
paddingRight: 20,
paddingBottom: 17,
borderRadius: 3,
borderWidth: 2,
borderColor: colors.getList().app,
backgroundColor: colors.getList().app,
marginBottom: 20,
minWidth: 300
}
} else {
return {
marginTop: 30,
paddingTop: 17,
paddingLeft: 20,
paddingRight: 20,
paddingBottom: 17,
borderRadius: 3,
borderWidth: 2,
borderColor: '#333',
backgroundColor: '#333',
marginBottom: 20,
minWidth: 300
}
}
}
renderButtonOpacityStyle() {
if (this.state.email !== '' && this.state.email.length > 4) {
return 0.8;
} else {
return 1;
}
}
render() {
return(
<View style={styles.container} renderToHardwareTextureAndroid={true}>
<View style={{height: height, width: width}}>
<Image source={require('../../assets/img/bg-welcome-light.png')} style={styles.bg} />
</View>
<View style={{position: 'absolute', top: 30, left: width/2-150, width: 300}}>
<Text onPress={this._goBack.bind(this)} style={styles.textBack}>
<Icon name="arrow-back" size={30} color="#FFF" />
</Text>
<Text style={styles.labelRemember}>Introduce tu email para que te enviemos un formulario de cambio de contraseña</Text>
<TextInput
style={styles.input}
onChangeText={(email) => this.setState({email})}
value={this.state.email}
autoFocus={true}
placeholder="Email"
placeholderTextColor="#666"
onSubmitEditing={this._remember.bind(this)}
returnKeyType="done"
autoFocus={false}
/>
<TouchableOpacity onPress={this._remember.bind(this)} style={this.renderButtonStyle()} activeOpacity={this.renderButtonOpacityStyle()}>
{this.showButtonLoading()}
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'flex-start',
backgroundColor: colors.getList().primary,
// paddingTop: 10,
// padding: 30
},
center: {
alignItems: 'center',
justifyContent: 'center',
width: 200,
backgroundColor: 'rgba(255,255,255,0.2)'
},
textBack: {
marginTop: 24,
paddingLeft: -5,
marginBottom: 30,
},
arrowBack: {
width: 30,
height: 30
},
label: {
textAlign: 'left',
fontSize: 25,
marginBottom: 30,
color: colors.getList().white
},
labelRemember: {
fontSize: 18,
marginBottom: 30,
color: colors.getList().white
},
input: {
minWidth: 300,
marginBottom: 25,
fontSize: 15,
paddingVertical: 10,
color: colors.getList().white
},
button: {
marginTop: 30,
paddingTop: 17,
paddingLeft: 20,
paddingRight: 20,
paddingBottom: 17,
borderRadius: 3,
borderWidth: 2,
borderColor: colors.getList().app,
backgroundColor: colors.getList().app,
marginBottom: 20,
minWidth: 300,
},
buttonClear: {
paddingTop: 17,
paddingLeft: 20,
paddingRight: 20,
paddingBottom: 17,
borderRadius: 3,
borderWidth: 2,
borderColor: colors.getList().app,
backgroundColor: colors.getList().primary,
marginBottom: 20,
minWidth: 300
},
buttonText: {
color: '#444',
textAlign: 'center',
fontWeight: 'bold',
fontSize: 14
},
buttonTextClear: {
color: colors.getList().white,
textAlign: 'center',
fontWeight: 'bold',
fontSize: 14
}
});
|
src/index.js | ljones140/react_redux_weather_app | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
|
information/blendle-frontend-react-source/app/modules/sectionsPage/components/Intro/index.js | BramscoChill/BlendleParser | import React from 'react';
import { string } from 'prop-types';
import { config as i18nConfig } from 'instances/i18n';
import { SmallScreenOnly, NotSmallScreen } from 'components/BreakPoints';
import HTMLWithLinks from 'components/HTMLWithLinks';
import FormattedDate from 'components/FormattedDate';
import CSS from './style.scss';
const alignment = [CSS.horizontalAlignment, CSS.verticalAlignment].join(' ');
const linkProps = {
analytics: { type: 'sections-intro' },
};
function Intro({ introHtml, date, timeOfDayTitle }) {
return (
<div className={alignment}>
<NotSmallScreen>
<span>
<FormattedDate
date={date}
format={i18nConfig.sectionIntroLongDateFormat}
className={CSS.date}
component="strong"
/>
<h2 className={CSS.timeOfDay}>{timeOfDayTitle}</h2>
</span>
</NotSmallScreen>
<SmallScreenOnly>
<FormattedDate date={date} format="dddd" className={CSS.timeOfDay} component="h2" />
</SmallScreenOnly>
<HTMLWithLinks className={CSS.intro} linkProps={linkProps}>
{introHtml}
</HTMLWithLinks>
</div>
);
}
Intro.propTypes = {
introHtml: string,
date: string.isRequired,
timeOfDayTitle: string.isRequired,
};
Intro.defaultProps = {
introHtml: '',
};
export default Intro;
// WEBPACK FOOTER //
// ./src/js/app/modules/sectionsPage/components/Intro/index.js |
src/routes/blogPost/index.js | goldylucks/adamgoldman.me | import React from 'react'
import axios from 'axios'
import BlogPost from './BlogPost'
import Transcript from './Transcript'
import Layout from '../../components/Layout'
const dbPosts = [
'healing-metaphors-water-slime',
'ocd-and-guilt-gone-in-one-session',
'resolving-cramps-with-metaphors',
'oliver-anxiety-ocd',
]
async function action({ params, path }) {
if (dbPosts.includes(params.post)) {
const { data } = await axios.get(`/api/posts/${params.post}`)
const Comp = data.transcript.length ? Transcript : BlogPost
return {
title: data.title,
description: data.description,
path,
component: (
<Layout path={path}>
<Comp {...data} />
</Layout>
),
}
}
const post = await import(`../../posts/${params.post}.js`)
.then(module => module.default) // use an object from `export default`
.catch(error => {
if (error.message.startsWith('Cannot find module')) {
return null // module (post) does not exists
}
throw error // loading chunk failed (render error page)
})
if (!post) return null // go to next route (or render 404)
const Comp = post.transcript ? Transcript : BlogPost
return {
title: post.title,
path,
description: post.description,
component: (
<Layout path={path}>
<Comp {...post} />
</Layout>
),
}
}
export default action
|
lib/components/TorrentTitleRow.js | imsnif/wtorrent-browser | "use strict";
import prettyMs from 'pretty-ms';
import React from 'react';
import { Row } from 'react-bootstrap';
import { Col } from 'react-bootstrap';
import { ProgressBar } from 'react-bootstrap';
import DeleteButton from '../containers/DeleteButton';
export default class TorrentTitleRow extends React.Component {
render () {
const torrent = this.props.torrent
const downloadSpeed = torrent.downloadSpeed ? Math.round(torrent.downloadSpeed / 1000) + "K" : "0K";
const uploadSpeed = torrent.downloadSpeed ? Math.round(torrent.uploadSpeed / 1000) + "K" : "0K";
const progress = torrent.progress ? Math.floor(torrent.progress * 100) : 0
const timeRemaining = torrent.timeRemaining ?
prettyMs(Math.round(torrent.timeRemaining), { compact: true }) + " remaining":
0
return (
<Row>
<Col xs={5} className="textOverflow" title={torrent.name}>{torrent.name}</Col>
<Col xs={3}>
<ProgressBar
striped
bsStyle="success"
now={progress}
label="%(percent)s%"
/>
</Col>
<Col xs={3}><small>{timeRemaining}</small></Col>
<Col xs={1}><DeleteButton torrentId={torrent.infoHash} status={torrent.status}/></Col>
</Row>
);
}
};
TorrentTitleRow.propTypes = {
torrent: React.PropTypes.object
};
|
components/Footer.js | tim-speed/manifold-todo | import React from 'react'
import FilterLink from '../containers/FilterLink'
const Footer = () => (
<p>
Show:
{' '}
<FilterLink filter='SHOW_ALL'>
All
</FilterLink>
{', '}
<FilterLink filter='SHOW_ACTIVE'>
Active
</FilterLink>
{', '}
<FilterLink filter='SHOW_COMPLETED'>
Completed
</FilterLink>
</p>
)
export default Footer
|
packages/arwes/src/Words/sandbox.js | romelperez/prhone-ui | import React from 'react';
import Arwes from '../Arwes';
import Words from './index';
export default () => (
<Arwes>
<h3>
<Words animate>A cyberpunk UI project</Words>
</h3>
<p>
<Words animate>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus,
amet cupiditate laboriosam sunt libero aliquam, consequatur alias
ducimus adipisci nesciunt odit? Odio tenetur et itaque suscipit atque
officiis debitis qui. Lorem ipsum dolor sit amet, consectetur
adipisicing elit. Accusamus, amet cupiditate laboriosam sunt libero
aliquam, consequatur alias ducimus adipisci nesciunt odit? Odio tenetur
et itaque suscipit atque officiis debitis qui. Lorem ipsum dolor sit
amet, consectetur adipisicing elit. Accusamus, amet cupiditate
laboriosam sunt libero aliquam, consequatur alias ducimus adipisci
nesciunt odit? Odio tenetur et itaque suscipit atque officiis debitis
qui.
</Words>
</p>
<p>
<Words animate layer="success">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus,
amet cupiditate laboriosam sunt libero aliquam, consequatur alias
ducimus adipisci nesciunt odit? Odio tenetur et itaque suscipit atque
officiis debitis qui.
</Words>
</p>
<p>
<Words animate layer="alert">
With animations based on SciFi and designs from high technology
</Words>
</p>
</Arwes>
);
|
fields/types/relationship/RelationshipField.js | xyzteam2016/keystone | import async from 'async';
import Field from '../Field';
import { listsByKey } from '../../../admin/client/utils/lists';
import React from 'react';
import Select from 'react-select';
import xhr from 'xhr';
import { Button, InputGroup } from 'elemental';
import _ from 'lodash';
function compareValues (current, next) {
const currentLength = current ? current.length : 0;
const nextLength = next ? next.length : 0;
if (currentLength !== nextLength) return false;
for (let i = 0; i < currentLength; i++) {
if (current[i] !== next[i]) return false;
}
return true;
}
module.exports = Field.create({
displayName: 'RelationshipField',
statics: {
type: 'Relationship',
},
getInitialState () {
return {
value: null,
createIsOpen: false,
};
},
componentDidMount () {
this._itemsCache = {};
this.loadValue(this.props.value);
},
componentWillReceiveProps (nextProps) {
if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return;
this.loadValue(nextProps.value);
},
shouldCollapse () {
if (this.props.many) {
// many:true relationships have an Array for a value
return this.props.collapse && !this.props.value.length;
}
return this.props.collapse && !this.props.value;
},
buildFilters () {
var filters = {};
_.forEach(this.props.filters, (value, key) => {
if (_.isString(value) && value[0] == ':') { // eslint-disable-line eqeqeq
var fieldName = value.slice(1);
var val = this.props.values[fieldName];
if (val) {
filters[key] = val;
return;
}
// check if filtering by id and item was already saved
if (fieldName === ':_id' && Keystone.item) {
filters[key] = Keystone.item.id;
return;
}
} else {
filters[key] = value;
}
}, this);
var parts = [];
_.forEach(filters, function (val, key) {
parts.push('filters[' + key + '][value]=' + encodeURIComponent(val));
});
return parts.join('&');
},
cacheItem (item) {
item.href = Keystone.adminPath + '/' + this.props.refList.path + '/' + item.id;
this._itemsCache[item.id] = item;
},
loadValue (values) {
if (!values) {
return this.setState({
loading: false,
value: null,
});
};
values = Array.isArray(values) ? values : values.split(',');
const cachedValues = values.map(i => this._itemsCache[i]).filter(i => i);
if (cachedValues.length === values.length) {
this.setState({
loading: false,
value: this.props.many ? cachedValues : cachedValues[0],
});
return;
}
this.setState({
loading: true,
value: null,
});
async.map(values, (value, done) => {
xhr({
url: Keystone.adminPath + '/api/' + this.props.refList.path + '/' + value + '?basic',
responseType: 'json',
}, (err, resp, data) => {
if (err || !data) return done(err);
this.cacheItem(data);
done(err, data);
});
}, (err, expanded) => {
if (!this.isMounted()) return;
this.setState({
loading: false,
value: this.props.many ? expanded : expanded[0],
});
});
},
// NOTE: this seems like the wrong way to add options to the Select
loadOptionsCallback: {},
loadOptions (input, callback) {
// NOTE: this seems like the wrong way to add options to the Select
this.loadOptionsCallback = callback;
const filters = this.buildFilters();
xhr({
url: Keystone.adminPath + '/api/' + this.props.refList.path + '?basic&search=' + input + '&' + filters,
responseType: 'json',
}, (err, resp, data) => {
if (err) {
console.error('Error loading items:', err);
return callback(null, []);
}
data.results.forEach(this.cacheItem);
callback(null, {
options: data.results,
complete: data.results.length === data.count,
});
});
},
valueChanged (value) {
this.props.onChange({
path: this.props.path,
value: value,
});
},
openCreate () {
this.setState({
createIsOpen: true,
});
},
closeCreate () {
this.setState({
createIsOpen: false,
});
},
onCreate (item) {
this.cacheItem(item);
if (Array.isArray(this.state.value)) {
// For many relationships, append the new item to the end
const values = this.state.value.map((item) => item.id);
values.push(item.id);
this.valueChanged(values.join(','));
} else {
this.valueChanged(item.id);
}
// NOTE: this seems like the wrong way to add options to the Select
this.loadOptionsCallback(null, {
complete: true,
options: Object.keys(this._itemsCache).map((k) => this._itemsCache[k]),
});
this.toggleCreate(false);
},
renderSelect (noedit) {
return (
<Select.Async
multi={this.props.many}
disabled={noedit}
loadOptions={this.loadOptions}
labelKey="name"
name={this.props.path}
onChange={this.valueChanged}
simpleValue
value={this.state.value}
valueKey="id"
/>
);
},
renderInputGroup () {
// TODO: find better solution
// when importing the CreateForm using: import CreateForm from '../../../admin/client/App/shared/CreateForm';
// CreateForm was imported as a blank object. This stack overflow post suggested lazilly requiring it:
// http://stackoverflow.com/questions/29807664/cyclic-dependency-returns-empty-object-in-react-native
// TODO: Implement this somewhere higher in the app, it breaks the encapsulation of the RelationshipField component
const CreateForm = require('../../../admin/client/App/shared/CreateForm');
return (
<InputGroup>
<InputGroup.Section grow>
{this.renderSelect()}
</InputGroup.Section>
<InputGroup.Section>
<Button onClick={this.openCreate} type="success">+</Button>
</InputGroup.Section>
<CreateForm
list={listsByKey[this.props.refList.key]}
isOpen={this.state.createIsOpen}
onCreate={this.onCreate}
onCancel={this.closeCreate} />
</InputGroup>
);
},
renderValue () {
return this.renderSelect(true);
},
renderField () {
if (this.props.createInline) {
return this.renderInputGroup();
} else {
return this.renderSelect();
}
},
});
|
examples/src/components/MultiSelectField.js | oriweingart/react-select | import React from 'react';
import Select from 'react-select';
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
var MultiSelectField = React.createClass({
displayName: 'MultiSelectField',
propTypes: {
label: React.PropTypes.string,
},
getInitialState () {
return {
disabled: false,
value: []
};
},
handleSelectChange (value, values) {
logChange('New value:', value, 'Values:', values);
this.setState({ value: value });
},
toggleDisabled (e) {
this.setState({ 'disabled': e.target.checked });
},
render () {
var ops = [
{ label: 'Chocolate', value: 'chocolate' },
{ label: 'Vanilla', value: 'vanilla' },
{ label: 'Strawberry', value: 'strawberry' },
{ label: 'Caramel', value: 'caramel' },
{ label: 'Cookies and Cream', value: 'cookiescream' },
{ label: 'Peppermint', value: 'peppermint' }
];
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select multi={true} disabled={this.state.disabled} value={this.state.value} placeholder="Select your favourite(s)" options={ops} onChange={this.handleSelectChange} />
<div className="checkbox-list">
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.disabled} onChange={this.toggleDisabled} />
<span className="checkbox-label">Disabled</span>
</label>
</div>
</div>
);
}
});
module.exports = MultiSelectField; |
app/containers/App/index.js | JohnPhoto/Julmustracet-2016 | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { injectIntl, intlShape } from 'react-intl';
import Helmet from 'react-helmet';
import messages from './messages';
import styles from './styles.css';
class App extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
intl: intlShape.isRequired,
};
render() {
const { formatMessage } = this.props.intl;
return (
<div className={styles.container}>
<Helmet
title={formatMessage(messages.title)}
meta={[
{ name: 'description', content: formatMessage(messages.description) },
{ name: 'og:title', content: formatMessage(messages.title) },
]}
/>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
export default injectIntl(App);
|
app/javascript/mastodon/features/ui/components/bundle.js | sylph-sin-tyaku/mastodon | import React from 'react';
import PropTypes from 'prop-types';
const emptyComponent = () => null;
const noop = () => { };
class Bundle extends React.PureComponent {
static propTypes = {
fetchComponent: PropTypes.func.isRequired,
loading: PropTypes.func,
error: PropTypes.func,
children: PropTypes.func.isRequired,
renderDelay: PropTypes.number,
onFetch: PropTypes.func,
onFetchSuccess: PropTypes.func,
onFetchFail: PropTypes.func,
}
static defaultProps = {
loading: emptyComponent,
error: emptyComponent,
renderDelay: 0,
onFetch: noop,
onFetchSuccess: noop,
onFetchFail: noop,
}
static cache = new Map
state = {
mod: undefined,
forceRender: false,
}
componentWillMount() {
this.load(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.fetchComponent !== this.props.fetchComponent) {
this.load(nextProps);
}
}
componentWillUnmount () {
if (this.timeout) {
clearTimeout(this.timeout);
}
}
load = (props) => {
const { fetchComponent, onFetch, onFetchSuccess, onFetchFail, renderDelay } = props || this.props;
const cachedMod = Bundle.cache.get(fetchComponent);
if (fetchComponent === undefined) {
this.setState({ mod: null });
return Promise.resolve();
}
onFetch();
if (cachedMod) {
this.setState({ mod: cachedMod.default });
onFetchSuccess();
return Promise.resolve();
}
this.setState({ mod: undefined });
if (renderDelay !== 0) {
this.timestamp = new Date();
this.timeout = setTimeout(() => this.setState({ forceRender: true }), renderDelay);
}
return fetchComponent()
.then((mod) => {
Bundle.cache.set(fetchComponent, mod);
this.setState({ mod: mod.default });
onFetchSuccess();
})
.catch((error) => {
this.setState({ mod: null });
onFetchFail(error);
});
}
render() {
const { loading: Loading, error: Error, children, renderDelay } = this.props;
const { mod, forceRender } = this.state;
const elapsed = this.timestamp ? (new Date() - this.timestamp) : renderDelay;
if (mod === undefined) {
return (elapsed >= renderDelay || forceRender) ? <Loading /> : null;
}
if (mod === null) {
return <Error onRetry={this.load} />;
}
return children(mod);
}
}
export default Bundle;
|
docs/src/Root.js | bvasko/react-bootstrap | import React from 'react';
import Router from 'react-router';
const Root = React.createClass({
statics: {
/**
* Get the list of pages that are renderable
*
* @returns {Array}
*/
getPages() {
return [
'index.html',
'introduction.html',
'getting-started.html',
'components.html',
'support.html'
];
}
},
getDefaultProps() {
return {
assetBaseUrl: ''
};
},
childContextTypes: {
metadata: React.PropTypes.object
},
getChildContext() {
return { metadata: this.props.propData };
},
render() {
// Dump out our current props to a global object via a script tag so
// when initialising the browser environment we can bootstrap from the
// same props as what each page was rendered with.
let browserInitScriptObj = {
__html:
`window.INITIAL_PROPS = ${JSON.stringify(this.props)};
// console noop shim for IE8/9
(function (w) {
var noop = function () {};
if (!w.console) {
w.console = {};
['log', 'info', 'warn', 'error'].forEach(function (method) {
w.console[method] = noop;
});
}
}(window));`
};
let head = {
__html: `<title>React-Bootstrap</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${this.props.assetBaseUrl}/assets/bundle.css" rel="stylesheet">
<link href="${this.props.assetBaseUrl}/assets/favicon.ico?v=2" type="image/x-icon" rel="shortcut icon">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script>
<![endif]-->`
};
return (
<html>
<head dangerouslySetInnerHTML={head} />
<body>
<Router.RouteHandler propData={this.props.propData} />
<script dangerouslySetInnerHTML={browserInitScriptObj} />
<script src={`${this.props.assetBaseUrl}/assets/bundle.js`} />
</body>
</html>
);
}
});
export default Root;
|
packages/demos/demo/src/components/Textarea/index.js | garth/cerebral | import React from 'react'
import { connect } from '@cerebral/react'
import { props, signal, state } from 'cerebral/tags'
import translations from '../../common/compute/translations'
export default connect(
{
// autoFocus
enterPressed: signal`${props`moduleName`}.enterPressed`,
escPressed: signal`${props`moduleName`}.escPressed`,
// field
// placeholderKey
t: translations,
value: state`${props`moduleName`}.$draft.${props`field`}`,
valueChanged: signal`${props`moduleName`}.formValueChanged`,
},
function Input({
autoFocus,
enterPressed,
escPressed,
field,
placeholderKey,
t,
value,
valueChanged,
}) {
const onKeyPress = e => {
switch (e.key) {
case 'Enter':
enterPressed()
break
case 'Esc':
escPressed()
break
default:
break // noop
}
}
const onChange = e => {
valueChanged({ key: field, value: e.target.value })
}
return (
<textarea
className="textarea"
autoFocus={autoFocus}
placeholder={t[placeholderKey]}
onKeyPress={onKeyPress}
onChange={onChange}
name={field}
value={value || ''}
/>
)
}
)
|
src/PageItem.js | Azerothian/react-bootstrap | import React from 'react';
import classNames from 'classnames';
const PageItem = React.createClass({
propTypes: {
href: React.PropTypes.string,
target: React.PropTypes.string,
title: React.PropTypes.string,
disabled: React.PropTypes.bool,
previous: React.PropTypes.bool,
next: React.PropTypes.bool,
onSelect: React.PropTypes.func,
eventKey: React.PropTypes.any
},
getDefaultProps() {
return {
href: '#'
};
},
render() {
let classes = {
'disabled': this.props.disabled,
'previous': this.props.previous,
'next': this.props.next
};
return (
<li
{...this.props}
className={classNames(this.props.className, classes)}>
<a
href={this.props.href}
title={this.props.title}
target={this.props.target}
onClick={this.handleSelect}
ref="anchor">
{this.props.children}
</a>
</li>
);
},
handleSelect(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
}
}
}
});
export default PageItem;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.