path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
features/apimgt/org.wso2.carbon.apimgt.admin.feature/src/main/resources/admin/source/src/app/components/ThrottlingPolicies/Shared/CustomAttributes.js | Minoli/carbon-apimgt | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { Component } from 'react';
import Grid from 'material-ui/Grid';
import Divider from 'material-ui/Divider';
import TextField from 'material-ui/TextField';
import Paper from 'material-ui/Paper';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import DeleteIcon from '@material-ui/icons/Delete';
import IconButton from 'material-ui/IconButton';
import Tooltip from 'material-ui/Tooltip';
import './Shared.css';
class CustomAttributes extends Component {
constructor(props) {
super(props);
this.addAttribute = this.addAttribute.bind(this);
this.removeAttribute = this.removeAttribute.bind(this);
this.handleAttributeChange = this.handleAttributeChange.bind(this);
}
addAttribute() {
const attribute = {
name: '',
value: '',
};
const attributes = this.props.attributes;
attributes.push(attribute);
this.props.handleAttributeChange(attributes);
}
removeAttribute(attrIndex) {
const attributes = this.props.attributes;
attributes.splice(attrIndex, 1);
this.props.handleAttributeChange(attributes);
}
handleAttributeChange(id) {
return (event) => {
const value = event.target.value;
const elemId = event.target.id;
const attributes = this.props.attributes;
const attribute = attributes[id];
if (elemId == 'attrName') {
attribute.name = value;
} else if (elemId == 'attrValue') {
attribute.value = value;
}
attributes[id] = attribute;
this.props.handleAttributeChange(attributes);
};
}
render() {
return (
<Paper elevation={20}>
<Grid item xs={12}>
<Typography className='page-title' type='subheading' gutterBottom>
Custom Attributes
</Typography>
</Grid>
<Grid item xs={6} className='grid-item'>
<Divider />
<div className='container'>
<Button raised color='accent' onClick={() => this.addAttribute()}>
Add Custom Attribute
</Button>
</div>
<div>
{this.props.attributes.map((n) => {
return (
<Grid item xs={6} className='grid-item'>
<TextField
id='attrName'
label='name'
value={n.name}
onChange={this.handleAttributeChange(this.props.attributes.indexOf(n))}
/>
<TextField
id='attrValue'
label='value'
value={n.value}
onChange={this.handleAttributeChange(this.props.attributes.indexOf(n))}
/>
<IconButton
aria-label='Delete'
onClick={() => this.removeAttribute(this.props.attributes.indexOf(n))}
>
<DeleteIcon />
</IconButton>
</Grid>
);
})}
</div>
</Grid>
</Paper>
);
}
}
export default CustomAttributes;
|
components/News.js | githubhaohao/DevNews | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
ScrollView,
TouchableHighlight,
TouchableOpacity,
StatusBar,
} from 'react-native';
import NavigationBar from 'react-native-navigationbar';
const COVER_HEIGHT = 400;
export default class News extends Component {
// 构造
constructor(props) {
super(props);
// 初始状态
this.state = {
opacity:0,
};
}
render() {
let newsData = this.props.news;
let imgSrc = (typeof newsData.results.福利[0].url !== 'undefined') ? {uri:newsData.results.福利[0].url} : require('../images/logo.jpg');
let header = (
<NavigationBar
title={`${newsData.date}期`}
backHidden={false}
backColor='white'
backIcon={true}
barTintColor='transparent'
barOpacity= {this.state.opacity}
barStyle={styles.navigationBar}
backFunc={() => {
this.props.navigator.pop();
}}/>
);
return (
<View style={styles.container}>
<ScrollView
onScroll={this.onScroll.bind(this)}
scrollEventThrottle={5}
bounces={false}>
<Image style={{height:COVER_HEIGHT}} source={imgSrc}/>
{this.getChildViews(newsData)}
</ScrollView>
{/*<View style={[styles.backIcon,{opacity:this.state.opacity}]}/>*/}
<View style={[styles.titleView,{opacity:this.state.opacity}]}>
<TouchableOpacity
activeOpacity={0.5}
onPress={() => this.props.navigator.pop()}
style={styles.backWrapper}
>
<View style={styles.backIcon}></View>
</TouchableOpacity>
<Text style={styles.title}>{`${newsData.date}期`}</Text>
<View style={[styles.backIcon,{opacity:0}]}></View>
</View>
</View>
);
}
onScroll(event){
const MAX = COVER_HEIGHT - 64;
let y = event.nativeEvent.contentOffset.y;
if(y > MAX){
y = MAX;
}
let opacity = y / MAX;
this.setState({
opacity:opacity,
});
}
getChildViews(newsData){
console.log(newsData);
let views = [];
for(let i = 0;i<newsData.category.length;i++){
views.push(<View key={i} style={styles.childView}>
<Text style={styles.childTitle}>{newsData.category[i]}</Text>
{this.getItems(newsData,newsData.category[i])}
</View>)
}
return views;
}
getItems(newsData,category){
let child = [];
let data = newsData.results[category];
for(let i = 0;i<data.length;i++){
let item = data[i];
//console.log('[item]',item);item._id
child.push(
<TouchableOpacity
activeOpacity={0.3}
onPress={() => {
this.props.navigator.push({
name:'detail',
url:item.url,
title:item.desc,
id:item._id,
});
}}
style={styles.itemView} key={i}>
<Text style={styles.itemTitle}><Text style={{fontSize:14,color:'red'}}>♥</Text> {item.desc} ( {item.who} )</Text>
</TouchableOpacity>);
}
return child;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#efefef',
},
contentView:{
flex:1,
},
childView:{
backgroundColor:'white',
margin:8,
padding:15,
borderRadius:3,
flex:1,
},
childTitle:{
fontSize:18,
color:'orange',
},
itemView:{
marginTop:10,
},
itemTitle:{
fontSize:14,
marginLeft:15,
color:'blue',
},
navigationBar:{
top:0,
left:0,
position:'absolute',
backgroundColor:'transparent',
},
tintBackIcon:{
width:14,
height:14,
borderColor:'#444',
borderLeftWidth:2,
borderBottomWidth:2,
transform:[{rotate:'45deg'}],
backgroundColor:'transparent',
},
tintBack:{
position:'absolute',
top:33.9,
left:14.5,
width:16,
height:16,
},
title:{
color:'white',
fontSize:18,
fontWeight:'bold',
},
titleView:{
top:0,
right:0,
position:'absolute',
left:0,
top:0,
height:76,
paddingTop:20,
justifyContent:'space-between',
alignItems:'center',
backgroundColor:'#00a2ed',
flexDirection:'row',
},
backIcon: {
width: 14,
height: 14,
marginLeft: 12,
borderLeftWidth: 2,
borderBottomWidth: 2,
transform: [{rotate: '45deg'}],
borderColor:'white',
},
backWrapper: {
flexDirection: 'row',
alignItems: 'center',
height:66,
},
});
|
src/admin/client/modules/products/edit/general/components/form.js | cezerin/cezerin | import React from 'react';
import { Link } from 'react-router-dom';
import { Field, reduxForm } from 'redux-form';
import { TextField } from 'redux-form-material-ui';
import Editor from 'modules/shared/editor';
import messages from 'lib/text';
import style from './style.css';
import api from 'lib/api';
import Paper from 'material-ui/Paper';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
const validate = values => {
const errors = {};
const requiredFields = ['name'];
requiredFields.map(field => {
if (values && !values[field]) {
errors[field] = messages.errors_required;
}
});
return errors;
};
const slugExists = values => {
if (values.slug && values.slug.length > 0) {
return api.products
.slugExists(values.id, values.slug)
.then(response => response.status === 200);
} else {
return Promise.resolve(false);
}
};
const asyncValidate = values => {
return Promise.all([slugExists(values)]).then(([isSlugExists]) => {
let errors = {};
if (isSlugExists) {
errors.slug = messages.errors_urlTaken;
}
if (Object.keys(errors).length > 0) {
return Promise.reject(errors);
} else {
return Promise.resolve();
}
});
};
const ProductGeneralForm = ({
handleSubmit,
pristine,
reset,
submitting,
initialValues
}) => {
if (initialValues) {
return (
<form onSubmit={handleSubmit}>
<Paper className="paper-box" zDepth={1}>
<div className={style.innerBox}>
<Field
name="name"
component={TextField}
floatingLabelText={messages.products_name + ' *'}
fullWidth={true}
/>
<Field
name="slug"
component={TextField}
floatingLabelText={messages.slug}
fullWidth={true}
/>
<p className="field-hint">{messages.help_slug}</p>
<Field
name="meta_title"
component={TextField}
floatingLabelText={messages.pageTitle}
fullWidth={true}
/>
<Field
name="meta_description"
component={TextField}
floatingLabelText={messages.metaDescription}
fullWidth={true}
/>
<div className="field-hint" style={{ marginTop: 40 }}>
{messages.description}
</div>
<Field name="description" component={Editor} />
</div>
<div
className={
'buttons-box ' +
(pristine ? 'buttons-box-pristine' : 'buttons-box-show')
}
>
<FlatButton
label={messages.cancel}
className={style.button}
onClick={reset}
disabled={pristine || submitting}
/>
<RaisedButton
type="submit"
label={messages.save}
primary={true}
className={style.button}
disabled={pristine || submitting}
/>
</div>
</Paper>
</form>
);
} else {
return null;
}
};
export default reduxForm({
form: 'ProductGeneralForm',
validate,
asyncValidate,
asyncBlurFields: ['slug'],
enableReinitialize: true
})(ProductGeneralForm);
|
src/features/scramble/Scramble.js | saadq/flow-timer | /**
* @flow
*/
import React from 'react'
import styled from 'styled-components'
import { subtle } from '../../common/colors'
const Div = styled.div`
width: 100%;
background: #22262f;
color: ${subtle};
text-align: center;
padding: 2em 0;
word-spacing: 1em;
font-size: 1em;
`
type Props = {
scramble: string
}
function Scramble({ scramble }: Props) {
return <Div>{scramble}</Div>
}
export default Scramble
|
tests/lib/rules/indent.js | tornqvist/eslint | /**
* @fileoverview This option sets a specific tab width for your code
* @author Dmitriy Shekhovtsov
* @author Gyandeep Singh
* @copyright 2014 Dmitriy Shekhovtsov. All rights reserved.
* @copyright 2015 Gyandeep Singh. All rights reserved.
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var rule = require("../../../lib/rules/indent"),
RuleTester = require("../../../lib/testers/rule-tester");
var fs = require("fs");
var path = require("path");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var fixture = fs.readFileSync(path.join(__dirname, "../../fixtures/rules/indent/indent-invalid-fixture-1.js"), "utf8");
function expectedErrors(indentType, errors) {
if (Array.isArray(indentType)) {
errors = indentType;
indentType = "space";
}
if (!errors[0].length) {
errors = [errors];
}
return errors.map(function(err) {
var chars = err[1] === 1 ? "character" : "characters";
return {
message: "Expected indentation of " + err[1] + " " + indentType + " " + chars + " but found " + err[2] + ".",
type: err[3] || "Program",
line: err[0]
};
});
}
var ruleTester = new RuleTester();
ruleTester.run("indent", rule, {
valid: [
{
code:
"if(data) {\n" +
" console.log('hi');\n" +
" b = true;};",
options: [2, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"foo = () => {\n" +
" console.log('hi');\n" +
" return true;};",
options: [2, {"VariableDeclarator": 1, "SwitchCase": 1}],
ecmaFeatures: {arrowFunctions: true}
},
{
code:
"function test(data) {\n" +
" console.log('hi');\n" +
" return true;};",
options: [2, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"var test = function(data) {\n" +
" console.log('hi');\n" +
"};",
options: [2, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"arr.forEach(function(data) {\n" +
" otherdata.forEach(function(zero) {\n" +
" console.log('hi');\n" +
" }) });",
options: [2, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"a = [\n" +
" ,3\n" +
"]",
options: [4, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"[\n" +
" ['gzip', 'gunzip'],\n" +
" ['gzip', 'unzip'],\n" +
" ['deflate', 'inflate'],\n" +
" ['deflateRaw', 'inflateRaw'],\n" +
"].forEach(function(method) {\n" +
" console.log(method);\n" +
"});\n",
options: [2, {"SwitchCase": 1, "VariableDeclarator": 2}]
},
{
code:
"test(123, {\n" +
" bye: {\n" +
" hi: [1,\n" +
" {\n" +
" b: 2\n" +
" }\n" +
" ]\n" +
" }\n" +
"});",
options: [4, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"var xyz = 2,\n" +
" lmn = [\n" +
" {\n" +
" a: 1\n" +
" }\n" +
" ];",
options: [4, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"lmn = [{\n" +
" a: 1\n" +
"},\n" +
"{\n" +
" b: 2\n" +
"}," +
"{\n" +
" x: 2\n" +
"}];",
options: [4, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"abc({\n" +
" test: [\n" +
" [\n" +
" c,\n" +
" xyz,\n" +
" 2\n" +
" ].join(',')\n" +
" ]\n" +
"});",
options: [4, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"abc = {\n" +
" test: [\n" +
" [\n" +
" c,\n" +
" xyz,\n" +
" 2\n" +
" ]\n" +
" ]\n" +
"};",
options: [2, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"abc(\n" +
" {\n" +
" a: 1,\n" +
" b: 2\n" +
" }\n" +
");",
options: [2, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"abc({\n" +
" a: 1,\n" +
" b: 2\n" +
"});",
options: [4, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"var abc = \n" +
" [\n" +
" c,\n" +
" xyz,\n" +
" {\n" +
" a: 1,\n" +
" b: 2\n" +
" }\n" +
" ];",
options: [2, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"var abc = [\n" +
" c,\n" +
" xyz,\n" +
" {\n" +
" a: 1,\n" +
" b: 2\n" +
" }\n" +
"];",
options: [2, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"var abc = 5,\n" +
" c = 2,\n" +
" xyz = \n" +
" {\n" +
" a: 1,\n" +
" b: 2\n" +
" };",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}]
},
{
code:
"var abc = \n" +
" {\n" +
" a: 1,\n" +
" b: 2\n" +
" };",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}]
},
{
code:
"var a = new abc({\n" +
" a: 1,\n" +
" b: 2\n" +
" }),\n" +
" b = 2;",
options: [4, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"var a = 2,\n" +
" c = {\n" +
" a: 1,\n" +
" b: 2\n" +
" },\n" +
" b = 2;",
options: [2, {"VariableDeclarator": 1, "SwitchCase": 1}]
},
{
code:
"var x = 2,\n" +
" y = {\n" +
" a: 1,\n" +
" b: 2\n" +
" },\n" +
" b = 2;",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}]
},
{
code:
"var e = {\n" +
" a: 1,\n" +
" b: 2\n" +
" },\n" +
" b = 2;",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}]
},
{
code:
"var a = {\n" +
" a: 1,\n" +
" b: 2\n" +
"};",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}]
},
{
code:
"function test() {\n" +
" if (true ||\n " +
" false){\n" +
" console.log(val);\n" +
" }\n" +
"}",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}]
},
{
code:
"for (var val in obj)\n" +
" if (true)\n" +
" console.log(val);",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}]
},
{
code:
"if(true)\n" +
" if (true)\n" +
" if (true)\n" +
" console.log(val);",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}]
},
{
code:
"function hi(){ var a = 1;\n" +
" y++; x++;\n" +
"}",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}]
},
{
code:
"for(;length > index; index++)if(NO_HOLES || index in self){\n" +
" x++;\n" +
"}",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}]
},
{
code:
"function test(){\n" +
" switch(length){\n" +
" case 1: return function(a){\n" +
" return fn.call(that, a);\n" +
" };\n" +
" }\n" +
"}",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}]
},
{
code:
"var geometry = 2,\n" +
"rotate = 2;",
options: [2, {VariableDeclarator: 0}]
},
{
code:
"var geometry,\n" +
" rotate;",
options: [4, {VariableDeclarator: 1}]
},
{
code:
"var geometry,\n" +
"\trotate;",
options: ["tab", {VariableDeclarator: 1}]
},
{
code:
"var geometry,\n" +
" rotate;",
options: [2, {VariableDeclarator: 1}]
},
{
code:
"var geometry,\n" +
" rotate;",
options: [2, {VariableDeclarator: 2}]
},
{
code:
"let geometry,\n" +
" rotate;",
options: [2, {VariableDeclarator: 2}],
ecmaFeatures: {
blockBindings: true
}
},
{
code:
"const geometry = 2,\n" +
" rotate = 3;",
options: [2, {VariableDeclarator: 2}],
ecmaFeatures: {
blockBindings: true
}
},
{
code:
"var geometry, box, face1, face2, colorT, colorB, sprite, padding, maxWidth,\n" +
" height, rotate;",
options: [2, {SwitchCase: 1}]
},
{
code:
"var geometry, box, face1, face2, colorT, colorB, sprite, padding, maxWidth;",
options: [2, {SwitchCase: 1}]
},
{
code:
"if (1 < 2){\n" +
"//hi sd \n" +
"}",
options: [2]
},
{
code:
"while (1 < 2){\n" +
" //hi sd \n" +
"}",
options: [2]
},
{
code:
"while (1 < 2) console.log('hi');",
options: [2]
},
{
code:
"[a, b, \nc].forEach((index) => {\n" +
" index;\n" +
"});\n",
options: [4],
ecmaFeatures: { arrowFunctions: true }
},
{
code:
"[a, b, \nc].forEach(function(index){\n" +
" return index;\n" +
"});\n",
options: [4],
ecmaFeatures: { arrowFunctions: true }
},
{
code:
"[a, b, c].forEach((index) => {\n" +
" index;\n" +
"});\n",
options: [4],
ecmaFeatures: { arrowFunctions: true }
},
{
code:
"[a, b, c].forEach(function(index){\n" +
" return index;\n" +
"});\n",
options: [4],
ecmaFeatures: { arrowFunctions: true }
},
{
code:
"switch (x) {\n" +
" case \"foo\":\n" +
" a();\n" +
" break;\n" +
" case \"bar\":\n" +
" switch (y) {\n" +
" case \"1\":\n" +
" break;\n" +
" case \"2\":\n" +
" a = 6;\n" +
" break;\n" +
" }\n" +
" case \"test\":\n" +
" break;\n" +
"}",
options: [4, {SwitchCase: 1}]
},
{
code:
"switch (x) {\n" +
" case \"foo\":\n" +
" a();\n" +
" break;\n" +
" case \"bar\":\n" +
" switch (y) {\n" +
" case \"1\":\n" +
" break;\n" +
" case \"2\":\n" +
" a = 6;\n" +
" break;\n" +
" }\n" +
" case \"test\":\n" +
" break;\n" +
"}",
options: [4, {SwitchCase: 2}]
},
{
code:
"switch (a) {\n" +
"case \"foo\":\n" +
" a();\n" +
" break;\n" +
"case \"bar\":\n" +
" switch(x){\n" +
" case '1':\n" +
" break;\n" +
" case '2':\n" +
" a = 6;\n" +
" break;\n" +
" }\n" +
"}"
},
{
code:
"switch (a) {\n" +
"case \"foo\":\n" +
" a();\n" +
" break;\n" +
"case \"bar\":\n" +
" if(x){\n" +
" a = 2;\n" +
" }\n" +
" else{\n" +
" a = 6;\n" +
" }\n" +
"}"
},
{
code:
"switch (a) {\n" +
"case \"foo\":\n" +
" a();\n" +
" break;\n" +
"case \"bar\":\n" +
" if(x){\n" +
" a = 2;\n" +
" }\n" +
" else\n" +
" a = 6;\n" +
"}"
},
{
code:
"switch (a) {\n" +
"case \"foo\":\n" +
" a();\n" +
" break;\n" +
"case \"bar\":\n" +
" a(); break;\n" +
"case \"baz\":\n" +
" a(); break;\n" +
"}"
},
{
code: "switch (0) {\n}"
},
{
code:
"function foo() {\n" +
" var a = \"a\";\n" +
" switch(a) {\n" +
" case \"a\":\n" +
" return \"A\";\n" +
" case \"b\":\n" +
" return \"B\";\n" +
" }\n" +
"}\n" +
"foo();"
},
{
code:
"switch(value){\n" +
" case \"1\":\n" +
" case \"2\":\n" +
" a();\n" +
" break;\n" +
" default:\n" +
" a();\n" +
" break;\n" +
"}\n" +
"switch(value){\n" +
" case \"1\":\n" +
" a();\n" +
" break;\n" +
" case \"2\":\n" +
" break;\n" +
" default:\n" +
" break;\n" +
"}",
options: [4, {SwitchCase: 1}]
},
{
code:
"var obj = {foo: 1, bar: 2};\n" +
"with (obj) {\n" +
" console.log(foo + bar);\n" +
"}\n"
},
{
code:
"if (a) {\n" +
" (1 + 2 + 3);\n" + // no error on this line
"}"
},
{
code:
"switch(value){ default: a(); break; }\n"
},
{
code: "import {addons} from 'react/addons'\nimport React from 'react'",
options: [2],
ecmaFeatures: {
modules: true
}
},
{
code:
"var a = 1,\n" +
" b = 2,\n" +
" c = 3;\n",
options: [4]
},
{
code:
"var a = 1\n" +
" ,b = 2\n" +
" ,c = 3;\n",
options: [4]
},
{
code: "while (1 < 2) console.log('hi')\n",
options: [2]
},
{
code:
"function salutation () {\n" +
" switch (1) {\n" +
" case 0: return console.log('hi')\n" +
" case 1: return console.log('hey')\n" +
" }\n" +
"}\n",
options: [2, { SwitchCase: 1 }]
},
{
code:
"var items = [\n" +
" {\n" +
" foo: 'bar'\n" +
" }\n" +
"];\n",
options: [2, {"VariableDeclarator": 2}]
},
{
code:
"const geometry = 2,\n" +
" rotate = 3;\n" +
"var a = 1,\n" +
" b = 2;\n" +
"let light = true,\n" +
" shadow = false;",
options: [2, { VariableDeclarator: { "const": 3, "let": 2 } }],
ecmaFeatures: { blockBindings: true }
},
{
code:
"const abc = 5,\n" +
" c = 2,\n" +
" xyz = \n" +
" {\n" +
" a: 1,\n" +
" b: 2\n" +
" };\n" +
"let abc = 5,\n" +
" c = 2,\n" +
" xyz = \n" +
" {\n" +
" a: 1,\n" +
" b: 2\n" +
" };\n" +
"var abc = 5,\n" +
" c = 2,\n" +
" xyz = \n" +
" {\n" +
" a: 1,\n" +
" b: 2\n" +
" };\n",
options: [2, { VariableDeclarator: { var: 2, const: 3 }, "SwitchCase": 1}],
ecmaFeatures: { blockBindings: true }
},
{
code:
"module.exports =\n" +
"{\n" +
" 'Unit tests':\n" +
" {\n" +
" rootPath: './',\n" +
" environment: 'node',\n" +
" tests:\n" +
" [\n" +
" 'test/test-*.js'\n" +
" ],\n" +
" sources:\n" +
" [\n" +
" '*.js',\n" +
" 'test/**.js'\n" +
" ]\n" +
" }\n" +
"};",
options: [2]
},
{
code:
"var path = require('path')\n" +
" , crypto = require('crypto')\n" +
" ;\n",
options: [2]
},
{
code:
"var a = 1\n" +
" ,b = 2\n" +
" ;"
}
],
invalid: [
{
code:
"var a = b;\n" +
"if (a) {\n" +
"b();\n" +
"}\n",
options: [2],
errors: expectedErrors([[3, 2, 0, "ExpressionStatement"]])
},
{
code:
"if (array.some(function(){\n" +
" return true;\n" +
"})) {\n" +
"a++; // ->\n" +
" b++;\n" +
" c++; // <-\n" +
"}\n",
options: [2],
errors: expectedErrors([[4, 2, 0, "ExpressionStatement"], [6, 2, 4, "ExpressionStatement"]])
},
{
code: "if (a){\n\tb=c;\n\t\tc=d;\ne=f;\n}",
options: ["tab"],
errors: expectedErrors("tab", [[3, 1, 2, "ExpressionStatement"], [4, 1, 0, "ExpressionStatement"]])
},
{
code: "if (a){\n b=c;\n c=d;\n e=f;\n}",
options: [4],
errors: expectedErrors([[3, 4, 6, "ExpressionStatement"], [4, 4, 1, "ExpressionStatement"]])
},
{
code: fixture,
options: [2, {SwitchCase: 1}],
errors: expectedErrors([
[5, 2, 4, "VariableDeclaration"],
[10, 4, 6, "BlockStatement"],
[11, 2, 4, "BlockStatement"],
[15, 4, 2, "ExpressionStatement"],
[16, 2, 4, "BlockStatement"],
[23, 2, 4, "BlockStatement"],
[29, 2, 4, "ForStatement"],
[31, 4, 2, "BlockStatement"],
[36, 4, 6, "ExpressionStatement"],
[38, 2, 4, "BlockStatement"],
[39, 4, 2, "ExpressionStatement"],
[40, 2, 0, "BlockStatement"],
[46, 0, 1, "VariableDeclaration"],
[54, 2, 4, "BlockStatement"],
[114, 4, 2, "VariableDeclaration"],
[120, 4, 6, "VariableDeclaration"],
[124, 4, 2, "BreakStatement"],
[134, 4, 6, "BreakStatement"],
[143, 4, 0, "ExpressionStatement"],
[151, 4, 6, "ExpressionStatement"],
[159, 4, 2, "ExpressionStatement"],
[161, 4, 6, "ExpressionStatement"],
[175, 2, 0, "ExpressionStatement"],
[177, 2, 4, "ExpressionStatement"],
[189, 2, 0, "VariableDeclaration"],
[193, 6, 4, "ExpressionStatement"],
[195, 6, 8, "ExpressionStatement"],
[197, 2, 0, "VariableDeclaration"],
[305, 6, 4, "ExpressionStatement"],
[306, 6, 8, "ExpressionStatement"],
[308, 2, 4, "VariableDeclarator"],
[311, 4, 6, "Identifier"],
[312, 4, 6, "Identifier"],
[313, 4, 6, "Identifier"],
[314, 2, 4, "ArrayExpression"],
[315, 2, 4, "VariableDeclarator"],
[318, 4, 6, "Property"],
[319, 4, 6, "Property"],
[320, 4, 6, "Property"],
[321, 2, 4, "ObjectExpression"],
[322, 2, 4, "VariableDeclarator"],
[326, 2, 1, "Literal"],
[327, 2, 1, "Literal"],
[328, 2, 1, "Literal"],
[329, 2, 1, "Literal"],
[330, 2, 1, "Literal"],
[331, 2, 1, "Literal"],
[332, 2, 1, "Literal"],
[333, 2, 1, "Literal"],
[334, 2, 1, "Literal"],
[335, 2, 1, "Literal"],
[340, 2, 4, "ExpressionStatement"],
[341, 2, 0, "ExpressionStatement"],
[344, 2, 4, "ExpressionStatement"],
[345, 2, 0, "ExpressionStatement"],
[348, 2, 4, "ExpressionStatement"],
[349, 2, 0, "ExpressionStatement"],
[355, 2, 0, "ExpressionStatement"],
[357, 2, 4, "ExpressionStatement"],
[363, 2, 4, "VariableDeclarator"],
[368, 2, 0, "SwitchCase"],
[370, 2, 4, "SwitchCase"],
[374, 4, 6, "VariableDeclaration"],
[376, 4, 2, "VariableDeclaration"],
[383, 2, 0, "ExpressionStatement"],
[385, 2, 4, "ExpressionStatement"],
[390, 2, 0, "ExpressionStatement"],
[392, 2, 4, "ExpressionStatement"],
[409, 2, 0, "ExpressionStatement"],
[410, 2, 4, "ExpressionStatement"],
[416, 2, 0, "ExpressionStatement"],
[417, 2, 4, "ExpressionStatement"],
[422, 2, 4, "ExpressionStatement"],
[423, 2, 0, "ExpressionStatement"],
[428, 6, 8, "ExpressionStatement"],
[429, 6, 4, "ExpressionStatement"],
[434, 2, 4, "BlockStatement"],
[437, 2, 0, "ExpressionStatement"],
[438, 0, 4, "BlockStatement"],
[451, 2, 0, "ExpressionStatement"],
[453, 2, 4, "ExpressionStatement"],
[499, 6, 8, "BlockStatement"],
[500, 10, 8, "ExpressionStatement"],
[501, 8, 6, "BlockStatement"],
[506, 6, 8, "BlockStatement"]
])
},
{
code:
"switch(value){\n" +
" case \"1\":\n" +
" a();\n" +
" break;\n" +
" case \"2\":\n" +
" a();\n" +
" break;\n" +
" default:\n" +
" a();\n" +
" break;\n" +
"}",
options: [4, {SwitchCase: 1}],
errors: expectedErrors([[4, 8, 4, "BreakStatement"], [7, 8, 4, "BreakStatement"]])
},
{
code:
"switch(value){\n" +
" case \"1\":\n" +
" a();\n" +
" break;\n" +
" case \"2\":\n" +
" a();\n" +
" break;\n" +
" default:\n" +
" break;\n" +
"}",
options: [4, {SwitchCase: 1}],
errors: expectedErrors([9, 8, 4, "BreakStatement"])
},
{
code:
"switch(value){\n" +
" case \"1\":\n" +
" case \"2\":\n" +
" a();\n" +
" break;\n" +
" default:\n" +
" break;\n" +
"}\n" +
"switch(value){\n" +
" case \"1\":\n" +
" break;\n" +
" case \"2\":\n" +
" a();\n" +
" break;\n" +
" default:\n" +
" a();\n" +
" break;\n" +
"}",
options: [4, {SwitchCase: 1}],
errors: expectedErrors([[11, 8, 4, "BreakStatement"], [14, 8, 4, "BreakStatement"], [17, 8, 4, "BreakStatement"]])
},
{
code:
"switch(value){\n" +
"case \"1\":\n" +
" a();\n" +
" break;\n" +
" case \"2\":\n" +
" break;\n" +
" default:\n" +
" break;\n" +
"}",
options: [4],
errors: expectedErrors([
[3, 4, 8, "ExpressionStatement"],
[4, 4, 8, "BreakStatement"],
[5, 0, 4, "SwitchCase"],
[6, 4, 8, "BreakStatement"],
[7, 0, 4, "SwitchCase"],
[8, 4, 8, "BreakStatement"]
])
},
{
code:
"var obj = {foo: 1, bar: 2};\n" +
"with (obj) {\n" +
"console.log(foo + bar);\n" +
"}\n",
errors: expectedErrors([3, 4, 0, "ExpressionStatement"])
},
{
code:
"switch (a) {\n" +
"case '1':\n" +
"b();\n" +
"break;\n" +
"default:\n" +
"c();\n" +
"break;\n" +
"}\n",
options: [4, {SwitchCase: 1}],
errors: expectedErrors([
[2, 4, 0, "SwitchCase"],
[3, 8, 0, "ExpressionStatement"],
[4, 8, 0, "BreakStatement"],
[5, 4, 0, "SwitchCase"],
[6, 8, 0, "ExpressionStatement"],
[7, 8, 0, "BreakStatement"]
])
},
{
code:
"while (a) \n" +
"b();",
options: [4],
errors: expectedErrors([
[2, 4, 0, "ExpressionStatement"]
])
},
{
code:
"for (;;) \n" +
"b();",
options: [4],
errors: expectedErrors([
[2, 4, 0, "ExpressionStatement"]
])
},
{
code:
"for (a in x) \n" +
"b();",
options: [4],
errors: expectedErrors([
[2, 4, 0, "ExpressionStatement"]
])
},
{
code:
"do \n" +
"b();\n" +
"while(true)",
options: [4],
errors: expectedErrors([
[2, 4, 0, "ExpressionStatement"]
])
},
{
code:
"if(true) \n" +
"b();",
options: [4],
errors: expectedErrors([
[2, 4, 0, "ExpressionStatement"]
])
},
{
code:
"var test = {\n" +
" a: 1,\n" +
" b: 2\n" +
" };\n",
options: [2],
errors: expectedErrors([
[2, 2, 6, "Property"],
[3, 2, 4, "Property"],
[4, 0, 4, "ObjectExpression"]
])
},
{
code:
"var a = function() {\n" +
" a++;\n" +
" b++;\n" +
" c++;\n" +
" },\n" +
" b;\n",
options: [4],
errors: expectedErrors([
[2, 8, 6, "ExpressionStatement"],
[3, 8, 4, "ExpressionStatement"],
[4, 8, 10, "ExpressionStatement"]
])
},
{
code:
"var a = 1,\n" +
"b = 2,\n" +
"c = 3;\n",
options: [4],
errors: expectedErrors([
[2, 4, 0, "VariableDeclarator"],
[3, 4, 0, "VariableDeclarator"]
])
},
{
code:
"[a, b, \nc].forEach((index) => {\n" +
" index;\n" +
"});\n",
options: [4],
ecmaFeatures: { arrowFunctions: true },
errors: expectedErrors([
[3, 4, 2, "ExpressionStatement"]
])
},
{
code:
"[a, b, \nc].forEach(function(index){\n" +
" return index;\n" +
"});\n",
options: [4],
ecmaFeatures: { arrowFunctions: true },
errors: expectedErrors([
[3, 4, 2, "ReturnStatement"]
])
},
{
code:
"[a, b, c].forEach((index) => {\n" +
" index;\n" +
"});\n",
options: [4],
ecmaFeatures: { arrowFunctions: true },
errors: expectedErrors([
[2, 4, 2, "ExpressionStatement"]
])
},
{
code:
"[a, b, c].forEach(function(index){\n" +
" return index;\n" +
"});\n",
options: [4],
ecmaFeatures: { arrowFunctions: true },
errors: expectedErrors([
[2, 4, 2, "ReturnStatement"]
])
},
{
code: "while (1 < 2)\nconsole.log('foo')\n console.log('bar')",
options: [2],
errors: expectedErrors([
[2, 2, 0, "ExpressionStatement"],
[3, 0, 2, "ExpressionStatement"]
])
},
{
code:
"function salutation () {\n" +
" switch (1) {\n" +
" case 0: return console.log('hi')\n" +
" case 1: return console.log('hey')\n" +
" }\n" +
"}\n",
options: [2, { SwitchCase: 1 }],
errors: expectedErrors([
[3, 4, 2, "SwitchCase"]
])
},
{
code:
"var geometry, box, face1, face2, colorT, colorB, sprite, padding, maxWidth,\n" +
"height, rotate;",
options: [2, {SwitchCase: 1}],
errors: expectedErrors([
[2, 2, 0, "VariableDeclarator"]
])
},
{
code:
"switch (a) {\n" +
"case '1':\n" +
"b();\n" +
"break;\n" +
"default:\n" +
"c();\n" +
"break;\n" +
"}\n",
options: [4, {SwitchCase: 2}],
errors: expectedErrors([
[2, 8, 0, "SwitchCase"],
[3, 12, 0, "ExpressionStatement"],
[4, 12, 0, "BreakStatement"],
[5, 8, 0, "SwitchCase"],
[6, 12, 0, "ExpressionStatement"],
[7, 12, 0, "BreakStatement"]
])
},
{
code:
"var geometry,\n" +
"rotate;",
options: [2, {VariableDeclarator: 1}],
errors: expectedErrors([
[2, 2, 0, "VariableDeclarator"]
])
},
{
code:
"var geometry,\n" +
" rotate;",
options: [2, {VariableDeclarator: 2}],
errors: expectedErrors([
[2, 4, 2, "VariableDeclarator"]
])
},
{
code:
"var geometry,\n" +
"\trotate;",
options: ["tab", {VariableDeclarator: 2}],
errors: expectedErrors("tab", [
[2, 2, 1, "VariableDeclarator"]
])
},
{
code:
"let geometry,\n" +
" rotate;",
options: [2, {VariableDeclarator: 2}],
ecmaFeatures: {
blockBindings: true
},
errors: expectedErrors([
[2, 4, 2, "VariableDeclarator"]
])
},
{
code:
"if(true)\n" +
" if (true)\n" +
" if (true)\n" +
" console.log(val);",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}],
errors: expectedErrors([
[4, 6, 4, "ExpressionStatement"]
])
},
{
code:
"var a = {\n" +
" a: 1,\n" +
" b: 2\n" +
"}",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}],
errors: expectedErrors([
[2, 2, 4, "Property"],
[3, 2, 4, "Property"]
])
},
{
code:
"var a = [\n" +
" a,\n" +
" b\n" +
"]",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}],
errors: expectedErrors([
[2, 2, 4, "Identifier"],
[3, 2, 4, "Identifier"]
])
},
{
code:
"let a = [\n" +
" a,\n" +
" b\n" +
"]",
options: [2, {"VariableDeclarator": { let: 2 }, "SwitchCase": 1}],
ecmaFeatures: { blockBindings: true },
errors: expectedErrors([
[2, 2, 4, "Identifier"],
[3, 2, 4, "Identifier"]
])
},
{
code:
"var a = new Test({\n" +
" a: 1\n" +
" }),\n" +
" b = 4;\n",
options: [4],
errors: expectedErrors([
[2, 8, 6, "Property"],
[3, 4, 2, "ObjectExpression"]
])
},
{
code:
"var a = new Test({\n" +
" a: 1\n" +
" }),\n" +
" b = 4;\n" +
"const a = new Test({\n" +
" a: 1\n" +
" }),\n" +
" b = 4;\n",
options: [2, { VariableDeclarator: { var: 2 }}],
ecmaFeatures: { blockBindings: true },
errors: expectedErrors([
[6, 4, 6, "Property"],
[7, 2, 4, "ObjectExpression"],
[8, 2, 4, "VariableDeclarator"]
])
},
{
code:
"var abc = 5,\n" +
" c = 2,\n" +
" xyz = \n" +
" {\n" +
" a: 1,\n" +
" b: 2\n" +
" };",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}],
errors: expectedErrors([
[4, 4, 5, "ObjectExpression"],
[5, 6, 7, "Property"],
[6, 6, 8, "Property"],
[7, 4, 5, "ObjectExpression"]
])
},
{
code:
"var abc = \n" +
" {\n" +
" a: 1,\n" +
" b: 2\n" +
" };",
options: [2, {"VariableDeclarator": 2, "SwitchCase": 1}],
errors: expectedErrors([
[2, 4, 5, "ObjectExpression"],
[3, 6, 7, "Property"],
[4, 6, 8, "Property"],
[5, 4, 5, "ObjectExpression"]
])
},
{
code:
"var path = require('path')\n" +
" , crypto = require('crypto')\n" +
";\n",
options: [2],
errors: expectedErrors([
[3, 1, 0, "VariableDeclaration"]
])
},
{
code:
"var a = 1\n" +
" ,b = 2\n" +
";",
errors: expectedErrors([
[3, 3, 0, "VariableDeclaration"]
])
}
]
});
|
docs/src/SupportPage.js | asiniy/react-bootstrap | import React from 'react';
import NavMain from './NavMain';
import PageHeader from './PageHeader';
import PageFooter from './PageFooter';
export default class Page extends React.Component {
render() {
return (
<div>
<NavMain activePage="support" />
<PageHeader
title="Need help?"
subTitle="Community resources for answering your React-Bootstrap questions." />
<div className="container bs-docs-container">
<div className="row">
<div className="col-md-9" role="main">
<div className="bs-docs-section">
<p className="lead">Stay up to date on the development of React-Bootstrap and reach out to the community with these helpful resources.</p>
<h3>Stack Overflow</h3>
<p><a href="http://stackoverflow.com/questions/ask">Ask questions</a> about specific problems you have faced, including details about what exactly you are trying to do. Make sure you tag your question with <code className="js">react-bootstrap</code>. You can also read through <a href="http://stackoverflow.com/questions/tagged/react-bootstrap">existing React-Bootstrap questions</a>.</p>
<h3>Live help</h3>
<p>Bring your questions and pair with other react-bootstrap users in a <a href="http://start.thinkful.com/react/?utm_source=github&utm_medium=badge&utm_campaign=react-bootstrap">live Thinkful hangout</a>. Hear about the challenges other developers are running into, or screenshare your own code with the group for feedback.</p>
<h3>Chat rooms</h3>
<p>Discuss questions in the <code className="js">#react-bootstrap</code> channel on the <a href="http://www.reactiflux.com/">Reactiflux Slack</a> or on <a href="https://gitter.im/react-bootstrap/react-bootstrap">Gitter</a>.</p>
<h3>GitHub issues</h3>
<p>The issue tracker is the preferred channel for bug reports, features requests and submitting pull requests. See more about how we use issues in the <a href="https://github.com/react-bootstrap/react-bootstrap/blob/master/CONTRIBUTING.md#issues">contribution guidelines</a>.</p>
</div>
</div>
</div>
</div>
<PageFooter />
</div>
);
}
shouldComponentUpdate() {
return false;
}
}
|
src/routes/Dashboard/index.js | imrenagi/rojak-web-frontend | import React from 'react'
import { Switch, Route } from 'react-router-dom'
import Dashboard from './layouts/Dashboard'
const ElectionRoute = () => (
<Switch>
<Route path='/dashboard' component={Dashboard} />
</Switch>
)
export default ElectionRoute
|
docs/src/examples/modules/Accordion/Types/index.js | Semantic-Org/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/src/components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/src/components/ComponentDoc/ExampleSection'
const AccordionTypesExamples = () => (
<ExampleSection title='Types'>
<ComponentExample
title='Accordion'
description='A standard Accordion.'
examplePath='modules/Accordion/Types/AccordionExampleStandard'
/>
<ComponentExample
description='Accordion can be rendered via shorthand prop. It will automatically manage the component state.'
examplePath='modules/Accordion/Types/AccordionExampleStandardShorthand'
/>
<ComponentExample
title='Styled'
description='A styled accordion adds basic formatting.'
examplePath='modules/Accordion/Types/AccordionExampleStyled'
/>
</ExampleSection>
)
export default AccordionTypesExamples
|
javascript/AddOn/Navbar.js | AppStateESS/stories | 'use strict'
import React from 'react'
import PropTypes from 'prop-types'
import './nav.css'
const Navbar = (props) => {
const {rightSide, leftSide, header,} = props
let url = './'
let title
if (header != null) {
if (header.title != undefined) {
if (header.url != null) {
url = header.url
}
title = header.title
} else {
title = header
}
}
return (
<div className="stories-navbar">
<nav className="navbar navbar-expand-md fixed-top navbar-light">
<a className="navbar-brand" href={url}>{title}</a>
<button
type="button"
className="navbar-toggler"
data-toggle="collapse"
data-target="#stories-navbar-toggle"
aria-expanded="false"
aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="stories-navbar-toggle">
<ul className="navbar-nav mr-auto">
<li className="nav-item dropdown">
<a
className="nav-link dropdown-toggle pointer"
data-toggle="dropdown"
role="button"
aria-haspopup="true"
aria-expanded="false">Manage
</a>
<div className="dropdown-menu">
<a className="dropdown-item" href="./stories/Entry/create">
<i className="fas fa-book"></i> Create a new story</a>
<hr/>
<a className="dropdown-item" href="./stories/Listing/admin">
<i className="fas fa-list"></i> Stories</a>
<a className="dropdown-item" href="./stories/Feature">
<span className="fas fa-th-large"></span> Features</a>
<a className="dropdown-item" href="./stories/Author">
<i className="fas fa-user"></i> Authors</a>
<a className="dropdown-item" href="./stories/Share">
<i className="fas fa-share-alt"></i> Share</a>
<a className="dropdown-item" href="./stories/Settings">
<i className="fas fa-cog"></i> Settings</a>
<hr/>
<a className="dropdown-item" href="index.php?module=controlpanel">Control panel</a>
</div>
</li>
{leftSide}
</ul>
<ul className="nav navbar-nav navbar-right">
{rightSide}
</ul>
</div>
</nav>
</div>
)
}
Navbar.propTypes = {
leftSide: PropTypes.oneOfType([PropTypes.array, PropTypes.object,]),
rightSide: PropTypes.oneOfType([PropTypes.array, PropTypes.object,]),
header: PropTypes.oneOfType([PropTypes.object, PropTypes.string,]),
}
export default Navbar
|
docs/app/Examples/modules/Sidebar/Overlay/index.js | aabustamante/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const SidebarVariationsExamples = () => (
<ExampleSection title='Overlay'>
<ComponentExample
title='Left Overlay'
description='Sidebar attached to the left of the pushable container overlayed on the pusher.'
examplePath='modules/Sidebar/Overlay/SidebarExampleLeftOverlay'
/>
<ComponentExample
title='Right Overlay'
description='Sidebar attached to the right of the pushable container overlayed on the pusher.'
examplePath='modules/Sidebar/Overlay/SidebarExampleRightOverlay'
/>
<ComponentExample
title='Top Overlay'
description='Sidebar attached to the top of the pushable container overlayed on the pusher.'
examplePath='modules/Sidebar/Overlay/SidebarExampleTopOverlay'
/>
<ComponentExample
title='Bottom Overlay'
description='Sidebar attached to the bottom of the pushable container overlayed on the pusher.'
examplePath='modules/Sidebar/Overlay/SidebarExampleBottomOverlay'
/>
</ExampleSection>
)
export default SidebarVariationsExamples
|
src/index.js | scalixte-mdsol/ReorderEventsWithReactDND | import React from 'react';
import ReactDOM from 'react-dom';
import Grid from './Grid';
ReactDOM.render(<Grid rows={10} cols={5}/>, document.getElementById('grid'));
|
app/ui/src/App.js | pequalsnp/eve-isk-tracker | import React, { Component } from 'react';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import {
BrowserRouter as Router,
Route
} from 'react-router-dom'
import {
ApolloClient,
ApolloProvider,
createNetworkInterface,
} from 'react-apollo';
import './App.css';
import { Navbar, Nav, NavItem } from 'react-bootstrap';
import Logout from './components/Logout';
import NavbarCharacterInfo from './components/NavbarCharacterInfo';
import Home from './pages/Home';
import BuildOMatic from './pages/BuildOMatic';
import Login from './pages/Login'
import {appReducer} from './reducers/AppReducer';
const networkInterface = createNetworkInterface({
uri: '/api/graphql',
opts: {
credentials: 'same-origin'
}
});
networkInterface.useAfter([{
/**
* applyAfterware
*
* Handle response error codes.
*/
applyAfterware(res, next) {
if (res.response.status === 401 || res.response.status === 403) {
window.location.replace("/logout");
}
next();
}
}]);
const client = new ApolloClient({
networkInterface,
});
const store = createStore(
combineReducers({
apollo: client.reducer(),
app: appReducer
}),
undefined,
compose(
applyMiddleware(client.middleware()),
// If you are using the devToolsExtension, you can add it here also
(typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined') ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f,
)
);
class App extends Component {
render() {
return (
<ApolloProvider store={store} client={client}>
<Router>
<div>
<Navbar inverse>
<Navbar.Header>
<Navbar.Brand>
<a href="/">Eve ISK</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Nav>
<NavItem href="/buildomatic">Build O Matic</NavItem>
</Nav>
<NavbarCharacterInfo />
</Navbar>
<Route exact path="/" component={Home}/>
<Route path="/buildomatic" component={BuildOMatic}/>
<Route path="/login" component={Login}/>
<Route path="/logout" component={Logout}/>
</div>
</Router>
</ApolloProvider>
);
}
}
export default App;
|
src/components/app/About/index.js | RelativeMedia/rm-frontend | import React from 'react'
import portrait from 'static/img/portrait_260x400.jpg'
const AboutComponent = (props) => (<div className='AboutComponent'>
<div className='container'>
<div className='row'>
<h1>About</h1>
</div>
<div className='row'>
<div className='about-body'>
<div className='col-xs-12 col-sm-3'>
<img src={portrait} className='img-responsive' />
</div>
<div className='col-xs-12 col-sm-9'>
<p>Hey there, my name is <strong>Mike DeVita</strong>. I am an IT professional that has worked in the industry since for over a decade. I develop custom websites and web applications for businesses. I am also a systems administrator for linux and windows systems. I live in Arizona have been here all my life, I've always had a passion for technology and programming.</p>
<p>I started web development in 2006 as a freelance developer writing custom PHP applications and customizing WordPress websites. In 2008 I opened Relative Media, the professional front to my web development and systems administration services.</p>
<p>I love hacking away at a command prompt solving problems and learning new things. I have managed single full-stack websites all the way up to small data centers and small business infrastructures.</p>
</div>
</div>
</div>
</div>
</div>)
AboutComponent.propTypes = {
}
export default AboutComponent
|
src/parser/warrior/fury/modules/features/checklist/Module.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import BaseChecklist from 'parser/shared/modules/features/Checklist/Module';
import CastEfficiency from 'parser/shared/modules/CastEfficiency';
import Combatants from 'parser/shared/modules/Combatants';
import PreparationRuleAnalyzer from 'parser/shared/modules/features/Checklist/PreparationRuleAnalyzer';
import RageDetails from '../../core/RageDetails';
import RageTracker from '../../core/RageTracker';
import AlwaysBeCasting from '../AlwaysBeCasting';
import MissedRampage from '../../spells/MissedRampage';
import Component from './Component';
import SiegeBreaker from '../../talents/Siegebreaker';
import Bladestorm from '../../talents/Bladestorm';
import DragonRoar from '../../talents/DragonRoar';
import WhirlWind from '../../spells/Whirlwind';
class Checklist extends BaseChecklist {
static dependencies = {
alwaysBeCasting: AlwaysBeCasting,
combatants: Combatants,
castEfficiency: CastEfficiency,
rageDetails: RageDetails,
rageTracker: RageTracker,
missedRampage: MissedRampage,
preparationRuleAnalyzer: PreparationRuleAnalyzer,
siegeBreaker: SiegeBreaker,
bladeStorm: Bladestorm,
dragonRoar: DragonRoar,
whirlWind: WhirlWind,
};
render() {
return (
<Component
combatant={this.combatants.selected}
castEfficiency={this.castEfficiency}
thresholds={{
...this.preparationRuleAnalyzer.thresholds,
rageDetails: this.rageDetails.suggestionThresholds,
siegeBreaker: this.siegeBreaker.suggestionThresholds,
bladeStorm: this.bladeStorm.suggestionThresholds,
dragonRoar: this.dragonRoar.suggestionThresholds,
downtimeSuggestionThresholds: this.alwaysBeCasting.downtimeSuggestionThresholds,
missedRampage: this.missedRampage.suggestionThresholds,
whirlWind: this.whirlWind.suggestionThresholds,
}}
/>
);
}
}
export default Checklist;
|
src/svg-icons/action/three-d-rotation.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionThreeDRotation = (props) => (
<SvgIcon {...props}>
<path d="M7.52 21.48C4.25 19.94 1.91 16.76 1.55 13H.05C.56 19.16 5.71 24 12 24l.66-.03-3.81-3.81-1.33 1.32zm.89-6.52c-.19 0-.37-.03-.52-.08-.16-.06-.29-.13-.4-.24-.11-.1-.2-.22-.26-.37-.06-.14-.09-.3-.09-.47h-1.3c0 .36.07.68.21.95.14.27.33.5.56.69.24.18.51.32.82.41.3.1.62.15.96.15.37 0 .72-.05 1.03-.15.32-.1.6-.25.83-.44s.42-.43.55-.72c.13-.29.2-.61.2-.97 0-.19-.02-.38-.07-.56-.05-.18-.12-.35-.23-.51-.1-.16-.24-.3-.4-.43-.17-.13-.37-.23-.61-.31.2-.09.37-.2.52-.33.15-.13.27-.27.37-.42.1-.15.17-.3.22-.46.05-.16.07-.32.07-.48 0-.36-.06-.68-.18-.96-.12-.28-.29-.51-.51-.69-.2-.19-.47-.33-.77-.43C9.1 8.05 8.76 8 8.39 8c-.36 0-.69.05-1 .16-.3.11-.57.26-.79.45-.21.19-.38.41-.51.67-.12.26-.18.54-.18.85h1.3c0-.17.03-.32.09-.45s.14-.25.25-.34c.11-.09.23-.17.38-.22.15-.05.3-.08.48-.08.4 0 .7.1.89.31.19.2.29.49.29.86 0 .18-.03.34-.08.49-.05.15-.14.27-.25.37-.11.1-.25.18-.41.24-.16.06-.36.09-.58.09H7.5v1.03h.77c.22 0 .42.02.6.07s.33.13.45.23c.12.11.22.24.29.4.07.16.1.35.1.57 0 .41-.12.72-.35.93-.23.23-.55.33-.95.33zm8.55-5.92c-.32-.33-.7-.59-1.14-.77-.43-.18-.92-.27-1.46-.27H12v8h2.3c.55 0 1.06-.09 1.51-.27.45-.18.84-.43 1.16-.76.32-.33.57-.73.74-1.19.17-.47.26-.99.26-1.57v-.4c0-.58-.09-1.1-.26-1.57-.18-.47-.43-.87-.75-1.2zm-.39 3.16c0 .42-.05.79-.14 1.13-.1.33-.24.62-.43.85-.19.23-.43.41-.71.53-.29.12-.62.18-.99.18h-.91V9.12h.97c.72 0 1.27.23 1.64.69.38.46.57 1.12.57 1.99v.4zM12 0l-.66.03 3.81 3.81 1.33-1.33c3.27 1.55 5.61 4.72 5.96 8.48h1.5C23.44 4.84 18.29 0 12 0z"/>
</SvgIcon>
);
ActionThreeDRotation = pure(ActionThreeDRotation);
ActionThreeDRotation.displayName = 'ActionThreeDRotation';
export default ActionThreeDRotation;
|
pootle/static/js/admin/components/User/UserEdit.js | ta2-1/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
import UserForm from './UserForm';
const UserEdit = React.createClass({
propTypes: {
collection: React.PropTypes.object.isRequired,
model: React.PropTypes.object,
onAdd: React.PropTypes.func.isRequired,
onDelete: React.PropTypes.func.isRequired,
onSuccess: React.PropTypes.func.isRequired,
},
render() {
return (
<div className="item-edit">
<div className="hd">
<h2>{gettext('Edit User')}</h2>
<button
onClick={this.props.onAdd}
className="btn btn-primary"
>
{gettext('Add User')}
</button>
</div>
<div className="bd">
{!this.props.model ?
<p>{gettext('Use the search form to find the user, then click on a user to edit.')}</p> :
<UserForm
key={this.props.model.id}
model={this.props.model}
collection={this.props.collection}
onSuccess={this.props.onSuccess}
onDelete={this.props.onDelete}
/>
}
</div>
</div>
);
},
});
export default UserEdit;
|
common/containers/FooterContainer/FooterContainer.js | sauleddy/HomePortal | import React from 'react';
import { connect } from 'react-redux';
import Footer from '../../components/Footer';
export default connect(
(state) => ({
}),
(dispatch) => ({
})
)(Footer);
|
src/decorators/withViewport.js | LukevdPalen/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value}); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
spec/javascripts/jsx/assignments/IndexMenuSpec.js | djbender/canvas-lms | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import ReactDOM from 'react-dom'
import TestUtils from 'react-dom/test-utils'
import Modal from 'react-modal'
import IndexMenu from 'jsx/assignments/IndexMenu'
import Actions from 'jsx/assignments/actions/IndexMenuActions'
import createFakeStore from './createFakeStore'
QUnit.module('AssignmentsIndexMenu')
const generateProps = (overrides, initialState = {}) => {
const state = {
externalTools: [],
selectedTool: null,
...initialState
}
return {
store: createFakeStore(state),
contextType: 'course',
contextId: 1,
setTrigger: () => {},
setDisableTrigger: () => {},
registerWeightToggle: () => {},
disableSyncToSis: () => {},
sisName: 'PowerSchool',
postToSisDefault: ENV.POST_TO_SIS_DEFAULT,
hasAssignments: ENV.HAS_ASSIGNMENTS,
...overrides
}
}
const renderComponent = props => TestUtils.renderIntoDocument(<IndexMenu {...props} />)
const context = {}
const beforeEach = () => {
context.sinon = sinon.createSandbox()
context.sinon.stub(Actions, 'apiGetLaunches').returns({
type: 'STUB_API_GET_TOOLS'
})
}
const afterEach = () => {
context.sinon.restore()
}
const testCase = (msg, testFunc) => {
beforeEach()
test(msg, testFunc)
afterEach()
}
testCase('renders a dropdown menu trigger and options list', () => {
const component = renderComponent(generateProps({}))
const triggers = TestUtils.scryRenderedDOMComponentsWithClass(component, 'al-trigger')
equal(triggers.length, 1)
const options = TestUtils.scryRenderedDOMComponentsWithClass(component, 'al-options')
equal(options.length, 1)
component.closeModal()
ReactDOM.unmountComponentAtNode(component.node.parentElement)
})
testCase('renders a bulk edit option if property is specified', () => {
const requestBulkEditFn = sinon.stub()
const component = renderComponent(generateProps({requestBulkEdit: requestBulkEditFn}))
const menuitem = TestUtils.scryRenderedDOMComponentsWithClass(
component,
'requestBulkEditMenuItem'
)
equal(menuitem.length, 1)
TestUtils.Simulate.click(menuitem[0])
ok(requestBulkEditFn.called)
component.closeModal()
ReactDOM.unmountComponentAtNode(component.node.parentElement)
})
testCase('does not render a bulk edit option if property is not specified', () => {
const component = renderComponent(generateProps())
const menuitem = TestUtils.scryRenderedDOMComponentsWithClass(
component,
'requestBulkEditMenuItem'
)
equal(menuitem.length, 0)
component.closeModal()
ReactDOM.unmountComponentAtNode(component.node.parentElement)
})
testCase('renders a LTI tool modal', () => {
const component = renderComponent(generateProps({}, {modalIsOpen: true}))
const modals = TestUtils.scryRenderedComponentsWithType(component, Modal)
equal(modals.length, 1)
component.closeModal()
ReactDOM.unmountComponentAtNode(component.node.parentElement)
})
testCase('Modal visibility agrees with state modalIsOpen', () => {
const component1 = renderComponent(generateProps({}, {modalIsOpen: true}))
const modal1 = TestUtils.findRenderedComponentWithType(component1, Modal)
equal(modal1.props.isOpen, true)
const component2 = renderComponent(generateProps({}, {modalIsOpen: false}))
equal(TestUtils.scryRenderedComponentsWithType(component2, Modal).length, 0)
component1.closeModal()
component2.closeModal()
ReactDOM.unmountComponentAtNode(component1.node.parentElement)
ReactDOM.unmountComponentAtNode(component2.node.parentElement)
})
testCase('renders no iframe when there is no selectedTool in state', () => {
const component = renderComponent(generateProps({}, {selectedTool: null}))
const iframes = TestUtils.scryRenderedDOMComponentsWithTag(component, 'iframe')
equal(iframes.length, 0)
component.closeModal()
ReactDOM.unmountComponentAtNode(component.node.parentElement)
})
testCase('renders iframe when there is a selectedTool in state', () => {
const component = renderComponent(
generateProps(
{},
{
modalIsOpen: true,
selectedTool: {
placements: {course_assignments_menu: {title: 'foo'}},
definition_id: 100
}
}
)
)
const modal = TestUtils.findRenderedComponentWithType(component, Modal)
const modalPortal = modal.portal
const iframes = TestUtils.scryRenderedDOMComponentsWithTag(modalPortal, 'iframe')
equal(iframes.length, 1)
component.closeModal()
ReactDOM.unmountComponentAtNode(component.node.parentElement)
})
testCase('onWeightedToggle dispatches expected actions', () => {
const props = generateProps({})
const store = props.store
const component = renderComponent(props)
const actionsCount = store.dispatchedActions.length
component.onWeightedToggle(true)
equal(store.dispatchedActions.length, actionsCount + 1)
equal(store.dispatchedActions[actionsCount].type, Actions.SET_WEIGHTED)
equal(store.dispatchedActions[actionsCount].payload, true)
component.onWeightedToggle(false)
equal(store.dispatchedActions.length, actionsCount + 2)
equal(store.dispatchedActions[actionsCount + 1].type, Actions.SET_WEIGHTED)
equal(store.dispatchedActions[actionsCount + 1].payload, false)
component.closeModal()
ReactDOM.unmountComponentAtNode(component.node.parentElement)
})
testCase('renders a dropdown menu with one option when sync to sis conditions are not met', () => {
const component = renderComponent(generateProps({}))
const options = TestUtils.scryRenderedDOMComponentsWithTag(component, 'li')
equal(options.length, 1)
component.closeModal()
ReactDOM.unmountComponentAtNode(component.node.parentElement)
})
testCase('renders a dropdown menu with two options when sync to sis conditions are met', () => {
ENV.POST_TO_SIS_DEFAULT = true
ENV.HAS_ASSIGNMENTS = true
const component = renderComponent(generateProps({}))
const options = TestUtils.scryRenderedDOMComponentsWithTag(component, 'li')
equal(options.length, 2)
component.closeModal()
ReactDOM.unmountComponentAtNode(component.node.parentElement)
})
testCase('renders a dropdown menu with one option when sync to sis conditions are not met', () => {
ENV.POST_TO_SIS_DEFAULT = true
ENV.HAS_ASSIGNMENTS = false
const component = renderComponent(generateProps({}))
const options = TestUtils.scryRenderedDOMComponentsWithTag(component, 'li')
equal(options.length, 1)
component.closeModal()
ReactDOM.unmountComponentAtNode(component.node.parentElement)
})
|
src/server/routes/collections.js | bookbrainz/bookbrainz-site | /*
* Copyright (C) 2020 Prabal Singh
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import * as commonUtils from '../../common/helpers/utils';
import * as error from '../../common/helpers/error';
import * as propHelpers from '../../client/helpers/props';
import * as utils from '../helpers/utils';
import {escapeProps, generateProps} from '../helpers/props';
import CollectionsPage from '../../client/components/pages/collections';
import Layout from '../../client/containers/layout';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import _ from 'lodash';
import express from 'express';
import {getOrderedPublicCollections} from '../helpers/collections';
import target from '../templates/target';
const router = express.Router();
/* GET collections page. */
// eslint-disable-next-line consistent-return
router.get('/', async (req, res, next) => {
try {
const {orm} = req.app.locals;
const size = req.query.size ? parseInt(req.query.size, 10) : 20;
const from = req.query.from ? parseInt(req.query.from, 10) : 0;
const type = req.query.type ? req.query.type : null;
const entityTypes = _.keys(commonUtils.getEntityModels(orm));
if (!entityTypes.includes(type) && type !== null) {
throw new error.BadRequestError(`Type ${type} do not exist`);
}
const {user} = req;
// fetch 1 more collections than required to check nextEnabled
const orderedRevisions = await getOrderedPublicCollections(from, size + 1, type, orm);
const {newResultsArray, nextEnabled} = utils.getNextEnabledAndResultsArray(orderedRevisions, size);
const props = generateProps(req, res, {
entityTypes,
from,
nextEnabled,
results: newResultsArray,
showLastModified: true,
showOwner: true,
size,
tableHeading: 'Public Collections',
type,
user
});
/*
* Renders react components server side and injects markup into target
* file object spread injects the app.locals variables into React as
* props
*/
const markup = ReactDOMServer.renderToString(
<Layout {...propHelpers.extractLayoutProps(props)}>
<CollectionsPage {...propHelpers.extractChildProps(props)}/>
</Layout>
);
res.send(target({
markup,
props: escapeProps(props),
script: '/js/collections.js',
title: 'All Collections'
}));
}
catch (err) {
return next(err);
}
});
// eslint-disable-next-line consistent-return
router.get('/collections', async (req, res, next) => {
try {
const {orm} = req.app.locals;
const size = req.query.size ? parseInt(req.query.size, 10) : 20;
const from = req.query.from ? parseInt(req.query.from, 10) : 0;
const type = req.query.type ? req.query.type : null;
const entityTypes = _.keys(commonUtils.getEntityModels(orm));
if (!entityTypes.includes(type) && type !== null) {
throw new error.BadRequestError(`Type ${type} do not exist`);
}
const orderedRevisions = await getOrderedPublicCollections(from, size, type, orm);
res.send(orderedRevisions);
}
catch (err) {
return next(err);
}
});
export default router;
|
stories/landing/index.js | sethbergman/operationcode_frontend | import React from 'react';
import { Router } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import { storiesOf } from '@storybook/react';
import Landing from 'scenes/home/landing/landing';
const history = createHistory();
storiesOf('Landing', module)
.add('Basic', () => (
<Router history={history}>
<Landing />
</Router>
));
|
src/svg-icons/notification/phone-in-talk.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationPhoneInTalk = (props) => (
<SvgIcon {...props}>
<path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 12h2c0-4.97-4.03-9-9-9v2c3.87 0 7 3.13 7 7zm-4 0h2c0-2.76-2.24-5-5-5v2c1.66 0 3 1.34 3 3z"/>
</SvgIcon>
);
NotificationPhoneInTalk = pure(NotificationPhoneInTalk);
NotificationPhoneInTalk.displayName = 'NotificationPhoneInTalk';
NotificationPhoneInTalk.muiName = 'SvgIcon';
export default NotificationPhoneInTalk;
|
Libraries/Image/Image.ios.js | CodeLinkIO/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Image
* @flow
*/
'use strict';
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const ImageResizeMode = require('ImageResizeMode');
const ImageSourcePropType = require('ImageSourcePropType');
const ImageStylePropTypes = require('ImageStylePropTypes');
const NativeMethodsMixin = require('NativeMethodsMixin');
const NativeModules = require('NativeModules');
const React = require('React');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheet = require('StyleSheet');
const StyleSheetPropType = require('StyleSheetPropType');
const flattenStyle = require('flattenStyle');
const requireNativeComponent = require('requireNativeComponent');
const resolveAssetSource = require('resolveAssetSource');
const PropTypes = React.PropTypes;
const ImageViewManager = NativeModules.ImageViewManager;
/**
* A React component for displaying different types of images,
* including network images, static resources, temporary local images, and
* images from local disk, such as the camera roll.
*
* This example shows both fetching and displaying an image from local
* storage as well as one from network.
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, View, Image } from 'react-native';
*
* class DisplayAnImage extends Component {
* render() {
* return (
* <View>
* <Image
* source={require('./img/favicon.png')}
* />
* <Image
* style={{width: 50, height: 50}}
* source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}
* />
* </View>
* );
* }
* }
*
* // App registration and rendering
* AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage);
* ```
*
* You can also add `style` to an image:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, View, Image, StyleSheet } from 'react-native';
*
* const styles = StyleSheet.create({
* stretch: {
* width: 50,
* height: 200
* }
* });
*
* class DisplayAnImageWithStyle extends Component {
* render() {
* return (
* <View>
* <Image
* style={styles.stretch}
* source={require('./img/favicon.png')}
* />
* </View>
* );
* }
* }
*
* // App registration and rendering
* AppRegistry.registerComponent(
* 'DisplayAnImageWithStyle',
* () => DisplayAnImageWithStyle
* );
* ```
*
* ### GIF and WebP support on Android
*
* By default, GIF and WebP are not supported on Android.
*
* You will need to add some optional modules in `android/app/build.gradle`, depending on the needs of your app.
*
* ```
* dependencies {
* // If your app supports Android versions before Ice Cream Sandwich (API level 14)
* compile 'com.facebook.fresco:animated-base-support:0.11.0'
*
* // For animated GIF support
* compile 'com.facebook.fresco:animated-gif:0.11.0'
*
* // For WebP support, including animated WebP
* compile 'com.facebook.fresco:animated-webp:0.11.0'
* compile 'com.facebook.fresco:webpsupport:0.11.0'
*
* // For WebP support, without animations
* compile 'com.facebook.fresco:webpsupport:0.11.0'
* }
* ```
*
* Also, if you use GIF with ProGuard, you will need to add this rule in `proguard-rules.pro` :
* ```
* -keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl {
* public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline.core.ExecutorSupplier);
* }
* ```
*
*/
const Image = React.createClass({
propTypes: {
/**
* > `ImageResizeMode` is an `Enum` for different image resizing modes, set via the
* > `resizeMode` style property on `Image` components. The values are `contain`, `cover`,
* > `stretch`, `center`, `repeat`.
*/
style: StyleSheetPropType(ImageStylePropTypes),
/**
* The image source (either a remote URL or a local file resource).
*
* This prop can also contain several remote URLs, specified together with
* their width and height and potentially with scale/other URI arguments.
* The native side will then choose the best `uri` to display based on the
* measured size of the image container. A `cache` property can be added to
* control how networked request interacts with the local cache.
*/
source: ImageSourcePropType,
/**
* A static image to display while loading the image source.
*
* - `uri` - a string representing the resource identifier for the image, which
* should be either a local file path or the name of a static image resource
* (which should be wrapped in the `require('./path/to/image.png')` function).
* - `width`, `height` - can be specified if known at build time, in which case
* these will be used to set the default `<Image/>` component dimensions.
* - `scale` - used to indicate the scale factor of the image. Defaults to 1.0 if
* unspecified, meaning that one image pixel equates to one display point / DIP.
* - `number` - Opaque type returned by something like `require('./image.jpg')`.
*
* @platform ios
*/
defaultSource: PropTypes.oneOfType([
// TODO: Tooling to support documenting these directly and having them display in the docs.
PropTypes.shape({
uri: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
scale: PropTypes.number,
}),
PropTypes.number,
]),
/**
* When true, indicates the image is an accessibility element.
* @platform ios
*/
accessible: PropTypes.bool,
/**
* The text that's read by the screen reader when the user interacts with
* the image.
* @platform ios
*/
accessibilityLabel: PropTypes.node,
/**
* blurRadius: the blur radius of the blur filter added to the image
* @platform ios
*/
blurRadius: PropTypes.number,
/**
* When the image is resized, the corners of the size specified
* by `capInsets` will stay a fixed size, but the center content and borders
* of the image will be stretched. This is useful for creating resizable
* rounded buttons, shadows, and other resizable assets. More info in the
* [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets).
*
* @platform ios
*/
capInsets: EdgeInsetsPropType,
/**
* The mechanism that should be used to resize the image when the image's dimensions
* differ from the image view's dimensions. Defaults to `auto`.
*
* - `auto`: Use heuristics to pick between `resize` and `scale`.
*
* - `resize`: A software operation which changes the encoded image in memory before it
* gets decoded. This should be used instead of `scale` when the image is much larger
* than the view.
*
* - `scale`: The image gets drawn downscaled or upscaled. Compared to `resize`, `scale` is
* faster (usually hardware accelerated) and produces higher quality images. This
* should be used if the image is smaller than the view. It should also be used if the
* image is slightly bigger than the view.
*
* More details about `resize` and `scale` can be found at http://frescolib.org/docs/resizing-rotating.html.
*
* @platform android
*/
resizeMethod: PropTypes.oneOf(['auto', 'resize', 'scale']),
/**
* Determines how to resize the image when the frame doesn't match the raw
* image dimensions.
*
* - `cover`: Scale the image uniformly (maintain the image's aspect ratio)
* so that both dimensions (width and height) of the image will be equal
* to or larger than the corresponding dimension of the view (minus padding).
*
* - `contain`: Scale the image uniformly (maintain the image's aspect ratio)
* so that both dimensions (width and height) of the image will be equal to
* or less than the corresponding dimension of the view (minus padding).
*
* - `stretch`: Scale width and height independently, This may change the
* aspect ratio of the src.
*
* - `repeat`: Repeat the image to cover the frame of the view. The
* image will keep it's size and aspect ratio. (iOS only)
*/
resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat', 'center']),
/**
* A unique identifier for this element to be used in UI Automation
* testing scripts.
*/
testID: PropTypes.string,
/**
* Invoked on mount and layout changes with
* `{nativeEvent: {layout: {x, y, width, height}}}`.
*/
onLayout: PropTypes.func,
/**
* Invoked on load start.
*
* e.g., `onLoadStart={(e) => this.setState({loading: true})}`
*/
onLoadStart: PropTypes.func,
/**
* Invoked on download progress with `{nativeEvent: {loaded, total}}`.
* @platform ios
*/
onProgress: PropTypes.func,
/**
* Invoked on load error with `{nativeEvent: {error}}`.
*/
onError: PropTypes.func,
/**
* Invoked when a partial load of the image is complete. The definition of
* what constitutes a "partial load" is loader specific though this is meant
* for progressive JPEG loads.
* @platform ios
*/
onPartialLoad: PropTypes.func,
/**
* Invoked when load completes successfully.
*/
onLoad: PropTypes.func,
/**
* Invoked when load either succeeds or fails.
*/
onLoadEnd: PropTypes.func,
},
statics: {
resizeMode: ImageResizeMode,
/**
* Retrieve the width and height (in pixels) of an image prior to displaying it.
* This method can fail if the image cannot be found, or fails to download.
*
* In order to retrieve the image dimensions, the image may first need to be
* loaded or downloaded, after which it will be cached. This means that in
* principle you could use this method to preload images, however it is not
* optimized for that purpose, and may in future be implemented in a way that
* does not fully load/download the image data. A proper, supported way to
* preload images will be provided as a separate API.
*
* @param uri The location of the image.
* @param success The function that will be called if the image was successfully found and width
* and height retrieved.
* @param failure The function that will be called if there was an error, such as failing to
* to retrieve the image.
*
* @returns void
*
* @platform ios
*/
getSize: function(
uri: string,
success: (width: number, height: number) => void,
failure: (error: any) => void,
) {
ImageViewManager.getSize(uri, success, failure || function() {
console.warn('Failed to get size for image: ' + uri);
});
},
/**
* Prefetches a remote image for later use by downloading it to the disk
* cache
*
* @param url The remote location of the image.
*
* @return The prefetched image.
*/
prefetch(url: string) {
return ImageViewManager.prefetchImage(url);
},
/**
* Resolves an asset reference into an object which has the properties `uri`, `width`,
* and `height`. The input may either be a number (opaque type returned by
* require('./foo.png')) or an `ImageSource` like { uri: '<http location || file path>' }
*/
resolveAssetSource: resolveAssetSource,
},
mixins: [NativeMethodsMixin],
/**
* `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
* make `this` look like an actual native component class.
*/
viewConfig: {
uiViewClassName: 'UIView',
validAttributes: ReactNativeViewAttributes.UIView
},
render: function() {
const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined };
let sources;
let style;
if (Array.isArray(source)) {
style = flattenStyle([styles.base, this.props.style]) || {};
sources = source;
} else {
const {width, height, uri} = source;
style = flattenStyle([{width, height}, styles.base, this.props.style]) || {};
sources = [source];
if (uri === '') {
console.warn('source.uri should not be an empty string');
}
}
const resizeMode = this.props.resizeMode || (style || {}).resizeMode || 'cover'; // Workaround for flow bug t7737108
const tintColor = (style || {}).tintColor; // Workaround for flow bug t7737108
if (this.props.src) {
console.warn('The <Image> component requires a `source` property rather than `src`.');
}
return (
<RCTImageView
{...this.props}
style={style}
resizeMode={resizeMode}
tintColor={tintColor}
source={sources}
/>
);
},
});
const styles = StyleSheet.create({
base: {
overflow: 'hidden',
},
});
const RCTImageView = requireNativeComponent('RCTImageView', Image);
module.exports = Image;
|
src/routes/register/Register.js | louisukiri/react-starter-kit | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present 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 PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Register.css';
class Register extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>
{this.props.title}
</h1>
<p>...</p>
</div>
</div>
);
}
}
export default withStyles(s)(Register);
|
src/App/ui/routes-App.js | techmsi/mental-health-app | import React from 'react';
import { Route, Switch } from 'react-router-dom';
import {
DiagnosisRoutes,
Welcome,
TherapistRoutes,
StyleGuide,
QuestionsRoutes
} from 'App/ui/dynamicRoutes';
const AppRoutes = () => (
<Switch>
<Route exact path='/' component={Welcome} />
<Route path='/therapists' component={TherapistRoutes} />
<Route exact path='/questionnaire' component={QuestionsRoutes} />
<Route exact path='/results' component={DiagnosisRoutes} />
<Route exact path='/styles' component={StyleGuide} />
</Switch>
);
export default AppRoutes;
|
src/svg-icons/notification/vpn-lock.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationVpnLock = (props) => (
<SvgIcon {...props}>
<path d="M22 4v-.5C22 2.12 20.88 1 19.5 1S17 2.12 17 3.5V4c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zm-.8 0h-3.4v-.5c0-.94.76-1.7 1.7-1.7s1.7.76 1.7 1.7V4zm-2.28 8c.04.33.08.66.08 1 0 2.08-.8 3.97-2.1 5.39-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H7v-2h2c.55 0 1-.45 1-1V8h2c1.1 0 2-.9 2-2V3.46c-.95-.3-1.95-.46-3-.46C5.48 3 1 7.48 1 13s4.48 10 10 10 10-4.48 10-10c0-.34-.02-.67-.05-1h-2.03zM10 20.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L8 16v1c0 1.1.9 2 2 2v1.93z"/>
</SvgIcon>
);
NotificationVpnLock = pure(NotificationVpnLock);
NotificationVpnLock.displayName = 'NotificationVpnLock';
export default NotificationVpnLock;
|
docs/src/app/components/pages/components/FlatButton/ExampleComplex.js | tan-jerene/material-ui | import React from 'react';
import FlatButton from 'material-ui/FlatButton';
import FontIcon from 'material-ui/FontIcon';
import ActionAndroid from 'material-ui/svg-icons/action/android';
const styles = {
exampleImageInput: {
cursor: 'pointer',
position: 'absolute',
top: 0,
bottom: 0,
right: 0,
left: 0,
width: '100%',
opacity: 0,
},
};
const FlatButtonExampleComplex = () => (
<div>
<FlatButton label="Choose an Image" labelPosition="before">
<input type="file" style={styles.exampleImageInput} />
</FlatButton>
<FlatButton
label="Label before"
labelPosition="before"
primary={true}
style={styles.button}
icon={<ActionAndroid />}
/>
<FlatButton
label="GitHub Link"
href="https://github.com/callemall/material-ui"
secondary={true}
icon={<FontIcon className="muidocs-icon-custom-github" />}
/>
</div>
);
export default FlatButtonExampleComplex;
|
src/routes/Logout/components/Logout.js | EricThsi/today-focus-news | import React, { Component } from 'react';
// import PropTypes from 'prop-types'
import { Grid, Col, Panel, HelpBlock } from 'react-bootstrap'
import { Link } from 'react-router'
import './Logout.scss'
class Logout extends Component {
constructor(props) {
super(props)
this.timer = null
this.state = {
timeout: this.props.timeout
}
}
componentDidMount() {
this.props.logout()
this.timer = setInterval(() => {
let timeout = this.state.timeout - 1
if (timeout <= 0) {
this.clearTimer()
this.props.redirect()
return
}
this.setState({
timeout: timeout
})
}, 1000)
}
componentWillUnmount() {
if (this.timer != null) {
this.clearTimer()
}
}
clearTimer() {
clearInterval(this.timer)
this.timer = null
}
render() {
return (
<Grid>
<Col md={6} mdPush={3}>
<Panel>
<HelpBlock style={{textAlign: 'center'}}>
<p><strong>You have been logged out.</strong></p>
<p>Redirecting to <Link to="/">home page</Link>
...in {this.state.timeout}s</p>
<p>or <Link to="/login">login</Link> again.</p>
</HelpBlock>
</Panel>
</Col>
</Grid>
)
}
}
export default Logout
|
modules/Navigation.js | emmenko/react-router | import React from 'react';
var { object } = React.PropTypes;
/**
* A mixin for components that modify the URL.
*
* Example:
*
* import { Navigation } from 'react-router';
*
* var MyLink = React.createClass({
* mixins: [ Navigation ],
* handleClick(event) {
* event.preventDefault();
* this.transitionTo('aRoute', { the: 'params' }, { the: 'query' });
* },
* render() {
* return (
* <a onClick={this.handleClick}>Click me!</a>
* );
* }
* });
*/
var Navigation = {
contextTypes: {
router: object.isRequired
}
};
var RouterNavigationMethods = [
'makePath',
'makeHref',
'transitionTo',
'replaceWith',
'go',
'goBack',
'goForward'
];
RouterNavigationMethods.forEach(function (method) {
Navigation[method] = function () {
var router = this.context.router;
return router[method].apply(router, arguments);
};
});
export default Navigation;
|
fluxArchitecture/src/js/components/catalog/app-catalogitem.js | 3mundi/React-Bible | import React from 'react';
import AppActions from '../../actions/app-actions';
import CartButton from '../cart/app-cart-button';
import { Link } from 'react-router';
export default (props) => {
let itemStyle = {
borderBottom: '1px solid #ccc',
paddingBottom: 15
}
return (
<div className="col-xs-6 col-sm-4 col-md-3" style={itemStyle}>
<h4>{ props.item.title }</h4>
<img src="http://placehold.it/250x250" width="100%" className="img-responsive"/>
<p>{ props.item.summary }</p>
<p>${ props.item.cost } <span
className="text-success">
{ props.item.qty && `(${props.item.qty} in cart)`}
</span>
</p>
<div className="btn-group">
<Link to={ `/item/${props.item.id}` } className="btn btn-default btn-sm">Learn More</Link>
<CartButton
handler={
AppActions.addItem.bind(null, props.item)
}
txt="Add To Cart"
/>
</div>
</div>
)
}
|
project/react-ant-multi-pages/src/pages/index/containers/FunderMgmt/List/form.js | FFF-team/generator-earth | import moment from 'moment'
import React from 'react'
import { Input, DatePicker, Button, Form, Select } from 'antd'
import BaseContainer from 'ROOT_SOURCE/base/BaseContainer'
import { mapMoment } from 'ROOT_SOURCE/utils/fieldFormatter'
import DateRangePicker from 'ROOT_SOURCE/components/DateRangePicker'
const { MonthPicker, RangePicker } = DatePicker
const FormItem = Form.Item
export default class extends BaseContainer {
componentDidMount() {
// 其他页面使用 this.props.history.push(`${this.context.CONTAINER_ROUTE_PREFIX}/list`) 跳转到本页面时
// 建议使用store中的formData拉取新的tableData
if (this.props.history.action === 'PUSH') {
this.props.updateTable && this.props.formData && this.props.updateTable(this.props.formData)
}
}
/**
* 提交表单
*/
submitForm = async (e) => {
e && e.preventDefault && e.preventDefault()
// 提交表单最好新一个事务,不受其他事务影响
await this.sleep()
let _formData = { ...this.props.form.getFieldsValue() }
// _formData里的一些值需要适配
_formData = mapMoment(_formData, 'YYYY-MM-DD HH:mm:ss')
// action
this.props.updateTable && this.props.updateTable(_formData)
}
render() {
let { form, formData } = this.props
let { getFieldDecorator } = form
let { assetCode, assetName, contract, startDate, endDate } = formData
return (
<div className="ui-background">
<Form layout="inline" onSubmit={this.submitForm}>
<FormItem label={('资产方编号')}>
{getFieldDecorator('assetCode', {initialValue: assetCode||''})(<Input />)}
</FormItem>
<FormItem label={('资产方名称')}>
{getFieldDecorator('assetName', {initialValue: assetName||''})(<Input />)}
</FormItem>
<FormItem label={('签约主体')}>
{getFieldDecorator('contract', {initialValue: contract||''})(<Input />)}
</FormItem>
<FormItem label={('签约时间')}>
<DateRangePicker
dateShowFormat='YYYY年MM月DD HH:mm:ss'
form={form}
startVal={startDate}
startKey='startDate'
endVal={endDate}
endKey='endDate'
/>
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit"> 查询 </Button>
</FormItem>
</Form>
</div>
)
}
}
|
src/components/reduxDraft.js | gocreating/redux-draft | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actionCreators from '../actions/index';
export default (config) => (WrappedComponent) => {
class ReduxDraft extends Component {
constructor(props) {
super(props);
let { _initialized, init } = props;
if (!_initialized) {
init(config);
}
}
getChildContext() {
let {
updateEditorState,
updateReadOnly,
updateEntityData,
removeBlock,
} = this.props;
return {
_reduxDraft: {
updateEditorState,
updateReadOnly,
updateEntityData,
removeBlock,
},
};
}
render() {
let {
_instance,
name,
config,
editorState,
customStyleMap,
...rest
} = this.props;
return name !== undefined ? (
<WrappedComponent
focus={(_instance || {}).focus}
name={name}
config={config}
editorState={editorState}
customStyleMap={customStyleMap}
{...rest}
/>
) : null;
}
}
ReduxDraft.childContextTypes = {
_reduxDraft: PropTypes.object,
};
let mapStateToProps = (state) => {
let currentDraft = state.draft[config.name] || {};
return currentDraft;
};
let mapDispatchToProps = (dispatch) => {
let bindDraft = (actionCreator) => actionCreator.bind(null, config.name);
let bondDraftActionCreators = {};
Object
.keys(actionCreators)
.forEach(ac => {
bondDraftActionCreators[ac] = bindDraft(actionCreators[ac]);
});
return {
...bindActionCreators(bondDraftActionCreators, dispatch),
dispatch,
};
};
return connect(mapStateToProps, mapDispatchToProps)(ReduxDraft);
};
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Promises.js | Clearcover/web-build | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load() {
return Promise.resolve([
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
{ id: 4, name: '4' },
]);
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
componentDidMount() {
load().then(users => {
this.setState({ users });
});
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-promises">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
frontend/app_v2/src/components/DashboardCreate/DashboardCreateContainer.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import { Route, Routes } from 'react-router-dom'
// FPCC
import PageCrud from 'components/PageCrud'
import WidgetCrud from 'components/WidgetCrud'
import RequireAuth from 'common/RequireAuth'
import DashboardCreateData from 'components/DashboardCreate/DashboardCreateData'
import DashboardCreatePresentation from 'components/DashboardCreate/DashboardCreatePresentation'
function DashboardCreateContainer() {
const { tileContent, headerContent, site } = DashboardCreateData()
return (
<div id="DashboardCreateContainer">
<Routes>
<Route
path="page"
element={
<RequireAuth role="Admin" withMessage>
<PageCrud.Container />
</RequireAuth>
}
/>
<Route
path="widget"
element={
<RequireAuth role="Admin" withMessage>
<WidgetCrud.Container />
</RequireAuth>
}
/>
<Route
path="*"
element={<DashboardCreatePresentation tileContent={tileContent} headerContent={headerContent} site={site} />}
/>
</Routes>
</div>
)
}
export default DashboardCreateContainer
|
frontend/src/Components/Form/CheckInput.js | geogolem/Radarr | import classNames from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Icon from 'Components/Icon';
import { icons, kinds } from 'Helpers/Props';
import FormInputHelpText from './FormInputHelpText';
import styles from './CheckInput.css';
class CheckInput extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this._checkbox = null;
}
componentDidMount() {
this.setIndeterminate();
}
componentDidUpdate() {
this.setIndeterminate();
}
//
// Control
setIndeterminate() {
if (!this._checkbox) {
return;
}
const {
value,
uncheckedValue,
checkedValue
} = this.props;
this._checkbox.indeterminate = value !== uncheckedValue && value !== checkedValue;
}
toggleChecked = (checked, shiftKey) => {
const {
name,
value,
checkedValue,
uncheckedValue
} = this.props;
const newValue = checked ? checkedValue : uncheckedValue;
if (value !== newValue) {
this.props.onChange({
name,
value: newValue,
shiftKey
});
}
}
//
// Listeners
setRef = (ref) => {
this._checkbox = ref;
}
onClick = (event) => {
if (this.props.isDisabled) {
return;
}
const shiftKey = event.nativeEvent.shiftKey;
const checked = !this._checkbox.checked;
event.preventDefault();
this.toggleChecked(checked, shiftKey);
}
onChange = (event) => {
const checked = event.target.checked;
const shiftKey = event.nativeEvent.shiftKey;
this.toggleChecked(checked, shiftKey);
}
//
// Render
render() {
const {
className,
containerClassName,
name,
value,
checkedValue,
uncheckedValue,
helpText,
helpTextWarning,
isDisabled,
kind
} = this.props;
const isChecked = value === checkedValue;
const isUnchecked = value === uncheckedValue;
const isIndeterminate = !isChecked && !isUnchecked;
const isCheckClass = `${kind}IsChecked`;
return (
<div className={containerClassName}>
<label
className={styles.label}
onClick={this.onClick}
>
<input
ref={this.setRef}
className={styles.checkbox}
type="checkbox"
name={name}
checked={isChecked}
disabled={isDisabled}
onChange={this.onChange}
/>
<div
className={classNames(
className,
isChecked ? styles[isCheckClass] : styles.isNotChecked,
isIndeterminate && styles.isIndeterminate,
isDisabled && styles.isDisabled
)}
>
{
isChecked &&
<Icon name={icons.CHECK} />
}
{
isIndeterminate &&
<Icon name={icons.CHECK_INDETERMINATE} />
}
</div>
{
helpText &&
<FormInputHelpText
className={styles.helpText}
text={helpText}
/>
}
{
!helpText && helpTextWarning &&
<FormInputHelpText
className={styles.helpText}
text={helpTextWarning}
isWarning={true}
/>
}
</label>
</div>
);
}
}
CheckInput.propTypes = {
className: PropTypes.string.isRequired,
containerClassName: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
checkedValue: PropTypes.bool,
uncheckedValue: PropTypes.bool,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
helpText: PropTypes.string,
helpTextWarning: PropTypes.string,
isDisabled: PropTypes.bool,
kind: PropTypes.oneOf(kinds.all).isRequired,
onChange: PropTypes.func.isRequired
};
CheckInput.defaultProps = {
className: styles.input,
containerClassName: styles.container,
checkedValue: true,
uncheckedValue: false,
kind: kinds.PRIMARY
};
export default CheckInput;
|
src/backward/Widgets/Subtitle.js | sampsasaarela/NativeBase | /* @flow */
import React, { Component } from 'react';
import { Text } from 'react-native';
import { connectStyle } from 'native-base-shoutem-theme';
import mapPropsToStyleNames from '../../Utils/mapPropsToStyleNames';
class Subtitle extends Component {
render() {
return (
<Text ref={c => this._root = c} {...this.props} />
);
}
}
Subtitle.propTypes = {
...Text.propTypes,
style: React.PropTypes.object,
};
const StyledSubtitle = connectStyle('NativeBase.Subtitle', {}, mapPropsToStyleNames)(Subtitle);
export {
StyledSubtitle as Subtitle,
};
|
src/components/general/ShortcutButton.js | katima-g33k/blu-react-desktop | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Button from './Button';
import Icon from './Icon';
export default class ShortcutButton extends Component {
static propTypes = {
hint: PropTypes.string.isRequired,
href: PropTypes.string.isRequired,
icon: PropTypes.oneOf(Object.values(Icon.ICONS)),
label: PropTypes.string,
onClick: PropTypes.func.isRequired,
style: PropTypes.shape(),
};
static defaultProps = {
icon: null,
label: '',
style: {},
};
handleOnClick = () => this.props.onClick(this.props.href);
render() {
return (
<Button
glyph={this.props.icon}
hint={this.props.hint}
label={this.props.label}
onClick={this.handleOnClick}
style={this.props.style}
/>
);
}
}
|
app/client/main.js | dshook/issue-viewer | import React from 'react';
import babel from 'babel/polyfill';
import { Router, Route, Link } from 'react-router';
import { history } from 'react-router/lib/HashHistory';
import Layout from './views/Layout.jsx';
import IssueList from './views/IssueList.jsx';
import Issue from './views/Issue.jsx';
// Finally we render a `Router` component with some `Route`s, it'll do all
// the fancy routing stuff for us.
React.render((
<Router history={history}>
<Route component={Layout}>
<Route path="/" component={IssueList}/>
<Route path="issue/:repo/:number" component={Issue}/>
</Route>
</Router>
), document.getElementById('layout'));
|
lib/components/ChromeNotice.js | hanford/filepizza | import React from 'react'
import DownloadStore from '../stores/DownloadStore'
import SupportStore from '../stores/SupportStore'
function getState() {
return {
active: SupportStore.getState().isChrome && DownloadStore.getState().fileSize >= 500000000
}
}
export default class ChromeNotice extends React.Component {
constructor() {
super()
this.state = getState()
this._onChange = () => {
this.setState(getState())
}
}
componentDidMount() {
DownloadStore.listen(this._onChange)
SupportStore.listen(this._onChange)
}
componentDidUnmount() {
DownloadStore.unlisten(this._onChange)
SupportStore.unlisten(this._onChange)
}
render() {
if (this.state.active) {
return <p className="notice">Chrome has issues downloading files > 500 MB. Try using Firefox instead.</p>
} else {
return null
}
}
}
|
src/JSONObjectNode.js | jasisk/react-json-tree | import React from 'react';
import reactMixin from 'react-mixin';
import { ExpandedStateHandlerMixin } from './mixins';
import JSONArrow from './JSONArrow';
import grabNode from './grab-node';
const styles = {
base: {
position: 'relative',
paddingTop: 3,
paddingBottom: 3,
marginLeft: 14
},
label: {
margin: 0,
padding: 0,
display: 'inline-block'
},
span: {
cursor: 'default'
},
spanType: {
marginLeft: 5,
marginRight: 5
}
};
@reactMixin.decorate(ExpandedStateHandlerMixin)
export default class JSONObjectNode extends React.Component {
defaultProps = {
data: [],
initialExpanded: false
};
// cache store for the number of items string we display
itemString = false;
// flag to see if we still need to render our child nodes
needsChildNodes = true;
// cache store for our child nodes
renderedChildren = [];
constructor(props) {
super(props);
this.state = {
expanded: this.props.initialExpanded,
createdChildNodes: false
};
}
// Returns the child nodes for each element in the object. If we have
// generated them previously, we return from cache, otherwise we create
// them.
getChildNodes() {
if (this.state.expanded && this.needsChildNodes) {
const obj = this.props.data;
let childNodes = [];
for (let k in obj) {
if (obj.hasOwnProperty(k)) {
let prevData;
if (typeof this.props.previousData !== 'undefined' && this.props.previousData !== null) {
prevData = this.props.previousData[k];
}
const node = grabNode(k, obj[k], prevData, this.props.theme);
if (node !== false) {
childNodes.push(node);
}
}
}
this.needsChildNodes = false;
this.renderedChildren = childNodes;
}
return this.renderedChildren;
}
// Returns the "n Items" string for this node, generating and
// caching it if it hasn't been created yet.
getItemString() {
if (!this.itemString) {
const len = Object.keys(this.props.data).length;
this.itemString = len + ' key' + (len !== 1 ? 's' : '');
}
return this.itemString;
}
render() {
let childListStyle = {
padding: 0,
margin: 0,
listStyle: 'none',
display: (this.state.expanded) ? 'block' : 'none'
};
let containerStyle;
let spanStyle = {
...styles.span,
color: this.props.theme.base0B
};
containerStyle = {
...styles.base
};
if (this.state.expanded) {
spanStyle = {
...spanStyle,
color: this.props.theme.base03
};
}
return (
<li style={containerStyle}>
<JSONArrow theme={this.props.theme} open={this.state.expanded} onClick={::this.handleClick}/>
<label style={{
...styles.label,
color: this.props.theme.base0D
}} onClick={::this.handleClick}>
{this.props.keyName}:
</label>
<span style={spanStyle} onClick={::this.handleClick}>
<span style={styles.spanType}>{}</span>
{this.getItemString()}
</span>
<ul style={childListStyle}>
{this.getChildNodes()}
</ul>
</li>
);
}
}
|
src/components/map.js | bartvde/sdk | /*
* Copyright 2015-present Boundless Spatial Inc., http://boundlessgeo.com
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations
* under the License.
*/
import fetch from 'isomorphic-fetch';
import uuid from 'uuid';
import createFilter from '@mapbox/mapbox-gl-style-spec/feature_filter';
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
import {connect} from 'react-redux';
import {applyBackground, applyStyle} from 'ol-mapbox-style';
import OlMap from 'ol/pluggablemap';
import View from 'ol/view';
import Overlay from 'ol/overlay';
import MapRenderer from 'ol/renderer/canvas/map';
import interaction from 'ol/interaction';
import plugins from 'ol/plugins';
import PluginType from 'ol/plugintype';
import TileLayerRenderer from 'ol/renderer/canvas/tilelayer';
import Observable from 'ol/observable';
import Proj from 'ol/proj';
import Coordinate from 'ol/coordinate';
import Sphere from 'ol/sphere';
import TileLayer from 'ol/layer/tile';
import XyzSource from 'ol/source/xyz';
import TileWMSSource from 'ol/source/tilewms';
import TileJSON from 'ol/source/tilejson';
import TileGrid from 'ol/tilegrid';
import VectorTileLayer from 'ol/layer/vectortile';
import VectorTileSource from 'ol/source/vectortile';
import MvtFormat from 'ol/format/mvt';
import RenderFeature from 'ol/render/feature';
import ImageLayer from 'ol/layer/image';
import ImageStaticSource from 'ol/source/imagestatic';
import VectorLayer from 'ol/layer/vector';
import VectorSource from 'ol/source/vector';
import GeoJsonFormat from 'ol/format/geojson';
import EsriJsonFormat from 'ol/format/esrijson';
import DrawInteraction from 'ol/interaction/draw';
import ModifyInteraction from 'ol/interaction/modify';
import SelectInteraction from 'ol/interaction/select';
import Style from 'ol/style/style';
import SpriteStyle from '../style/sprite';
import AttributionControl from 'ol/control/attribution';
import LoadingStrategy from 'ol/loadingstrategy';
import {updateLayer, setView, setBearing} from '../actions/map';
import {setMapSize, setMousePosition, setMapExtent, setResolution, setProjection} from '../actions/mapinfo';
import {INTERACTIONS, LAYER_VERSION_KEY, SOURCE_VERSION_KEY, TIME_KEY, TIME_ATTRIBUTE_KEY, QUERYABLE_KEY, QUERY_ENDPOINT_KEY} from '../constants';
import {dataVersionKey} from '../reducers/map';
import {setMeasureFeature, clearMeasureFeature} from '../actions/drawing';
import ClusterSource from '../source/cluster';
import {parseQueryString, jsonClone, jsonEquals, getLayerById, degreesToRadians, radiansToDegrees, getKey, encodeQueryObject} from '../util';
import fetchJsonp from 'fetch-jsonp';
import 'ol/ol.css';
/** @module components/map
*
* @desc Provide an OpenLayers map which reflects the
* state of the Redux store.
*/
const GEOJSON_FORMAT = new GeoJsonFormat();
const ESRIJSON_FORMAT = new EsriJsonFormat();
const WGS84_SPHERE = new Sphere(6378137);
const MAPBOX_PROTOCOL = 'mapbox://';
const BBOX_STRING = '{bbox-epsg-3857}';
plugins.register(PluginType.MAP_RENDERER, MapRenderer);
plugins.register(PluginType.LAYER_RENDERER, TileLayerRenderer);
/** This variant of getVersion() differs as it allows
* for undefined values to be returned.
* @param {Object} obj The state.map object
* @param {Object} obj.metadata The state.map.metadata object
* @param {string} key One of 'bnd:layer-version', 'bnd:source-version', or 'bnd:data-version'.
*
* @returns {(number|undefined)} The version number of the given metadata key.
*/
function getVersion(obj, key) {
if (obj.metadata === undefined) {
return undefined;
}
return obj.metadata[key];
}
/** Configures an OpenLayers TileWMS or XyzSource object from the provided
* Mapbox GL style object.
* @param {Object} glSource The Mapbox GL map source containing a 'tiles' property.
* @param {Object} mapProjection The OpenLayers projection object.
* @param {string} time TIME parameter.
*
* @returns {Object} Configured OpenLayers TileWMSSource or XyzSource.
*/
function configureTileSource(glSource, mapProjection, time) {
const tile_url = glSource.tiles[0];
const commonProps = {
attributions: glSource.attribution,
minZoom: glSource.minzoom,
maxZoom: 'maxzoom' in glSource ? glSource.maxzoom : 22,
tileSize: glSource.tileSize || 512,
crossOrigin: 'crossOrigin' in glSource ? glSource.crossOrigin : 'anonymous',
projection: mapProjection,
};
// check to see if the url is a wms request.
if (tile_url.toUpperCase().indexOf('SERVICE=WMS') >= 0) {
const urlParts = glSource.tiles[0].split('?');
const params = parseQueryString(urlParts[1]);
const keys = Object.keys(params);
for (let i = 0, ii = keys.length; i < ii; ++i) {
if (keys[i].toUpperCase() === 'REQUEST') {
delete params[keys[i]];
}
}
if (time) {
params.TIME = time;
}
return new TileWMSSource(Object.assign({
url: urlParts[0],
params,
}, commonProps));
}
const source = new XyzSource(Object.assign({
urls: glSource.tiles,
}, commonProps));
source.setTileLoadFunction((tile, src) => {
// copy the src string.
let img_src = src.slice();
if (src.indexOf(BBOX_STRING) !== -1) {
const bbox = source.getTileGrid().getTileCoordExtent(tile.getTileCoord());
img_src = src.replace(BBOX_STRING, bbox.toString());
}
// disabled the linter below as this is how
// OpenLayers documents this operation.
// eslint-disable-next-line
tile.getImage().src = img_src;
});
if (glSource.scheme === 'tms') {
source.setTileUrlFunction((tileCoord, pixelRatio, projection) => {
const min = 0;
const max = glSource.tiles.length - 1;
const idx = Math.floor(Math.random() * (max - min + 1)) + min;
const z = tileCoord[0];
const x = tileCoord[1];
const y = tileCoord[2] + (1 << z);
return glSource.tiles[idx].replace('{z}', z).replace('{y}', y).replace('{x}', x);
});
}
return source;
}
/** Configures an OpenLayers TileJSONSource object from the provided
* Mapbox GL style object.
* @param {Object} glSource The Mapbox GL map source containing a 'url' property.
*
* @returns {Object} Configured OpenLayers TileJSONSource.
*/
function configureTileJSONSource(glSource) {
return new TileJSON({
url: glSource.url,
crossOrigin: 'anonymous',
});
}
/** Configures an OpenLayers ImageStaticSource object from the provided
* Mapbox GL style object.
* @param {Object} glSource The Mapbox GL map source of type 'image'.
*
* @returns {Object} Configured OpenLayers ImageStaticSource.
*/
function configureImageSource(glSource) {
const coords = glSource.coordinates;
const source = new ImageStaticSource({
url: glSource.url,
imageExtent: [coords[0][0], coords[3][1], coords[1][0], coords[0][1]],
projection: 'EPSG:4326',
});
return source;
}
/** Configures an OpenLayers VectorTileSource object from the provided
* Mapbox GL style object.
* @param {Object} glSource The Mapbox GL map source of type 'vector'.
* @param {string} accessToken The user's Mapbox tiles access token .
*
* @returns {Object} Configured OpenLayers VectorTileSource.
*/
function configureMvtSource(glSource, accessToken) {
const url = glSource.url;
let urls;
if (url.indexOf(MAPBOX_PROTOCOL) === 0) {
const mapid = url.replace(MAPBOX_PROTOCOL, '');
const suffix = 'vector.pbf';
const hosts = ['a', 'b', 'c', 'd'];
urls = [];
for (let i = 0, ii = hosts.length; i < ii; ++i) {
const host = hosts[i];
urls.push(`https://${host}.tiles.mapbox.com/v4/${mapid}/{z}/{x}/{y}.${suffix}?access_token=${accessToken}`);
}
} else {
urls = [url];
}
// predefine the source in-case it is needed
// for the tile_url_fn
let source;
// check to see if the url uses bounding box or Z,X,Y
let tile_url_fn;
if (url.indexOf(BBOX_STRING) !== -1) {
tile_url_fn = function(urlTileCoord, pixelRatio, projection) {
const bbox = source.getTileGrid().getTileCoordExtent(urlTileCoord);
return url.replace(BBOX_STRING, bbox.toString());
};
}
source = new VectorTileSource({
urls,
tileGrid: TileGrid.createXYZ({maxZoom: 22}),
tilePixelRatio: 16,
format: new MvtFormat(),
crossOrigin: 'crossOrigin' in glSource ? glSource.crossOrigin : 'anonymous',
tileUrlFunction: tile_url_fn,
});
return source;
}
function getLoaderFunction(glSource, mapProjection, baseUrl) {
return function(bbox, resolution, projection) {
// setup a feature promise to handle async loading
// of features.
let features_promise;
// if the data is a string, assume it's a url
if (typeof glSource.data === 'string') {
let url = glSource.data;
// if the baseUrl is present and the url does not
// start with http:// or "https://" then assume the path is
// relative to the style doc.
if (!(url.indexOf('https://') === 0 || url.indexOf('http://') === 0)) {
if (baseUrl && url.indexOf('.') === 0) {
url = url.substring(1);
}
url = baseUrl + url;
}
// check to see if the bbox strategy should be employed
// for this source.
if (url.indexOf(BBOX_STRING) >= 0) {
url = url.replace(BBOX_STRING, bbox.toString());
}
features_promise = fetch(url).then(response => response.json());
} else if (typeof glSource.data === 'object'
&& (glSource.data.type === 'Feature' || glSource.data.type === 'FeatureCollection')) {
features_promise = new Promise((resolve) => {
resolve(glSource.data);
});
}
// if data is undefined then no promise would
// have been created.
if (features_promise) {
// when the feature promise resolves,
// add those features to the source.
features_promise.then((features) => {
// features could be null, in which case there
// are no features to add.
if (features) {
// setup the projection options.
const readFeatureOpt = {featureProjection: mapProjection};
// bulk load the feature data
this.addFeatures(GEOJSON_FORMAT.readFeatures(features, readFeatureOpt));
}
}).catch((error) => {
console.error(error);
});
}
};
}
function updateGeojsonSource(olSource, glSource, mapView, baseUrl) {
let src = olSource;
if (glSource.cluster) {
src = olSource.getSource();
}
// update the loader function based on the glSource definition
src.loader_ = getLoaderFunction(glSource, mapView.getProjection(), baseUrl);
// clear the layer WITHOUT dispatching remove events.
src.clear(true);
// force a refresh
src.loadFeatures(mapView.calculateExtent(), mapView.getResolution(), mapView.getProjection());
}
/** Create a vector source based on a
* Mapbox GL styles definition.
*
* @param {Object} glSource A Mapbox GL styles defintiion of the source.
* @param {Object} mapView The OpenLayers map view.
* @param {string} baseUrl The mapbox base url.
* @param {boolean} wrapX Should we wrap the world?
*
* @returns {Object} ol.source.vector instance.
*/
function configureGeojsonSource(glSource, mapView, baseUrl, wrapX) {
const use_bbox = (typeof glSource.data === 'string' && glSource.data.indexOf(BBOX_STRING) >= 0);
const vector_src = new VectorSource({
strategy: use_bbox ? LoadingStrategy.bbox : LoadingStrategy.all,
loader: getLoaderFunction(glSource, mapView.getProjection(), baseUrl),
useSpatialIndex: true,
wrapX: wrapX,
});
// GeoJson sources can be clustered but OpenLayers
// uses a special source type for that. This handles the
// "switch" of source-class.
let new_src = vector_src;
if (glSource.cluster) {
new_src = new ClusterSource({
source: vector_src,
// default the distance to 50 as that's what
// is specified by Mapbox.
distance: glSource.clusterRadius ? glSource.clusterRadius : 50,
});
}
// seed the vector source with the first update
// before returning it.
updateGeojsonSource(new_src, glSource, mapView, baseUrl);
return new_src;
}
/** Configures a Mapbox GL source object into appropriate
* an appropriatly typed OpenLayers source object.
* @param {Object} glSource The source object.
* @param {Object} mapView The OpenLayers view object.
* @param {string} accessToken A Mapbox access token.
* @param {string} baseUrl A baseUrl provided by this.props.mapbox.baseUrl.
* @param {string} time The current time if time-enabled.
* @param {boolean} wrapX Should we wrap the world?
*
* @returns {(Object|null)} Callback to the applicable configure source method.
*/
function configureSource(glSource, mapView, accessToken, baseUrl, time, wrapX) {
// tiled raster layer.
if (glSource.type === 'raster') {
if ('tiles' in glSource) {
return configureTileSource(glSource, mapView.getProjection(), time);
} else if (glSource.url) {
return configureTileJSONSource(glSource);
}
} else if (glSource.type === 'geojson') {
return configureGeojsonSource(glSource, mapView, baseUrl, wrapX);
} else if (glSource.type === 'image') {
return configureImageSource(glSource);
} else if (glSource.type === 'vector') {
return configureMvtSource(glSource, accessToken);
}
return null;
}
/** Create a unique key for a group of layers
* @param {Object[]} layer_group An array of Mapbox GL layers.
*
* @returns {string} The layer_group source name, followed by a concatenated string of layer ids.
*/
function getLayerGroupName(layer_group) {
const all_names = [];
for (let i = 0, ii = layer_group.length; i < ii; i++) {
all_names.push(layer_group[i].id);
}
return `${layer_group[0].source}-${all_names.join(',')}`;
}
/** Get the source name from the layer group name.
* @param {string} groupName The layer group name.
*
* @returns {string} The source name for the provided layer group name.
*/
function getSourceName(groupName) {
const dash = groupName.indexOf('-');
return groupName.substring(0, dash);
}
/** Populate a ref'd layer.
* @param {Object[]} layersDef All layers defined in the Mapbox GL stylesheet.
* @param {Object} glLayer Subset of layers to be rendered as a group.
*
* @returns {Object} A new glLayer object with ref'd layer properties mixed in.
*/
export function hydrateLayer(layersDef, glLayer) {
// Small sanity check for when this
// is blindly called on any layer.
if (glLayer === undefined || glLayer.ref === undefined) {
return glLayer;
}
const ref_layer = getLayerById(layersDef, glLayer.ref);
// default the layer definition to return to
// the layer itself, incase we can't find the ref layer.
let layer_def = glLayer;
// ensure the ref layer is SOMETHING.
if (ref_layer) {
// clone the gl layer
layer_def = jsonClone(glLayer);
// remove the reference
layer_def.ref = undefined;
// mixin the layer_def to the ref layer.
layer_def = Object.assign({}, ref_layer, layer_def);
}
// return the new layer.
return layer_def;
}
/** Hydrate a layer group
* Normalizes all the ref layers in a group.
*
* @param {Object[]} layersDef All layers defined in the Mapbox GL stylesheet.
* @param {Object[]} layerGroup Subset of layers to be rendered as a group.
*
* @returns {Object[]} An array with the ref layers normalized.
*/
function hydrateLayerGroup(layersDef, layerGroup) {
const hydrated_group = [];
for (let i = 0, ii = layerGroup.length; i < ii; i++) {
// hydrateLayer checks for "ref"
hydrated_group.push(hydrateLayer(layersDef, layerGroup[i]));
}
return hydrated_group;
}
export function getFakeStyle(sprite, layers, baseUrl, accessToken) {
const fake_style = {
version: 8,
sprite,
layers,
};
if (sprite && sprite.indexOf(MAPBOX_PROTOCOL) === 0) {
fake_style.sprite = `${baseUrl}/sprite?access_token=${accessToken}`;
}
return fake_style;
}
export class Map extends React.Component {
constructor(props) {
super(props);
this.sourcesVersion = null;
this.layersVersion = null;
// keep a version of the sources in
// their OpenLayers source definition.
this.sources = {};
// hash of the openlayers layers in the map.
this.layers = {};
// popups and their elements are stored as an ID managed hash.
this.popups = {};
this.elems = {};
// interactions are how the user can manipulate the map,
// this tracks any active interaction.
this.activeInteractions = null;
}
componentDidMount() {
// put the map into the DOM
this.configureMap();
}
componentWillUnmount() {
if (this.map) {
this.map.setTarget(null);
}
}
/** This will check nextProps and nextState to see
* what needs to be updated on the map.
* @param {Object} nextProps The next properties of this component.
*
* @returns {boolean} should the component re-render?
*/
shouldComponentUpdate(nextProps) {
const old_time = getKey(this.props.map.metadata, TIME_KEY);
const new_time = getKey(nextProps.map.metadata, TIME_KEY);
if (old_time !== new_time) {
// find time dependent layers
for (let i = 0, ii = nextProps.map.layers.length; i < ii; ++i) {
const layer = nextProps.map.layers[i];
if (layer.metadata[TIME_ATTRIBUTE_KEY] !== undefined) {
this.props.updateLayer(layer.id, {
filter: this.props.createLayerFilter(layer, nextProps.map.metadata[TIME_KEY])
});
}
if (layer.metadata[TIME_KEY] !== undefined) {
const source = layer.source;
const olSource = this.sources[source];
if (olSource && olSource instanceof TileWMSSource) {
olSource.updateParams({TIME: nextProps.map.metadata[TIME_KEY]});
}
}
}
}
const map_view = this.map.getView();
const map_proj = map_view.getProjection();
// compare the centers
if (nextProps.map.center !== undefined) {
// center has not been set yet or differs
if (this.props.map.center === undefined ||
(nextProps.map.center[0] !== this.props.map.center[0]
|| nextProps.map.center[1] !== this.props.map.center[1])) {
// convert the center point to map coordinates.
const center = Proj.transform(nextProps.map.center, 'EPSG:4326', map_proj);
map_view.setCenter(center);
}
}
// compare the zoom
if (nextProps.map.zoom !== undefined && (nextProps.map.zoom !== this.props.map.zoom)) {
map_view.setZoom(nextProps.map.zoom + 1);
}
// compare the rotation
if (nextProps.map.bearing !== undefined && nextProps.map.bearing !== this.props.map.bearing) {
const rotation = degreesToRadians(nextProps.map.bearing);
map_view.setRotation(-rotation);
}
// check the sources diff
const next_sources_version = getVersion(nextProps.map, SOURCE_VERSION_KEY);
if (this.sourcesVersion !== next_sources_version) {
// go through and update the sources.
this.configureSources(nextProps.map.sources, next_sources_version);
}
const next_layer_version = getVersion(nextProps.map, LAYER_VERSION_KEY);
if (this.layersVersion !== next_layer_version) {
// go through and update the layers.
this.configureLayers(nextProps.map.sources, nextProps.map.layers, next_layer_version, nextProps.map.sprite);
}
// check the vector sources for data changes
const src_names = Object.keys(nextProps.map.sources);
for (let i = 0, ii = src_names.length; i < ii; i++) {
const src_name = src_names[i];
const src = this.props.map.sources[src_name];
if (src && src.type === 'geojson') {
const version_key = dataVersionKey(src_name);
if (this.props.map.metadata !== undefined &&
this.props.map.metadata[version_key] !== nextProps.map.metadata[version_key]) {
const next_src = nextProps.map.sources[src_name];
updateGeojsonSource(this.sources[src_name], next_src, map_view, this.props.mapbox.baseUrl);
}
}
}
// do a quick sweep to remove any popups
// that have been closed.
this.updatePopups();
// change the current interaction as needed
if (nextProps.drawing && (nextProps.drawing.interaction !== this.props.drawing.interaction
|| nextProps.drawing.sourceName !== this.props.drawing.sourceName)) {
this.updateInteraction(nextProps.drawing);
}
if (nextProps.print && nextProps.print.exportImage) {
// this uses the canvas api to get the map image
this.map.once('postcompose', (evt) => {
evt.context.canvas.toBlob(this.props.onExportImage);
}, this);
this.map.renderSync();
}
// This should always return false to keep
// render() from being called.
return false;
}
/** Callback for finished drawings, converts the event's feature
* to GeoJSON and then passes the relevant information on to
* this.props.onFeatureDrawn, this.props.onFeatureModified,
* or this.props.onFeatureSelected.
*
* @param {string} eventType One of 'drawn', 'modified', or 'selected'.
* @param {string} sourceName Name of the geojson source.
* @param {Object} feature OpenLayers feature object.
*
*/
onFeatureEvent(eventType, sourceName, feature) {
if (feature !== undefined) {
// convert the feature to GeoJson
const proposed_geojson = GEOJSON_FORMAT.writeFeatureObject(feature, {
dataProjection: 'EPSG:4326',
featureProjection: this.map.getView().getProjection(),
});
// Pass on feature drawn this map object, the target source,
// and the drawn feature.
if (eventType === 'drawn') {
this.props.onFeatureDrawn(this, sourceName, proposed_geojson);
} else if (eventType === 'modified') {
this.props.onFeatureModified(this, sourceName, proposed_geojson);
} else if (eventType === 'selected') {
this.props.onFeatureSelected(this, sourceName, proposed_geojson);
}
}
}
/** Convert the GL source definitions into internal
* OpenLayers source definitions.
* @param {Object} sourcesDef All sources defined in the Mapbox GL stylesheet.
* @param {number} sourceVersion Counter for the source metadata updates.
*/
configureSources(sourcesDef, sourceVersion) {
this.sourcesVersion = sourceVersion;
// TODO: Update this to check "diff" configurations
// of sources. Currently, this will only detect
// additions and removals.
let src_names = Object.keys(sourcesDef);
const map_view = this.map.getView();
for (let i = 0, ii = src_names.length; i < ii; i++) {
const src_name = src_names[i];
// Add the source because it's not in the current
// list of sources.
if (!(src_name in this.sources)) {
const time = getKey(this.props.map.metadata, TIME_KEY);
this.sources[src_name] = configureSource(sourcesDef[src_name], map_view,
this.props.mapbox.accessToken, this.props.mapbox.baseUrl, time, this.props.wrapX);
}
const src = this.props.map.sources[src_name];
if (src && src.type !== 'geojson' && !jsonEquals(src, sourcesDef[src_name])) {
// reconfigure source and tell layers about it
this.sources[src_name] = configureSource(sourcesDef[src_name], map_view);
this.updateLayerSource(src_name);
}
// Check to see if there was a clustering change.
// Because OpenLayers requires a *different* source to handle clustering,
// this handles update the named source and then subsequently updating
// the layers.
if (src && (src.cluster !== sourcesDef[src_name].cluster
|| src.clusterRadius !== sourcesDef[src_name].clusterRadius)) {
// reconfigure the source for clustering.
this.sources[src_name] = configureSource(sourcesDef[src_name], map_view);
// tell all the layers about it.
this.updateLayerSource(src_name);
}
}
// remove sources no longer there.
src_names = Object.keys(this.sources);
for (let i = 0, ii = src_names.length; i < ii; i++) {
const src_name = src_names[i];
if (!(src_name in sourcesDef)) {
// TODO: Remove all layers that are using this source.
delete this.sources[src_name];
}
}
}
/** Applies the sprite animation information to the layer
* @param {Object} olLayer OpenLayers layer object.
* @param {Object[]} layers Array of Mapbox GL layer objects.
*/
applySpriteAnimation(olLayer, layers) {
this.map.on('postcompose', (e) => {
this.map.render(); // animate
});
const styleCache = {};
const spriteOptions = {};
for (let i = 0, ii = layers.length; i < ii; ++i) {
const layer = layers[i];
spriteOptions[layer.id] = jsonClone(layer.metadata['bnd:animate-sprite']);
if (Array.isArray(layer.filter)) {
layer.filter = createFilter(layer.filter);
}
}
olLayer.setStyle((feature, resolution) => {
// loop over the layers to see which one matches
for (let l = 0, ll = layers.length; l < ll; ++l) {
const layer = layers[l];
if (!layer.filter || layer.filter({properties: feature.getProperties()})) {
if (!spriteOptions[layer.id].rotation || (spriteOptions[layer.id].rotation && !spriteOptions[layer.id].rotation.property)) {
if (!styleCache[layer.id]) {
const sprite = new SpriteStyle(spriteOptions[layer.id]);
styleCache[layer.id] = new Style({image: sprite});
this.map.on('postcompose', (e) => {
sprite.update(e);
});
}
return styleCache[layer.id];
} else {
if (!styleCache[layer.id]) {
styleCache[layer.id] = {};
}
const rotationAttribute = spriteOptions[layer.id].rotation.property;
const rotation = feature.get(rotationAttribute);
if (!styleCache[layer.id][rotation]) {
const options = jsonClone(layer.metadata['bnd:animate-sprite']);
options.rotation = rotation;
const sprite = new SpriteStyle(options);
const style = new Style({image: sprite});
this.map.on('postcompose', (e) => {
sprite.update(e);
});
styleCache[layer.id][rotation] = style;
}
return styleCache[layer.id][rotation];
}
}
}
return null;
});
}
/** Configures OpenLayers layer style.
* @param {Object} olLayer OpenLayers layer object.
* @param {Object[]} layers Array of Mapbox GL layer objects.
* @param {string} sprite The sprite of the map.
*/
applyStyle(olLayer, layers, sprite) {
// filter out the layers which are not visible
const render_layers = [];
const spriteLayers = [];
for (let i = 0, ii = layers.length; i < ii; i++) {
const layer = layers[i];
if (layer.metadata && layer.metadata['bnd:animate-sprite']) {
spriteLayers.push(layer);
}
const is_visible = layer.layout ? layer.layout.visibility !== 'none' : true;
if (is_visible) {
render_layers.push(layer);
}
}
if (spriteLayers.length > 0) {
this.applySpriteAnimation(olLayer, spriteLayers);
}
const fake_style = getFakeStyle(
sprite || this.props.map.sprite,
render_layers,
this.props.mapbox.baseUrl,
this.props.mapbox.accessToken,
);
if (olLayer.setStyle && spriteLayers.length === 0) {
applyStyle(olLayer, fake_style, layers[0].source);
}
// handle toggling the layer on or off
olLayer.setVisible(render_layers.length > 0);
}
/** Convert a Mapbox GL-defined layer to an OpenLayers layer.
* @param {string} sourceName Layer's source name.
* @param {Object} glSource Mapbox GL source object.
* @param {Object[]} layers Array of Mapbox GL layer objects.
* @param {string} sprite The sprite of the map.
*
* @returns {(Object|null)} Configured OpenLayers layer object, or null.
*/
configureLayer(sourceName, glSource, layers, sprite) {
const source = this.sources[sourceName];
let layer = null;
switch (glSource.type) {
case 'raster':
layer = new TileLayer({
source,
});
this.applyStyle(layer, layers, sprite);
return layer;
case 'geojson':
layer = new VectorLayer({
declutter: true,
source,
});
this.applyStyle(layer, layers, sprite);
return layer;
case 'vector':
layer = new VectorTileLayer({
declutter: true,
source,
});
this.applyStyle(layer, layers, sprite);
return layer;
case 'image':
return new ImageLayer({
source,
opacity: layers[0].paint ? layers[0].paint['raster-opacity'] : undefined,
});
default:
// pass, let the function return null
}
// this didn't work out.
return null;
}
/** Update a layer source, provided its name.
* @param {string} sourceName Layer's source name.
*/
updateLayerSource(sourceName) {
const layer_names = Object.keys(this.layers);
for (let i = 0, ii = layer_names.length; i < ii; i++) {
const name = layer_names[i];
if (getSourceName(name) === sourceName) {
this.layers[name].setSource(this.sources[sourceName]);
}
}
}
/** Updates the rendered OpenLayers layers
* based on the current Redux state.map.layers.
* @param {string[]} layerNames An array of layer names.
*/
cleanupLayers(layerNames) {
const layer_exists = {};
for (let i = 0, ii = layerNames.length; i < ii; i++) {
layer_exists[layerNames[i]] = true;
}
// check for layers which should be removed.
const layer_ids = Object.keys(this.layers);
for (let i = 0, ii = layer_ids.length; i < ii; i++) {
const layer_id = layer_ids[i];
// if the layer_id was not set to true then
// it has been removed from the state and needs to be removed
// from the map.
if (layer_exists[layer_id] !== true) {
this.map.removeLayer(this.layers[layer_id]);
delete this.layers[layer_id];
}
}
}
/** Configures the layers in the state
* and performs updates to the rendered layers as necessary.
* @param {Object[]} sourcesDef The array of sources in map.state.
* @param {Object[]} layersDef The array of layers in map.state.
* @param {number} layerVersion The value of state.map.metadata[LAYER_VERSION_KEY].
* @param {string} sprite The sprite of the map.
*/
configureLayers(sourcesDef, layersDef, layerVersion, sprite) {
// update the internal version counter.
this.layersVersion = layerVersion;
// bin layers into groups based on their source.
const layer_groups = [];
let last_source = null;
let layer_group = [];
for (let i = 0, ii = layersDef.length; i < ii; i++) {
let layer = layersDef[i];
// fake the "layer" by getting the source
// from the ref'd layer.
if (layer.ref !== undefined) {
layer = {
source: getLayerById(layersDef, layer.ref).source,
};
}
// if the layers differ start a new layer group
if (last_source === null || last_source !== layer.source) {
if (layer_group.length > 0) {
layer_groups.push(layer_group);
layer_group = [];
}
}
last_source = layer.source;
layer_group.push(layersDef[i]);
}
if (layer_group.length > 0) {
layer_groups.push(layer_group);
}
const group_names = [];
for (let i = 0, ii = layer_groups.length; i < ii; i++) {
const lyr_group = layer_groups[i];
const group_name = getLayerGroupName(lyr_group);
group_names.push(group_name);
const source_name = hydrateLayer(layersDef, lyr_group[0]).source;
const source = sourcesDef[source_name];
// if the layer is not on the map, create it.
if (!(group_name in this.layers)) {
if (lyr_group[0].type === 'background') {
applyBackground(this.map, {layers: lyr_group});
} else {
const hydrated_group = hydrateLayerGroup(layersDef, lyr_group);
const new_layer = this.configureLayer(source_name, source, hydrated_group, sprite);
// if the new layer has been defined, add it to the map.
if (new_layer !== null) {
new_layer.set('name', group_name);
this.layers[group_name] = new_layer;
this.map.addLayer(this.layers[group_name]);
}
}
} else {
const ol_layer = this.layers[group_name];
// check for style changes, the OL style
// is defined by filter and paint elements.
const current_layers = [];
for (let j = 0, jj = lyr_group.length; j < jj; j++) {
current_layers.push(getLayerById(this.props.map.layers, lyr_group[j].id));
}
if (!jsonEquals(lyr_group, current_layers)) {
this.applyStyle(ol_layer, hydrateLayerGroup(layersDef, lyr_group), sprite);
}
// update the min/maxzooms
const view = this.map.getView();
if (source.minzoom) {
ol_layer.setMinResolution(view.getResolutionForZoom(source.minzoom));
}
if (source.maxzoom) {
ol_layer.setMaxResolution(view.getResolutionForZoom(source.maxzoom));
}
// update the display order.
ol_layer.setZIndex(i);
}
}
// clean up layers which should be removed.
this.cleanupLayers(group_names);
}
/** Removes popups from the map via OpenLayers removeOverlay().
*/
updatePopups() {
const overlays = this.map.getOverlays();
const overlays_to_remove = [];
overlays.forEach((overlay) => {
const id = overlay.get('popupId');
if (this.popups[id].state.closed !== false) {
this.popups[id].setMap(null);
// mark this for removal
overlays_to_remove.push(overlay);
// umount the component from the DOM
ReactDOM.unmountComponentAtNode(this.elems[id]);
// remove the component from the popups hash
delete this.popups[id];
delete this.elems[id];
}
});
// remove the old/closed overlays from the map.
for (let i = 0, ii = overlays_to_remove.length; i < ii; i++) {
this.map.removeOverlay(overlays_to_remove[i]);
}
}
removePopup(popupId) {
this.popups[popupId].close();
this.updatePopups();
}
/** Add a Popup to the map.
*
* @param {SdkPopup} popup Instance of SdkPopop or a subclass.
* @param {boolean} [silent] When true, do not call updatePopups() after adding.
*
*/
addPopup(popup, silent = false) {
// each popup uses a unique id to relate what is
// in openlayers vs what we have in the react world.
const id = uuid.v4();
const elem = document.createElement('div');
elem.setAttribute('class', 'sdk-popup');
const overlay = new Overlay({
// create an empty div element for the Popup
element: elem,
// allow events to pass through, using the default stopevent
// container does not allow react to check for events.
stopEvent: false,
// put the popup into view
autoPan: true,
autoPanAnimation: {
duration: 250,
},
});
// Editor's note:
// I hate using the self = this construction but
// there were few options when needing to get the
// instance of the react component using the callback
// method recommened by eslint and the react team.
// See here:
// - https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-render-return-value.md
const self = this;
// render the element into the popup's DOM.
ReactDOM.render(popup, elem, (function addInstance() {
self.popups[id] = this;
self.elems[id] = elem;
this.setMap(self);
}));
// set the popup id so we can match the component
// to the overlay.
overlay.set('popupId', id);
// Add the overlay to the map,
this.map.addOverlay(overlay);
// reset the position after the popup has been added to the map.
// assumes the popups coordinate is 4326
const wgs84 = [popup.props.coordinate[0], popup.props.coordinate[1]];
const xy = Proj.transform(wgs84, 'EPSG:4326', this.map.getView().getProjection());
overlay.setPosition(xy);
// do not trigger an update if silent is
// set to true. Useful for bulk popup additions.
if (silent !== true) {
this.updatePopups();
}
}
/** Handles async (WMS, ArcGIS rest) GetFeatureInfo for a given map event.
*
* @param {Object} layer Mapbox GL layer object.
* @param {Promise[]} promises Features promies.
* @param {Object} evt Map event whose coordinates drive the feature request.
*
*/
handleAsyncGetFeatureInfo(layer, promises, evt) {
const map = this.map;
const view = map.getView();
const map_prj = view.getProjection();
let url, features_by_layer, layer_name;
if (layer.metadata[QUERYABLE_KEY] && (!layer.layout || (layer.layout.visibility && layer.layout.visibility !== 'none'))) {
const map_resolution = view.getResolution();
const source = this.sources[layer.source];
if (source instanceof TileWMSSource) {
promises.push(new Promise((resolve) => {
features_by_layer = {};
layer_name = layer.id;
url = this.sources[layer.source].getGetFeatureInfoUrl(
evt.coordinate, map_resolution, map_prj, {
INFO_FORMAT: 'application/json',
},
);
fetch(url).then(
response => response.json(),
error => console.error('An error occured.', error),
)
.then((json) => {
features_by_layer[layer_name] = GEOJSON_FORMAT.writeFeaturesObject(
GEOJSON_FORMAT.readFeatures(json), {
featureProjection: GEOJSON_FORMAT.readProjection(json),
dataProjection: 'EPSG:4326',
},
).features;
resolve(features_by_layer);
});
}));
} else if (layer.metadata[QUERY_ENDPOINT_KEY]) {
const map_size = map.getSize();
promises.push(new Promise((resolve) => {
features_by_layer = {};
const params = {
geometryType: 'esriGeometryPoint',
geometry: evt.coordinate.join(','),
sr: map_prj.getCode().split(':')[1],
tolerance: 2,
mapExtent: view.calculateExtent(map_size).join(','),
imageDisplay: map_size.join(',') + ',90',
f: 'json',
pretty: 'false'
};
url = `${layer.metadata[QUERY_ENDPOINT_KEY]}?${encodeQueryObject(params)}`;
fetchJsonp(url).then(
response => response.json(),
).then((json) => {
layer_name = layer.id;
const features = [];
for (let i = 0, ii = json.results.length; i < ii; ++i) {
features.push(ESRIJSON_FORMAT.readFeature(json.results[i]));
}
features_by_layer[layer_name] = GEOJSON_FORMAT.writeFeaturesObject(
features, {
featureProjection: map_prj,
dataProjection: 'EPSG:4326',
},
).features;
resolve(features_by_layer);
}).catch(function(error) {
console.error('An error occured.', error);
});
}));
}
}
}
/** Query the map and the appropriate layers.
*
* @param {Object} evt The click event that kicked off the query.
*
* @returns {Promise} Promise.all promise.
*/
queryMap(evt) {
// get the map projection
const map_prj = this.map.getView().getProjection();
// this is the standard "get features when clicking"
// business.
const features_promise = new Promise((resolve) => {
const features_by_layer = {};
this.map.forEachFeatureAtPixel(evt.pixel, (feature, layer) => {
// get the gl-name for the layer from the openlayer's layer.
const layer_name = layer.get('name');
// use that name as the key for the features-by-layer object,
// and initialize the array if the layer hasn't been used.
if (features_by_layer[layer_name] === undefined) {
features_by_layer[layer_name] = [];
}
// if the feature comes from a vector tiled source then
// it does not have a complete geometry to serialize and the
// geojson parser will fail.
if (feature instanceof RenderFeature) {
features_by_layer[layer_name].push({
properties: feature.getProperties(),
});
} else {
// ensure the features are in 4326 when sent back to the caller.
features_by_layer[layer_name].push(GEOJSON_FORMAT.writeFeatureObject(feature, {
featureProjection: map_prj,
dataProjection: 'EPSG:4326',
}));
}
});
resolve(features_by_layer);
});
const promises = [features_promise];
// add other async queries here.
for (let i = 0, ii = this.props.map.layers.length; i < ii; ++i) {
const layer = this.props.map.layers[i];
this.handleAsyncGetFeatureInfo(layer, promises, evt);
}
return Promise.all(promises);
}
/** Initialize the map */
configureMap() {
// determine the map's projection.
const map_proj = this.props.projection;
// determine the map's rotation.
let rotation;
if (this.props.map.bearing !== undefined) {
rotation = degreesToRadians(this.props.map.bearing);
}
// reproject the initial center based on that projection.
let center;
if (this.props.map.center !== undefined) {
center = Proj.transform(this.props.map.center, 'EPSG:4326', map_proj);
}
// initialize the map.
this.map = new OlMap({
interactions: interaction.defaults(),
controls: [new AttributionControl()],
target: this.mapdiv,
logo: false,
view: new View({
center,
zoom: this.props.map.zoom >= 0 ? this.props.map.zoom + 1 : this.props.map.zoom,
rotation: rotation !== undefined ? -rotation : 0,
projection: map_proj,
}),
});
if (this.props.hover) {
this.map.on('pointermove', (evt) => {
const lngLat = Proj.toLonLat(evt.coordinate);
this.props.setMousePosition({lng: lngLat[0], lat: lngLat[1]}, evt.coordinate);
});
}
// when the map moves update the location in the state
this.map.on('moveend', () => {
this.props.setView(this.map);
});
this.props.setSize(this.map);
this.props.setProjection(map_proj);
this.map.on('change:size', () => {
this.props.setSize(this.map);
});
// when the map is clicked, handle the event.
this.map.on('singleclick', (evt) => {
// React listens to events on the document, OpenLayers places their
// event listeners on the element themselves. The only element
// the map should care to listen to is the actual rendered map
// content. This work-around allows the popups and React-based
// controls to be placed on the ol-overlaycontainer instead of
// ol-overlaycontainer-stop-event
// eslint-disable-next-line no-underscore-dangle
if (this.map.getRenderer().canvas_ === evt.originalEvent.target) {
const map_prj = this.map.getView().getProjection();
// if includeFeaturesOnClick is true then query for the
// features on the map.
let features_promises = null;
if (this.props.includeFeaturesOnClick) {
features_promises = this.queryMap(evt);
}
// ensure the coordinate is also in 4326
const pt = Proj.transform(evt.coordinate, map_prj, 'EPSG:4326');
const coordinate = {
0: pt[0],
1: pt[1],
xy: evt.coordinate,
hms: Coordinate.toStringHDMS(pt),
};
// send the clicked-on coordinate and the list of features
this.props.onClick(this, coordinate, features_promises);
}
});
// bootstrap the map with the current configuration.
this.configureSources(this.props.map.sources, this.props.map.metadata[SOURCE_VERSION_KEY]);
this.configureLayers(this.props.map.sources, this.props.map.layers,
this.props.map.metadata[LAYER_VERSION_KEY]);
// this is done after the map composes itself for the first time.
// otherwise the map was not always ready for the initial popups.
this.map.once('postcompose', () => {
// add the initial popups from the user.
for (let i = 0, ii = this.props.initialPopups.length; i < ii; i++) {
// set silent to true since updatePopups is called after the loop
this.addPopup(this.props.initialPopups[i], true);
}
this.updatePopups();
});
// check for any interactions
if (this.props.drawing && this.props.drawing.interaction) {
this.updateInteraction(this.props.drawing);
}
}
/** Updates drawing interations.
* @param {Object} drawingProps props.drawing.
*/
updateInteraction(drawingProps) {
// this assumes the interaction is different,
// so the first thing to do is clear out the old interaction
if (this.activeInteractions !== null) {
for (let i = 0, ii = this.activeInteractions.length; i < ii; i++) {
this.map.removeInteraction(this.activeInteractions[i]);
}
this.activeInteractions = null;
}
if (drawingProps.interaction === INTERACTIONS.modify) {
const select = new SelectInteraction({
wrapX: false,
});
const modify = new ModifyInteraction({
features: select.getFeatures(),
});
modify.on('modifyend', (evt) => {
this.onFeatureEvent('modified', drawingProps.sourceName, evt.features.item(0));
});
this.activeInteractions = [select, modify];
} else if (drawingProps.interaction === INTERACTIONS.select) {
// TODO: Select is typically a single-feature affair but there
// should be support for multiple feature selections in the future.
const select = new SelectInteraction({
wrapX: false,
layers: (layer) => {
const layer_src = this.sources[drawingProps.sourceName];
return (layer.getSource() === layer_src);
},
});
select.on('select', () => {
this.onFeatureEvent('selected', drawingProps.sourcename, select.getFeatures().item(0));
});
this.activeInteractions = [select];
} else if (INTERACTIONS.drawing.includes(drawingProps.interaction)) {
let drawObj = {};
if (drawingProps.interaction === INTERACTIONS.box) {
const geometryFunction = DrawInteraction.createBox();
drawObj = {
type: 'Circle',
geometryFunction
};
} else {
drawObj = {type: drawingProps.interaction};
}
const draw = new DrawInteraction(drawObj);
draw.on('drawend', (evt) => {
this.onFeatureEvent('drawn', drawingProps.sourceName, evt.feature);
});
this.activeInteractions = [draw];
} else if (INTERACTIONS.measuring.includes(drawingProps.interaction)) {
// clear the previous measure feature.
this.props.clearMeasureFeature();
const measure = new DrawInteraction({
// The measure interactions are the same as the drawing interactions
// but are prefixed with "measure:"
type: drawingProps.interaction.split(':')[1],
});
let measure_listener = null;
measure.on('drawstart', (evt) => {
const geom = evt.feature.getGeometry();
const proj = this.map.getView().getProjection();
measure_listener = geom.on('change', (geomEvt) => {
this.props.setMeasureGeometry(geomEvt.target, proj);
});
this.props.setMeasureGeometry(geom, proj);
});
measure.on('drawend', () => {
// remove the listener
Observable.unByKey(measure_listener);
});
this.activeInteractions = [measure];
}
if (this.activeInteractions) {
for (let i = 0, ii = this.activeInteractions.length; i < ii; i++) {
this.map.addInteraction(this.activeInteractions[i]);
}
}
}
render() {
let className = 'sdk-map';
if (this.props.className) {
className = `${className} ${this.props.className}`;
}
return (
<div style={this.props.style} ref={(c) => {
this.mapdiv = c;
}} className={className}>
<div className="controls">
{this.props.children}
</div>
</div>
);
}
}
Map.propTypes = {
/** Should we wrap the world? If yes, data will be repeated in all worlds. */
wrapX: PropTypes.bool,
/** Should we handle map hover to show mouseposition? */
hover: PropTypes.bool,
/** Projection of the map, normally an EPSG code. */
projection: PropTypes.string,
/** Map configuration, modelled after the Mapbox Style specification. */
map: PropTypes.shape({
/** Center of the map. */
center: PropTypes.array,
/** Zoom level of the map. */
zoom: PropTypes.number,
/** Rotation of the map in degrees. */
bearing: PropTypes.number,
/** Extra information about the map. */
metadata: PropTypes.object,
/** List of map layers. */
layers: PropTypes.array,
/** List of layer sources. */
sources: PropTypes.object,
/** Sprite sheet to use. */
sprite: PropTypes.string,
}),
/** Child components. */
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]),
/** Mapbox specific configuration. */
mapbox: PropTypes.shape({
/** Base url to use for mapbox:// substitutions. */
baseUrl: PropTypes.string,
/** Access token for the Mapbox account to use. */
accessToken: PropTypes.string,
}),
/** Style configuration object. */
style: PropTypes.object,
/** Css className. */
className: PropTypes.string,
/** Drawing specific configuration. */
drawing: PropTypes.shape({
/** Current interaction to use for drawing. */
interaction: PropTypes.string,
/** Current source name to use for drawing. */
sourceName: PropTypes.string,
}),
/** Initial popups to display in the map. */
initialPopups: PropTypes.arrayOf(PropTypes.object),
/** setView callback function, triggered on moveend. */
setView: PropTypes.func,
/** setSize callback function, triggered on change size. */
setSize: PropTypes.func,
/** setMousePosition callback function, triggered on pointermove. */
setMousePosition: PropTypes.func,
/** setProjection callback function. */
setProjection: PropTypes.func,
/** Should we include features when the map is clicked? */
includeFeaturesOnClick: PropTypes.bool,
/** onClick callback function, triggered on singleclick. */
onClick: PropTypes.func,
/** onFeatureDrawn callback, triggered on drawend of the draw interaction. */
onFeatureDrawn: PropTypes.func,
/** onFeatureModified callback, triggered on modifyend of the modify interaction. */
onFeatureModified: PropTypes.func,
/** onFeatureSelected callback, triggered on select event of the select interaction. */
onFeatureSelected: PropTypes.func,
/** onExportImage callback, done on postcompose. */
onExportImage: PropTypes.func,
/** setMeasureGeometry callback, called when the measure geometry changes. */
setMeasureGeometry: PropTypes.func,
/** clearMeasureFeature callback, called when the measure feature is cleared. */
clearMeasureFeature: PropTypes.func,
/** Callback function that should generate a TIME based filter. */
createLayerFilter: PropTypes.func,
};
Map.defaultProps = {
wrapX: true,
hover: true,
projection: 'EPSG:3857',
map: {
center: [0, 0],
zoom: 2,
bearing: 0,
metadata: {},
layers: [],
sources: {},
sprite: undefined,
},
drawing: {
interaction: null,
source: null,
},
mapbox: {
baseUrl: '',
accessToken: '',
},
initialPopups: [],
setView: () => {
// swallow event.
},
setSize: () => {},
setMousePosition: () => {
// swallow event.
},
setProjection: () => {},
includeFeaturesOnClick: false,
onClick: () => {
},
onFeatureDrawn: () => {
},
onFeatureModified: () => {
},
onFeatureSelected: () => {
},
onExportImage: () => {
},
setMeasureGeometry: () => {
},
clearMeasureFeature: () => {
},
createLayerFilter: () => {
},
};
function mapStateToProps(state) {
return {
map: state.map,
drawing: state.drawing,
print: state.print,
mapbox: state.mapbox,
};
}
export function getMapExtent(view, size) {
const projection = view.getProjection();
const targetProj = 'EPSG:4326';
const view_extent = view.calculateExtent(size);
return Proj.transformExtent(view_extent, projection, targetProj);
}
function mapDispatchToProps(dispatch) {
return {
updateLayer: (layerId, layerConfig) => {
dispatch(updateLayer(layerId, layerConfig));
},
setView: (map) => {
const view = map.getView();
const projection = view.getProjection();
// transform the center to 4326 before dispatching the action.
const center = Proj.transform(view.getCenter(), projection, 'EPSG:4326');
const rotation = radiansToDegrees(view.getRotation());
const zoom = view.getZoom() - 1;
const size = map.getSize();
dispatch(setView(center, zoom));
dispatch(setBearing(-rotation));
dispatch(setMapExtent(getMapExtent(view, size)));
dispatch(setResolution(view.getResolution()));
},
setSize: (map) => {
const size = map.getSize();
const view = map.getView();
dispatch(setMapExtent(getMapExtent(view, size)));
dispatch(setMapSize(size));
},
setProjection: (projection) => {
dispatch(setProjection(projection));
},
setMeasureGeometry: (geometry, projection) => {
const geom = GEOJSON_FORMAT.writeGeometryObject(geometry, {
featureProjection: projection,
dataProjection: 'EPSG:4326',
});
const segments = [];
if (geom.type === 'LineString') {
for (let i = 0, ii = geom.coordinates.length - 1; i < ii; i++) {
const a = geom.coordinates[i];
const b = geom.coordinates[i + 1];
segments.push(WGS84_SPHERE.haversineDistance(a, b));
}
} else if (geom.type === 'Polygon' && geom.coordinates.length > 0) {
segments.push(Math.abs(WGS84_SPHERE.geodesicArea(geom.coordinates[0])));
}
dispatch(setMeasureFeature({
type: 'Feature',
properties: {},
geometry: geom,
}, segments));
},
clearMeasureFeature: () => {
dispatch(clearMeasureFeature());
},
setMousePosition(lngLat, coordinate) {
dispatch(setMousePosition(lngLat, coordinate));
},
};
}
// Ensure that withRef is set to true so getWrappedInstance will return the Map.
export default connect(mapStateToProps, mapDispatchToProps, undefined, {withRef: true})(Map);
|
src/svg-icons/communication/phonelink-ring.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationPhonelinkRing = (props) => (
<SvgIcon {...props}>
<path d="M20.1 7.7l-1 1c1.8 1.8 1.8 4.6 0 6.5l1 1c2.5-2.3 2.5-6.1 0-8.5zM18 9.8l-1 1c.5.7.5 1.6 0 2.3l1 1c1.2-1.2 1.2-3 0-4.3zM14 1H4c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 19H4V4h10v16z"/>
</SvgIcon>
);
CommunicationPhonelinkRing = pure(CommunicationPhonelinkRing);
CommunicationPhonelinkRing.displayName = 'CommunicationPhonelinkRing';
CommunicationPhonelinkRing.muiName = 'SvgIcon';
export default CommunicationPhonelinkRing;
|
src/containers/Manifesto.js | pjkarlik/ReactUI | import React from 'react';
const Manifesto = () => {
const content = (
<span>
<h2>Interface Research and Design</h2>
<p>
Sed quis mattis turpis. Ut vitae finibus sem. Donec scelerisque nec nisi non malesuada. Praesent mattis
lacus quis diam imperdiet rhoncus. Ut porta efficitur magna, quis pretium magna. Nam venenatis convallis
finibus. Nunc non mi tincidunt, luctus purus tempus.
<br/><br/>
Vitae dignissim ante est vel erat. Maecenas auctor dolor vitae egestas aliquam.
<br/><br/>
Morbi sed arcu vitae ligula porta gravida. Integer vel ex neque. Etiam quis elementum magna.
Duis nec tincidunt enim.
</p>
</span>
);
return content;
};
Manifesto.displayName = 'Manifesto';
export default Manifesto;
|
app/src/assets/js/components/global/player-hero.js | Huskie/ScottishPremiershipData | import React from 'react';
import { Link } from 'react-router';
import slugify from '../../modules/utilities/slugify';
class PlayerHeroComponent extends React.Component {
constructor (props) {
super(props);
}
render() {
let playerObject = this.props.player || {
birthDate: '',
club: '',
name: ''
};
const clubSlug = slugify(playerObject.club);
const imageSlug = slugify(playerObject.name + '-' + playerObject.birthDate);
const urlSlug = slugify(playerObject.name);
return (
<div className={"player-hero player-hero--" + clubSlug}>
<div className="container">
<h1 className="player-hero__title">{playerObject.squadNumber}. {playerObject.name}</h1>
<div className="player-hero__club-badge">
<Link className="player-hero__club-badge-link" to={"/clubs/" + clubSlug} title={playerObject.club + " club page"}>
<img alt={playerObject.club + " club badge"} className="player-hero__club-badge-image" src={"/assets/img/logos/scotland/" + clubSlug + ".png"} />
</Link>
</div>
</div>
</div>
)
}
}
PlayerHeroComponent.defaultProps = {};
PlayerHeroComponent.displayName = 'PlayerHeroComponent';
PlayerHeroComponent.propTypes = {};
export default PlayerHeroComponent; |
client/kit/entry/browser.js | Bartekus/FuseR | // Browser entry point, for Webpack. We'll grab the browser-flavoured
// versions of React mounting, routing etc to hook into the DOM
// ----------------------
// IMPORTS
// Enable async/await and generators, cross-browser
import 'regenerator-runtime/runtime';
// Patch global.`fetch` so that Apollo calls to GraphQL work
import 'isomorphic-fetch';
// React parts
import React from 'react';
import ReactDOM from 'react-dom';
// Browser routing
import { BrowserRouter } from 'react-router-dom';
// Apollo Provider. This HOC will 'wrap' our React component chain
// and handle injecting data down to any listening component
import { ApolloProvider } from 'react-apollo';
// Grab the shared Apollo Client
import { browserClient } from 'kit/lib/apollo';
// Custom redux store creator. This will allow us to create a store 'outside'
// of Apollo, so we can apply our own reducers and make use of the Redux dev
// tools in the browser
import createNewStore from 'kit/lib/redux';
// Root component. This is our 'entrypoint' into the app. If you're using
// the ReactQL starter kit for the first time, `src/app.js` is where
// you can start editing to add your own code
import App from 'src/app';
// ----------------------
// Create a new browser Apollo client
const client = browserClient();
// Create a new Redux store
const store = createNewStore(client);
// Create the 'root' entry point into the app. If we have React hot loading
// (i.e. if we're in development), then we'll wrap the whole thing in an
// <AppContainer>. Otherwise, we'll jump straight to the browser router
function doRender() {
ReactDOM.render(
<Root />,
document.getElementById('main'),
);
}
// The <Root> component. We'll run this as a self-contained function since
// we're using a bunch of temporary vars that we can safely discard.
//
// If we have hot reloading enabled (i.e. if we're in development), then
// we'll wrap the whole thing in <AppContainer> so that our views can respond
// to code changes as needed
const Root = (() => {
// Wrap the component hierarchy in <BrowserRouter>, so that our children
// can respond to route changes
const Chain = () => (
<ApolloProvider store={store} client={client}>
<BrowserRouter>
<App />
</BrowserRouter>
</ApolloProvider>
);
// React hot reloading -- only enabled in development. This branch will
// be shook from production, so we can run a `require` statement here
// without fear that it'll inflate the bundle size
if (module.hot) {
// <AppContainer> will respond to our Hot Module Reload (HMR) changes
// back from WebPack, and handle re-rendering the chain as needed
const AppContainer = require('react-hot-loader').AppContainer;
// Start our 'listener' at the root component, so that any changes that
// occur in the hierarchy can be captured
module.hot.accept('src/app', () => {
// Refresh the entry point of our app, to get the changes.
// eslint-disable-next-line
require('src/app').default;
// Re-render the hierarchy
doRender();
});
return () => (
<AppContainer>
<Chain />
</AppContainer>
);
}
return Chain;
})();
doRender();
|
src/routes/contact/index.js | arkeros/react-native-starter-kit | /**
* 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 Contact from './Contact';
const title = 'Contact Us';
export default {
path: '/contact',
action() {
return {
title,
component: <Contact title={title} />,
};
},
};
|
docs/app/Examples/collections/Menu/Content/MenuExampleDropdownItem.js | koenvg/Semantic-UI-React | import React from 'react'
import { Dropdown, Menu } from 'semantic-ui-react'
const MenuExampleDropdownItem = () => {
return (
<Menu vertical>
<Dropdown item text='Categories'>
<Dropdown.Menu>
<Dropdown.Item>Electronics</Dropdown.Item>
<Dropdown.Item>Automotive</Dropdown.Item>
<Dropdown.Item>Home</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</Menu>
)
}
export default MenuExampleDropdownItem
|
src/svg-icons/image/exposure-zero.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageExposureZero = (props) => (
<SvgIcon {...props}>
<path d="M16.14 12.5c0 1-.1 1.85-.3 2.55-.2.7-.48 1.27-.83 1.7-.36.44-.79.75-1.3.95-.51.2-1.07.3-1.7.3-.62 0-1.18-.1-1.69-.3-.51-.2-.95-.51-1.31-.95-.36-.44-.65-1.01-.85-1.7-.2-.7-.3-1.55-.3-2.55v-2.04c0-1 .1-1.85.3-2.55.2-.7.48-1.26.84-1.69.36-.43.8-.74 1.31-.93C10.81 5.1 11.38 5 12 5c.63 0 1.19.1 1.7.29.51.19.95.5 1.31.93.36.43.64.99.84 1.69.2.7.3 1.54.3 2.55v2.04zm-2.11-2.36c0-.64-.05-1.18-.13-1.62-.09-.44-.22-.79-.4-1.06-.17-.27-.39-.46-.64-.58-.25-.13-.54-.19-.86-.19-.32 0-.61.06-.86.18s-.47.31-.64.58c-.17.27-.31.62-.4 1.06s-.13.98-.13 1.62v2.67c0 .64.05 1.18.14 1.62.09.45.23.81.4 1.09s.39.48.64.61.54.19.87.19c.33 0 .62-.06.87-.19s.46-.33.63-.61c.17-.28.3-.64.39-1.09.09-.45.13-.99.13-1.62v-2.66z"/>
</SvgIcon>
);
ImageExposureZero = pure(ImageExposureZero);
ImageExposureZero.displayName = 'ImageExposureZero';
ImageExposureZero.muiName = 'SvgIcon';
export default ImageExposureZero;
|
index.ios.js | vineetha2438/react-native-horizontal-picker | import React, { Component } from 'react';
import { requireNativeComponent, Event } from 'react-native';
import _ from 'lodash';
import PropTypes from 'prop-types';
const RNTHorizontalPicker = requireNativeComponent('RNTHorizontalPicker', {
propTypes: {
titles: PropTypes.array,
selectedIndex: PropTypes.number
}
}, {
nativeOnly: {
onChange: true
}
});
export default class HorizontalPicker extends Component {
constructor (props) {
super(props);
}
convertToString(array) {
return _.map(array, (item) => {
return item.toString();
});
}
render() {
const {
onChange,
selectedIndex,
style,
titles
} = this.props;
return (
<RNTHorizontalPicker
selectedIndex={selectedIndex || 0}
style={style}
titles={this.convertToString(titles)}
onChange={onChange}
/>
);
}
}
HorizontalPicker.defaultProps = {
selectedIndex: 0,
style: { width: 150, height: 100 },
titles: [1, 2, 3, 4]
};
HorizontalPicker.propTypes = {
onChange: PropTypes.func.isRequired,
selectedIndex: PropTypes.number,
style: PropTypes.object,
titles: PropTypes.array.isRequired
};
|
src/pure/MonthSelector.react.js | vlad-doru/react-native-calendar-datepicker | /**
* MonthSelector pure component.
* @flow
*/
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import {
LayoutAnimation,
TouchableHighlight,
View,
Text,
StyleSheet,
} from 'react-native';
import ViewPropTypes from '../util/ViewPropTypes';
// Component specific libraries.
import _ from 'lodash';
import Moment from 'moment';
type Props = {
selected?: Moment,
// Styling
style?: ViewPropTypes.style,
// Controls the focus of the calendar.
focus: Moment,
onFocus?: (date: Moment) => void,
// Minimum and maximum valid dates.
minDate: Moment,
maxDate: Moment,
// Styling properties.
monthText?: Text.propTypes.style,
monthDisabledText?: Text.propTypes.style,
selectedText?: Text.propTypes.style,
};
type State = {
months: Array<Array<Object>>,
};
export default class MonthSelector extends Component {
props: Props;
state: State;
static defaultProps: Props;
constructor(props: Object) {
super(props);
const months = Moment.monthsShort();
let groups = [];
let group = [];
_.map(months, (month, index) => {
if (index % 3 === 0) {
group = [];
groups.push(group);
}
// Check if the month is valid.
let maxChoice = Moment(this.props.focus).month(index).endOf('month');
let minChoice = Moment(this.props.focus).month(index).startOf('month');
group.push({
valid: this.props.maxDate.diff(minChoice, 'seconds') >= 0 &&
this.props.minDate.diff(maxChoice, 'seconds') <= 0,
name: month,
index,
});
})
this.state = {
months: groups,
};
}
_onFocus = (index : number) : void => {
let focus = Moment(this.props.focus);
focus.month(index);
this.props.onFocus && this.props.onFocus(focus);
}
render() {
return (
<View style={[{
// Wrapper view default style.
},this.props.style]}>
{_.map(this.state.months, (group, i) =>
<View key={i} style={[styles.group]}>
{_.map(group, (month, j) =>
<TouchableHighlight
key={j}
style={{flexGrow: 1}}
activeOpacity={1}
underlayColor='transparent'
onPress={() => month.valid && this._onFocus(month.index)}>
<Text style={[
styles.monthText,
this.props.monthText,
month.valid ? null : styles.disabledText,
month.valid ? null : this.props.monthDisabledText,
month.index === (this.props.selected && this.props.selected.month()) ? this.props.selectedText : null,
]}>
{month.name}
</Text>
</TouchableHighlight>
)}
</View>
)}
</View>
);
}
}
MonthSelector.defaultProps = {
focus: Moment(),
minDate: Moment(),
maxDate: Moment(),
};
const styles = StyleSheet.create({
group: {
//flexGrow: 1,
flexDirection: 'row',
},
disabledText: {
borderColor: 'grey',
color: 'grey',
},
monthText: {
borderRadius: 5,
borderWidth: 1,
flexGrow: 1,
margin: 5,
padding: 10,
textAlign: 'center',
},
});
|
modules/Link.js | bmathews/react-router | import React from 'react';
var { object, string, func } = React.PropTypes;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
/**
* <Link> components are used to create an <a> element that links to a route.
* When that route is active, the link gets an "active" class name (or the
* value of its `activeClassName` prop).
*
* For example, assuming you have the following route:
*
* <Route name="showPost" path="/posts/:postID" handler={Post}/>
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along query string parameters
* using the `query` prop.
*
* <Link to="/posts/123" query={{ show:true }}/>
*/
export var Link = React.createClass({
contextTypes: {
router: object
},
propTypes: {
activeStyle: object,
activeClassName: string,
to: string.isRequired,
query: object,
state: object,
onClick: func
},
getDefaultProps() {
return {
className: '',
activeClassName: 'active',
style: {}
};
},
handleClick(event) {
var allowTransition = true;
var clickResult;
if (this.props.onClick)
clickResult = this.props.onClick(event);
if (isModifiedEvent(event) || !isLeftClickEvent(event))
return;
if (clickResult === false || event.defaultPrevented === true)
allowTransition = false;
event.preventDefault();
if (allowTransition)
this.context.router.transitionTo(this.props.to, this.props.query, this.props.state);
},
render() {
var { router } = this.context;
var { to, query } = this.props;
var props = Object.assign({}, this.props, {
href: router.makeHref(to, query),
onClick: this.handleClick
});
// ignore if rendered outside of the context of a router, simplifies unit testing
if (router && router.isActive(to, query)) {
if (props.activeClassName)
props.className += props.className !== '' ? ` ${props.activeClassName}` : props.activeClassName;
if (props.activeStyle)
props.style = Object.assign({}, props.style, props.activeStyle);
}
return React.createElement('a', props);
}
});
export default Link;
|
react/src/components/HelloText.js | thoughtbit/webpack-bucket | // Import React and JS
import React, { Component } from 'react';
import { render } from 'react-dom';
// Create class called HelloText that extends the base React Component class
export default class HelloText extends Component {
constructor(props) {
super(props);
}
render() {
return <p>你好, {this.props.name}!</p>;
}
}
|
server/server.js | inCodeSystemsNsk/frontend-boilerplate | /* eslint-disable no-console, no-use-before-define */
import Express from 'express'
import serialize from 'serialize-javascript'
import cookie from 'cookie-parser'
import body from 'body-parser'
import jwt from 'express-jwt'
import jsonwebtoken from 'jsonwebtoken' // using in demo auth route only
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import webpackConfig from '../webpack.config'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import { createMemoryHistory, match, RouterContext } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import Helmet from 'react-helmet'
import routes from '../shared/routes'
import { configureStore } from '../shared/store/configureStore'
import fetchComponentData from '../shared/lib/fetchComponentData'
import { login } from '../shared/actions/user'
import config from './config'
const app = new Express()
const port = config.server.port
app.use(cookie())
app.use(jwt({
secret: config.auth.JWT_SECRET,
credentialsRequired: false,
getToken: (req) => {
let token = null
if (req.cookies && req.cookies.token) {
token = req.cookies.token
} else if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
token = req.headers.authorization.split(' ')[1]
} else if (req.query && req.query.token) {
token = req.query.token
}
req.token = token
return token
}
}))
// Use this middleware to set up hot module reloading via webpack.
const compiler = webpack(webpackConfig)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }))
app.use(webpackHotMiddleware(compiler))
// Demo auth route
app.post('/login', body.json(), (req, res) => {
let id = Math.round(Math.random() * 10000)
let user = {
id,
email: req.body.email
}
let token = jsonwebtoken.sign(user, config.auth.JWT_SECRET)
res.json({ ...user, token })
})
const HTML = ({ content, store, head }) => {
return (
<html>
<head>
{head.title.toComponent()}
{head.meta.toComponent()}
{head.link.toComponent()}
</head>
<body>
<div id="root" dangerouslySetInnerHTML={{ __html: content }}/>
<div id="devtools"/>
<script dangerouslySetInnerHTML={{ __html: `window.__initialState__=${serialize(store.getState())};` }}/>
<script src="/static/bundle.js"/>
</body>
</html>
)
}
app.use(function (req, res) {
const memoryHistory = createMemoryHistory(req.url)
const store = configureStore(memoryHistory)
const history = syncHistoryWithStore(memoryHistory, store)
if (req.user) {
store.dispatch(login({ ...req.user, token: req.token }))
}
match({ history, routes, location: req.url }, (error, redirectLocation, renderProps) => {
fetchComponentData(store.dispatch, renderProps.components, renderProps.params)
.then(() => {
if (error) {
res.status(500).send(error.message)
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
const content = renderToString(
<Provider store={store}>
<RouterContext {...renderProps}/>
</Provider>
)
let head = Helmet.rewind()
res.send('<!doctype html>\n' +
renderToString(<HTML content={content} store={store} head={head}/>))
}
})
.catch((error) => {
res.status(500).send(error.message)
})
})
})
app.listen(port, (error) => {
if (error) {
console.error(error)
} else {
console.info(`Listening on port ${port}`)
}
})
|
src/main.js | garrettmurphy/cromag | import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import thunk from 'redux-thunk';
import { Router, Route, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import { syncHistoryWithStore } from 'react-router-redux';
import { configureCounterStore } from './store';
import { NotFound } from './pages/404';
import { About } from './pages/about';
import { App } from './pages/app';
export function init() {
const store = configureCounterStore({ counter: 0 }, thunk);
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App} />
<Route path="/yo" component={App} />
<Route path="/about" component={About} />
<Route path="*" component={NotFound} />
</Router>
</Provider>
, document.getElementById('app'));
}
|
gh/components/AutoPlayCarousel.js | bitriddler/react-items-carousel | import React from 'react';
import range from 'lodash/range';
import styled from 'styled-components';
import ItemsCarousel from '../../src/ItemsCarousel';
const noOfItems = 12;
const noOfCards = 3;
const autoPlayDelay = 2000;
const chevronWidth = 40;
const Wrapper = styled.div`
padding: 0 ${chevronWidth}px;
max-width: 1000px;
margin: 0 auto;
`;
const SlideItem = styled.div`
height: 200px;
background: #EEE;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
font-weight: bold;
`;
const carouselItems = range(noOfItems).map(index => (
<SlideItem key={index}>
{index+1}
</SlideItem>
));
export default class AutoPlayCarousel extends React.Component {
state = {
activeItemIndex: 0,
};
componentDidMount() {
this.interval = setInterval(this.tick, autoPlayDelay);
}
componentWillUnmount() {
clearInterval(this.interval);
}
tick = () => this.setState(prevState => ({
activeItemIndex: (prevState.activeItemIndex + 1) % (noOfItems-noOfCards + 1),
}));
onChange = value => this.setState({ activeItemIndex: value });
render() {
return (
<Wrapper>
<ItemsCarousel
gutter={12}
numberOfCards={noOfCards}
activeItemIndex={this.state.activeItemIndex}
requestToChangeActive={this.onChange}
rightChevron={<button>{'>'}</button>}
leftChevron={<button>{'<'}</button>}
chevronWidth={chevronWidth}
outsideChevron
children={carouselItems}
/>
</Wrapper>
);
}
}
|
js/Header.js | adamki/Reactv2-2017 | import React from 'react'
import { connect } from 'react-redux'
import { setSearchTerm } from './actionCreators'
import { Link } from 'react-router'
class Header extends React.Component {
constructor (props) {
super(props)
this.handleSearchTermChange = this.handleSearchTermChange.bind(this)
}
handleSearchTermChange (e) {
this.props.dispatch(setSearchTerm(e.target.value))
}
render () {
let utilSpace
if (this.props.showSearch) {
utilSpace = (
<input
type='text'
placeholder='search'
value={this.props.searchTerm}
onChange={this.handleSearchTermChange}
/>
)
} else {
utilSpace = (
<h2>
<Link to='/search'>
Back
</Link>
</h2>
)
}
return (
<header>
<h1>
<Link to='/'>
sVideo
</Link>
</h1>
{utilSpace}
</header>
)
}
}
const {func, bool, string} = React.PropTypes
Header.propTypes = {
dispatch: func,
showSearch: bool,
searchTerm: string
}
const mapStateToProps = (state) => {
return {
searchTerm: state.searchTerm
}
}
export default connect(mapStateToProps)(Header)
|
app/javascript/mastodon/features/notifications/components/setting_toggle.js | mimumemo/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
export default class SettingToggle extends React.PureComponent {
static propTypes = {
prefix: PropTypes.string,
settings: ImmutablePropTypes.map.isRequired,
settingPath: PropTypes.array.isRequired,
label: PropTypes.node.isRequired,
onChange: PropTypes.func.isRequired,
}
onChange = ({ target }) => {
this.props.onChange(this.props.settingPath, target.checked);
}
render () {
const { prefix, settings, settingPath, label } = this.props;
const id = ['setting-toggle', prefix, ...settingPath].filter(Boolean).join('-');
return (
<div className='setting-toggle'>
<Toggle id={id} checked={settings.getIn(settingPath)} onChange={this.onChange} onKeyDown={this.onKeyDown} />
<label htmlFor={id} className='setting-toggle__label'>{label}</label>
</div>
);
}
}
|
admin/client/components/Popout/PopoutListHeading.js | andreufirefly/keystone | import React from 'react';
import blacklist from 'blacklist';
import classnames from 'classnames';
var PopoutListHeading = React.createClass({
displayName: 'PopoutListHeading',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
},
render () {
const className = classnames('PopoutList__heading', this.props.className);
const props = blacklist(this.props, 'className');
return <div className={className} {...props} />;
},
});
module.exports = PopoutListHeading;
|
src/AppBundle/Resources/static/jsx/util/form/InputMultiSelect.js | viszerale-therapie/simple-courses | import React from 'react';
import tl from '../translator';
import InputDefault from './InputDefault';
import InputLabel from './InputLabel';
export default class InputMultiSelect extends InputDefault {
constructor(props) {
super(props);
this.state = {
value: { },
error: false
};
}
/**
* Function to
*
* @param {Event} e
* @param {string} key the component of the multi value, either 'currencyCode' or 'value'
*/
handleChange(key, e){
let value = this.state.value;
value[key] = e.target.checked ? 1 : 0;
this.setValue(value);
}
render() {
let formfield = this.props.fieldDef,
formIdent = this.props.formIdent,
that = this
;
if (! formfield.options) formfield.options = [];
let options = formfield.options.map(function (option) {
if (option.key) {
let key = formIdent + '-' + option.key;
return <div className="form-group" key={key}>
<input checked={ that.state.value[option.key] ? true : false } type="checkbox" onChange={that.handleChange.bind(that, option.key)} className="form-control checkbox" value={option.key} name={key} id={option.key} />
<label htmlFor={option.key}>{option.label}</label>
</div>;
}
});
let errorElem = this.state.error ? <div className="alert alert-danger">{tl.t('global.form.error.required')}</div> : null;
return <div className={"form-group" + (this.state.error ? ' has-error' : '')} id={formIdent + '-wrp'}>
<InputLabel fieldDef={formfield} currentLocale={this.props.currentLocale} formIdent={formIdent} />
<div ref="input" id={formIdent} className="entity-display multi_select-form">
{options}
</div>
{errorElem}
</div>;
}
}; |
src/components/chart.js | brunobc182/weather-in-the-city-react-redux | import _ from 'lodash'
import React from 'react';
import {Sparklines, SparklinesLine, SparklinesReferenceLine} from 'react-sparklines';
function average(data){
return _.round(_.sum(data)/data.length);
}
export default(props) => {
return (
<div>
<Sparklines height={120} width={180} data={props.data}>
<SparklinesLine color={props.color}/>
<SparklinesReferenceLine type="avg"/>
</Sparklines>
<div>
Average: {average(props.data)}{props.units}
</div>
</div>
);
} |
src/components/Controls.js | CharmedSatyr/game_of_life | import React, { Component } from 'react';
import PropTypes from 'prop-types';
// Font Awesome
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
faPause,
faPlay,
faRandom,
faStepForward,
faTimes,
} from '@fortawesome/free-solid-svg-icons';
library.add(faPause, faPlay, faRandom, faStepForward, faTimes);
// Controls
export default class Controls extends Component {
constructor(props) {
super(props);
this.state = { selected: null };
}
clear = () => {
if (this.state.selected !== 'clear') {
cancelAnimationFrame(this.requestID);
this.props.clear();
this.setState({ selected: 'clear' });
}
};
pause = () => {
if (
this.state.selected !== 'clear' &&
this.state.selected !== 'pause' &&
this.state.selected !== 'random'
) {
cancelAnimationFrame(this.requestID);
this.setState({ selected: 'pause' });
}
};
play = () => {
this.props.nextGen();
this.requestID = requestAnimationFrame(this.play);
this.setState({ selected: 'play' });
};
random = () => {
cancelAnimationFrame(this.requestID);
this.props.makeGrid();
this.setState({ selected: 'random' });
};
step = () => {
if (this.state.selected !== 'play') {
this.props.nextGen();
}
};
componentDidMount() {
this.play();
}
render() {
const { selected } = this.state;
return (
<div className="controls">
{/* STEP */}
<button className={`step ${selected === 'play' ? 'disabled' : ''}`} onClick={this.step}>
<FontAwesomeIcon icon="step-forward" />
Step
</button>
{/* PLAY */}
<button
className={`play ${selected === 'play' ? 'selected disabled' : ''}`}
onClick={selected !== 'play' ? this.play : null}
>
<FontAwesomeIcon icon="play" />
Play
</button>
{/* PAUSE */}
<button
className={`pause ${selected === 'pause' ? 'selected disabled' : ''} ${
selected !== 'play' ? 'disabled' : ''
}`}
onClick={this.pause}
>
<FontAwesomeIcon icon="pause" />
Pause
</button>
{/* CLEAR */}
<button
className={`clear ${selected === 'clear' ? 'selected disabled' : ''}`}
onClick={this.clear}
>
<FontAwesomeIcon icon="times" />
Clear
</button>
{/* RANDOM */}
<button
className={`random ${selected === 'random' ? 'selected' : ''}`}
onClick={this.random}
>
<FontAwesomeIcon icon="random" />
Random
</button>
</div>
);
}
}
Controls.propTypes = {
clear: PropTypes.func.isRequired,
makeGrid: PropTypes.func.isRequired,
nextGen: PropTypes.func.isRequired,
};
|
docs/app/Examples/elements/Reveal/States/index.js | mohammed88/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const RevealStatesExamples = () => (
<ExampleSection title='States'>
<ComponentExample
title='Active'
description='An active reveal displays its hidden content.'
examplePath='elements/Reveal/States/RevealExampleActive'
/>
<ComponentExample
title='Disabled'
description='A disabled reveal will not animate when hovered.'
examplePath='elements/Reveal/States/RevealExampleDisabled'
/>
</ExampleSection>
)
export default RevealStatesExamples
|
examples/real-world/routes.js | andreieftimie/redux | import React from 'react';
import { Route } from 'react-router';
import App from './containers/App';
import UserPage from './containers/UserPage';
import RepoPage from './containers/RepoPage';
export default (
<Route path="/" component={App}>
<Route path="/:login/:name"
component={RepoPage} />
<Route path="/:login"
component={UserPage} />
</Route>
);
|
src/parser/warrior/arms/modules/features/RageDetails.js | fyruna/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import Panel from 'interface/others/Panel';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import { formatPercentage } from 'common/format';
import Icon from 'common/Icon';
import ResourceBreakdown from 'parser/shared/modules/resourcetracker/ResourceBreakdown';
import RageTracker from './RageTracker';
class RageDetails extends Analyzer {
static dependencies = {
rageTracker: RageTracker,
};
get wastedPercent() {
return (this.rageTracker.wasted / (this.rageTracker.wasted + this.rageTracker.generated) || 0);
}
get efficiencySuggestionThresholds() {
return {
actual: 1 - this.wastedPercent,
isLessThan: {
minor: 0.95,
average: 0.90,
major: .85,
},
style: 'percentage',
};
}
get suggestionThresholds() {
return {
actual: this.wastedPercent,
isGreaterThan: {
minor: 0.05,
average: 0.1,
major: .15,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(`You wasted ${formatPercentage(this.wastedPercent)}% of your Rage.`)
.icon('spell_nature_reincarnation')
.actual(`${formatPercentage(actual)}% wasted`)
.recommended(`<${formatPercentage(recommended)}% is recommended`);
});
}
statistic() {
return (
<StatisticBox
position={STATISTIC_ORDER.CORE(5)}
icon={<Icon icon="spell_nature_reincarnation" />}
value={`${formatPercentage(this.wastedPercent)} %`}
label="Rage wasted"
tooltip={`${this.rageTracker.wasted} out of ${this.rageTracker.wasted + this.rageTracker.generated} rage wasted.`}
/>
);
}
tab() {
return {
title: 'Rage usage',
url: 'rage-usage',
render: () => (
<Panel>
<ResourceBreakdown
tracker={this.rageTracker}
showSpenders
/>
</Panel>
),
};
}
}
export default RageDetails;
|
stories/Grid.stories.js | react-materialize/react-materialize | import React from 'react';
import { storiesOf } from '@storybook/react';
import Row from '../src/Row';
import Col from '../src/Col';
const stories = storiesOf('CSS/Grid', module);
stories.addParameters({
info: {
text: `We are using a standard 12 column
fluid responsive grid system. The grid helps
you layout your page in an ordered, easy fashion.`
}
});
stories.add('default', () => (
<Row>
<Col s={1} className="teal white-text">
1
</Col>
<Col s={1} className="teal white-text">
2
</Col>
<Col s={1} className="teal white-text">
3
</Col>
<Col s={1} className="teal white-text">
4
</Col>
<Col s={1} className="teal white-text">
5
</Col>
<Col s={1} className="teal white-text">
6
</Col>
<Col s={1} className="teal white-text">
7
</Col>
<Col s={1} className="teal white-text">
8
</Col>
<Col s={1} className="teal white-text">
9
</Col>
<Col s={1} className="teal white-text">
10
</Col>
<Col s={1} className="teal white-text">
11
</Col>
<Col s={1} className="teal white-text">
12
</Col>
</Row>
));
|
src/index.js | nikunjagarwal1/react-make-notes | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
.storybook/mocks/providers.js | iiet/iiet-chat | import i18next from 'i18next';
import React from 'react';
import { TranslationContext } from '../../client/contexts/TranslationContext';
let contextValue;
const getContextValue = () => {
if (contextValue) {
return contextValue;
}
i18next.init({
fallbackLng: 'en',
defaultNS: 'project',
resources: {
en: {
project: require('../../packages/rocketchat-i18n/i18n/en.i18n.json'),
},
},
interpolation: {
prefix: '__',
suffix: '__',
},
initImmediate: false,
});
const translate = (key, ...replaces) => {
if (typeof replaces[0] === 'object') {
const [options] = replaces;
return i18next.t(key, options);
}
if (replaces.length === 0) {
return i18next.t(key);
}
return i18next.t(key, {
postProcess: 'sprintf',
sprintf: replaces,
});
};
translate.has = (key) => key && i18next.exists(key);
contextValue = {
languages: [{
name: 'English',
en: 'English',
key: 'en',
}],
language: 'en',
translate,
};
return contextValue;
};
function TranslationProviderMock({ children }) {
return <TranslationContext.Provider children={children} value={getContextValue()} />;
}
export function MeteorProviderMock({ children }) {
return <TranslationProviderMock>
{children}
</TranslationProviderMock>;
}
|
packages/components/src/List/Toolbar/ColumnChooserButton/ColumnChooser/ColumnChooser.stories.js | Talend/ui | import React from 'react';
import { action } from '@storybook/addon-actions';
import ColumnChooser from './ColumnChooser.component';
const columns = [
{ key: 'id', label: 'Id', order: 1 },
{ key: 'name', label: 'Name', order: 2 },
{ key: 'author', label: 'Author', order: 3 },
{ key: 'created', label: 'Created', order: 6 },
{
key: 'modified',
label: 'Very long name long name long name long name long name',
order: 4,
header: 'icon',
data: { iconName: 'talend-scheduler' },
},
{ key: 'icon', label: 'Icon', hidden: true, order: 5, locked: true },
];
export default {
title: 'Data/List/Column Chooser',
};
export const Default = () => (
<div>
<h1>Column chooser tooltip</h1>
<p>Default mode with minimal props</p>
<ColumnChooser
columnsFromList={columns}
nbLockedLeftItems={2}
id="default-column-chooser"
onSubmit={action('submit')}
/>
</div>
);
export const CustomizeColumnChooser = () => (
<div>
<h1>Column chooser tooltip</h1>
<p>You can provide and compose some of the column chooser part.</p>
<ColumnChooser
columnsFromList={columns}
id="default-column-chooser"
onSubmit={action('submit')}
>
<ColumnChooser.Header>
<span>Hello world</span>
<button style={{ marginLeft: '200px' }}>My Button</button>
</ColumnChooser.Header>
<ColumnChooser.Body>
{myBodyColumns =>
myBodyColumns.map(column => (
<div key={column.label}>
<ColumnChooser.Body.Row>
<ColumnChooser.Body.Row.Label label={column.label} />
<button
style={{ marginLeft: '20px', display: 'flex', height: '50%' }}
onClick={action('my custom action')}
>
Action
</button>
</ColumnChooser.Body.Row>
</div>
))
}
</ColumnChooser.Body>
<ColumnChooser.Footer />
</ColumnChooser>
</div>
);
|
client/app/containers/Login/Login.js | krouw/T.SIA-electron-blueprint | // @flow
import React, { Component } from 'react';
import {Row, Col} from 'react-flexbox-grid';
import SigninForm from '../../components/SigninForm/SigninForm'
import LogoImg from '../../logo.png';
import { loginServer } from '../../actions/auth'
import { addToast } from '../../actions/Toasts'
import { connect } from 'react-redux'
class Login extends Component {
render() {
const { loginServer, addToast } = this.props;
return (
<Row center="xs" middle="xs" style={{margin:0}}>
<Col xs={10} sm={6} md={4}>
<div className="Login-Card pt-card pt-elevation-1">
<div className="Login-Logo">
<img src={LogoImg} />
</div>
<Row className="Login-Form" center="xs">
<Col xs={12}>
<SigninForm
loginServer={loginServer}
addToast={addToast}
/>
</Col>
</Row>
</div>
</Col>
</Row>
);
}
}
Login.propTypes = {
loginServer: React.PropTypes.func.isRequired,
addToast: React.PropTypes.func.isRequired,
};
export default connect(null,{ loginServer, addToast })(Login);
|
source/client/components/todos/AddTodoButton.js | flipace/lovli.js | import React from 'react';
import { subscribe } from 'horizon-react';
import { createDoc } from 'horizon-react/lib/utils';
import styles from './styles';
const AddTodoButton = (props) => {
const collection = props.horizon('todos');
const addTodo = (t) => createDoc(collection, { text: t });
return (
<div>
<input
id="todo-text"
className={styles.input}
type="text"
placeholder="A new todo item..."
autoFocus
onKeyPress={function(e) { if (e.key === 'Enter') { addTodo(e.target.value); e.target.value = ''; } }}
/>
<div
className={styles.button}
onClick={() => { addTodo(document.getElementById('todo-text').value); document.getElementById('todo-text').value = ''; }}
>
+ Add todo
</div>
</div>
);
};
export default subscribe()(AddTodoButton);
|
webpack/containers/sections/SectionEditContainer.js | CDCgov/SDP-Vocabulary-Service | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { denormalize } from 'normalizr';
import { Button, Grid, Row, Col } from 'react-bootstrap';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import keyBy from 'lodash/keyBy';
import { sectionSchema } from '../../schema';
import { setSteps } from '../../actions/tutorial_actions';
import { setStats } from '../../actions/landing';
import { fetchSection, saveSection, newSection, saveDraftSection, addNestedItem, removeNestedItem, reorderNestedItem } from '../../actions/section_actions';
import { fetchQuestion } from '../../actions/questions_actions';
import SectionEdit from '../../components/sections/SectionEdit';
import ResponseSetModal from '../response_sets/ResponseSetModal';
import QuestionModalContainer from '../questions/QuestionModalContainer';
import SectionEditSearchContainer from '../sections/SectionEditSearchContainer';
import { sectionProps, sectionsProps } from '../../prop-types/section_props';
import { questionsProps } from '../../prop-types/question_props';
import { responseSetsProps } from '../../prop-types/response_set_props';
import LoadingSpinner from '../../components/LoadingSpinner';
import BasicAlert from '../../components/BasicAlert';
import InfoModal from '../../components/InfoModal';
class SectionEditContainer extends Component {
constructor(props) {
super(props);
let selectedSectionSaver = this.props.saveSection;
if (this.props.params.sectionId) {
this.props.fetchSection(this.props.params.sectionId);
if (this.props.params.action === 'edit') {
selectedSectionSaver = this.props.saveDraftSection;
}
} else {
this.props.newSection();
this.props.params.sectionId = 0;
this.props.params.action = 'new';
}
this.state = {selectedSectionSaver: selectedSectionSaver, showQuestionModal: false, showResponseSetModal: false};
this.showQuestionModal = this.showQuestionModal.bind(this);
this.closeQuestionModal = this.closeQuestionModal.bind(this);
this.showResponseSetModal = this.showResponseSetModal.bind(this);
this.closeResponseSetModal = this.closeResponseSetModal.bind(this);
this.handleSelectSearchResult = this.handleSelectSearchResult.bind(this);
this.handleSaveQuestionSuccess = this.handleSaveQuestionSuccess.bind(this);
}
componentDidMount() {
this.props.setSteps([
{
title: 'Help',
text: 'Click next to see a step by step walkthrough for using this page. To see more detailed information about this application and actions you can take <a class="tutorial-link" href="#help">click here to view the full Help Documentation.</a> Accessible versions of these steps are also duplicated in the help documentation.',
selector: '.help-link',
position: 'bottom',
},
{
title: 'Author Question For Section',
text: 'If you need to create a new question without leaving the the section use this button to author a new question from scratch.',
selector: '.add-question',
position: 'right',
},
{
title: 'Search',
text: 'Type in your search keywords here to search for questions or nested sections to add to the section.',
selector: '.search-input',
position: 'bottom',
},
{
title: 'Advanced Search Filters',
text: 'Click Advanced to see additional filters you can apply to your search.',
selector: '.search-group',
position: 'right',
},
{
title: 'Search Result',
text: 'Use these search results to find the question or nested section you want to add.',
selector: '.u-result',
position: 'right',
},
{
title: 'Add Item',
text: 'Click on the add (+) button to select an item for the section.',
selector: '.fa-plus-square',
position: 'bottom',
},
{
title: 'Section Details',
text: 'Edit the various section details on the right side of the page. Select save in the top right of the page when done editing to save a private draft of the content (this content will not be public until it is published).',
selector: '.section-edit-details',
position: 'left',
},
{
title: 'Code System Mappings Table',
text: 'Click the info (i) icon, or <a class="tutorial-link" href="#help">go to the full help documentation</a> to see more information and examples on how to get the most out of mappings.',
selector: '.code-system-mappings-table-header',
position: 'left',
}]);
}
componentDidUpdate(prevProps) {
if(this.props.params.sectionId && prevProps.params.sectionId != this.props.params.sectionId){
this.props.fetchSection(this.props.params.sectionId);
}
if(this.props.section && this.props.section.sectionNestedItems) {
this.refs.section.updateSectionNestedItems(this.props.section.sectionNestedItems);
}
}
showQuestionModal(){
this.setState({showQuestionModal: true});
}
closeQuestionModal(){
this.setState({showQuestionModal: false});
}
showResponseSetModal(){
this.setState({showResponseSetModal: true});
}
closeResponseSetModal(){
this.setState({showResponseSetModal: false});
}
handleSaveQuestionSuccess(successResponse){
this.setState({showQuestionModal: false});
this.props.fetchQuestion(successResponse.data.id);
this.props.addNestedItem(this.props.section, successResponse.data);
}
handleSelectSearchResult(sni, type){
this.props.addNestedItem(this.props.section, sni, type);
}
actionWord() {
const wordMap = {'new': 'Create', 'revise': 'Revise', 'extend': 'Extend', 'edit': 'Edit'};
return wordMap[this.props.params.action || 'new'];
}
render() {
if(!this.props.section || !this.props.questions || !this.props.sections || this.props.isLoading || this.props.loadStatus == 'failure'){
return (
<Grid className="basic-bg">
<Row>
<Col xs={12}>
{this.props.isLoading && <LoadingSpinner msg="Loading section..." />}
{this.props.loadStatus == 'failure' &&
<BasicAlert msg={this.props.loadStatusText} severity='danger' />
}
{this.props.loadStatus == 'success' &&
<BasicAlert msg="Sorry, there is a problem loading this section." severity='warning' />
}
</Col>
</Row>
</Grid>
);
}
return (
<Grid className="section-edit-container">
<QuestionModalContainer route ={this.props.route}
router={this.props.router}
showModal={this.state.showQuestionModal}
closeQuestionModal ={this.closeQuestionModal}
handleSaveQuestionSuccess={this.handleSaveQuestionSuccess} />
<ResponseSetModal show={this.state.showResponseSetModal}
router={this.props.router}
closeModal={this.closeResponseSetModal}
saveResponseSetSuccess={this.closeResponseSetModal} />
<Row>
<div className="panel panel-default">
<div className="panel-heading">
<h1 className="panel-title">{`${this.actionWord()} Section`}</h1>
</div>
<Row className="panel-body">
<Col md={5}>
<div className="add-question">
<InfoModal show={this.state.showInfoAddNewQuestion} header="Add New Question" body={<p>After searching the service, if no suitable Questions are found, a user can create a new Question and add it to the Section directly from this page.</p>} hideInfo={()=>this.setState({showInfoAddNewQuestion: false})} />
<Button onClick={this.showQuestionModal} bsStyle="primary">Add New Question</Button>
<Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoAddNewQuestion: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button>
</div>
<InfoModal show={this.state.showInfoSearchAndSelectQuestionsOrSections} header="Search and Select Questions or Sections" body={<p>Search through existing Questions and Sections in the system to identify the content that composes this Section. A section is a grouping of related questions intended to appear together on a data collection instrument.
<br/><br/><u>Adding Questions</u>: Existing Questions in the repository can be searched from the “Questions” tab. To select a specific Question, click the blue “+” button. Once added, the “+” sign will change into a checkmark to indicate the Question will be added to this Section after save.
<br/><br/><u>Adding Sub-Sections</u>: A Section may also contain one or more Sections (e.g., sub-Sections or nested Sections) to show how questions are related to one another. For instance, a “Symptom” section, that contains a group of symptom-related questions, and a “Diagnosis” section, which contains a group of diagnosis-related questions, may be added to a “Clinical” section since both symptom and diagnosis questions provide clinical information.
<br/><br/>Existing Sections in the repository can be searched from the “Sections” tab. To select a specific Section, click the blue “+” button. Once added, the “+” sign will change into a checkmark to indicate the selected Section will be added to the Section after save.</p>} hideInfo={()=>this.setState({showInfoSearchAndSelectQuestionsOrSections: false})} />
<label htmlFor="searchAndSelectQuestionsOrSections">Search and Select Questions or Sections<Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoSearchAndSelectQuestionsOrSections: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button></label>
<SectionEditSearchContainer selectedQuestions={this.props.selectedQuestions}
selectedSections={this.props.selectedSections}
sectionId={this.props.section.id}
handleSelectSearchResult={this.handleSelectSearchResult} />
</Col>
<SectionEdit ref ='section'
section={this.props.section}
route ={this.props.route}
router={this.props.router}
stats={this.props.stats}
setStats={this.props.setStats}
action={this.props.params.action || 'new'}
questions={this.props.questions}
responseSets ={this.props.responseSets}
sections={this.props.sections}
sectionSubmitter={this.state.selectedSectionSaver}
removeNestedItem={this.props.removeNestedItem}
reorderNestedItem={this.props.reorderNestedItem}
showResponseSetModal={this.showResponseSetModal} />
</Row>
</div>
</Row>
</Grid>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({setSteps, addNestedItem, fetchQuestion,
newSection, fetchSection, removeNestedItem, reorderNestedItem, setStats,
saveSection, saveDraftSection}, dispatch);
}
function mapStateToProps(state, ownProps) {
const section = denormalize(state.sections[ownProps.params.sectionId || 0], sectionSchema, state);
var selectedQuestions = {};
var selectedSections = {};
if(section && section.sectionNestedItems){
section.sectionNestedItems.map((sni)=>{
if (sni.questionId) {
selectedQuestions[sni.questionId] = true;
} else {
selectedSections[sni.nestedSectionId] = true;
}
});
}
let nestedSections = {};
if (section && section.nestedSections) {
nestedSections = keyBy(section.nestedSections, 'id');
}
const sections = Object.assign({}, state.sections, nestedSections);
return {
section: section,
questions: state.questions,
responseSets: state.responseSets,
sections: sections,
stats: state.stats,
selectedQuestions: selectedQuestions,
selectedSections: selectedSections,
isLoading : state.ajaxStatus.section.isLoading,
loadStatus : state.ajaxStatus.section.loadStatus,
loadStatusText : state.ajaxStatus.section.loadStatusText
};
}
SectionEditContainer.propTypes = {
section: sectionProps,
route: PropTypes.object.isRequired,
router: PropTypes.object.isRequired,
params: PropTypes.object.isRequired,
questions: questionsProps,
responseSets: responseSetsProps,
sections: sectionsProps,
setSteps: PropTypes.func,
setStats: PropTypes.func,
stats: PropTypes.object,
newSection: PropTypes.func,
saveSection: PropTypes.func,
fetchSection: PropTypes.func,
isLoading: PropTypes.bool,
loadStatus : PropTypes.string,
loadStatusText : PropTypes.string,
addNestedItem: PropTypes.func,
saveDraftSection: PropTypes.func,
fetchQuestion: PropTypes.func,
removeNestedItem: PropTypes.func,
reorderNestedItem: PropTypes.func,
selectedQuestions: PropTypes.object,
selectedSections: PropTypes.object
};
export default connect(mapStateToProps, mapDispatchToProps)(SectionEditContainer);
|
src/index.js | danielmoll/component-win-articlepage | import React from 'react';
import VariantArticle from './variant-article';
export default function WorldInArticle(rest) {
return (
<VariantArticle
{...rest}
/>
);
}
WorldInArticle.defaultProps = {
scrollToOffset: 100,
};
if (process.env.NODE_ENV !== 'production') {
WorldInArticle.propTypes = {
sectionName: React.PropTypes.string,
content: React.PropTypes.arrayOf(React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.object ])),
advert: React.PropTypes.shape({
adTag: React.PropTypes.string,
reserveHeight: React.PropTypes.number,
}),
scrollToOffset: React.PropTypes.number,
};
}
|
src/svg-icons/file/cloud.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let FileCloud = (props) => (
<SvgIcon {...props}>
<path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96z"/>
</SvgIcon>
);
FileCloud = pure(FileCloud);
FileCloud.displayName = 'FileCloud';
FileCloud.muiName = 'SvgIcon';
export default FileCloud;
|
webpack/containers/sections/SectionNestedItemList.js | CDCgov/SDP-Vocabulary-Service | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';
import shallowCompare from 'react-addons-shallow-compare';
import SearchResult from '../../components/SearchResult';
import { updatePDV } from "../../actions/section_actions";
class SectionNestedItemList extends Component {
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
render() {
if(!this.props.items){
return (
<div>Loading...</div>
);
}
return (
<div className="question-group">
{this.props.items.map((sni, i) => {
let sniType = sni.content ? 'question' : 'section';
return <SearchResult key={i} resultStyle={this.props.resultStyle} type={sniType} result={{Source: sni}} programVar={sni.programVar} currentUser={this.props.currentUser} updatePDV={this.props.updatePDV}/>;
})}
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ updatePDV }, dispatch);
}
SectionNestedItemList.propTypes = {
items: PropTypes.array,
updatePDV: PropTypes.func,
currentUser: PropTypes.object,
resultStyle: PropTypes.string
};
export default connect(null, mapDispatchToProps)(SectionNestedItemList);
|
views/NotFound.js | dominiktilp/congestion-charge-app | import React from 'react';
export default props => {
return <div>Page Not Found</div>;
};
|
imageviewapp/src/App.js | senacor/epic-image-aws-bonanza-robot | import React, { Component } from 'react';
import './App.css';
import Images from './Images'
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src="angry-1300616_1280.png" className="App-logo" alt="logo" />
<h2>Epic Image Robot / Display</h2>
</div>
<Images />
</div>
);
}
}
export default App;
|
examples/async/index.js | voidException/redux | import 'babel-core/polyfill';
import React from 'react';
import Root from './containers/Root';
React.render(
<Root />,
document.getElementById('root')
);
|
src/js/components/icons/base/Contact.js | odedre/grommet-final | /**
* @description Contact SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M1,2 L22,2 L22,18 L14,18 L6,22 L6,18 L1,18 L1,2 Z M6,10 L7,10 L7,11 L6,11 L6,10 Z M11,10 L12,10 L12,11 L11,11 L11,10 Z M16,10 L17,10 L17,11 L16,11 L16,10 Z"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-contact`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'contact');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M1,2 L22,2 L22,18 L14,18 L6,22 L6,18 L1,18 L1,2 Z M6,10 L7,10 L7,11 L6,11 L6,10 Z M11,10 L12,10 L12,11 L11,11 L11,10 Z M16,10 L17,10 L17,11 L16,11 L16,10 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Contact';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
src/svg-icons/communication/comment.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationComment = (props) => (
<SvgIcon {...props}>
<path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18zM18 14H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
</SvgIcon>
);
CommunicationComment = pure(CommunicationComment);
CommunicationComment.displayName = 'CommunicationComment';
export default CommunicationComment;
|
admin/client/App/screens/Home/components/Lists.js | helloworld3q3q/keystone | import React from 'react';
import _ from 'lodash';
import { connect } from 'react-redux';
import { FormattedMessage, intlShape, injectIntl, defineMessages } from 'react-intl';
import { plural } from '../../../../utils/string';
import ListTile from './ListTile';
const messages = defineMessages({
item: {id: 'item'},
items: {id: 'items'}
});
export class Lists extends React.Component {
constructor(props) {
super(props);
this.state={
formatMessage: this.props.intl['formatMessage'],
};
}
render () {
return (
<div className="dashboard-group__lists">
{_.map(this.props.lists, (list, key) => {
// If an object is passed in the key is the index,
// if an array is passed in the key is at list.key
const listKey = list.key || key;
const href = list.external ? list.path : `${Keystone.adminPath}/${list.path}`;
const listData = this.props.listsData[list.path];
const isNoCreate = listData ? listData.nocreate : false;
return (
<ListTile
key={list.path}
path={list.path}
label={list.label}
hideCreateButton={isNoCreate}
href={href}
count={plural(this.props.counts[listKey],
`* ${this.state.formatMessage(messages.item)}`,
`* ${this.state.formatMessage(messages.items)}`)}
spinner={this.props.spinner}
/>
);
})}
</div>
);
}
}
Lists.propTypes = {
counts: React.PropTypes.object.isRequired,
lists: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.object,
]).isRequired,
spinner: React.PropTypes.node,
intl: intlShape.isRequired,
};
export default connect((state) => {
return {
listsData: state.lists.data,
};
})(injectIntl(Lists));
|
src/components/Main.js | suiyang1714/gallery-by-react | require('normalize.css/normalize.css');
require('styles/App.sass');
import React from 'react';
//获取图片相关的数据
var imageDatas = require('../data/imageDatas.json');
//利用自执行函数,将图片名信息转成图片URL路径信息
imageDatas = (function getImageURL(imageDataArr){
for (var i = 0 , j = imageDataArr.length ; i < j;i++) {
var singleImageData = imageDataArr[i];
singleImageData.imageURL = require('../images/'+singleImageData.fileName);
imageDataArr[i] = singleImageData
}
return imageDataArr;
})(imageDatas);
//给定一个区间,取随机位置,即获取区间内的一个随机值
function getRangeRandom(low,high) {
return Math.ceil(Math.random() * (high - low) + low)
}
//获取0~30°之间的一个正负值
function get30DegRandom(){
return Math.random() > 0.5 ? Math.ceil(Math.random() * 30) : -Math.ceil(Math.random() * 30)
}
var ImgFigure = React.createClass({
//*
handleClick: function (e) {
if(this.props.arrange.isCenter){
this.props.inverse();
} else {
this.props.center();
}
e.stopPropagation();
e.preventDefault();
},
render: function () {
var styleObj = {};
//如果props属性中制定了这张图片的位置,则使用
if(this.props.arrange.pos){
styleObj = this.props.arrange.pos;
}
//如果图片的旋转角度有值并且不为0,则添加旋转角度
if(this.props.arrange.rotate){
(['-moz-','-ms-','-webkit-','']).forEach(function (value) {
styleObj[value+'transform'] = 'rotate(' + this.props.arrange.rotate + 'deg)';
}.bind(this));
}
if (this.props.arrange.isCenter) {
styleObj.zIndex = 11;
}
var imgFigureClassName = "img-figure";
imgFigureClassName += this.props.arrange.isInverse ? ' isInverse' : '';
return (
<figure className={imgFigureClassName} style = {styleObj} ref="figure" onClick={this.handleClick}>
<img src={this.props.data.imageURL} alt={this.props.data.title}/>
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
<div className="img-back" onClick={this.handleClick}>
<p>
{this.props.data.desc}
</p>
</div>
</figcaption>
</figure>
)
}
});
var GalleryByReactApp = React.createClass({
//图片排列位置
Constant: {
centerPos:{
left : 0,
right : 0
},
hPosRange:{ // 水平方向的取值范围
leftSecX: [0,0], //左侧分区范围
rightSecX: [0,0], //右侧分区范围
y: [0,0] //Y轴的范围
},
vPosRange:{ // 垂直方向的取值范围
x:[0,0], //上侧分区
topY: [0,0]
}
},
/*
* 翻转图片
* @param index 输入当前被执行inverse 操作的图片对应的图片信息数组的index值
* @return { Function} 这是一个闭包函数,其内return一个真正待被执行的函数
*/
inverse : function (index){
return function(){
var imgsArrangeArr = this.state.imgsArrangeArr;
imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse
this.setState({
imgsArrangeArr: imgsArrangeArr
})
}.bind(this);
},
//重新布局所有的图片
// @param centerIndex 指定居中排布哪个图片
rearrange: function(centerIndex){
var imgsArrangeArr = this.state.imgsArrangeArr, //存放的是所有图片的状态信息
Constant = this.Constant,
centerPos = Constant.centerPos,
hPosRange = Constant.hPosRange,
vPosRange = Constant.vPosRange,
hPosRangeLeftSecX = hPosRange.leftSecX,
hPosRangeRightSecX = hPosRange.rightSecX,
hPosRangeY = hPosRange.y,
vPosRangeTopY = vPosRange.topY,
vPosRangeX = vPosRange.x,
//该数组存储放在上侧分区图片的状态信息
imgsArrangeTopArr = [];
//放在上侧分区图片的数量
var topImgNum = Math.ceil(Math.random() * 2) ; //取一个或者不取
//用来标记部署在上侧的图片是从数组中哪个位置中拿出来的
var topImgSpliceIndex = 0 ;
//imgArrangeCenterArr存放居中图片的状态信息
var imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1);
//splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目
//该方法会改变原始数组
// 首先居中 centerIndex 的图片
imgsArrangeCenterArr[0]= {
pos: centerPos,
rotate: 0,
isCenter: true
};
//居中的 centerIndex 的图片不需要旋转
imgsArrangeCenterArr[0].rotate = 0;
//取出要布局上侧的图片的状态信息
topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum));
imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum);
//布局位图上侧的图片
imgsArrangeTopArr.forEach(function (value,index) {
imgsArrangeTopArr[index] = {
pos: {
top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
left: getRangeRandom(vPosRangeX[0], vPosRangeX[1])
},
rotate: get30DegRandom(),
isCenter: false
}
});
// 布局左右两侧的图片
for(var i = 0, j = imgsArrangeArr.length,k = j/2;i<j;i++){
var hPosRangeLORX = null;
//前半部分布局左边,右半部分布局右边
if(i < k){
hPosRangeLORX = hPosRangeLeftSecX;
} else {
hPosRangeLORX = hPosRangeRightSecX;
}
imgsArrangeArr[i] = {
pos: {
top: getRangeRandom(hPosRangeY[0],hPosRangeY[1]),
left: getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1])
},
rotate: get30DegRandom(),
isCenter: false
};
}
//如果上侧分区放图片了,再将该图片放入到imgsArrangeArr原来的位置
if(imgsArrangeTopArr && imgsArrangeTopArr[0]) {
imgsArrangeArr.splice(topImgSpliceIndex, 0 ,imgsArrangeTopArr[0]);
}
//接下来,再将中心位置的图片放入到imgsArrangeArr原来的位置
imgsArrangeArr.splice(centerIndex, 0 ,imgsArrangeCenterArr[0]);
//接下来设置state,可以出发~,重新渲染页面
this.setState({
imgsArrangeArr:imgsArrangeArr
});
},
/*
* 利用 rearrange函数,居中对应index 的图片
* @param index ,需要悲剧中的图片对应的图片信息数组的index值
* */
center : function(index){
return function () {
this.rearrange(index);
}.bind(this)
},
getInitialState:function () {
return {
imgsArrangeArr: [
/*{
pos:{
left: '0',
top: '0'
},
rotate: 0, //旋转角度
isInverse: false, //图片正反面
isCenter: false //图片是否居中
}*/
]
};
},
// 组件加载以后,为每张图片计算其位置范围
componentDidMount: function() {
//首先拿到舞台的大小
//scrollWidth:对象的实际内容的宽度,不包滚动条和边线宽度,会随对象中内容超过可视区后而变大。
//clientWidth:对象内容的可视区的宽度,不包滚动条等边线,会随对象显示大小的变化而改变。
//offsetWidth:对象整体的实际宽度,包滚动条等边线,会随对象显示大小的变化而改变。
var stageDOM = this.refs.stage,
stageW = stageDOM.scrollWidth,
stageH = stageDOM.scrollHeight,
halfStageW = Math.ceil(stageW / 2),
halfStageH = Math.ceil(stageH / 2);
//拿到一个imageFigure的大小
var imgFigureDOM = this.refs.imgFigure0.refs.figure,
imgW = imgFigureDOM.scrollWidth,
imgH = imgFigureDOM.scrollHeight,
halfImgW = Math.ceil(imgW / 2),
halfImgH = Math.ceil(imgH / 2);
//计算中心图片的位置点
this.Constant.centerPos = {
left: halfStageW - halfImgW,
top: halfStageH - halfImgH
};
//计算左侧,右侧区域图片排布位置的取值范围
this.Constant.hPosRange.leftSecX[0] = -halfImgW;
this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
this.Constant.hPosRange.y[0] = -halfImgH;
this.Constant.hPosRange.y[1] = stageH - halfImgH;
//计算上侧区域图片排布位置的取值范围
this.Constant.vPosRange.topY[0] = -halfImgH;
this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
this.Constant.vPosRange.x[0] = halfStageW - imgW;
this.Constant.vPosRange.x[1] = halfStageW;
//第一张图片居中
this.rearrange(0)
},
render: function() {
var controllerUnits = [],
imgFigures = [];
imageDatas.forEach(function(value,index){
if(!this.state.imgsArrangeArr[index]) {
this.state.imgsArrangeArr[index] = {
pos: {
left: 0,
top: 0
},
rotate : 0,
isInverse: false,
isCenter: false
};
}
imgFigures.push(<ImgFigure data={value} ref={'imgFigure' + index} key = {index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
//通过arrange将
}.bind(this));
return (
<section className="stage" ref="stage">
<section className="img-sec">
{imgFigures}
</section>
<nav className="controller-nav">
{controllerUnits}
</nav>
</section>
);
}
});
GalleryByReactApp.defaultProps = {
};
export default GalleryByReactApp;
|
react-flux-mui/js/material-ui/src/svg-icons/image/rotate-left.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageRotateLeft = (props) => (
<SvgIcon {...props}>
<path d="M7.11 8.53L5.7 7.11C4.8 8.27 4.24 9.61 4.07 11h2.02c.14-.87.49-1.72 1.02-2.47zM6.09 13H4.07c.17 1.39.72 2.73 1.62 3.89l1.41-1.42c-.52-.75-.87-1.59-1.01-2.47zm1.01 5.32c1.16.9 2.51 1.44 3.9 1.61V17.9c-.87-.15-1.71-.49-2.46-1.03L7.1 18.32zM13 4.07V1L8.45 5.55 13 10V6.09c2.84.48 5 2.94 5 5.91s-2.16 5.43-5 5.91v2.02c3.95-.49 7-3.85 7-7.93s-3.05-7.44-7-7.93z"/>
</SvgIcon>
);
ImageRotateLeft = pure(ImageRotateLeft);
ImageRotateLeft.displayName = 'ImageRotateLeft';
ImageRotateLeft.muiName = 'SvgIcon';
export default ImageRotateLeft;
|
client/src/app/parts/auth/views/loginView.js | Einsteinish/DumbNode | import React from 'react';
import { Link } from 'react-router';
import tr from 'i18next';
import Paper from 'material-ui/Paper';
import FlatButton from 'material-ui/FlatButton';
import MediaSigninButtons from '../components/mediaSigninButtons';
import LocalLoginForm from '../components/localLoginForm';
import DocTitle from 'components/docTitle';
import Debug from 'debug';
let debug = new Debug("views:login");
export default React.createClass( {
contextTypes: {
router: React.PropTypes.object.isRequired
},
propTypes:{
},
componentWillReceiveProps(nextProps){
debug("componentWillReceiveProps", nextProps);
let path = nextProps.location.query.nextPath || '/app';
debug("componentWillReceiveProps next path: ", path);
if (nextProps.authenticated) {
this.context.router.push(path);
}
},
render() {
return (
<div id='login'>
<DocTitle
title="Login"
/>
<Paper className="text-center view">
<h2 >{tr.t('login')}</h2>
<div>
<LocalLoginForm {...this.props}/>
<div className="strike"><span className="or"></span></div>
<div>
<MediaSigninButtons />
</div>
<div className="strike"><span className="or"></span></div>
<FlatButton
label={tr.t('forgotPassword')}
containerElement={<Link to="/forgot" />}
linkButton={true}
/>
</div>
</Paper>
</div>
);
}
} );
|
app/routes.js | Yukaii/ImgurDownloader | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/App';
import Home from './components/Home';
export default (
<Route path="/" component={App}>
<IndexRoute component={Home} />
</Route>
);
|
packages/@vega/issues-tool/src/components/providers/ArticleList.js | VegaPublish/vega-studio | // @flow
import React from 'react'
import styles from './styles/ArticleList.css'
import cx from 'classnames'
import type {Reference} from '../types'
import CompactArticle from '@vega/components/CompactArticle'
type Props = {
articles: ?Array<Reference>,
onToggleArticle: (articleId: string) => void,
openArticleId: ?string
}
export default class ArticleList extends React.Component<Props> {
render() {
const {articles, onToggleArticle, openArticleId} = this.props
return (
<ul className={cx(openArticleId ? styles.listDimmed : styles.list)}>
{(articles || []).map(article => {
const isOpen = openArticleId === article._ref
const isArticleSelected = isOpen || !openArticleId
const isArticleDimmed = !isArticleSelected
const itemClasses = cx(
isArticleDimmed && styles.listItemDimmed,
isOpen ? styles.listItemOpen : styles.listItemClosed
)
return (
<li key={article._ref} className={itemClasses}>
<CompactArticle
article={article}
isOpen={openArticleId === article._ref}
onToggle={onToggleArticle}
/>
</li>
)
})}
</ul>
)
}
}
|
lib/index.js | StephanieEA/firebae | import React from 'react';
import { render } from 'react-dom';
import Application from './components/Application';
import firebase from './firebase';
require('./css/reset.scss')
require('./css/style.scss');
render(<Application/>, document.getElementById('application'));
|
app/src/components/Header.js | tom-s/3d-ears | import React from 'react'
import { Link } from 'react-router'
// Components
import NavBarRight from './header/NavBarRight'
import NavBarRightLoggedIn from './header/NavBarRightLoggedIn'
const Header = (props) => {
const { loggedIn, signOut } = props
const headerLinks = (loggedIn) ? (<NavBarRightLoggedIn signOut={signOut} />) : (<NavBarRight />)
return (
<nav className="Header navbar navbar-default navbar-static-top">
<div className="HeaderContainer container">
<div className="NavBarHeader navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<Link className="navbar-brand em-text" to="/">
<img alt="3D Ears" className="Logo" src="assets/images/logo.png" />
</Link>
</div>
<div id="navbar" className="NavBarCollapse collapse navbar-collapse">
{headerLinks}
</div>
</div>
</nav>
)
}
export default Header |
src/containers/DevTools/DevTools.js | dunglas/calavera-react-client | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-H"
changePositionKey="ctrl-Q">
<LogMonitor />
</DockMonitor>
);
|
client/router/Router.js | Mignon-han/issue-processing | import React from 'react';
import { Router, Route, Redirect, hashHistory, browserHistory } from 'react-router';
import Auth from '../containers/Auth';
import App from '../containers/App';
import Loading from '../containers/Utils/Loading';
const home = () => (<h1>Home</h1>);
const login = () => (
<div>
<Auth />
<Loading />
</div>);
//roter config
var history = process.env.NODE_ENV === 'development' ? hashHistory : hashHistory;
const appRouter = () => (
<Router history={history}>
<Redirect from="/" to="/login" />
<Route path="/" component={home} />
<Route path="/app" component={App} />
<Route path="/login" component={login} />
</Router>
);
export default appRouter; |
src/routes.js | KoushikKumar/trade-a-book-client | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/app';
import Home from './components/home';
import ViewAll from './components/view-all'
import SignUp from './components/signup';
import Login from './components/login';
import MyBooks from './components/my-books';
import AddBook from './components/add-book';
import Profile from './components/profile';
import BookDetails from './components/book-details';
import { SIGNUP, LOGIN, MY_BOOKS, ADD_BOOK, UPDATE_PROFILE, BOOK_DETAILS, VIEW_ALL } from './constants/routes-constants';
import requireUnAuth from './components/hoc/require-unauthentication';
import requireAuth from './components/hoc/require-authentication';
export default (
<Route path ="/" component = {App} >
<IndexRoute component = {Home} />
<Route path = { VIEW_ALL } component = {ViewAll} />
<Route path = { SIGNUP } component = {requireUnAuth(SignUp)} />
<Route path = { LOGIN } component = {requireUnAuth(Login)} />
<Route path = { UPDATE_PROFILE } component = { requireAuth(Profile) } />
<Route path = { MY_BOOKS } component = {requireAuth(MyBooks)} />
<Route path = { ADD_BOOK } component = {requireAuth(AddBook)} />
<Route path = { BOOK_DETAILS } component = {BookDetails} />
</Route>
);
|
app/components/Slider/tests/stories/index.js | VonIobro/ab-web | import React from 'react';
import { storiesOf } from '@storybook/react';
import { fromJS } from 'immutable';
import Slider from '../../index';
export const props = fromJS({
amount: 100,
minRaise: 100,
myStack: 332,
sb: 50,
updateAmount: () => {},
});
const stories = storiesOf('Slider', module);
stories.add('Default', () => {
const newProps = props.toJS();
return (
<Slider {...newProps} />
);
});
|
packages/cf-component-table/src/TableHead.js | mdno/mdno.github.io | import React from 'react';
import PropTypes from 'prop-types';
class TableHead extends React.Component {
render() {
let className = 'cf-table__head';
if (this.props.className.trim())
className += ' ' + this.props.className.trim();
return (
<thead className={className}>
{this.props.children}
</thead>
);
}
}
TableHead.propTypes = {
className: PropTypes.string,
children: PropTypes.node
};
TableHead.defaultProps = {
className: ''
};
export default TableHead;
|
app/routes/ConversationHistory.js | andreybutenko/fieldtrip | import React, { Component } from 'react';
import MapView from 'react-native-maps';
import { TextInput, StyleSheet, Text, View, ScrollView } from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import configStyles from '../config/configStyles';
import AdvancedChat from '../components/AdvancedChat';
import ChatBubble from '../components/ChatBubble';
const styles = StyleSheet.create({
container: {
flex: 1
},
chat: {
flex: 1,
marginBottom: 8
},
textChat: {
flexDirection: 'row',
alignItems: 'center',
paddingTop: 0
},
input: {
flex: 1,
paddingTop: 6,
paddingBottom: 6,
marginLeft: 8
},
icon: {
paddingLeft: 8,
paddingRight: 8,
fontSize: 20
}
});
export default class ConversationHistory extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.initialScrollDone = false;
this.setState({
enabledSection: -1,
typing: '',
messages: [
{
sender: 'Andrey Butenko',
text: 'Diam veri has ne, te eum iusto persecuti, vivendo partiendo ne usu.'
},
{
sender: 'John Doe',
text: 'Ex per modus graece, duo omnesque accusamus imperdiet no. An vel alia choro, et accusamus contentiones mei, duo ne omnes oratio pericula. Deleniti nominati vix cu. An sea percipit mnesarchum dissentiunt, velit simul indoctum ei ius, id diceret eleifend qui. Ne nam omnis vidisse delicata.'
},
{
sender: 'John Doe',
text: 'An vel alia choro, et accusamus contentiones mei, duo ne omnes oratio pericula. Deleniti nominati vix cu. An sea percipit mnesarchum dissentiunt, velit simul indoctum ei ius, id diceret eleifend qui. Ne nam omnis vidisse delicata.'
},
{
sender: 'Andrey Butenko',
text: 'Deleniti nominati vix cu. An sea percipit mnesarchum dissentiunt, velit simul indoctum ei ius, id diceret eleifend qui. Ne nam omnis vidisse delicata.'
},
{
sender: 'Andrey Butenko',
text: 'Ne nam omnis vidisse delicata.'
}
]
});
}
scrollResize(height) {
this.scrollView.scrollTo({ y: height, animated: this.initialScrollDone });
this.initialScrollDone = true;
}
enableSection(i, curr) {
// Can just pass i to set a section
// If passing -1, should also pass curr to make sure you're not overwriting an already-opened section
if(curr == null || this.state.enabledSection == curr) {
this.setState({
...this.state,
enabledSection: i
});
}
if(i == 0) {
this.textInput.focus();
}
}
sendMessage(data) {
if(data.type == 'text') {
if(data.content != null && data.content != '') {
this.setState({
...this.state,
messages: [
...this.state.messages,
{
sender: 'Andrey Butenko',
text: data.content
}
]
});
this.textInput.clear(0);
}
}
}
render() {
return (
<View style={[styles.container, configStyles.sceneWrapper]}>
<ScrollView style={styles.chat} ref={(scrollView) => { this.scrollView = scrollView; }} onContentSizeChange={(width, height) => { this.scrollResize(height); }}>
{this.state.messages.map((msg, i) =>
<ChatBubble
key={i}
fromMe={msg.sender == 'Andrey Butenko'}
sender={msg.sender}
text={msg.text}
/>
)}
</ScrollView>
<AdvancedChat
enabledSection={this.state.enabledSection}
sendMessage={(data) => this.sendMessage(data)}
enableSection={(i) => this.enableSection(i)}
/>
<View style={styles.textChat}>
<TextInput
ref={(textInput) => { this.textInput = textInput; }}
style={styles.input}
placeholder={'Write a message'}
multiline={true}
onChangeText={(val) => this.setState({
...this.state,
typing: val
})}
onFocus={() => this.enableSection(0)}
onBlur={() => this.enableSection(-1, 0)}
/>
<Icon
style={styles.icon}
name="send"
onPress={() => this.sendMessage({
type: 'text',
content: this.state.typing
})} />
</View>
<View style={styles.locationView}>
<MapView
style={styles.mapView}
showsUserLocation={true}
showsMyLocationButton={true}
showsPointsOfInterest={false}
/>
</View>
</View>
);
}
}
|
client/source/components/Dictionaries.js | r-pr/mnesis | import PropTypes from 'prop-types';
import React from 'react';
class Dictionaries extends React.Component {
render() {
let dicts = [];
for (let key in this.props.dictionaries) {
dicts.push(<li key = {key}><a href="#"
onClick={()=>{this.props.onDictClick(key);}}
>
{this.props.dictionaries[key].name}
</a>
</li>);
}
return (<div>
<div className="col-sm-12">
{dicts.length > 0 ? <ul style={{lineHeight: '2em'}}>{dicts}</ul> : <p>You have no dictionaries yet.</p>}
</div>
<div className="col-sm-12">
<button
className="btn btn-default"
onClick={this.props.onCreateNew}
style={{marginLeft: '1.75em'}}
>
Create new
</button>
</div>
</div>);
}
}
Dictionaries.propTypes = {
onCreateNew: PropTypes.func.isRequired,
onDictClick: PropTypes.func.isRequired,
dictionaries: PropTypes.object.isRequired
};
export default Dictionaries;
|
frontend/src/components/Scroller.js | daGrevis/msks | import _ from 'lodash'
import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'
import React from 'react'
import { connect } from 'react-redux'
import ResizeObserver from 'resize-observer-polyfill'
import { saveLastScrollPosition } from '../store/actions/app'
import '../styles/Scroller.css'
const SCROLL_ACTIONS = {
toItem: 'toItem',
adjustForTop: 'adjustForTop',
toBottom: 'toBottom',
restore: 'restore',
}
const isCloseToTop = node => node.scrollTop < node.clientHeight
const isCloseToBottom = node =>
node.scrollHeight - (node.scrollTop + node.clientHeight) < node.clientHeight
class Scroller extends React.Component {
node = null
resizeObserver = null
scrollHeight = null
scrollTop = null
scrollAction = null
isScrollUpdated = false
isItemAddedToTop = false
isItemAddedToBottom = false
isScrolledTopFired = false
isScrolledBottomFired = false
componentWillMount() {
this.calculateScroll(null, this.props)
}
componentWillReceiveProps(nextProps) {
this.calculateScroll(this.props, nextProps)
}
componentDidMount() {
this.updateScroll()
let prevHeight
this.resizeObserver = new ResizeObserver(([entry]) => {
const { height } = entry.contentRect
if (prevHeight && prevHeight !== height) {
const heightDelta = prevHeight - height
const scrollBottom =
this.node.scrollHeight -
this.node.clientHeight -
this.node.scrollTop -
heightDelta
if (-scrollBottom < heightDelta) {
this.node.scrollTop = this.node.scrollTop + heightDelta
}
}
prevHeight = height
})
this.resizeObserver.observe(this.node)
}
componentDidUpdate() {
this.updateScroll()
}
componentWillUnmount() {
this.resizeObserver.disconnect()
}
calculateScroll(prevProps, nextProps) {
if (this.node) {
this.scrollHeight = this.node.scrollHeight
this.scrollTop = this.node.scrollTop
}
if (
prevProps &&
!prevProps.shouldResetScrolledBottom &&
nextProps.shouldResetScrolledBottom
) {
this.isScrolledBottomFired = false
}
const prevItems = (prevProps && prevProps.items) || []
const nextItems = nextProps.items || []
if (!nextItems.length) {
this.isScrollUpdated = false
}
this.isItemAddedToTop = !!(
(nextItems.length &&
prevItems.length &&
prevItems[0].id !== nextItems[0].id) ||
(prevItems.length && !nextItems.length)
)
this.isItemAddedToBottom = !!(
(nextItems.length &&
prevItems.length &&
prevItems[prevItems.length - 1].id !==
nextItems[nextItems.length - 1].id) ||
(prevItems.length && !nextItems.length)
)
const shouldScrollToItem =
nextProps.itemId &&
(!prevProps ? true : prevProps.itemId !== nextProps.itemId)
if (shouldScrollToItem) {
this.scrollAction = SCROLL_ACTIONS.toItem
return
}
if (this.isItemAddedToTop) {
this.scrollAction = SCROLL_ACTIONS.adjustForTop
return
}
const hasReachedBottom = !!(
this.node &&
nextItems.length &&
// May be 1px off due to native rounding.
this.node.scrollHeight - (this.scrollTop + this.node.clientHeight) <= 1
)
if (
this.props.stickToBottom ||
(this.props.autoStickToBottom && hasReachedBottom)
) {
this.scrollAction = SCROLL_ACTIONS.toBottom
return
}
const shouldRestore = !!(!prevProps && nextProps.scrollPosition)
if (shouldRestore) {
this.scrollAction = SCROLL_ACTIONS.restore
return
}
}
updateScroll = () => {
const isScrollable = this.node.clientHeight !== this.node.scrollHeight
const shouldRescroll = !!(
this.props.items &&
this.props.items.length &&
(!isScrollable || isCloseToTop(this.node) || isCloseToBottom(this.node))
)
switch (this.scrollAction) {
case SCROLL_ACTIONS.toItem:
scrollIntoViewIfNeeded(document.getElementById(this.props.itemId), {
scrollMode: 'if-needed',
block: 'center',
})
break
case SCROLL_ACTIONS.adjustForTop:
// Force stop momentum scrolling.
this.node.style.overflow = 'hidden'
this.node.scrollTop =
this.scrollTop + (this.node.scrollHeight - this.scrollHeight)
this.node.style.overflowY = 'scroll'
break
case SCROLL_ACTIONS.toBottom:
this.node.scrollTop = this.node.scrollHeight
break
case SCROLL_ACTIONS.restore:
this.node.scrollTop = this.props.scrollPosition
break
default:
break
}
if (this.scrollAction) {
this.isScrollUpdated = true
}
if (this.isItemAddedToTop) {
this.isItemAddedToTop = false
this.isScrolledTopFired = false
}
if (this.isItemAddedToBottom) {
this.isItemAddedToBottom = false
this.isScrolledBottomFired = false
}
this.scrollAction = null
if (shouldRescroll) {
this.isScrollUpdated = true
this.onScroll()
}
}
onRef = node => {
this.node = node
}
onScroll = () => {
if (!this.node) {
return
}
if (!this.isScrollUpdated) {
return
}
const shouldFireScrolledTop = !!(
this.props.items &&
this.props.items.length &&
this.props.onScrolledTop &&
!this.isScrolledTopFired &&
isCloseToTop(this.node)
)
if (shouldFireScrolledTop) {
this.isScrolledTopFired = this.props.onScrolledTop()
}
const shouldFireScrolledBottom = !!(
this.props.items &&
this.props.items.length &&
this.props.onScrolledBottom &&
!this.isScrolledBottomFired &&
isCloseToBottom(this.node)
)
if (shouldFireScrolledBottom) {
this.isScrolledBottomFired = this.props.onScrolledBottom()
}
this.saveLastScrollPosition()
}
onThrottledScroll = _.throttle(() => {
this.onScroll()
}, 250)
saveLastScrollPosition = _.debounce(() => {
if (!this.node) {
return
}
if (this.props.id) {
this.props.saveLastScrollPosition({
id: this.props.id,
position: Math.round(this.node.scrollTop),
})
}
}, 500)
render() {
return (
<div
className="scroller"
ref={this.onRef}
onScroll={this.onThrottledScroll}
>
{this.props.children}
</div>
)
}
}
const mapStateToProps = (state, ownProps) => ({
scrollPosition: ownProps.id ? state.scrollPositions[ownProps.id] : undefined,
})
const mapDispatchToProps = {
saveLastScrollPosition,
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Scroller)
|
src/icons/SocialFacebookOutline.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class SocialFacebookOutline extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M288,192v-38.1c0-17.2,3.8-25.9,30.5-25.9H352V64h-55.9c-68.5,0-91.1,31.4-91.1,85.3V192h-45v64h45v192h83V256h56.4l7.6-64
H288z M330.2,240h-41.1H272v15.5V432h-51V255.5V240h-14.9H176v-32h30.1H221v-16.5v-42.2c0-24.5,5.4-41.2,15.5-51.8
C247.7,85.5,267.6,80,296.1,80H336v32h-17.5c-12,0-27.5,1.1-37.1,11.7c-8.1,9-9.4,20.1-9.4,30.1v37.6V208h17.1H334L330.2,240z"></path>
</g>;
} return <IconBase>
<path d="M288,192v-38.1c0-17.2,3.8-25.9,30.5-25.9H352V64h-55.9c-68.5,0-91.1,31.4-91.1,85.3V192h-45v64h45v192h83V256h56.4l7.6-64
H288z M330.2,240h-41.1H272v15.5V432h-51V255.5V240h-14.9H176v-32h30.1H221v-16.5v-42.2c0-24.5,5.4-41.2,15.5-51.8
C247.7,85.5,267.6,80,296.1,80H336v32h-17.5c-12,0-27.5,1.1-37.1,11.7c-8.1,9-9.4,20.1-9.4,30.1v37.6V208h17.1H334L330.2,240z"></path>
</IconBase>;
}
};SocialFacebookOutline.defaultProps = {bare: false} |
blueocean-material-icons/src/js/components/svg-icons/content/sort.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ContentSort = (props) => (
<SvgIcon {...props}>
<path d="M3 18h6v-2H3v2zM3 6v2h18V6H3zm0 7h12v-2H3v2z"/>
</SvgIcon>
);
ContentSort.displayName = 'ContentSort';
ContentSort.muiName = 'SvgIcon';
export default ContentSort;
|
src/Elevation/Elevation.js | kradio3/react-mdc-web | import PropTypes from 'prop-types';
import React from 'react';
import classnames from 'classnames';
import isDefined from '../utils/isDefined';
const propTypes = {
className: PropTypes.string,
children: PropTypes.node,
transition: PropTypes.bool,
z: PropTypes.number,
};
const Elevation = ({ className, children, z, transition, ...otherProps }) => (
<div
className={classnames({
[`mdc-elevation--z${z}`]: isDefined(z),
'mdc-elevation-transition': transition,
}, className)}
{...otherProps}
>
{children}
</div>
);
Elevation.propTypes = propTypes;
export default Elevation;
|
pages/api/drawer.js | cherniavskii/material-ui | import React from 'react';
import withRoot from 'docs/src/modules/components/withRoot';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from './drawer.md';
function Page() {
return <MarkdownDocs markdown={markdown} />;
}
export default withRoot(Page);
|
server/sonar-web/src/main/js/apps/permissions/global/components/AllHoldersList.js | Builders-SonarSource/sonarqube-bis | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// @flow
import React from 'react';
import { connect } from 'react-redux';
import SearchForm from '../../shared/components/SearchForm';
import HoldersList from '../../shared/components/HoldersList';
import {
loadHolders,
grantToUser,
revokeFromUser,
grantToGroup,
revokeFromGroup,
updateFilter,
updateQuery,
selectPermission
} from '../store/actions';
import { translate } from '../../../../helpers/l10n';
import {
getPermissionsAppUsers,
getPermissionsAppGroups,
getPermissionsAppQuery,
getPermissionsAppFilter,
getPermissionsAppSelectedPermission
} from '../../../../store/rootReducer';
const PERMISSIONS_ORDER = [
'admin',
'profileadmin',
'gateadmin',
'scan',
'provisioning'
];
const PERMISSIONS_FOR_CUSTOM_ORG = [
'admin',
'scan',
'provisioning'
];
class AllHoldersList extends React.Component {
componentDidMount () {
this.props.loadHolders();
}
handleToggleUser (user, permission) {
const hasPermission = user.permissions.includes(permission);
if (hasPermission) {
this.props.revokePermissionFromUser(user.login, permission);
} else {
this.props.grantPermissionToUser(user.login, permission);
}
}
handleToggleGroup (group, permission) {
const hasPermission = group.permissions.includes(permission);
if (hasPermission) {
this.props.revokePermissionFromGroup(group.name, permission);
} else {
this.props.grantPermissionToGroup(group.name, permission);
}
}
render () {
const order = (this.props.organization && !this.props.organization.isDefault) ?
PERMISSIONS_FOR_CUSTOM_ORG :
PERMISSIONS_ORDER;
const l10nPrefix = this.props.organization ? 'organizations_permissions' : 'global_permissions';
const permissions = order.map(p => ({
key: p,
name: translate(l10nPrefix, p),
description: translate(l10nPrefix, p, 'desc')
}));
return (
<HoldersList
permissions={permissions}
selectedPermission={this.props.selectedPermission}
users={this.props.users}
groups={this.props.groups}
onSelectPermission={this.props.onSelectPermission}
onToggleUser={this.handleToggleUser.bind(this)}
onToggleGroup={this.handleToggleGroup.bind(this)}>
<SearchForm
query={this.props.query}
filter={this.props.filter}
onSearch={this.props.onSearch}
onFilter={this.props.onFilter}/>
</HoldersList>
);
}
}
const mapStateToProps = state => ({
users: getPermissionsAppUsers(state),
groups: getPermissionsAppGroups(state),
query: getPermissionsAppQuery(state),
filter: getPermissionsAppFilter(state),
selectedPermission: getPermissionsAppSelectedPermission(state)
});
type OwnProps = {
organization?: { key: string }
};
const mapDispatchToProps = (dispatch, ownProps: OwnProps) => {
const organizationKey = ownProps.organization ? ownProps.organization.key : undefined;
return {
loadHolders: () => dispatch(loadHolders(organizationKey)),
onSearch: query => dispatch(updateQuery(query, organizationKey)),
onFilter: filter => dispatch(updateFilter(filter, organizationKey)),
onSelectPermission: permission => dispatch(selectPermission(permission, organizationKey)),
grantPermissionToUser: (login, permission) =>
dispatch(grantToUser(login, permission, organizationKey)),
revokePermissionFromUser: (login, permission) =>
dispatch(revokeFromUser(login, permission, organizationKey)),
grantPermissionToGroup: (groupName, permission) =>
dispatch(grantToGroup(groupName, permission, organizationKey)),
revokePermissionFromGroup: (groupName, permission) =>
dispatch(revokeFromGroup(groupName, permission, organizationKey))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(AllHoldersList);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.