path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
UI/Charts/LineChart.js
|
Datasilk/Dedicate
|
import React from 'react';
import {View, ScrollView, StyleSheet, Dimensions, TouchableWithoutFeedback, Animated} from 'react-native';
import Text from 'text/Text';
import AppStyles from 'dedicate/AppStyles';
import {Svg, Line, Polyline, Circle} from 'react-native-svg';
import IconSwipeArrow from 'icons/IconSwipeArrow';
import DbRecords from 'db/DbRecords';
import ChartFilter from 'utility/ChartFilter'
import ToNumber from 'utility/ToNumber';
import ProperNumber from 'utility/ProperNumber';
import GetDate from 'utility/Date';
export default class LineChart extends React.Component{
constructor(props){
super(props);
let date = GetDate();
const days = this.props.days || 14;
const {width} = Dimensions.get('window');
this.width = width;
this.state = {
datestart: this.props.dateStart || date.setDate(date.getDate() - days),
days: days,
chart:this.props.chart || {name:'Unknown'},
records:this.props.records || [],
chartinfo:null,
height: this.props.height || 120,
padding: this.props.padding || 30,
lines:[],
line1:{min:'', max:''},
line2:{min:'', max:''},
minmax:[],
view:-1, //-1 = all
dots:[],
dotsminmax:[],
legend:[],
showLegendTaskNames: this.props.showLegendTaskNames || false,
update:this.props.update || Math.round(999 * Math.random())
}
//bind methods
this.onLayout = this.onLayout.bind(this);
this.getChart = this.getChart.bind(this);
this.getPoints = this.getPoints.bind(this);
this.getLine = this.getLine.bind(this);
this.getDots = this.getDots.bind(this);
this.getLegendLine = this.getLegendLine.bind(this);
this.getLegendDot = this.getLegendDot.bind(this);
this.onPressChart = this.onPressChart.bind(this);
}
componentWillMount(){
if(this.state.records.length == 0){
//get records for chart
this.setState({records:this.getRecords()}, () => {
this.getChart();
});
}else{
this.getChart();
}
}
componentDidUpdate(){
if(this.props.update != null && this.state.update != this.props.update){
const days = this.props.days || 14;
let date = GetDate();
date = this.props.dateStart || date.setDate(date.getDate() - days);
this.setState({
datestart: date,
days: days,
chart: this.props.chart || {name:'Unknown'},
records: this.props.records || this.getRecords(),
legend:[],
chartinfo: null,
width: this.props.width || 300,
height: this.props.height || 120,
padding: this.props.padding || 30,
update: this.props.update
}, () =>{
this.getChart();
});
}
}
onLayout(e){
const w = e.nativeEvent.layout.width;
if(this.width != w){
this.width = w;
this.getChart();
}
}
getRecords(){
const dbRecords = new DbRecords();
const chart = this.state.chart;
let records = [];
for(let x = 0; x < chart.sources.length; x++){
let source = chart.sources[x];
let filtered = null;
if(source.filters != null && source.filters.length > 0){
filtered = ChartFilter(source.filters);
}
records.push(dbRecords.GetList({taskId:source.taskId, filtered:filtered}));
}
return records;
}
// Generate Chart //////////////////////////////////////////////////////////////////////////////////////////////////////////////
getChart(){
let info = [];
let lines = [];
let chartinfo = this.state.chartinfo || null;
let dots = [];
let minmax = this.state.minmax || [];
let dotsminmax = this.state.dotsminmax || [];
let legend = this.state.legend || [];
if(chartinfo == null){
//generate chart information from database (if neccessary)
let legends = [];
let legendIds = [];
let offsetType = '';
switch(this.state.chart.offset){
case 1: offsetType = 'Day'; break;
case 2: offsetType = 'Week'; break;
case 3: offsetType = 'Month'; break;
case 4: offsetType = 'Year'; break;
}
chartinfo = {lines:[], dots:[]};
for(let x = 0; x < this.state.records.length; x++){
let source = this.state.chart.sources[x];
let records = this.state.records[x];
let input = source.input;
if(input != null){
if(legendIds.indexOf(source.taskId) < 0){
//create legend for new task
legendIds.push(source.taskId);
legends.push({name:source.task.name, items:[]});
}
let legendIndex = legendIds.indexOf(source.taskId);
if(input.type == 0 || input.type == 5 || input.type == 7){ //number
let color = this.getColor(source.color);
let minmaxExtra = '';
if(source.offset && source.offset > 0){
minmaxExtra = ' (-' + source.offset + ' ' + offsetType + (source.offset > 1 ? 's' : '') + ')';
}
info = this.getPoints(records, input, source);
info.color = color;
chartinfo.lines.push(info);
legends[legendIndex].items.push(this.getLegendLine((this.state.showLegendTaskNames ? source.task.name + ': ' : '') + input.name, color));
if(input.type == 5){
//currency
const currency = Currencies.filter(c => c.value == input.option)[0];
minmax.push({
name:source.task.name + ': ' + input.name + minmaxExtra,
min:currency.symbol + ProperNumber(info.min.toFixed(2)),
max:currency.symbol + ProperNumber(info.max.toFixed(2))
});
} else{
//number
minmax.push({name:source.task.name + ': ' + input.name + minmaxExtra, min:info.min, max:info.max});
}
}else if(input.type == 6){ //yes/no
let color = this.getColor(source.color);
chartinfo.dots.push(this.getDots(records, input, color));
legends[legendIndex].items.push(this.getLegendDot((this.state.showLegendTaskNames ? source.task.name + ': ' : '') + input.name, color));
dotsminmax.push({name:source.task.name + ': ' + input.name, min:'', max:''});
}
}
}
for(let x = 0; x < legends.length; x++){
legend.push(
<View key={'legend' + x} style={[this.styles.legendContainer, {width:this.width, height:this.state.height + 5, padding:this.state.padding}]}>
{legends[x].items}
<Text style={this.styles.legendName}>{legends[x].name}</Text>
<View style={this.styles.legendArrows}>
{x < legends.length - 1 &&
<IconSwipeArrow direction="next" size="xxsmall" opacity={0.15}/>
}
</View>
</View>
);
}
}
//get lines based on cached chart info
for(let x = 0; x < chartinfo.lines.length; x++){
const info = chartinfo.lines[x];
lines.push({line:this.getLine(info.points, info.min, info.max, x, info.color), show:true, opacity: new Animated.Value(1), x: new Animated.Value(0), y: new Animated.Value(0)});
}
//get dots based on cached chart info
for(let x = 0; x < chartinfo.dots.length; x++){
const info = chartinfo.dots[x];
dots.push({dot:info, show:true, opacity: new Animated.Value(1)});
}
this.setState({chartinfo:chartinfo, lines:lines, dots:dots, legend:legend, line1:minmax[0] || {min:'', max:''}, minmax:minmax,
line2:minmax.length > 1 ? minmax[1] : {min:'', max:''}, dotsminmax:dotsminmax});
}
// Lines //////////////////////////////////////////////////////////////////////////////////////////////////////////////
getPoints = (records, input, source) => {
let min = 999999;
let max = 0;
let points = [];
let days = this.state.days;
let offsetType = this.state.chart.offset || 0;
let datestart = GetDate(this.state.datestart);
switch(offsetType){
case 1: //day
datestart.setDate(datestart.getDate() - (source.offset || 0));
break;
case 2: //week
datestart.setDate(datestart.getDate() - ((source.offset || 0) * 7));
break;
case 3: //month
datestart.setMonth(datestart.getMonth() - (source.offset || 0));
break;
case 4: //year
datestart.setYear(datestart.getYear() - (source.offset || 0));
break;
}
let curry = 0;
//find first record for first day
for(let y = 0; y < records.length; y++){
let rec = records[y];
if(rec.datestart > datestart){
curry = y;
}else{
break;
}
}
//get totals for each day
for(let x = 0; x <= days; x++){
let count = 0;
let date = GetDate(datestart);
date.setDate(date.getDate() + x);
for(let y = curry; y >= 0; y--){
let rec = records[y];
if(rec == null || rec.datestart == null){continue;}
if(DatesMatch(date, GetDate(rec.datestart))){
let i = rec.inputs.map(a => a.inputId).indexOf(input.id);
if(rec.inputs.length > i && i > -1){
if(rec.inputs[i].number != null){
count += rec.inputs[i].number;
}
}
}else{
curry = y;
break;
}
}
points.push(ToNumber(count, 2));
}
//check totals for min & max
for(let x = 0; x < points.length; x++){
if(points[x] < min){ min = points[x];}
if(points[x] > max){ max = points[x];}
}
if(max == 0){max = 1;}
return {points:points, min:ToNumber(min, 2), max:ToNumber(max, 2)};
}
getLine = (points, min, max, index, stroke) => {
//draw lines
let lines = [];
let days = this.state.days;
let width = this.width - this.state.padding - AppStyles.paddingLarge;
let height = this.state.height - 70;
for(let x = 0; x < points.length; x++){
lines.push(Math.round(((width / days) * x) + 10) + ',' + Math.round((height + 20) - ((height) / (max - min)) * (points[x] - min)));
}
return (
<Svg width={width + 20} height={height + 30}>
<Polyline key={'line'}
stroke={stroke}
strokeWidth="5"
fill="none"
points={lines.join(' ')}
></Polyline>
</Svg>
);
}
// Dots //////////////////////////////////////////////////////////////////////////////////////////////////////////////
getDots = (records, input, color) => {
let dots = [];
let days = this.state.days;
let width = this.width - this.state.padding - AppStyles.paddingLarge;
let height = this.state.height - 70;
for(let x = 1; x <= days; x++){
let date = GetDate();
date = GetDate(date.setDate(date.getDate() - (days - x)));
for(let y = 0; y < records.length; y++){
const rec = records[y];
if(DatesMatch(date, GetDate(rec.datestart))){
let i = rec.inputs.map(a => a.inputId).indexOf(input.id);
if(i >= 0){
if(rec.inputs[i].number != null){
if(rec.inputs[i].type == 6 && rec.inputs[i].number == 1){
dots.push(
<Circle key={'dot' + x}
cx={Math.round(((width / days) * x) + 10)}
cy={height + 20}
r={5}
fill={color}
></Circle>
)
}
}
}
}
}
}
return (<Svg width={width + 20} height={height + 30}>{dots}</Svg>);
}
// Legend //////////////////////////////////////////////////////////////////////////////////////////////////////////////
getLegendLine(name, color){
return (
<View style={[this.styles.legendItem, this.state.showLegendTaskNames ? {flexDirection:'column'} : {}]} key={name}>
<View style={this.styles.legendItemIcon}>
<Svg width="20" height="10">
<Line x1="0" x2="20" y1="4" y2="4" strokeWidth="5" stroke={color}></Line>
</Svg>
</View>
<View style={this.styles.legendItemLabel}>
<Text style={this.styles.legendItemText}>{name}</Text>
</View>
</View>
);
}
getLegendDot(name, color){
return (
<View style={[this.styles.legendItem, this.state.showLegendTaskNames ? {flexDirection:'column'} : {}]} key={name}>
<View style={this.styles.legendItemIcon}>
<Svg width="20" height="10">
<Circle cx={10} cy={5} r={5} fill={color}></Circle>
</Svg>
</View>
<View style={this.styles.legendItemLabel}>
<Text style={this.styles.legendItemText}>{name}</Text>
</View>
</View>
);
}
// Line Color //////////////////////////////////////////////////////////////////////////////////////////////////////////////
getColor(index){
switch(index){
case 1: default:
return AppStyles.chartLine1Stroke;
case 2:
return AppStyles.chartLine2Stroke;
case 3:
return AppStyles.chartLine3Stroke;
case 4:
return AppStyles.chartLine4Stroke;
case 5:
return AppStyles.chartLine5Stroke;
case 6:
return AppStyles.chartLine6Stroke;
case 7:
return AppStyles.chartLine7Stroke;
case 8:
return AppStyles.chartLine8Stroke;
}
}
// Change Chart View //////////////////////////////////////////////////////////////////////////////////////////////////////////////
onPressChart(event){
let view = this.state.view;
let inc = 1;
let lines = this.state.lines;
let dots = this.state.dots;
let line1 = this.state.line1;
let line2 = this.state.line2;
let minmax = this.state.minmax;
let dotsminmax = this.state.dotsminmax;
//if(touches >= 2){
// inc = -1;
//}
if(view+inc == lines.length + dots.length || view+inc == -1){
view = -1;
for(let x = 0; x < lines.length; x++){
if(lines[x].show == false){
lines[x].show = true;
Animated.timing(
this.state.lines[x].opacity,
{
toValue:1,
duration:300
}
).start();
}
}
if(this.state.dots.length > 0){
dots[0].show = true;
Animated.timing(
this.state.dots[0].opacity,
{
toValue:1,
duration:300
}
).start();
}
line1 = minmax[0];
if(minmax.length > 1){
line2 = minmax[1];
}else{
line2 = {min:'', max:''};
}
}else{
view = view + inc;
if(view == -2){
view = (lines.length - 1) + dots.length;
}
for(let x = 0; x < lines.length; x++){
if(lines[x].show == true){
if(x != view){
//fade out lines
lines[x].show = false;
Animated.timing(
this.state.lines[x].opacity,
{
toValue:0,
duration:300
}
).start();
}
}else{
if(x == view){
//fade in line
lines[x].show = true;
Animated.timing(
this.state.lines[x].opacity,
{
toValue:1,
duration:300
}
).start();
}
}
}
if(view < lines.length){
//hide dot
line1 = minmax[view];
line2 = {min:'', max:minmax[view].name};
if(this.state.dots.length > 0){
Animated.timing(
this.state.dots[0].opacity,
{
toValue:0,
duration:300
}
).start();
}
}else{
//show dot instead of line
Animated.timing(
this.state.dots[0].opacity,
{
toValue:1,
duration:300
}
).start();
line1 = dotsminmax[0];
line2 = {min:'', max:dotsminmax[0].name};
}
}
this.setState({view:view, lines:lines, line1:line1, line2:line2});
}
render(){
return (
<ScrollView onLayout={this.onLayout} horizontal={true} pagingEnabled={true} showsHorizontalScrollIndicator={false}>
<View style={[this.styles.chartContainer, {width:this.width, paddingHorizontal:this.state.padding - 5}]}>
<TouchableWithoutFeedback onPress={this.onPressChart}>
<View style={{height:this.state.height, width:this.width - this.state.padding}}>
<View style={this.styles.chartLine1MinMax}>
<Text style={[this.styles.chartLabel, this.styles.chartLineMax]}>{this.state.line1.max}</Text>
<Text style={[this.styles.chartLabel, this.styles.chartLineMin]}>{this.state.line1.min}</Text>
</View>
<View style={this.styles.chartLine2MinMax}>
<Text style={[this.styles.chartLabel, this.styles.chartLineMax, this.styles.chartLabelEnd]}>{this.state.line2.max}</Text>
<Text style={[this.styles.chartLabel, this.styles.chartLineMin, this.styles.chartLabelEnd]}>{this.state.line2.min}</Text>
</View>
<View style={[this.styles.chart]}>
{this.state.lines.map(line => { return (
<Animated.View
key={line.name+(Math.round(9999 * Math.random()))}
style={[this.styles.chartLine, {opacity:line.opacity, left:line.x, top:line.y}]}
>{line.line}</Animated.View>
);}).reverse()}
{this.state.dots.map(dot => { return (
<Animated.View key='dots' style={[this.styles.chartDots, {opacity:dot.opacity}]}>{dot.dot}</Animated.View>
);})}
</View>
<Text style={this.styles.chartName}>{this.state.chart.name}</Text>
</View>
</TouchableWithoutFeedback>
</View>
{this.props.extraPage &&
<View style={[{width:this.width, height:this.state.height + 5, padding:this.state.padding}]}>
{this.props.extraPage}
<Text style={this.styles.legendName}>{this.state.chart.name}</Text>
<View style={this.styles.legendArrows}>
<IconSwipeArrow direction="next" size="xxsmall" opacity={0.15}/>
</View>
</View>
}
{this.state.legend}
</ScrollView>
);
}
styles = StyleSheet.create({
chartContainer: {paddingBottom:20, paddingTop:5, width:'100%'},
chart:{position:'absolute', width:'100%', height:'100%', top:15, left:-5},
chartName: {position:'absolute', bottom:0, fontSize:20, width:'100%', left:-10, textAlign:'center'},
chartLine:{position:'absolute', height:'100%'},
chartLineMax:{position:'absolute', top:0},
chartLineMin:{position:'absolute', bottom:0},
chartLine1MinMax:{position:'absolute', height:'100%'},
chartLine2MinMax:{position:'absolute', height:'100%', right:20, alignItems:'flex-end'},
chartLabel:{fontSize:20, opacity:0.5},
chartLabelEnd:{textAlign:'right'},
chartDots:{position:'absolute'},
legendContainer:{flexDirection:'row', flexWrap:'wrap'},
legendItem:{flex:1, alignSelf:'flex-start', flexDirection:'row'},
legendItemIcon:{paddingRight:10, paddingTop:7, height:20},
legendItemLabel:{},
legendItemText:{fontSize:17},
legendName:{position:'absolute', width:'100%', bottom:0, fontSize:20, left:30, textAlign:'center', alignSelf:'center'},
legendArrows:{position:'absolute', width:'100%', bottom:0, flexDirection:'row', justifyContent:'flex-end', left:30},
legendArrowBack:{opacity:0.3},
legendArrowNext:{opacity:0.3}
});
}
|
actor-apps/app-web/src/app/index.js
|
JeeLiu/actor-platform
|
import crosstab from 'crosstab';
import React from 'react';
import Router from 'react-router';
import Raven from 'utils/Raven'; // eslint-disable-line
import injectTapEventPlugin from 'react-tap-event-plugin';
import Deactivated from 'components/Deactivated.react';
import Login from 'components/Login.react';
import Main from 'components/Main.react';
import JoinGroup from 'components/JoinGroup.react';
import LoginStore from 'stores/LoginStore';
import LoginActionCreators from 'actions/LoginActionCreators';
//import AppCache from 'utils/AppCache'; // eslint-disable-line
import Pace from 'pace';
Pace.start({
ajax: false,
restartOnRequestAfter: false,
restartOnPushState: false
});
const DefaultRoute = Router.DefaultRoute;
const Route = Router.Route;
const RouteHandler = Router.RouteHandler;
const ActorInitEvent = 'concurrentActorInit';
if (crosstab.supported) {
crosstab.on(ActorInitEvent, (msg) => {
if (msg.origin !== crosstab.id && window.location.hash !== '#/deactivated') {
window.location.assign('#/deactivated');
window.location.reload();
}
});
}
const initReact = () => {
if (window.location.hash !== '#/deactivated') {
if (crosstab.supported) {
crosstab.broadcast(ActorInitEvent, {});
}
if (location.pathname === '/app/index.html') {
window.messenger = new window.actor.ActorApp(['ws://' + location.hostname + ':9080/']);
} else {
window.messenger = new window.actor.ActorApp();
}
}
const App = React.createClass({
render() {
return <RouteHandler/>;
}
});
const routes = (
<Route handler={App} name="app" path="/">
<Route handler={Main} name="main" path="/"/>
<Route handler={JoinGroup} name="join" path="/join/:token"/>
<Route handler={Login} name="login" path="/auth"/>
<Route handler={Deactivated} name="deactivated" path="/deactivated"/>
<DefaultRoute handler={Main}/>
</Route>
);
const router = Router.run(routes, Router.HashLocation, function (Handler) {
injectTapEventPlugin();
React.render(<Handler/>, document.getElementById('actor-web-app'));
});
if (window.location.hash !== '#/deactivated') {
if (LoginStore.isLoggedIn()) {
LoginActionCreators.setLoggedIn(router, {redirect: false});
}
}
};
window.jsAppLoaded = () => {
setTimeout(initReact, 0);
};
|
app/containers/SideBar/PermissionsNavTree.js
|
klpdotorg/tada-frontend
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import TreeView from 'react-treeview';
import { Link } from 'react-router';
import { capitalize } from '../../utils';
import { filterBoundaries } from './utils';
import {
collapsedProgramEntity,
getBoundariesEntities,
openPermissionBoundary,
} from '../../actions/';
import { Loading, Message } from '../../components/common';
class NavTree extends Component {
componentDidMount() {
this.props.getBoundariesEntities([{ depth: 0, uniqueId: this.props.parentId }]);
}
getTreeNodes(index) {
const nodes = this.props.entitiesByParentId[index];
if (nodes) {
const updatedNodes = nodes.map((node) => {
return { entity: this.props.entities[node], uniqueId: node };
});
if (index !== 0) {
return updatedNodes;
}
const filterEntities = filterBoundaries(updatedNodes, this.props.selectedPrimary);
return filterEntities;
}
return [];
}
renderLabel(node, depth, collapsed) {
const { entity } = node;
const label =
capitalize(entity.label) || capitalize(entity.name) || capitalize(entity.first_name);
return (
<Link
key={entity.name || entity.id}
tabIndex="0"
onClick={() => {
if (!collapsed) {
this.props.getBoundariesEntities([
{
id: entity.id,
depth,
uniqueId: node.uniqueId,
},
]);
}
this.props.openBoundary(node.uniqueId, depth);
}}
>
<span>{label}</span>
</Link>
);
}
renderSubTree(node, index, depth) {
const newDepth = depth + 1;
const { entity } = node;
const treeNodes = this.getTreeNodes(newDepth);
const collapsed = this.props.uncollapsed[newDepth] === node.uniqueId;
const name = this.renderLabel(node, newDepth, collapsed);
if (depth >= 2) {
return <span key={index} />;
}
return (
<TreeView
key={index}
onClick={() => {
this.props.getBoundariesEntities([
{
id: entity.id,
depth: newDepth,
uniqueId: node.uniqueId,
},
]);
}}
nodeLabel={name}
collapsed={!collapsed}
>
{depth <= 2 && collapsed ? (
treeNodes.map((child, i) => {
return this.renderSubTree(child, i + 1, newDepth);
})
) : (
<div />
)}
{!treeNodes.length && this.props.loading ? <Loading /> : <span />}
</TreeView>
);
}
renderBoundariesState(length) {
if (this.props.loading && !length) {
return <Loading />;
}
if (!length) {
return <Message message="No Boundaries Found" />;
}
return <span />;
}
render() {
const nodes = this.getTreeNodes(0);
return (
<div>
{nodes.map((element, i) => {
return this.renderSubTree(element, i, 0);
})}
{this.renderBoundariesState(nodes.length)}
</div>
);
}
}
const mapStateToProps = (state) => {
return {
entities: state.boundaries.boundaryDetails,
entitiesByParentId: state.boundaries.boundariesByParentId,
uncollapsed: state.boundaries.uncollapsedEntities,
loading: state.appstate.loadingBoundary,
selectedPrimary: state.schoolSelection.primarySchool,
parentId: state.profile.parentNodeId,
};
};
NavTree.propTypes = {
getBoundariesEntities: PropTypes.func,
uncollapsed: PropTypes.object,
entitiesByParentId: PropTypes.object,
entities: PropTypes.object,
openBoundary: PropTypes.func,
loading: PropTypes.bool,
selectedPrimary: PropTypes.bool,
parentId: PropTypes.string,
};
const PermissionsNavTree = connect(mapStateToProps, {
collapsedProgramEntity,
getBoundariesEntities,
openBoundary: openPermissionBoundary,
})(NavTree);
export { PermissionsNavTree };
|
pootle/static/js/admin/components/Language/LanguageAdd.js
|
phlax/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 LanguageForm from './LanguageForm';
const LanguageAdd = React.createClass({
propTypes: {
collection: React.PropTypes.object.isRequired,
model: React.PropTypes.func.isRequired,
onCancel: React.PropTypes.func.isRequired,
onSuccess: React.PropTypes.func.isRequired,
},
render() {
const Model = this.props.model;
return (
<div className="item-add">
<div className="hd">
<h2>{gettext('Add Language')}</h2>
<button
onClick={this.props.onCancel}
className="btn btn-primary"
>
{gettext('Cancel')}
</button>
</div>
<div className="bd">
<LanguageForm
model={new Model()}
collection={this.props.collection}
onSuccess={this.props.onSuccess}
/>
</div>
</div>
);
},
});
export default LanguageAdd;
|
test/helpers/shallowRenderHelper.js
|
Aleczhang1992/gallery-by-react
|
/**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
internals/templates/containers/HomePage/index.js
|
mhoffman/CatAppBrowser
|
/*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
src/index.js
|
wmaurer/frontend_pizza_react_redux
|
import 'babel-polyfill';
require('./app.css');
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './containers/App';
import DevTools from './containers/DevTools';
import configureStore from './store/configureStore';
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<div>
<App />
<DevTools />
</div>
</Provider>,
document.getElementById('root')
);
|
ReactComponents/CauseListView.js
|
DoSomething/LetsDoThis-iOS
|
'use strict';
import React from 'react';
import {
AppRegistry,
ListView,
StyleSheet,
Text,
Image,
RefreshControl,
TouchableHighlight,
View
} from 'react-native';
var Style = require('./Style.js');
var Bridge = require('react-native').NativeModules.LDTReactBridge;
var NetworkErrorView = require('./NetworkErrorView.js');
var NetworkLoadingView = require('./NetworkLoadingView.js')
var CauseListView = React.createClass({
getInitialState: function() {
return {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
isRefreshing: false,
loaded: false,
error: false,
};
},
componentDidMount: function() {
this.fetchData();
},
fetchData: function() {
this.setState({
error: false,
loaded: false,
});
fetch(this.props.url)
.then((response) => response.json())
.catch((error) => this.catchError(error))
.then((responseData) => {
if (!responseData) {
return;
}
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.categories),
loaded: true,
});
})
.done();
},
catchError: function(error) {
console.log("CauseListView.catchError");
this.setState({
error: error,
});
},
render: function() {
if (this.state.error) {
return (
<NetworkErrorView
title="Actions aren't loading right now"
retryHandler={this.fetchData}
errorMessage={this.state.error.message}
/>);
}
if (!this.state.loaded) {
return <NetworkLoadingView text="Loading actions..." />;
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
refreshControl={<RefreshControl
onRefresh={this._onRefresh}
refreshing={this.state.isRefreshing}
tintColor="#CCC" />}
/>
);
},
_onRefresh: function () {
this.setState({isRefreshing: true});
setTimeout(() => {
this.fetchData();
this.setState({
isRefreshing: false,
});
}, 1000);
},
_onPressRow(cause) {
Bridge.pushCause(cause);
},
renderRow: function(cause) {
var causeColorStyle = {backgroundColor: '#' + cause.hex};
return (
<TouchableHighlight onPress={() => this._onPressRow(cause)}>
<View style={styles.row}>
<View style={[styles.causeColor, causeColorStyle]} />
<View style={[styles.contentContainer, styles.bordered]}>
<View>
<Text style={Style.textHeading}>{cause.title}</Text>
</View>
</View>
<View style={[styles.arrowContainer, styles.bordered]}>
<Image
style={styles.arrowImage}
source={require('image!Arrow')}
/>
</View>
</View>
</TouchableHighlight>
);
},
});
var styles = StyleSheet.create({
listView: {
backgroundColor: '#FFFFFF',
paddingBottom: 10,
},
row: {
backgroundColor: '#FFFFFF',
flex: 1,
flexDirection: 'row',
},
causeColor: {
width: 8,
backgroundColor: '#00FF00',
height: 84,
},
bordered: {
borderColor: '#EDEDED',
borderTopWidth: 2,
borderBottomWidth: 2,
},
contentContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
paddingLeft: 8,
height: 84,
},
arrowContainer: {
width: 38,
height: 84,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
},
arrowImage: {
width: 12,
height: 21,
},
});
module.exports = CauseListView;
|
src/modules/Checkbox/Checkbox.js
|
shengnian/shengnian-ui-react
|
import cx from 'classnames'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import {
AutoControlledComponent as Component,
createHTMLLabel,
customPropTypes,
getElementType,
getUnhandledProps,
makeDebugger,
META,
partitionHTMLInputProps,
useKeyOnly,
} from '../../lib'
const debug = makeDebugger('checkbox')
/**
* A checkbox allows a user to select a value from a small set of options, often binary.
* @see Form
* @see Radio
*/
export default class Checkbox extends Component {
static propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Whether or not checkbox is checked. */
checked: PropTypes.bool,
/** Additional classes. */
className: PropTypes.string,
/** The initial value of checked. */
defaultChecked: PropTypes.bool,
/** Whether or not checkbox is indeterminate. */
defaultIndeterminate: PropTypes.bool,
/** A checkbox can appear disabled and be unable to change states */
disabled: PropTypes.bool,
/** Removes padding for a label. Auto applied when there is no label. */
fitted: PropTypes.bool,
/** Whether or not checkbox is indeterminate. */
indeterminate: PropTypes.bool,
/** The text of the associated label element. */
label: customPropTypes.itemShorthand,
/** The HTML input name. */
name: PropTypes.string,
/**
* Called when the user attempts to change the checked state.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and proposed checked/indeterminate state.
*/
onChange: PropTypes.func,
/**
* Called when the checkbox or label is clicked.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and current checked/indeterminate state.
*/
onClick: PropTypes.func,
/**
* Called when the user presses down on the mouse.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and current checked/indeterminate state.
*/
onMouseDown: PropTypes.func,
/** Format as a radio element. This means it is an exclusive option. */
radio: customPropTypes.every([
PropTypes.bool,
customPropTypes.disallow(['slider', 'toggle']),
]),
/** A checkbox can be read-only and unable to change states. */
readOnly: PropTypes.bool,
/** Format to emphasize the current selection state. */
slider: customPropTypes.every([
PropTypes.bool,
customPropTypes.disallow(['radio', 'toggle']),
]),
/** A checkbox can receive focus. */
tabIndex: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
/** Format to show an on or off choice. */
toggle: customPropTypes.every([
PropTypes.bool,
customPropTypes.disallow(['radio', 'slider']),
]),
/** HTML input type, either checkbox or radio. */
type: PropTypes.oneOf(['checkbox', 'radio']),
/** The HTML input value. */
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
}
static defaultProps = {
type: 'checkbox',
}
static autoControlledProps = [
'checked',
'indeterminate',
]
static _meta = {
name: 'Checkbox',
type: META.TYPES.MODULE,
}
componentDidMount() {
this.setIndeterminate()
}
componentDidUpdate() {
this.setIndeterminate()
}
canToggle = () => {
const { disabled, radio, readOnly } = this.props
const { checked } = this.state
return !disabled && !readOnly && !(radio && checked)
}
computeTabIndex = () => {
const { disabled, tabIndex } = this.props
if (!_.isNil(tabIndex)) return tabIndex
return disabled ? -1 : 0
}
handleInputRef = c => (this.inputRef = c)
handleClick = (e) => {
debug('handleClick()')
const { checked, indeterminate } = this.state
if (!this.canToggle()) return
_.invoke(this.props, 'onClick', e, { ...this.props, checked: !checked, indeterminate: !!indeterminate })
_.invoke(this.props, 'onChange', e, { ...this.props, checked: !checked, indeterminate: false })
this.trySetState({ checked: !checked, indeterminate: false })
}
handleMouseDown = (e) => {
debug('handleMouseDown()')
const { checked, indeterminate } = this.state
_.invoke(this.props, 'onMouseDown', e, { ...this.props, checked: !!checked, indeterminate: !!indeterminate })
_.invoke(this.inputRef, 'focus')
e.preventDefault()
}
// Note: You can't directly set the indeterminate prop on the input, so we
// need to maintain a ref to the input and set it manually whenever the
// component updates.
setIndeterminate = () => {
const { indeterminate } = this.state
if (this.inputRef) this.inputRef.indeterminate = !!indeterminate
}
render() {
const {
className,
disabled,
label,
name,
radio,
readOnly,
slider,
toggle,
type,
value,
} = this.props
const { checked, indeterminate } = this.state
const classes = cx(
'ui',
useKeyOnly(checked, 'checked'),
useKeyOnly(disabled, 'disabled'),
useKeyOnly(indeterminate, 'indeterminate'),
// auto apply fitted class to compact white space when there is no label
// https://shengnian.github.io/modules/checkbox.html#fitted
useKeyOnly(!label, 'fitted'),
useKeyOnly(radio, 'radio'),
useKeyOnly(readOnly, 'read-only'),
useKeyOnly(slider, 'slider'),
useKeyOnly(toggle, 'toggle'),
'checkbox',
className,
)
const unhandled = getUnhandledProps(Checkbox, this.props)
const ElementType = getElementType(Checkbox, this.props)
const [htmlInputProps, rest] = partitionHTMLInputProps(unhandled, { htmlProps: [] })
return (
<ElementType
{...rest}
className={classes}
onChange={this.handleClick}
onClick={this.handleClick}
onMouseDown={this.handleMouseDown}
>
<input
{...htmlInputProps}
checked={checked}
className='hidden'
name={name}
readOnly
ref={this.handleInputRef}
tabIndex={this.computeTabIndex()}
type={type}
value={value}
/>
{/*
Heads Up!
Do not remove empty labels, they are required by SUI CSS
*/}
{createHTMLLabel(label) || <label />}
</ElementType>
)
}
}
|
app/javascript/mastodon/components/modal_root.js
|
rainyday/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import 'wicg-inert';
export default class ModalRoot extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
onClose: PropTypes.func.isRequired,
};
state = {
revealed: !!this.props.children,
};
activeElement = this.state.revealed ? document.activeElement : null;
handleKeyUp = (e) => {
if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27)
&& !!this.props.children) {
this.props.onClose();
}
}
handleKeyDown = (e) => {
if (e.key === 'Tab') {
const focusable = Array.from(this.node.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter((x) => window.getComputedStyle(x).display !== 'none');
const index = focusable.indexOf(e.target);
let element;
if (e.shiftKey) {
element = focusable[index - 1] || focusable[focusable.length - 1];
} else {
element = focusable[index + 1] || focusable[0];
}
if (element) {
element.focus();
e.stopPropagation();
e.preventDefault();
}
}
}
componentDidMount () {
window.addEventListener('keyup', this.handleKeyUp, false);
window.addEventListener('keydown', this.handleKeyDown, false);
}
componentWillReceiveProps (nextProps) {
if (!!nextProps.children && !this.props.children) {
this.activeElement = document.activeElement;
this.getSiblings().forEach(sibling => sibling.setAttribute('inert', true));
} else if (!nextProps.children) {
this.setState({ revealed: false });
}
}
componentDidUpdate (prevProps) {
if (!this.props.children && !!prevProps.children) {
this.getSiblings().forEach(sibling => sibling.removeAttribute('inert'));
// Because of the wicg-inert polyfill, the activeElement may not be
// immediately selectable, we have to wait for observers to run, as
// described in https://github.com/WICG/inert#performance-and-gotchas
Promise.resolve().then(() => {
this.activeElement.focus();
this.activeElement = null;
}).catch((error) => {
console.error(error);
});
}
if (this.props.children) {
requestAnimationFrame(() => {
this.setState({ revealed: true });
});
}
}
componentWillUnmount () {
window.removeEventListener('keyup', this.handleKeyUp);
window.removeEventListener('keydown', this.handleKeyDown);
}
getSiblings = () => {
return Array(...this.node.parentElement.childNodes).filter(node => node !== this.node);
}
setRef = ref => {
this.node = ref;
}
render () {
const { children, onClose } = this.props;
const { revealed } = this.state;
const visible = !!children;
if (!visible) {
return (
<div className='modal-root' ref={this.setRef} style={{ opacity: 0 }} />
);
}
return (
<div className='modal-root' ref={this.setRef} style={{ opacity: revealed ? 1 : 0 }}>
<div style={{ pointerEvents: visible ? 'auto' : 'none' }}>
<div role='presentation' className='modal-root__overlay' onClick={onClose} />
<div role='dialog' className='modal-root__container'>{children}</div>
</div>
</div>
);
}
}
|
src/components/Icon/Icon-story.js
|
joshblack/carbon-components-react
|
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { iconAdd, iconAddSolid, iconAddOutline } from 'carbon-icons';
import { storiesOf } from '@storybook/react';
import { withKnobs, select, text } from '@storybook/addon-knobs';
import Icon from '../Icon';
import IconSkeleton from '../Icon/Icon.Skeleton';
const icons = {
'Add (iconAdd from `carbon-icons`)': 'iconAdd',
'Add with filled circle (iconAddSolid from `carbon-icons`)': 'iconAddSolid',
'Add with circle (iconAddOutline from `carbon-icons`)': 'iconAddOutline',
};
const iconMap = {
iconAdd,
iconAddSolid,
iconAddOutline,
};
const props = () => {
const selectedIcon = select(
'The icon (icon (regular)/name (legacy))',
icons,
'iconAdd'
);
return {
style: {
margin: '50px',
},
icon: iconMap[selectedIcon],
name: iconMap[selectedIcon] ? undefined : selectedIcon,
role: text('ARIA role (role)', ''),
fill: text('The SVG `fill` attribute (fill)', 'grey'),
fillRule: text('The SVG `fillRule` attribute (fillRule)', ''),
width: text('The SVG `width` attribute (width)', ''),
height: text('The SVG `height` attribute (height)', ''),
description: text(
'The a11y text (description)',
'This is a description of the icon and what it does in context'
),
iconTitle: text('The content in <title> in SVG (iconTitle)', ''),
className: 'extra-class',
};
};
const propsSkeleton = {
style: {
margin: '50px',
},
};
const propsSkeleton2 = {
style: {
margin: '50px',
width: '24px',
height: '24px',
},
};
storiesOf('Icon', module)
.addDecorator(withKnobs)
.add(
'Default',
() => (
<div>
<Icon {...props()} />
</div>
),
{
info: {
text: `
Icons are used in the product to present common actions and commands. Modify the fill property to change the color of the icon. The name property defines which icon to display. For accessibility, provide a context-rich description with the description prop. For a full list of icon names, see carbondesignsystem.com/style/iconography/library
`,
},
}
)
.add(
'Skeleton',
() => (
<div>
<IconSkeleton {...propsSkeleton} />
<IconSkeleton {...propsSkeleton2} />
</div>
),
{
info: {
text: `
Icons are used in the product to present common actions and commands. Modify the fill property to change the color of the icon. The name property defines which icon to display. For accessibility, provide a context-rich description with the description prop. For a full list of icon names, see carbondesignsystem.com/style/iconography/library
`,
},
}
);
|
blueocean-material-icons/src/js/components/svg-icons/action/info.js
|
kzantow/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionInfo = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
</SvgIcon>
);
ActionInfo.displayName = 'ActionInfo';
ActionInfo.muiName = 'SvgIcon';
export default ActionInfo;
|
src/components/TextInputStyledComponents/TextInputStyledComponents.js
|
thomashoggard/ps-react-tom
|
import React from 'react';
import PropTypes from 'prop-types';
import Label from '../Label';
import styled from 'styled-components';
/** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */
function TextInput({ htmlId, name, label, type = "text", required = false, onChange, placeholder, value, error, children, ...props }) {
const Error = styled.div`
color: red;
`;
const Input = styled.input`
border: ${error && 'solid 1px red'};
display: block;
`;
const Fieldset = styled.div`
margin-bottom: 16px;
`;
return (
<Fieldset>
<Label htmlFor={htmlId} label={label} required={required} />
<Input
id={htmlId}
type={type}
name={name}
placeholder={placeholder}
value={value}
onChange={onChange}
{...props} />
{children}
{error && <Error>{error}</Error>}
</Fieldset>
);
};
TextInput.propTypes = {
/** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */
htmlId: PropTypes.string.isRequired,
/** Input name. Recommend setting this to match object's property so a single change handler can be used. */
name: PropTypes.string.isRequired,
/** Input label */
label: PropTypes.string.isRequired,
/** Input type */
type: PropTypes.oneOf(['text', 'number', 'password']),
/** Mark label with asterisk if set to true */
required: PropTypes.bool,
/** Function to call onChange */
onChange: PropTypes.func.isRequired,
/** Placeholder to display when empty */
placeholder: PropTypes.string,
/** Value */
value: PropTypes.any,
/** String to display when error occurs */
error: PropTypes.string,
/** Child component to display next to the input */
children: PropTypes.node
};
export default TextInput;
|
packages/icons/src/dv/Vue.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function DvVue(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M45 5.831L24 42.169 3 5.831h3.413L24 36.264 41.587 5.83H45zm-21 8.264l4.855-8.264h7.363L24 26.973 11.782 5.831h7.363L24 14.095z" />
</IconBase>
);
}
export default DvVue;
|
demo/index.js
|
JulienPradet/react-flip
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { HashRouter } from 'react-router-dom';
import Navigation from './Navigation';
import Examples from './Examples';
import './style/index.scss';
class App extends Component {
render() {
return (
<HashRouter>
<div>
<Navigation />
<Examples />
</div>
</HashRouter>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
|
app/components/Menu/MenuHeader.js
|
cdiezmoran/playgrounds-desktop
|
/**
* Created on Tue Nov 8 2016
*
* Side-bar menu header component containing the user profile pic and username
* and the search bar component.
*
* @flow
*/
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import jwtDecode from 'jwt-decode';
// import SearchBar from '../SearchBar';
class MenuHeader extends Component {
render() {
const token = localStorage.getItem('id_token');
const currentUser = jwtDecode(token);
return (
<div className="menu-header">
<div className="menu-user container">
<div className="row flex-items-xs-center center-align">
<Link to="/" className="menu-profile">
<img src={currentUser.profilePic} className="circular-img" alt="" />
<p className="username">
{currentUser.username}
</p>
</Link>
</div>
</div>
</div>
);
}
}
export default MenuHeader;
|
src/src/components/SideBar/Nav.js
|
chaitanya1375/Myprojects
|
import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { Collapse } from 'react-bootstrap';
class Nav extends Component {
state = {};
render() {
let { location } = this.props;
return (
<ul className="nav">
<li className={location.pathname === '/' ? 'active' : null}>
<Link to="/">
<i className="pe-7s-graph"></i>
<p>Dashboard</p>
</Link>
</li>
<li className={this.isPathActive('/charts') ? 'active' : null}>
<Link to="/charts">
<i className="pe-7s-graph"></i>
<p>Charts</p>
</Link>
</li>
</ul>
);
}
isPathActive(path) {
return this.props.location.pathname.startsWith(path);
}
}
export default withRouter(Nav);
|
src/Col.js
|
xsistens/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import styleMaps from './styleMaps';
import CustomPropTypes from './utils/CustomPropTypes';
const Col = React.createClass({
propTypes: {
/**
* The number of columns you wish to span
*
* for Extra small devices Phones (<768px)
*
* class-prefix `col-xs-`
*/
xs: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Small devices Tablets (≥768px)
*
* class-prefix `col-sm-`
*/
sm: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Medium devices Desktops (≥992px)
*
* class-prefix `col-md-`
*/
md: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Large devices Desktops (≥1200px)
*
* class-prefix `col-lg-`
*/
lg: React.PropTypes.number,
/**
* Move columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-offset-`
*/
xsOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-offset-`
*/
smOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-offset-`
*/
mdOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-offset-`
*/
lgOffset: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-push-`
*/
xsPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-push-`
*/
smPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-push-`
*/
mdPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-push-`
*/
lgPush: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Extra small devices Phones
*
* class-prefix `col-xs-pull-`
*/
xsPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Small devices Tablets
*
* class-prefix `col-sm-pull-`
*/
smPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Medium devices Desktops
*
* class-prefix `col-md-pull-`
*/
mdPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Large devices Desktops
*
* class-prefix `col-lg-pull-`
*/
lgPull: React.PropTypes.number,
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
componentClass: 'div'
};
},
render() {
let ComponentClass = this.props.componentClass;
let classes = {};
Object.keys(styleMaps.SIZES).forEach(function (key) {
let size = styleMaps.SIZES[key];
let prop = size;
let classPart = size + '-';
if (this.props[prop]) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Offset';
classPart = size + '-offset-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Push';
classPart = size + '-push-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Pull';
classPart = size + '-pull-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
}, this);
return (
<ComponentClass {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</ComponentClass>
);
}
});
export default Col;
|
node_modules/react-scripts/template/src/index.js
|
webtutorial/builder
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
src/components/performance/LineAndBarsChart.js
|
jmporchet/bravakin-client
|
import React from 'react';
import { AreaClosed, BarGroup, LinePath } from '@vx/shape';
import { Group } from '@vx/group';
import { AxisLeft, AxisBottom } from '@vx/axis';
import { scaleTime, scaleBand, scaleLinear, scaleOrdinal } from '@vx/scale';
import { curveMonotoneX } from '@vx/curve';
import { timeFormat } from 'd3-time-format';
import { extent, max } from 'd3-array';
import { Grid } from '@vx/grid';
// accessors
const xDate = d => d.date;
const yLine = d => d.engagement;
const yBar = d => Math.max(d.likes, d.comments)
export default ({
data,
width,
height,
margin = {
top: 10,
left: 50,
right: 20,
bottom: 100,
}
}) => {
if (width < 10) return null;
const keys = Object.keys(data[0]).filter(d => d !== 'date' && d !== 'followers' && d !== 'engagement');
const format = timeFormat("%H");
const formatDate = (date) => format(date);
// bounds
const xMax = width - margin.left - margin.right;
const yMax = height - margin.top - margin.bottom;
// Bar scales
// hours on x axis
const x0Scale = scaleBand({
rangeRound: [0, xMax],
domain: data.map(xDate),
padding: 0.1,
tickFormat: () => (val) => formatDate(val)
});
const x1Scale = scaleBand({
rangeRound: [0, x0Scale.bandwidth()],
domain: keys,
padding: 0.1
});
// colors for the bars
const zScale = scaleOrdinal({
domain: keys,
range: ['#aeeef8', '#e5fd3d']
});
// Engagement line scales
const xLineScale = scaleTime({
range: [0, xMax],
domain: extent(data, xDate),
});
const yLineScale = scaleLinear({
range: [yMax, 0],
domain: [0, max(data, yLine)],
nice: true,
});
const yBarScale = scaleLinear({
range: [yMax ,0],
domain: [0, max(data, yBar)],
nice: true,
})
// responsive utils for axis ticks
function numTicksForHeight(height) {
if (height <= 300) return 3;
if (300 < height && height <= 600) return 5;
return 10;
}
function numTicksForWidth(width) {
if (width <= 300) return 3;
if (300 < width && width <= 400) return 6;
return 12;
}
return (
<svg width={width} height={height} >
<Grid
top={margin.top}
left={margin.left}
xScale={xLineScale}
yScale={yLineScale}
stroke='#8a265f'
strokeDasharray='1,15'
width={xMax}
height={yMax}
numTicksRows={numTicksForHeight(height)}
numTicksColumns={numTicksForWidth(width)}
/>
<AxisLeft
top={margin.top}
left={margin.left}
scale={yLineScale}
hideZero
numTicks={numTicksForHeight(height)}
label={
<text
fill="#8e205f"
textAnchor="middle"
fontSize={10}
fontFamily="Arial"
>
likes
</text>
}
stroke="#1b1a1e"
tickLabelComponent={
<text
fill="#8e205f"
textAnchor="end"
fontSize={10}
fontFamily="Arial"
dx="-0.25em"
dy="0.25em"
/>
}
/>
<AxisBottom
scale={xLineScale}
top={height - margin.bottom}
left={margin.left}
numTicks={numTicksForWidth(width)}
stroke='#1b1a1e'
tickStroke='#1b1a1e'
tickLabelComponent={(
<text
fill="#8e205f"
textAnchor="middle"
fontSize={10}
fontFamily="Arial"
dy="0.25em"
/>
)}
/>
<BarGroup
top={margin.top}
left={margin.left}
data={data}
keys={keys}
height={yMax}
x0={xDate}
x0Scale={x0Scale}
x1Scale={x1Scale}
yScale={yBarScale}
zScale={zScale}
rx={4}
/>
<Group top={margin.top} left={margin.left+7}>
<AreaClosed
data={data}
xScale={x0Scale}
yScale={yLineScale}
x={xDate}
y={yLine}
strokeWidth={2}
stroke='transparent'
fill="url('#orangeRed')"
curve={curveMonotoneX}
/>
<LinePath
data={data}
xScale={x0Scale}
yScale={yLineScale}
x={xDate}
y={yLine}
stroke="url('#orangeRed')"
strokeWidth={2}
curve={curveMonotoneX}
/>
</Group>
</svg>
);
}
|
docs/src/app/components/pages/components/Menu/ExampleNested.js
|
owencm/material-ui
|
import React from 'react';
import Paper from 'material-ui/Paper';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import Divider from 'material-ui/Divider';
import ArrowDropRight from 'material-ui/svg-icons/navigation-arrow-drop-right';
const style = {
display: 'inline-block',
margin: '16px 32px 16px 0',
};
const MenuExampleNested = () => (
<div>
<Paper style={style}>
<Menu desktop={true} width={320}>
<MenuItem primaryText="Single" insetChildren={true} />
<MenuItem primaryText="1.15" insetChildren={true} />
<MenuItem primaryText="Double" insetChildren={true} />
<MenuItem
primaryText="Custom: 1.2"
checked={true}
rightIcon={<ArrowDropRight />}
menuItems={[
<MenuItem
primaryText="Show"
rightIcon={<ArrowDropRight />}
menuItems={[
<MenuItem primaryText="Show Level 2" />,
<MenuItem primaryText="Grid lines" checked={true} />,
<MenuItem primaryText="Page breaks" insetChildren={true} />,
<MenuItem primaryText="Rules" checked={true} />,
]}
/>,
<MenuItem primaryText="Grid lines" checked={true} />,
<MenuItem primaryText="Page breaks" insetChildren={true} />,
<MenuItem primaryText="Rules" checked={true} />,
]}
/>
<Divider />
<MenuItem primaryText="Add space before paragraph" />
<MenuItem primaryText="Add space after paragraph" />
<Divider />
<MenuItem primaryText="Custom spacing..." />
</Menu>
</Paper>
</div>
);
export default MenuExampleNested;
|
src/modules/pages/feeds/js/feedStore.js
|
lenxeon/react
|
import React from 'react';
let FeedStore = {
list(cat, page, size, cb) {
cat = cat || 'all';
page = page || 1;
size = size || 20;
$.get('/dist/data/feeds/list_' + cat + '.json', function(result) {
let list = result[0].card_group;
setTimeout(() => {
cb({
list: list
});
}, 500)
}.bind(this));
},
listTag(feedId, cb) {
let list = [];
for (let i = 0; i < 5; i++) {
list.push({
uuid: i,
name: '标签'+i
})
}
setTimeout(() => {
cb({
list: list
});
}, 500)
},
searchTag(val, cb) {
let list = [];
let size = Math.round(Math.random()*10)+1;
for (let i = 0; i < size; i++) {
list.push({
uuid: i,
name: 'tag:('+val+')'+i
})
}
setTimeout(() => {
cb({
list: list
});
}, 200)
},
saveTag(feedId, tagId, tagName, cb) {
setTimeout(() => {
cb({
uuid: 'global',
cli_uuid: tagId,
name: tagName
});
}, 500)
},
}
export default FeedStore;
|
client/app/components/MapPage.js
|
BeaconCorp/beacon
|
import React from 'react';
import { Link } from 'react-router';
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';
import { getAllBeacons } from '../utils/helpers';
var MapPage = React.createClass({
getInitialState: () => {
console.log('MapPage.getInitialState()');
return {
beacons: [],
};
},
componentDidMount: function () {
console.log('MapPage.componentDidMount()');
navigator.geolocation.getCurrentPosition((data) => {
getAllBeacons(data.coords.latitude, data.coords.longitude)
.then((response) => {
console.log('MapPage.componentDidMount(), got location successfully.',
response);
this.setState({ beacons: response.data });
this.renderBeacons();
});
});
},
renderBeacons: function () {
console.log('MapPage.renderBeacons()', this.state.beacons);
let beacons = this.state.beacons.map((beacon, index) => {
let position = [beacon.lat, beacon.lng];
return (
<Marker position={position} key={index}>
<Popup>
<div>
<h3>{beacon.title}</h3>
<p>{beacon.description}</p>
<p>{beacon.topics}</p>
</div>
</Popup>
</Marker>
);
});
return beacons;
},
render: function () {
const position = [43.044591, -76.150566]; // tech garden
const mapStyle = { height: '100%' };
return (
<div className="map">
<Map center={position} zoom={12} style={mapStyle}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
{ this.renderBeacons() }
</Map>
<Link to='new-beacon' className="btn btn-primary btn-fab add-beacon">
<i className="material-icons">+</i>
</Link>
</div>
);
},
});
module.exports = MapPage;
|
clients/libs/slate-editor-list-plugin/src/ListButtonBar.js
|
nossas/bonde-client
|
/* eslint-disable no-undef */
import React from 'react'
import { UnorderedListButton, OrderedListButton } from './'
// FIXME: Needs to handle assets files to work with SSR
// eslint-disable-next-line @typescript-eslint/no-var-requires
if (require('exenv').canUseDOM) require('./ListButtonBar.module.css')
const ListButtonBar = props => (
<div className='slate-list-plugin--button-bar'>
<UnorderedListButton {...props} />
<OrderedListButton {...props} />
</div>
)
export default ListButtonBar
|
src/client/components/Note.js
|
ampext/graphql-notes
|
import React from 'react';
import PropTypes from 'prop-types';
import { createFragmentContainer } from 'react-relay';
import Button from './Button';
class Note extends React.PureComponent {
onRemoveButton = () => this.props.onRemove(this.props.item.id);
onEditButton = () => {
const {id, content, date} = this.props.item;
this.props.onEdit(id, content);
};
render() {
const {content, date} = this.props.item;
const classNames = ['note'];
if (this.props.highlighted) {
classNames.push('note--highlighted');
}
return (
<div className='note-container'>
<div className='note-container__avatar' />
<div className='note-container__body'>
<div className={classNames.join(' ')}>
<span className='note__content'>{content}</span>
<Button key='edit' faName='fa-pencil' onClick={this.onEditButton} />
<Button key='remove' faName='fa-times' onClick={this.onRemoveButton} />
</div>
<span className='note-container__date'>{new Date(date).toLocaleString()}</span>
</div>
</div>
);
}
}
Note.propTypes = {
item: PropTypes.object,
highlighted: PropTypes.bool,
onRemove: PropTypes.func,
onEdit: PropTypes.func
};
export default createFragmentContainer(Note,
graphql`
fragment Note_item on Note {
id,
content,
date
}
`
);
|
packages/mineral-ui-icons/src/IconMonochromePhotos.js
|
mineral-ui/mineral-ui
|
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconMonochromePhotos(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M20 5h-3.2L15 3H9L7.2 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 14h-8v-1c-2.8 0-5-2.2-5-5s2.2-5 5-5V7h8v12zm-3-6c0-2.8-2.2-5-5-5v1.8c1.8 0 3.2 1.4 3.2 3.2s-1.4 3.2-3.2 3.2V18c2.8 0 5-2.2 5-5zm-8.2 0c0 1.8 1.4 3.2 3.2 3.2V9.8c-1.8 0-3.2 1.4-3.2 3.2z"/>
</g>
</Icon>
);
}
IconMonochromePhotos.displayName = 'IconMonochromePhotos';
IconMonochromePhotos.category = 'image';
|
src/components/__tests__/placeholder-test.js
|
shwethadn/StarterApp
|
/**
* Test to check if the component renderes correctly
*/
/* global it expect */
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import Soon from '../general/Placeholder';
/**
* Check if alerts renders correcly
* and asserting it to the matching snapshot
*/
it('Soon renders correcly', () => {
const tree = renderer.create(
<Soon navigator={{ push: () => {} }} />
).toJSON();
expect(tree).toMatchSnapshot();
});
|
src/scripts/views/detailView.js
|
sharnee/instaClone
|
import React from 'react'
import Header from './header'
import Footer from './footer'
// import Likes from './likes'
import CommentsHeader from './commentsHeader'
import Comments from './comments'
import Image from './image'
var DetailView = React.createClass({
render: function() {
return (
<div className="detail-body-container">
<Header />
<div className="flex-wrapper">
<ImagePost model={this.props.model} />
</div>
<Footer />
</div>
)
}
})
var ImagePost = React.createClass({
render: function() {
var detailData = this.props.model
return (
<section className="image-wrapper">
<div className="image-container">
<Image model={this.props.model} />
</div>
<div className="details-container">
<CommentsHeader model={this.props.model} />
<Comments model={this.props.model} />
</div>
</section>
)
}
})
export default DetailView
|
src/Jumbotron.js
|
dongtong/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import CustomPropTypes from './utils/CustomPropTypes';
const Jumbotron = React.createClass({
propTypes: {
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return { componentClass: 'div' };
},
render() {
const ComponentClass = this.props.componentClass;
return (
<ComponentClass {...this.props} className={classNames(this.props.className, 'jumbotron')}>
{this.props.children}
</ComponentClass>
);
}
});
export default Jumbotron;
|
packages/spust-koa/src/BodyParser.js
|
michalkvasnicak/spust
|
// @flow
import koaBodyParser from 'koa-bodyparser';
import React from 'react';
import { type Context as ServerContext, serverContextType } from './Server';
export default class BodyParser extends React.Component<void, *, void> {
static contextTypes = serverContextType;
context: ServerContext;
constructor(props: any, context: ServerContext) {
super(props, context);
this.context.use(koaBodyParser());
}
render() {
return null;
}
}
|
src/svg-icons/notification/confirmation-number.js
|
barakmitz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationConfirmationNumber = (props) => (
<SvgIcon {...props}>
<path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z"/>
</SvgIcon>
);
NotificationConfirmationNumber = pure(NotificationConfirmationNumber);
NotificationConfirmationNumber.displayName = 'NotificationConfirmationNumber';
NotificationConfirmationNumber.muiName = 'SvgIcon';
export default NotificationConfirmationNumber;
|
custom_modules/Picture.js
|
hustmsc/hustmsc-app
|
import React, { Component } from 'react';
import {
StyleSheet,
Image
} from 'react-native';
export default class Picture extends Component {
render() {
return (
<Image source={this.props.src} style={styles.images} />
);
}
}
const styles = StyleSheet.create({
images: {
width: 193,
height: 110,
},
});
|
app/components/Form/FormField.js
|
acebusters/ab-web
|
import React from 'react';
import PropTypes from 'prop-types';
import FormGroup from './FormGroup';
import Input from '../Input';
import Label from '../Label';
import { ErrorMessage, WarningMessage } from '../../components/FormMessages';
const FormField = ({ input, label, type, meta: { touched, error, warning }, ...props }) => (
<FormGroup>
<Label htmlFor={input.name}>{label}</Label>
<Input {...input} {...props} type={type} id={input.name} />
{touched && error && <ErrorMessage error={error} />}
{touched && warning && <WarningMessage error={warning} />}
</FormGroup>
);
FormField.propTypes = {
input: PropTypes.object,
label: PropTypes.node,
type: PropTypes.string,
meta: PropTypes.object,
};
export default FormField;
|
src/svg-icons/social/sentiment-dissatisfied.js
|
ichiohta/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialSentimentDissatisfied = (props) => (
<SvgIcon {...props}>
<circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-6c-2.33 0-4.32 1.45-5.12 3.5h1.67c.69-1.19 1.97-2 3.45-2s2.75.81 3.45 2h1.67c-.8-2.05-2.79-3.5-5.12-3.5z"/>
</SvgIcon>
);
SocialSentimentDissatisfied = pure(SocialSentimentDissatisfied);
SocialSentimentDissatisfied.displayName = 'SocialSentimentDissatisfied';
SocialSentimentDissatisfied.muiName = 'SvgIcon';
export default SocialSentimentDissatisfied;
|
js/src/ui/ModalBox/summary.js
|
nipunn1313/parity
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
import React from 'react';
import { nodeOrStringProptype } from '~/util/proptypes';
import styles from './modalBox.css';
export default function Summary ({ summary }) {
if (!summary) {
return null;
}
return (
<div className={ styles.summary }>
{ summary }
</div>
);
}
Summary.propTypes = {
summary: nodeOrStringProptype()
};
|
admin/client/views/signin.js
|
Ftonso/keystone
|
'use strict';
import classnames from 'classnames';
import React from 'react';
import ReactDOM from 'react-dom';
import SessionStore from '../stores/SessionStore';
import { Alert, Button, Form, FormField, FormInput } from 'elemental';
import { createHistory } from 'history';
var history = createHistory();
var SigninView = React.createClass({
getInitialState () {
return {
email: '',
password: '',
isAnimating: false,
isInvalid: false,
invalidMessage: '',
signedOut: window.location.search === '?signedout'
};
},
componentDidMount () {
if (this.state.signedOut && window.history.replaceState) {
history.replaceState({}, window.location.pathname);
}
if (this.refs.email) {
ReactDOM.findDOMNode(this.refs.email).select();
}
},
handleInputChange (e) {
let newState = {};
newState[e.target.name] = e.target.value;
this.setState(newState);
},
handleSubmit (e) {
e.preventDefault();
if (!this.state.email || !this.state.password) {
return this.displayError('Please enter an email address and password to sign in.');
}
SessionStore.signin({
email: this.state.email,
password: this.state.password
}, (err, data) => {
if (err || data && data.error) {
this.displayError('The email and password you entered are not valid.');
} else {
// TODO: Handle custom signin redirections
top.location.href = Keystone.adminPath;
}
});
},
displayError (message) {
this.setState({
isAnimating: true,
isInvalid: true,
invalidMessage: message
});
setTimeout(this.finishAnimation, 750);
},
finishAnimation () {
if (!this.isMounted()) return;
if (this.refs.email) {
ReactDOM.findDOMNode(this.refs.email).select();
}
this.setState({
isAnimating: false
});
},
renderBrand () {
let logo = { src: `${Keystone.adminPath}/images/logo.png`, width: 205, height: 68 };
if (this.props.logo) {
logo = typeof this.props.logo === 'string' ? { src: this.props.logo } : this.props.logo;
// TODO: Deprecate this
if (Array.isArray(logo)) {
logo = { src: logo[0], width: logo[1], height: logo[2] };
}
}
return (
<div className="auth-box__col">
<div className="auth-box__brand">
<a href="/" className="auth-box__brand__logo">
<img src={logo.src} width={logo.width ? logo.width : null} height={logo.height ? logo.height : null} alt={this.props.brand} />
</a>
</div>
</div>
);
},
renderUserInfo () {
if (!this.props.user) return null;
let openKeystoneButton = this.props.userCanAccessKeystone ? <Button href={Keystone.adminPath} type="primary">Open Keystone</Button> : null;
return (
<div className="auth-box__col">
<p>Hi {this.props.user.name.first},</p>
<p>You're already signed in.</p>
{openKeystoneButton}
<Button href={`${Keystone.adminPath}/signout`} type="link-cancel">Sign Out</Button>
</div>
);
},
renderAlert () {
if (this.state.isInvalid) {
return <Alert key="error" type="danger" style={{ textAlign: 'center' }}>{this.state.invalidMessage}</Alert>;
} else if (this.state.signedOut) {
return <Alert key="signed-out" type="info" style={{ textAlign: 'center' }}>You have been signed out.</Alert>;
} else {
/* eslint-disable react/self-closing-comp */
// TODO: This probably isn't the best way to do this, we
// shouldn't be using Elemental classNames instead of components
return <div key="fake" className="Alert Alert--placeholder"> </div>;
/* eslint-enable */
}
},
renderForm () {
if (this.props.user) return null;
return (
<div className="auth-box__col">
<Form method="post" onSubmit={this.handleSubmit} noValidate>
<FormField label="Email" htmlFor="email">
<FormInput type="email" name="email" onChange={this.handleInputChange} value={this.state.email} ref="email" />
</FormField>
<FormField label="Password" htmlFor="password">
<FormInput type="password" name="password" onChange={this.handleInputChange} value={this.state.password} ref="password" />
</FormField>
<Button disabled={this.state.animating} type="primary" submit>Sign In</Button>
{/*<Button disabled={this.state.animating} type="link-text">Forgot Password?</Button>*/}
</Form>
</div>
);
},
render () {
let boxClassname = classnames('auth-box', {
'auth-box--has-errors': this.state.isAnimating
});
return (
<div className="auth-wrapper">
{this.renderAlert()}
<div className={boxClassname}>
<h1 className="u-hidden-visually">{this.props.brand ? this.props.brand : 'Keystone'} Sign In </h1>
<div className="auth-box__inner">
{this.renderBrand()}
{this.renderUserInfo()}
{this.renderForm()}
</div>
</div>
<div className="auth-footer">
<span>Powered by </span>
<a href="http://keystonejs.com" target="_blank" title="The Node.js CMS and web application platform (new window)">KeystoneJS</a>
</div>
</div>
);
}
});
ReactDOM.render(<SigninView
brand={Keystone.brand}
logo={Keystone.logo}
user={Keystone.user}
userCanAccessKeystone={Keystone.userCanAccessKeystone}
/>, document.getElementById('signin-view'));
|
modules/__tests__/Redirect-test.js
|
zipongo/react-router
|
import expect from 'expect'
import React from 'react'
import { render, unmountComponentAtNode } from 'react-dom'
import createHistory from 'history/lib/createMemoryHistory'
import Redirect from '../Redirect'
import Router from '../Router'
import Route from '../Route'
describe('A <Redirect>', function () {
let node
beforeEach(function () {
node = document.createElement('div')
})
afterEach(function () {
unmountComponentAtNode(node)
})
it('works', function (done) {
render((
<Router history={createHistory('/notes/5')}>
<Route path="/messages/:id" />
<Redirect from="/notes/:id" to="/messages/:id" />
</Router>
), node, function () {
expect(this.state.location.pathname).toEqual('/messages/5')
done()
})
})
it('works with relative paths', function (done) {
render((
<Router history={createHistory('/nested/route1')}>
<Route path="nested">
<Route path="route2" />
<Redirect from="route1" to="route2" />
</Route>
</Router>
), node, function () {
expect(this.state.location.pathname).toEqual('/nested/route2')
done()
})
})
it('works with relative paths with param', function (done) {
render((
<Router history={createHistory('/nested/1/route1')}>
<Route path="nested/:id">
<Route path="route2" />
<Redirect from="route1" to="route2" />
</Route>
</Router>
), node, function () {
expect(this.state.location.pathname).toEqual('/nested/1/route2')
done()
})
})
})
|
src/components/HabitPageContent.js
|
simplebee/everyday
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { Route, Link } from 'react-router-dom';
import { Button } from 'antd';
import Calendar from './Calendar';
import Datapoints from './Datapoints';
import Graph from './Graph';
import { deleteHabit } from '../actions/habitActions';
class HabitPageContent extends Component {
handleDeleteClick = () => {
const { habitId } = this.props.match.params;
this.props
.deleteHabit(habitId)
.then(() => this.props.history.push('/app'))
.catch(error => console.log(error));
};
render() {
const { match } = this.props;
return (
<React.Fragment>
<div>
<Link to={`${match.url}/edit`}>
<Button icon="edit">Edit</Button>
</Link>
<Button type="danger" icon="delete" onClick={this.handleDeleteClick}>
Delete
</Button>
</div>
<Route path={`${match.path}`} exact component={Calendar} />
<Route path={`${match.path}/datapoints`} component={Datapoints} />
<Route path={`${match.path}/graph`} component={Graph} />
</React.Fragment>
);
}
}
const mapDispatchToProps = { deleteHabit };
export default withRouter(
connect(
null,
mapDispatchToProps
)(HabitPageContent)
);
|
examples/js/selection/select-bgcolor-table.js
|
powerhome/react-bootstrap-table
|
/* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
const selectRowProp = {
mode: 'checkbox',
bgColor: 'pink'
};
export default class SelectBgColorTable extends React.Component {
render() {
return (
<BootstrapTable data={ products } selectRow={ selectRowProp }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
node_modules/react-router/es6/Link.js
|
save-password/save-password.github.io
|
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import { routerShape } from './PropTypes';
var _React$PropTypes = React.PropTypes;
var bool = _React$PropTypes.bool;
var object = _React$PropTypes.object;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
var oneOfType = _React$PropTypes.oneOfType;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
// TODO: De-duplicate against hasAnyProperties in createTransitionManager.
function isEmptyObject(object) {
for (var p in object) {
if (Object.prototype.hasOwnProperty.call(object, p)) return false;
}return true;
}
function createLocationDescriptor(to, _ref) {
var query = _ref.query;
var hash = _ref.hash;
var state = _ref.state;
if (query || hash || state) {
return { pathname: to, query: query, hash: hash, state: state };
}
return to;
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
var Link = React.createClass({
displayName: 'Link',
contextTypes: {
router: routerShape
},
propTypes: {
to: oneOfType([string, object]),
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func,
target: string
},
getDefaultProps: function getDefaultProps() {
return {
onlyActiveOnIndex: false,
style: {}
};
},
handleClick: function handleClick(event) {
if (this.props.onClick) this.props.onClick(event);
if (event.defaultPrevented) return;
!this.context.router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0;
if (isModifiedEvent(event) || !isLeftClickEvent(event)) return;
// If target prop is set (e.g. to "_blank"), let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) return;
event.preventDefault();
var _props = this.props;
var to = _props.to;
var query = _props.query;
var hash = _props.hash;
var state = _props.state;
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
this.context.router.push(location);
},
render: function render() {
var _props2 = this.props;
var to = _props2.to;
var query = _props2.query;
var hash = _props2.hash;
var state = _props2.state;
var activeClassName = _props2.activeClassName;
var activeStyle = _props2.activeStyle;
var onlyActiveOnIndex = _props2.onlyActiveOnIndex;
var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0;
// Ignore if rendered outside the context of router, simplifies unit testing.
var router = this.context.router;
if (router) {
// If user does not specify a `to` prop, return an empty anchor tag.
if (to == null) {
return React.createElement('a', props);
}
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
props.href = router.createHref(location);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(location, onlyActiveOnIndex)) {
if (activeClassName) {
if (props.className) {
props.className += ' ' + activeClassName;
} else {
props.className = activeClassName;
}
}
if (activeStyle) props.style = _extends({}, props.style, activeStyle);
}
}
}
return React.createElement('a', _extends({}, props, { onClick: this.handleClick }));
}
});
export default Link;
|
generators/js-framework/modules/react/components/Footer.js
|
sahat/boilerplate
|
import React from 'react';
class Footer extends React.Component {
render() {
return (
<footer>
<p>© 2016 Company, Inc. All Rights Reserved.</p>
</footer>
);
}
}
export default Footer;
|
src/MediaListItem.js
|
mmarcant/react-bootstrap
|
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
class MediaListItem extends React.Component {
render() {
const { className, ...props } = this.props;
const [bsProps, elementProps] = splitBsProps(props);
const classes = getClassSet(bsProps);
return (
<li
{...elementProps}
className={classNames(className, classes)}
/>
);
}
}
export default bsClass('media', MediaListItem);
|
examples/src/components/CustomRenderField.js
|
silppuri/react-select
|
import React from 'react';
import Select from 'react-select';
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
var CustomRenderField = React.createClass({
displayName: 'CustomRenderField',
propTypes: {
delimiter: React.PropTypes.string,
label: React.PropTypes.string,
multi: React.PropTypes.bool,
},
renderOption (option) {
return <span style={{ color: option.hex }}>{option.label} ({option.hex})</span>;
},
renderValue (option) {
return <strong style={{ color: option.hex }}>{option.label}</strong>;
},
render () {
var ops = [
{ label: 'Red', value: 'red', hex: '#EC6230' },
{ label: 'Green', value: 'green', hex: '#4ED84E' },
{ label: 'Blue', value: 'blue', hex: '#6D97E2' }
];
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select
delimiter={this.props.delimiter}
multi={this.props.multi}
allowCreate
placeholder="Select your favourite"
options={ops}
optionRenderer={this.renderOption}
valueRenderer={this.renderValue}
onChange={logChange} />
</div>
);
}
});
module.exports = CustomRenderField;
|
client/index.js
|
Jakeyrob/chill
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
require('./styles.css');
ReactDOM.render(
<App />,
document.getElementById('app')
);
|
src/components/Start.js
|
Babbins/fullstalker
|
import React from 'react';
import {Link} from 'react-router';
function myFunction() {
console.log('your mom!');
}
export default () => (
<div>
<br />
<br />
<br />
<div className="valign-wrapper row">
<div className="valign col s7 center">
<img id="logo" className="text-align" src="/media/logo.png" />
</div>
<div className="valgin col s5 center">
<div className="start-text">
<h5>
Fullstalkr will learn you the names of the many faces of Fullstack and Grace Hopper Academy!
</h5>
</div>
<Link to="/flashcard">
<button className="waves-effect waves-light btn-large amber darken-3">Begin!</button>
</Link>
</div>
</div>
</div>
);
|
fields/types/select/SelectField.js
|
riyadhalnur/keystone
|
import Field from '../Field';
import React from 'react';
import Select from 'react-select';
import { FormInput } from 'elemental';
/**
* TODO:
* - Custom path support
*/
module.exports = Field.create({
displayName: 'SelectField',
valueChanged (newValue) {
// TODO: This should be natively handled by the Select component
if (this.props.numeric && 'string' === typeof newValue) {
newValue = newValue ? Number(newValue) : undefined;
}
this.props.onChange({
path: this.props.path,
value: newValue
});
},
renderValue () {
var selected = this.props.ops.find(option => option.value === this.props.value);
return <FormInput noedit>{selected ? selected.label : null}</FormInput>;
},
renderField () {
// TODO: This should be natively handled by the Select component
var ops = (this.props.numeric) ? this.props.ops.map(function(i) { return { label: i.label, value: String(i.value) }; }) : this.props.ops;
var value = ('number' === typeof this.props.value) ? String(this.props.value) : this.props.value;
return <Select simpleValue name={this.props.path} value={value} options={ops} onChange={this.valueChanged} />;
}
});
|
src/react/JSONTree/JSONStringNode.js
|
threepointone/redux-devtools
|
import React from 'react';
import reactMixin from 'react-mixin';
import { SquashClickEventMixin } from './mixins';
import hexToRgb from '../../utils/hexToRgb';
const styles = {
base: {
paddingTop: 3,
paddingBottom: 3,
paddingRight: 0,
marginLeft: 14
},
label: {
display: 'inline-block',
marginRight: 5
}
};
@reactMixin.decorate(SquashClickEventMixin)
export default class JSONStringNode extends React.Component {
render() {
let backgroundColor = 'transparent';
if (this.props.previousValue !== this.props.value) {
const bgColor = hexToRgb(this.props.theme.base06);
backgroundColor = `rgba(${bgColor.r}, ${bgColor.g}, ${bgColor.b}, 0.1)`;
}
return (
<li style={{ ...styles.base, backgroundColor }} onClick={::this.handleClick}>
<label style={{
...styles.label,
color: this.props.theme.base0D
}}>
{this.props.keyName}:
</label>
<span style={{ color: this.props.theme.base0B }}>"{this.props.value}"</span>
</li>
);
}
}
|
test/NavItemSpec.js
|
azmenak/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import NavItem from '../src/NavItem';
describe('NavItem', function () {
it('Should add active class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem active={true}>
Item content
</NavItem>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'active'));
});
it('Should add disabled class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem disabled={true}>
Item content
</NavItem>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'disabled'));
});
it('Should add DOM properties', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href="/some/unique-thing/" title="content">
Item content
</NavItem>
);
let linkElement = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.ok(linkElement.href.indexOf('/some/unique-thing/') >= 0);
assert.equal(linkElement.title, 'content');
});
it('Should not add anchor properties to li', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href='/hi' title='boom!'>
Item content
</NavItem>
);
assert.ok(!React.findDOMNode(instance).hasAttribute('href'));
assert.ok(!React.findDOMNode(instance).hasAttribute('title'));
});
it('Should call `onSelect` when item is selected', function (done) {
function handleSelect(key) {
assert.equal(key, '2');
done();
}
let instance = ReactTestUtils.renderIntoDocument(
<NavItem eventKey='2' onSelect={handleSelect}>
<span>Item content</span>
</NavItem>
);
ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'span'));
});
it('Should not call `onSelect` when item disabled and is selected', function () {
function handleSelect() {
throw new Error('onSelect should not be called');
}
let instance = ReactTestUtils.renderIntoDocument(
<NavItem disabled={true} onSelect={handleSelect}>
<span>Item content</span>
</NavItem>
);
ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'span'));
});
it('Should set target attribute on anchor', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href="/some/unique-thing/" target="_blank">Item content</NavItem>
);
let linkElement = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.equal(linkElement.target, '_blank');
});
it('Should call `onSelect` with target attribute', function (done) {
function handleSelect(key, href, target) {
assert.equal(target, '_blank');
done();
}
let instance = ReactTestUtils.renderIntoDocument(
<NavItem onSelect={handleSelect} target="_blank">
<span>Item content</span>
</NavItem>
);
ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'span'));
});
it('Should set role="button" when href=="#"', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href="#" target="_blank">Item content</NavItem>
);
let linkElement = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert(linkElement.outerHTML.match('role="button"'), true);
});
it('Should not set role when href!="#"', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href="/path/to/stuff" target="_blank">Item content</NavItem>
);
let linkElement = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.equal(linkElement.outerHTML.match('role="button"'), null);
});
describe('Web Accessibility', function(){
it('Should pass aria-controls to the link', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem href="/path/to/stuff" target="_blank" aria-controls='hi'>Item content</NavItem>
);
let linkElement = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.ok(linkElement.hasAttribute('aria-controls'));
});
it('Should add aria-selected to the link', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem active>Item content</NavItem>
);
let linkElement = React.findDOMNode(
ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.equal(linkElement.getAttribute('aria-selected'), 'true');
});
it('Should pass role down', function () {
let instance = ReactTestUtils.renderIntoDocument(
<NavItem role='tab'>Item content</NavItem>
);
let linkElement = React.findDOMNode(
ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'));
assert.equal(linkElement.getAttribute('role'), 'tab');
});
});
});
|
src/svg-icons/action/settings-input-antenna.js
|
pradel/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsInputAntenna = (props) => (
<SvgIcon {...props}>
<path d="M12 5c-3.87 0-7 3.13-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.87-3.13-7-7-7zm1 9.29c.88-.39 1.5-1.26 1.5-2.29 0-1.38-1.12-2.5-2.5-2.5S9.5 10.62 9.5 12c0 1.02.62 1.9 1.5 2.29v3.3L7.59 21 9 22.41l3-3 3 3L16.41 21 13 17.59v-3.3zM12 1C5.93 1 1 5.93 1 12h2c0-4.97 4.03-9 9-9s9 4.03 9 9h2c0-6.07-4.93-11-11-11z"/>
</SvgIcon>
);
ActionSettingsInputAntenna = pure(ActionSettingsInputAntenna);
ActionSettingsInputAntenna.displayName = 'ActionSettingsInputAntenna';
export default ActionSettingsInputAntenna;
|
app/javascript/mastodon/features/notifications/components/setting_toggle.js
|
tri-star/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,
defaultValue: PropTypes.bool,
disabled: PropTypes.bool,
}
onChange = ({ target }) => {
this.props.onChange(this.props.settingPath, target.checked);
}
render () {
const { prefix, settings, settingPath, label, defaultValue, disabled } = this.props;
const id = ['setting-toggle', prefix, ...settingPath].filter(Boolean).join('-');
return (
<div className='setting-toggle'>
<Toggle disabled={disabled} id={id} checked={settings.getIn(settingPath, defaultValue)} onChange={this.onChange} onKeyDown={this.onKeyDown} />
<label htmlFor={id} className='setting-toggle__label'>{label}</label>
</div>
);
}
}
|
src/component/check.js
|
stevenocchipinti/react-toggle
|
import React from 'react'
export default () => (
<svg width='14' height='11' viewBox='0 0 14 11'>
<title>
switch-check
</title>
<path d='M11.264 0L5.26 6.004 2.103 2.847 0 4.95l5.26 5.26 8.108-8.107L11.264 0' fill='#fff' fillRule='evenodd' />
</svg>
)
|
src/app/components/Delta.js
|
devgru/color
|
import React from 'react';
import { hcl } from 'd3-color';
import deltae from 'deltae';
import toString from '../domain/ColorToString';
import classNames from 'classnames';
import round from 'round-to-precision';
const cents = round(0.01);
function Delta(props) {
let delta = 0;
const hcl1 = hcl(props.colors[0]);
const hcl2 = hcl(props.colors[1]);
deltae.delta(toString(hcl1), toString(hcl2), function(d) {
delta = cents(d);
});
const textClasses = classNames({
delta: true,
'color-card__text_bright': hcl1.l + hcl2.l > 100,
'color-card__text_dark': hcl1.l + hcl2.l <= 100,
});
const style = {
background:
'-webkit-linear-gradient(left, ' + hcl1 + ' 0%, ' + hcl2 + ' 100%)',
};
return (
<div style={style} className={textClasses}>
<span>{delta}</span>
</div>
);
}
export default Delta;
|
HTML/前端/my-react-app-spring-boot-yao/src/hello.js
|
xiaoxiaoyao/MyApp
|
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
|
src/Parser/HolyPaladin/Modules/Items/Tier19_4set.js
|
mwwscott0/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import HIT_TYPES from 'Parser/Core/HIT_TYPES';
import Module from 'Parser/Core/Module';
import calculateEffectiveHealing from 'Parser/Core/calculateEffectiveHealing';
import Combatants from 'Parser/Core/Modules/Combatants';
const INFUSION_OF_LIGHT_BUFF_EXPIRATION_BUFFER = 150; // the buff expiration can occur several MS before the heal event is logged, this is the buffer time that an IoL charge may have dropped during which it will still be considered active.
const INFUSION_OF_LIGHT_BUFF_MINIMAL_ACTIVE_TIME = 200; // if someone heals with FoL and then immediately casts a HS race conditions may occur. This prevents that (although the buff is probably not applied before the FoL).
const INFUSION_OF_LIGHT_FOL_HEALING_INCREASE = 0.5;
const debug = false;
class Tier19_4set extends Module {
static dependencies = {
combatants: Combatants,
};
healing = 0;
totalIolProcsUsed = 0;
bonusIolProcsUsed = 0;
bonusIolProcsUsedOnFol = 0;
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.HOLY_PALADIN_T19_4SET_BONUS_BUFF.id);
}
iolProcsUsedSinceLastHolyShock = 0;
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.HOLY_SHOCK_HEAL.id) {
if (event.hitType === HIT_TYPES.CRIT) {
debug && console.log((event.timestamp - this.owner.fight.start_time) / 1000, 'Holy Shock crit!', event);
this.iolProcsUsedSinceLastHolyShock = 0;
}
}
if (spellId === SPELLS.FLASH_OF_LIGHT.id || spellId === SPELLS.HOLY_LIGHT.id) {
const hasIol = this.combatants.selected.getBuff(SPELLS.INFUSION_OF_LIGHT.id, event.timestamp, INFUSION_OF_LIGHT_BUFF_EXPIRATION_BUFFER, INFUSION_OF_LIGHT_BUFF_MINIMAL_ACTIVE_TIME);
if (hasIol) {
this.iolProcsUsedSinceLastHolyShock += 1;
debug && console.log((event.timestamp - this.owner.fight.start_time) / 1000, 'IoL', event.ability.name, this.iolProcsUsedSinceLastHolyShock, event);
this.totalIolProcsUsed += 1;
if (this.iolProcsUsedSinceLastHolyShock === 2) {
debug && console.log((event.timestamp - this.owner.fight.start_time) / 1000, 'Bonus IOL', event, event);
this.bonusIolProcsUsed += 1;
if (spellId === SPELLS.FLASH_OF_LIGHT.id) {
this.bonusIolProcsUsedOnFol += 1;
this.healing += calculateEffectiveHealing(event, INFUSION_OF_LIGHT_FOL_HEALING_INCREASE);
}
}
} else {
debug && console.log((event.timestamp - this.owner.fight.start_time) / 1000, 'Regular', event.ability.name, event);
}
}
}
on_byPlayer_damage(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.HOLY_SHOCK_DAMAGE.id) {
if (event.hitType === HIT_TYPES.CRIT) {
debug && console.log((event.timestamp - this.owner.fight.start_time) / 1000, 'Holy Shock crit!');
this.iolProcsUsedSinceLastHolyShock = 0;
}
}
}
on_beacon_heal(beaconTransferEvent, healEvent) {
const spellId = healEvent.ability.guid;
if (spellId !== SPELLS.FLASH_OF_LIGHT.id) {
return;
}
const combatant = this.combatants.players[healEvent.targetID];
if (!combatant) {
// If combatant doesn't exist it's probably a pet.
debug && console.log('Skipping beacon heal event since combatant couldn\'t be found:', beaconTransferEvent, 'for heal:', healEvent);
return;
}
const hasIol = this.combatants.selected.getBuff(SPELLS.INFUSION_OF_LIGHT.id, healEvent.timestamp, INFUSION_OF_LIGHT_BUFF_EXPIRATION_BUFFER, INFUSION_OF_LIGHT_BUFF_MINIMAL_ACTIVE_TIME);
if (!hasIol) {
return;
}
if (this.iolProcsUsedSinceLastHolyShock === 2) {
debug && console.log((beaconTransferEvent.timestamp - this.owner.fight.start_time) / 1000, 'Beacon transfer', beaconTransferEvent);
this.healing += calculateEffectiveHealing(beaconTransferEvent, INFUSION_OF_LIGHT_FOL_HEALING_INCREASE);
}
}
item() {
return {
id: `spell-${SPELLS.HOLY_PALADIN_T19_4SET_BONUS_BUFF.id}`,
icon: <SpellIcon id={SPELLS.HOLY_PALADIN_T19_4SET_BONUS_BUFF.id} />,
title: <SpellLink id={SPELLS.HOLY_PALADIN_T19_4SET_BONUS_BUFF.id} />,
result: (
<dfn data-tip={`The actual effective healing contributed by the tier 19 4 set bonus. <b>This does not include any healing "gained" from the Holy Light cast time reduction.</b> You used a total of ${this.totalIolProcsUsed} Infusion of Light procs, ${this.bonusIolProcsUsed} of those were from procs from the 4 set bonus and ${this.bonusIolProcsUsedOnFol} of those bonus procs were used on Flash of Light.`}>
{this.owner.formatItemHealingDone(this.healing)}
</dfn>
),
};
}
}
export default Tier19_4set;
|
src/containers/Editor.js
|
petercollingridge/math-for-programmers-prototype
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
// CodeMirror Imports
import CodeMirror from 'react-codemirror2';
import 'codemirror/mode/stex/stex';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/monokai.css';
class Editor extends Component {
constructor(props) {
super(props);
this.state = {
waiting: false,
timer: null
};
// Function Bindings
this.tabToSpaces = this.tabToSpaces.bind(this);
this.codeChange = this.codeChange.bind(this);
}
/*
Prevents uppdating the code too fast
for correct Preview rendering
*/
codeChange(cm, meta, code) {
const { updateCode } = this.props;
const { waiting, timer } = this.state;
const delay = 500;
if (waiting) {
clearTimeout(timer);
const newTimer = setTimeout(() => {
this.setState({
waiting: false
});
updateCode(code);
}, delay);
this.setState({
timer: newTimer
});
} else {
const newTimer = setTimeout(updateCode(code), delay);
this.setState({
waiting: true,
timer: newTimer
});
}
}
tabToSpaces(cm) {
const spaces = Array(cm.getOption('indentUnit') + 1).join(' ');
cm.replaceSelection(spaces);
}
render() {
const { code } = this.props;
const options = {
lineNumbers: true,
lineWrapping: true,
extraKeys: {
Tab: this.tabToSpaces
},
mode: 'stex',
tabSize: 2,
theme: 'monokai'
};
return (
<CodeMirror
editorDidMount={cm => cm.focus()}
onValueChange={this.codeChange}
onValueSet={cm => {
// Prevent First line from being edited
cm.markText(
{ line: 0, ch: 0 },
{ line: 1, ch: 0 },
{
atomic: true,
inclusiveLeft: true,
readOnly: true
}
);
// Prevent Last line from being edited
const lastLine = cm.lineCount() - 1;
cm.markText(
{ line: lastLine, ch: 0 },
{ line: lastLine },
{
atomic: true,
inclusiveLeft: true,
inclusiveRight: true,
readOnly: true
}
);
}}
options={options}
value={code}
/>
);
}
}
Editor.propTypes = {
code: PropTypes.string.isRequired,
updateCode: PropTypes.func.isRequired
};
export default Editor;
|
src/components/Scenario.js
|
kalpetros/hawkpass
|
import PropTypes from 'prop-types';
import React from 'react';
import { Panel } from './Panel';
export const Scenario = props => {
const { per_second, per_minute, per_hour, per_day, per_year } = props.values;
return (
<div className="grid grid-cols-2 sm:grid-cols-5 gap-4">
<Panel>
<div className="text-xl font-semibold truncate">{per_second}</div>
<div className="truncate">seconds</div>
</Panel>
<Panel>
<div className="text-xl font-semibold truncate">{per_minute}</div>
<div className="truncate">minutes</div>
</Panel>
<Panel>
<div className="text-xl font-semibold truncate">{per_hour}</div>
<div className="truncate">hours</div>
</Panel>
<Panel>
<div className="text-xl font-semibold truncate">{per_day}</div>
<div className="truncate">days</div>
</Panel>
<Panel>
<div className="text-xl font-semibold truncate">{per_year}</div>
<div className="truncate">years</div>
</Panel>
</div>
);
};
Scenario.defaultProps = {
values: {
per_second: '-',
per_minute: '-',
per_hour: '-',
per_day: '-',
per_year: '-',
},
};
Scenario.propTypes = {
values: PropTypes.object.isRequired,
};
|
ui/src/app/components/Types.js
|
kuppuswamy/foodie
|
import React from 'react';
import AddTypeMutation from '../mutations/AddTypeMutation';
import EditTypeMutation from '../mutations/EditTypeMutation';
import DeleteTypeMutation from '../mutations/DeleteTypeMutation';
export default class Types extends React.Component {
state = {
text: '',
editID: null,
showModal: false
};
_handleChange = (e) => {
this.setState({text: e.target.value});
};
_onAdd = () => {
if (this.state.text.trim() !== '') {
AddTypeMutation.commit(this.props.relay.environment, this.state.text);
}
this.setState({text: '', showModal: false});
};
_onEdit = (type) => {
this.setState({text: type.name, editID: type.id, showModal: true}, () => this.typeName.focus());
};
_onCancel = () => {
this.setState({text: '', editID: null, showModal: false});
};
_onSave = () => {
let type = {name: this.state.text, id: this.state.editID};
this.setState({text: '', editID: null, showModal: false});
EditTypeMutation.commit(this.props.relay.environment, type);
};
_onDelete = (type) => {
DeleteTypeMutation.commit(this.props.relay.environment, type);
};
_showModal = () => {
this.setState({showModal: true}, () => this.typeName.focus());
};
_onEnter = e => {
if (e.keyCode === 13) {
if (this.state.editID) this._onSave(); else this._onAdd();
}
};
render = () => {
let {types} = this.props;
return (
<div>
<div className={`modal ${this.state.showModal ? 'is-active' : ''}`}>
<div className="modal-background" onClick={e => this._onCancel()}/>
<div className="modal-card">
<header className="modal-card-head">
<p className="modal-card-title">{this.state.editID ? 'Edit' : 'Add'} type</p>
<button className="delete" aria-label="close" onClick={e => this._onCancel()}/>
</header>
<section className="modal-card-body">
<div className="field">
<p className="control is-expanded">
<input ref={n => this.typeName = n} className="input" type="text" placeholder="Name"
value={this.state.text} onChange={this._handleChange} onKeyDown={e => this._onEnter(e)}/>
</p>
</div>
</section>
<footer className="modal-card-foot">
{
this.state.editID ? (
<button className="button is-primary" onClick={e => this._onSave()}>Save</button>
) : (
<button className="button is-primary" onClick={e => this._onAdd()}>Add</button>
)
}
<button className="button" onClick={e => this._onCancel()}>Cancel</button>
</footer>
</div>
</div>
<h1 className="title">Types</h1>
<div className="field">
<p className="control">
<a className="button is-warning" onClick={e => this._showModal()}>Add</a>
</p>
</div>
{
types.edges.length ?
types.edges.map((type, key) => (
<div className="field card" key={type.node.id}>
<div className="card-content">
<p className="subtitle is-4">
{type.node.name}{' - #'}{type.node.id}
</p>
</div>
<footer className="card-footer">
<a className="card-footer-item" onClick={e => this._onEdit(type.node)}>Edit</a>
<a className="card-footer-item" onClick={e => this._onDelete(type.node)}>Delete</a>
</footer>
</div>
)) : (
<div className="field card has-text-centered">
<div className="card-content">
<p className="subtitle is-4">
<i>Add a type<br/>of food.</i>
</p>
</div>
</div>
)
}
</div>
);
}
}
|
src/components/Sidebar/SelectMessage.js
|
vogelino/design-timeline
|
import React from 'react';
export default () => (
<div className="sidebar_selectMessage">
Please select an item to view its content
</div>
);
|
ui/src/main/js/components/__tests__/Diff-test.js
|
medallia/aurora
|
import React from 'react';
import { shallow } from 'enzyme';
import Diff from '../Diff';
import { TaskConfigBuilder } from 'test-utils/TaskBuilders';
describe('Diff', () => {
it('Should not add change classes to diff viewer when objects are same', () => {
const el = shallow(<Diff left={{test: true}} right={{test: true}} />);
expect(el.find('span.removed').length).toBe(0);
expect(el.find('span.added').length).toBe(0);
});
it('Should add change classes to diff viewer when configs are not the same', () => {
const el = shallow(<Diff left={{test: true}} right={{test: false}} />);
expect(el.find('span.removed').length).toBe(1);
expect(el.find('span.added').length).toBe(1);
});
it('Should render a finer grained diff when Thermos executor is used', () => {
const left = TaskConfigBuilder.executorConfig({
name: 'AuroraExecutor',
data: JSON.stringify({
one: 1,
two: 2,
three: 3,
nested: {
okay: true
}
})
}).build();
const right = TaskConfigBuilder.executorConfig({
name: 'AuroraExecutor',
data: JSON.stringify({
one: 'one',
two: 2,
three: 3,
nested: {
okay: false
}
})
}).build();
const el = shallow(<Diff left={left} right={right} />);
expect(el.find('span.removed').length).toBe(2);
expect(el.find('span.added').length).toBe(2);
});
it('Just treats executor config as a string for custom executors', () => {
const left = TaskConfigBuilder.executorConfig({
name: 'MyExecutor',
data: JSON.stringify({
one: 1,
two: 2,
three: 3,
nested: {
okay: true
}
})
}).build();
const right = TaskConfigBuilder.executorConfig({
name: 'MyExecutor',
data: JSON.stringify({
one: 'one',
two: 2,
three: 3,
nested: {
okay: false
}
})
}).build();
const el = shallow(<Diff left={left} right={right} />);
expect(el.find('span.removed').length).toBe(1);
expect(el.find('span.added').length).toBe(1);
});
});
|
src/js/components/members/newMemberForm.js
|
jrnail23/sitterswap-ui
|
import React from 'react'
import Input from '../common/textInput'
import {Link} from 'react-router'
export default class extends React.Component {
static propTypes = {
member: React.PropTypes.shape({
firstName: React.PropTypes.string.isRequired,
lastName: React.PropTypes.string.isRequired,
emailAddress: React.PropTypes.string.isRequired
}).isRequired,
onChange: React.PropTypes.func.isRequired,
onSave: React.PropTypes.func.isRequired,
errors: React.PropTypes.object
}
render () {
return (
<div>
<form>
<Input name='firstName'
label='First Name'
value={this.props.member.firstName}
onChange={this.props.onChange}
error={this.props.errors.firstName} />
<Input name='lastName'
label='Last Name'
value={this.props.member.lastName}
onChange={this.props.onChange}
error={this.props.errors.lastName} />
<Input name='emailAddress'
label='Email Address'
value={this.props.member.emailAddress}
onChange={this.props.onChange}
error={this.props.errors.emailAddress} />
<Link to='/members' className='btn btn-default'>Cancel</Link>
<input type='submit'
value='Save'
className='btn btn-primary'
onClick={this.props.onSave} />
</form>
</div>
)
}
}
|
src/utils/griddleConnect.js
|
GriddleGriddle/Griddle
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
/// This method appends options onto existing connect parameters
export const mergeConnectParametersWithOptions = (
originalConnect,
newOptions
) => {
const [
mapStateFromProps,
mapDispatchFromProps,
mergeProps,
options
] = originalConnect;
return [
mapStateFromProps,
mapDispatchFromProps,
mergeProps,
{ ...options, ...newOptions }
];
};
const griddleConnect = (...connectOptions) => OriginalComponent =>
class extends React.Component {
static contextTypes = {
storeKey: PropTypes.string
};
constructor(props, context) {
super(props, context);
const newOptions = mergeConnectParametersWithOptions(connectOptions, {
storeKey: context.storeKey
});
this.ConnectedComponent = connect(...newOptions)(OriginalComponent);
}
render() {
return <this.ConnectedComponent {...this.props} />;
}
};
export { griddleConnect as connect };
|
spec/javascripts/jsx/grading/CourseTabContainerSpec.js
|
djbender/canvas-lms
|
/*
* Copyright (C) 2017 - 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 {mount} from 'enzyme'
import $ from 'jquery'
import _ from 'underscore'
import CourseTabContainer from 'jsx/grading/CourseTabContainer'
import 'jqueryui/tabs'
QUnit.module('CourseTabContainer', {
renderComponent(props = {}) {
const defaults = {}
const mergedProps = _.defaults(props, defaults)
this.wrapper = mount(React.createElement(CourseTabContainer, mergedProps))
},
setup() {
sandbox.stub($, 'getJSON').returns({success: () => ({error: () => {}}), done: () => {}})
},
teardown() {
this.wrapper.unmount()
}
})
test('tabs are present when there are grading periods', function() {
this.renderComponent({hasGradingPeriods: true})
const $el = this.wrapper.getDOMNode()
strictEqual($el.querySelectorAll('.ui-tabs').length, 1)
strictEqual($el.querySelectorAll('.ui-tabs ul.ui-tabs-nav li').length, 2)
equal($el.querySelector('#grading-periods-tab').getAttribute('style'), 'display: block;')
equal($el.querySelector('#grading-standards-tab').getAttribute('style'), 'display: none;')
})
test('tabs are not present when there are no grading periods', function() {
this.renderComponent({hasGradingPeriods: false})
equal(this.wrapper.find('.ui-tabs').length, 0)
})
test('jquery-ui tabs() is called when there are grading periods', function() {
const tabsSpy = sandbox.spy($.fn, 'tabs')
this.renderComponent({hasGradingPeriods: true})
ok(tabsSpy.calledOnce)
})
test('jquery-ui tabs() is not called when there are no grading periods', function() {
const tabsSpy = sandbox.spy($.fn, 'tabs')
this.renderComponent({hasGradingPeriods: false})
notOk(tabsSpy.called)
})
test('does not render grading periods if there are no grading periods', function() {
this.renderComponent({hasGradingPeriods: false})
notOk(this.wrapper.instance().gradingPeriods)
})
test('renders the grading periods if there are grading periods', function() {
this.renderComponent({hasGradingPeriods: true})
ok(this.wrapper.instance().gradingPeriods)
})
test('renders the grading standards if there are no grading periods', function() {
this.renderComponent({hasGradingPeriods: false})
ok(this.wrapper.instance().gradingStandards)
})
test('renders the grading standards if there are grading periods', function() {
this.renderComponent({hasGradingPeriods: true})
ok(this.wrapper.instance().gradingStandards)
})
|
src/renderer/components/app-wrapper.js
|
sirbrillig/gitnews-menubar
|
import PropTypes from 'prop-types';
import { ipcRenderer } from 'electron';
import React from 'react';
import { connect } from 'react-redux';
import {
markAllNotesSeen,
scrollToTop,
markAppHidden,
markAppShown,
} from 'common/lib/reducer';
class AppWrapper extends React.Component {
constructor(props) {
super(props);
ipcRenderer.on('hide-app', () => {
this.props.markAppHidden();
});
ipcRenderer.on('show-app', () => {
this.props.markAppShown();
});
ipcRenderer.on('menubar-click', () => {
this.props.markAllNotesSeen();
this.props.scrollToTop();
});
}
render() {
return this.props.children;
}
}
AppWrapper.propTypes = {
// Functions
quitApp: PropTypes.func.isRequired,
// All following are provided by connect
markAllNotesSeen: PropTypes.func.isRequired,
scrollToTop: PropTypes.func.isRequired,
// Values
version: PropTypes.string.isRequired,
};
const actions = {
markAllNotesSeen,
scrollToTop,
markAppHidden,
markAppShown,
};
export default connect(null, actions)(AppWrapper);
|
fields/types/color/ColorField.js
|
suryagh/keystone
|
import ColorPicker from 'react-color';
import Field from '../Field';
import React from 'react';
import { FormInput, InputGroup } from 'elemental';
const PICKER_TYPES = ['chrome', 'compact', 'material', 'photoshop', 'sketch', 'slider', 'swatches'];
const TRANSPARENT_BG
= `<svg width="24" height="24" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g fill="#CCCCCC">
<path d="M0,0 L8,0 L8,8 L0,8 L0,0 Z M8,8 L16,8 L16,16 L8,16 L8,8 Z M0,16 L8,16 L8,24 L0,24 L0,16 Z M16,0 L24,0 L24,8 L16,8 L16,0 Z M16,16 L24,16 L24,24 L16,24 L16,16 Z" />
</g>
</svg>`;
module.exports = Field.create({
displayName: 'ColorField',
propTypes: {
onChange: React.PropTypes.func,
path: React.PropTypes.string,
pickerType: React.PropTypes.oneOf(PICKER_TYPES),
value: React.PropTypes.string,
},
getInitialState () {
return {
displayColorPicker: false,
};
},
getDefaultProps () {
return {
pickerType: 'sketch',
};
},
updateValue (value) {
this.props.onChange({
path: this.props.path,
value: value,
});
},
handleInputChange (event) {
var newValue = event.target.value;
if (/^([0-9A-F]{3}){1,2}$/.test(newValue)) {
newValue = '#' + newValue;
}
if (newValue === this.props.value) return;
this.updateValue(newValue);
},
handleClick () {
this.setState({ displayColorPicker: !this.state.displayColorPicker });
},
handleClose () {
this.setState({ displayColorPicker: false });
},
handlePickerChange (color) {
var newValue = '#' + color.hex;
if (newValue === this.props.value) return;
this.updateValue(newValue);
},
renderSwatch () {
return (this.props.value) ? (
<span className="field-type-color__swatch" style={{ backgroundColor: this.props.value }} />
) : (
<span className="field-type-color__swatch" dangerouslySetInnerHTML={{ __html: TRANSPARENT_BG }} />
);
},
renderField () {
return (
<div className="field-type-color__wrapper">
<InputGroup>
<InputGroup.Section grow>
<FormInput ref="field" onChange={this.valueChanged} name={this.props.path} value={this.props.value} autoComplete="off" />
</InputGroup.Section>
<InputGroup.Section>
<button type="button" onClick={this.handleClick} className="FormInput FormSelect field-type-color__button">
{this.renderSwatch()}
</button>
</InputGroup.Section>
</InputGroup>
<div className="field-type-color__picker">
<ColorPicker
color={this.props.value}
display={this.state.displayColorPicker}
onChangeComplete={this.handlePickerChange}
onClose={this.handleClose}
position={window.innerWidth > 480 ? 'right' : 'below'}
type={this.props.pickerType}
/>
</div>
</div>
);
},
});
|
packages/ringcentral-widgets/components/IncomingCallPad/index.js
|
u9520107/ringcentral-js-widget
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Tooltip from 'rc-tooltip';
import 'rc-tooltip/assets/bootstrap_white.css';
import ForwardForm from '../ForwardForm';
import ReplyWithMessage from '../ReplyWithMessage';
import ActiveCallButton from '../ActiveCallButton';
import MultiCallAnswerButton from '../MultiCallAnswerButton';
import MessageIcon from '../../assets/images/MessageFill.svg';
import ForwardIcon from '../../assets/images/Forward.svg';
import IgnoreIcon from '../../assets/images/Ignore.svg';
import VoicemailIcon from '../../assets/images/Voicemail.svg';
import AnswerIcon from '../../assets/images/Answer.svg';
import styles from './styles.scss';
import i18n from './i18n';
export default class IncomingCallPad extends Component {
constructor(props) {
super(props);
this.state = {
showForward: false,
replyMessage: null,
showReplyWithMessage: false,
toVoiceMailEnabled: true,
replyMessageEnabled: true,
};
this.onShowForwardChange = (visible) => {
this.setState({
showForward: visible,
});
};
this.closeForwardForm = () => {
this.onShowForwardChange(false);
};
this.onShowReplyWithMessageChange = (visible) => {
this.setState({
showReplyWithMessage: visible,
});
};
this.onReplyMessageChange = (message) => {
this.setState({ replyMessage: message });
};
this.closeReplyWithMessage = () => {
this.onShowReplyWithMessageChange(false);
};
this.toVoiceMail = () => {
this.props.toVoiceMail();
if (this.props.toVoiceMail) {
this.setState({
toVoiceMailEnabled: false
});
this.voicemailTimeout = setTimeout(() => {
this.props.reject();
}, 3000);
}
};
this.replyWithMessage = (value) => {
this.props.replyWithMessage(value);
if (this.props.replyWithMessage) {
this.setState({
replyMessageEnabled: false
});
this.replyTimeout = setTimeout(() => {
this.props.reject();
}, 3000);
}
};
}
componentWillReceiveProps(newProps) {
if (this.props.sessionId !== newProps.sessionId) {
if (this.replyTimeout) {
clearTimeout(this.replyTimeout);
this.replyTimeout = null;
}
if (this.voicemailTimeout) {
clearTimeout(this.voicemailTimeout);
this.voicemailTimeout = null;
}
}
}
componentWillUnmount() {
if (this.replyTimeout) {
clearTimeout(this.replyTimeout);
this.replyTimeout = null;
}
if (this.voicemailTimeout) {
clearTimeout(this.voicemailTimeout);
this.voicemailTimeout = null;
}
}
render() {
const {
currentLocale,
reject,
answer,
forwardingNumbers,
formatPhone,
className,
hasOtherActiveCall,
answerAndEnd,
answerAndHold,
} = this.props;
// const isMultiCall = true;
const multiCallButtons = (
<div className={classnames(styles.buttonRow, styles.multiCallsButtonGroup)}>
<MultiCallAnswerButton
onClick={answerAndEnd}
title={i18n.getString('answerAndEnd', currentLocale)}
className={styles.callButton}
isEndOtherCall
/>
<ActiveCallButton
onClick={this.toVoiceMail}
title={i18n.getString('toVoicemail', currentLocale)}
buttonClassName={this.state.toVoiceMailEnabled ? styles.voiceMailButton : ''}
icon={VoicemailIcon}
iconWidth={274}
iconX={116}
showBorder={!this.state.toVoiceMailEnabled}
className={styles.callButton}
disabled={!this.state.toVoiceMailEnabled}
/>
<MultiCallAnswerButton
onClick={answerAndHold}
title={i18n.getString('answerAndHold', currentLocale)}
className={styles.callButton}
isEndOtherCall={false}
/>
</div>
);
const singleCallButtons = (
<div className={classnames(styles.buttonRow, styles.answerButtonGroup)}>
<ActiveCallButton
onClick={this.toVoiceMail}
title={i18n.getString('toVoicemail', currentLocale)}
buttonClassName={this.state.toVoiceMailEnabled ? styles.voiceMailButton : ''}
icon={VoicemailIcon}
iconWidth={274}
iconX={116}
showBorder={!this.state.toVoiceMailEnabled}
className={styles.bigCallButton}
disabled={!this.state.toVoiceMailEnabled}
/>
<ActiveCallButton
onClick={answer}
title={i18n.getString('answer', currentLocale)}
buttonClassName={styles.answerButton}
icon={AnswerIcon}
showBorder={false}
className={styles.bigCallButton}
/>
</div>
);
return (
<div className={classnames(styles.root, className)}>
<div
className={styles.forwardContainner}
ref={(containner) => {
this.forwardContainner = containner;
}}
/>
<div
className={styles.replyWithMessageContainner}
ref={(containner) => {
this.replyWithMessageContainner = containner;
}}
/>
<div className={styles.buttonRow}>
<Tooltip
defaultVisible={false}
visible={this.state.showForward}
onVisibleChange={this.onShowForwardChange}
placement="topRight"
trigger="click"
arrowContent={<div className="rc-tooltip-arrow-inner" />}
getTooltipContainer={() => this.forwardContainner}
overlay={
<ForwardForm
forwardingNumbers={forwardingNumbers}
currentLocale={currentLocale}
onCancel={this.closeForwardForm}
formatPhone={formatPhone}
onForward={this.props.onForward}
searchContact={this.props.searchContact}
searchContactList={this.props.searchContactList}
phoneTypeRenderer={this.props.phoneTypeRenderer}
/>
}
>
<ActiveCallButton
icon={ForwardIcon}
iconWidth={250}
iconX={125}
onClick={() => null}
title={i18n.getString('forward', currentLocale)}
className={styles.callButton}
/>
</Tooltip>
<Tooltip
defaultVisible={false}
visible={this.state.showReplyWithMessage}
onVisibleChange={this.onShowReplyWithMessageChange}
placement="top"
trigger="click"
arrowContent={<div className="rc-tooltip-arrow-inner" />}
getTooltipContainer={() => this.replyWithMessageContainner}
overlay={
<ReplyWithMessage
currentLocale={currentLocale}
onCancel={this.closeReplyWithMessage}
value={this.state.replyMessage}
onChange={this.onReplyMessageChange}
onReply={this.replyWithMessage}
disabled={!this.state.replyMessageEnabled}
/>
}
>
<ActiveCallButton
onClick={() => null}
icon={MessageIcon}
title={i18n.getString('reply', currentLocale)}
className={styles.callButton}
/>
</Tooltip>
<ActiveCallButton
onClick={reject}
icon={IgnoreIcon}
title={i18n.getString('ignore', currentLocale)}
className={styles.callButton}
/>
</div>
{hasOtherActiveCall ? multiCallButtons : singleCallButtons}
</div>
);
}
}
IncomingCallPad.propTypes = {
answer: PropTypes.func.isRequired,
reject: PropTypes.func.isRequired,
toVoiceMail: PropTypes.func.isRequired,
currentLocale: PropTypes.string.isRequired,
forwardingNumbers: PropTypes.array.isRequired,
formatPhone: PropTypes.func,
onForward: PropTypes.func.isRequired,
replyWithMessage: PropTypes.func.isRequired,
className: PropTypes.string,
answerAndEnd: PropTypes.func,
answerAndHold: PropTypes.func,
hasOtherActiveCall: PropTypes.bool,
sessionId: PropTypes.string.isRequired,
searchContactList: PropTypes.array.isRequired,
searchContact: PropTypes.func.isRequired,
phoneTypeRenderer: PropTypes.func,
};
IncomingCallPad.defaultProps = {
formatPhone: phone => phone,
className: null,
answerAndEnd: () => null,
answerAndHold: () => null,
hasOtherActiveCall: false,
phoneTypeRenderer: undefined,
};
|
website/src/index.js
|
chrisl8/ArloBot
|
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.css';
import './index.css';
import App from './containers/App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root'),
);
|
components/Messenger/Messenger.js
|
tbescherer/TrumpAnxietyHotline
|
import React from 'react';
import store from '../../core/store.js';
import {keycodes} from './constants.js';
class Messenger extends React.Component {
constructor(props) {
super(props);
this.post = this.post.bind(this);
this.changeBlogText = this.changeBlogText.bind(this);
this.renderPosts = this.renderPosts.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
this.postAdminMessage = this.postAdminMessage.bind(this);
this.state = {
alone: true,
user_id: "",
posts: [],
blogText: "",
error: "",
conversationID: ""
}
}
startConversationAndListen = () => {
let conversationRef = firebase.database().ref('conversations');
let that = this;
var newConvoKey = conversationRef.push().key;
conversationRef.transaction(function(conversation) {
if (conversation === null) {
let update = {};
update['open_conversation'] = newConvoKey;
update[newConvoKey] = {};
return update;
} else if (conversation.open_conversation && conversation[conversation.open_conversation]["participant1"]["id"] !== firebase.auth().currentUser.uid) {
console.log("no second participant");
newConvoKey = conversation.open_conversation;
let now = new Date();
let participantData = {
'id': firebase.auth().currentUser.uid,
'connected_datetime': now.toTimeString()
}
that.setState({'alone': false});
conversation[newConvoKey]["participant2"] = participantData;
conversation = that.postAdminMessage(conversation, newConvoKey, "Second participant connected at " + now.toTimeString())
conversation = that.postAdminMessage(conversation, newConvoKey, "OK, you're both here, let it all out!")
conversation['open_conversation'] = false;
return conversation;
} else {
conversation['open_conversation'] = newConvoKey;
let now = new Date();
let participantData = {
'id': firebase.auth().currentUser.uid,
'connected_datetime': now.toDateString()
}
conversation[newConvoKey] = {
'participant1': participantData
};
conversation = that.postAdminMessage(conversation, newConvoKey, "First participant connected at " + now.toTimeString())
conversation = that.postAdminMessage(conversation, newConvoKey, "Waiting for a second participant...")
var participantRef = firebase.database().ref('conversations/' + newConvoKey + '/participant2').limitToLast(1);
participantRef.on('value', function(data){
console.log(data.val());
if (data.val() !== null) {
that.setState({'alone': false})
}
})
return conversation;
}
}, function(error, committed, snapshot){
that.setState({conversationID: newConvoKey});
var recentPostsRef = firebase.database().ref('conversations/' + newConvoKey + '/posts').limitToLast(100);
recentPostsRef.on('child_added', function(data){
store.dispatch({type:'ADD_POST', data: {'posts': data.val()}});
});
recentPostsRef.on('child_removed', function(data){
store.dispatch({type:'DELETE_POST', data: {'posts': data.val()}});
});
});
};
postAdminMessage(conversationsRef, conversationID, postBody) {
let now = new Date();
let newPostKey = firebase.database().ref().child('conversations').push().key;
let postData = {};
let existingConvo = conversationsRef[conversationID];
let postInfo = {
'text': postBody,
'user_id': 'admin',
'post_datetime': now.toDateString(),
}
let existingPosts = existingConvo["posts"] || {};
existingPosts[newPostKey] = postInfo;
existingConvo["posts"] = existingPosts;
conversationsRef[conversationID] = existingConvo;
return conversationsRef;
}
componentWillMount() {
let that = this;
that.startConversationAndListen();
firebase.auth().signInAnonymously().catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
});
that.context.store.subscribe(function() {
let state = that.context.store.getState();
that.setState({posts: state.posts});
});
}
post() {
let newPostKey = firebase.database().ref().child('conversations').push().key;
let update = {}
let that = this;
let now = new Date();
console.log(firebase.auth().currentUser.uid);
let postData = {
'text': this.state.blogText,
'user_id': firebase.auth().currentUser.uid,
'post_datetime': now.toDateString(),
}
update['/conversations/' + this.state.conversationID + "/posts/" + newPostKey] = postData;
firebase.database().ref().update(update).then(function() {
that.setState({blogText: ""});
}).catch((e) => {
that.setState({error: true});
});
}
startOrJoinConversation() {
let newConversationKey = firebase.database().ref.child('conversations')
}
deletePost() {
console.log("should delete here");
}
changeBlogText(event) {
this.setState({blogText: event.target.value})
}
renderPosts() {
let posts = this.state.posts.map(function(post) {
let isCurrentUser = (firebase.auth().currentUser && post.user_id === firebase.auth().currentUser.uid);
return (
<div key={post.text} style={{marginLeft: '10px'}}>
{isCurrentUser ? "You" : (post.user_id == "admin" ? "Admin" : "Anonymous Ally")}: {post.text}
</div>
)
})
let style;
if (this.state.alone) {
style = {}
} else {
style = {background: '#4CAF50'}
}
return (
<div style={{width: '90%', display: 'block', position: 'relative', margin: 'auto', marginTop: '10px', paddingBottom: '10px'}} className="mdl-card mdl-shadow--2dp">
<div className="mdl-card__title" style={{fontSize: '24px', background: '#CFD8DC'}}>
Your Shared Anxiety
<div
className="mdl-button mdl-js-button mdl-button--fab mdl-button--colored"
style={Object.assign({cursor: 'default', marginRight: '0px'}, style)}
/>
</div>
<div className="mdl-card__supporting-text" style={{height: '400px', overflowY: 'scroll', width: '100%', padding: '0px'}}>
{posts}
</div>
{this.renderPostArea()}
</div>
)
}
handleKeyDown (e) {
var that = this;
if (e.keyCode == keycodes.ENTER) {
that.post();
} else {
console.log(e)
}
}
renderPostArea() {
return (
<div style={{paddingLeft: '20px', paddingRight: '20px'}}>
<div className="mdl-textfield mdl-js-textfield" style={{width: '100%'}}>
<input onChange={this.changeBlogText} placeholder="Enter your message..." onKeyDown={this.handleKeyDown} value={this.state.blogText} className="mdl-textfield__input" type="text" id="sample1"/>
</div>
{(this.state.error ? <div>Must be logged in</div> : null)}
</div>
)
}
render() {
return (
<div>
{this.renderPosts()}
</div>
)
}
}
Messenger.contextTypes = {
store: React.PropTypes.object
};
export default Messenger;
|
src/components/molecules/Loading/index.js
|
SIB-Colombia/biodiversity_catalogue_v2_frontend
|
import React from 'react';
import styled from 'styled-components';
import {Link} from 'components';
import RefreshIndicator from 'material-ui/RefreshIndicator';
import CircularProgress from 'material-ui/CircularProgress';
const Wrapper = styled.div `
text-align: center;
padding: 40px 20px;
.text{
color:#555;
font-size: 12px;
padding-top: 10px;
font-weight: lighter;
}
`
class Loading extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Wrapper className="animated fadeInUp">
<CircularProgress size={30} thickness={3} color={'#EF7748'}/>
{this.props.text && <div className="text">{this.props.text}</div>}
</Wrapper>
)
}
}
export default Loading;
|
actor-apps/app-web/src/app/components/dialog/TypingSection.react.js
|
fhchina/actor-platform
|
import React from 'react';
import { PureRenderMixin } from 'react/addons';
import classNames from 'classnames';
import DialogStore from 'stores/DialogStore';
export default React.createClass({
mixins: [PureRenderMixin],
getInitialState() {
return {
typing: null,
show: false
};
},
componentDidMount() {
DialogStore.addTypingListener(this.onTypingChange);
},
componentWillUnmount() {
DialogStore.removeTypingListener(this.onTypingChange);
},
onTypingChange() {
const typing = DialogStore.getSelectedDialogTyping();
if (typing === null) {
this.setState({show: false});
} else {
this.setState({typing: typing, show: true});
}
},
render() {
const typing = this.state.typing;
const show = this.state.show;
const typingClassName = classNames('typing', {
'typing--hidden': show === false
});
return (
<div className={typingClassName}>
<div className="typing-indicator"><i></i><i></i><i></i></div>
<span>{typing}</span>
</div>
);
}
});
|
src/routes/admin/index.js
|
ADourgarian/Syscoin-Payroll
|
/**
* 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 Layout from '../../components/Layout';
const title = 'Admin Page';
const isAdmin = false;
export default {
path: '/admin',
async action() {
if (!isAdmin) {
return { redirect: '/login' };
}
const Admin = await require.ensure([], require => require('./Admin').default, 'admin');
return {
title,
chunk: 'admin',
component: <Layout><Admin title={title} /></Layout>,
};
},
};
|
src/components/profile/Profile.js
|
n8e/melange
|
import React from 'react';
import PropTypes from 'prop-types';
import './Profile.css';
const Profile = ({ name, nameColor, textColor, profile, handleClick, handleChange }) => (
<div className="profile-card">
<h3>Profile</h3>
<div className="profile-entry">
<strong style={{ marginRight: '10px' }}>User Name:</strong>
<input name="name" type="text" value={name || ''} placeholder="user name" className="profile-input" onChange={handleChange} />
</div>
<div className="profile-entry">
<strong style={{ marginRight: '10px' }}>Email:</strong>
<input name="email" type="text" value={profile.email || ''} placeholder="email" disabled className="profile-input" onChange={handleChange} />
</div>
<div className="profile-entry">
<strong style={{ marginRight: '10px' }}>Name Color:</strong>
<input name="nameColor" type="text" value={nameColor || ''} placeholder="name color" className="profile-input" onChange={handleChange} />
</div>
<div className="profile-entry">
<strong style={{ marginRight: '10px' }}>Text Color:</strong>
<input name="textColor" type="text" value={textColor || ''} placeholder="text color" className="profile-input" onChange={handleChange} />
</div>
<div className="profile-entry">
<button className="edit-button" onClick={handleClick}>Update Profile</button>
</div>
</div>
);
Profile.propTypes = {
profile: PropTypes.shape({
email: PropTypes.string,
}).isRequired,
name: PropTypes.string.isRequired,
nameColor: PropTypes.string.isRequired,
textColor: PropTypes.string.isRequired,
handleClick: PropTypes.func.isRequired,
handleChange: PropTypes.func.isRequired,
};
export default Profile;
|
src/components/field_group.js
|
b0ts/react-redux-sweetlightstudios-website
|
import React from 'react';
import { FormGroup, ControlLabel, FormControl, HelpBlock } from 'react-bootstrap';
const FieldGroup = ({ id, label, help, ...props }) => (
<FormGroup controlId={id}>
<ControlLabel>{label}</ControlLabel>
<FormControl {...props} />
{help && <HelpBlock>{help}</HelpBlock>}
</FormGroup>
);
export default FieldGroup;
|
src/svg-icons/editor/insert-invitation.js
|
mmrtnz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorInsertInvitation = (props) => (
<SvgIcon {...props}>
<path d="M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 18H5V8h14v11z"/>
</SvgIcon>
);
EditorInsertInvitation = pure(EditorInsertInvitation);
EditorInsertInvitation.displayName = 'EditorInsertInvitation';
EditorInsertInvitation.muiName = 'SvgIcon';
export default EditorInsertInvitation;
|
react/CrossIcon/CrossIcon.sketch.js
|
seek-oss/seek-style-guide
|
import React from 'react';
import CrossIcon from './CrossIcon';
import generateSketchIconSizes from '../private/generateSketchIconSizes';
export const symbols = {
...generateSketchIconSizes('Cross', <CrossIcon />)
};
|
src/client/client-views/org.js
|
davidbstein/moderator
|
import React from 'react'
import {connect} from 'react-redux'
import API from '../client-model/API'
import EventCard from './event-card'
export default connect(
storeState => storeState,
dispatch => ({API: new API(dispatch)})
)(
class Org extends React.Component {
constructor(props) {
super(props);
}
render() {
const o = this.props.state.org;
return <div className="org">
<div className="page-header">
<div className="page-header-container">
<div className="org-title page-title">
<a href="/"> {o.title || o.domain} Moderator </a>
</div>
<div className="logout-button"><a href="/logout">logout</a></div>
</div>
</div>
<div className="underheader" />
<div className="org-event-list">
{
Object.values(this.props.state.event_lookup).sort(
(a, b) => b.id - a.id
).map(
(e) => {
console.log(e);
return <EventCard key={e.id} event={e} />
}
)
}
</div>
<div className="new-event-link-container">
<p>
<a href="/new_event">
Click here to create a new event.
</a>
</p>
<p> More information on moderator <a href="/about"> here </a></p>
</div>
</div>
}
}
);
|
router_tutorial/07-more-nesting/modules/Repo.js
|
Muzietto/react-playground
|
import React from 'react';
export default React.createClass({
render() {
return (
<div>
<h3>link of Repos remains active because Repo is nested in Repos and Repos is nested in /</h3>
<h6>here under comes the repo name</h6>
<h4>{this.props.params.repoName}</h4>
<h6>here under comes the user name</h6>
<h4>{this.props.params.userName}</h4>
</div>
);
}
});
|
renderer/components/Icon/ConnectOnboarding.js
|
LN-Zap/zap-desktop
|
import React from 'react'
const SvgConnectOnboarding = props => (
<svg height="1em" viewBox="0 0 96 62" width="1em" {...props}>
<g fill="none" fillRule="evenodd" stroke="currentColor">
<circle cx={30} cy={30} r={30} transform="translate(1 1)" />
<circle cx={30} cy={30} r={30} transform="translate(35 1)" />
</g>
</svg>
)
export default SvgConnectOnboarding
|
tests/Rules-isEmptyString-spec.js
|
yesmeck/formsy-react
|
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import Formsy from './..';
import { InputFactory } from './utils/TestInput';
const TestInput = InputFactory({
render() {
return <input value={this.getValue()} readOnly/>;
}
});
const TestForm = React.createClass({
render() {
return (
<Formsy.Form>
<TestInput name="foo" validations="isEmptyString" value={this.props.inputValue}/>
</Formsy.Form>
);
}
});
export default {
'should pass with a default value': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should fail with non-empty string': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue="abc"/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should pass with an empty string': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue=""/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), true);
test.done();
},
'should fail with undefined': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={undefined}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should fail with null': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={null}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should fail with a number': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={42}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
},
'should fail with a zero': function (test) {
const form = TestUtils.renderIntoDocument(<TestForm inputValue={0}/>);
const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(inputComponent.isValid(), false);
test.done();
}
};
|
pages/index0.js
|
adjohnson916/site-gatsby
|
import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
// Styles for highlighted code blocks.
import 'css/zenburn.css'
export default class Sass extends React.Component {
render () {
return (
<div>
<h1>
Hi people
</h1>
<p>Welcome to your new Gatsby site</p>
<h2>Below are some pages showing different capabilities built-in to Gatsby</h2>
<h3>Supported file types</h3>
<ul>
<li>
<Link to={prefixLink('/markdown/')}>Markdown</Link>
</li>
<li>
<Link to={prefixLink('/react/')}>JSX (React components)</Link>
</li>
<li>
<Link to={prefixLink('/coffee-react/')}>CJSX (Coffeescript React components)</Link>
</li>
<li>
<Link to={prefixLink('/html/')}>HTML</Link>
</li>
<li>
<Link to={prefixLink('/json/')}>JSON</Link>
</li>
<li>
<Link to={prefixLink('/yaml/')}>YAML</Link>
</li>
<li>
<Link to={prefixLink('/toml/')}>TOML</Link>
</li>
</ul>
<h3>Supported CSS processors</h3>
<ul>
<li>
<Link to={prefixLink('/postcss/')}>PostCSS</Link>
</li>
<li>
<Link to={prefixLink('/sass/')}>Sass</Link>
</li>
<li>
<Link to={prefixLink('/less/')}>Less</Link>
</li>
</ul>
</div>
)
}
}
|
app/react-icons/fa/volume-off.js
|
scampersand/sonos-front
|
import React from 'react';
import IconBase from 'react-icon-base';
export default class FaVolumeOff extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m28.6 7.9v24.2q0 0.6-0.4 1t-1 0.5-1-0.5l-7.4-7.4h-5.9q-0.6 0-1-0.4t-0.4-1v-8.6q0-0.6 0.4-1t1-0.4h5.9l7.4-7.4q0.4-0.5 1-0.5t1 0.5 0.4 1z"/></g>
</IconBase>
);
}
}
|
src/components/EditableSelectInput/EditableSelectInput.stories.js
|
austinknight/ui-components
|
import React from "react";
import { storiesOf } from "@storybook/react";
import EditableSelectInput from "./";
import { wrapComponentWithContainerAndTheme, colors } from "../styles";
const darkExample = {
height: "220px",
backgroundColor: "#2a434a",
padding: "16px"
};
const genericOptions = [
{ value: "1", label: "Option One" },
{ value: "2", label: "Option Two" },
{ value: "3", label: "Option Three" },
{ value: "4", label: "Option Four" },
{ value: "5", label: "Option Five" },
{ value: "6", label: "Option Six" },
{ value: "7", label: "Option Seven" },
{ value: "8", label: "Option Eight" },
{ value: "9", label: "Option Nine" },
{ value: "10", label: "Option Ten" },
{
value: "11",
label:
"A really long string A really long string A really long string A really long string A really long string A really long string A really long string A really long string A really long string A really long string"
}
];
function renderChapterWithTheme(theme) {
return {
info: `
Usage
~~~
import React from 'react';
import {EditableSelectInput} from 'insidesales-components';
~~~
`,
chapters: [
{
sections: [
{
title: "Default Theme",
sectionFn: () =>
wrapComponentWithContainerAndTheme(
theme,
<div style={darkExample}>
<EditableSelectInput
options={genericOptions}
value="555-555-5555"
placeholder={"Phone Number"}
/>
</div>
)
}
]
}
]
};
}
storiesOf("Form", module)
.addWithChapters("Default EditableSelectInput", renderChapterWithTheme({}))
.addWithChapters(
"EditableSelectInput w/ BlueYellow Theme",
renderChapterWithTheme(colors.blueYellowTheme)
);
|
app/javascript/mastodon/features/ui/components/tabs_bar.js
|
RobertRence/Mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import NavLink from 'react-router-dom/NavLink';
import { FormattedMessage, injectIntl } from 'react-intl';
import { debounce } from 'lodash';
import { isUserTouching } from '../../../is_mobile';
export const links = [
<NavLink className='tabs-bar__link primary' to='/statuses/new' data-preview-title-id='tabs_bar.compose' data-preview-icon='pencil' ><i className='fa fa-fw fa-pencil' /><FormattedMessage id='tabs_bar.compose' defaultMessage='Compose' /></NavLink>,
<NavLink className='tabs-bar__link primary' to='/timelines/home' data-preview-title-id='column.home' data-preview-icon='home' ><i className='fa fa-fw fa-home' /><FormattedMessage id='tabs_bar.home' defaultMessage='Home' /></NavLink>,
<NavLink className='tabs-bar__link primary' to='/notifications' data-preview-title-id='column.notifications' data-preview-icon='bell' ><i className='fa fa-fw fa-bell' /><FormattedMessage id='tabs_bar.notifications' defaultMessage='Notifications' /></NavLink>,
<NavLink className='tabs-bar__link secondary' to='/timelines/public/local' data-preview-title-id='column.community' data-preview-icon='users' ><i className='fa fa-fw fa-users' /><FormattedMessage id='tabs_bar.local_timeline' defaultMessage='Local' /></NavLink>,
<NavLink className='tabs-bar__link secondary' exact to='/timelines/public' data-preview-title-id='column.public' data-preview-icon='globe' ><i className='fa fa-fw fa-globe' /><FormattedMessage id='tabs_bar.federated_timeline' defaultMessage='Federated' /></NavLink>,
<NavLink className='tabs-bar__link primary' style={{ flexGrow: '0', flexBasis: '30px' }} to='/getting-started' data-preview-title-id='getting_started.heading' data-preview-icon='asterisk' ><i className='fa fa-fw fa-asterisk' /></NavLink>,
];
export function getIndex (path) {
return links.findIndex(link => link.props.to === path);
}
export function getLink (index) {
return links[index].props.to;
}
@injectIntl
export default class TabsBar extends React.Component {
static contextTypes = {
router: PropTypes.object.isRequired,
}
static propTypes = {
intl: PropTypes.object.isRequired,
}
setRef = ref => {
this.node = ref;
}
handleClick = (e) => {
// Only apply optimization for touch devices, which we assume are slower
// We thus avoid the 250ms delay for non-touch devices and the lag for touch devices
if (isUserTouching()) {
e.preventDefault();
e.persist();
requestAnimationFrame(() => {
const tabs = Array(...this.node.querySelectorAll('.tabs-bar__link'));
const currentTab = tabs.find(tab => tab.classList.contains('active'));
const nextTab = tabs.find(tab => tab.contains(e.target));
const { props: { to } } = links[Array(...this.node.childNodes).indexOf(nextTab)];
if (currentTab !== nextTab) {
if (currentTab) {
currentTab.classList.remove('active');
}
const listener = debounce(() => {
nextTab.removeEventListener('transitionend', listener);
this.context.router.history.push(to);
}, 50);
nextTab.addEventListener('transitionend', listener);
nextTab.classList.add('active');
}
});
}
}
render () {
const { intl: { formatMessage } } = this.props;
return (
<nav className='tabs-bar' ref={this.setRef}>
{links.map(link => React.cloneElement(link, { key: link.props.to, onClick: this.handleClick, 'aria-label': formatMessage({ id: link.props['data-preview-title-id'] }) }))}
</nav>
);
}
}
|
docs/includes/nav/Sidebar.js
|
harjeethans/materialistic
|
import React from 'react';
import {Link} from 'react-router';
function Sidebar(props) {
const renderSidebarItems = function(items){
return (
items.map((item, index) => {
return (
<li className="mdl-list__item" key={index}>
<span className="mdl-list__item-primary-content">
<Link className="mdl-navigation__link" to={'/' +item.href}>{item.text}</Link></span>
</li>
);
})
);
}
return (
<ul className="demo-list-item mdl-list">
{renderSidebarItems(props.items)}
</ul>
);
}
Sidebar.propTypes = {
items: React.PropTypes.array
};
Sidebar.defaultProps = {
items: [1]
};
export default Sidebar;
|
frontend/modules/recipe_form/components/TabbedView.js
|
RyanNoelk/OpenEats
|
import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import { Popover, OverlayTrigger } from 'react-bootstrap'
import {
injectIntl,
defineMessages,
} from 'react-intl';
class TabbedView extends React.Component {
constructor(props) {
super(props);
this.state = {
display: this.props.display || 0,
};
}
switchView = val => {
this.setState({ display: val })
};
render() {
const { formatMessage } = this.props.intl;
const messages = defineMessages({
preview: {
id: 'recipe.create.preview',
description: 'Preview',
defaultMessage: 'Preview',
},
editor: {
id: 'recipe.create.editor',
description: 'Editor',
defaultMessage: 'Editor',
},
});
let { children, label, infoTitle, infoDesc, errors } = this.props;
let { display } = this.state;
let contentClassName = classNames({
'content': true,
'has-error': !!this.props.errors
});
let navClassName = classNames({
'nav': true,
'nav-tabs': true,
'has-error': !!this.props.errors
});
const popoverHoverFocus = (
<Popover id="help" title={ infoTitle }>
{ infoDesc }
</Popover>
);
return (
<div className="live-editor">
<ul className={ navClassName }>
<li className={ classNames({ left: true, active: true })}>
<span>
{ label }
<OverlayTrigger
trigger={['hover']}
placement="top"
overlay={ popoverHoverFocus }
>
<span className="glyphicon glyphicon-info-sign"/>
</OverlayTrigger>
</span>
</li>
<li className={ classNames({ active: display === 0 })}>
<span onClick={ this.switchView.bind(this, 0) }>
{ formatMessage(messages.editor) }
</span>
</li>
<li className={ classNames({ active: display === 1 })}>
<span onClick={ this.switchView.bind(this, 1) }>
{ formatMessage(messages.preview) }
</span>
</li>
</ul>
<div className={ contentClassName }>{ children[display] }</div>
<div className="help-inline">{ errors }</div>
</div>
)
}
}
TabbedView.PropTypes = {
label: PropTypes.string.isRequired,
display: PropTypes.number,
errors: PropTypes.string,
className: PropTypes.string,
infoTitle: PropTypes.string,
infoDesc: PropTypes.string,
intl: PropTypes.obj,
};
export default injectIntl(TabbedView)
|
app/components/shape_tween.js
|
laynemcnish/personal-site
|
import React, { Component } from 'react';
import d3 from 'd3';
export default class ShapeTween extends Component {
componentDidMount () {
var node = React.findDOMNode(this);
var width = 960,
height = 500;
var projection = d3.geo.albers()
.rotate([120, 0])
.center([15, 35])
.scale(1200);
var svg = d3.select(node).append("svg")
.attr("width", width)
.attr("height", height);
d3.json("california.json", function(polygon) {
console.log(polygon);
var coordinates0 = polygon.coordinates[0].map(projection),
coordinates1 = circle(coordinates0),
path = svg.append("path"),
d0 = "M" + coordinates0.join("L") + "Z",
d1 = "M" + coordinates1.join("L") + "Z";
loop();
function loop() {
path
.attr("d", d0)
.transition()
.duration(5000)
.attr("d", d1)
.transition()
.delay(5000)
.attr("d", d0)
.each("end", loop);
}
});
function circle(coordinates) {
var circle = [],
length = 0,
lengths = [length],
polygon = d3.geom.polygon(coordinates),
p0 = coordinates[0],
p1,
x,
y,
i = 0,
n = coordinates.length;
// Compute the distances of each coordinate.
while (++i < n) {
p1 = coordinates[i];
x = p1[0] - p0[0];
y = p1[1] - p0[1];
lengths.push(length += Math.sqrt(x * x + y * y));
p0 = p1;
}
var area = polygon.area(),
radius = Math.sqrt(Math.abs(area) / Math.PI),
centroid = polygon.centroid(-1 / (6 * area)),
angleOffset = -Math.PI / 2, // TODO compute automatically
angle,
i = -1,
k = 2 * Math.PI / lengths[lengths.length - 1];
// Compute points along the circle’s circumference at equivalent distances.
while (++i < n) {
angle = angleOffset + lengths[i] * k;
circle.push([
centroid[0] + radius * Math.cos(angle),
centroid[1] + radius * Math.sin(angle)
]);
}
return circle;
}
}
render () {
return React.DOM.div(null, '');
}
}
|
src/containers/pages/create-deck/after-class-selection/left-container/filter-sidebar.js
|
vFujin/HearthLounge
|
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import IconFilter from '../../../../shared-assets/filters/redux-icon-filter';
import InputFilter from '../../../../shared-assets/filters/redux-input-filter';
import SliderFilter from '../../../../shared-assets/filters/redux-slider-filter';
import {connect} from 'react-redux';
import {toggleSelectedIcon} from "../../../../../utils/filter/toggle-selected-icon";
import {updateDeckCreationFilters} from "../../../../../redux/create-deck/actions/create-deck.action";
const FilterSidebar = ({faction, mechanics, name, race, type, cardName, cardRace, cardMechanics, cardFaction, cardType, cardHealth, cardAttack, cardDurability, cardStandardSet, cardWildSet, cardRarity, updateDeckCreationFilters}) => {
const handleSelect = (value, selector) =>{
updateDeckCreationFilters({[`card${_.startCase(selector)}`]:value});
};
const handleIconClick = (e, selector) =>{
toggleSelectedIcon(e, selector, updateDeckCreationFilters, true);
};
return (
<div className="sidebar__body">
<InputFilter attribute={name} value={cardName} filter="name" multiple={false} handleSelect={handleSelect}/>
<InputFilter attribute={race} value={cardRace} filter="race" multiple={true} handleSelect={handleSelect}/>
<InputFilter attribute={mechanics} value={cardMechanics} filter="mechanics" multiple={true} handleSelect={handleSelect}/>
<InputFilter attribute={faction} value={cardFaction} filter="faction" multiple={true} handleSelect={handleSelect}/>
<InputFilter attribute={type} value={cardType} filter="type" multiple={true} handleSelect={handleSelect}/>
<SliderFilter filter="health" value={cardHealth} defaultValue={[0, 30]} max={50} marks={{0:0, 30:30, 50:50}} handleSelect={handleSelect}/>
<SliderFilter filter="attack" value={cardAttack} defaultValue={[0, 5]} max={30} marks={{0:0, 5:5, 30:30}} handleSelect={handleSelect}/>
<SliderFilter filter="durability" value={cardDurability} defaultValue={[0, 7]} max={10} marks={{0:0, 7:7, 10:10}} handleSelect={handleSelect}/>
<IconFilter header={true} headerLabel="standard set" filter="cardSet" value={cardStandardSet} wrapperClass="sidebar-icons" isStandard={true} handleIconClick={handleIconClick}/>
<IconFilter header={true} headerLabel="wild set" filter="cardSet" value={cardWildSet} wrapperClass="sidebar-icons" isStandard={false} handleIconClick={handleIconClick}/>
<IconFilter header={true} headerLabel="rarity" filter="rarity" value={cardRarity} wrapperClass="sidebar-icons" handleIconClick={handleIconClick}/>
</div>
);
};
FilterSidebar.propTypes = {
faction: PropTypes.array,
mechanics: PropTypes.array,
name: PropTypes.array,
query: PropTypes.object,
race: PropTypes.array,
type: PropTypes.array,
};
const mapStateToProps = (state) => {
const {cardName, cardRace, cardMechanics, cardFaction, cardType, cardHealth, cardAttack, cardDurability, cardStandardSet, cardWildSet, cardRarity} = state.deckCreation;
return {
filtersQuery: {
cardName,
cardRace,
cardMechanics,
cardFaction,
cardType,
cardHealth,
cardAttack,
cardDurability,
cardRarity,
cardStandardSet,
cardWildSet
}
};
};
const mapDispatchToProps = (dispatch) => {
return {
updateDeckCreationFilters: deckCreationFilters => dispatch(updateDeckCreationFilters(deckCreationFilters)),
}
};
export default connect(mapStateToProps, mapDispatchToProps)(FilterSidebar);
|
public/js/cat_source/es6/components/modals/LoginModal.js
|
matecat/MateCat
|
import PropTypes from 'prop-types'
import update from 'immutability-helper'
import _ from 'lodash'
import React from 'react'
import TextField from '../common/TextField'
import * as RuleRunner from '../common/ruleRunner'
import * as FormRules from '../common/formRules'
import {checkRedeemProject as checkRedeemProjectApi} from '../../api/checkRedeemProject'
import {loginUser} from '../../api/loginUser'
class LoginModal extends React.Component {
constructor(props) {
super(props)
this.state = {
showErrors: false,
validationErrors: {},
generalError: '',
requestRunning: false,
}
this.state.validationErrors = RuleRunner.run(this.state, fieldValidations)
this.handleFieldChanged = this.handleFieldChanged.bind(this)
this.handleSubmitClicked = this.handleSubmitClicked.bind(this)
this.sendLoginData = this.sendLoginData.bind(this)
this.errorFor = this.errorFor.bind(this)
}
// TODO: find a way to abstract this into the plugin
otherServiceLogin() {
let url = config.pluggable.other_service_auth_url
let self = this
this.checkRedeemProject()
let newWindow = window.open(url, 'name', 'height=900,width=900')
if (window.focus) {
newWindow.focus()
}
let interval = setInterval(function () {
if (newWindow.closed) {
clearInterval(interval)
let loc
if (self.props.goToManage) {
window.location = '/manage/'
} else if ((loc = window.localStorage.getItem('wanted_url'))) {
window.localStorage.removeItem('wanted_url')
window.location.href = loc
} else {
window.location.reload()
}
}
}, 600)
}
googole_popup() {
let url = this.props.googleUrl
let self = this
this.checkRedeemProject()
let newWindow = window.open(url, 'name', 'height=600,width=900')
if (window.focus) {
newWindow.focus()
}
let interval = setInterval(function () {
if (newWindow.closed) {
clearInterval(interval)
let loc
if (self.props.goToManage) {
window.location = '/manage/'
} else if ((loc = window.localStorage.getItem('wanted_url'))) {
window.localStorage.removeItem('wanted_url')
window.location.href = loc
} else {
window.location.reload()
}
}
}, 600)
}
handleFieldChanged(field) {
return (e) => {
let newState = update(this.state, {
[field]: {$set: e.target.value},
})
newState.validationErrors = RuleRunner.run(newState, fieldValidations)
newState.generalError = ''
this.setState(newState)
}
}
handleSubmitClicked() {
let self = this
this.setState({showErrors: true})
if ($.isEmptyObject(this.state.validationErrors) == false) return null
if (this.state.requestRunning) {
return false
}
this.setState({requestRunning: true})
this.checkRedeemProject().then(
this.sendLoginData()
.then(() => {
if (self.props.goToManage) {
window.location = '/manage/'
} else {
window.location.reload()
}
})
.catch(() => {
const text = 'Login failed.'
self.setState({
generalError: text,
requestRunning: false,
})
}),
)
}
checkRedeemProject() {
if (this.props.redeemMessage) {
return checkRedeemProjectApi()
} else {
return Promise.resolve()
}
}
sendLoginData() {
return loginUser(this.state.emailAddress, this.state.password)
}
errorFor(field) {
return this.state.validationErrors[field]
}
openRegisterModal() {
$('#modal').trigger('openregister')
}
openForgotPassword() {
$('#modal').trigger('openforgotpassword')
}
googleLoginButton() {
if (!(config.pluggable && config.pluggable.auth_disable_google)) {
return (
<a
className="google-login-button btn-confirm-medium"
onClick={this.googole_popup.bind(this)}
/>
)
}
}
otherServiceLoginButton() {
if (config.pluggable && config.pluggable.other_service_auth_url) {
return (
<a
className="btn-confirm-medium"
onClick={this.otherServiceLogin.bind(this)}
>
{config.pluggable.other_service_button_label}
</a>
)
}
}
loginFormContainerCode() {
if (!(config.pluggable && config.pluggable.auth_disable_email)) {
let generalErrorHtml = ''
let buttonSignInClass =
_.size(this.state.validationErrors) === 0 ? '' : 'disabled'
if (this.state.generalError.length) {
generalErrorHtml = (
<div style={{color: 'red', fontSize: '14px'}} className="text">
{this.state.generalError}
</div>
)
}
let loaderClass = this.state.requestRunning ? 'show' : ''
return (
<div className="login-form-container">
<div className="form-divider">
<div className="divider-line"></div>
<span>OR</span>
<div className="divider-line"></div>
</div>
<TextField
showError={this.state.showErrors}
onFieldChanged={this.handleFieldChanged('emailAddress')}
placeholder="Email"
name="emailAddress"
errorText={this.errorFor('emailAddress')}
tabindex={1}
onKeyPress={(e) => {
e.key === 'Enter' ? this.handleSubmitClicked() : null
}}
/>
<TextField
type="password"
showError={this.state.showErrors}
onFieldChanged={this.handleFieldChanged('password')}
placeholder="Password (minimum 8 characters)"
name="password"
errorText={this.errorFor('password')}
tabindex={2}
onKeyPress={(e) => {
e.key === 'Enter' ? this.handleSubmitClicked() : null
}}
/>
<a
className={
'login-button btn-confirm-medium sing-in ' + buttonSignInClass
}
onKeyPress={(e) => {
e.key === 'Enter' ? this.handleSubmitClicked() : null
}}
onClick={this.handleSubmitClicked.bind()}
tabIndex={3}
>
<span className={'button-loader ' + loaderClass} /> Sign in{' '}
</a>
{generalErrorHtml}
<br />
<span className="forgot-password" onClick={this.openForgotPassword}>
Forgot password?
</span>
</div>
)
}
}
render() {
let htmlMessage = (
<div className="login-container-right">
<h2>Sign up now to:</h2>
<ul className="">
<li>Manage your TMs, glossaries and MT engines</li>
<li>Access the management panel</li>
<li>Translate Google Drive files</li>
</ul>
<a
className="register-button btn-confirm-medium"
onClick={this.openRegisterModal}
>
Sign up
</a>
</div>
)
if (this.props.redeemMessage) {
htmlMessage = (
<div className="login-container-right">
<h2 style={{fontSize: '21px'}}>
Sign up or sign in to add the project to your management panel and:
</h2>
<ul className="add-project-manage">
<li>Track the progress of your translations</li>
<li>Monitor the activity for increased security</li>
<li>Manage TMs, MT and glossaries</li>
</ul>
<a
className="register-button btn-confirm-medium sing-up"
onClick={this.openRegisterModal}
>
Sign up
</a>
</div>
)
}
return (
<div className="login-modal">
{htmlMessage}
<div className="login-container-left">
{this.otherServiceLoginButton()}
{this.googleLoginButton()}
{this.loginFormContainerCode()}
</div>
</div>
)
}
}
const fieldValidations = [
RuleRunner.ruleRunner(
'emailAddress',
'Email address',
FormRules.requiredRule,
FormRules.checkEmail,
),
RuleRunner.ruleRunner(
'password',
'Password',
FormRules.requiredRule,
FormRules.minLength(8),
),
]
LoginModal.propTypes = {
googleUrl: PropTypes.string,
}
export default LoginModal
|
src/routes.js
|
allyrippley/7ds
|
import React from 'react'
import { Route, IndexRoute } from 'react-router'
import App from './containers/App'
import Main from './containers/Main'
import AboutPage from './containers/About'
import Portfolio from './containers/Portfolio'
import PortfolioPage from './containers/Portfolio/Page'
import Contact from './containers/ContactForm'
import NotFoundPage from './components/NotFoundPage/kitty.js'
export default (
<Route path="/" component={App}>
<IndexRoute component={Main}/>
<Route path="/fuel-savings" component={Main}/>
<Route path="/portfolio/page/:id" component={PortfolioPage}/>
<Route path="/portfolio" component={Portfolio}/>
<Route path="/contact" component={Contact}/>
<Route path="/about" component={AboutPage}/>
<Route path="*" component={NotFoundPage}/>
</Route>
)
|
client/modules/App/__tests__/Components/Footer.spec.js
|
Trulsabe/reactLinuxMern
|
import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import { Footer } from '../../components/Footer/Footer';
test('renders the footer properly', t => {
const wrapper = shallow(
<Footer />
);
t.is(wrapper.find('p').length, 2);
t.is(wrapper.find('p').first().text(), '© 2016 · Hashnode · LinearBytes Inc.');
});
|
example-slack-message/src/App.js
|
atFriendly/react-native-friendly-chat
|
import React, { Component } from 'react';
import { View, Platform } from 'react-native';
import PropTypes from 'prop-types';
import { GiftedChat } from 'react-native-gifted-chat';
import emojiUtils from 'emoji-utils';
import SlackMessage from './SlackMessage';
class App extends Component {
renderMessage(props) {
const { currentMessage: { text: currText } } = props;
let messageTextStyle;
// Make "pure emoji" messages much bigger than plain text.
if (currText && emojiUtils.isPureEmojiString(currText)) {
messageTextStyle = {
fontSize: 28,
// Emoji get clipped if lineHeight isn't increased; make it consistent across platforms.
lineHeight: Platform.OS === 'android' ? 34 : 30,
};
}
return (
<SlackMessage {...props} messageTextStyle={messageTextStyle} />
);
}
render() {
return (
<GiftedChat
messages={[]}
renderMessage={this.renderMessage}
/>
);
}
}
export default App;
|
src/components/tablePrices/presentation/TPDeadlines.js
|
edu-affiliates/promo_calculators
|
'use strict';
import React from 'react';
import {connect} from 'react-redux'
import {changeDeadline} from '../../../store/actions'
class TPDeadlines extends React.Component {
constructor(props) {
super(props);
}
render() {
const {deadlineList, deadline} = this.props;
let list = deadlineList.map((d) => {
return <li key={d.id} className={`${(deadline === d.name) ? 'active' : ''} tp-deadline__item`}>{d.name}</li>
});
return (
<div className="tp-deadline">
<div className="tp-deadline__top">
<div className="tp-deadline__title">DEADLINE</div>
<div className="tp-deadline__icon">
<img src={require("../../../images/icons/tp.svg")}/>
</div>
</div>
<ul className="tp-deadline__list">
{list}
</ul>
</div>
)
}
}
//container to match redux state to component props and dispatch redux actions to callback props
const mapStateToProps = (reduxState, ownProps) => {
const state = reduxState.calculatorSmall[ownProps.calcId];
return {
deadlineList: state.currentDeadlines,
deadline: state.deadline.name,
}
};
const mapDispatchToProps = (reduxState, ownProps) => {
return {
changeDeadline: (id) => {
dispatch(changeDeadline(id, ownProps.calcId))
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(TPDeadlines);
|
src/components/course/CourseForm.js
|
RockingChewee/react-redux-building-applications
|
import React from 'react';
import TextInput from '../common/TextInput';
import SelectInput from '../common/SelectInput';
const CourseForm = ({course, allAuthors, onSave, onChange, saving, errors}) => {
return (
<form>
<h1>Manage Course</h1>
<TextInput
name="title"
label="Title"
value={course.title}
onChange={onChange}
error={errors.title}/>
<SelectInput
name="authorId"
label="Author"
value={course.authorId}
defaultOption="Select Author"
options={allAuthors}
onChange={onChange}
error={errors.authorId}/>
<TextInput
name="category"
label="Category"
value={course.category}
onChange={onChange}
error={errors.category}/>
<TextInput
name="length"
label="Length"
value={course.length}
onChange={onChange}
error={errors.length}/>
<input
type="submit"
disabled={saving}
value={saving ? 'Saving...' : 'Save'}
className="btn btn-primary"
onClick={onSave}/>
</form>
);
};
CourseForm.propTypes = {
course: React.PropTypes.object.isRequired,
allAuthors: React.PropTypes.array,
onSave: React.PropTypes.func.isRequired,
onChange: React.PropTypes.func.isRequired,
saving: React.PropTypes.bool,
errors: React.PropTypes.object
};
export default CourseForm;
|
packages/my-joy-instances/src/containers/create-instance/index.js
|
geek/joyent-portal
|
/* eslint-disable camelcase */
import React from 'react';
import { Margin } from 'styled-components-spacing';
import ReduxForm from 'declarative-redux-form';
import { stopAsyncValidation, SubmissionError, destroy } from 'redux-form';
import { connect } from 'react-redux';
import { set, destroyAll } from 'react-redux-values';
import { graphql, compose } from 'react-apollo';
import intercept from 'apr-intercept';
import constantCase from 'constant-case';
import queryString from 'query-string';
import get from 'lodash.get';
import lvalues from 'lodash.values';
import omit from 'lodash.omit';
import uniqBy from 'lodash.uniqby';
import {
ViewContainer,
H2,
Button,
Message,
MessageTitle,
MessageDescription
} from 'joyent-ui-toolkit';
import Name from '@containers/create-instance/name';
import Image from '@containers/create-instance/image';
import Package from '@containers/create-instance/package';
import Tags from '@containers/create-instance/tags';
import Metadata from '@containers/create-instance/metadata';
import UserScript from '@containers/create-instance/user-script';
import Networks from '@containers/create-instance/networks';
import Firewall from '@containers/create-instance/firewall';
import CNS from '@containers/create-instance/cns';
import Affinity from '@containers/create-instance/affinity';
import CreateInstanceMutation from '@graphql/create-instance.gql';
import GetInstance from '@graphql/get-instance-small.gql';
import createClient from '@state/apollo-client';
import parseError from '@state/parse-error';
import { Forms, Values } from '@root/constants';
const {
IC_F,
IC_NAME_F,
IC_IMG_F,
IC_PKG_F_SELECT,
IC_NW_F,
IC_US_F,
IC_FW_F_ENABLED
} = Forms;
const {
IC_MD_V_MD,
IC_TAG_V_TAGS,
IC_AFF_V_AFF,
IC_CNS_V_ENABLED,
IC_CNS_V_SERVICES,
IC_V_VALIDATING
} = Values;
const CreateInstance = ({
history,
match,
query,
step,
error,
disabled,
shouldAsyncValidate,
handleAsyncValidate,
handleSubmit,
validating
}) => (
<ViewContainer>
<Margin top={4} bottom={4}>
<H2>Create Instances</H2>
</Margin>
{error ? (
<Margin bottom={4}>
<Message error>
<MessageTitle>Ooops!</MessageTitle>
<MessageDescription>{error}</MessageDescription>
</Message>
</Margin>
) : null}
{query.image ? (
<Image
history={history}
match={match}
query={query}
step="image"
expanded={step === 'image'}
/>
) : null}
<Name
history={history}
match={match}
query={query}
step="name"
expanded={step === 'name'}
/>
{!query.image ? (
<Image
history={history}
match={match}
query={query}
step="image"
expanded={step === 'image'}
/>
) : null}
<Package
history={history}
match={match}
step="package"
expanded={step === 'package'}
/>
<Tags
history={history}
match={match}
step="tags"
expanded={step === 'tags'}
/>
<Metadata
history={history}
match={match}
step="metadata"
expanded={step === 'metadata'}
/>
<UserScript
history={history}
match={match}
step="user-script"
expanded={step === 'user-script'}
/>
<Networks
history={history}
match={match}
step="networks"
expanded={step === 'networks'}
/>
<Firewall
history={history}
match={match}
step="firewall"
expanded={step === 'firewall'}
/>
<CNS history={history} match={match} step="cns" expanded={step === 'cns'} />
<Affinity
history={history}
match={match}
step="affinity"
expanded={step === 'affinity'}
/>
<Margin top={7} bottom={10}>
{error ? (
<Margin bottom={4}>
<Message error>
<MessageTitle>Ooops!</MessageTitle>
<MessageDescription>{error}</MessageDescription>
</Message>
</Margin>
) : null}
<ReduxForm
form={IC_F}
shouldAsyncValidate={shouldAsyncValidate}
asyncValidate={handleAsyncValidate}
onSubmit={handleSubmit}
>
{({ handleSubmit, submitting }) => (
<form onSubmit={handleSubmit}>
<Button disabled={disabled} loading={submitting || validating}>
Deploy
</Button>
</form>
)}
</ReduxForm>
</Margin>
</ViewContainer>
);
export default compose(
graphql(CreateInstanceMutation, { name: 'createInstance' }),
connect(({ form, values }, { match, location }) => {
const query = queryString.parse(location.search);
const step = get(match, 'params.step', 'name');
const validating = get(values, IC_V_VALIDATING, false);
const isNameInvalid = get(form, `${IC_NAME_F}.asyncErrors.name`, null);
const error = get(form, `${IC_F}.error`, null);
const name = get(form, `${IC_NAME_F}.values.name`, '');
const image = get(form, `${IC_IMG_F}.values.image`, '');
const pkg = get(form, `${IC_PKG_F_SELECT}.values.package`, '');
const networks = get(form, `${IC_NW_F}.values`, {});
const enabled =
!isNameInvalid &&
name.length &&
image.length &&
pkg.length &&
lvalues(networks).filter(Boolean).length;
if (!enabled) {
return {
validating,
error,
query,
disabled: !enabled,
step
};
}
const metadata = get(values, IC_MD_V_MD, []);
const tags = get(values, IC_TAG_V_TAGS, []).map(tag => tag); // clone
const affinity = get(values, IC_AFF_V_AFF, null);
const cns = get(values, IC_CNS_V_ENABLED, true);
const cnsServices = get(values, IC_CNS_V_SERVICES, null);
const userScript = get(form, `${IC_US_F}.values.value`, '');
const firewall_enabled = get(
form,
`${IC_FW_F_ENABLED}.values.enabled`,
false
);
tags.push({
name: 'triton.cns.disable',
value: !cns
});
if (cnsServices && cns) {
tags.push({
name: 'triton.cns.services',
value: cnsServices.join(',')
});
}
return {
validating,
error,
query,
forms: Object.keys(form), // improve this
name,
pkg,
image,
affinity,
metadata,
userScript,
tags,
firewall_enabled,
networks,
step
};
}),
connect(null, (dispatch, ownProps) => {
const {
name,
pkg,
image,
affinity,
metadata,
userScript,
tags,
firewall_enabled,
networks,
forms,
createInstance,
history
} = ownProps;
const parseAffRule = ({
conditional,
placement,
identity,
name,
pattern,
value
}) => {
const type = constantCase(
`${conditional}_${placement === 'same' ? 'equal' : 'not_equal'}`
);
const patterns = {
equalling: value => value,
starting: value => `/^${value}/`
};
const _name = identity === 'name' ? 'instance' : name;
const _value = patterns[pattern](type === 'name' ? name : value);
return {
type,
key: _name,
value: _value
};
};
return {
shouldAsyncValidate: ({ trigger }) => {
return trigger === 'submit';
},
handleAsyncValidate: async () => {
dispatch(set({ name: IC_V_VALIDATING, value: true }));
const [nameError, res] = await intercept(
createClient().query({
fetchPolicy: 'network-only',
query: GetInstance,
variables: { name }
})
);
if (nameError) {
return dispatch([
set({ name: IC_V_VALIDATING, value: false }),
stopAsyncValidation(IC_F, { _error: parseError(nameError) })
]);
}
const { data } = res;
const { machines = [] } = data;
if (machines.length) {
return dispatch([
set({ name: IC_V_VALIDATING, value: false }),
stopAsyncValidation(IC_F, { _error: `${name} already exists.` })
]);
}
dispatch(set({ name: IC_V_VALIDATING, value: false }));
},
handleSubmit: async () => {
const _affinity = affinity ? parseAffRule(affinity) : null;
const _name = name.toLowerCase();
const _metadata = metadata.map(a => omit(a, 'open'));
const _tags = uniqBy(tags.map(a => omit(a, 'expanded')), 'name').map(
a => omit(a, 'expanded')
);
const _networks = Object.keys(networks).filter(
network => networks[network]
);
if (userScript && userScript.length) {
_metadata.push({ name: 'user-script', value: userScript });
}
const [err, res] = await intercept(
createInstance({
variables: {
name: _name,
package: pkg,
image,
affinity: _affinity ? [_affinity] : [],
metadata: _metadata,
tags: _tags,
firewall_enabled,
networks: _networks.length ? _networks : undefined
}
})
);
if (err) {
throw new SubmissionError({
_error: parseError(err)
});
}
dispatch([destroyAll(), forms.map(name => destroy(name))]);
history.push(`/instances/${res.data.createMachine.id}`);
}
};
})
)(CreateInstance);
|
packages/icons/src/md/image/ExposureNeg2.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdExposureNeg2(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M31.09 33.58l5.73-6.13c.75-.79 1.44-1.57 2.08-2.35.63-.78 1.18-1.56 1.64-2.33.46-.78.82-1.55 1.07-2.33.26-.78.39-1.57.39-2.37 0-1.07-.18-2.04-.54-2.92-.36-.87-.88-1.62-1.57-2.23-.69-.61-1.53-1.08-2.53-1.42-1-.33-2.14-.5-3.42-.5-1.38 0-2.62.21-3.7.64-1.08.43-1.99 1.01-2.73 1.75s-1.3 1.61-1.68 2.6c-.36.94-.54 1.95-.56 3.01h4.28c.01-.62.09-1.21.26-1.74.18-.58.45-1.08.81-1.5.36-.42.81-.74 1.35-.98.55-.23 1.19-.35 1.93-.35.61 0 1.15.1 1.62.31.47.21.87.49 1.19.85.32.36.57.8.74 1.29.17.5.25 1.04.25 1.63 0 .43-.06.87-.17 1.3-.11.43-.3.9-.58 1.4-.28.5-.65 1.05-1.11 1.66-.46.6-1.05 1.29-1.75 2.07l-8.35 9.11V37H43v-3.42H31.09zM5 23v4h16v-4H5z" />
</IconBase>
);
}
export default MdExposureNeg2;
|
frontend/src/components/Auth/presenter.js
|
plusbeauxjours/nomadgram
|
import React from 'react';
import styles from './styles.scss';
import PropTypes from 'prop-types';
import LoginForm from 'components/LoginForm';
import SignupForm from 'components/SignupForm';
const Auth = (
{
action,
changeAction
},
context
) => (
<main className={styles.auth}>
<div className={styles.column}>
<img src={require("images/phone.png" )} alt={context.t('Check our app. Is cool')} />
</div>
<div className={styles.column}>
<div className={`${styles.whiteBox} ${styles.formBox}`}>
{action === 'login' && <LoginForm />}
{action === 'signup' && <SignupForm />}
</div>
<div className={styles.whiteBox}>
{action === "login" && (
<p className={styles.text}>
{context.t("Don't have an account?")}{" "}
<span className={styles.changeLink} onClick={changeAction}>
{context.t('Sign up')}
</span>
</p>
)}
{action === "signup" && (
<p className={styles.text}>
{context.t('Have an account?')}{" "}
<span className={styles.changeLink} onClick={changeAction}>
{context.t('Log in')}
</span>
</p>
)}
</div>
<div className={styles.appBox}>
<span>{context.t('Get the app')}</span>
<div className={styles.appstores}>
<img
src={require("images/ios.png")}
alt={context.t('Download it on the Apple Appstore')}
/>
<img
src={require("images/android.png")}
alt={context.t('Download it on tha Android Appstore')}
/>
</div>
</div>
</div>
</main>
);
Auth.propTypes = {
action: PropTypes.string.isRequired,
changeAction: PropTypes.func.isRequired,
};
Auth.contextTypes = {
t: PropTypes.func.isRequired
};
export default Auth;
|
app/index.js
|
binayverma/weathernow
|
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { AppContainer } from 'react-hot-loader';
import configureStore from './store/configureStore';
import Root from './containers/Root';
import './styles/index.scss';
import './styles/footer.scss';
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
render(
<AppContainer>
<Root store={store} history={history} />
</AppContainer>,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept('./containers/Root', () => {
const NewRoot = require('./containers/Root').default;
render(
<AppContainer>
<NewRoot store={store} history={history} />
</AppContainer>,
document.getElementById('root')
);
});
}
|
examples/vuecli3-custom/styleguide/components/SectionsRenderer.js
|
vue-styleguidist/vue-styleguidist
|
import React from 'react';
import PropTypes from 'prop-types';
import Styled from 'rsg-components/Styled';
import Heading from 'rsg-components/Heading';
// Avoid circular ref
// Import default implementation using `rsg-components-default`
import DefaultSectionsRenderer from 'rsg-components-default/Sections/SectionsRenderer';
const styles = ({ fontFamily, space }) => ({
headingSpacer: {
marginBottom: space[2],
},
descriptionText: {
marginTop: space[0],
fontFamily: fontFamily.base,
},
});
export function SectionsRenderer({ classes, children }) {
return (
<div>
{!!children.length &&
<div className={classes.headingSpacer}>
<Heading level={1}>Example Components</Heading>
<p className={classes.descriptionText}>These are the greatest components</p>
</div>}
<DefaultSectionsRenderer>{children}</DefaultSectionsRenderer>
</div>
);
}
SectionsRenderer.propTypes = {
classes: PropTypes.object.isRequired,
children: PropTypes.node,
};
export default Styled(styles)(SectionsRenderer);
|
src/components/Home.js
|
aalselius/Test
|
import React, { Component } from 'react';
import Image from './Image.js';
import ImageHeader from './ImageHeader.js';
import InfoText from './InfoText.js';
import Header from './Header.js';
class Home extends Component {
constructor() {
super();
this.state = {
imageUrl: '',
url:'',
inputType: '',
imageNumber: 0,
json:'',
images:[],
text: 'cat',
loaded: false,
}
}
componentDidMount() {
this.url = "http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC";
console.log(this.url);
fetch(this.url)
.then((data) => {
return data.json();
})
.then((json) => {
console.log(json);
this.setState({json:json});
this.setState({imageUrl:this.state.json.data[0].images.downsized.url});
this.setState({loaded: true});
})
;
}
changeLink = (arrow) => {
if (arrow === "left") {
this.setState({imageNumber: this.state.imageNumber -1}); //previous state, if 0 => 25
if (this.state.imageNumber <= 0) {
this.setState({imageNumber: 24}); //previous state, if 0 => 25
}
} else if (arrow === "right") {
this.setState({imageNumber: this.state.imageNumber +1}); // previous state, if 25 => 0
if (this.state.imageNumber >= 24) {
this.setState({imageNumber: 0}); //previous state, if 0 => 25
}
}
console.log(this.state.imageNumber);
let xx=this.state.json;
this.setState ({imageUrl:xx.data[this.state.imageNumber].images.downsized.url});
}
updateText = (event) => {
this.setState({text: event.target.value})
}
handleSubmit = (event) => {
if(event.keyCode === 13) {
this.setState({text: event.target.value})
console.log(this.state.text);
// set new url
this.updateUrl(this.state.text);
event.target.value='';
}
}
render() {
return (
<div className="pageContainer">
<Header headerText="Home" headerClass="sideHeader"/>
<ImageHeader text="Popular Giphy"/>
{this.state.loaded ? (
<div>
<div className="imageContainer">
<i className="fa fa-angle-left" onClick={()=>this.changeLink("left")}></i>
<Image url={this.state.imageUrl}/>
<i className="fa fa-angle-right" onClick={()=>this.changeLink("right")}></i>
</div>
<InfoText infoText="I don't take responsibility for giphys shown on this site. There is no filter on the giphys."/>
</div>
) : (
<div className="imageContainer"><i className="fa fa-spinner" aria-hidden="true"></i></div>
)}
</div>
);
}
}
export default Home;
|
client/views/admin/settings/SettingsRoute.js
|
VoiSmart/Rocket.Chat
|
import React from 'react';
import NotAuthorizedPage from '../../../components/NotAuthorizedPage';
import { useRouteParameter } from '../../../contexts/RouterContext';
import { useIsPrivilegedSettingsContext } from '../../../contexts/SettingsContext';
import EditableSettingsProvider from '../../../providers/EditableSettingsProvider';
import GroupSelector from './GroupSelector';
export function SettingsRoute() {
const hasPermission = useIsPrivilegedSettingsContext();
const groupId = useRouteParameter('group');
if (!hasPermission) {
return <NotAuthorizedPage />;
}
return (
<EditableSettingsProvider>
<GroupSelector groupId={groupId} />
</EditableSettingsProvider>
);
}
export default SettingsRoute;
|
src/components/posts_index.js
|
937aaron/reduxblog
|
import _ from 'lodash'
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions';
import { Link } from 'react-router-dom';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts()
}
renderPosts(){
return _.map(this.props.posts, post => {
return(
<li className="list-group-item" key={post.id}>
<Link to={`/posts/${post.id}`}>
{post.title}
</Link>
</li>
);
});
}
render() {
return (
<div>
<div className="text-xs-right">
<Link className="btn btn-primary" to="/posts/new">Add a Post +</Link>
</div>
<h3>Posts:</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
)
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts }) (PostsIndex);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.