path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
blueocean-material-icons/src/js/components/svg-icons/image/photo-camera.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImagePhotoCamera = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImagePhotoCamera.displayName = 'ImagePhotoCamera';
ImagePhotoCamera.muiName = 'SvgIcon';
export default ImagePhotoCamera;
|
src/components/loading-indicators/loading-repository-list-item.component.js | housseindjirdeh/git-point | import React, { Component } from 'react';
import { StyleSheet, Animated, View } from 'react-native';
import { colors } from 'config';
import { loadingAnimation } from 'utils';
const styles = StyleSheet.create({
container: {
paddingTop: 20,
paddingRight: 20,
paddingBottom: 20,
height: 100,
borderBottomColor: '#ededed',
borderBottomWidth: 1,
backgroundColor: 'transparent',
},
wrapper: {
flex: 1,
flexDirection: 'column',
marginLeft: 10,
},
textBarTitle: {
height: 7,
width: 100,
backgroundColor: colors.greyDarkest,
marginBottom: 10,
},
textBarLine1: {
height: 7,
width: 250,
backgroundColor: colors.grey,
marginBottom: 10,
},
textBarLine2: {
height: 7,
width: 80,
backgroundColor: colors.grey,
},
});
export class LoadingRepositoryListItem extends Component {
constructor() {
super();
this.state = {
fadeAnimValue: new Animated.Value(0),
};
}
componentDidMount() {
loadingAnimation(this.state.fadeAnimValue).start();
}
render() {
return (
<View style={styles.container}>
<View style={styles.wrapper}>
<Animated.View
style={[styles.textBarTitle, { opacity: this.state.fadeAnimValue }]}
/>
<Animated.View
style={[styles.textBarLine1, { opacity: this.state.fadeAnimValue }]}
/>
<Animated.View
style={[styles.textBarLine2, { opacity: this.state.fadeAnimValue }]}
/>
</View>
</View>
);
}
}
|
app/components/DatePicker.js | matthieuh/desktop-assistant | // @flow
import React, { Component } from 'react';
import moment from 'moment';
import DayPicker from 'react-day-picker';
import classNames from 'classnames/bind';
import styles from './DatePicker.css';
const cx = classNames.bind(styles);
export default class DatePicker extends Component {
state: {
modalVisible: boolean,
selectedDay: Date
};
props: {
input: Object,
meta: Object,
label: string
}
constructor() {
super();
this.state = { modalVisible: false, selectedDay: new Date() };
}
onDayChange(day) {
const value = moment(day);
this.setState({
modalVisible: false,
selectedDay: day,
displayValue: value.format('MM-DD-YYYY')
});
this.props.input.onChange(value.format());
}
componentWillReceiveProps(nextProps) {
if (nextProps && nextProps.value) {
this.setState({
displayValue: moment(nextProps.value).format('MM-DD-YYYY')
});
}
}
handleClick() {
this.setState({ modalVisible: true });
}
closeModal() {
this.setState({ modalVisible: false });
}
render() {
const { input: { label, onChange }, meta: { touched, error, invalid, warning } } = this.props;
const modalClassName = cx({
modal: true,
visible: this.state.modalVisible
});
return (
<div className={styles.container}>
<div className={`${touched && invalid ? 'has-error' : ''}`}>
<label htmlFor={this.props.input.name} className="control-label">{this.props.label}</label>
<div>
<input
{...this.props.input}
value={this.state.displayValue}
className="form-control"
placeholder="Select a date"
onClick={this.handleClick.bind(this)}
/>
<div className="help-block">
{touched && ((error && <span>{error}</span>) || (warning && <span>{warning}</span>))}
</div>
<div className={modalClassName}>
<button className={styles.close} onClick={this.closeModal.bind(this)} />
<DayPicker
selectedDays={this.state.selectedDay}
onDayClick={day => { this.onDayChange(day); }}
/>
</div>
</div>
</div>
</div>
);
}
}
|
app/components/PageItemCard/index.js | interra/data-generate | import React from 'react';
import PropTypes from 'prop-types';
import Item from './Item';
import Wrapper from './Wrapper';
import LoadingIndicator from 'components/LoadingIndicator';
import { Link } from 'react-router-dom';
import { Parser } from 'html-to-react';
import ellipsize from 'ellipsize';
function PageItemCard(props) {
const computeGrid = (numberOfItems) => {
let number = 3;
if (numberOfItems === 2) {
number = 6;
}
else if (numberOfItems === 3) {
number = 4;
}
else if (numberOfItems === 4) {
number = 3;
}
else if (numberOfItems === 5 || numberOfItems == 6) {
number = 3;
}
return number;
}
const label = props.label ? <strong>{props.labelValue}:</strong> : '';
if (props.loading || !props.data.collection) {
return (
<LoadingIndicator />
)
} else {
const maxPerRow = 4;
const num = props.data.collection.length;
const numRows = num > maxPerRow ? Math.ceil(num/maxPerRow) : 1;
const columnWidth = computeGrid(num);
const parser = new Parser();
const items = props.data.collection.map(function(item, i) {
const ref = `${props.data.collectionType}/${item.interra.id}`;
const description = item.description ? parser.parse(ellipsize(item.description, 150)) : '';
// TODO: Maybe default image?
const image = 'image' in item ? <img style={{top: "50%",transform: "translateY(-50%)", position: "relative", maxHeight: "150px", maxWidth: "300px"}} alt={`image for ${item.name}`} src={item. image}/> : <div style={{height: "125px"}}className="font-icon-select-1 font-icon-select-1-account-group-1"></div>;
item.columnWidth = columnWidth;
return <div key={`col-${i}`} className={`col-lg-${columnWidth}`}>
<article style={{minHeight: "435px", marginBottom: "20px"}}>
<div style={{textAlign: "center", height: "155px"}}>
<Link to={ref}>{image}</Link>
</div>
<h2 style={{fontSize: "25px", lineHeight: "35px"}}><Link to={ref}>{item.name}</Link></h2>
<div>
{description}
</div>
</article>
</div>;
});
let count = 0;
const rows = [...Array(numRows)].map((e, i) => {
let divs = '';
divs = [...Array(maxPerRow)].map((l, x) => {
const item = items[count];
count = count + 1;
return item;
});
return <div key={`row-${i}`} className="row">{divs}</div>;
});
return (
<div style={{margin: "10px -5px"}}>
{label} {rows}
</div>
);
}
}
/**
PageItemCard.propTypes = {
item: PropTypes.any,
};
*/
export default PageItemCard;
|
submissions/arqex/src/boot.js | okmttdhr/flux-challenge | import React from 'react';
import AppContainer from './components/AppContainer';
import State from './State';
// Subscribe reactions
import './Reactions';
// Start listening to planet updates
var ws = new WebSocket('ws://localhost:4000');
ws.onmessage = function (event) {
State.trigger('planet:update', JSON.parse(event.data) );
};
// Fetch the first sith
State.trigger('siths:fetch', 3616);
React.render(<AppContainer />, document.getElementById('root'));
|
examples/src/components/Virtualized.js | Paveltarno/react-select | import React from 'react';
import VirtualizedSelect from 'react-virtualized-select';
const DATA = require('../data/cities');
var CitiesField = React.createClass({
displayName: 'CitiesField',
getInitialState () {
return {};
},
updateValue (newValue) {
this.setState({
selectValue: newValue
});
},
render () {
var options = DATA.CITIES;
return (
<div className="section">
<h3 className="section-heading">Cities (Large Dataset)</h3>
<VirtualizedSelect ref="citySelect"
options={options}
simpleValue
clearable
name="select-city"
value={this.state.selectValue}
onChange={this.updateValue}
searchable
labelKey="name"
valueKey="name"
/>
<div className="hint">
Uses <a href="https://github.com/bvaughn/react-virtualized">react-virtualized</a> and <a href="https://github.com/bvaughn/react-virtualized-select/">react-virtualized-select</a> to display a list of the world's 1,000 largest cities.
</div>
</div>
);
}
});
module.exports = CitiesField;
|
templates/rubix/demo/src/routes/Cropjs.js | jeffthemaximum/jeffline | import React from 'react';
import ReactDOM from 'react-dom';
import {
Row,
Col,
Grid,
Form,
Panel,
Checkbox,
PanelBody,
PanelHeader,
FormControl,
ControlLabel,
PanelContainer,
} from '@sketchpixy/rubix';
export default class Cropjs extends React.Component {
componentDidMount() {
(() => {
$(ReactDOM.findDOMNode(this.refs.target)).Jcrop({
setSelect: [ 60, 50, 540, 300 ]
});
})();
(() => {
var jcrop_api;
// Simple event handler, called from onChange and onSelect
// event handlers, as per the Jcrop invocation above
var showCoords = (c) => {
$('#x1').val(c.x);
$('#y1').val(c.y);
$('#x2').val(c.x2);
$('#y2').val(c.y2);
$('#w').val(c.w);
$('#h').val(c.h);
};
var clearCoords = () => {
$('#coords input').val('');
};
$(ReactDOM.findDOMNode(this.refs.eventtarget)).Jcrop({
onChange : showCoords,
onSelect : showCoords,
onRelease: clearCoords,
setSelect: [ 60, 50, 540, 300 ]
}, function() {
jcrop_api = this;
});
$('#coords').on('change','input', function(e){
var x1 = $('#x1').val(),
x2 = $('#x2').val(),
y1 = $('#y1').val(),
y2 = $('#y2').val();
jcrop_api.setSelect([x1,y1,x2,y2]);
});
})();
(() => {
// Create variables (in this scope) to hold the API and image size
var jcrop_api,
boundx,
boundy,
// Grab some information about the preview pane
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
var updatePreview = (c) => {
if (parseInt(c.w) > 0) {
var rx = xsize / c.w;
var ry = ysize / c.h;
$pimg.css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
};
$(ReactDOM.findDOMNode(this.refs.aspectwithpreview)).Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: xsize / ysize,
setSelect: [ 60, 50, 540, 300 ]
}, function() {
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
jcrop_api = this;
// Move the preview into the jcrop container for css positioning
$preview.appendTo(jcrop_api.ui.holder);
});
})();
(() => {
var jcrop_api;
$(ReactDOM.findDOMNode(this.refs.animationstransitions)).Jcrop({
bgFade: true,
bgOpacity: .2,
setSelect: [ 60, 50, 540, 300 ]
}, function() {
jcrop_api = this;
});
$('#fadetog').change(function() {
jcrop_api.setOptions({
bgFade: this.checked
});
}).attr('checked','checked');
$('#shadetog').change(function() {
if (this.checked) $('#shadetxt').slideDown();
else $('#shadetxt').slideUp();
jcrop_api.setOptions({
shade: this.checked
});
}).attr('checked',false);
// Define page sections
var sections = {
bgc_buttons: 'Change bgColor',
bgo_buttons: 'Change bgOpacity',
anim_buttons: 'Animate Selection'
};
// Define animation buttons
var ac = {
anim1: [217,122,382,284],
anim2: [20,20,580,380],
anim3: [24,24,176,376],
anim4: [347,165,550,355],
anim5: [136,55,472,183]
};
// Define bgOpacity buttons
var bgo = {
Low: .2,
Mid: .5,
High: .8,
Full: 1
};
// Define bgColor buttons
var bgc = {
R: '#900',
B: '#4BB6F0',
Y: '#F0B207',
G: '#46B81C',
W: 'white',
K: 'black'
};
// Create fieldset targets for buttons
for(var i in sections)
insertSection(i,sections[i]);
function create_btn(c) {
var $o = $('<button />').addClass('btn btn-small btn-outlined btn-primary');
if (c) $o.append(c);
return $o;
}
var a_count = 1;
// Create animation buttons
for(var i in ac) {
$('#anim_buttons .btn-group')
.append(
create_btn(a_count++).click(animHandler(ac[i])),
' '
);
}
$('#anim_buttons .btn-group').append(
create_btn('Bye!').click((e) => {
$(e.target).addClass('active');
jcrop_api.animateTo(
[300,200,300,200],
function() {
this.release();
$(e.target).closest('.btn-group').find('.active').removeClass('active');
}
);
return false;
})
);
// Create bgOpacity buttons
for(var i in bgo) {
$('#bgo_buttons .btn-group').append(
create_btn(i).click(setoptHandler('bgOpacity',bgo[i])),
' '
);
}
// Create bgColor buttons
for(var i in bgc) {
$('#bgc_buttons .btn-group').append(
create_btn(i).css({
background: bgc[i],
color: ((i == 'K') || (i == 'R'))?'white':'black'
}).click(setoptHandler('bgColor',bgc[i])), ' '
);
}
// Function to insert named sections into interface
function insertSection(k,v) {
$('#interface').prepend(
$('<fieldset></fieldset>').attr('id',k).append(
$('<legend></legend>').append(v),
'<div class="btn-toolbar"><div class="btn-group"></div></div>'
)
);
};
// Handler for option-setting buttons
function setoptHandler(k,v) {
return function(e) {
$(e.target).closest('.btn-group').find('.active').removeClass('active');
$(e.target).addClass('active');
var opt = { };
opt[k] = v;
jcrop_api.setOptions(opt);
return false;
};
};
// Handler for animation buttons
function animHandler(v) {
return function(e) {
$(e.target).addClass('active');
jcrop_api.animateTo(v, () => {
$(e.target).closest('.btn-group').find('.active').removeClass('active');
});
return false;
};
};
$('#bgo_buttons .btn:first,#bgc_buttons .btn:last').addClass('active');
$('#interface').show();
})();
}
render() {
return (
<Row>
<Col sm={12}>
<PanelContainer>
<Panel>
<PanelHeader className='bg-orange75 fg-white' style={{margin: 0}}>
<Grid>
<Row>
<Col xs={12}>
<h3>jCrop : Basic</h3>
</Col>
</Row>
</Grid>
</PanelHeader>
<PanelBody>
<Grid>
<Row>
<Col xs={12}>
<br/>
<div><img src='/imgs/app/wefunction/020.jpg' ref='target' alt='[Jcrop example]' width='100%' height='350' /></div>
<br/>
<p>
<strong>
This example demonstrates the default behavior of Jcrop.
</strong><br/>
<span>Since no event handlers have been attached it only performs the cropping behavior.</span>
</p>
</Col>
</Row>
</Grid>
</PanelBody>
</Panel>
</PanelContainer>
<PanelContainer>
<Panel>
<PanelHeader className='bg-darkgreen45 fg-white' style={{margin: 0}}>
<Grid>
<Row>
<Col xs={12}>
<h3>jCrop : Handler</h3>
</Col>
</Row>
</Grid>
</PanelHeader>
<PanelBody>
<Grid>
<Row>
<Col xs={12}>
<br/>
<div><img src='/imgs/app/unsplash/parie.jpg' ref='eventtarget' alt='[Jcrop example]' width='100%' height='350' /></div>
<br/>
<Form id="coords"
className="coords">
<div className="inline-labels">
<ControlLabel className='inline'>X1 <FormControl defaultValue={0} className='form-control' type="text" size="4" id="x1" name="x1" /></ControlLabel>
<ControlLabel className='inline'>Y1 <FormControl defaultValue={0} className='form-control' type="text" size="4" id="y1" name="y1" /></ControlLabel>
<ControlLabel className='inline'>X2 <FormControl defaultValue={0} className='form-control' type="text" size="4" id="x2" name="x2" /></ControlLabel>
<ControlLabel className='inline'>Y2 <FormControl defaultValue={0} className='form-control' type="text" size="4" id="y2" name="y2" /></ControlLabel>
<ControlLabel className='inline'>W <FormControl defaultValue={0} className='form-control' type="text" size="4" id="w" name="w" /></ControlLabel>
<ControlLabel className='inline'>H <FormControl defaultValue={0} className='form-control' type="text" size="4" id="h" name="h" /></ControlLabel>
</div>
</Form>
<div className="description">
<p>
<b>{"An example with a basic event handler."}</b>{"Here we've tied several form values together with a simple event handler invocation. The result is that the form values are updated in real-time as the selection is changed using Jcrop's "}<em>onChange</em> handler.
</p>
<p>
{"That's how easily Jcrop can be integrated into a traditional web form!"}
</p>
</div>
</Col>
</Row>
</Grid>
</PanelBody>
</Panel>
</PanelContainer>
<PanelContainer>
<Panel>
<PanelHeader className='bg-red fg-white' style={{margin: 0}}>
<Grid>
<Row>
<Col xs={12}>
<h3>jCrop : Aspect Ratio with Preview Pane</h3>
</Col>
</Row>
</Grid>
</PanelHeader>
<PanelBody>
<Grid>
<Row>
<Col xs={12}>
<br/>
<Grid>
<Row>
<Col sm={8} collapseLeft collapseRight>
<img src='/imgs/app/unsplash/hot-air-baloon.jpg' ref='aspectwithpreview' alt='[Jcrop example]' width='100%' height='350' />
</Col>
<Col sm={4} collapseLeft collapseRight>
<div id='preview-pane' style={{display: 'block', position: 'absolute', zIndex: 2000, top: 10, right: '-250px', padding: 6, border: '1px rgba(0,0,0,.4) solid', background: 'white', borderRadius: 6}}>
<div className='preview-container' style={{width: 225, height: 170, overflow: 'hidden'}}>
<img src='/imgs/app/unsplash/hot-air-baloon.jpg' className='jcrop-preview' alt='Preview' width='100%' />
</div>
</div>
</Col>
</Row>
</Grid>
<br/>
<div className='description'>
<p>
<b>An example implementing a preview pane.</b>
Obviously the most visual demo, the preview pane is accomplished
entirely outside of Jcrop with a simple jQuery-flavored callback.
This type of interface could be useful for creating a thumbnail
or avatar. The onChange event handler is used to update the
view in the preview pane.
</p>
</div>
</Col>
</Row>
</Grid>
</PanelBody>
</Panel>
</PanelContainer>
<PanelContainer>
<Panel>
<PanelHeader className='bg-purple fg-white' style={{margin: 0}}>
<Grid>
<Row>
<Col xs={12}>
<h3>jCrop : Animations + Transitions</h3>
</Col>
</Row>
</Grid>
</PanelHeader>
<PanelBody>
<Grid>
<Row>
<Col xs={12}>
<br/>
<Grid>
<Row>
<Col sm={7} collapseLeft collapseRight>
<div><img src='/imgs/app/wefunction/020.jpg' ref='animationstransitions' alt='[Jcrop example]' width='100%' height='350' /></div>
<br/>
<div className="description">
<p id="shadetxt" style={{display:'none', color:'#900'}}>
<b>Experimental shader active.</b>
<span>{"Jcrop now includes a shading mode that facilitates building better transparent Jcrop instances. The experimental shader is less robust than Jcrop's default shading method and should only be used if you require this functionality."}</span>
</p>
<p>
<b>Animation/Transitions.</b>
<span>{"Demonstration of animateTo API method and transitions for bgColor and bgOpacity options. Color fading requires inclusion of John Resig's jQuery"}</span><a href="http://plugins.jquery.com/project/color">Color Animations</a>{" plugin. If it is not included, colors will not fade."}
</p>
</div>
</Col>
<Col sm={5} id='interface'>
<Checkbox id='fadetog'>
Enable fading (bgFade: true)
</Checkbox>
<Checkbox id='shadetog'>
Use experimental shader (shade: true)
</Checkbox>
</Col>
</Row>
</Grid>
</Col>
</Row>
</Grid>
</PanelBody>
</Panel>
</PanelContainer>
</Col>
</Row>
);
}
}
|
test-harness/app/index.js | bugsnag/bugsnag-react-native | import React, { Component } from 'react';
import { Platform, Navigator, View } from 'react-native';
import { Client, Configuration, StandardDelivery } from "bugsnag-react-native";
import { bugsnag } from 'lib/bugsnag';
import Main from './components/scenes/main';
import Repos from './components/scenes/repos';
import Crashy from './components/scenes/crashy';
import Register from './components/scenes/register';
export default class App extends Component {
constructor(props) {
super(props);
const config = new Configuration();
config.apiKey = "123";
// Android emulator uses 10.0.2.2 by default
const endpoint = Platform.OS === 'android' ? "http://10.0.2.2:9999" : "http://localhost:9999";
config.delivery = new StandardDelivery(endpoint);
const client = new Client(config);
client.notify(new Error(`Whoops!`));
}
render() {
return (
<View/>
);
}
}
|
packages/react-scripts/fixtures/kitchensink/src/features/env/NodePath.js | Antontsyk/react_vk | import React from 'react'
import load from 'absoluteLoad'
export default class extends React.Component {
constructor(props) {
super(props);
this.done = () => {};
this.props.setCallWhenDone && this.props.setCallWhenDone((done) => {
this.done = done;
});
this.state = { users: [] };
}
async componentDidMount() {
const users = load();
this.setState({ users }, () => this.done());
}
render() {
return (
<div id="feature-node-path">
{this.state.users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
);
}
}
|
src/components/PlayerController.js | Greatlemer/react-gomoku-bot | import React, { Component } from 'react';
import PropTypes from 'prop-types';
class PlayerController extends Component {
constructor() {
super();
this.handleGameTick = this.handleGameTick.bind(this);
this.getStatus = this.getStatus.bind(this);
this.nextMove = this.nextMove.bind(this);
this.state = {
playingMove: false,
}
}
componentDidMount() {
this.context.loop.subscribe(this.handleGameTick);
}
componentWillUnmount() {
this.context.loop.unsubscribe(this.handleGameTick);
}
handleGameTick() {
const moveNumber = this.props.nextMoveNumber;
if (this.props.isWaitingForMove && this.state.playingMove !== moveNumber) {
this.setState({
playingMove: moveNumber,
});
this.nextMove(this.props.board, this.props.playMove);
} else if(!this.props.isWaitingForMove && this.state.playingMove) {
this.setState({
playingMove: false,
});
}
}
async nextMove(board, playFunc) {
playFunc(1);
}
getStatus() {
return 'Implement me!';
}
render() {
return <p className='unknown-player'>{this.getStatus()}</p>
}
}
PlayerController.contextTypes = {
loop: PropTypes.object,
}
export default PlayerController;
|
src/svg-icons/navigation/more-vert.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationMoreVert = (props) => (
<SvgIcon {...props}>
<path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/>
</SvgIcon>
);
NavigationMoreVert = pure(NavigationMoreVert);
NavigationMoreVert.displayName = 'NavigationMoreVert';
export default NavigationMoreVert;
|
src/svg-icons/communication/phonelink-lock.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationPhonelinkLock = (props) => (
<SvgIcon {...props}>
<path d="M19 1H9c-1.1 0-2 .9-2 2v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm-8.2 10V9.5C10.8 8.1 9.4 7 8 7S5.2 8.1 5.2 9.5V11c-.6 0-1.2.6-1.2 1.2v3.5c0 .7.6 1.3 1.2 1.3h5.5c.7 0 1.3-.6 1.3-1.2v-3.5c0-.7-.6-1.3-1.2-1.3zm-1.3 0h-3V9.5c0-.8.7-1.3 1.5-1.3s1.5.5 1.5 1.3V11z"/>
</SvgIcon>
);
CommunicationPhonelinkLock = pure(CommunicationPhonelinkLock);
CommunicationPhonelinkLock.displayName = 'CommunicationPhonelinkLock';
CommunicationPhonelinkLock.muiName = 'SvgIcon';
export default CommunicationPhonelinkLock;
|
example/razzle-ssr/src/Home.js | i18next/react-i18next | import React from 'react';
import { Trans, useTranslation } from 'react-i18next';
import logo from './react.svg';
import './Home.css';
function Home() {
const [ t ] = useTranslation('translations');
return (
<div className="Home">
<div className="Home-header">
<img src={logo} className="Home-logo" alt="logo" />
<h2>{t('message.welcome')}</h2>
</div>
<div className="Home-intro">
<Trans i18nKey="guideline">
To get started, edit <code>src/App.js</code> or <code>src/Home.js</code> and save to
reload.
</Trans>
</div>
<ul className="Home-resources">
<li>
<a href="https://github.com/jaredpalmer/razzle">Docs</a>
</li>
<li>
<a href="https://github.com/jaredpalmer/razzle/issues">Issues</a>
</li>
<li>
<a href="https://palmer.chat">Community Slack</a>
</li>
</ul>
</div>
);
}
export default Home;
|
MyApp/view/sectionList.js | liwei0505/react-native | /**
* Created by lee on 2017/9/18.
*/
import React, { Component } from 'react';
import {
AppRegistry,
SectionList,
StyleSheet,
Text,
View
} from 'react-native';
export default class SectionListBasics extends Component {
render() {
return (
<View style = {styles.container} >
<SectionList
sections={[
{title: 'D', data: ['Devin']},
{title: 'J', data: ['Jackson', 'James', 'Jillian', 'Jimmy', 'Joel', 'John', 'Julie']},
]}
renderItem = {({item}) => <Text style={styles.item}>{item}</Text>}
renderSectionHeader = {({section}) => <Text style={styles.sectionHeader}>{section.title}</Text> }
/>
</View>
);
}
}
const styles = StyleSheet.create({
container:{
flex: 1,
paddingTop: 22,
},
sectionHeader: {
paddingTop: 2,
paddingLeft: 10,
paddingRight: 10,
paddingBottom: 2,
fontSize: 14,
fontWeight: 'bold',
backgroundColor: 'rgba(247,247,247,1.0)',
},
item:{
padding: 10,
fontSize: 18,
height: 44,
},
}) |
docs/app/Examples/modules/Checkbox/States/CheckboxExampleReadOnly.js | clemensw/stardust | import React from 'react'
import { Checkbox } from 'semantic-ui-react'
const CheckboxExampleReadOnly = () => (
<Checkbox label='This checkbox is read-only' readOnly />
)
export default CheckboxExampleReadOnly
|
common/components/App.js | BostonGlobe/elections-2017 | import React from 'react'
import PropTypes from 'prop-types'
const App = ({ children }) => (
<div className='App'>
{ children }
</div>
)
App.propTypes = {
children: PropTypes.object.isRequired,
}
export default App
|
src/example/treemap/simple-treemap.js | jameskraus/react-vis | // Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import {Treemap} from '../../';
export default class SimpleTreemapExample extends React.Component {
render() {
return (
<Treemap
data={{
title: '',
children: [
{
title: 'China',
size: 1357
},
{
title: 'India',
size: 1252
},
{
title: 'USA',
size: 321
},
{
title: 'Indonesia',
size: 249.9
},
{
title: 'Brasil',
size: 200.4
},
{
title: 'Pakistan',
size: 192
},
{
title: 'Nigeria',
size: 173.6
}
]
}}
height={300}
width={350}/>
);
}
}
|
examples/_dustbin-simple/index.js | prometheusresearch/react-dnd | 'use strict';
import React from 'react';
import Container from './Container';
const DustbinSimple = React.createClass({
render() {
return (
<div>
<Container />
<hr />
<p>
Drag items on a dropzone. Note that it has different neutral, active (something is being dragged) and hovered states.
Dragged item itself has neutral and dragging states.
</p>
</div>
);
}
});
export default DustbinSimple; |
src/server/express.js | fk1blow/react-presentception | /*eslint-disable no-console */
import React from 'react';
import compression from 'compression';
import config from './config';
import express from 'express';
import favicon from 'serve-favicon';
import render from './render';
export default function() {
const app = express();
app.use(compression());
// TODO: Add favicon.
// app.use(favicon('assets/img/favicon.ico'))
// TODO: Move to CDN.
app.use('/build', express.static('build'));
app.use('/assets', express.static('assets'));
app.get('*', (req, res) => {
const acceptsLanguages = req.acceptsLanguages(config.appLocales);
render(req, res, acceptsLanguages || config.defaultLocale)
.catch((error) => {
const msg = error.stack || error;
console.log(msg);
res.status(500).send('500: ' + msg);
});
});
app.listen(config.port);
console.log(`App started on port ${config.port}`);
}
|
docs/pages/templates/_template.js | tleunen/react-mdl | import React from 'react';
// import { Link } from 'react-router';
// import { prefixLink } from 'gatsby-helpers';
const Template = (props) => (
<div>{props.children}</div>
);
export default Template;
|
assets/javascript/components/viewActivity/viewActivity.js | colinjeanne/learning-site | import ActivityLinksList from './activityLinksList';
import { activityPropType } from './../propTypes';
import React from 'react';
const viewActivity = props => {
const linksSection = props.activity.activityLinks ?
(
<section>
<h2>Links</h2>
<ActivityLinksList
activityLinks={props.activity.activityLinks} />
</section>
) :
undefined;
return (
<section>
<section
className="activityViewHeader">
<button
onClick={props.onBack}
type="button">
Back
</button>
<button
className="activityEditButton"
onClick={props.onEdit}
type="button">
Edit
</button>
</section>
<h1>
{props.activity.name}
</h1>
<section className="activityView">
<section>
{props.activity.description}
</section>
{linksSection}
</section>
</section>
);
};
viewActivity.propTypes = {
activity: activityPropType.isRequired,
onBack: React.PropTypes.func.isRequired,
onEdit: React.PropTypes.func.isRequired
};
export default viewActivity; |
src/components/Text/Paragraph.js | primaveraentalca/lavoragine-contentful | import React from 'react';
const Paragraph = (props) => (
<p
style={{
color:'rgba(0,0,0,.8)',
fontSize: '1.33em',
textAlign: 'justify'
}}
>
{props.children}
</p>
);
export default Paragraph;
|
src/components/CastTable/CastTable.js | Nanjaa/Webcomic | import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './CastTable.scss';
import Firebase from 'firebase';
import Link from '../Link';
class CastTable extends React.Component {
constructor(props) {
super(props);
this.state = {
mainCharacters: [],
secondaryCharacters: [],
otherCharacters: []
}
this.pageLink = this.pageLink.bind(this);
this.componentWillMount = this.componentWillMount.bind(this);
this.characterCard = this.characterCard.bind(this);
}
componentWillMount() {
var ref = Firebase.database().ref("Cast/");
ref.once("value")
.then(function(snapshot) {
var cast = snapshot.val(),
mainCharacters = [],
secondaryCharacters = [],
otherCharacters = [];
for(var i=0; i<cast.length; i++) {
if(cast[i].Importance === 1) {
mainCharacters.push(cast[i]);
}
else if(cast[i].Importance === 2) {
secondaryCharacters.push(cast[i]);
}
else {
otherCharacters.push(cast[i]);
}
}
this.setState({
mainCharacters: mainCharacters,
secondaryCharacters: secondaryCharacters,
otherCharacters: otherCharacters
});
}.bind(this))
}
pageLink(number) {
var pageNumber = '/page/' + number;
return pageNumber;
}
characterCard(character) {
var characterImg = 'http://nanja.space/Hubris/Cast/' + character.Img;
return(
<div className={s.characterCard}>
<h4 className={s.mobileOnly}>{character.Name}</h4>
<img src={characterImg}/>
<div className={s.characterText}>
<h4 className={s.mobileHidden}>{character.Name}</h4>
<p>{character.Desc}</p>
<Link to={this.pageLink(character.FirstPage)}>First Appearance: Page {character.FirstPage}</Link>
</div>
</div>
)
}
render() {
return(
<div className={s.root}>
<div className={s.container}>
<h3>Main Characters</h3>
{this.state.mainCharacters.map((character) => {
return(
<div className={s.charactersList} key={character.Name}>
{this.characterCard(character)}
</div>
)
})}
<h3>Secondary Characters</h3>
{this.state.secondaryCharacters.map((character) => {
return(
<div className={s.charactersList} key={character.Name}>
{this.characterCard(character)}
</div>
)
})}
<h3>Other Characters</h3>
{this.state.otherCharacters.map((character) => {
return(
<div className={s.charactersList} key={character.Name}>
{this.characterCard(character)}
</div>
)
})}
</div>
</div>
)
}
}
export default withStyles(CastTable, s); |
ui/src/boot.js | starbops/OpenADM | import React from 'react';
import ReactDOM from 'react-dom';
import { syncHistoryWithStore } from 'react-router-redux';
import { browserHistory } from 'react-router';
import Immutable from 'seamless-immutable';
import configureStore from './js/stores/configureStore';
import Root from './js/Root.js';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
const initialState = Immutable.from({
routing: { locationBeforeTransitions: null },
layout: {
gridLayout: [
{ i: 'Flowtable', x: 1, y: 5, w: 8, h: 7 },
{ i: 'ControllerStatus', x: 4, y: 0, w: 5, h: 3 },
{ i: 'PortStatus', x: 4, y: 0, w: 5, h: 3 },
{ i: 'SettingContainer', x: 1, y: 0, w: 5, h: 8 },
],
hiddenPanel: ['Flowtable', 'ControllerStatus', 'PortStatus', 'SettingContainer'],
maximumPanel: '',
},
setting: {
coreURL: '',
controllerURL: '',
controllerName: '',
},
topology: {
filterType: [
{ type: 'type', filter: 'switch' },
{ type: 'id', filter: '00:0a:00:00:00:51:85:91' },
],
selectNodes: {},
level: 0,
nodes: [],
fixedNode: {},
links: [],
controllerList: [],
},
controllerStatus: [],
flowtable: {
filterString: '',
visibleField: ['ipv4'],
flowlist: [{ controller: '', flows: [] }],
selectFlow: {},
},
portStatus: [],
});
const store = configureStore(initialState, browserHistory);
const history = syncHistoryWithStore(
browserHistory,
store,
{ selectLocationState: state => state.routing }
);
ReactDOM.render(
<Root store={store} history={history} />,
document.getElementById('app')
);
export default store;
|
src/routes.js | Anshul-HL/blitz-vihanga | import React from 'react';
import {IndexRoute, Route, Router} from 'react-router';
import {
App,
Home,
// NotFound,
PastProjectList,
PastProject,
WardRobes,
Kitchens,
WallUnits,
PressCoverage,
About,
Contact,
TermsOfUse,
PrivacyPolicy,
Sitemap,
Whyhomelane,
LandingPage
} from 'containers';
export default () => {
/**
* Please keep routes in alphabetical order
*/
return (
<Router>
<Route path="/hl/homeinteriors1" component={LandingPage}/>
<Route path="/hl/homeinteriors" component={LandingPage} />
<Route path="/" component={App}>
<IndexRoute component={Home}/>
//<Route path="about" component={About}/>
//<Route path="kitchens" component={Kitchens}/>
//<Route path="wardrobes" component={WardRobes}/>
//<Route path="wallunits" component={WallUnits}/>
//<Route path="pastprojects" component={PastProjectList}/>
//<Route path="pastprojects/:projectUrl" component={PastProject}/>
//<Route path="press-coverage" component={PressCoverage} />
//<Route path="contact" component={Contact}/>
//<Route path="termsofuse" component={TermsOfUse} />
//<Route path="privacypolicy" component={PrivacyPolicy} />
//<Route path="sitemap" component={Sitemap} />
//<Route path="whyhomelane" component={Whyhomelane} />
//<Route path="hl/homeinteriors" component={LandingPage} />
//<Route path="hl/homeinteriors1" component={LandingPage} />
{ /* Catch all route
<Route path="*" component={NotFound} status={404} />
*/ }
</Route>
</Router>
);
};
|
app/javascript/mastodon/features/compose/components/character_counter.js | narabo/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { length } from 'stringz';
class CharacterCounter extends React.PureComponent {
static propTypes = {
text: PropTypes.string.isRequired,
max: PropTypes.number.isRequired,
};
checkRemainingText (diff) {
if (diff < 0) {
return <span className='character-counter character-counter--over'>{diff}</span>;
}
return <span className='character-counter'>{diff}</span>;
}
render () {
const diff = this.props.max - length(this.props.text);
return this.checkRemainingText(diff);
}
}
export default CharacterCounter;
|
src/svg-icons/communication/speaker-phone.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationSpeakerPhone = (props) => (
<SvgIcon {...props}>
<path d="M7 7.07L8.43 8.5c.91-.91 2.18-1.48 3.57-1.48s2.66.57 3.57 1.48L17 7.07C15.72 5.79 13.95 5 12 5s-3.72.79-5 2.07zM12 1C8.98 1 6.24 2.23 4.25 4.21l1.41 1.41C7.28 4 9.53 3 12 3s4.72 1 6.34 2.62l1.41-1.41C17.76 2.23 15.02 1 12 1zm2.86 9.01L9.14 10C8.51 10 8 10.51 8 11.14v9.71c0 .63.51 1.14 1.14 1.14h5.71c.63 0 1.14-.51 1.14-1.14v-9.71c.01-.63-.5-1.13-1.13-1.13zM15 20H9v-8h6v8z"/>
</SvgIcon>
);
CommunicationSpeakerPhone = pure(CommunicationSpeakerPhone);
CommunicationSpeakerPhone.displayName = 'CommunicationSpeakerPhone';
export default CommunicationSpeakerPhone;
|
blueocean-material-icons/src/js/components/svg-icons/action/timeline.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionTimeline = (props) => (
<SvgIcon {...props}>
<path d="M23 8c0 1.1-.9 2-2 2-.18 0-.35-.02-.51-.07l-3.56 3.55c.05.16.07.34.07.52 0 1.1-.9 2-2 2s-2-.9-2-2c0-.18.02-.36.07-.52l-2.55-2.55c-.16.05-.34.07-.52.07s-.36-.02-.52-.07l-4.55 4.56c.05.16.07.33.07.51 0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2c.18 0 .35.02.51.07l4.56-4.55C8.02 9.36 8 9.18 8 9c0-1.1.9-2 2-2s2 .9 2 2c0 .18-.02.36-.07.52l2.55 2.55c.16-.05.34-.07.52-.07s.36.02.52.07l3.55-3.56C19.02 8.35 19 8.18 19 8c0-1.1.9-2 2-2s2 .9 2 2z"/>
</SvgIcon>
);
ActionTimeline.displayName = 'ActionTimeline';
ActionTimeline.muiName = 'SvgIcon';
export default ActionTimeline;
|
examples/src/index.js | onurhb/react-popover-portal | import { Router, Route, browserHistory, IndexRoute } from 'react-router'
import ReactDOM from 'react-dom';
import React from 'react';
// - Root component
import App from './components/App';
import Basic from './routes/Basic';
import Arrow from './routes/Arrow';
import Animated from './routes/Animated';
import Group from './routes/Group';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Basic}></IndexRoute>
<Route path='arrow' component={Arrow}></Route>
<Route path='animated' component={Animated}></Route>
<Route path='group' component={Group}></Route>
</Route>
</Router>,
document.getElementById('root')
);
|
features/apimgt/org.wso2.carbon.apimgt.store.feature/src/main/resources/store_new/source/src/app/components/Layout/Header/Header.js | lakmali/carbon-apimgt | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react'
import {Link, withRouter} from "react-router-dom";
import AuthManager from '../../../data/AuthManager.js';
import qs from 'qs'
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import IconButton from 'material-ui/IconButton';
import MenuIcon from 'material-ui-icons/Menu';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import Menu, { MenuItem } from 'material-ui/Menu';
class Header extends React.Component {
constructor(props){
super(props);
this.state = {
anchorEl: undefined,
open: false,
}
}
handleClick = event => {
this.setState({ open: true, anchorEl: event.currentTarget });
};
handleRequestClose = () => {
this.setState({ open: false });
};
leftMenuToggle = () => {
}
render(props) {
let params = {};
return (
<AppBar position="static">
<Toolbar>
<IconButton color="contrast" aria-label="Menu">
<MenuIcon onClick={this.leftMenuToggle} />
</IconButton>
<Typography type="title" color="inherit" style={{flex:1}}>
<Link to="/" style={{ textDecoration: 'none' }}>
<Button color="primary">
<img className="brand" src="/store_new/public/images/logo.svg" alt="wso2-logo"/>
<span style={{fontSize:"20px"}}>APIM Store</span>
</Button>
</Link>
</Typography>
{ AuthManager.getUser() ?
<div>
<Button aria-owns="simple-menu" aria-haspopup="true" onClick={this.handleClick}>
Open Menu
</Button>
<Menu
id="simple-menu"
anchorEl={this.state.anchorEl}
open={this.state.open}
onRequestClose={this.handleRequestClose}
>
<MenuItem onClick={this.handleRequestClose}>Change Password</MenuItem>
<MenuItem onClick={this.handleRequestClose}>
<Link to="/logout" style={{color:"#000",textDecoration: 'none'}}>Logout</Link>
</MenuItem>
</Menu>
</div>
:
<div>
<Button color="contrast">Sign Up</Button>
<Button color="contrast">Sign In</Button>
</div> }
</Toolbar>
</AppBar>
);
}
}
export default withRouter(Header) |
app/components/Navbar.js | mestern/farmers_market | import React from 'react'
import { connect } from 'react-redux'
import { Link, browserHistory } from 'react-router'
import {logout} from '../reducers/auth'
const Navbar = (props) => {
console.log('navbar props', props)
return (
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-collapse">
<ul className="nav navbar-nav navbar-right navflex">
<li><Link to="/">HOME</Link></li>
<li><Link to="/">ABOUT</Link></li>
{
(props.auth && props.auth.farmer) ? <li><Link to={`/listproduce`}>ADD PRODUCE</Link></li> : <li><Link to={`/produce`}>VIEW PRODUCE</Link></li>
}
{
(props.auth && props.auth.farmer) ? <li><Link to={`/requests`}>VIEW REQUESTS</Link></li> : <li></li>
}
{
props.auth ? <li><Link to={`/dashboard`}>MY ACCOUNT</Link></li> : <li></li>
}
{
props.auth ? <li><button className="mybutton" onClick={props.logout}>LOG OUT</button></li> : <li><Link to="/Login">LOG IN</Link></li>
}
</ul>
<ul className="nav navbar-nav navbar-left">
<li className="nav-item dropdown navbar-left">
<a className="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<img src="/arrow.png" width="40" height="40"/>
</a>
<div className="dropdown-menu navbar-left" id="navbar-drop" aria-labelledby="navbarDropdownMenuLink">
<p className="dropdown-item" href="#">Farmers</p>
<br/>
<p className="dropdown-item" href="#">Produce</p>
</div>
</li>
</ul>
</div>
</div>
</nav>
)
}
const mapStateToProps = (state) => ({
auth: state.auth
})
// const mapDispatchToProps = (dispatch, getState) => ({
// logoutUser(dispatch) {
// dispatch(logout)
// console.log('in logout func')
// browserHistory.push('/')
// }
// })
export default connect(mapStateToProps, { logout })(Navbar)
|
client/src/components/Star.js | chi-bumblebees-2017/gnomad | import React, { Component } from 'react';
import { Button, Icon, Segment } from 'semantic-ui-react';
class Star extends Component {
constructor(props) {
super(props);
this.color = this.color.bind(this);
this.userData = this.userData.bind(this);
this.state = {
count: props.count,
}
this.changeCount = this.changeCount.bind(this);
this.toggleStar = this.props.action;
}
color() {
if (this.props.starred) {
return "yellow";
} else { return "grey"; }
}
userData(id) {
var data = new FormData();
data.append("star[recipient_id]", id);
return data;
}
changeCount(){
let newStatus = this.toggleStar();
if (newStatus === true) {
this.setState({count: (this.state.count + 1)})
}
else if (newStatus === false) {
this.setState({count: (this.state.count - 1)})
} else { alert("SOMETHING IS FUCKY HERE")}
}
componentDidUpdate() {
if (this.props.starred) {
fetch(`/stars`, {
method: 'POST',
accept: 'application/json',
headers: {
'Authorization': localStorage.getItem('gnomad-auth-token'),
},
body: this.userData(this.props.userID),
});
} else if (!this.props.starred) {
fetch(`/stars`, {
method: 'DELETE',
accept: 'application/json',
headers: {
'Authorization': localStorage.getItem('gnomad-auth-token'),
},
body: this.userData(this.props.userID),
});
} else {
alert("Error: could not complete action, please try again later");
}
}
render() {
return(
<Button compact content='Stars' size='mini' icon='star' color={this.color()} onClick={this.changeCount}
label={{basic: true, color: this.color(), content: this.state.count, pointing: 'left', size: 'mini'}} />
);
}
}
export default Star
|
packages/material-ui/src/Portal/LegacyPortal.js | cherniavskii/material-ui | import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import ownerDocument from 'dom-helpers/ownerDocument';
import exactProp from '../utils/exactProp';
function getContainer(container, defaultContainer) {
container = typeof container === 'function' ? container() : container;
return ReactDOM.findDOMNode(container) || defaultContainer;
}
function getOwnerDocument(element) {
return ownerDocument(ReactDOM.findDOMNode(element));
}
/**
* @ignore - internal component.
*
* This module will soon be gone. We should drop it as soon as react@15.x support stop.
*/
class LegacyPortal extends React.Component {
componentDidMount() {
this.mounted = true;
this.renderOverlay();
}
componentDidUpdate(prevProps) {
if (this.overlayTarget && prevProps.container !== this.props.container) {
this.mountNode.removeChild(this.overlayTarget);
this.mountNode = getContainer(this.props.container, getOwnerDocument(this).body);
this.mountNode.appendChild(this.overlayTarget);
}
this.renderOverlay();
}
componentWillUnmount() {
this.mounted = false;
this.unrenderOverlay();
this.unmountOverlayTarget();
}
/**
* @public
*/
getMountNode = () => {
return this.mountNode;
};
mountOverlayTarget = () => {
if (!this.overlayTarget) {
this.overlayTarget = document.createElement('div');
this.mountNode = getContainer(this.props.container, getOwnerDocument(this).body);
this.mountNode.appendChild(this.overlayTarget);
}
};
unmountOverlayTarget = () => {
if (this.overlayTarget) {
this.mountNode.removeChild(this.overlayTarget);
this.overlayTarget = null;
}
this.mountNode = null;
};
unrenderOverlay = () => {
if (this.overlayTarget) {
ReactDOM.unmountComponentAtNode(this.overlayTarget);
this.overlayInstance = null;
}
};
renderOverlay = () => {
const overlay = this.props.children;
this.mountOverlayTarget();
const initialRender = !this.overlayInstance;
this.overlayInstance = ReactDOM.unstable_renderSubtreeIntoContainer(
this,
overlay,
this.overlayTarget,
() => {
if (initialRender && this.props.onRendered) {
this.props.onRendered();
}
},
);
};
render() {
return null;
}
}
LegacyPortal.propTypes = {
children: PropTypes.element.isRequired,
container: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
onRendered: PropTypes.func,
};
LegacyPortal.propTypes = exactProp(LegacyPortal.propTypes, 'LegacyPortal');
export default LegacyPortal;
|
hub-ui/src/dashboard/components/Dashboard.js | lchase/hub | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactGridLayout from 'react-grid-layout';
import ChatWidget from '../../components/chat/ChatWidget';
import AddDashboardDialog from './AddDashboardDialog';
import { DatePicker, Progress, Card } from 'antd';
const defaultWidgetWidth = 3;
const defaultWidgetHeight = 3;
export default class Dashboard extends Component {
constructor(props) {
super(props);
console.log('Dashboard.constructor', props);
}
render() {
return (
<ReactGridLayout className="layout" cols={12} rowHeight={30} width={1200}>
{this.props.widgetComponents.map(component => {
let Widget = component.slug;
//let componentProps = component.props;
// return <Widget key={component.id}>
// </Widget>
return <div key={component.id}
data-grid={{
x: component.column * defaultWidgetWidth,
y: component.row * defaultWidgetHeight,
w: defaultWidgetWidth,
h: defaultWidgetHeight,
minW: 2,
maxW: 4}}>
<Widget key={component.id}>
</Widget>
</div>
})}
</ReactGridLayout>
);
//TODO: test render the component, show an error in UI if component rendering failed
//NOTE: It is important that "TestComponent" or any user-defined component (i.e. one that is not built in to react) start with a
//capital letter in order to be instantiated correctly.
// See https://facebook.github.io/react/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized
//let TestComponent = this.props.component.slug;
// return <TestComponent {...this.props}>
// {this.props.component.value}
// </TestComponent>;
// return (
// <ul>
// {this.props.widgetComponents.map(component => {
// let Widget = component.slug;
// //let componentProps = component.props;
// return <Widget key={component.id}>
// </Widget>
// })}
// </ul>
// );
}
}
Dashboard.propTypes = {
widgetComponents: PropTypes.array.isRequired
};
/*
<DatePicker />
<Card title="Card title" extra={<a href="#">More</a>} style={{ width: 300 }}>
<div>
<Progress percent={30} strokeWidth={5} />
<Progress percent={50} strokeWidth={5} status="active" />
<Progress percent={70} strokeWidth={5} status="exception" />
<Progress percent={100} strokeWidth={5} />
<Progress percent={50} strokeWidth={5} showInfo={false} />
<Progress type="circle" percent={30} width={80} />
<Progress type="circle" percent={70} width={80} status="exception" />
<Progress type="circle" percent={100} width={80} />
</div>
</Card>
<AddDashboardDialog />
<ReactGridLayout className="layout" layout={layout} cols={12} rowHeight={90} width={1200}>
<div key={'a'}>
<ChatWidget />
</div>
<div key={'b'}>
<PingWidget />
</div>
<div key={'c'}>
<ChatWidget />
</div>
</ReactGridLayout>
*/ |
client/src/components/Loading.js | nemish/mathbattle | import React from 'react';
import Grid from 'material-ui/Grid';
import Paper from 'material-ui/Paper';
import Spinner from 'react-spinkit';
import Dotting from '../Dotting';
const styles = {
container: {height: '100%'},
spinner: {width: 100, margin: 'auto'}
}
export default props => <Grid container justify='center' style={styles.container} direction='column'>
<Grid item className='text-center'>
<div className='text-center'>
<Spinner name='pacman' color='#fff' style={styles.spinner} />
</div>
</Grid>
</Grid> |
styleguide/sections/Home.js | iest/loggins | import React from 'react';
import Markdown from 'matthewmueller-react-remarkable';
import * as m from 'globals/modifiers.css';
import styles from './Home.css';
export default class Home {
render() {
return (
<div>
<div style={{ maxWidth: '40em', margin: '0 auto' }} className={m.alignc}>
<span className={styles.loggins}/>
<Markdown>{`
# Loggins
_Pact's styleguide & component library_
`}</Markdown>
<div className={[m.alignl, m.mtl].join(' ')}>
<Markdown>{`
## Well, hello there
Loggins is a library we use at Pact to build our interfaces with. Components are built with react and modularised CSS.
It's a living styleguide in the _truest_ sense of the word; this site auto-deployed on every push to master, and the components within are interactive.
## Component ground rules
### 1. Be flexible to surroundings
Components themselves don't contain media queries or anything else that alter their display at various shapes and sizes. While some components have specific widths, most will simply fit to the container they're placed in.
### 2. Go for composability
Break components down into the smallest useful level of functionality, then put them together to solve common use cases. An example of this is the [HoverCard][1], which is used by [Dropdown][2] and [TooltipToggle][3]. It could also be consumed directly to build something custom like a modal.
[1]: https://github.com/PactCoffee/loggins/blob/master/components/HoverCard/HoverCard.js
[2]: https://github.com/PactCoffee/loggins/blob/master/components/Dropdown/Dropdown.js
[3]: https://github.com/PactCoffee/loggins/blob/master/components/TooltipToggle/TooltipToggle.js
### 3. TBA
`}</Markdown>
</div>
</div>
</div>
);
}
}
|
src/components/sidebar-modal.js | Lokiedu/libertysoil-site | /*
This file is a part of libertysoil.org website
Copyright (C) 2017 Loki Education (Social Enterprise)
This program 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, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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 PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import isEqual from 'lodash/isEqual';
import Link from 'react-router/lib/Link';
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';
import { OldIcon as Icon } from './icon';
class SidebarModalMain extends React.PureComponent {
static displayName = 'SidebarModalMain';
static propTypes = {
animate: PropTypes.bool,
children: PropTypes.node,
className: PropTypes.string,
innerClassName: PropTypes.string,
isVisible: PropTypes.bool,
onClose: PropTypes.func,
onCloseTo: PropTypes.oneOfType([
PropTypes.func,
PropTypes.string
]),
rtl: PropTypes.bool
};
static defaultProps = {
animate: true,
isVisible: false
};
render() {
let innerClassName = 'sidebar-modal__main';
if (this.props.innerClassName) {
innerClassName += ` ${this.props.innerClassName}`;
}
const content = (
<div className={innerClassName} key="main">
{this.props.children}
</div>
);
let outside;
const { onClose, onCloseTo } = this.props;
if (onClose || onCloseTo) {
outside = (
<Link
className="sidebar-modal__outside"
onClick={onClose}
to={onCloseTo}
/>
);
}
const cn = classNames(
'sidebar-modal',
this.props.className,
{ 'sidebar-modal--rtl': this.props.rtl }
);
if (this.props.animate) {
return (
<div className={cn}>
{outside}
<CSSTransitionGroup
transitionName="sidebar-modal__main--transition"
transitionAppear
transitionAppearTimeout={250}
transitionEnterTimeout={250}
transitionLeaveTimeout={250}
>
{this.props.isVisible ? content : null}
</CSSTransitionGroup>
</div>
);
}
if (!this.props.isVisible) {
return null;
}
return (
<div className={cn}>
{outside}{content}
</div>
);
}
}
class SidebarModalOverlay extends React.Component {
static displayName = 'SidebarModalOverlay';
static propTypes = {
color: PropTypes.string,
isVisible: PropTypes.bool
};
static defaultProps = {
color: "white",
isVisible: false
};
constructor(props, ...args) {
super(props, ...args);
this.state = {
isAppearing: typeof window === 'undefined',
isVisible: typeof window === 'undefined'
};
}
componentDidMount() {
if (this.props.isVisible) {
// eslint-disable-next-line react/no-did-mount-set-state
this.setState({ isVisible: true });
}
}
componentWillReceiveProps(nextProps) {
if (!nextProps.isVisible && this.props.isVisible) {
setTimeout(() => this.setState({ isVisible: false, isAppearing: false }), 250);
} else if (nextProps.isVisible && !this.props.isVisible) {
this.setState({ isVisible: true });
}
}
shouldComponentUpdate(nextProps, nextState) {
return nextProps !== this.props
|| !isEqual(nextState, this.state);
}
componentDidUpdate(prevProps, prevState) {
if (!prevState.isVisible && this.state.isVisible) {
setTimeout(() => this.setState({ isAppearing: true }), 60);
}
}
render() {
const def = 'sidebar-modal__overlay';
const cn = classNames('sidebar-modal', def, this.props.className, {
[def.concat('--transition_appear')]: this.state.isAppearing,
[def.concat('--transition_disappear')]: !this.props.isVisible && this.state.isVisible,
[def.concat('--color_').concat(this.props.color)]: this.props.color,
[def.concat('--rtl')]: this.props.rtl
});
const content = <div className={cn}>{this.props.children}</div>;
if (!this.props.isVisible) {
return this.state.isVisible ? content : null;
}
return content;
}
}
class SidebarModalBody extends React.Component {
static displayName = 'SidebarModalBody';
shouldComponentUpdate(nextProps) {
return nextProps !== this.props;
}
render() {
const className = classNames(
this.props.className,
{ 'sidebar-modal__body': !this.props.raw }
);
return (
<div className={className}>
{this.props.children}
</div>
);
}
}
class SidebarModalHeader extends React.Component {
static displayName = 'SidebarModalHeader';
static propTypes = (() => {
const iconOrNone = PropTypes.oneOfType([
PropTypes.shape(Icon.propTypes),
PropTypes.oneOf([false])
]);
return {
className: PropTypes.string,
closeIcon: iconOrNone,
mainIcon: iconOrNone,
theme: PropTypes.string
};
})();
static defaultProps = {
closeIcon: {},
mainIcon: {}
};
shouldComponentUpdate(nextProps) {
return nextProps !== this.props;
}
render() {
let mainIcon;
if (this.props.mainIcon !== false) {
const { className: mainIconClassName, ...props } = this.props.mainIcon;
mainIcon = (
<Icon
className={classNames('sidebar-modal__icon', mainIconClassName)}
color="white"
outline="blue"
icon="cogs"
pack="fa"
size="block"
round={false}
{...props}
/>
);
}
let closeIcon;
if (this.props.closeIcon !== false) {
const { className: closeIconClassName, ...props } = this.props.closeIcon;
closeIcon = (
<Icon
className={classNames('action sidebar-modal__close', closeIconClassName)}
icon="close"
pack="fa"
size="common"
{...props}
onClick={this.props.onClose}
/>
);
}
const className = classNames(
'sidebar-modal__header',
this.props.className,
this.props.theme &&
`sidebar-modal__header--theme_${this.props.theme}`
);
return (
<div className={className}>
{mainIcon}
<div className="sidebar-modal__title">{this.props.children}</div>
{closeIcon}
</div>
);
}
}
export default {
Body: SidebarModalBody,
Header: SidebarModalHeader,
Main: SidebarModalMain,
Overlay: SidebarModalOverlay
};
|
src/Table.js | simonliubo/react-ui | import React from 'react';
import classNames from 'classnames';
const Table = React.createClass({
propTypes: {
striped: React.PropTypes.bool,
bordered: React.PropTypes.bool,
condensed: React.PropTypes.bool,
hover: React.PropTypes.bool,
responsive: React.PropTypes.bool
},
render() {
let classes = {
'table': true,
'table-striped': this.props.striped,
'table-bordered': this.props.bordered,
'table-condensed': this.props.condensed,
'table-hover': this.props.hover
};
let table = (
<table {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</table>
);
return this.props.responsive ? (
<div className="table-responsive">
{table}
</div>
) : table;
}
});
export default Table;
|
app/routes/company/ShowRoute.js | ryrudnev/dss-wm | import React from 'react';
import Helmet from 'react-helmet';
import { Route } from '../../core/router';
import { Model as Company } from '../../entities/Company';
import { Deferred } from '../../util/utils';
import { PageHeader } from 'react-bootstrap';
import CompanyProfile from '../../components/CompanyProfile';
import radio from 'backbone.radio';
const router = radio.channel('router');
export default class CompanyShowRoute extends Route {
breadcrumb({ params }) {
const dfd = new Deferred;
(new Company({ fid: params.fid })).fetch({ success: model => dfd.resolve(model.get('title')) });
return dfd.promise;
}
fetch({ params }) {
this.company = new Company({ fid: params.fid });
return this.company.expandParam('waste,methods').fetch();
}
search(cb) {
this.company.searchStrategy({
success: resp => {
cb(resp.data);
},
});
}
delete(cb) {
this.company.destroy({
success: () => {
cb();
router.request('navigate', 'companies');
},
});
}
render() {
return (
<div>
<Helmet title={`Предприятие ${this.company.get('title')}`} />
<PageHeader>{`Предприятие ${this.company.get('title')}`}</PageHeader>
<CompanyProfile
company={this.company}
onSearch={cb => this.search(cb)}
onDelete={cb => this.delete(cb)}
/>
</div>
);
}
}
|
app/javascript/mastodon/features/ui/components/zoomable_image.js | tootsuite/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import IconButton from 'mastodon/components/icon_button';
import { defineMessages, injectIntl } from 'react-intl';
const messages = defineMessages({
compress: { id: 'lightbox.compress', defaultMessage: 'Compress image view box' },
expand: { id: 'lightbox.expand', defaultMessage: 'Expand image view box' },
});
const MIN_SCALE = 1;
const MAX_SCALE = 4;
const NAV_BAR_HEIGHT = 66;
const getMidpoint = (p1, p2) => ({
x: (p1.clientX + p2.clientX) / 2,
y: (p1.clientY + p2.clientY) / 2,
});
const getDistance = (p1, p2) =>
Math.sqrt(Math.pow(p1.clientX - p2.clientX, 2) + Math.pow(p1.clientY - p2.clientY, 2));
const clamp = (min, max, value) => Math.min(max, Math.max(min, value));
// Normalizing mousewheel speed across browsers
// copy from: https://github.com/facebookarchive/fixed-data-table/blob/master/src/vendor_upstream/dom/normalizeWheel.js
const normalizeWheel = event => {
// Reasonable defaults
const PIXEL_STEP = 10;
const LINE_HEIGHT = 40;
const PAGE_HEIGHT = 800;
let sX = 0,
sY = 0, // spinX, spinY
pX = 0,
pY = 0; // pixelX, pixelY
// Legacy
if ('detail' in event) {
sY = event.detail;
}
if ('wheelDelta' in event) {
sY = -event.wheelDelta / 120;
}
if ('wheelDeltaY' in event) {
sY = -event.wheelDeltaY / 120;
}
if ('wheelDeltaX' in event) {
sX = -event.wheelDeltaX / 120;
}
// side scrolling on FF with DOMMouseScroll
if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) {
sX = sY;
sY = 0;
}
pX = sX * PIXEL_STEP;
pY = sY * PIXEL_STEP;
if ('deltaY' in event) {
pY = event.deltaY;
}
if ('deltaX' in event) {
pX = event.deltaX;
}
if ((pX || pY) && event.deltaMode) {
if (event.deltaMode === 1) { // delta in LINE units
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
} else { // delta in PAGE units
pX *= PAGE_HEIGHT;
pY *= PAGE_HEIGHT;
}
}
// Fall-back if spin cannot be determined
if (pX && !sX) {
sX = (pX < 1) ? -1 : 1;
}
if (pY && !sY) {
sY = (pY < 1) ? -1 : 1;
}
return {
spinX: sX,
spinY: sY,
pixelX: pX,
pixelY: pY,
};
};
export default @injectIntl
class ZoomableImage extends React.PureComponent {
static propTypes = {
alt: PropTypes.string,
src: PropTypes.string.isRequired,
width: PropTypes.number,
height: PropTypes.number,
onClick: PropTypes.func,
zoomButtonHidden: PropTypes.bool,
intl: PropTypes.object.isRequired,
}
static defaultProps = {
alt: '',
width: null,
height: null,
};
state = {
scale: MIN_SCALE,
zoomMatrix: {
type: null, // 'width' 'height'
fullScreen: null, // bool
rate: null, // full screen scale rate
clientWidth: null,
clientHeight: null,
offsetWidth: null,
offsetHeight: null,
clientHeightFixed: null,
scrollTop: null,
scrollLeft: null,
translateX: null,
translateY: null,
},
zoomState: 'expand', // 'expand' 'compress'
navigationHidden: false,
dragPosition: { top: 0, left: 0, x: 0, y: 0 },
dragged: false,
lockScroll: { x: 0, y: 0 },
lockTranslate: { x: 0, y: 0 },
}
removers = [];
container = null;
image = null;
lastTouchEndTime = 0;
lastDistance = 0;
componentDidMount () {
let handler = this.handleTouchStart;
this.container.addEventListener('touchstart', handler);
this.removers.push(() => this.container.removeEventListener('touchstart', handler));
handler = this.handleTouchMove;
// on Chrome 56+, touch event listeners will default to passive
// https://www.chromestatus.com/features/5093566007214080
this.container.addEventListener('touchmove', handler, { passive: false });
this.removers.push(() => this.container.removeEventListener('touchend', handler));
handler = this.mouseDownHandler;
this.container.addEventListener('mousedown', handler);
this.removers.push(() => this.container.removeEventListener('mousedown', handler));
handler = this.mouseWheelHandler;
this.container.addEventListener('wheel', handler);
this.removers.push(() => this.container.removeEventListener('wheel', handler));
// Old Chrome
this.container.addEventListener('mousewheel', handler);
this.removers.push(() => this.container.removeEventListener('mousewheel', handler));
// Old Firefox
this.container.addEventListener('DOMMouseScroll', handler);
this.removers.push(() => this.container.removeEventListener('DOMMouseScroll', handler));
this.initZoomMatrix();
}
componentWillUnmount () {
this.removeEventListeners();
}
componentDidUpdate () {
this.setState({ zoomState: this.state.scale >= this.state.zoomMatrix.rate ? 'compress' : 'expand' });
if (this.state.scale === MIN_SCALE) {
this.container.style.removeProperty('cursor');
}
}
UNSAFE_componentWillReceiveProps () {
// reset when slide to next image
if (this.props.zoomButtonHidden) {
this.setState({
scale: MIN_SCALE,
lockTranslate: { x: 0, y: 0 },
}, () => {
this.container.scrollLeft = 0;
this.container.scrollTop = 0;
});
}
}
removeEventListeners () {
this.removers.forEach(listeners => listeners());
this.removers = [];
}
mouseWheelHandler = e => {
e.preventDefault();
const event = normalizeWheel(e);
if (this.state.zoomMatrix.type === 'width') {
// full width, scroll vertical
this.container.scrollTop = Math.max(this.container.scrollTop + event.pixelY, this.state.lockScroll.y);
} else {
// full height, scroll horizontal
this.container.scrollLeft = Math.max(this.container.scrollLeft + event.pixelY, this.state.lockScroll.x);
}
// lock horizontal scroll
this.container.scrollLeft = Math.max(this.container.scrollLeft + event.pixelX, this.state.lockScroll.x);
}
mouseDownHandler = e => {
this.container.style.cursor = 'grabbing';
this.container.style.userSelect = 'none';
this.setState({ dragPosition: {
left: this.container.scrollLeft,
top: this.container.scrollTop,
// Get the current mouse position
x: e.clientX,
y: e.clientY,
} });
this.image.addEventListener('mousemove', this.mouseMoveHandler);
this.image.addEventListener('mouseup', this.mouseUpHandler);
}
mouseMoveHandler = e => {
const dx = e.clientX - this.state.dragPosition.x;
const dy = e.clientY - this.state.dragPosition.y;
this.container.scrollLeft = Math.max(this.state.dragPosition.left - dx, this.state.lockScroll.x);
this.container.scrollTop = Math.max(this.state.dragPosition.top - dy, this.state.lockScroll.y);
this.setState({ dragged: true });
}
mouseUpHandler = () => {
this.container.style.cursor = 'grab';
this.container.style.removeProperty('user-select');
this.image.removeEventListener('mousemove', this.mouseMoveHandler);
this.image.removeEventListener('mouseup', this.mouseUpHandler);
}
handleTouchStart = e => {
if (e.touches.length !== 2) return;
this.lastDistance = getDistance(...e.touches);
}
handleTouchMove = e => {
const { scrollTop, scrollHeight, clientHeight } = this.container;
if (e.touches.length === 1 && scrollTop !== scrollHeight - clientHeight) {
// prevent propagating event to MediaModal
e.stopPropagation();
return;
}
if (e.touches.length !== 2) return;
e.preventDefault();
e.stopPropagation();
const distance = getDistance(...e.touches);
const midpoint = getMidpoint(...e.touches);
const _MAX_SCALE = Math.max(MAX_SCALE, this.state.zoomMatrix.rate);
const scale = clamp(MIN_SCALE, _MAX_SCALE, this.state.scale * distance / this.lastDistance);
this.zoom(scale, midpoint);
this.lastMidpoint = midpoint;
this.lastDistance = distance;
}
zoom(nextScale, midpoint) {
const { scale, zoomMatrix } = this.state;
const { scrollLeft, scrollTop } = this.container;
// math memo:
// x = (scrollLeft + midpoint.x) / scrollWidth
// x' = (nextScrollLeft + midpoint.x) / nextScrollWidth
// scrollWidth = clientWidth * scale
// scrollWidth' = clientWidth * nextScale
// Solve x = x' for nextScrollLeft
const nextScrollLeft = (scrollLeft + midpoint.x) * nextScale / scale - midpoint.x;
const nextScrollTop = (scrollTop + midpoint.y) * nextScale / scale - midpoint.y;
this.setState({ scale: nextScale }, () => {
this.container.scrollLeft = nextScrollLeft;
this.container.scrollTop = nextScrollTop;
// reset the translateX/Y constantly
if (nextScale < zoomMatrix.rate) {
this.setState({
lockTranslate: {
x: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateX * ((nextScale - MIN_SCALE) / (zoomMatrix.rate - MIN_SCALE)),
y: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateY * ((nextScale - MIN_SCALE) / (zoomMatrix.rate - MIN_SCALE)),
},
});
}
});
}
handleClick = e => {
// don't propagate event to MediaModal
e.stopPropagation();
const dragged = this.state.dragged;
this.setState({ dragged: false });
if (dragged) return;
const handler = this.props.onClick;
if (handler) handler();
this.setState({ navigationHidden: !this.state.navigationHidden });
}
handleMouseDown = e => {
e.preventDefault();
}
initZoomMatrix = () => {
const { width, height } = this.props;
const { clientWidth, clientHeight } = this.container;
const { offsetWidth, offsetHeight } = this.image;
const clientHeightFixed = clientHeight - NAV_BAR_HEIGHT;
const type = width / height < clientWidth / clientHeightFixed ? 'width' : 'height';
const fullScreen = type === 'width' ? width > clientWidth : height > clientHeightFixed;
const rate = type === 'width' ? Math.min(clientWidth, width) / offsetWidth : Math.min(clientHeightFixed, height) / offsetHeight;
const scrollTop = type === 'width' ? (clientHeight - offsetHeight) / 2 - NAV_BAR_HEIGHT : (clientHeightFixed - offsetHeight) / 2;
const scrollLeft = (clientWidth - offsetWidth) / 2;
const translateX = type === 'width' ? (width - offsetWidth) / (2 * rate) : 0;
const translateY = type === 'height' ? (height - offsetHeight) / (2 * rate) : 0;
this.setState({
zoomMatrix: {
type: type,
fullScreen: fullScreen,
rate: rate,
clientWidth: clientWidth,
clientHeight: clientHeight,
offsetWidth: offsetWidth,
offsetHeight: offsetHeight,
clientHeightFixed: clientHeightFixed,
scrollTop: scrollTop,
scrollLeft: scrollLeft,
translateX: translateX,
translateY: translateY,
},
});
}
handleZoomClick = e => {
e.preventDefault();
e.stopPropagation();
const { scale, zoomMatrix } = this.state;
if ( scale >= zoomMatrix.rate ) {
this.setState({
scale: MIN_SCALE,
lockScroll: {
x: 0,
y: 0,
},
lockTranslate: {
x: 0,
y: 0,
},
}, () => {
this.container.scrollLeft = 0;
this.container.scrollTop = 0;
});
} else {
this.setState({
scale: zoomMatrix.rate,
lockScroll: {
x: zoomMatrix.scrollLeft,
y: zoomMatrix.scrollTop,
},
lockTranslate: {
x: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateX,
y: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateY,
},
}, () => {
this.container.scrollLeft = zoomMatrix.scrollLeft;
this.container.scrollTop = zoomMatrix.scrollTop;
});
}
this.container.style.cursor = 'grab';
this.container.style.removeProperty('user-select');
}
setContainerRef = c => {
this.container = c;
}
setImageRef = c => {
this.image = c;
}
render () {
const { alt, src, width, height, intl } = this.props;
const { scale, lockTranslate } = this.state;
const overflow = scale === MIN_SCALE ? 'hidden' : 'scroll';
const zoomButtonShouldHide = this.state.navigationHidden || this.props.zoomButtonHidden || this.state.zoomMatrix.rate <= MIN_SCALE ? 'media-modal__zoom-button--hidden' : '';
const zoomButtonTitle = this.state.zoomState === 'compress' ? intl.formatMessage(messages.compress) : intl.formatMessage(messages.expand);
return (
<React.Fragment>
<IconButton
className={`media-modal__zoom-button ${zoomButtonShouldHide}`}
title={zoomButtonTitle}
icon={this.state.zoomState}
onClick={this.handleZoomClick}
size={40}
style={{
fontSize: '30px', /* Fontawesome's fa-compress fa-expand is larger than fa-close */
}}
/>
<div
className='zoomable-image'
ref={this.setContainerRef}
style={{ overflow }}
>
<img
role='presentation'
ref={this.setImageRef}
alt={alt}
title={alt}
src={src}
width={width}
height={height}
style={{
transform: `scale(${scale}) translate(-${lockTranslate.x}px, -${lockTranslate.y}px)`,
transformOrigin: '0 0',
}}
draggable={false}
onClick={this.handleClick}
onMouseDown={this.handleMouseDown}
/>
</div>
</React.Fragment>
);
}
}
|
src/components/exercises/HasPhoneme.stories.js | cognostics/serlo-abc | import React from 'react';
import { storiesOf } from '@storybook/react-native';
import HasPhoneme from './HasPhoneme';
storiesOf('exercises/HasPhoneme', module).add('one letter', () => (
<HasPhoneme
image={require('../../assets/images/gabel.jpg')}
sound={require('../../assets/sounds/gabel_short.mp3')}
word="gabel"
phoneme={'b'}
/>
));
|
src/index.js | ipfs/webui | import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'redux-bundler-react'
import './index.css'
import 'react-virtualized/styles.css'
import App from './App'
import getStore from './bundles'
import bundleCache from './lib/bundle-cache'
import { I18nextProvider } from 'react-i18next'
import i18n from './i18n'
import { DndProvider } from 'react-dnd'
import DndBackend from './lib/dnd-backend'
const appVersion = process.env.REACT_APP_VERSION
const gitRevision = process.env.REACT_APP_GIT_REV
console.log(`IPFS Web UI - v${appVersion} - https://github.com/ipfs-shipyard/ipfs-webui/commit/${gitRevision}`)
async function render () {
const initialData = await bundleCache.getAll()
if (initialData && process.env.NODE_ENV !== 'production') {
console.log('intialising store with data from cache', initialData)
}
const store = getStore(initialData)
ReactDOM.render(
<Provider store={store}>
<I18nextProvider i18n={i18n} >
<DndProvider backend={DndBackend}>
<App />
</DndProvider>
</I18nextProvider>
</Provider>,
document.getElementById('root')
)
}
render()
|
src/parser/shared/modules/features/Checklist/PreparationRule.js | yajinni/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { Trans } from '@lingui/macro';
import Rule from './Rule';
import Requirement from './Requirement';
class PreparationRule extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
thresholds: PropTypes.object.isRequired,
};
renderPotionRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={<Trans id="shared.modules.features.checklist.combatPotionsUsed">Combat potions used</Trans>}
thresholds={thresholds.potionsUsed}
/>
<Requirement
name={<Trans id="shared.modules.features.checklist.highQualityCombatPotionsUsed">High quality combat potions used</Trans>}
thresholds={thresholds.bestPotionUsed}
/>
</>
);
}
renderEnchantRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={<Trans id="shared.modules.features.checklist.enchanted">All items enchanted</Trans>}
thresholds={thresholds.itemsEnchanted}
/>
<Requirement
name={<Trans id="shared.modules.features.checklist.enchantedHigh">Using high quality enchants</Trans>}
thresholds={thresholds.itemsBestEnchanted}
/>
</>
);
}
renderWeaponEnhancementRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={<Trans>All weapons enhanced (oils/stones)</Trans>}
thresholds={thresholds.weaponsEnhanced}
/>
<Requirement
name={<Trans>Using high quality weapon enhancements</Trans>}
thresholds={thresholds.bestWeaponEnhancements}
/>
</>
);
}
renderFlaskRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={<Trans id="shared.modules.features.checklist.flaskHigh">High quality flask used</Trans>}
thresholds={thresholds.higherFlaskPresent}
/>
<Requirement
name={<Trans id="shared.modules.features.checklist.flask">Flask used</Trans>}
thresholds={thresholds.flaskPresent}
/>
</>
);
}
renderFoodRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={<Trans id="shared.modules.features.checklist.foodHigh">High quality food used</Trans>}
thresholds={thresholds.higherFoodPresent}
/>
<Requirement
name={<Trans id="shared.modules.features.checklist.food">Food used</Trans>}
thresholds={thresholds.foodPresent}
/>
</>
);
}
renderAugmentRuneRequirements() {
const { thresholds } = this.props;
return (
<>
<Requirement
name={<Trans id="shared.modules.features.checklist.augmentRune">Augment rune used</Trans>}
thresholds={thresholds.augmentRunePresent}
/>
</>
);
}
render() {
const { children } = this.props;
return (
<Rule
name={<Trans id="shared.modules.features.checklist.wellPrepared">Be well prepared</Trans>}
description={<Trans id="shared.modules.features.checklist.wellPreparedDetails">Being well prepared with food, flasks, potions and enchants is an easy way to improve your performance.</Trans>}
>
{this.renderEnchantRequirements()}
{this.renderWeaponEnhancementRequirements()}
{this.renderPotionRequirements()}
{this.renderFlaskRequirements()}
{this.renderFoodRequirements()}
{this.renderAugmentRuneRequirements()}
{children}
</Rule>
);
}
}
export default PreparationRule;
|
src/components/app.js | cungen/www | import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Header from './partials/header/';
import Loading from './loading/loading';
export default class App extends Component {
render() {
return (
<MuiThemeProvider>
<div>
<Header />
<Loading />
{this.props.children}
</div>
</MuiThemeProvider>
)
}
} |
src/components/core/Breakpoint.js | ESTEBANMURUZABAL/my-ecommerce-template | /**
* Imports
*/
import React from 'react';
import connectToStores from 'fluxible-addons-react/connectToStores';
// Flux
import ResponsiveStore from '../../stores/Application/ResponsiveStore';
/**
* Component
*/
class Breakpoint extends React.Component {
static contextTypes = {
getStore: React.PropTypes.func.isRequired
};
//*** Initial State & Defaults ***//
state = {
breakpoint: this.context.getStore(ResponsiveStore).getBreakPoint()
};
//*** Component Lifecycle ***//
componentWillReceiveProps(nextProps) {
this.setState({breakpoint: nextProps._breakpoint});
}
//*** Template ***//
render() {
if (this.state.breakpoint === this.props.point) {
return <div>{this.props.children}</div>;
} else {
return null;
}
}
}
/**
* Flux
*/
Breakpoint = connectToStores(Breakpoint, [ResponsiveStore], (context) => {
return {
_breakpoint: context.getStore(ResponsiveStore).getBreakPoint()
};
});
/**
* Export
*/
export default Breakpoint;
|
src/lib/plot/xy-plot.js | jameskraus/react-vis | // Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import equal from 'deep-equal';
import {
extractScalePropsFromProps,
getMissingScaleProps
} from '../utils/scales-utils';
import {
getStackedData,
getSeriesChildren,
getSeriesPropsFromChildren
} from '../utils/series-utils';
import {getInnerDimensions, MarginPropType} from '../utils/chart-utils';
import {AnimationPropType} from '../utils/animation-utils';
import {CONTINUOUS_COLOR_RANGE, SIZE_RANGE, OPACITY_RANGE} from '../theme';
const ATTRIBUTES = [
'x',
'y',
'color',
'fill',
'stroke',
'opacity',
'size'
];
const DEFAULT_MARGINS = {
left: 40,
right: 10,
top: 10,
bottom: 40
};
class XYPlot extends React.Component {
static get propTypes() {
return {
width: React.PropTypes.number.isRequired,
height: React.PropTypes.number.isRequired,
margin: MarginPropType,
onMouseLeave: React.PropTypes.func,
onMouseMove: React.PropTypes.func,
onMouseEnter: React.PropTypes.func,
animation: AnimationPropType,
stackBy: React.PropTypes.oneOf(ATTRIBUTES)
};
}
constructor(props) {
super(props);
this._mouseLeaveHandler = this._mouseLeaveHandler.bind(this);
this._mouseEnterHandler = this._mouseEnterHandler.bind(this);
this._mouseMoveHandler = this._mouseMoveHandler.bind(this);
const {stackBy} = props;
const children = getSeriesChildren(props.children);
const data = getStackedData(children, stackBy);
this.state = {
scaleMixins: this._getScaleMixins(data, props),
data
};
}
componentWillReceiveProps(nextProps) {
const children = getSeriesChildren(nextProps.children);
const nextData = getStackedData(children, nextProps.stackBy);
const {scaleMixins} = this.state;
const nextScaleMixins = this._getScaleMixins(nextData, nextProps);
if (!equal(nextScaleMixins, scaleMixins)) {
this.setState({
scaleMixins: nextScaleMixins,
data: nextData
});
}
}
/**
* Trigger movement-related callbacks if they are available.
* @param {React.SyntheticEvent} event Mouse move event.
* @private
*/
_mouseMoveHandler(event) {
const {onMouseMove, children} = this.props;
if (onMouseMove) {
onMouseMove(event);
}
const seriesChildren = getSeriesChildren(children);
seriesChildren.forEach((child, index) => {
const component = this.refs[`series${index}`];
if (component && component.onParentMouseMove) {
component.onParentMouseMove(event);
}
});
}
/**
* Trigger onMouseLeave handler if it was passed in props.
* @param {Event} event Native event.
* @private
*/
_mouseLeaveHandler(event) {
const {onMouseLeave} = this.props;
if (onMouseLeave) {
onMouseLeave({event});
}
}
/**
* Trigger onMouseEnter handler if it was passed in props.
* @param {Event} event Native event.
* @private
*/
_mouseEnterHandler(event) {
const {onMouseEnter} = this.props;
if (onMouseEnter) {
onMouseEnter({event});
}
}
/**
* Get the list of scale-related settings that should be applied by default.
* @param {Object} props Object of props.
* @returns {Object} Defaults.
* @private
*/
_getDefaultScaleProps(props) {
const {innerWidth, innerHeight} = getInnerDimensions(
props,
DEFAULT_MARGINS
);
return {
xRange: [0, innerWidth],
yRange: [innerHeight, 0],
colorRange: CONTINUOUS_COLOR_RANGE,
opacityRange: OPACITY_RANGE,
sizeRange: SIZE_RANGE
};
}
/**
* Get the map of scales from the props, apply defaults to them and then pass
* them further.
* @param {Object} data Array of all data.
* @param {Object} props Props of the component.
* @returns {Object} Map of scale-related props.
* @private
*/
_getScaleMixins(data, props) {
const filteredData = data.filter(d => d);
const allData = [].concat(...filteredData);
const defaultScaleProps = this._getDefaultScaleProps(props);
const userScaleProps = extractScalePropsFromProps(props, ATTRIBUTES);
const missingScaleProps = getMissingScaleProps({
...defaultScaleProps,
...userScaleProps
}, allData, ATTRIBUTES);
const children = getSeriesChildren(props.children);
const zeroBaseProps = {};
const adjustBy = new Set();
const adjustWhat = new Set();
children.forEach((child, index) => {
if (!child || !data[index]) {
return;
}
ATTRIBUTES.forEach(attr => {
const {
isDomainAdjustmentNeeded,
zeroBaseValue} = child.type.getParentConfig(
attr,
child.props
);
if (isDomainAdjustmentNeeded) {
adjustBy.add(attr);
adjustWhat.add(index);
}
if (zeroBaseValue) {
zeroBaseProps[`${attr}BaseValue`] = 0;
}
});
});
return {
...defaultScaleProps,
...zeroBaseProps,
...userScaleProps,
...missingScaleProps,
_allData: data,
_adjustBy: Array.from(adjustBy),
_adjustWhat: Array.from(adjustWhat),
_stackBy: props.stackBy
};
}
/**
* Checks if the plot is empty or not.
* Currently checks the data only.
* @returns {boolean} True for empty.
* @private
*/
_isPlotEmpty() {
const {data} = this.state;
return !data || !data.length ||
!data.some(series => series && series.some(d => d));
}
/**
* Prepare the child components (including series) for rendering.
* @returns {Array} Array of child components.
* @private
*/
_getClonedChildComponents() {
const {animation} = this.props;
const {scaleMixins, data} = this.state;
const dimensions = getInnerDimensions(this.props, DEFAULT_MARGINS);
const children = React.Children.toArray(this.props.children);
const seriesProps = getSeriesPropsFromChildren(children);
return children.map((child, index) => {
let dataProps = null;
if (seriesProps[index]) {
// Get the index of the series in the list of props and retrieve
// the data property from it.
const {seriesIndex} = seriesProps[index];
dataProps = {data: data[seriesIndex]};
}
return React.cloneElement(child, {
...dimensions,
animation,
...seriesProps[index],
...scaleMixins,
...child.props,
...dataProps
});
});
}
render() {
const {width, height} = this.props;
if (this._isPlotEmpty()) {
return (
<div
className="rv-xy-plot"
style={{
width: `${width}px`,
height: `${height}px`
}}/>
);
}
const components = this._getClonedChildComponents();
return (
<div
style={{
width: `${width}px`,
height: `${height}px`
}}
className="rv-xy-plot">
<svg
className="rv-xy-plot__inner"
width={width}
height={height}
onMouseMove={this._mouseMoveHandler}
onMouseLeave={this._mouseLeaveHandler}
onMouseEnter={this._mouseEnterHandler}>
{components.filter(c => c && c.type.requiresSVG)}
</svg>
{components.filter(c => c && !c.type.requiresSVG)}
</div>
);
}
}
XYPlot.displayName = 'XYPlot';
export default XYPlot;
|
example/src/index.js | bokuweb/react-animation-sprite | import React from 'react';
import { render } from 'react-dom';
import Example from './example';
render(<Example />, document.querySelector('#content'));
|
src/parser/monk/brewmaster/modules/spells/BlackoutCombo.js | sMteX/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import { formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import { SPELLS_WHICH_REMOVE_BOC } from '../../constants';
const debug = false;
const BOC_DURATION = 15000;
class BlackoutCombo extends Analyzer {
blackoutComboConsumed = 0;
blackoutComboBuffs = 0;
lastBlackoutComboCast = 0;
spellsBOCWasUsedOn = {};
get dpsWasteThreshold() {
if(!this.active) {
return null;
}
return {
actual: this.spellsBOCWasUsedOn[SPELLS.TIGER_PALM.id] / this.blackoutComboBuffs,
isLessThan: {
minor: 0.95,
average: 0.9,
major: 0.85,
},
style: 'percentage',
};
}
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.BLACKOUT_COMBO_TALENT.id);
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.BLACKOUT_COMBO_BUFF.id) {
debug && console.log('Blackout combo applied');
this.blackoutComboBuffs += 1;
this.lastBlackoutComboCast = event.timestamp;
}
}
on_byPlayer_refreshbuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.BLACKOUT_COMBO_BUFF.id) {
debug && console.log('Blackout combo refreshed');
this.blackoutComboBuffs += 1;
this.lastBlackoutComboCast = event.timestamp;
}
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (!SPELLS_WHICH_REMOVE_BOC.includes(spellId)) {
return;
}
// BOC should be up
if (this.lastBlackoutComboCast > 0 && this.lastBlackoutComboCast + BOC_DURATION > event.timestamp) {
this.blackoutComboConsumed += 1;
if (this.spellsBOCWasUsedOn[spellId] === undefined) {
this.spellsBOCWasUsedOn[spellId] = 0;
}
this.spellsBOCWasUsedOn[spellId] += 1;
}
this.lastBlackoutComboCast = 0;
}
suggestions(when) {
const wastedPerc = (this.blackoutComboBuffs - this.blackoutComboConsumed) / this.blackoutComboBuffs;
when(wastedPerc).isGreaterThan(0.1)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>You wasted {formatPercentage(actual)}% of your <SpellLink id={SPELLS.BLACKOUT_COMBO_BUFF.id} /> procs. Try to use the procs as soon as you get them so they are not overwritten.</span>)
.icon(SPELLS.BLACKOUT_COMBO_BUFF.icon)
.actual(`${formatPercentage(actual)}% unused`)
.recommended(`${Math.round(formatPercentage(recommended))}% or less is recommended`)
.regular(recommended + 0.1).major(recommended + 0.2);
});
}
statistic() {
const wastedPerc = (this.blackoutComboBuffs - this.blackoutComboConsumed) / this.blackoutComboBuffs;
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.BLACKOUT_COMBO_BUFF.id} />}
value={`${formatPercentage(wastedPerc)}%`}
label="Wasted Blackout Combo"
tooltip={(
<>
You got total <strong>{this.blackoutComboBuffs}</strong> Blackout Combo procs and used <strong>{this.blackoutComboConsumed}</strong> of them.<br />
Blackout combo buff usage:
<ul>
{Object.keys(this.spellsBOCWasUsedOn)
.sort((a, b) => this.spellsBOCWasUsedOn[b] - this.spellsBOCWasUsedOn[a])
.map(type => (
<li><em>{SPELLS[type].name || 'Unknown'}</em> was used {this.spellsBOCWasUsedOn[type]} time{this.spellsBOCWasUsedOn[type] === 1 ? '' : 's'} ({formatPercentage(this.spellsBOCWasUsedOn[type] / this.blackoutComboConsumed)}%)</li>)
)}
</ul>
</>
)}
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL();
}
export default BlackoutCombo;
|
imports/client/ui/pages/Admin/UserSearch/index.js | mordka/fl-events | import React, { Component } from 'react';
import {Form, FormGroup, Input, Button} from 'reactstrap'
class UserSearch extends Component {
constructor(props) {
super(props);
this.userToSearch = React.createRef();
}
searchForUser = (e) => {
e.preventDefault();
this.props.searchForUser(this.userToSearch.current.value);
}
render() {
return (
<div className="search-container">
<Form onSubmit={this.searchForUser} action="">
<FormGroup>
<input placeholder="profile name or email" type="text" ref={this.userToSearch} />
<Button>Search</Button>
</FormGroup>
</Form>
</div>
)
}
}
export default UserSearch; |
stories/components/spinner.stories.js | LN-Zap/zap-desktop | import React from 'react'
import { storiesOf } from '@storybook/react'
import { Spinner } from 'components/UI'
storiesOf('Components', module).addWithChapters('Spinner', {
subtitle: 'For letting the user know that something is happening.',
chapters: [
{
sections: [
{
sectionFn: () => <Spinner />,
},
],
},
],
})
|
packages/insights-web/src/scenes/explorer/connection/subset/form/models/json/index.js | mariusandra/insights | import React from 'react'
import { Button, Form, Input, Modal } from 'antd'
import { useActions, useValues } from 'kea'
import modelsLogic from '../logic'
function JSONComponent ({ visible, form: { getFieldDecorator, validateFieldsAndScroll, getFieldValue } }) {
const { defaultJSON } = useValues(modelsLogic)
const { hideJSON, setNewFields, setEditedFields, setCheckedKeys } = useActions(modelsLogic)
const handleSave = (e) => {
e.preventDefault()
validateFieldsAndScroll((err, values) => {
if (!err) {
const { newFields, editedFields, checkedKeys } = JSON.parse(values.json)
setNewFields(newFields || {})
setEditedFields(editedFields || {})
setCheckedKeys(checkedKeys || [])
hideJSON()
}
})
}
return (
<Modal
visible={visible}
destroyOnClose
onCancel={hideJSON}
width='75%'
keyboard={false}
title='subset-changes.json'
footer={[
<Button key="back" onClick={hideJSON}>
Cancel
</Button>,
<Button key="submit" type="primary" loading={false} onClick={handleSave}>
Save
</Button>,
]}>
{visible ? (
<Form onSubmit={handleSave}>
<Form.Item>
{getFieldDecorator('json', {
initialValue: defaultJSON,
rules: [
{
required: true,
message: 'Please input the JSON!',
},
(rule, value, callback) => {
try {
JSON.parse(value)
callback()
} catch (e) {
callback('This is not valid JSON!')
}
}
]
})(<Input.TextArea autoSize={{ minRows: 2, maxRows: 20 }} placeholder='{}' style={{width: '100%', fontFamily: 'monospace'}} />)}
</Form.Item>
</Form>
) : null}
</Modal>
)
}
export default Form.create({ name: 'modelsJSON' })(JSONComponent)
|
src/components/HostsNav.js | cpsubrian/redis-explorer | import React from 'react'
import autobind from 'autobind-decorator'
import ImmutablePropTypes from 'react-immutable-proptypes'
import hostsActions from '../actions/hostsActions'
import browseActions from '../actions/browseActions'
import Icon from '../components/Icon'
import {LeftNav, MenuItem} from 'material-ui'
@autobind
class HostsNav extends React.Component {
static propTypes = {
hosts: ImmutablePropTypes.list,
activeHost: ImmutablePropTypes.map
}
shouldComponentUpdate (nextProps, nextState) {
return !(
nextProps.hosts === this.props.hosts &&
nextProps.activeHost.get('Host') === this.props.activeHost.get('Host')
)
}
toggle () {
this.refs.nav.toggle()
}
onChangeHost (e, i, menuItem) {
if (menuItem.host.get('Host') !== this.props.activeHost.get('Host')) {
browseActions.resetKeys()
hostsActions.connectToHost(menuItem.host)
}
}
render () {
let selectedIndex
let menuItems
menuItems = this.props.hosts.map((host, i) => {
if (this.props.activeHost === host) {
selectedIndex = i
}
return {
host: host,
text: <span className='host-option'><Icon type='public'/> {host.get('Host')}</span>
}
}).toArray()
// Splice in subheaders.
menuItems.splice(0, 0, {type: MenuItem.Types.SUBHEADER, text: 'Local' })
menuItems.splice(2, 0, {type: MenuItem.Types.SUBHEADER, text: 'Remote' })
// Adjust selected index.
if (selectedIndex === 0) {
selectedIndex = 1
} else {
selectedIndex += 2
}
return (
<LeftNav ref='nav'
docked={false}
openRight={true}
onChange={this.onChangeHost}
selectedIndex={selectedIndex}
menuItems={menuItems} />
)
}
}
export default HostsNav
|
browser/app/js/components/Browse.js | luomeiqin/minio | /*
* Minio Cloud Storage (C) 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react'
import classNames from 'classnames'
import browserHistory from 'react-router/lib/browserHistory'
import humanize from 'humanize'
import Moment from 'moment'
import Modal from 'react-bootstrap/lib/Modal'
import ModalBody from 'react-bootstrap/lib/ModalBody'
import ModalHeader from 'react-bootstrap/lib/ModalHeader'
import Alert from 'react-bootstrap/lib/Alert'
import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger'
import Tooltip from 'react-bootstrap/lib/Tooltip'
import Dropdown from 'react-bootstrap/lib/Dropdown'
import MenuItem from 'react-bootstrap/lib/MenuItem'
import InputGroup from '../components/InputGroup'
import Dropzone from '../components/Dropzone'
import ObjectsList from '../components/ObjectsList'
import SideBar from '../components/SideBar'
import Path from '../components/Path'
import BrowserUpdate from '../components/BrowserUpdate'
import UploadModal from '../components/UploadModal'
import SettingsModal from '../components/SettingsModal'
import PolicyInput from '../components/PolicyInput'
import Policy from '../components/Policy'
import BrowserDropdown from '../components/BrowserDropdown'
import ConfirmModal from './ConfirmModal'
import logo from '../../img/logo.svg'
import * as actions from '../actions'
import * as utils from '../utils'
import * as mime from '../mime'
import { minioBrowserPrefix } from '../constants'
import CopyToClipboard from 'react-copy-to-clipboard'
import storage from 'local-storage-fallback'
import InfiniteScroll from 'react-infinite-scroller';
export default class Browse extends React.Component {
componentDidMount() {
const {web, dispatch, currentBucket} = this.props
if (!web.LoggedIn()) return
web.StorageInfo()
.then(res => {
let storageInfo = Object.assign({}, {
total: res.storageInfo.Total,
free: res.storageInfo.Free
})
storageInfo.used = storageInfo.total - storageInfo.free
dispatch(actions.setStorageInfo(storageInfo))
return web.ServerInfo()
})
.then(res => {
let serverInfo = Object.assign({}, {
version: res.MinioVersion,
memory: res.MinioMemory,
platform: res.MinioPlatform,
runtime: res.MinioRuntime,
envVars: res.MinioEnvVars
})
dispatch(actions.setServerInfo(serverInfo))
})
.catch(err => {
dispatch(actions.showAlert({
type: 'danger',
message: err.message
}))
})
}
componentWillMount() {
const {dispatch} = this.props
// Clear out any stale message in the alert of Login page
dispatch(actions.showAlert({
type: 'danger',
message: ''
}))
if (web.LoggedIn()) {
web.ListBuckets()
.then(res => {
let buckets
if (!res.buckets)
buckets = []
else
buckets = res.buckets.map(bucket => bucket.name)
if (buckets.length) {
dispatch(actions.setBuckets(buckets))
dispatch(actions.setVisibleBuckets(buckets))
if (location.pathname === minioBrowserPrefix || location.pathname === minioBrowserPrefix + '/') {
browserHistory.push(utils.pathJoin(buckets[0]))
}
}
})
}
this.history = browserHistory.listen(({pathname}) => {
let decPathname = decodeURI(pathname)
if (decPathname === `${minioBrowserPrefix}/login`) return // FIXME: better organize routes and remove this
if (!decPathname.endsWith('/'))
decPathname += '/'
if (decPathname === minioBrowserPrefix + '/') {
return
}
let obj = utils.pathSlice(decPathname)
if (!web.LoggedIn()) {
dispatch(actions.setBuckets([obj.bucket]))
dispatch(actions.setVisibleBuckets([obj.bucket]))
}
dispatch(actions.selectBucket(obj.bucket, obj.prefix))
})
}
componentWillUnmount() {
this.history()
}
selectBucket(e, bucket) {
e.preventDefault()
if (bucket === this.props.currentBucket) return
browserHistory.push(utils.pathJoin(bucket))
}
searchBuckets(e) {
e.preventDefault()
let {buckets} = this.props
this.props.dispatch(actions.setVisibleBuckets(buckets.filter(bucket => bucket.indexOf(e.target.value) > -1)))
}
listObjects() {
const {dispatch} = this.props
dispatch(actions.listObjects())
}
selectPrefix(e, prefix) {
e.preventDefault()
const {dispatch, currentPath, web, currentBucket} = this.props
const encPrefix = encodeURI(prefix)
if (prefix.endsWith('/') || prefix === '') {
if (prefix === currentPath) return
browserHistory.push(utils.pathJoin(currentBucket, encPrefix))
} else {
window.location = `${window.location.origin}/minio/download/${currentBucket}/${encPrefix}?token=${storage.getItem('token')}`
}
}
makeBucket(e) {
e.preventDefault()
const bucketName = this.refs.makeBucketRef.value
this.refs.makeBucketRef.value = ''
const {web, dispatch} = this.props
this.hideMakeBucketModal()
web.MakeBucket({
bucketName
})
.then(() => {
dispatch(actions.addBucket(bucketName))
dispatch(actions.selectBucket(bucketName))
})
.catch(err => dispatch(actions.showAlert({
type: 'danger',
message: err.message
})))
}
hideMakeBucketModal() {
const {dispatch} = this.props
dispatch(actions.hideMakeBucketModal())
}
showMakeBucketModal(e) {
e.preventDefault()
const {dispatch} = this.props
dispatch(actions.showMakeBucketModal())
}
showAbout(e) {
e.preventDefault()
const {dispatch} = this.props
dispatch(actions.showAbout())
}
hideAbout(e) {
e.preventDefault()
const {dispatch} = this.props
dispatch(actions.hideAbout())
}
showBucketPolicy(e) {
e.preventDefault()
const {dispatch} = this.props
dispatch(actions.showBucketPolicy())
}
hideBucketPolicy(e) {
e.preventDefault()
const {dispatch} = this.props
dispatch(actions.hideBucketPolicy())
}
uploadFile(e) {
e.preventDefault()
const {dispatch, buckets} = this.props
if (buckets.length === 0) {
dispatch(actions.showAlert({
type: 'danger',
message: "Bucket needs to be created before trying to upload files."
}))
return
}
let file = e.target.files[0]
e.target.value = null
this.xhr = new XMLHttpRequest()
dispatch(actions.uploadFile(file, this.xhr))
}
removeObject() {
const {web, dispatch, currentPath, currentBucket, deleteConfirmation, checkedObjects} = this.props
let objects = []
if (checkedObjects.length > 0) {
objects = checkedObjects.map(obj => `${currentPath}${obj}`)
} else {
objects = [deleteConfirmation.object]
}
web.RemoveObject({
bucketname: currentBucket,
objects: objects
})
.then(() => {
this.hideDeleteConfirmation()
if (checkedObjects.length > 0) {
for (let i = 0; i < checkedObjects.length; i++) {
dispatch(actions.removeObject(checkedObjects[i].replace(currentPath, '')))
}
dispatch(actions.checkedObjectsReset())
} else {
let delObject = deleteConfirmation.object.replace(currentPath, '')
dispatch(actions.removeObject(delObject))
}
})
.catch(e => dispatch(actions.showAlert({
type: 'danger',
message: e.message
})))
}
hideAlert(e) {
e.preventDefault()
const {dispatch} = this.props
dispatch(actions.hideAlert())
}
showDeleteConfirmation(e, object) {
e.preventDefault()
const {dispatch} = this.props
dispatch(actions.showDeleteConfirmation(object))
}
hideDeleteConfirmation() {
const {dispatch} = this.props
dispatch(actions.hideDeleteConfirmation())
}
shareObject(e, object) {
e.preventDefault()
const {dispatch} = this.props
// let expiry = 5 * 24 * 60 * 60 // 5 days expiry by default
dispatch(actions.shareObject(object, 5, 0, 0))
}
hideShareObjectModal() {
const {dispatch} = this.props
dispatch(actions.hideShareObject())
}
dataType(name, contentType) {
return mime.getDataType(name, contentType)
}
sortObjectsByName(e) {
const {dispatch, objects, sortNameOrder} = this.props
dispatch(actions.setObjects(utils.sortObjectsByName(objects, !sortNameOrder)))
dispatch(actions.setSortNameOrder(!sortNameOrder))
}
sortObjectsBySize() {
const {dispatch, objects, sortSizeOrder} = this.props
dispatch(actions.setObjects(utils.sortObjectsBySize(objects, !sortSizeOrder)))
dispatch(actions.setSortSizeOrder(!sortSizeOrder))
}
sortObjectsByDate() {
const {dispatch, objects, sortDateOrder} = this.props
dispatch(actions.setObjects(utils.sortObjectsByDate(objects, !sortDateOrder)))
dispatch(actions.setSortDateOrder(!sortDateOrder))
}
logout(e) {
const {web} = this.props
e.preventDefault()
web.Logout()
browserHistory.push(`${minioBrowserPrefix}/login`)
}
fullScreen(e) {
e.preventDefault()
let el = document.documentElement
if (el.requestFullscreen) {
el.requestFullscreen()
}
if (el.mozRequestFullScreen) {
el.mozRequestFullScreen()
}
if (el.webkitRequestFullscreen) {
el.webkitRequestFullscreen()
}
if (el.msRequestFullscreen) {
el.msRequestFullscreen()
}
}
toggleSidebar(status) {
this.props.dispatch(actions.setSidebarStatus(status))
}
hideSidebar(event) {
let e = event || window.event;
// Support all browsers.
let target = e.srcElement || e.target;
if (target.nodeType === 3) // Safari support.
target = target.parentNode;
let targetID = target.id;
if (!(targetID === 'feh-trigger')) {
this.props.dispatch(actions.setSidebarStatus(false))
}
}
showSettings(e) {
e.preventDefault()
const {dispatch} = this.props
dispatch(actions.showSettings())
}
showMessage() {
const {dispatch} = this.props
dispatch(actions.showAlert({
type: 'success',
message: 'Link copied to clipboard!'
}))
this.hideShareObjectModal()
}
selectTexts() {
this.refs.copyTextInput.select()
}
handleExpireValue(targetInput, inc, object) {
inc === -1 ? this.refs[targetInput].stepDown(1) : this.refs[targetInput].stepUp(1)
if (this.refs.expireDays.value == 7) {
this.refs.expireHours.value = 0
this.refs.expireMins.value = 0
}
if (this.refs.expireDays.value + this.refs.expireHours.value + this.refs.expireMins.value == 0) {
this.refs.expireDays.value = 7
}
const {dispatch} = this.props
dispatch(actions.shareObject(object, this.refs.expireDays.value, this.refs.expireHours.value, this.refs.expireMins.value))
}
checkObject(e, objectName) {
const {dispatch} = this.props
e.target.checked ? dispatch(actions.checkedObjectsAdd(objectName)) : dispatch(actions.checkedObjectsRemove(objectName))
}
downloadSelected() {
const {dispatch} = this.props
let req = {
bucketName: this.props.currentBucket,
objects: this.props.checkedObjects,
prefix: this.props.currentPath
}
let requestUrl = location.origin + "/minio/zip?token=" + localStorage.token
this.xhr = new XMLHttpRequest()
dispatch(actions.downloadSelected(requestUrl, req, this.xhr))
}
clearSelected() {
const {dispatch} = this.props
dispatch(actions.checkedObjectsReset())
}
render() {
const {total, free} = this.props.storageInfo
const {showMakeBucketModal, alert, sortNameOrder, sortSizeOrder, sortDateOrder, showAbout, showBucketPolicy, checkedObjects} = this.props
const {version, memory, platform, runtime} = this.props.serverInfo
const {sidebarStatus} = this.props
const {showSettings} = this.props
const {policies, currentBucket, currentPath} = this.props
const {deleteConfirmation} = this.props
const {shareObject} = this.props
const {web, prefixWritable, istruncated} = this.props
// Don't always show the SettingsModal. This is done here instead of in
// SettingsModal.js so as to allow for #componentWillMount to handle
// the loading of the settings.
let settingsModal = showSettings ? <SettingsModal /> : <noscript></noscript>
let alertBox = <Alert className={ classNames({
'alert': true,
'animated': true,
'fadeInDown': alert.show,
'fadeOutUp': !alert.show
}) } bsStyle={ alert.type } onDismiss={ this.hideAlert.bind(this) }>
<div className='text-center'>
{ alert.message }
</div>
</Alert>
// Make sure you don't show a fading out alert box on the initial web-page load.
if (!alert.message)
alertBox = ''
let signoutTooltip = <Tooltip id="tt-sign-out">
Sign out
</Tooltip>
let uploadTooltip = <Tooltip id="tt-upload-file">
Upload file
</Tooltip>
let makeBucketTooltip = <Tooltip id="tt-create-bucket">
Create bucket
</Tooltip>
let loginButton = ''
let browserDropdownButton = ''
let storageUsageDetails = ''
let used = total - free
let usedPercent = (used / total) * 100 + '%'
let freePercent = free * 100 / total
if (web.LoggedIn()) {
browserDropdownButton = <BrowserDropdown fullScreenFunc={ this.fullScreen.bind(this) }
aboutFunc={ this.showAbout.bind(this) }
settingsFunc={ this.showSettings.bind(this) }
logoutFunc={ this.logout.bind(this) } />
} else {
loginButton = <a className='btn btn-danger' href='/minio/login'>Login</a>
}
if (web.LoggedIn()) {
storageUsageDetails = <div className="feh-usage">
<div className="fehu-chart">
<div style={ { width: usedPercent } }></div>
</div>
<ul>
<li>
<span>Used: </span>
{ humanize.filesize(total - free) }
</li>
<li className="pull-right">
<span>Free: </span>
{ humanize.filesize(total - used) }
</li>
</ul>
</div>
}
let createButton = ''
if (web.LoggedIn()) {
createButton = <Dropdown dropup className="feb-actions" id="fe-action-toggle">
<Dropdown.Toggle noCaret className="feba-toggle">
<span><i className="fa fa-plus"></i></span>
</Dropdown.Toggle>
<Dropdown.Menu>
<OverlayTrigger placement="left" overlay={ uploadTooltip }>
<a href="#" className="feba-btn feba-upload">
<input type="file"
onChange={ this.uploadFile.bind(this) }
style={ { display: 'none' } }
id="file-input"></input>
<label htmlFor="file-input"> <i className="fa fa-cloud-upload"></i> </label>
</a>
</OverlayTrigger>
<OverlayTrigger placement="left" overlay={ makeBucketTooltip }>
<a href="#" className="feba-btn feba-bucket" onClick={ this.showMakeBucketModal.bind(this) }><i className="fa fa-hdd-o"></i></a>
</OverlayTrigger>
</Dropdown.Menu>
</Dropdown>
} else {
if (prefixWritable)
createButton = <Dropdown dropup className="feb-actions" id="fe-action-toggle">
<Dropdown.Toggle noCaret className="feba-toggle">
<span><i className="fa fa-plus"></i></span>
</Dropdown.Toggle>
<Dropdown.Menu>
<OverlayTrigger placement="left" overlay={ uploadTooltip }>
<a href="#" className="feba-btn feba-upload">
<input type="file"
onChange={ this.uploadFile.bind(this) }
style={ { display: 'none' } }
id="file-input"></input>
<label htmlFor="file-input"> <i className="fa fa-cloud-upload"></i> </label>
</a>
</OverlayTrigger>
</Dropdown.Menu>
</Dropdown>
}
return (
<div className={ classNames({
'file-explorer': true,
'toggled': sidebarStatus
}) }>
<SideBar searchBuckets={ this.searchBuckets.bind(this) }
selectBucket={ this.selectBucket.bind(this) }
clickOutside={ this.hideSidebar.bind(this) }
showPolicy={ this.showBucketPolicy.bind(this) } />
<div className="fe-body">
<div className={ 'list-actions' + (classNames({
' list-actions-toggled': checkedObjects.length > 0
})) }>
<span className="la-label"><i className="fa fa-check-circle" /> { checkedObjects.length } Objects selected</span>
<span className="la-actions pull-right"><button onClick={ this.downloadSelected.bind(this) }> Download all as zip </button></span>
<span className="la-actions pull-right"><button onClick={ this.showDeleteConfirmation.bind(this) }> Delete selected </button></span>
<i className="la-close fa fa-times" onClick={ this.clearSelected.bind(this) }></i>
</div>
<Dropzone>
{ alertBox }
<header className="fe-header-mobile hidden-lg hidden-md">
<div id="feh-trigger" className={ 'feh-trigger ' + (classNames({
'feht-toggled': sidebarStatus
})) } onClick={ this.toggleSidebar.bind(this, !sidebarStatus) }>
<div className="feht-lines">
<div className="top"></div>
<div className="center"></div>
<div className="bottom"></div>
</div>
</div>
<img className="mh-logo" src={ logo } alt="" />
</header>
<header className="fe-header">
<Path selectPrefix={ this.selectPrefix.bind(this) } />
{ storageUsageDetails }
<ul className="feh-actions">
<BrowserUpdate />
{ loginButton }
{ browserDropdownButton }
</ul>
</header>
<div className="feb-container">
<header className="fesl-row" data-type="folder">
<div className="fesl-item fesl-item-icon"></div>
<div className="fesl-item fesl-item-name" onClick={ this.sortObjectsByName.bind(this) } data-sort="name">
Name
<i className={ classNames({
'fesli-sort': true,
'fa': true,
'fa-sort-alpha-desc': sortNameOrder,
'fa-sort-alpha-asc': !sortNameOrder
}) } />
</div>
<div className="fesl-item fesl-item-size" onClick={ this.sortObjectsBySize.bind(this) } data-sort="size">
Size
<i className={ classNames({
'fesli-sort': true,
'fa': true,
'fa-sort-amount-desc': sortSizeOrder,
'fa-sort-amount-asc': !sortSizeOrder
}) } />
</div>
<div className="fesl-item fesl-item-modified" onClick={ this.sortObjectsByDate.bind(this) } data-sort="last-modified">
Last Modified
<i className={ classNames({
'fesli-sort': true,
'fa': true,
'fa-sort-numeric-desc': sortDateOrder,
'fa-sort-numeric-asc': !sortDateOrder
}) } />
</div>
<div className="fesl-item fesl-item-actions"></div>
</header>
</div>
<div className="feb-container">
<InfiniteScroll loadMore={ this.listObjects.bind(this) }
hasMore={ istruncated }
useWindow={ true }
initialLoad={ false }>
<ObjectsList dataType={ this.dataType.bind(this) }
selectPrefix={ this.selectPrefix.bind(this) }
showDeleteConfirmation={ this.showDeleteConfirmation.bind(this) }
shareObject={ this.shareObject.bind(this) }
checkObject={ this.checkObject.bind(this) }
checkedObjectsArray={ checkedObjects } />
</InfiniteScroll>
<div className="text-center" style={ { display: (istruncated && currentBucket) ? 'block' : 'none' } }>
<span>Loading...</span>
</div>
</div>
<UploadModal />
{ createButton }
<Modal className="modal-create-bucket"
bsSize="small"
animation={ false }
show={ showMakeBucketModal }
onHide={ this.hideMakeBucketModal.bind(this) }>
<button className="close close-alt" onClick={ this.hideMakeBucketModal.bind(this) }>
<span>×</span>
</button>
<ModalBody>
<form onSubmit={ this.makeBucket.bind(this) }>
<div className="input-group">
<input className="ig-text"
type="text"
ref="makeBucketRef"
placeholder="Bucket Name"
autoFocus/>
<i className="ig-helpers"></i>
</div>
</form>
</ModalBody>
</Modal>
<Modal className="modal-about modal-dark"
animation={ false }
show={ showAbout }
onHide={ this.hideAbout.bind(this) }>
<button className="close" onClick={ this.hideAbout.bind(this) }>
<span>×</span>
</button>
<div className="ma-inner">
<div className="mai-item hidden-xs">
<a href="https://minio.io" target="_blank"><img className="maii-logo" src={ logo } alt="" /></a>
</div>
<div className="mai-item">
<ul className="maii-list">
<li>
<div>
Version
</div>
<small>{ version }</small>
</li>
<li>
<div>
Memory
</div>
<small>{ memory }</small>
</li>
<li>
<div>
Platform
</div>
<small>{ platform }</small>
</li>
<li>
<div>
Runtime
</div>
<small>{ runtime }</small>
</li>
</ul>
</div>
</div>
</Modal>
<Modal className="modal-policy"
animation={ false }
show={ showBucketPolicy }
onHide={ this.hideBucketPolicy.bind(this) }>
<ModalHeader>
Bucket Policy (
{ currentBucket })
<button className="close close-alt" onClick={ this.hideBucketPolicy.bind(this) }>
<span>×</span>
</button>
</ModalHeader>
<div className="pm-body">
<PolicyInput bucket={ currentBucket } />
{ policies.map((policy, i) => <Policy key={ i } prefix={ policy.prefix } policy={ policy.policy } />
) }
</div>
</Modal>
<ConfirmModal show={ deleteConfirmation.show }
icon='fa fa-exclamation-triangle mci-red'
text='Are you sure you want to delete?'
sub='This cannot be undone!'
okText='Delete'
cancelText='Cancel'
okHandler={ this.removeObject.bind(this) }
cancelHandler={ this.hideDeleteConfirmation.bind(this) }>
</ConfirmModal>
<Modal show={ shareObject.show }
animation={ false }
onHide={ this.hideShareObjectModal.bind(this) }
bsSize="small">
<ModalHeader>
Share Object
</ModalHeader>
<ModalBody>
<div className="input-group copy-text">
<label>
Shareable Link
</label>
<input type="text"
ref="copyTextInput"
readOnly="readOnly"
value={ window.location.protocol + '//' + shareObject.url }
onClick={ this.selectTexts.bind(this) } />
</div>
<div className="input-group" style={ { display: web.LoggedIn() ? 'block' : 'none' } }>
<label>
Expires in (Max 7 days)
</label>
<div className="set-expire">
<div className="set-expire-item">
<i className="set-expire-increase" onClick={ this.handleExpireValue.bind(this, 'expireDays', 1, shareObject.object) } />
<div className="set-expire-title">
Days
</div>
<div className="set-expire-value">
<input ref="expireDays"
type="number"
min={ 0 }
max={ 7 }
defaultValue={ 5 }
readOnly="readOnly"
/>
</div>
<i className="set-expire-decrease" onClick={ this.handleExpireValue.bind(this, 'expireDays', -1, shareObject.object) } />
</div>
<div className="set-expire-item">
<i className="set-expire-increase" onClick={ this.handleExpireValue.bind(this, 'expireHours', 1, shareObject.object) } />
<div className="set-expire-title">
Hours
</div>
<div className="set-expire-value">
<input ref="expireHours"
type="number"
min={ 0 }
max={ 23 }
defaultValue={ 0 }
readOnly="readOnly"
/>
</div>
<i className="set-expire-decrease" onClick={ this.handleExpireValue.bind(this, 'expireHours', -1, shareObject.object) } />
</div>
<div className="set-expire-item">
<i className="set-expire-increase" onClick={ this.handleExpireValue.bind(this, 'expireMins', 1, shareObject.object) } />
<div className="set-expire-title">
Minutes
</div>
<div className="set-expire-value">
<input ref="expireMins"
type="number"
min={ 0 }
max={ 59 }
defaultValue={ 0 }
readOnly="readOnly"
/>
</div>
<i className="set-expire-decrease" onClick={ this.handleExpireValue.bind(this, 'expireMins', -1, shareObject.object) } />
</div>
</div>
</div>
</ModalBody>
<div className="modal-footer">
<CopyToClipboard text={ window.location.protocol + '//' + shareObject.url } onCopy={ this.showMessage.bind(this) }>
<button className="btn btn-success">
Copy Link
</button>
</CopyToClipboard>
<button className="btn btn-link" onClick={ this.hideShareObjectModal.bind(this) }>
Cancel
</button>
</div>
</Modal>
{ settingsModal }
</Dropzone>
</div>
</div>
)
}
}
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Generators.js | sThig/jabbascrypt | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function* load(limit) {
let i = 1;
while (i <= limit) {
yield { id: i, name: i };
i++;
}
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
componentDidMount() {
const users = [];
for (let user of load(4)) {
users.push(user);
}
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-generators">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
app/javascript/mastodon/features/compose/components/upload_form.js | d6rkaiz/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import UploadProgressContainer from '../containers/upload_progress_container';
import ImmutablePureComponent from 'react-immutable-pure-component';
import UploadContainer from '../containers/upload_container';
import SensitiveButtonContainer from '../containers/sensitive_button_container';
import { FormattedMessage } from 'react-intl';
export default class UploadForm extends ImmutablePureComponent {
static propTypes = {
mediaIds: ImmutablePropTypes.list.isRequired,
};
render () {
const { mediaIds } = this.props;
return (
<div className='compose-form__upload-wrapper'>
<UploadProgressContainer icon='upload' message={<FormattedMessage id='upload_progress.label' defaultMessage='Uploading…' />} />
<div className='compose-form__uploads-wrapper'>
{mediaIds.map(id => (
<UploadContainer id={id} key={id} />
))}
</div>
{!mediaIds.isEmpty() && <SensitiveButtonContainer />}
</div>
);
}
}
|
packages/xo-web/src/xo-app/hub/templates/resource.js | vatesfr/xo-web | import _ from 'intl'
import ActionButton from 'action-button'
import decorate from 'apply-decorators'
import defined from '@xen-orchestra/defined'
import Icon from 'icon'
import marked from 'marked'
import React from 'react'
import { alert, form } from 'modal'
import { Card, CardBlock, CardHeader } from 'card'
import { Col, Row } from 'grid'
import { connectStore, formatSize } from 'utils'
import { createGetObjectsOfType } from 'selectors'
import { deleteTemplates, downloadAndInstallResource, pureDeleteVm } from 'xo'
import { error, success } from 'notification'
import { find, filter, isEmpty, map, omit, startCase } from 'lodash'
import { injectState, provideState } from 'reaclette'
import { withRouter } from 'react-router'
import ResourceForm from './resource-form'
const Li = props => <li {...props} className='list-group-item' />
const Ul = props => <ul {...props} className='list-group' />
// Template <id> : specific to a template version
// Template <namespace> : general template identifier (can have multiple versions)
// Template <any> : a default hub metadata, please don't remove it from BANNED_FIELDS
const BANNED_FIELDS = ['any', 'description'] // These fields will not be displayed on description modal
const EXCLUSIVE_FIELDS = ['longDescription'] // These fields will not have a label
const MARKDOWN_FIELDS = ['longDescription', 'description']
const STATIC_FIELDS = [...EXCLUSIVE_FIELDS, ...BANNED_FIELDS] // These fields will not be displayed with dynamic fields
export default decorate([
withRouter,
connectStore(() => {
const getTemplates = createGetObjectsOfType('VM-template').sort()
const getPools = createGetObjectsOfType('pool')
return {
templates: getTemplates,
pools: getPools,
hubInstallingResources: state => state.hubInstallingResources,
}
}),
provideState({
initialState: () => ({
selectedInstallPools: [],
}),
effects: {
async install() {
const {
id,
name,
namespace,
markHubResourceAsInstalled,
markHubResourceAsInstalling,
templates,
version,
} = this.props
const { isTemplateInstalled } = this.state
const resourceParams = await form({
defaultValue: {
mapPoolsSrs: {},
pools: [],
},
render: props => <ResourceForm install multi poolPredicate={isTemplateInstalled} {...props} />,
header: (
<span>
<Icon icon='add-vm' /> {name}
</span>
),
size: 'medium',
})
markHubResourceAsInstalling(id)
try {
await Promise.all(
resourceParams.pools.map(async pool => {
await downloadAndInstallResource({
namespace,
id,
version,
sr: defined(resourceParams.mapPoolsSrs[pool.id], pool.default_SR),
})
const oldTemplates = filter(
templates,
template => pool.$pool === template.$pool && template.other['xo:resource:namespace'] === namespace
)
await Promise.all(oldTemplates.map(template => pureDeleteVm(template)))
})
)
success(_('hubImportNotificationTitle'), _('successfulInstall'))
} catch (_error) {
error(_('hubImportNotificationTitle'), _error.message)
}
markHubResourceAsInstalled(id)
},
async create() {
const { isPoolCreated, installedTemplates } = this.state
const { name } = this.props
const resourceParams = await form({
defaultValue: {
pool: undefined,
},
render: props => <ResourceForm poolPredicate={isPoolCreated} {...props} />,
header: (
<span>
<Icon icon='add-vm' /> {name}
</span>
),
size: 'medium',
})
const { $pool } = resourceParams.pool
const template = find(installedTemplates, { $pool })
if (template !== undefined) {
this.props.router.push(`/vms/new?pool=${$pool}&template=${template.id}`)
} else {
throw new Error(`can't find template for pool: ${$pool}`)
}
},
async deleteTemplates(__, { name }) {
const { isPoolCreated } = this.state
const resourceParams = await form({
defaultValue: {
pools: [],
},
render: props => <ResourceForm delete multi poolPredicate={isPoolCreated} {...props} />,
header: (
<span>
<Icon icon='vm-delete' /> {name}
</span>
),
size: 'medium',
})
const _templates = filter(this.state.installedTemplates, template =>
find(resourceParams.pools, { $pool: template.$pool })
)
await deleteTemplates(_templates)
},
updateSelectedInstallPools(_, selectedInstallPools) {
return {
selectedInstallPools,
}
},
updateSelectedCreatePool(_, selectedCreatePool) {
return {
selectedCreatePool,
}
},
redirectToTaskPage() {
this.props.router.push('/tasks')
},
showDescription() {
const {
data: { public: _public },
name,
} = this.props
alert(
name,
<div>
{isEmpty(omit(_public, BANNED_FIELDS)) ? (
<p>{_('hubTemplateDescriptionNotAvailable')}</p>
) : (
<div>
<Ul>
{EXCLUSIVE_FIELDS.map(fieldKey => {
const field = _public[fieldKey]
if (field !== undefined) {
return (
<Li key={fieldKey}>
{MARKDOWN_FIELDS.includes(fieldKey) ? (
<div
dangerouslySetInnerHTML={{
__html: marked(field),
}}
/>
) : (
field
)}
</Li>
)
}
return null
})}
</Ul>
<br />
<Ul>
{map(omit(_public, STATIC_FIELDS), (value, key) => (
<Li key={key}>
{startCase(key)}
<span className='pull-right'>
{typeof value === 'boolean' ? (
<Icon color={value ? 'green' : 'red'} icon={value ? 'true' : 'false'} />
) : key.toLowerCase().endsWith('size') ? (
<strong>{formatSize(value)}</strong>
) : (
<strong>{value}</strong>
)}
</span>
</Li>
))}
</Ul>
</div>
)}
</div>
)
},
},
computed: {
description: (
_,
{
data: {
public: { description },
},
description: _description,
}
) =>
(description !== undefined || _description !== undefined) && (
<div
className='text-muted'
dangerouslySetInnerHTML={{
__html: marked(defined(description, _description)),
}}
/>
),
installedTemplates: (_, { id, templates }) => filter(templates, ['other.xo:resource:xva:id', id]),
isTemplateInstalledOnAllPools: ({ installedTemplates }, { pools }) =>
installedTemplates.length > 0 &&
pools.every(pool => installedTemplates.find(template => template.$pool === pool.id) !== undefined),
isTemplateInstalled: ({ installedTemplates }) => pool =>
installedTemplates.find(template => template.$pool === pool.id) === undefined,
isPoolCreated: ({ installedTemplates }) => pool =>
installedTemplates.find(template => template.$pool === pool.id) !== undefined,
},
}),
injectState,
({ effects, hubInstallingResources, id, name, size, state, totalDiskSize }) => (
<Card shadow>
<CardHeader>
{name}
<ActionButton
className='pull-right'
color='light'
data-name={name}
disabled={state.installedTemplates.length === 0}
handler={effects.deleteTemplates}
icon='delete'
size='small'
style={{ border: 'none' }}
tooltip={_('remove')}
/>
<br />
</CardHeader>
<CardBlock>
{state.description}
<ActionButton className='pull-right' color='light' handler={effects.showDescription} icon='info' size='small'>
{_('moreDetails')}
</ActionButton>
<div>
<span className='text-muted'>{_('size')}</span>
{' '}
<strong>{formatSize(size)}</strong>
</div>
<div>
<span className='text-muted'>{_('totalDiskSize')}</span>
{' '}
<strong>{formatSize(totalDiskSize)}</strong>
</div>
<hr />
<Row>
<Col mediumSize={6}>
<ActionButton
block
disabled={state.isTemplateInstalledOnAllPools}
form={state.idInstallForm}
handler={effects.install}
icon='add'
pending={hubInstallingResources[id]}
>
{_('install')}
</ActionButton>
</Col>
<Col mediumSize={6}>
<ActionButton
block
disabled={state.installedTemplates.length === 0}
form={state.idCreateForm}
handler={effects.create}
icon='deploy'
>
{_('create')}
</ActionButton>
</Col>
</Row>
</CardBlock>
</Card>
),
])
|
src/components/Header.js | jamigibbs/fair-split-calculator | import React from 'react';
const Header = (props) => {
return (
<div className="header clearfix">
<h3>Fair Split</h3>
<p className="text-muted">This calculator takes two earnings and determines the amount each should pay towards household bills. Based on the thought that two different incomes should not be paying the same amount.</p>
</div>
);
}
export default Header;
|
project-base/src/universal/features/routing/components/NotFound/index.js | ch-apptitude/goomi | /**
*
* NotFound
*
*/
import React from 'react';
import { Row, Col } from 'react-flexbox-grid';
import styled from 'styled-components';
import Theme from 'assets/theme';
import Text from 'features/common_ui/components/Text';
import messages from './messages';
const Container = styled.div`
height: 100%;
width: 100%;
text-align: center;
`;
const Title = styled(Text)`margin-bottom: 30px;`;
const NotFound = () => (
<Container>
<Row>
<Col xs={12}>
<Text message={messages.errorTitle} tag="h1" size={Theme.Metrics.title} />
</Col>
</Row>
<Row>
<Col xs={12}>
<Title message={messages.title} tag="h2" size={Theme.Metrics.subTitle} />
</Col>
</Row>
<Row>
<Col xs={12}>
<Text message={messages.body} tag="p" />
</Col>
</Row>
</Container>
);
export default NotFound;
|
src/user/userForm.js | codyloyd/teamup | import React from 'react'
import {Field, reduxForm} from 'redux-form'
const UserForm = props => {
const {handleSubmit} = props
return (
<form onSubmit={handleSubmit}>
<div>
<label>First Name</label>
<div>
<Field
name="firstName"
component="input"
type="text"
placeholder="First Name"
/>
</div>
</div>
</form>
)
}
export default reduxForm({form: 'userForm'})(UserForm)
|
src/containers/GuessInput.js | dpickett/name-game | import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Select from 'react-select'
class GuessInput extends React.Component {
constructor () {
super();
this.focus = this.focus.bind(this)
this.onChange = this.onChange.bind(this)
this.state = {}
}
focus() {
}
onChange(newVal) {
//bubble event back up to redux-form
this.props.onChange(newVal)
}
componentDidMount () {
this.focus()
const { identities } = this.props
if(!this.state.options){
this.setState({
options: identities.map((identity) => {
return {
value: identity.name,
label: identity.name
}
})
})
}
}
render () {
const { options } = this.state
const { identities } = this.props
const inputProps = {
placeholder: 'Guess Who',
options: options,
autofocus: true,
autosize: false,
name: this.props.name,
value: this.props.value,
onChange: this.onChange
}
return (
<div>
<Select { ...inputProps } />
</div>
);
}
}
function mapStateToProps (state) {
return {
identities: state.identities
}
}
export default connect(mapStateToProps)(GuessInput)
|
chrome/extension/todoapp.js | altany/react-new-tab-chrome-extension | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import Root from '../../app/containers/Root';
import createStore from '../../app/store/configureStore';
import './todoapp.css';
chrome.storage.sync.get('state', (obj) => {
const { state } = obj;
const initialState = JSON.parse(state || '{}');
const store = createStore(initialState);
if (document.querySelector('#root')) {
ReactDOM.render(
<Provider store={store}>
<Root isPopup={!!(document.querySelector('#root.popup'))} />
</Provider>,
document.querySelector('#root')
);
}
window.addEventListener('load', () => {
const links = document.querySelectorAll('aside nav div, main div a');
Array.from(links).forEach((link) => {
link.addEventListener('contextmenu', (e) => {
e.preventDefault();
return false;
}, false);
});
});
});
|
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | cs011164/cs011164.github.io | import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
docs/src/app/pages/components/ProgressBar/ExampleProgressBarDefault.js | GetAmbassador/react-ions | import React from 'react'
import ProgressBar from 'react-ions/lib/components/ProgressBar'
const ExampleProgressBarDefault = () => (
<ProgressBar />
)
export default ExampleProgressBarDefault
|
app/jsx/confetti/index.js | djbender/canvas-lms | /*
* Copyright (C) 2020 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import ReactDOM from 'react-dom'
import Confetti from './components/Confetti'
export default function renderConfettiApp(env, elt) {
ReactDOM.render(<Confetti />, elt)
}
|
src/app.js | chemoish/react-webpack | import React from 'react';
import Router from 'react-router';
var {DefaultRoute, Link, Route, RouteHandler} = Router;
var App = React.createClass({
render() {
return (
<div>
<header>
<ul>
<li><Link to="home">Home</Link></li>
<li><Link to="category-list">Category List</Link></li>
<li><Link to="setting">Settings</Link></li>
</ul>
</header>
<h1>Look Ma—I am an app</h1>
<RouteHandler />
</div>
);
}
});
Router.run((
<Route path="/" handler={App}>
<DefaultRoute handler={require('react-router-proxy!./components/home/home.js')}></DefaultRoute>
<Route name="category" path="/category/:slug" handler={require('react-router-proxy!./components/category/category.js')}></Route>
<Route name="category-list" path="/categories" handler={require('react-router-proxy!./components/category/category-list.js')}></Route>
<Route name="home" handler={require('react-router-proxy!./components/home/home.js')}></Route>
<Route name="movie" path="/movie/:slug" handler={require('react-router-proxy!./components/movie/movie.js')}></Route>
<Route name="setting" path="settings" handler={require('react-router-proxy!./components/setting/setting.js')}></Route>
</Route>
), Router.HistoryLocation, function (Handler) {
React.render(<Handler />, document.body);
});
|
frontend/src/components/overview/index.js | rossnomann/playlog | import moment from 'moment';
import PropTypes from 'prop-types';
import React from 'react';
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux';
import {createSelector} from 'reselect';
import {actions} from '../../redux';
import {DATE_FORMAT, formatDate} from '../../utils';
import AlbumIcon from '../../icons/album.svg';
import ArtistIcon from '../../icons/artist.svg';
import CalendarIcon from '../../icons/calendar.svg';
import PlayIcon from '../../icons/play.svg';
import TrackIcon from '../../icons/track.svg';
import DateChart from '../shared/date-chart';
import Error from '../shared/error';
import Spinner from '../shared/spinner';
import Counters from './counters';
import Navigation from './navigation';
import Nowplay from './nowplay';
import RecentTracks from './recent-tracks';
import User from './user';
import './index.css';
const Overview = ({
biggestDay,
counters,
currentStreak,
longestStreak,
nowplay,
recentTracks,
recentlyAdded,
user
}) => (
<div className="overview">
<div className="overview-sidebar">
<div className="overview-sidebar-item">
<User {...user} />
</div>
{
nowplay &&
<div className="overview-sidebar-item">
<Nowplay {...nowplay} />
</div>
}
{
currentStreak && <div className="overview-sidebar-item">
<Counters {...{
header: 'Current Streak',
data: [
{
icon: CalendarIcon,
label: 'days',
value: currentStreak.days
},
{
icon: PlayIcon,
label: 'plays',
value: currentStreak.plays
}
],
footer: currentStreak.period
}} />
</div>
}
{
longestStreak && <div className="overview-sidebar-item">
<Counters {...{
header: 'Longest Streak',
data: [
{
icon: CalendarIcon,
label: 'days',
value: longestStreak.days
},
{
icon: PlayIcon,
label: 'plays',
value: longestStreak.plays
}
],
footer: longestStreak.period
}} />
</div>
}
{
biggestDay && <div className="overview-sidebar-item">
<Counters {...{
header: 'Biggest Day',
data: [
{
icon: PlayIcon,
label: 'plays',
value: biggestDay.plays
}
],
footer: biggestDay.day
}} />
</div>
}
<div className="overview-sidebar-item">
<Counters {...{
header: 'Recently Added',
data: [
{
icon: ArtistIcon,
label: 'artists',
value: recentlyAdded.artists
},
{
icon: AlbumIcon,
label: 'albums',
value: recentlyAdded.albums
},
{
icon: TrackIcon,
label: 'tracks',
value: recentlyAdded.tracks
}
],
footer: recentlyAdded.period
}} />
</div>
</div>
<div className="overview-content">
<div className="overview-content-header">Overview</div>
<div className="overview-content-row">
<div className="overview-content-row-col overview-content-row-col__one-fourth">
<Navigation counters={counters} />
</div>
<div className="overview-content-row-col overview-content-row-col__three-fourths">
<div style={{padding: '5px 0'}}>
<DateChart height="190px" />
</div>
</div>
</div>
<div className="overview-content-header">Recent Tracks</div>
<div className="overview-content-row">
<RecentTracks data={recentTracks} />
</div>
</div>
</div>
);
Overview.propTypes = {
biggestDay: PropTypes.object,
counters: PropTypes.object.isRequired,
currentStreak: PropTypes.object,
longestStreak: PropTypes.object,
nowplay: PropTypes.object,
recentTracks: PropTypes.array.isRequired,
recentlyAdded: PropTypes.object.isRequired,
user: PropTypes.object.isRequired
};
class OverviewContainer extends React.Component {
componentDidMount() {
if (!this.props.data.loaded) {
this.props.loadData();
}
}
render() {
let data = this.props.data,
result = null;
if (!data.loaded) {
result = <Spinner fullscreen={true} />;
} else {
if (data.success) {
result = <Overview {...data.payload} />;
} else {
result = <Error />;
}
}
return result;
}
}
OverviewContainer.propTypes = {
data: PropTypes.object.isRequired,
loadData: PropTypes.func.isRequired
};
function groupTracks(items) {
const result = {};
items.forEach(item => {
const date = moment.utc(item.date).local();
const key = date.clone().startOf('day').unix();
if (!result.hasOwnProperty(key)) {
result[key] = {date: date.format(DATE_FORMAT), items: []};
}
result[key].items.push({
artist: {
id: item.artistId,
name: item.artist
},
album: {
id: item.albumId,
name: item.album
},
track: {
id: item.trackId,
name: item.track
},
time: date.format('HH:mm')
});
});
return Object.keys(result).sort().reverse().map(key => result[key]);
}
const dataSelector = createSelector(
state => state.overview,
data => {
if (data.loaded && data.success) {
let {
biggestDay,
currentStreak,
longestStreak,
recentTracks,
recentlyAdded
} = data.payload;
[currentStreak, longestStreak, recentlyAdded].forEach(item => {
if (item) {
const startDate = formatDate(item.startDate);
const endDate = formatDate(item.endDate);
item.period = `${startDate} — ${endDate}`;
}
});
if (biggestDay) {
biggestDay.day = formatDate(biggestDay.day);
}
data.payload.recentTracks = groupTracks(recentTracks);
}
return data;
}
);
export default connect(
state => ({data: dataSelector(state)}),
dispatch => ({loadData: bindActionCreators(actions.overviewRequest, dispatch)})
)(OverviewContainer);
|
data/workshops.js | subvisual/2017.mirrorconf.com | import React from 'react';
import EventDescription, { Text, Title } from '../Components/EventDescription';
import atomicImage from '../images/workshops/atomic_workshop.jpg';
import productImage from '../images/workshops/product_workshop.jpg';
import saraImage from '../images/workshops/sara_workshop.jpg';
import vitalyImage from '../images/workshops/vitaly_workshop.jpg';
/* eslint-disable max-len, react/no-unescaped-entities */
export default [
{
id: 'product-roadmapping',
name: 'Roadmapping Your Product Roadmap',
instructor: 'C Todd Lombardo',
datetime: 'Oct. 10 - 10:00 AM',
location: 'GNRation',
locationUrl: 'https://www.google.pt/maps/place/GNRation/@41.5531265,-8.4284087,17z/data=!3m1!4b1!4m5!3m4!1s0xd24fee9ae15fe63:0xf715da419f911455!8m2!3d41.5531265!4d-8.42622?hl=en',
image: productImage,
attendeePrice: 150,
nonAttendeePrice: 200,
isExpanded: true,
description: <EventDescription>
<Text>Ask 10 people what a product roadmap is and you will get 10 different answers! This artifact is an often misunderstood component of product development, but an incredibly important one to get right. Creating a great one is part art and part science. In this session we will talk through the real purpose of a roadmap and how it can be used to get the most out of your project and team. We'll unpack the key steps in the process such as product visioning, themes, prioritization and stakeholder buy-in and alignment as well as and shed some light on the tools and frameworks that can be used to ensure a successful roadmapping effort.</Text>
</EventDescription>,
},
{
id: 'front-end-espresso',
name: 'The Front-End Espresso Shot',
instructor: 'Sara Soueidan',
image: saraImage,
datetime: 'Oct. 10 - 10:00 AM',
location: 'GNRation',
locationUrl: 'https://www.google.pt/maps/place/GNRation/@41.5531265,-8.4284087,17z/data=!3m1!4b1!4m5!3m4!1s0xd24fee9ae15fe63:0xf715da419f911455!8m2!3d41.5531265!4d-8.42622?hl=en',
attendeePrice: 150,
soldOut: true,
nonAttendeePrice: 200,
description: <EventDescription>
<Text>CSS has seen a lot of new feature releases in the last few years. Keeping up with everything can sometimes be overwhelming. It’s even harder for many designers and developers to ditch the tools and frameworks they’re already familiar with and relying on, in favor of new, native “frameworks” with a less than familiar syntax. But doing so is the way forward. CSS’s native features like Flexbox and Grid as well as CSS Variables provide a lot more power and flexibility than any previous frameworks or tools did—power than we should embrace and put to good use today moving forward.</Text>
<Text>In this workshop, we will cover a range of topics from SVG usage as an image system to CSS features, building progressively enhanced page layouts with the newest CSS layout techniques, creating truly scalable, responsive typography, theming using CSS Variables, and creative visual effects using CSS transformations, blend modes and filters, and making sure our components have at least the minimum level of accessibility.</Text>
<Text>Attendees will walk away with knowledge they can apply right away, including:</Text>
<ul>
<li className="EventDescription-listItem"><Text>Creating creative page layouts with the new CSS Grid framework.</Text></li>
<li className="EventDescription-listItem"><Text>Component-level layout enhancements using CSS Flexbox.</Text></li>
<li className="EventDescription-listItem"><Text>Using CSS’s native feature detection @supports to leverage the new layout techniques, all the while providing basic fallback for non-supporting browsers.</Text></li>
<li className="EventDescription-listItem"><Text>Using CSS custom properties to create and support multiple themes, including providing an accessible theme for less accessible designs.</Text></li>
<li className="EventDescription-listItem"><Text>Using math in CSS to create scalable, responsive typography for our responsive designs: CSS viewport and relative units inside calc().</Text></li>
<li className="EventDescription-listItem"><Text>Using CSS transforms and shapes to break out of the box and create creative, non-rectangular layouts.</Text></li>
<li className="EventDescription-listItem"><Text>Make peace with the occasional responsible usage of CSS hacks, without compromising the accessibility of the user interface.</Text></li>
<li className="EventDescription-listItem"><Text>Implementing SVGs in a responsive workflow, including basic icon animations.</Text></li>
<li className="EventDescription-listItem"><Text>Enhancing and styling UI elements (such as form elements) accessibly and using animated SVGs.</Text></li>
<li className="EventDescription-listItem"><Text>Learn how to use SVG to display, style and apply powerful image effects to other image formats!</Text></li>
<li className="EventDescription-listItem"><Text>Strong focus on semantics and accessibility using ARIA roles and attributes where needed.</Text></li>
<li className="EventDescription-listItem"><Text>Learning how all the new CSS features open up more flexible possibilities for designing and making decisions in the browser.</Text></li>
<li className="EventDescription-listItem"><Text>We'll also be getting an overview of CSS graphical effects such as filters and blend modes, allowing us to give our designs that extra punch, making design and experimenting in the browser more accessible to us.</Text></li>
</ul>
<Text>Attendees will be challenged with a series of creative exercises, implying all the above techniques to solve real-world design challenges.</Text>
<Text>Satisfaction guaranteed.</Text>
</EventDescription>,
},
{
id: 'atomic-design',
name: 'Atomic Design: Patterns and Principles',
instructor: 'Brad Frost',
image: atomicImage,
datetime: 'Oct. 11 - 10:00 AM',
location: 'GNRation',
locationUrl: 'https://www.google.pt/maps/place/GNRation/@41.5531265,-8.4284087,17z/data=!3m1!4b1!4m5!3m4!1s0xd24fee9ae15fe63:0xf715da419f911455!8m2!3d41.5531265!4d-8.42622?hl=en',
attendeePrice: 150,
soldOut: true,
nonAttendeePrice: 200,
description: <EventDescription>
<Text>Style guides, design systems, and pattern libraries provide solid ground for us to stand on as we tackle the increasingly diverse and fast-moving web landscape. This full-day session will tackle all that goes into making and maintaining successful interface design systems, including:</Text>
<Title>Atomic Design Principles</Title>
<Text>We’ll cover core principles of modular UI interface design and discuss considerations around atomic design, a methodology for crafting robust, deliberate design systems.</Text>
<Title>Selling Design Systems</Title>
<Text>We all know design systems and pattern libraries are great, but how do you get your clients, bosses, and teammates on board? We’ll cover tactics and tools for selling pattern libraries to clients and stakeholders, and detail how to create an interface inventory to pave the way for style guide success.</Text>
<Title>A Pattern-Based Process</Title>
<Text>Making modular interfaces requires massive shifts in our design and development process. We’ll discuss why front-end development is an essential part of the design process and demonstrate how tools like lo-fi sketches, style tiles, element collages, Pattern Lab, and others facilitate collaboration—and result in successful design systems.</Text>
<Title>Style Guide Maintenance</Title>
<Text> Like a fine wine, a design system increases in value over time. We’ll discuss tactics and techniques to ensure that your pattern library stays in sync, and your design system provides lasting value to your organization.</Text>
<Title>UI Patterns</Title>
<Text>Creating modular interfaces is challenging, but thankfully the web community is hard at work creating flexible, downright innovative UI design patterns. We’ll look at patterns for tackling layout, navigation, images, data tables, and really anything else you can include in an interface.</Text>
<Text>By the end of the day, you’ll be armed with all the insights and resources you need to create, sell, and maintain effective interface design systems.</Text>
</EventDescription>,
},
{
id: 'responsive-design',
name: 'Responsive Interface Design Bootcamp',
instructor: 'Vitaly Friedman',
image: vitalyImage,
datetime: 'Oct. 11 - 10:00 AM',
location: 'GNRation',
locationUrl: 'https://www.google.pt/maps/place/GNRation/@41.5531265,-8.4284087,17z/data=!3m1!4b1!4m5!3m4!1s0xd24fee9ae15fe63:0xf715da419f911455!8m2!3d41.5531265!4d-8.42622?hl=en',
attendeePrice: 150,
soldOut: true,
nonAttendeePrice: 200,
description: <EventDescription>
<Text>Are you ready for a design challenge? In this brand new workshop, Vitaly Friedman, editor-in-chief and co-founder of Smashing Magazine, will be taking a microscopic examination of common interface components and problems appearing in responsive user interfaces. In this workshop, we’ll be spending an entire day drawing and designing responsive interfaces, starting from accordions, to date/time pickers, sliders, feature comparisons, car configurators all the way to insurance calculators and trip planners.</Text>
<Text>The workshop is intended for intermediate/advanced designers and developers who have an understanding of responsive design and how it works. </Text>
<Text>Most techniques are borrowed from mid-size and large-scale real-life projects, such as large eCommerce projects, online magazines and web applications. We won't cover the basics, instead, the workshop covers more advanced — and often obscure and innovative techniques.</Text>
<Title>What will the workshop cover?</Title>
<Text>In this workshop, we’ll go hands-on into exploring:</Text>
<ul>
<li className="EventDescription-listItem"><Text>Responsive art direction techniques and advanced layouts, with many inspiring and memorable examples,</Text></li>
<li className="EventDescription-listItem"><Text>Navigation, with mega-drop-downs, breadcrumbs, carousels, accordion and filters,</Text></li>
<li className="EventDescription-listItem"><Text>Builders, with a car configurator and mobile plan builder,</Text></li>
<li className="EventDescription-listItem"><Text>Forms, with email verification, password input, country selector, privacy issues, sliders and public transportation, and a banking transaction UI,</Text></li>
<li className="EventDescription-listItem"><Text>Date pickers, date range picker and a time picker, incl. booking an appointment and booking an airline ticket,</Text></li>
<li className="EventDescription-listItem"><Text>Tables, with a feature comparison table, currency exchange calculator, pricing plans,</Text></li>
<li className="EventDescription-listItem"><Text>Search, with autocomplete, filters, search results,</Text></li>
<li className="EventDescription-listItem"><Text>Calendars, with a multi-track schedule, TV Guide schedule, music festival schedule, exhibition calendar, spreadsheets and dashboard,</Text></li>
<li className="EventDescription-listItem"><Text>Audio/Video, with a video player UI and audio-based input,</Text></li>
<li className="EventDescription-listItem"><Text>Maps / Data Visualization, with a shopping mall map, election map, smart region input.</Text></li>
<li className="EventDescription-listItem"><Text>Timelines, with a historical timelines, soccer game signature and live leaderboard and standings,</Text></li>
<li className="EventDescription-listItem"><Text>Real-time experience with betting UI for soccer, poker and live video streaming,</Text></li>
<li className="EventDescription-listItem"><Text>Footnotes and sidenotes in magazine articles,</Text></li>
<li className="EventDescription-listItem"><Text>Seat selection, for a concert/theatre/exhibition and a perfect airplane check-in,</Text></li>
<li className="EventDescription-listItem"><Text>Responsive PDF for documents and restaurant menus,</Text></li>
<li className="EventDescription-listItem"><Text>Responsive upscaling, with eCommerce experience on large screens and article layout on large screens,</Text></li>
<li className="EventDescription-listItem"><Text>Design anti-patterns to avoid to prevent running into maintenance issues and “slow UX decay”.</Text></li>
</ul>
<Title>What hardware/software do you need?</Title>
<Text>You'll need to bring a lot of creativity with your preferred coffee mug. We’ll be spending a lot of time drawing, sketching, designing and thinking. Laptop is preferred but not absolutely necessary. You’ll need a lot of sleep reserves since it’s going to be a packed day. Bring a lot of attention to detail and non-standard thinking to this one! ;-)</Text>
</EventDescription>,
},
];
/* eslint-enable max-len */
|
src/ui/elements/svg/Mailing.js | gouxlord/dev-insight | import React from 'react'
var Mailing = React.createClass({
render: function () {
return (
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 161.736 150" preserveAspectRatio="xMinYMin meet">
<polygon fill="#ED574E" points="81.093,103.13 21.421,145.185 152.247,146.088 "/>
<polygon fill="#FFFFFF" points="31.251,8.482 31.251,75.028 73.217,93.754 81.093,87.95 87.95,93.754 142.417,67.046 142.417,8.482 "/>
<g>
<path d="M160.537,62.135l-20.652-13.692V2.679c0-1.479-1.199-2.679-2.679-2.679H24.527c-1.481,0-2.679,1.2-2.679,2.679v45.768 L1.198,62.135H1.2C0.476,62.615,0,63.436,0,64.367v82.954C0,148.8,1.2,150,2.679,150h156.379c1.479,0,2.679-1.2,2.679-2.679V64.367 C161.736,63.436,161.259,62.615,160.537,62.135L160.537,62.135z M21.848,71.503l-8.402-4.458h8.402V71.503z M5.357,68.821 l61.601,32.676L5.357,142.33V68.821z M80.866,98.704l69.303,45.938H11.565L80.866,98.704z M94.776,101.497l61.601-32.676v73.511 L94.776,101.497z M139.885,67.046h8.406l-8.406,4.459V67.046z M150.169,61.688h-10.284V54.87L150.169,61.688z M134.527,5.357 v68.988L89.694,98.128l-7.348-4.87c-0.898-0.595-2.063-0.595-2.959,0l-7.347,4.87L27.206,74.344V5.357H134.527z M21.848,61.688 H11.567l10.281-6.815V61.688z M21.848,61.688"/>
<path d="M80.866,70.447h21.341c1.48,0,2.679-1.2,2.679-2.679c0-1.479-1.198-2.679-2.679-2.679H80.866 c-10.291,0-18.664-8.373-18.664-18.664v-0.79c0-10.291,8.373-18.664,18.664-18.664s18.662,8.373,18.662,18.664v1.976 c0,2.229-1.812,4.041-4.039,4.041c-2.229,0-4.041-1.812-4.041-4.041v-3.755c0-6.379-5.189-11.571-11.571-11.571 c-6.379,0-11.571,5.192-11.571,11.571c0,6.381,5.191,11.571,11.571,11.571c2.917,0,5.584-1.086,7.623-2.876 c1.659,2.674,4.618,4.458,7.989,4.458c5.182,0,9.396-4.215,9.396-9.397v-1.976c0-13.245-10.774-24.021-24.02-24.021 S56.845,32.391,56.845,45.636v0.79C56.845,59.671,67.621,70.447,80.866,70.447L80.866,70.447z M79.877,50.07 c-3.427,0-6.213-2.787-6.213-6.214c0-3.425,2.789-6.214,6.213-6.214c3.427,0,6.213,2.789,6.213,6.214 C86.091,47.284,83.305,50.07,79.877,50.07L79.877,50.07z M79.877,50.07"/>
</g>
</svg>
)
}
});
export default Mailing;
|
js/AppNavigator.js | crod93/googlePlacesEx-react-native |
'use strict';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import _ from 'lodash/core';
import { Drawer } from 'native-base';
import { BackAndroid, Platform, StatusBar } from 'react-native';
import { closeDrawer } from './actions/drawer';
import { popRoute } from './actions/route';
import Navigator from 'Navigator';
import Login from './components/login/';
import Home from './components/home/';
import BlankPage from './components/blankPage/';
import SplashPage from './components/splashscreen/';
import SideBar from './components/sideBar';
import { statusBarColor } from "./themes/base-theme";
Navigator.prototype.replaceWithAnimation = function (route) {
const activeLength = this.state.presentedIndex + 1;
const activeStack = this.state.routeStack.slice(0, activeLength);
const activeAnimationConfigStack = this.state.sceneConfigStack.slice(0, activeLength);
const nextStack = activeStack.concat([route]);
const destIndex = nextStack.length - 1;
const nextSceneConfig = this.props.configureScene(route, nextStack);
const nextAnimationConfigStack = activeAnimationConfigStack.concat([nextSceneConfig]);
const replacedStack = activeStack.slice(0, activeLength - 1).concat([route]);
this._emitWillFocus(nextStack[destIndex]);
this.setState({
routeStack: nextStack,
sceneConfigStack: nextAnimationConfigStack,
}, () => {
this._enableScene(destIndex);
this._transitionTo(destIndex, nextSceneConfig.defaultTransitionVelocity, null, () => {
this.immediatelyResetRouteStack(replacedStack);
});
});
};
export var globalNav = {};
const searchResultRegexp = /^search\/(.*)$/;
const reducerCreate = params=>{
const defaultReducer = Reducer(params);
return (state, action)=>{
var currentState = state;
if(currentState){
while (currentState.children){
currentState = currentState.children[currentState.index]
}
}
return defaultReducer(state, action);
}
};
const drawerStyle = { shadowColor: '#000000', shadowOpacity: 0.8, shadowRadius: 3};
class AppNavigator extends Component {
constructor(props){
super(props);
}
componentDidMount() {
globalNav.navigator = this._navigator;
this.props.store.subscribe(() => {
if(this.props.store.getState().drawer.drawerState == 'opened')
this.openDrawer();
if(this.props.store.getState().drawer.drawerState == 'closed')
this._drawer.close();
});
BackAndroid.addEventListener('hardwareBackPress', () => {
var routes = this._navigator.getCurrentRoutes();
if(routes[routes.length - 1].id == 'home' || routes[routes.length - 1].id == 'login') {
return false;
}
else {
this.popRoute();
return true;
}
});
}
popRoute() {
this.props.popRoute();
}
openDrawer() {
this._drawer.open();
}
closeDrawer() {
if(this.props.store.getState().drawer.drawerState == 'opened') {
this._drawer.close();
this.props.closeDrawer();
}
}
render() {
return (
<Drawer
ref={(ref) => this._drawer = ref}
type="overlay"
content={<SideBar navigator={this._navigator} />}
tapToClose={true}
acceptPan={false}
onClose={() => this.closeDrawer()}
openDrawerOffset={0.2}
panCloseMask={0.2}
negotiatePan={true}>
<StatusBar
backgroundColor={statusBarColor}
barStyle="light-content"
/>
<Navigator
ref={(ref) => this._navigator = ref}
configureScene={(route) => {
return Navigator.SceneConfigs.FloatFromRight;
}}
initialRoute={{id: (Platform.OS === "android") ? 'splashscreen' : 'login', statusBarHidden: true}}
renderScene={this.renderScene}
/>
</Drawer>
);
}
renderScene(route, navigator) {
switch (route.id) {
case 'splashscreen':
return <SplashPage navigator={navigator} />;
case 'login':
return <Login navigator={navigator} />;
case 'home':
return <Home navigator={navigator} />;
case 'blankPage':
return <BlankPage navigator={navigator} />;
default :
return <Login navigator={navigator} />;
}
}
}
function bindAction(dispatch) {
return {
closeDrawer: () => dispatch(closeDrawer()),
popRoute: () => dispatch(popRoute())
}
}
const mapStateToProps = (state) => {
return {
drawerState: state.drawer.drawerState
}
}
export default connect(mapStateToProps, bindAction) (AppNavigator);
|
src/ButtonToolbar.js | mmartche/boilerplate-shop | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const ButtonToolbar = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'button-toolbar'
};
},
render() {
let classes = this.getBsClassSet();
return (
<div
{...this.props}
role="toolbar"
className={classNames(this.props.className, classes)}>
{this.props.children}
</div>
);
}
});
export default ButtonToolbar;
|
test/integration/app-aspath/pages/_app.js | azukaru/next.js | import React from 'react'
import App from 'next/app'
export default class MyApp extends App {
// find this
static async getInitialProps({ ctx }) {
const { query, pathname, asPath } = ctx
return { url: { query, pathname, asPath } }
}
render() {
const { Component, url } = this.props
return <Component url={url} />
}
}
|
react-router/components/About.js | JonnyCheng/flux-examples | /**
* Copyright 2014, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
import React from 'react';
class About extends React.Component {
render() {
return <p>This is a description of the site.</p>;
}
}
export default About;
|
src/svg-icons/action/reorder.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionReorder = (props) => (
<SvgIcon {...props}>
<path d="M3 15h18v-2H3v2zm0 4h18v-2H3v2zm0-8h18V9H3v2zm0-6v2h18V5H3z"/>
</SvgIcon>
);
ActionReorder = pure(ActionReorder);
ActionReorder.displayName = 'ActionReorder';
ActionReorder.muiName = 'SvgIcon';
export default ActionReorder;
|
examples/src/components/CustomOption.js | miraks/react-select | import React from 'react';
import Gravatar from 'react-gravatar';
var Option = React.createClass({
propTypes: {
addLabelText: React.PropTypes.string,
className: React.PropTypes.string,
mouseDown: React.PropTypes.func,
mouseEnter: React.PropTypes.func,
mouseLeave: React.PropTypes.func,
option: React.PropTypes.object.isRequired,
renderFunc: React.PropTypes.func
},
handleMouseDown (e) {
this.props.mouseDown(this.props.option, e);
},
handleMouseEnter (e) {
this.props.mouseEnter(this.props.option, e);
},
handleMouseLeave (e) {
this.props.mouseLeave(this.props.option, e);
},
render () {
var obj = this.props.option;
var size = 15;
var gravatarStyle = {
borderRadius: 3,
display: 'inline-block',
marginRight: 10,
position: 'relative',
top: -2,
verticalAlign: 'middle',
};
return (
<div className={this.props.className}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
onMouseDown={this.handleMouseDown}
onClick={this.handleMouseDown}>
<Gravatar email={obj.email} size={size} style={gravatarStyle} />
{obj.value}
</div>
);
}
});
module.exports = Option;
|
pages/index.js | rpowis/pusscat.lol | /**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import React, { Component } from 'react';
import Images from './../components/Images';
import Spinner from './../components/Spinner';
export default class extends Component {
constructor(props) {
super(props);
this.endpoint = 'https://raw.githubusercontent.com/rpowis/pusscat.lol/master';
this.state = {
data: null
}
}
isBirthday() {
var today = new Date();
var birthday = new Date(today.getFullYear(), 0, 22);
return birthday.setHours(0,0,0,0) === today.setHours(0,0,0,0);
}
isAnniversary() {
var today = new Date();
var anniversary = new Date(today.getFullYear(), 5, 23);
return anniversary.setHours(0,0,0,0) === today.setHours(0,0,0,0);
}
componentDidMount() {
let keyword = this.isBirthday() ? 'birthday' :
this.isAnniversary() ? 'anniversary' :
'happy';
let url = this.endpoint + '/data/' + keyword + '.json';
this.fetchData(url);
}
fetchData(url) {
(async () => {
try {
var response = await fetch(url);
var data = await response.json();
this.setData(data);
} catch (e) {
console.log("Error: ", e);
}
})();
}
setData(data) {
this.setState({data});
}
render() {
if (!this.state.data) {
return <Spinner/>;
}
let images = Object.keys(this.state.data).map(item => {
return this.state.data[item].rgi_image;
});
let message = this.isBirthday() ? <h2>HAPPY BIRTHDAY BABES!!!</h2> :
this.isAnniversary() ? <h2>HAPPY ANNIVERSARY MY LOVE!!!</h2> :
<h2>Noooooo it's you!!!</h2>
return (
<div>
{message}
<Images list={images}></Images>
</div>
);
}
}
|
src/route/account/InvestorAccountManager.js | simors/yjbAdmin | /**
* Created by lilu on 2017/10/16.
*/
import React from 'react';
import {connect} from 'react-redux';
import {Row, Col, Input, Select, Button,DatePicker, Form, message} from 'antd';
import InvestorAccountList from './InvestorAccountList';
import {stationAction, stationSelector} from '../station/redux';
import {accountAction,accountSelector} from './redux'
import {action as authAction, selector as authSelector} from '../../util/auth'
import * as excelFuncs from '../../util/excel'
import {PERMISSION_CODE,ROLE_CODE} from '../../util/rolePermission'
import moment from 'moment'
import mathjs from 'mathjs'
import {withRouter} from 'react-router'
import StationSelect from '../station/StationSelect'
import {loadAction} from '../../component/loadActivity'
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;
const ButtonGroup = Button.Group
const FormItem = Form.Item
// var Excel = require('exceljs');
class InvestorAccountManager extends React.Component {
constructor(props) {
super(props);
this.state = {
curUserId: -1,
selectedRowId: undefined,
selectedRowData: undefined,
status: undefined,
stationId: undefined,
userId: undefined,
startDate: moment().day(-30).format(),
endDate: moment().format(),
selectedType: 'all',
viewType: 'all'
}
}
selectStation(value) {
this.setState({
stationId: value
})
}
selectInvestor(value){
this.setState({
userId: value
})
}
componentWillMount() {
this.props.fetchInvestorAccounts({
...this.state,
success: ()=> {
console.log('hahhahah')
},
})
this.props.requestStations({
})
this.props.fetchAdminsByRole({roleCode:ROLE_CODE.STATION_INVESTOR})
}
refresh() {
// this.props.requestStations({...this.state})
}
search(e) {
e.preventDefault()
this.props.form.validateFields((err, fieldsValue) => {
if (err) {
return
}
const rangeTimeValue = fieldsValue['rangeTimePicker']
let values = fieldsValue
// console.log('==============value------->',values)
if(rangeTimeValue && rangeTimeValue.length === 2) {
values = {
...fieldsValue,
'rangeTimePicker': [
rangeTimeValue[0].format('YYYY-MM-DD'),
rangeTimeValue[1].format('YYYY-MM-DD'),
],
}
}
let dateRange = mathjs.chain(moment(values.rangeTimePicker[1]) - moment(values.rangeTimePicker[0])).multiply(1 / 31536000000).done()
if(dateRange>2){
message.error('时间范围请不要超过2年')
}else{
let payload = {
stationId: values.stationId,
userId: values.userId,
mobilePhoneNumber: values.mobilePhoneNumber,
startDate: values.rangeTimePicker? values.rangeTimePicker[0] : moment().day(-30).format(),
endDate: values.rangeTimePicker? values.rangeTimePicker[1] : moment().format(),
success: ()=> {
console.log('success')
},
error: ()=> {
console.log('error')
}
}
// console.log('payload========>',payload)
this.setState({viewType:values.selectedType},()=>{
if(values.selectedType=='all'){
this.props.fetchInvestorAccounts(payload)
}else{
this.props.fetchInvestorAccountsDetail(payload)
}
})
}
})
}
renderSearchBar() {
const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form
return (
<Form style={{marginTop: 12, marginBottom: 12}} layout="inline" onSubmit={(e)=>{this.search(e)}}>
<FormItem>
{getFieldDecorator("rangeTimePicker", {
initialValue: [moment().day(-30),moment()],
rules: [{ type: 'array'}],
})(
<RangePicker format="YYYY-MM-DD" />
)}
</FormItem>
<FormItem >
{getFieldDecorator("stationId", {
})(
<StationSelect placeholder='请选择服务点' disabled={false}/>
)}
</FormItem>
<FormItem>
{getFieldDecorator("mobilePhoneNumber", {
})(
<Input placeholder = '电话号码' />
)}
</FormItem>
<FormItem>
{getFieldDecorator("selectedType", {
initialValue : 'all',
})(
<Select style={{width: 120}} placeholder="选择查询方式">
<Option value='all'>按周期</Option>
<Option value='detail'>按日期</Option>
</Select>
)}
</FormItem>
<FormItem>
<Button.Group>
<Button onClick={() => {this.props.form.resetFields()}}>重置</Button>
<Button type="primary" htmlType="submit">查询</Button>
</Button.Group> </FormItem>
</Form>
)
}
downExcelFile(wb) {
this.props.form.validateFields((err, fieldsValue) => {
if (err) {
return
}
let values = fieldsValue
let dateRange = mathjs.chain(values.rangeTimePicker[1] - values.rangeTimePicker[0]).multiply(1 / 31536000000).done()
if (dateRange > 2) {
message.error('时间范围请不要超过2年')
} else {
let payload = {
limit: 1000,
stationId: values.stationId,
userId: values.userId,
startDate: values.rangeTimePicker ? values.rangeTimePicker[0].format() : moment().day(-30).format(),
endDate: values.rangeTimePicker ? values.rangeTimePicker[1].format() : moment().format(),
success: (data)=> {
let excelData = [["服务点名称", "投资人信息", "利润", "开始日期", '结束日期'],]
// let accountArray = []
if (data && data.length > 0) {
data.forEach((account)=> {
let account2Arr = [account.station ? account.station.name : '全服务点', account.user.nickname, account.profit, account.startDate, account.endDate]
excelData.push(account2Arr)
})
}
this.props.updateLoadingState({isLoading: false})
let params = {data: excelData, sheetName: '投资人日结统计数据', fileName: '投资人日结统计数据'}
excelFuncs.exportExcel(params)
},
error: ()=> {
console.log('error')
}
}
this.props.exportInvestorExcel(payload)
}
})
}
downDetailExcelFile() {
this.props.form.validateFields((err, fieldsValue) => {
if (err) {
return
}
let values = fieldsValue
let dateRange = mathjs.chain(values.rangeTimePicker[1] - values.rangeTimePicker[0]).multiply(1 / 31536000000).done()
if (dateRange > 2) {
message.error('时间范围请不要超过2年')
} else {
let payload = {
limit: 1000,
stationId: values.stationId,
userId: values.userId,
startDate: values.rangeTimePicker ? values.rangeTimePicker[0].format() : moment().day(-30).format(),
endDate: values.rangeTimePicker ? values.rangeTimePicker[1].format() : moment().format(),
success: (data)=> {
let excelData = [["服务点名称", "投资人信息", "利润", '结算日期', "开始日期", '结束日期'],]
// let accountArray = []
if (data && data.length > 0) {
console.log('data====>',data)
data.forEach((account)=> {
let account2Arr = [account.station ? account.station.name : '全服务点', account.user?account.user.nickname:'', account.profit, account.accountDay, account.startDate, account.endDate]
excelData.push(account2Arr)
})
}
this.props.updateLoadingState({isLoading: false})
let params = {data: excelData, sheetName: '投资人日结数据', fileName: '投资人日结数据'}
excelFuncs.exportExcel(params)
},
error: ()=> {
console.log('error')
}
}
this.props.exportInvestorDetailExcel(payload)
}
})
}
viewChart(){
this.props.history.push({
pathname: '/settlement_investor/investorChart',
})
}
render() {
return (
<div>
<ButtonGroup>
<Button onClick={()=> {
if (this.state.viewType == 'all') {
this.downExcelFile()
} else {
this.downDetailExcelFile()
}
}}>导出Excel</Button>
<Button onClick={()=>{this.viewChart()}}>查看图表</Button>
</ButtonGroup>
{this.renderSearchBar()}
{<InvestorAccountList
viewType = {this.state.viewType}
investorAccounts={this.state.viewType=='all'?this.props.investorAccounts:this.props.investorAccountsDetail}/>}
</div>
)
};
}
const mapStateToProps = (state, ownProps) => {
let stations = stationSelector.selectStations(state)
let accounts = accountSelector.selectInvestorAccounts(state)
let accountsDetail = accountSelector.selectInvestorAccountsDetail(state)
let userList = authSelector.selectAdminsByRole(state,ROLE_CODE.STATION_INVESTOR)
return {
investorAccounts: accounts,
stations: stations,
userList: userList,
investorAccountsDetail: accountsDetail
};
};
const mapDispatchToProps = {
...stationAction,
...accountAction,
...authAction,
...loadAction
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Form.create()(InvestorAccountManager)));
export {saga, reducer} from './redux';
|
packages/@lyra/components/src/lists/default/ListItem.js | VegaPublish/vega-studio | // @flow
import React from 'react'
import styles from '../styles/DefaultListItem.css'
import classNames from 'classnames'
export default function CoreListItem(props: any) {
return (
<li {...props} className={classNames([styles.root, props.className])} />
)
}
|
examples/query-params/app.js | arasmussen/react-router | import React from 'react'
import { createHistory, useBasename } from 'history'
import { Router, Route, Link } from 'react-router'
const history = useBasename(createHistory)({
basename: '/query-params'
})
class User extends React.Component {
render() {
let { userID } = this.props.params
let { query } = this.props.location
let age = query && query.showAge ? '33' : ''
return (
<div className="User">
<h1>User id: {userID}</h1>
{age}
</div>
)
}
}
class App extends React.Component {
render() {
return (
<div>
<ul>
<li><Link to="/user/bob" activeClassName="active">Bob</Link></li>
<li><Link to="/user/bob" query={{ showAge: true }} activeClassName="active">Bob With Query Params</Link></li>
<li><Link to="/user/sally" activeClassName="active">Sally</Link></li>
</ul>
{this.props.children}
</div>
)
}
}
React.render((
<Router history={history}>
<Route path="/" component={App}>
<Route path="user/:userID" component={User} />
</Route>
</Router>
), document.getElementById('example'))
|
src/components/Layout/Layout.js | keenethics/estimateit | import React from 'react';
import PropTypes from 'prop-types';
import normalizeCss from 'normalize.css';
import { Form, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { compose } from 'react-apollo';
import { Container, Col, Card } from 'reactstrap';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import Header from '../libs/Header';
import * as s from './Layout.scss';
import scrollToItem from '../libs/scroll';
import { ESTIMATE_FORM } from '../../constants';
class Layout extends React.Component {
static propTypes = {
children: PropTypes.node.isRequired,
handleSubmit: PropTypes.func.isRequired,
};
static handleOnKeyPress(event) {
if (event.key === 'Enter') {
event.preventDefault();
}
}
getChildContext() {
const { handleSubmit } = this.props;
return { handleSubmit };
}
render() {
return (
<div>
<Header />
<Container className={s.estimator}>
<Card id="screen">
<Col
xs="12"
md="12"
lg="10"
className={s.estimator__container}
>
<Form
form={ESTIMATE_FORM}
onKeyPress={this.handleOnKeyPress}
>
{this.props.children}
</Form>
</Col>
</Card>
</Container>
</div>
);
}
}
Layout.childContextTypes = {
handleSubmit: PropTypes.func,
};
const LayoutWrapper = reduxForm({
form: ESTIMATE_FORM,
enableReinitialize: false,
onSubmitFail: scrollToItem,
})(Layout);
const initializeValues = () => {
const initialValues = {
moneyRate: '25',
estimateOptions: {
qa: 10,
pm: 10,
risks: 10,
bugFixes: 10,
completing: 100,
},
};
return { initialValues };
};
export default compose(
connect(initializeValues),
withStyles(normalizeCss, s),
)(LayoutWrapper);
|
src/components/Mail/List.js | maloun96/react-admin | import React from 'react';
import {render} from 'react-dom';
class ListControll extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<div className="box-footer no-padding">
<div className="mailbox-controls">
<button type="button" className="btn btn-default btn-sm checkbox-toggle"><i className="fa fa-square-o"></i>
</button>
<div className="btn-group">
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-trash-o"></i></button>
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-reply"></i></button>
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-share"></i></button>
</div>
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-refresh"></i></button>
<div className="pull-right">
1-50/200
<div className="btn-group">
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-chevron-left"></i></button>
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-chevron-right"></i></button>
</div>
</div>
</div>
</div>
<div className="box-body no-padding">
<div className="table-responsive mailbox-messages">
<table className="table table-hover table-striped">
<tbody>
<tr>
<td><input type="checkbox" /></td>
<td className="mailbox-star"><a href="#"><i className="fa fa-star text-yellow"></i></a></td>
<td className="mailbox-name"><a href="read-mail.html">Alexander Pierce</a></td>
<td className="mailbox-subject"><b>AdminLTE 2.0 Issue</b> - Trying to find a solution to this problem...
</td>
<td className="mailbox-attachment"></td>
<td className="mailbox-date">5 mins ago</td>
</tr>
</tbody>
</table>
</div>
</div>
<div className="box-footer no-padding">
<div className="mailbox-controls">
<button type="button" className="btn btn-default btn-sm checkbox-toggle"><i className="fa fa-square-o"></i>
</button>
<div className="btn-group">
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-trash-o"></i></button>
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-reply"></i></button>
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-share"></i></button>
</div>
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-refresh"></i></button>
<div className="pull-right">
1-50/200
<div className="btn-group">
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-chevron-left"></i></button>
<button type="button" className="btn btn-default btn-sm"><i className="fa fa-chevron-right"></i></button>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default ListControll;
|
src/containers/App.js | gaearon/redux-friendlist-demo | import React, { Component } from 'react';
import { combineReducers } from 'redux';
import { Provider } from 'react-redux';
import { createStore, renderDevTools } from '../store_enhancers/devTools';
import AppView from './AppView.js';
import reducer from '../reducers';
const store = createStore(reducer);
export default class App extends Component {
render() {
return (
<div>
<Provider store={store}>
{() => <AppView /> }
</Provider>
{renderDevTools(store)}
</div>
);
}
}
|
examples/with-react-multi-carousel/pages/index.js | BlancheXu/test | import React from 'react'
import MobileDetect from 'mobile-detect'
import { withStyles } from '@material-ui/core/styles'
import Carousel from 'react-multi-carousel'
import Image from '../components/image'
import '../style.css'
import 'react-multi-carousel/lib/styles.css'
const styles = theme => ({
root: {
textAlign: 'center'
},
title: {
maxWidth: 400,
margin: 'auto',
marginTop: 10
}
})
class Index extends React.Component {
static getInitialProps ({ req, isServer }) {
let userAgent
let deviceType
if (req) {
userAgent = req.headers['user-agent']
} else {
userAgent = navigator.userAgent
}
const md = new MobileDetect(userAgent)
if (md.tablet()) {
deviceType = 'tablet'
} else if (md.mobile()) {
deviceType = 'mobile'
} else {
deviceType = 'desktop'
}
return { deviceType }
}
render () {
const { classes } = this.props
const images = [
'https://images.unsplash.com/photo-1549989476-69a92fa57c36?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60',
'https://images.unsplash.com/photo-1549396535-c11d5c55b9df?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60',
'https://images.unsplash.com/photo-1550133730-695473e544be?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60',
'https://images.unsplash.com/photo-1550167164-1b67c2be3973?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60',
'https://images.unsplash.com/photo-1550338861-b7cfeaf8ffd8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60',
'https://images.unsplash.com/photo-1550223640-23097fc71cb2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60',
'https://images.unsplash.com/photo-1550353175-a3611868086b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60',
'https://images.unsplash.com/photo-1550330039-a54e15ed9d33?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60',
'https://images.unsplash.com/photo-1549737328-8b9f3252b927?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60',
'https://images.unsplash.com/photo-1549833284-6a7df91c1f65?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60',
'https://images.unsplash.com/photo-1549985908-597a09ef0a7c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60',
'https://images.unsplash.com/photo-1550064824-8f993041ffd3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60'
]
const responsive = {
desktop: {
breakpoint: { max: 3000, min: 1024 },
items: 3
},
tablet: {
breakpoint: { max: 1024, min: 464 },
items: 2
},
mobile: {
breakpoint: { max: 464, min: 0 },
items: 1
}
}
return (
<div className={classes.root}>
<Carousel
responsive={responsive}
ssr
showDots={false}
slidesToSlide={1}
infinite
containerClass='container-with-dots'
itemClass='image-item'
deviceType={this.props.deviceType}
>
{images.map(image => {
return <Image url={image} alt={image} />
})}
</Carousel>
</div>
)
}
}
export default withStyles(styles)(Index)
|
app/javascript/mastodon/components/avatar.js | rekif/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { autoPlayGif } from '../initial_state';
export default class Avatar extends React.PureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
size: PropTypes.number.isRequired,
style: PropTypes.object,
inline: PropTypes.bool,
animate: PropTypes.bool,
};
static defaultProps = {
animate: autoPlayGif,
size: 20,
inline: false,
};
state = {
hovering: false,
};
handleMouseEnter = () => {
if (this.props.animate) return;
this.setState({ hovering: true });
}
handleMouseLeave = () => {
if (this.props.animate) return;
this.setState({ hovering: false });
}
render () {
const { account, size, animate, inline } = this.props;
const { hovering } = this.state;
const src = account.get('avatar');
const staticSrc = account.get('avatar_static');
let className = 'account__avatar';
if (inline) {
className = className + ' account__avatar-inline';
}
const style = {
...this.props.style,
width: `${size}px`,
height: `${size}px`,
backgroundSize: `${size}px ${size}px`,
};
if (hovering || animate) {
style.backgroundImage = `url(${src})`;
} else {
style.backgroundImage = `url(${staticSrc})`;
}
return (
<div
className={className}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
style={style}
/>
);
}
}
|
client/acp/src/view/display/prompt-view.js | NicolasSiver/nodebb-plugin-ns-awards | import PropTypes from 'prop-types';
import React from 'react';
// FIXME Replace with Panel Controls
export default class PromptView extends React.Component {
render() {
return (
<div className="media">
<div className="media-body">
<p>{this.props.hint}</p>
<button
className="btn btn-primary"
onClick={this.props.labelDidClick}
type="button">{this.props.label}
</button>
</div>
</div>
);
}
}
PromptView.propTypes = {
hint : PropTypes.string,
label : PropTypes.string.isRequired,
labelDidClick: PropTypes.func.isRequired
};
|
src/containers/Asians/BreaksCalculator/MatchUps/RoundInstance/returnTableRow.js | westoncolemanl/tabbr-web | import React from 'react'
import {
TableRow,
TableCell
} from 'material-ui/Table'
export default (
roundIndex,
roundMatchUps,
minBreak,
sureBreak,
numberOfRounds
) => {
let arr = []
let currentScore = 0
let bracketRank = 0
roundMatchUps.forEach((room, index) => {
bracketRank++
let team1style = ''
let team2style = ''
const roomAverage = Math.round((room[0].score + room[1].score) / 2)
if (currentScore !== roomAverage) {
currentScore = roomAverage
bracketRank = 1
}
const pullUp = room[0].score !== room[1].score
const roomBG = roomAverage % 2 !== 0
? 'bg-light-gray'
: 'bg-white'
const roomStyle = pullUp
? 'bg-lightest-blue'
: roomBG
const roundsRemaining = numberOfRounds - roundIndex + 1
if (room[0].score + roundsRemaining < minBreak) {
team1style = 'red i'
}
if (room[0].score >= sureBreak) {
team1style = 'green b'
}
if (room[1].score + roundsRemaining < minBreak) {
team2style = 'red i'
}
if (room[1].score >= sureBreak) {
team2style = 'green b'
}
const name = (team) => `Rank ${team.rank} - (${team.score})`
arr.push(
<TableRow
key={index}
className={roomStyle}
>
<TableCell
className={'w-10'}
children={index + 1}
/>
<TableCell
className={'w-10'}
children={`${bracketRank}`}
/>
<TableCell
className={'w-10'}
children={`${roomAverage}`}
/>
<TableCell
className={'w-10'}
children={pullUp ? 'Pull up' : ''}
/>
<TableCell
className={team1style}
children={name(room[0])}
style={{
textAlign: 'center'
}}
/>
<TableCell
className={'w-10'}
children={'vs'}
style={{
textAlign: 'center'
}}
/>
<TableCell
className={team2style}
children={name(room[1])}
style={{
textAlign: 'center'
}}
/>
</TableRow>
)
})
return arr
}
|
src/docs/ComponentPage.js | rajeshpillai/zs-react-pattern-lib | import React from 'react';
import PropTypes from 'prop-types';
import Example from './Example';
import Props from './Props';
const ComponentPage = ({component}) => {
const {name, description, props, examples} = component;
return (
<div className="componentpage">
<h2>{name}</h2>
<p>{description}</p>
<h3>Example{examples.length > 1 && "s"}</h3>
{
examples.length > 0 ?
examples.map( example => <Example key={example.code} example={example} componentName={name} /> ) :
"No examples exist."
}
<h3>Props</h3>
{
props ?
<Props props={props} /> :
"This component accepts no props."
}
</div>
)
};
ComponentPage.propTypes = {
component: PropTypes.object.isRequired
};
export default ComponentPage;
|
src/components/common/svg-icons/image/brush.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBrush = (props) => (
<SvgIcon {...props}>
<path d="M7 14c-1.66 0-3 1.34-3 3 0 1.31-1.16 2-2 2 .92 1.22 2.49 2 4 2 2.21 0 4-1.79 4-4 0-1.66-1.34-3-3-3zm13.71-9.37l-1.34-1.34c-.39-.39-1.02-.39-1.41 0L9 12.25 11.75 15l8.96-8.96c.39-.39.39-1.02 0-1.41z"/>
</SvgIcon>
);
ImageBrush = pure(ImageBrush);
ImageBrush.displayName = 'ImageBrush';
ImageBrush.muiName = 'SvgIcon';
export default ImageBrush;
|
src/FormGroup.js | justinanastos/react-bootstrap | import React from 'react';
import classNames from 'classnames';
class FormGroup extends React.Component {
render() {
let classes = {
'form-group': !this.props.standalone,
'form-group-lg': !this.props.standalone && this.props.bsSize === 'large',
'form-group-sm': !this.props.standalone && this.props.bsSize === 'small',
'has-feedback': this.props.hasFeedback,
'has-success': this.props.bsStyle === 'success',
'has-warning': this.props.bsStyle === 'warning',
'has-error': this.props.bsStyle === 'error'
};
return (
<div className={classNames(classes, this.props.groupClassName)}>
{this.props.children}
</div>
);
}
}
FormGroup.defaultProps = {
hasFeedback: false,
standalone: false
};
FormGroup.propTypes = {
standalone: React.PropTypes.bool,
hasFeedback: React.PropTypes.bool,
bsSize (props) {
if (props.standalone && props.bsSize !== undefined) {
return new Error('bsSize will not be used when `standalone` is set.');
}
return React.PropTypes.oneOf(['small', 'medium', 'large'])
.apply(null, arguments);
},
bsStyle: React.PropTypes.oneOf(['success', 'warning', 'error']),
groupClassName: React.PropTypes.string
};
export default FormGroup;
|
modules/gui/src/app/landing/slideshow/slideshow.js | openforis/sepal | import React from 'react'
import background1 from './background1.jpg'
import background2 from './background2.jpg'
import styles from './slideshow.module.css'
const Slideshow = () =>
<div className={styles.slideshow}>
<img src={background1} className={styles.image1} alt=''/>
<img src={background2} className={styles.image2} alt=''/>
<div className={styles.overlay}/>
</div>
export default Slideshow
|
frontend/components/app-view.js | meandavejustice/min-vid | import React from 'react';
import cn from 'classnames';
import PlayerView from './player-view';
import LoadingView from './loading-view';
import ConfirmView from './confirm-view';
export default class AppView extends React.Component {
render() {
// if (this.props.confirm) window.AppData.set({minimized: false});
const confirmView = this.props.confirm ? (<ConfirmView {...this.props}/>) : null;
const hideLoadingView = (this.props.queue.length && this.props.queue[0].error);
return (
<div className='app'>
{confirmView}
{(!this.props.loaded && !hideLoadingView) ? <LoadingView {...this.props} /> : null}
<div className={cn('player-wrap', {hidden: !this.props.loaded && !hideLoadingView})}>
{this.props.queue.length ? (<PlayerView {...this.props} />) : null}
</div>
</div>
);
}
}
|
src/components/ProductList/index.js | Rhymond/product-compare-react | import React from 'react'
import {Product} from '../'
const ProductList = ({products, compare}) =>
<div className="row mt-3">
{products.map(product =>
<Product key={product.id} product={product} compare={compare} />
)}
</div>;
export default ProductList
|
src/components/Header/Header.js | jwarshaw/redux-dashboard-app | import React from 'react'
import { IndexLink, Link } from 'react-router'
import './Header.scss'
export const Header = () => (
<div>
<h1>React Redux Starter Kit</h1>
<IndexLink to='/' activeClassName='route--active'>
Home
</IndexLink>
{' · '}
<Link to='/counter' activeClassName='route--active'>
Counter
</Link>
{' · '}
<Link to='/dashboard' activeClassName='route--active'>
Dashboard
</Link>
</div>
)
export default Header
|
src/core/components/Autocomplete.js | remy/jsconsole | import React, { Component } from 'react';
class Autocomplete extends Component {
render() {
return (
<div className="Autocomplete">
<span className="matching">doc</span>
<span className="preview">ument</span>
</div>
);
}
}
export default Autocomplete;
|
src/routes/contact/index.js | murthymuddu/murthy-umg | /**
* 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';
import Contact from './Contact';
const title = 'Contact Us';
function action() {
return {
chunks: ['contact'],
title,
component: (
<Layout>
<Contact title={title} />
</Layout>
),
};
}
export default action;
|
website/sections/JsLibrary.js | sahat/megaboilerplate | import React from 'react';
import cx from 'classnames';
import { VelocityComponent, VelocityTransitionGroup } from 'velocity-react';
const JS_LIBRARY_SVG = (
<svg xmlns="http://www.w3.org/2000/svg" width="16px" height="16px" viewBox="0 0 50 50">
<path d="M 29.125 7.34375 L 17.125 41.34375 L 20.875 42.65625 L 32.875 8.65625 L 29.125 7.34375 z M 9.9375 13.375 L 1.25 23.71875 L 0.1875 25 L 1.25 26.28125 L 9.9375 36.65625 L 13.03125 34.09375 L 5.40625 25 L 13 15.9375 L 9.9375 13.375 z M 40.0625 13.375 L 37 15.9375 L 44.59375 25 L 37 34.0625 L 40.09375 36.625 L 48.71875 26.28125 L 49.78125 25 L 48.71875 23.71875 L 40.0625 13.375 z" overflow="visible"></path>
</svg>
);
class JsLibrary extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.onGenerateClick = this.onGenerateClick.bind(this);
}
componentDidMount() {
// Set default license type to "MIT"
this.props.handleChange({
target: {
name: 'jsLibraryLicenseRadios',
value: 'mit',
checked: true
}
})
}
onGenerateClick(event) {
this.props.handleGenerateLibraryName(event.target.value);
this.refs.jsLibraryName.focus();
}
render() {
const props = this.props;
let description;
switch (props.framework) {
case 'express':
description = (
<div>
<strong><a href="http://expressjs.com/" target="_blank">Express</a></strong> — A minimal and flexible web
application framework, providing a robust set of features for building web applications. It is the de facto
standard framework for Node.js.
</div>
);
break;
case 'meteor':
description = (
<div>
<strong><a href="https://www.meteor.com/" target="_blank">Meteor</a></strong> — A complete platform for
building web and mobile apps in pure JavaScript.
</div>
);
break;
default:
description = <div className="placeholder"></div>;
}
const validationError = props.jsLibraryValidationError ? (
<div className="help-block text-danger"><i className="fa fa-warning"></i> {props.jsLibraryValidationError}</div>
) : null;
if (props.jsLibraryValidationError) {
if (props.disableAutoScroll) {
$(this.refs.jsLibrary).velocity('scroll', { duration: 0 });
} else {
$(this.refs.jsLibrary).velocity('scroll');
}
}
return (
<div ref="jsLibrary" className='zoomInBackwards panel authentication'>
<div className="panel-heading">
<h6>{JS_LIBRARY_SVG}{props.library || 'JS Library Options'}</h6>
</div>
<div className="panel-body">
<div className="row">
<div className="col-sm-7">
<div className="form-group">
<label htmlFor="jsLibraryName" className="">Library Name <span className="text-danger">*</span></label>
<div className="input-group">
<input ref="jsLibraryName" type="text" id="jsLibraryName" name="jsLibraryName" className="form-control" value={props.jsLibraryName} onChange={props.handleChange} autoFocus/>
<span className="input-group-btn">
<button className="btn btn-primary" type="button" onClick={this.onGenerateClick} tabIndex="-1">Generate</button>
</span>
</div>
{validationError}
</div>
<strong>Additional Features</strong>
<div className="checkbox">
<label>
<input type="checkbox" name="jsLibraryOptionsCheckboxes" value="eslint" onChange={props.handleChange}/>
<span>ESLint</span>
</label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" name="jsLibraryOptionsCheckboxes" value="travis" onChange={props.handleChange}/>
<span>Travis CI</span>
</label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" name="jsLibraryOptionsCheckboxes" value="coverage" onChange={props.handleChange}/>
<span>Code Coverage</span>
</label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" name="jsLibraryOptionsCheckboxes" value="badges" onChange={props.handleChange}/>
<span>Shields.io Badges</span>
</label>
</div>
</div>
<div className="col-sm-5">
<div className="row">
<div className="col-sm-12 form-group ">
<label htmlFor="jsLibraryAuthor" className="">Author Name</label>
<span className="help hint--top hint--rounded" data-hint="Your full name is used in the license and package.json files." ><i className="fa fa-question-circle"></i></span>
<input type="text" id="jsLibraryAuthor" name="jsLibraryAuthor" className="form-control"
placeholder="Optional" value={props.jsLibraryAuthor} onChange={props.handleChange}/>
</div>
</div>
<div className="row">
<div className="col-sm-12">
<label htmlFor="jsLibraryGithubUsername" className="">GitHub Username</label>
<span className="help hint--top hint--rounded" data-hint="Your username is used for the GitHub project path." ><i className="fa fa-question-circle"></i></span>
<input type="text" id="jsLibraryGithubUsername" name="jsLibraryGithubUsername" className="form-control"
placeholder="Optional" value={props.jsLibraryGithubUsername} onChange={props.handleChange}/>
</div>
</div>
</div>
</div>
<br/>
<strong>License</strong>
<div className="radio-group">
<label className="radio-inline">
<input type="radio" name="jsLibraryLicenseRadios" value="none" onChange={props.handleChange} checked={props.jsLibraryLicense === 'none'}/>
<span>None</span>
</label>
<label className="radio-inline">
<input type="radio" name="jsLibraryLicenseRadios" value="mit" onChange={props.handleChange} checked={props.jsLibraryLicense === 'mit'}/>
<span>MIT</span>
</label>
<label className="radio-inline">
<input type="radio" name="jsLibraryLicenseRadios" value="apache" onChange={props.handleChange} checked={props.jsLibraryLicense === 'apache'}/>
<span>Apache License 2.0</span>
</label>
<label className="radio-inline">
<input type="radio" name="jsLibraryLicenseRadios" value="gplv3" onChange={props.handleChange} checked={props.jsLibraryLicense === 'gplv3'}/>
<span>GNU GPLv3</span>
</label>
</div>
</div>
</div>
);
}
}
export default JsLibrary;
|
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-bootstrap/0.31.0/es/Breadcrumb.js | Akkuma/npm-cache-benchmark | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import BreadcrumbItem from './BreadcrumbItem';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var Breadcrumb = function (_React$Component) {
_inherits(Breadcrumb, _React$Component);
function Breadcrumb() {
_classCallCheck(this, Breadcrumb);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Breadcrumb.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement('ol', _extends({}, elementProps, {
role: 'navigation',
'aria-label': 'breadcrumbs',
className: classNames(className, classes)
}));
};
return Breadcrumb;
}(React.Component);
Breadcrumb.Item = BreadcrumbItem;
export default bsClass('breadcrumb', Breadcrumb); |
src/components/DataTable/AnimTableBody.js | muidea/magicSite | import React from 'react'
import PropTypes from 'prop-types'
import { TweenOneGroup } from 'rc-tween-one'
const enterAnim = [
{
opacity: 0,
x: 30,
backgroundColor: '#fffeee',
duration: 0,
}, {
height: 0,
duration: 200,
type: 'from',
delay: 250,
ease: 'easeOutQuad',
onComplete: (e) => {
e.target.style.height = 'auto'
},
}, {
opacity: 1,
x: 0,
duration: 250,
ease: 'easeOutQuad',
}, {
delay: 1000,
backgroundColor: '#fff',
},
]
const leaveAnim = [
{
duration: 250,
x: -30,
opacity: 0,
}, {
height: 0,
duration: 200,
ease: 'easeOutQuad',
},
]
const AnimTableBody = ({ body, page = 1, current }) => {
if (current !== +page) {
return body
}
return (
<TweenOneGroup
component="tbody"
className={body.props.className}
enter={enterAnim}
leave={leaveAnim}
appear={false}
>
{body.props.children}
</TweenOneGroup>
)
}
AnimTableBody.propTypes = {
body: PropTypes.element,
page: PropTypes.any,
current: PropTypes.number.isRequired,
}
export default AnimTableBody
|
q-a11y-training-demo/src/components/react-router-aria-live/LiveRouterAnnouncer.js | AlmeroSteyn/Q-A11y-Training | import React from 'react';
import PoliteAnnouncer from '../react-aria-live/PoliteAnnouncer';
import LiveRouterHOC from './LiveRouterHOC';
const LiveRouterAnnouncer = ({ message }) =>
<PoliteAnnouncer message={message} />;
export default LiveRouterHOC(LiveRouterAnnouncer);
|
src/views/components/task-list/task-list.js | Metaburn/doocrate | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { List } from 'immutable';
import PropTypes from 'prop-types';
import TaskItem from '../task-item-row/task-item-row';
import InfiniteScroll from 'react-infinite-scroller';
import i18n from '../../../i18n';
import CompleteFilter from '../complete-filter';
import './task-list.css';
import EmptyPlaceholder from '../../molecules/emptyPlaceholder/emptyPlaceholder';
class TaskList extends Component {
constructor(props) {
super(props);
this.state = {
pageSize: 20,
pageNumber: 0,
};
this.loadMore = this.loadMore.bind(this);
}
loadMore(pageNumber) {
this.setState({ pageNumber });
}
clearSearchQuery = () => {
this.props.history.push({ search: '' });
};
render() {
const {
tasks,
selectedTaskId,
selectedProject,
labels,
projectUrl,
} = this.props;
const { pageSize, pageNumber } = this.state;
const isAnyTasks = tasks && tasks.size > 0;
let taskItems = [];
const search = this.props.location ? this.props.location.search : '';
if (isAnyTasks) {
taskItems = tasks
.slice(0, pageSize * (pageNumber + 1))
.map((task, index) => {
const taskId = task.get('id');
const isActive = taskId === selectedTaskId;
const taskRoute = `/${projectUrl}/task/${taskId}${search}`;
return (
<Link to={taskRoute} key={index}>
<TaskItem
taskNumber={index}
task={task}
selectedProject={selectedProject}
labels={labels}
isActive={isActive}
/>
</Link>
);
});
}
const hasMoreTasks = tasks ? pageSize * pageNumber < tasks.size : true;
return (
<div className="task-list-container">
<div className="task-list-header" name="task-list-header">
<CompleteFilter projectUrl={projectUrl} />
</div>
<div className="task-list">
{!isAnyTasks && (
<EmptyPlaceholder onClearFilters={this.clearSearchQuery} />
)}
<InfiniteScroll
pageStart={0}
loadMore={this.loadMore}
hasMore={hasMoreTasks}
useWindow={true}
loader={<div className="loader">{i18n.t('general.loading')}</div>}
>
{taskItems}
</InfiniteScroll>
</div>
</div>
);
}
}
TaskList.propTypes = {
tasks: PropTypes.instanceOf(List).isRequired,
selectedTaskId: PropTypes.string,
selectedProject: PropTypes.object,
history: PropTypes.object,
location: PropTypes.object,
projectUrl: PropTypes.string.isRequired,
};
export default TaskList;
|
src/components/discover/exam-detail/view/ExamDetailContent.js | phodal/growth-ng | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, Text, PanResponder } from 'react-native';
import Indicator from './ExamDetailIndicator';
import AppStyle from '../../../../theme/styles';
let startX;
let endX;
let pressPosition;
let leftslide;
let diff;
class ExamDetailContent extends Component {
static componentName = 'ExamDetailContent';
static propTypes = {
quizs: PropTypes.arrayOf(
PropTypes.string,
),
onIndexChangeListener: PropTypes.func,
test: PropTypes.bool,
};
static defaultProps = {
quizs: [],
onIndexChangeListener: () => {},
test: false,
};
constructor(props) {
super(props);
this.state = {
randomIndex: this.props.test
? 0
: Math.floor(Math.random() * (this.props.quizs.length - 9)),
text: this.props.quizs[
this.props.test
? 0
: Math.floor(Math.random() * (this.props.quizs.length - 9))],
index: 0,
};
}
componentWillMount() {
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onStartShouldSetPanResponderCapture: () => true,
onMoveShouldSetPanResponder: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderMove: () => true,
onPanResponderStart: (e, gestureState) => {
startX = gestureState.moveX;
pressPosition = gestureState.x0;
return true;
},
onPanResponderEnd: (e, gestureState) => {
endX = gestureState.moveX;
this.change();
return true;
},
});
}
change() {
const movePx = 0;
const minCount = 0;
const maxCount = 8;
const minSlideValue = 30;
if (endX === movePx) return;
leftslide = (pressPosition - endX) > movePx;
diff = endX - startX;
if (!leftslide) {
diff = -diff;
}
if (diff > minSlideValue && this.state.index < maxCount) {
this.state.index += 1;
} else if (diff < -minSlideValue && this.state.index > minCount) {
this.state.index -= 1;
}
this.setState({
text: this.props.quizs[this.state.randomIndex + this.state.index],
});
this.props.onIndexChangeListener(this.state.index);
}
render() {
return (
<View
{...this.panResponder.panHandlers}
style={{ flex: 1, backgroundColor: 'rgba(0,0,0,0)' }}
>
<View
style={AppStyle.examDetailContentStyle}
>
<Text>{this.state.text}</Text>
</View>
<Indicator index={this.state.index} />
</View>
);
}
}
export default ExamDetailContent;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.