path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
components/date_picker_all/Calendar.js | zooshgroup/react-toolbox-components | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import CssTransitionGroup from 'react-transition-group/CSSTransitionGroup';
import { range, getAnimationModule } from '../utils/utils';
import time from '../utils/time';
import CalendarMonth from './CalendarMonth';
const DIRECTION_STEPS = { left: -1, right: 1 };
const factory = (IconButton) => {
class Calendar extends Component {
static propTypes = {
disabledDates: PropTypes.arrayOf(PropTypes.instanceOf(Date)),
display: PropTypes.oneOf(['months', 'years']),
enabledDates: PropTypes.arrayOf(PropTypes.instanceOf(Date)),
handleSelect: PropTypes.func,
locale: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
]),
maxDate: PropTypes.instanceOf(Date),
minDate: PropTypes.instanceOf(Date),
onChange: PropTypes.func,
selectedDate: PropTypes.instanceOf(Date),
sundayFirstDayOfWeek: PropTypes.bool,
theme: PropTypes.shape({
active: PropTypes.string,
calendar: PropTypes.string,
next: PropTypes.string,
prev: PropTypes.string,
years: PropTypes.string,
}),
};
static defaultProps = {
display: 'months',
selectedDate: new Date(),
};
state = {
viewDate: this.props.selectedDate,
};
componentWillMount() {
document.body.addEventListener('keydown', this.handleKeys);
}
componentDidUpdate() {
if (this.activeYearNode) {
this.scrollToActive();
}
}
componentWillUnmount() {
document.body.removeEventListener('keydown', this.handleKeys);
}
scrollToActive() {
const offset = (this.yearsNode.offsetHeight / 2) + (this.activeYearNode.offsetHeight / 2);
this.yearsNode.scrollTop = this.activeYearNode.offsetTop - offset;
}
handleDayClick = (day) => {
this.props.onChange(time.setDay(this.state.viewDate, day), true);
};
handleYearClick = (event) => {
const year = parseInt(event.currentTarget.id, 10);
const viewDate = time.setYear(this.props.selectedDate, year);
this.setState({ viewDate });
this.props.onChange(viewDate, false);
};
handleKeys = (e) => {
const { selectedDate } = this.props;
if (e.which === 37 || e.which === 38 || e.which === 39 || e.which === 40 || e.which === 13) {
e.preventDefault();
}
switch (e.which) {
case 13: this.props.handleSelect(); break; // enter
case 37: this.handleDayArrowKey(time.addDays(selectedDate, -1)); break; // left
case 38: this.handleDayArrowKey(time.addDays(selectedDate, -7)); break; // up
case 39: this.handleDayArrowKey(time.addDays(selectedDate, 1)); break; // right
case 40: this.handleDayArrowKey(time.addDays(selectedDate, 7)); break; // down
default: break;
}
}
handleDayArrowKey = (date) => {
this.setState({ viewDate: date });
this.props.onChange(date, false);
}
changeViewMonth = (event) => {
const direction = event.currentTarget.id;
this.setState({
direction,
viewDate: time.addMonths(this.state.viewDate, DIRECTION_STEPS[direction]),
});
};
renderYears() {
return (
<ul
data-react-toolbox="years"
className={this.props.theme.years}
ref={(node) => { this.yearsNode = node; }}
>
{range(1900, 2100).map(year => (
<li
className={year === this.state.viewDate.getFullYear() ? this.props.theme.active : ''}
id={year}
key={year}
onClick={this.handleYearClick}
ref={(node) => {
if (year === this.state.viewDate.getFullYear()) {
this.activeYearNode = node;
}
}}
>
{year}
</li>
))}
</ul>
);
}
renderMonths() {
const { theme } = this.props;
const animation = this.state.direction === 'left' ? 'slideLeft' : 'slideRight';
const animationModule = getAnimationModule(animation, theme);
return (
<div data-react-toolbox="calendar">
<IconButton id="left" className={theme.prev} icon="chevron_left" onClick={this.changeViewMonth} />
<IconButton id="right" className={theme.next} icon="chevron_right" onClick={this.changeViewMonth} />
<CssTransitionGroup
transitionName={animationModule}
transitionEnterTimeout={350}
transitionLeaveTimeout={350}
>
<CalendarMonth
enabledDates={this.props.enabledDates}
disabledDates={this.props.disabledDates}
key={this.state.viewDate.getMonth()}
locale={this.props.locale}
maxDate={this.props.maxDate}
minDate={this.props.minDate}
onDayClick={this.handleDayClick}
selectedDate={this.props.selectedDate}
sundayFirstDayOfWeek={this.props.sundayFirstDayOfWeek}
theme={this.props.theme}
viewDate={this.state.viewDate}
/>
</CssTransitionGroup>
</div>
);
}
render() {
return (
<div className={this.props.theme.calendar}>
{this.props.display === 'months' ? this.renderMonths() : this.renderYears()}
</div>
);
}
}
return Calendar;
};
export default factory;
|
loc8-react-redux-front-end/src/components/Home/index.js | uberslackin/django-redux-loc8-ARweb | import Banner from './Banner';
import MainView from './MainView';
import React from 'react';
import Tags from './Tags';
import agent from '../../agent';
import { connect } from 'react-redux';
const Promise = global.Promise;
const mapStateToProps = state => ({
...state.home,
appName: state.common.appName,
token: state.common.token
});
const mapDispatchToProps = dispatch => ({
onClickTag: (tag, payload) =>
dispatch({ type: 'APPLY_TAG_FILTER', tag, payload }),
onLoad: (tab, payload) =>
dispatch({ type: 'HOME_PAGE_LOADED', tab, payload }),
onUnload: () =>
dispatch({ type: 'HOME_PAGE_UNLOADED' })
});
class Home extends React.Component {
componentWillMount() {
const tab = this.props.token ? 'feed' : 'all';
const articlesPromise = this.props.token ?
agent.Articles.feed() :
agent.Articles.all();
this.props.onLoad(tab, Promise.all([agent.Tags.getAll(), articlesPromise]));
}
componentWillUnmount() {
this.props.onUnload();
}
render() {
return (
<div className="home-page">
<Banner token={this.props.token} appName={this.props.appName} />
<div className="container page">
<div className="row">
<MainView />
<div className="col-md-3">
<div className="sidebar">
<p>Popular Tags</p>
<Tags
tags={this.props.tags}
onClickTag={this.props.onClickTag} />
</div>
</div>
</div>
</div>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);
|
src/components/LifeCycleDemo.js | GuoYongfeng/react-fundamental | import React, { Component } from 'react';
import LifeCycle from './LifeCycle';
class LifeCycleDemo extends Component {
state = {
value:1,
destroyed:false
}
increase = () => {
this.setState({
value: this.state.value + 1
});
}
destroy = () => {
this.setState({
destroyed: true
});
}
render() {
if(this.state.destroyed){
return null;
}
return <div>
<p>
<button onClick={this.increase}>每次加1,更新组件</button>
<button onClick={this.destroy}>干掉这两个按钮,销毁</button>
</p>
<LifeCycle value={this.state.value}/>
</div>;
}
}
export default LifeCycleDemo;
|
sub-packs/themes/zealder-default-theme/src/components/Header.js | Zealder/zealder-cms | // @flow
/* this is so similar to ContentWrapper we may have to merge together in the
future */
import React from 'react';
import { Grid } from 'react-bootstrap';
export default class Header extends React.Component {
render() {
const { content, getComponent, contentFillsWindow } = this.props;
const scContent = content.scContent;
// determine our background
let Background = getComponent('Background', '');
let MainNav;
if (!scContent.noNav) MainNav = getComponent('MainNav', '');
// determin style
let style = {}, height = '';
if (scContent.height && !contentFillsWindow) {
if (scContent.background && scContent.background.parallax) {
/* we must use a fixed height for parallax (fixed) background because
it will not "grow" with content as other parallax does */
style.height = scContent.height;
}
else style.minHeight = scContent.height;
height = scContent.height;
}
// determine title
let title;
if (!scContent.noTitle) {
if (content.scTitle) title = content.scTitle;
else {
// TODO: use page title. If none, use page name
}
}
// get children
let children = [];
if (scContent && scContent.children) {
children = scContent.children.map((item, index) => {
let NodeComponent = getComponent(item.scType, '');
return (
<NodeComponent key={`head-item-${index}`} content={item}
getComponent={getComponent} />
);
});
}
return (
<div className="header" style={style}>
{scContent && scContent.background
&& <Background background={scContent.background} height={height} isHeader />}
{MainNav &&
<MainNav getComponent={getComponent} />
}
<Grid fluid={scContent.isFluid} className={scContent.className}>
{title &&
<div className="header-title">
<h1>{title}</h1>
{scContent.subTitle && <div>{scContent.subTitle}</div>}
</div>
}
{!title &&
<div className="no-header-title"></div>
}
{children}
</Grid>
</div>
);
}
}
|
src/App.js | emilng/l-system-explorer | import React, { Component } from 'react';
import './App.css';
import Examples from './ui/Examples';
import Start from './ui/Start';
import Iterations from './ui/Iterations';
import Axiom from './ui/Axiom';
import InstructionsContainer from './ui/InstructionsContainer';
import RulesContainer from './ui/RulesContainer';
import CanvasUI from './ui/Canvas';
import * as encodeHash from './encoders/hash';
import * as rewrite from './rewrite';
import render from './render';
class App extends Component {
static updateStep = {
DECODE: 0,
REWRITE: 1,
RENDER: 2,
}
constructor(props) {
super(props);
const canvas = document.getElementById('canvas');
const data = this.decodeData();
this.state = { canvas,
start: data.start,
iterations: data.iterations,
axiom: data.axiom,
rules: data.rules,
rewrittenRules: '',
instructions: data.instructions,
};
this.canvasUI = new CanvasUI(canvas, data.start, this.updateStartData.bind(this));
this.update = this.update.bind(this);
this.updateStart = this.update.bind(this, App.updateStep.RENDER, 'start');
this.updateIterationData = this.updateIterationData.bind(this);
this.updateAxiom = this.update.bind(this, App.updateStep.REWRITE, 'axiom');
this.updateRules = this.update.bind(this, App.updateStep.REWRITE, 'rules');
this.updateInstructions = this.update.bind(this, App.updateStep.RENDER, 'instructions');
this.updateExample = this.update.bind(this, App.updateStep.DECODE);
this.decodeData = this.decodeData.bind(this);
this.rewriteData = this.rewriteData.bind(this);
this.renderData = this.renderData.bind(this);
this.updateMethods = [this.decodeData, this.rewriteData, this.renderData];
}
componentDidMount() {
this.update(App.updateStep.DECODE);
}
decodeData() {
let hash = window.location.hash.substr(1);
// hardcoded default for now if nothing is set
if (hash === '') {
hash = 'F/F:F+F-F-F+F/F,d3.5;+,a75;-,a-80/6/x347,y358,a70,i6,z100';
}
return encodeHash.decode(hash);
}
rewriteData(data) {
data.rewrittenRules = rewrite.write(data.rules, data.axiom, data.iterations);
return data;
}
renderData(data) {
render(this.state.canvas, data.start, data.rewrittenRules, data.instructions);
const urlHash = encodeHash.encode(data);
const stateObj = { data: urlHash };
window.history.replaceState(stateObj, 'L-Systems', `index.html${urlHash}`);
return data;
}
updateStartData(data) {
const updatedStartData = this.state;
updatedStartData.start = data;
this.renderData(updatedStartData);
this.setState({ start: data });
}
updateIterationData(iterations) {
const data = this.rewriteData({ ...this.state, iterations });
this.setState(this.renderData(data));
}
update(step, propName, propValue) {
let currentStep = step;
let newState = this.state;
if (propName) {
newState[propName] = propValue;
}
while (currentStep < this.updateMethods.length) {
newState = this.updateMethods[currentStep](newState);
currentStep++;
}
this.canvasUI.setData(newState.start);
if (propName) {
this.setState({ [propName]: propValue });
} else {
this.setState(newState);
}
}
render() {
const startProps = { data: this.state.start, update: this.updateStart };
const iterationsProps = { data: this.state.iterations, update: this.updateIterationData };
const axiomProps = { data: this.state.axiom, update: this.updateAxiom };
const rulesProps = { data: this.state.rules, update: this.updateRules };
const instructionsProps = { data: this.state.instructions, update: this.updateInstructions };
const exampleProps = { update: this.updateExample };
return (
<div>
<div id="side-bar">
<h2>L-System Explorer</h2>
<Start { ...startProps } />
<Iterations { ...iterationsProps } />
<Axiom { ...axiomProps } />
<RulesContainer { ...rulesProps } />
<InstructionsContainer { ...instructionsProps } />
<Examples { ...exampleProps } />
</div>
</div>
);
}
}
export default App;
|
packages/core/tocco-ui/src/Table/StaticCell.js | tocco/tocco-client | import PropTypes from 'prop-types'
import React from 'react'
import {js} from 'tocco-util'
import {Typography} from '../index'
import {columnPropType, rowDataPropType} from './propTypes'
import {StyledTableCell} from './StyledComponents'
const StaticCell = React.memo(({column, rowData, rowIdx}) => (
<StyledTableCell data-cy="list-cell">
{column.CellRenderer ? (
<column.CellRenderer rowData={rowData} column={column} rowIdx={rowIdx} />
) : (
<Typography.Span>{rowData[column.id]}</Typography.Span>
)}
</StyledTableCell>
))
StaticCell.propTypes = {
rowData: rowDataPropType.isRequired,
column: columnPropType.isRequired,
rowIdx: PropTypes.number
}
const areEqual = (prevProps, nextProps) => {
if (!prevProps.column.dynamic) {
return true
}
const diff = Object.keys(js.difference(prevProps, nextProps))
return diff.length === 0
}
export default React.memo(StaticCell, areEqual)
|
frontend/modules/browse/components/Loading.js | RyanNoelk/OpenEats | import React from 'react'
import Spinner from 'react-spinkit';
const Loading = () => {
return (
<div className="row">
<div className="col-xs-12">
<div id="browse" className="row">
<div className="spinner">
<Spinner className="spinner-obj" spinnerName="circle" noFadeIn />
</div>
</div>
</div>
</div>
)
};
export default Loading; |
com/jessewarden/contacts/NewContactView.js | JesterXL/react-bootstrap-express-cassandra-contacts | import React from 'react';
import ReactDOM from 'react-dom';
import ContactsModel from './models/ContactsModel';
import classNames from 'classnames';
import EventBus from './EventBus';
import ImageView from './contactClasses/ImageView';
import PhoneForm from './contactClasses/PhoneForm';
import NewImageView from './contactClasses/NewImageView';
class NewContactView extends React.Component
{
constructor(props)
{
super(props);
this.margins = {
marginTop: "1em"
};
}
render()
{
var btnClass = classNames({
'btn-primary': true,
'btn-default': false
});
return (
<div className="row" style={this.margins}>
<div className="col-xs-1"></div>
<div className="col-xs-10">
<NewImageView></NewImageView>
</div>
</div>
);
}
}
export default NewContactView |
src/app/screens/Anonymous/screens/Home/components/Home.js | docgecko/react-alt-firebase-starter | /*! React Alt Firebase Starter */
import './Home.less';
import React from 'react';
export default class Home extends React.Component {
render() {
return (
<div className='home'>
<h1>Welcome to the Home page...</h1>
</div>
);
}
}
|
styleguide/screens/Patterns/Tabs/Tabs.js | rdjpalmer/bloom | import React from 'react';
import { Link } from 'react-router-dom';
import cx from 'classnames';
import dedent from 'dedent';
import Specimen from '../../../components/Specimen/Specimen';
import { D, H, T, C } from '../../../components/Scaffold/Scaffold';
import Tabs from '../../../../components/Tabs/Tabs';
import Tab from '../../../../components/Tabs/Tab';
import m from '../../../../globals/modifiers.css';
import scaffoldCss from '../../../components/Scaffold/Scaffold.css';
const TabsDocumentation = () => (
<div>
<H level={ 1 }>Tabs</H>
<T elm="p" className={ cx(m.mtr, m.largeI, m.demi) }>
<C>Tabs</C> provide an easy way to navigate between views on a single page,
where content is related. For cases when you need page level
tabs, <Link className={ scaffoldCss.link } to="/patterns/tab-bar">TabBar</Link>.
</T>
<D>
<Specimen
classNames={ {
specimenContainer: m.par,
} }
code={ dedent`
<Tabs>
<Tab label="One">
Barry Chuckle
</Tab>
<Tab label="Two">
Paul Chuckle
</Tab>
</Tabs>
` }
>
<Tabs>
<Tab label="One">
Barry Chuckle
</Tab>
<Tab label="Two">
Paul Chuckle
</Tab>
</Tabs>
</Specimen>
</D>
</div>
);
export default TabsDocumentation;
|
src/index.js | postazure/redux-helloworld | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux'
import configureStore from '../store/configureStore'
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
|
docs/app/Examples/collections/Form/GroupVariations/FormExampleEvenlyDividedGroup.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Form, Input } from 'semantic-ui-react'
const FormExampleEvenlyDividedGroup = () => (
<Form>
<Form.Group widths='equal'>
<Form.Field>
<label>First name</label>
<Input placeholder='First name' />
</Form.Field>
<Form.Field>
<label>Middle name</label>
<Input placeholder='Middle name' />
</Form.Field>
<Form.Field>
<label>Last name</label>
<Input placeholder='Last name' />
</Form.Field>
</Form.Group>
</Form>
)
export default FormExampleEvenlyDividedGroup
|
modules/dreamview/frontend/src/components/common/Background.js | xiaoxq/apollo | import React from 'react';
import PropTypes from 'prop-types';
const Image = (props) => {
const { image, style, ...otherProps } = props;
const finalStyle = {
...(style || {}),
backgroundImage: `url(${image})`,
backgroundSize: 'cover',
};
return <div className="dreamview-background" style={finalStyle} />;
};
/* Image.propTypes = {
* image: React.PropTypes.string.isRequired,
* style: React.PropTypes.object,
* }; */
export default Image;
|
pact/pact-react-consumer/src/App.js | thombergs/code-examples | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
|
src/js/components/player/Html.js | barumel/ultritium-radio-player | import React from 'react';
import { Grid, Row, Col } from 'react-bootstrap';
export class PlayerHtml extends React.Component {
constructor() {
super();
this.state = {
audio: false,
playing: false
}
}
play() {
const { audio, playing } = this.state;
if (audio.paused) {
audio.play();
this.setState({ playing: true });
} else {
audio.pause();
this.setState({ playing: false });
}
console.log(audio);
}
componentDidMount() {
const audio = document.getElementById('player');
const playing = true;
this.setState({ audio, playing });
}
render() {
const { playlist } = this.props;
const { _id, thumb } = playlist;
const { playing } = this.state;
const icon = playing ? 'pause' : 'play';
const src = `http://localhost:8090/api/stream/radio/${playlist._id}`;
return(
<Row>
<Col lg={12} md={12} sm={12} xs={12}>
<div class={"video-thumbnail-" + icon} onClick={this.play.bind(this)}>
<img src={thumb}></img>
<audio id="player" preload="auto" autoPlay>
<source src={src} type="audio/mpeg"></source>
</audio>
</div>
</Col>
</Row>
);
}
}
|
node_modules/rc-tabs/es/TabPane.js | ZSMingNB/react-news | import _defineProperty from 'babel-runtime/helpers/defineProperty';
import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import classnames from 'classnames';
var TabPane = createReactClass({
displayName: 'TabPane',
propTypes: {
className: PropTypes.string,
active: PropTypes.bool,
style: PropTypes.any,
destroyInactiveTabPane: PropTypes.bool,
forceRender: PropTypes.bool,
placeholder: PropTypes.node
},
getDefaultProps: function getDefaultProps() {
return { placeholder: null };
},
render: function render() {
var _classnames;
var props = this.props;
var className = props.className,
destroyInactiveTabPane = props.destroyInactiveTabPane,
active = props.active,
forceRender = props.forceRender;
this._isActived = this._isActived || active;
var prefixCls = props.rootPrefixCls + '-tabpane';
var cls = classnames((_classnames = {}, _defineProperty(_classnames, prefixCls, 1), _defineProperty(_classnames, prefixCls + '-inactive', !active), _defineProperty(_classnames, prefixCls + '-active', active), _defineProperty(_classnames, className, className), _classnames));
var isRender = destroyInactiveTabPane ? active : this._isActived;
return React.createElement(
'div',
{
style: props.style,
role: 'tabpanel',
'aria-hidden': props.active ? 'false' : 'true',
className: cls
},
isRender || forceRender ? props.children : props.placeholder
);
}
});
export default TabPane; |
site/src/components/Demo.js | appbaseio/reactivesearch | import React, { Component } from 'react';
import { ThemeProvider } from 'emotion-theming';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import { Navbar, Logo, Button, H1, Title, Grid } from '@appbaseio/designkit';
import { Base, Layout, SecondaryLink, Section, titleText, showMobileFlex } from '../styles';
import Footer from '../components/Footer';
import ImageCard from '../styles/ImageCard';
class Demo extends Component {
componentDidMount() {
window.scrollTo(0, 0);
}
render() {
const { config, theme } = this.props;
const { primary } = theme;
return (
<ThemeProvider
theme={{
primaryColor: '#0033FF',
}}
>
<Base>
<Navbar bold>
<Navbar.Logo>
<Logo href={config.header.logo.href}>
<Logo.Icon css="color: #fff;">
<img src={config.header.logo.src} alt="Icon" />
</Logo.Icon>
<Logo.Light>{config.header.logo.title.light}</Logo.Light>
<Logo.Dark>{config.header.logo.title.dark}</Logo.Dark>
</Logo>
</Navbar.Logo>
<Navbar.List>
{config.header.links.map((l, i) => (
<li
className={l.href === '/demo' || l.href === '/native/demo' ? 'active' : undefined}
/* eslint-disable-next-line */
key={i}
>
{/* eslint-disable-next-line */}
<Link style={{ color: '#424242' }} to={l.href}>
{l.description.toUpperCase()}
</Link>
</li>
))}
<li className={showMobileFlex}>
<a href={config.urls.github}>GITHUB</a>
</li>
<li className="button">
<Button
style={{ backgroundColor: theme.secondary }}
href={config.urls.support}
bold
uppercase
>
<img src="images/support.svg" style={{ marginRight: 8 }} alt="support" /> SUPPORT
</Button>
</li>
</Navbar.List>
</Navbar>
<Section>
<Layout style={{ marginTop: '50px' }}>
<H1>{config.title}</H1>
<p className={titleText}>{config.description}</p>
<Grid
size={config.demos.length / 2}
mdSize={2}
smSize={1}
gutter="15px"
smGutter="0px"
style={{ margin: '50px 0px' }}
>
{config.demos.map((d, index) => (
// eslint-disable-next-line
<ImageCard key={index} src={d.src}>
<div>
<Title>{d.title}</Title>
<p>{d.description}</p>
</div>
<div>
<SecondaryLink
primary
href={d.href}
style={{
color: primary,
}}
>
Check Demo
</SecondaryLink>
</div>
</ImageCard>
))}
</Grid>
</Layout>
</Section>
<Footer configName={config.name} footerConfig={config.footer} />
</Base>
</ThemeProvider>
);
}
}
Demo.propTypes = {
config: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
};
export default Demo;
|
src/icons/IosFlaskOutline.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosFlaskOutline extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M436.912,370.441L320,175V48h16V32h-16.009H304v16v131.418l2.514,3.791l116.575,194.834
c6.75,12.818,9.314,25.95,9.001,37.957c-0.243,9.339-1.958,17.938-6.545,25.569C417.076,455.666,402.33,464,384.981,464H129.093
c-17.504,0-32.461-8.435-41.035-22.705c-11.897-19.801-10.889-38.145,2.275-63.139L181.821,224H240v-16h-48.683l14.687-24.756
L208,179.4V176h48v-16h-48v-32h32v-16h-32V80h48V64h-48V48V32h-15.989H176v16h16v127L76.126,370.441
C67.714,386.268,63.615,401.814,64.027,416c1.061,36.511,28.702,64,65.065,64h255.889c36.291,0,62.131-27.598,62.992-64
C448.311,401.756,445.367,386.349,436.912,370.441z"></path>
<path d="M108.292,374.616c-6.907,10.542-10.936,24.095-10.936,33.55c0,27.584,15.82,39.834,45.682,39.834h225.932
c29.804,0,44.975-15.711,45.681-39.959c0.277-9.488-3.143-22.729-10.086-33.324L332.729,256H179.5L108.292,374.616z M323.705,272
l67.168,110.87l0.151,0.124l0.159,0.182c5.382,8.212,7.647,18.275,7.476,24.18c-0.229,7.839-2.477,13.98-6.683,17.795
c-4.774,4.328-12.729,6.85-23.008,6.85H143.037c-11.064,0-19.27-2.236-23.73-5.996c-1.472-1.24-5.954-5.143-5.954-18.088
c0-5.943,2.857-16.383,8.319-24.717l0.177-0.302l0.166-0.042L188.564,272H323.705z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M436.912,370.441L320,175V48h16V32h-16.009H304v16v131.418l2.514,3.791l116.575,194.834
c6.75,12.818,9.314,25.95,9.001,37.957c-0.243,9.339-1.958,17.938-6.545,25.569C417.076,455.666,402.33,464,384.981,464H129.093
c-17.504,0-32.461-8.435-41.035-22.705c-11.897-19.801-10.889-38.145,2.275-63.139L181.821,224H240v-16h-48.683l14.687-24.756
L208,179.4V176h48v-16h-48v-32h32v-16h-32V80h48V64h-48V48V32h-15.989H176v16h16v127L76.126,370.441
C67.714,386.268,63.615,401.814,64.027,416c1.061,36.511,28.702,64,65.065,64h255.889c36.291,0,62.131-27.598,62.992-64
C448.311,401.756,445.367,386.349,436.912,370.441z"></path>
<path d="M108.292,374.616c-6.907,10.542-10.936,24.095-10.936,33.55c0,27.584,15.82,39.834,45.682,39.834h225.932
c29.804,0,44.975-15.711,45.681-39.959c0.277-9.488-3.143-22.729-10.086-33.324L332.729,256H179.5L108.292,374.616z M323.705,272
l67.168,110.87l0.151,0.124l0.159,0.182c5.382,8.212,7.647,18.275,7.476,24.18c-0.229,7.839-2.477,13.98-6.683,17.795
c-4.774,4.328-12.729,6.85-23.008,6.85H143.037c-11.064,0-19.27-2.236-23.73-5.996c-1.472-1.24-5.954-5.143-5.954-18.088
c0-5.943,2.857-16.383,8.319-24.717l0.177-0.302l0.166-0.042L188.564,272H323.705z"></path>
</g>
</IconBase>;
}
};IosFlaskOutline.defaultProps = {bare: false} |
src/pages/about-me/About.js | chtefi/golb | import React from 'react'
import { graphql } from 'gatsby'
export default () => <div />
export const blockImageFragment = graphql`
fragment BlockImage on File {
childImageSharp {
fixed(
width: 540
height: 200
cropFocus: CENTER
quality: 50
duotone: { highlight: "#0288d1", shadow: "#192550", opacity: 60 }
) {
...GatsbyImageSharpFixed
}
}
}
fragment BlockImageBottom on File {
childImageSharp {
fixed(
width: 540
height: 200
cropFocus: SOUTH
quality: 50
duotone: { highlight: "#0288d1", shadow: "#192550", opacity: 60 }
) {
...GatsbyImageSharpFixed
}
}
}
`
|
lib/cli/generators/WEBPACK_REACT/template-csf/stories/0-Welcome.stories.js | storybooks/react-storybook | import React from 'react';
import { linkTo } from '@storybook/addon-links';
import { Welcome } from '@storybook/react/demo';
export default {
title: 'Welcome',
component: Welcome,
};
export const ToStorybook = () => <Welcome showApp={linkTo('Button')} />;
ToStorybook.story = {
name: 'to Storybook',
};
|
src/components/wrapper/standalone-box-decrypt.js | josuerangel/signandencrypt | import React from 'react'
import BoxDecrypt from '../box-decrypt/index.jsx';
/**
* Options example, boxencrypt need the next structure
*/
/*
const options = {
publicKeys: {
key1 : 'http://localhost:8080/apps2012/filesPublication/QApgp1.gpg',
key2 : 'http://localhost:8080/apps2012/filesPublication/QApgp2.gpg'
},
language: 'sp'
};
*/
function renderBoxDecrypt(options, container, callback){
let _box = null;
ReactDOM.render(<BoxDecrypt language={options.language} publicKey1={options.publicKeys.key1} publicKey2={options.publicKeys.key2}
ref={(_bd => { _box = _bd; })} />, container, callback);
return _box;
}
module.exports = renderBoxDecrypt;
window.renderBoxDecrypt = renderBoxDecrypt; |
node_modules/react-icons/fa/wheelchair.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const FaWheelchair = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m24.8 26.5l2.3 4.5q-1.3 4-4.7 6.5t-7.5 2.5q-3.5 0-6.5-1.7t-4.7-4.7-1.7-6.5q0-4 2.3-7.3t6.2-4.7l0.3 2.9q-2.7 1.2-4.3 3.7t-1.6 5.4q0 4.2 2.9 7.1t7.1 2.9q2.8 0 5.1-1.4t3.7-3.9 1.1-5.3z m12.3 2.2l1.3 2.6-5.8 2.8q-0.2 0.2-0.6 0.2-0.9 0-1.3-0.8l-5.3-10.6h-10.5q-0.6 0-1-0.4t-0.5-0.9l-2.1-17.4q-0.1-0.4 0.1-0.9 0.3-1.2 1.3-1.9t2.2-0.7q1.4 0 2.5 1.1t1 2.5q0 1.5-1.1 2.6t-2.7 0.9l0.8 6.5h9.5v2.8h-9.1l0.3 2.9h10.2q0.9 0 1.3 0.8l5 10.1z"/></g>
</Icon>
)
export default FaWheelchair
|
src/svg-icons/image/navigate-before.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageNavigateBefore = (props) => (
<SvgIcon {...props}>
<path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
</SvgIcon>
);
ImageNavigateBefore = pure(ImageNavigateBefore);
ImageNavigateBefore.displayName = 'ImageNavigateBefore';
ImageNavigateBefore.muiName = 'SvgIcon';
export default ImageNavigateBefore;
|
src/components/App.js | rpowelll/universal-react-boilerplate | /* @flow */
import React from 'react'
import { renderRoutes } from 'react-router-config'
import styles from './App.css'
import NavigationLink from './NavigationLink'
import routes from '../routes'
type Props = {
title?: string
}
const App = ({ title }: Props) => (
<div className={styles.app}>
<h1 className={styles.title}>{ title }</h1>
<ul className={styles.navigation}>
<NavigationLink exact to='/'>Home</NavigationLink>
<NavigationLink to='/counter'>Counter</NavigationLink>
<NavigationLink to='/async'>Async</NavigationLink>
</ul>
{renderRoutes(routes)}
</div>
)
App.defaultProps = {
title: 'Hello Universal React'
}
export default App
|
app/components/List/index.js | hieubq90/react-boilerplate-3.4.0 | import React from 'react';
import PropTypes from 'prop-types';
import Ul from './Ul';
import Wrapper from './Wrapper';
function List(props) {
const ComponentToRender = props.component;
let content = <div />;
// If we have items, render them
if (props.items) {
content = props.items.map((item, index) =>
<ComponentToRender key={`item-${index}`} item={item} />
);
} else {
// Otherwise render a single component
content = <ComponentToRender />;
}
return (
<Wrapper>
<Ul>
{content}
</Ul>
</Wrapper>
);
}
List.propTypes = {
component: PropTypes.func.isRequired,
items: PropTypes.array,
};
export default List;
|
src/components/groupings/collapsable.js | nutgaard/react-storybook-addon-sections | import React, { Component } from 'react';
import { default as PT } from 'prop-types';
import Collapse from 'react-collapse';
import './collapsable.css';
import { factory } from './utils';
import { classNames } from './../utils';
class Collapsable extends Component {
constructor(props) {
super(props);
this.state = {
open: props.open || false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
this.setState({ open: !this.state.open });
}
render() {
const { title, children } = this.props;
const openBtn = this.state.open ? 'Close' : 'Open';
return (
<div className={classNames('section', 'collapsable')}>
<button className={classNames('collapsable__btn')} onClick={this.handleClick}>
<div className={classNames('collapsable__flex-wrapper')}>
<h2 className={classNames('collapsable__btntitle')}>{title}</h2>
<span className={classNames('collapsable__btnicon')}>{openBtn}</span>
</div>
</button>
<Collapse isOpened={this.state.open}>
<div className={classNames('collapsable__content')}>
{children}
</div>
</Collapse>
</div>
);
}
}
Collapsable.propTypes = {
open: PT.bool,
title: PT.string.isRequired,
children: PT.oneOfType([PT.node, PT.arrayOf(PT.node)]).isRequired
};
Collapsable.defaultProps = {
open: false
};
export default factory(Collapsable);
|
node_modules/react-bootstrap/es/InputGroupButton.js | superKaigon/TheCave | 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 { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var InputGroupButton = function (_React$Component) {
_inherits(InputGroupButton, _React$Component);
function InputGroupButton() {
_classCallCheck(this, InputGroupButton);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
InputGroupButton.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('span', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return InputGroupButton;
}(React.Component);
export default bsClass('input-group-btn', InputGroupButton); |
src/app/src/components/Landing.js | istreight/eggbeatr | /**
* FILENAME: Landing.js
* AUTHOR: Isaac Streight
* START DATE: October 19th, 2016
*
* This file contains the Landing class for the landing
* page content of the lesson calendar web application.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import Anchor from 'utils/Anchor';
import Animator from 'functions/Animator';
import FnScroll from 'functions/FnScroll';
class Landing extends React.Component {
componentDidMount() {
var node = ReactDOM.findDOMNode(this);
var title = node.querySelector("div h1 div");
var getStartedButton = node.querySelector("a");
// Fade in WELCOME, then cycle through title styles.
Animator.fadeIn(title, 1200, 400, () => {
Animator.fadeOut(title, 800, 0, () => {
title.innerHTML = "eggbeatr";
Animator.fadeIn(getStartedButton, 1500);
this.cycle(1, title);
});
});
}
/**
* Rotates through 3 styles of the application title,
* fading in and out.
*/
cycle(stage, title) {
var style = "";
var weight = "";
if (stage === 1) {
style = "italic";
} else if (stage === 2) {
weight = "bold";
}
Animator.fadeIn(title, 1200, 400, () => {
Animator.fadeOut(title, 800, 0, () => {
title.style.fontStyle = style;
title.style.fontWeight = weight;
this.cycle(++stage % 3, title);
});
});
}
/**
* Starts a tutorial on how to run application.
*/
getStarted() {
var nextLocation = document.getElementById("dynamicInstructors");
FnScroll.tutorialScroll(null, nextLocation);
}
render() {
return (
<div className="splash">
<h1 className="splash-head lowercase">
<div>
welcome
</div>
</h1>
<p className="splash-subhead">
a calendar application for organizing swim lessons<br />
doing the heavy lifting while leaving you with creative control
</p>
<div>
<Anchor
data={ "Get Started" }
handleClick={ this.getStarted }
styleClass={ "pure-button pure-button-primary" }
/>
</div>
</div>
);
}
}
export default Landing;
|
src/svg-icons/av/note.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvNote = (props) => (
<SvgIcon {...props}>
<path d="M22 10l-6-6H4c-1.1 0-2 .9-2 2v12.01c0 1.1.9 1.99 2 1.99l16-.01c1.1 0 2-.89 2-1.99v-8zm-7-4.5l5.5 5.5H15V5.5z"/>
</SvgIcon>
);
AvNote = pure(AvNote);
AvNote.displayName = 'AvNote';
export default AvNote;
|
src/index.js | jiangjiyun/jjy-music | import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import { ConnectedRouter, routerReducer, routerMiddleware, push } from 'react-router-redux';
import { AppContainer } from 'react-hot-loader';
import App from './App';
import createHistory from 'history/createBrowserHistory';
import rootReducer from './reducers/index';
var FastClick = require('fastclick');
import 'lodash'
const history = createHistory();
const middleware = routerMiddleware(history)
const logger = createLogger({ collapsed: true });
//解决移动端300毫秒延迟
FastClick.attach(document.body);
const middlewares = [thunk, middleware];
if(process.env.NODE_ENV === 'development') {
middlewares.push(logger)
}
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(...middlewares)));
const render = Component =>
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<Component />
</Provider>
</AppContainer>,
document.getElementById('root')
);
render(App)
if(module.hot) {
module.hot.accept('./App', () => { render(App) });
} |
src/Radio/Radio.js | AndriusBil/material-ui | // @flow weak
import React from 'react';
import type { Node } from 'react';
import withStyles from '../styles/withStyles';
import createSwitch from '../internal/SwitchBase';
import RadioButtonCheckedIcon from '../svg-icons/RadioButtonChecked';
import RadioButtonUncheckedIcon from '../svg-icons/RadioButtonUnchecked';
export const styles = (theme: Object) => ({
default: {
color: theme.palette.text.secondary,
},
checked: {
color: theme.palette.primary[500],
},
disabled: {
color: theme.palette.action.disabled,
},
});
const Radio = withStyles(styles, { name: 'MuiRadio' })(
createSwitch({
inputType: 'radio',
defaultIcon: <RadioButtonUncheckedIcon />,
defaultCheckedIcon: <RadioButtonCheckedIcon />,
}),
);
Radio.displayName = 'Radio';
export default Radio;
export type Props = {
/**
* If `true`, the component is checked.
*/
checked?: boolean | string,
/**
* The CSS class name of the root element when checked.
*/
checkedClassName?: string,
/**
* The icon to display when the component is checked.
* If a string is provided, it will be used as a font ligature.
*/
checkedIcon?: Node,
/**
* Useful to extend the style applied to components.
*/
classes?: Object,
/**
* @ignore
*/
className?: string,
/**
* @ignore
*/
defaultChecked?: boolean,
/**
* If `true`, the switch will be disabled.
*/
disabled?: boolean,
/**
* The CSS class name of the root element when disabled.
*/
disabledClassName?: string,
/**
* If `true`, the ripple effect will be disabled.
*/
disableRipple?: boolean,
/**
* The icon to display when the component is unchecked.
* If a string is provided, it will be used as a font ligature.
*/
icon?: Node,
/**
* Properties applied to the `input` element.
*/
inputProps?: Object,
/**
* Use that property to pass a ref callback to the native input component.
*/
inputRef?: Function,
/*
* @ignore
*/
name?: string,
/**
* Callback fired when the state is changed.
*
* @param {object} event The event source of the callback
* @param {boolean} checked The `checked` value of the switch
*/
onChange?: Function,
/**
* @ignore
*/
tabIndex?: number | string,
/**
* The value of the component.
*/
value?: string,
};
// This is here solely to trigger api doc generation
export const RadioDocs = (props: Props) => <span />; // eslint-disable-line no-unused-vars
|
src/app/components/Home.js | stevemu/qi-ern-stack-starter | import React, { Component } from 'react';
class Home extends Component {
render() {
return (
<div className="">
<p>Hello Home!</p>
<p>234234</p>
</div>
);
}
}
export default Home;
|
src/components/Toolbar/Toolbar-story.js | carbon-design-system/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import Filter16 from '@carbon/icons-react/lib/filter/16';
import Toolbar, {
ToolbarItem,
ToolbarTitle,
ToolbarOption,
ToolbarDivider,
} from '../Toolbar';
import OverflowMenu from '../OverflowMenu';
import OverflowMenuItem from '../OverflowMenuItem';
import Checkbox from '../Checkbox';
import RadioButton from '../RadioButton';
const toolbarProps = {
className: 'some-class',
};
const inputProps = {
className: 'some-class',
onChange: action('onChange'),
};
storiesOf('Toolbar', module).add(
'Default',
() => (
<Toolbar {...toolbarProps} className="some-class">
<ToolbarItem type="search" placeHolderText="Search" />
<ToolbarItem>
<OverflowMenu renderIcon={Filter16}>
<ToolbarTitle title="FILTER BY" />
<ToolbarOption>
<Checkbox {...inputProps} id="opt-1" labelText="Filter option 1" />
</ToolbarOption>
<ToolbarOption>
<Checkbox {...inputProps} id="opt-2" labelText="Filter option 2" />
</ToolbarOption>
<ToolbarOption>
<Checkbox {...inputProps} id="opt-3" labelText="Filter option 3" />
</ToolbarOption>
</OverflowMenu>
</ToolbarItem>
<ToolbarItem>
<OverflowMenu>
<OverflowMenuItem itemText="Refresh table" />
<ToolbarDivider />
<ToolbarTitle title="ROW HEIGHT" />
<ToolbarOption>
<RadioButton
{...inputProps}
value="short"
id="radio-1"
name="toolbar-radio"
labelText="Short"
/>
</ToolbarOption>
<ToolbarOption>
<RadioButton
{...inputProps}
value="tall"
id="radio-2"
name="toolbar-radio"
labelText="Tall"
/>
</ToolbarOption>
</OverflowMenu>
</ToolbarItem>
</Toolbar>
),
{
info: {
text: `
Toolbar stuff
`,
},
}
);
|
src/demo/stories/options_items/allow_to_drop_readonly.js | chybatronik/react_sortable | import React, { Component } from 'react';
import {default_order} from "../demo_data";
import SortableReact from '../../../lib/SortableReact';
import Markdown from 'react-markdown';
const code = `
\`\`\`js
<SortableReact
mode={mode}
isDropOnEmptyAreaAllowed={this.state.isDropOnEmptyAreaAllowed}
isGridLocked={this.state.isGridLocked}
cells=[
{id: "1", colspan:1, rowspan:1, defaultColumn:1, defaultRow:1, content: "1"},
{id: "2", colspan:1, rowspan:1, defaultColumn:2, defaultRow:1, content: "2"},
{id: "3", colspan:1, rowspan:1, defaultColumn:3, defaultRow:1, content: "3"},
{id: "4", colspan:1, rowspan:1, defaultColumn:4, defaultRow:1, content: "4"},
{id: "11", colspan:1, rowspan:1, defaultColumn:1, defaultRow:2, content: "11"},
{id: "12", colspan:1, rowspan:1, defaultColumn:2, defaultRow:2, content: "12"},
{id: "13", colspan:1, rowspan:1, defaultColumn:3, defaultRow:2, content: "13"},
{id: "14", colspan:1, rowspan:1, defaultColumn:4, defaultRow:2, content: "14"},
{id: "21", colspan:1, rowspan:1, defaultColumn:1, defaultRow:3, content: "21"},
{id: "22", colspan:1, rowspan:1, defaultColumn:2, defaultRow:3, content: "22"},
{id: "23", colspan:1, rowspan:1, defaultColumn:3, defaultRow:3, content: "23"},
{id: "24", colspan:1, rowspan:1, defaultColumn:4, defaultRow:3, content: "24"}
]
/>
\`\`\`
`
const text = `
#
${code}
`
class StoreAllowDropReadOnly extends Component {
constructor(props) {
super(props)
this.state = {mode: "SORT", isDropOnEmptyAreaAllowed:false, isGridLocked:false};
}
onState(e){
console.log("onState:", e.target.value)
this.setState({"mode": e.target.value})
}
onAllowToEmpty(e){
console.log("e.target.value:", !this.state.isDropOnEmptyAreaAllowed)
this.setState({"isDropOnEmptyAreaAllowed": !this.state.isDropOnEmptyAreaAllowed})
}
onDisableDrag(){
this.setState({"isGridLocked": !this.state.isGridLocked})
}
render(){
// console.log("this.props.mode;;", this.props)
const mode = this.state.mode
return (
<div>
<h1>Allow to drop empty cell. Locked grid.</h1>
<div style={{overflow:"scroll", height:450}}>
<label>mode:</label>
<select
style={{width:200, "marginLeft":20}} onChange={this.onState.bind(this)}>
<option value="SORT">SORT</option>
<option value="SWAP">SWAP</option>
</select>
<label style={{marginLeft:40}}>isDropOnEmptyAreaAllowed:
<input type="checkbox" style={{marginLeft:5}} onChange={this.onAllowToEmpty.bind(this)} checked={this.state.isDropOnEmptyAreaAllowed}/>
</label>
<label style={{marginLeft:40}}>isGridLocked:
<input type="checkbox" style={{marginLeft:5}} onChange={this.onDisableDrag.bind(this)} checked={this.state.isGridLocked}/>
</label>
<SortableReact
mode={mode}
isDropOnEmptyAreaAllowed={this.state.isDropOnEmptyAreaAllowed}
isGridLocked={this.state.isGridLocked}
cells={default_order}
/>
</div>
<Markdown source={text}/>
</div>
)
}
}
export default StoreAllowDropReadOnly;
|
tests/react/createElementRequiredProp_string.js | jeffmo/flow | // @flow
import React from 'react';
class Bar extends React.Component {
props: {
test: number,
};
render() {
return (
<div>
{this.props.test}
</div>
)
}
}
class Foo extends React.Component {
render() {
const Cmp = Math.random() < 0.5 ? 'div' : Bar;
return (<Cmp/>);
}
}
|
source/client/components/UserProfile.js | achobanov/ReactJS-Fundamentals-lab | import React from 'react';
import UserStore from '../stores/UserStore';
import UserInfo from './sub-components/UserInfo';
import UserVotedMovies from './sub-components/UserRatedMovies';
import UserReviews from './sub-components/UserReviews';
export default class UserProfile extends React.Component {
constructor(props) {
super(props);
this.state = UserStore.getState();
this.onChange = this.onChange.bind(this);
}
onChange(state) {
this.setState(state);
}
componentDidMount() {
UserStore.listen(this.onChange);
}
componentWillUnmount() {
UserStore.unlisten(this.onChange);
}
render() {
let nodes = {};
nodes.roles = this.state.roles.map((role, index) => {
return (
<h4 key={ index } className='lead'>
<strong>{ role }</strong>
</h4>
);
});
return (
<div>
<UserInfo name={ this.state.name }
roles={ this.state.roles }
information={ this.state.information } />
<UserVotedMovies votes={ this.state.votes } />
<UserReviews reviews={ this.props.reviews } />
</div>
);
}
}
|
src/components/HomePage.js | jojoee/whitt | import React from 'react';
const HomePage = () => {
return (
<div>
<h2>HomePage</h2>
</div>
);
};
export default HomePage;
|
src/pages/login/LoginPage.js | TimothyBom/react-redux-instagram | import React from 'react'
import { connect } from 'react-redux'
import LoginForm from './LoginForm'
import { getUserLogin } from '../../actions/login'
const LoginPage = props => (
<div className="container mt-10">
<h1 className="text-center mb-4">Login Page</h1>
<div className="row justify-content-center">
<LoginForm getUserLogin={props.getUserLogin} />
</div>
</div>
)
export default connect(null, { getUserLogin })(LoginPage) |
src/components/containers/register-active-container.js | HuangXingBin/goldenEast | import React from 'react';
import { Button, Input, message } from 'antd';
import RegisterActiveTable from '../views/register-active-table';
import { getRegisterActiveData } from '../../api/app-interaction-api';
import { mergeDeep} from '../../helpers/helpers';
const RegisterActiveContainer = React.createClass({
getInitialState(){
return {
data:{
list:[],
sum: {},
this_page: '',
total: '',
},
page: 1,
search: '',
loading: false,
}
},
submitSearch(){
this.getData();
},
onChange(e){
this.setState({
page: 1,
search: e.target.value
});
},
onPageChange(page){
this.setState({
page: page,
},function(){
this.getData();
});
},
getData(){
this.setState({
loading: true
});
var _this = this;
getRegisterActiveData({page:this.state.page,'search[find]':this.state.search},function(info){
_this.setState({
data: info.data,
loading: false,
});
},function(info){
message.error(info.info,5);
var template = { data : _this.state.data};
var resault = {
data : {
list:[],
sum: {
activated_total: 0,
fees_total: 0,
registered_total: 0,
},
this_page: '',
total: '',
}
}
var merged = mergeDeep(template, resault);
_this.setState({
data: merged.data,
loading: false,
});
});
},
componentDidMount(){
this.getData();
},
render(){
const { list, sum, this_page, total } = this.state.data;
console.log(this.props.children)
return this.props.children || (
<div>
<div className="userListHeader">
<div className="searchBar">
<Input
style={{ width: '200px' }}
onChange={this.onChange}
onPressEnter={this.submitSearch}
placeholder="输入公司名称"
/>
<Button onClick={this.submitSearch} type="primary" style={{marginLeft:'20px'}}>搜索</Button>
</div>
<div className="number-info">
<span>{sum.activated_total}</span>
<p>当月总激活量</p>
</div>
<div className="number-info">
<span>{sum.registered_total}</span>
<p>当月总注册量</p>
</div>
<div className="number-info">
<span>{sum.fees_total}</span>
<p>当月总手续费</p>
</div>
</div>
<RegisterActiveTable defaultPageSize={12} total={total} currentPage={this_page} dataSource={list} onPageChange={this.onPageChange} loading={this.state.loading}/>
</div>
)
},
});
export default RegisterActiveContainer;
|
examples/counter/containers/App.js | ErrorPro/redux | import React, { Component } from 'react';
import CounterApp from './CounterApp';
import { createRedux } from 'redux';
import { Provider } from 'redux/react';
import * as stores from '../stores';
const redux = createRedux(stores);
export default class App extends Component {
render() {
return (
<Provider redux={redux}>
{() => <CounterApp />}
</Provider>
);
}
}
|
src/view/greeting.js | MoonlightOwl/hel-site | import React from 'react'
class Greeting extends React.Component {
render() {
return (
<div className="ui negative message">
<i className="close icon"></i>
<div className="header">
Welcome to Hel Package Repository!
</div>
<p></p>
</div>
);
}
}
export default Greeting; |
ui/src/components/workflow/executions/WorkflowList.js | grfeng/conductor | /* eslint-disable no-restricted-globals */
import React, { Component } from 'react';
import PropTypes from "prop-types";
import { connect } from 'react-redux';
import { createSelector } from 'reselect'
import {changeSearch, fetchSearchResults} from '../../../actions/search';
import { performBulkOperation } from '../../../actions/bulk';
import WorkflowSearch from "./WorkflowSearch";
import WorkflowTable from './WorkflowTable';
import difference from 'lodash/difference';
import filter from "lodash/filter";
import get from "lodash/get";
import includes from "lodash/includes";
import intersection from 'lodash/intersection';
import isEmpty from "lodash/isEmpty";
import map from 'lodash/map';
import size from "lodash/size";
import uniq from 'lodash/uniq';
import without from 'lodash/without';
import WorkflowBulkAction from './WorkflowBulkAction';
class Workflow extends Component {
constructor(props) {
super(props);
this.nextPage = this.nextPage.bind(this);
this.prevPage = this.prevPage.bind(this);
this.bulkProcess = this.bulkProcess.bind(this);
this.onChangeBulkProcessSelection = this.onChangeBulkProcessSelection.bind(this);
this.handleSelect = this.handleSelect.bind(this);
this.handleSelectAll = this.handleSelectAll.bind(this);
this.state = {
selected: [],
bulkProcessOperation: "pause",
bulkValidationMessage: ""
};
}
componentDidUpdate(prevProps) {
const {search} = this.props;
const {selected} = this.state;
// remove from selection after updating filters
if (prevProps.search.results !== search.results) {
this.setState({
selected: intersection(map(search.results, 'workflowId'), selected),
bulkValidationMessage: ""
});
}
}
componentWillReceiveProps({bulk: {successfulResults}}) {
// remove successful bulk workflows from selection
const remaining = difference(this.state.selected, successfulResults);
if (size(remaining) !== size(this.state.selected)) {
this.setState({selected: remaining});
}
}
nextPage() {
const {changeSearch, fetchSearchResults, search} = this.props;
const {start} = search;
changeSearch({...search, start: start + 100});
fetchSearchResults();
}
prevPage() {
const {changeSearch, fetchSearchResults, search} = this.props;
const {start} = search;
changeSearch({...search, start: start - 100});
fetchSearchResults();
}
onChangeBulkProcessSelection({target: {value}}) {
this.setState({bulkProcessOperation: value, bulkValidationMessage: ""})
}
bulkProcess() {
const {selected, bulkProcessOperation} = this.state;
const {performBulkOperation} = this.props;
if (size(selected) === 0) {
this.setState({bulkValidationMessage: "Error: No workflows selected"});
return;
}
performBulkOperation(bulkProcessOperation, selected);
}
handleSelect({workflowId, id}, isSelected) {
const {selected} = this.state;
if (isSelected){
this.setState({
selected: uniq([...selected, workflowId]),
bulkValidationMessage: ""
});
} else {
this.setState({
selected: without(selected, workflowId),
bulkValidationMessage: ""
});
}
return false;
}
handleSelectAll(isSelected, rows) {
if (isSelected){
this.setState({selected: map(rows, 'workflowId'), bulkValidationMessage: ""});
} else {
this.setState({selected: [], bulkValidationMessage: ""});
}
return false;
}
render() {
const {location, history, bulk, metadata, search} = this.props;
const {workflows} = metadata;
const {bulkProcessOperation, bulkValidationMessage, selected} = this.state;
return (
<div className="ui-content">
<WorkflowSearch search={search} workflows={workflows} location={location} history={history}/>
<WorkflowBulkAction isFetching={bulk.isFetching} selectedCount={size(selected)}
validationMessage={bulkValidationMessage}
successfulResults={bulk.successfulResults}
errorResults={bulk.errorResults}
bulkProcess={this.bulkProcess}
onChangeBulkProcessSelection={this.onChangeBulkProcessSelection}
bulkProcessOperation={bulkProcessOperation}/>
<WorkflowTable results={search.results} selected={selected}
isFetching={search.isFetching}
totalHits={search.totalHits}
start={search.start}
handleSelect={this.handleSelect}
handleSelectAll={this.handleSelectAll}
nextPage={this.nextPage}
prevPage={this.prevPage}
/>
<br />
<br />
</div>
)
}
}
Workflow.propTypes = {
changeSearch: PropTypes.func.isRequired,
fetchSearchResults: PropTypes.func.isRequired,
performBulkOperation: PropTypes.func.isRequired,
search: PropTypes.shape({
isFetching: PropTypes.bool.isRequired,
start: PropTypes.number.isRequired,
types: PropTypes.array.isRequired,
results: PropTypes.array.isRequired,
totalHits: PropTypes.number.isRequired
}),
metadata: PropTypes.shape({
workflows: PropTypes.array.isRequired
}),
bulk: PropTypes.shape({
isFetching: PropTypes.bool.isRequired,
error: PropTypes.string,
successfulResults: PropTypes.arrayOf(PropTypes.string).isRequired,
errorResults: PropTypes.objectOf(PropTypes.string).isRequired
})
};
const getFilteredWorkflows = (results, states) => {
if (isEmpty(states)) {
return results;
} else {
return filter(results, r => includes(states, get(r, 'status')));
}
};
const getStates = state => state.states;
const getResults = state => state.results;
const getFilteredWorkflowSelector = createSelector([getResults, getStates], getFilteredWorkflows);
function mapStateToProps({bulk, metadata, search}) {
return {
search: {...search,
results: getFilteredWorkflowSelector(search)
}, metadata, bulk
};
}
const mapDispatchToProps = {changeSearch, fetchSearchResults, performBulkOperation};
export default connect(mapStateToProps, mapDispatchToProps)(Workflow);
|
client/app/components/ContentEditor/customPlugins/media-plugin/components/AddMediaButton.js | bryanph/Geist | import React from 'react';
import { insertDataBlock } from '../../../utils/block'
import { Entity } from 'draft-js'
import { getType, transformSrc } from '../utils/getMediaType'
import { InputText } from '../../../../Input'
import RaisedButton from 'material-ui/RaisedButton';
const addMedia = (editorState, setEditorState) => (src, cb?) => {
if (!src) {
return;
}
const type = getType(src)
if (!type) {
// const extension = extensionRe.exec(src)[1]
window.alert("This type of media is not supported (yet?) for embedding")
return;
}
const transformedSrc = transformSrc(type, src)
setEditorState(
insertDataBlock(
editorState,
{
type,
src: transformedSrc
}
)
)
if (cb) {
cb()
}
}
export class AddMediaInput extends React.Component {
constructor(props) {
super(props)
this.addMedia = addMedia(props.editorState, props.setEditorState)
this.addMediaFromSrc = this.addMediaFromSrc.bind(this)
this.state = {
value: "",
}
}
addMediaFromSrc() {
this.addMedia(this.state.value, this.props.onSuccess)
}
render() {
return (
<div>
<InputText
onChange={e => this.setState({ value: e.target.value })}
value={this.state.value}
placeholder={"Insert full URL here"}
/>
<RaisedButton
label="Confirm"
primary={true}
onClick={this.addMediaFromSrc}
style={{marginLeft: '15px'}}
/>
</div>
)
}
}
class AddMediaButton extends React.Component {
constructor(props) {
super(props)
this.addMedia = addMedia(props.editorState, props.setEditorState)
this.addMediaFromSrc = this.addMediaFromSrc.bind(this)
}
addMediaFromSrc() {
const src = window.prompt("Enter a URL (videos, images, audio, youtube, etc.)")
this.addMedia(src)
}
render() {
const className = this.props.theme.button;
return (
<button className={className} onMouseDown={this.addMediaFromSrc}>
{ this.props.label || "Add Media" }
</button>
)
}
}
AddMediaButton.defaultProps = {
theme: {
button: 'add-media-button'
}
}
export default AddMediaButton
|
scripts/experiences/Dmlf.js | storfarmand/dmlf | import React from 'react';
import Header from '../components/Header';
import Mainstage from '../components/Mainstage';
import * as KeyboardActions from '../actions/KeyboardActions';
import NavigationStore from '../stores/NavigationStore';
import TypographyStore from '../stores/TypographyStore';
export default class Dmlf extends React.Component {
constructor(props) {
super(props);
this.state = {
mounted: false,
content: {},
page: 0,
fontFactor: 2
};
}
componentWillMount() {
NavigationStore.on('experience:navigate', (obj) => {
switch (obj.direction) {
case 'prev':
this.prev(this.props);
break;
case 'next':
this.next(this.props);
break;
}
});
TypographyStore.on('experience:fontfactor', (obj) => {
this.setState({
fontFactor: obj.value
});
});
}
componentDidMount() {
this.setState({
mounted: true
});
window.addEventListener('keyup', (evt) => {
const prevKeys = ['arrowleft', 'arrowup', 'p', 'b'];
if (prevKeys.indexOf(evt.key.toLowerCase()) >= 0) {
KeyboardActions.navigate({direction: 'prev'});
}
const nextKeys = ['arrowright', 'arrowdown', 'n', 'f'];
if (nextKeys.indexOf(evt.key.toLowerCase()) >= 0) {
KeyboardActions.navigate({direction: 'next'});
}
const fontFactorKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
if (fontFactorKeys.indexOf(evt.key.toLowerCase()) >= 0) {
KeyboardActions.fontfactor({value: parseInt(evt.key.toLowerCase(), 10)});
}
});
}
componentWillUnmount() {
this.setState({
mounted: false
});
}
prev() {
if (this.state.page === 0) {
return;
}
this.setState({
page: this.state.page - 1
});
}
next(props) {
if (this.state.page === props.content.pages.length - 1) {
return;
}
this.setState({
page: this.state.page + 1
});
}
render() {
return (
<div
class={[
"dmlf",
].join(' ')}
ref={(experience) => {this.experience = experience}}
>
<Header
addclass="header-experience"
type="1"
text={this.props.content.pages[this.state.page].heading}
fontfactor={this.state.fontFactor}
/>
<Mainstage
config={this.state.config}
fontfactor={this.state.fontFactor}
content={this.props.content.pages[this.state.page]}
page={this.state.page}
/>
<div className="btn-group horizontal">
<button
class="btn btn-prev"
onClick={this.prev.bind(this, this.props)}
>{this.props.content.buttons.prev}</button>
<button
class="btn btn-next"
onClick={this.next.bind(this, this.props)}
>{this.props.content.buttons.next}</button>
</div>
</div>
);
}
}
|
node_modules/react-native-router-flux/src/LightboxNavigator.js | gunaangs/Feedonymous | /* @flow */
import React from 'react';
import { createNavigationContainer, createNavigator, TabRouter } from 'react-navigation';
import { View } from 'react-native';
const LightboxNavigator = (
routeConfigs,
tabsConfig = {}
) => {
const router = TabRouter(routeConfigs, tabsConfig);
const navigator = createNavigator(
router,
routeConfigs,
tabsConfig,
'react-navigation/STACK'
)(({ navigation }) => {
const { state, dispatch } = navigation;
const { routes, index } = state;
// Figure out what to render based on the navigation state and the router:
const Component = routeConfigs[tabsConfig.initialRouteName].screen;
let initialIndex = 0;
for (let i = 0; i < routes.length; i++) {
const route = routes[i];
if (route.routeName === tabsConfig.initialRouteName) {
initialIndex = i;
}
}
const Popup = index !== initialIndex ? routeConfigs[routes[index].routeName].screen : null;
return (<View style={{ flex: 1 }}>
<Component navigation={{ dispatch, state: routes[initialIndex] }} />
{Popup && <Popup navigation={{ dispatch, state: routes[index] }} />}
</View>);
});
return createNavigationContainer(navigator, tabsConfig.containerOptions);
};
export default LightboxNavigator;
|
SwipComponent/FacebookTabBar.js | MisterZhouZhou/ReactNativeLearing | import React from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
const FacebookTabBar = React.createClass({
tabIcons: [],
propTypes: {
goToPage: React.PropTypes.func,
activeTab: React.PropTypes.number,
tabs: React.PropTypes.array,
},
componentDidMount() {
this._listener = this.props.scrollValue.addListener(this.setAnimationValue);
},
setAnimationValue({ value, }) {
this.tabIcons.forEach((icon, i) => {
const progress = Math.min(1, Math.abs(value - i))
icon.setNativeProps({
style: {
color: this.iconColor(progress),
},
});
});
},
//color between rgb(59,89,152) and rgb(204,204,204)
iconColor(progress) {
const red = 59 + (204 - 59) * progress;
const green = 89 + (204 - 89) * progress;
const blue = 152 + (204 - 152) * progress;
return `rgb(${red}, ${green}, ${blue})`;
},
render() {
return <View style={[styles.tabs, this.props.style, ]}>
{this.props.tabs.map((tab, i) => {
return <TouchableOpacity key={tab} onPress={() => this.props.goToPage(i)} style={styles.tab}>
<Icon
name={tab}
size={30}
color={this.props.activeTab === i ? 'rgb(59,89,152)' : 'rgb(204,204,204)'}
ref={(icon) => { this.tabIcons[i] = icon; }}
/>
</TouchableOpacity>;
})}
</View>;
},
});
const styles = StyleSheet.create({
tab: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingBottom: 10,
},
tabs: {
height: 45,
flexDirection: 'row',
paddingTop: 5,
borderWidth: 1,
borderTopWidth: 0,
borderLeftWidth: 0,
borderRightWidth: 0,
borderBottomColor: 'rgba(0,0,0,0.05)',
},
});
export default FacebookTabBar;
|
jqwidgets/jqwidgets-react/react_jqxfileupload.js | UCF/IKM-APIM | /*
jQWidgets v5.6.0 (2018-Feb)
Copyright (c) 2011-2017 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxFileUpload extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['autoUpload','accept','browseTemplate','cancelTemplate','disabled','fileInputName','height','localization','multipleFilesUpload','renderFiles','rtl','theme','uploadUrl','uploadTemplate','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxFileUpload(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxFileUpload('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxFileUpload(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
autoUpload(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('autoUpload', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('autoUpload');
}
};
accept(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('accept', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('accept');
}
};
browseTemplate(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('browseTemplate', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('browseTemplate');
}
};
cancelTemplate(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('cancelTemplate', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('cancelTemplate');
}
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('disabled');
}
};
fileInputName(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('fileInputName', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('fileInputName');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('height', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('height');
}
};
localization(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('localization', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('localization');
}
};
multipleFilesUpload(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('multipleFilesUpload', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('multipleFilesUpload');
}
};
renderFiles(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('renderFiles', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('renderFiles');
}
};
rtl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('rtl', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('rtl');
}
};
theme(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('theme', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('theme');
}
};
uploadUrl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('uploadUrl', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('uploadUrl');
}
};
uploadTemplate(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('uploadTemplate', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('uploadTemplate');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxFileUpload('width', arg)
} else {
return JQXLite(this.componentSelector).jqxFileUpload('width');
}
};
browse() {
JQXLite(this.componentSelector).jqxFileUpload('browse');
};
cancelFile() {
JQXLite(this.componentSelector).jqxFileUpload('cancelFile');
};
cancelAll() {
JQXLite(this.componentSelector).jqxFileUpload('cancelAll');
};
destroy() {
JQXLite(this.componentSelector).jqxFileUpload('destroy');
};
performRender() {
JQXLite(this.componentSelector).jqxFileUpload('render');
};
refresh() {
JQXLite(this.componentSelector).jqxFileUpload('refresh');
};
uploadFile(fileIndex) {
JQXLite(this.componentSelector).jqxFileUpload('uploadFile', fileIndex);
};
uploadAll() {
JQXLite(this.componentSelector).jqxFileUpload('uploadAll');
};
render() {
let id = 'jqxFileUpload' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}>{this.props.value}{this.props.children}</div>
)
};
};
|
src/components/featured/feature-who.js | Vision100IT/v100it-template | import React from 'react';
import {Link} from 'react-router-dom';
import FaBank from 'react-icons/lib/fa/bank';
import FaUsers from 'react-icons/lib/fa/group';
import FaServer from 'react-icons/lib/fa/server';
import FaGraduationCap from 'react-icons/lib/fa/graduation-cap';
import FaAngleDown from 'react-icons/lib/fa/angle-down';
import styles from './feature-who.scss';
import Featured from '.';
const imageContext = require.context('../../images');
const FeaturedWho = () => (
<Featured name="who" background="black">
<div className="text-slab">
The right people at the right time
</div>
<div className={`${styles.snapshots}`}>
<div>
<FaBank height="4em" width="4em"/>
<span className="fa-university fa-5x"/>
<p>14+ years of history</p>
</div>
<div>
<FaGraduationCap height="4em" width="4em"/>
<p>30+ years of collective experience</p>
</div>
<div>
<FaUsers height="4em" width="4em"/>
<p>20+ clients on board</p>
</div>
<div>
<FaServer height="4em" width="4em"/>
<p>30+ websites served</p>
</div>
</div>
<p>
New Front Door are a national team of passionate IT and web development engineers, ministry leaders and management professionals who voluntarily build and maintain IT systems, training and educating our clients on the foundation of years of collective knowledge gleaned from within the IT industry.
</p>
<p>
New Front Door, previously Vision 100 IT, has now existed for over a decade, and has gradually built up a knowledge base of best practices and approaches for doing church IT <em>sustainably</em>. We are all about getting <em>and keeping</em> our clients on the web, in order to more effectively reach the lost and minister to the people in their congregations.
</p>
<p>
Currently our team has members in Hobart and in Sydney, ready to meet and discuss the needs of your ministry.
</p>
<div className="expand">
<Link to="/about">
<p>Meet the team and read our story</p>
<FaAngleDown height="1.5em" width="1.5em"/>
</Link>
</div>
<div className={styles.tiled}>
<div><img src={imageContext('./christian-tile.jpg')}/></div>
<div><img src={imageContext('./jonno-tile.jpg')}/></div>
<div><img src={imageContext('./emile-tile.jpg')}/></div>
<div><img src={imageContext('./gibbo-tile.jpg')}/></div>
<div><img src={imageContext('./alan-tile.jpg')}/></div>
<div><img src={imageContext('./chris-tile.jpg')}/></div>
</div>
</Featured>
);
export default FeaturedWho;
|
lib/beaver.js | dpkshrma/beaver | 'use babel';
import React from 'react';
import ReactDOM from 'react-dom';
import { CompositeDisposable } from 'atom';
import AppView from './AppView';
import beaverDB from './helpers/db';
import { dBPath } from './config';
// console.log('Lib Versions: ');
// console.log(process.versions);
// process.env.NODE_ENV = 'development';
// NOTE: If enabled without any minified react error, it gives following error:
// "validateDOMNesting.updatedAncestorInfo is not a function"
// so, rather run atom in development mode (atom --dev) to get unminified react error
let INIT_CALLED = false;
export default {
db: null,
appView: null,
modalPanel: null,
subscriptions: null,
initialize(state) {
// initialize database with config
this.db = beaverDB.configure({ dBPath });
INIT_CALLED = true;
},
activate(state) {
if (!INIT_CALLED) {
this.initialize();
}
this.appView = new AppView(state.appViewState);
this.modalPanel = atom.workspace.addRightPanel({
item: this.appView,
visible: false
});
// Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
this.subscriptions = new CompositeDisposable();
// Register command that toggles this view
this.subscriptions.add(
atom.commands.add('atom-workspace', {
'beaver:toggle': () => this.toggle()
})
);
},
deactivate() {
this.modalPanel.destroy();
this.subscriptions.dispose();
this.appView.destroy();
},
serialize() {
// fetch data from db
return { appViewState: {} };
},
toggle() {
return this.modalPanel.isVisible()
? this.modalPanel.hide()
: this.modalPanel.show();
}
};
|
app/javascript/mastodon/features/compose/components/emoji_picker_dropdown.js | d6rkaiz/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
import { EmojiPicker as EmojiPickerAsync } from '../../ui/util/async-components';
import Overlay from 'react-overlays/lib/Overlay';
import classNames from 'classnames';
import ImmutablePropTypes from 'react-immutable-proptypes';
import detectPassiveEvents from 'detect-passive-events';
import { buildCustomEmojis, categoriesFromEmojis } from '../../emoji/emoji';
const messages = defineMessages({
emoji: { id: 'emoji_button.label', defaultMessage: 'Insert emoji' },
emoji_search: { id: 'emoji_button.search', defaultMessage: 'Search...' },
emoji_not_found: { id: 'emoji_button.not_found', defaultMessage: 'No emojos!! (╯°□°)╯︵ ┻━┻' },
custom: { id: 'emoji_button.custom', defaultMessage: 'Custom' },
recent: { id: 'emoji_button.recent', defaultMessage: 'Frequently used' },
search_results: { id: 'emoji_button.search_results', defaultMessage: 'Search results' },
people: { id: 'emoji_button.people', defaultMessage: 'People' },
nature: { id: 'emoji_button.nature', defaultMessage: 'Nature' },
food: { id: 'emoji_button.food', defaultMessage: 'Food & Drink' },
activity: { id: 'emoji_button.activity', defaultMessage: 'Activity' },
travel: { id: 'emoji_button.travel', defaultMessage: 'Travel & Places' },
objects: { id: 'emoji_button.objects', defaultMessage: 'Objects' },
symbols: { id: 'emoji_button.symbols', defaultMessage: 'Symbols' },
flags: { id: 'emoji_button.flags', defaultMessage: 'Flags' },
});
const assetHost = process.env.CDN_HOST || '';
let EmojiPicker, Emoji; // load asynchronously
const backgroundImageFn = () => `${assetHost}/emoji/sheet_10.png`;
const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false;
class ModifierPickerMenu extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
onSelect: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
};
handleClick = e => {
this.props.onSelect(e.currentTarget.getAttribute('data-index') * 1);
}
componentWillReceiveProps (nextProps) {
if (nextProps.active) {
this.attachListeners();
} else {
this.removeListeners();
}
}
componentWillUnmount () {
this.removeListeners();
}
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
attachListeners () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
removeListeners () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
render () {
const { active } = this.props;
return (
<div className='emoji-picker-dropdown__modifiers__menu' style={{ display: active ? 'block' : 'none' }} ref={this.setRef}>
<button onClick={this.handleClick} data-index={1}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={1} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={2}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={2} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={3}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={3} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={4}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={4} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={5}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={5} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={6}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={6} backgroundImageFn={backgroundImageFn} /></button>
</div>
);
}
}
class ModifierPicker extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
modifier: PropTypes.number,
onChange: PropTypes.func,
onClose: PropTypes.func,
onOpen: PropTypes.func,
};
handleClick = () => {
if (this.props.active) {
this.props.onClose();
} else {
this.props.onOpen();
}
}
handleSelect = modifier => {
this.props.onChange(modifier);
this.props.onClose();
}
render () {
const { active, modifier } = this.props;
return (
<div className='emoji-picker-dropdown__modifiers'>
<Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={modifier} onClick={this.handleClick} backgroundImageFn={backgroundImageFn} />
<ModifierPickerMenu active={active} onSelect={this.handleSelect} onClose={this.props.onClose} />
</div>
);
}
}
@injectIntl
class EmojiPickerMenu extends React.PureComponent {
static propTypes = {
custom_emojis: ImmutablePropTypes.list,
frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string),
loading: PropTypes.bool,
onClose: PropTypes.func.isRequired,
onPick: PropTypes.func.isRequired,
style: PropTypes.object,
placement: PropTypes.string,
arrowOffsetLeft: PropTypes.string,
arrowOffsetTop: PropTypes.string,
intl: PropTypes.object.isRequired,
skinTone: PropTypes.number.isRequired,
onSkinTone: PropTypes.func.isRequired,
};
static defaultProps = {
style: {},
loading: true,
frequentlyUsedEmojis: [],
};
state = {
modifierOpen: false,
placement: null,
};
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
componentDidMount () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
componentWillUnmount () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
getI18n = () => {
const { intl } = this.props;
return {
search: intl.formatMessage(messages.emoji_search),
notfound: intl.formatMessage(messages.emoji_not_found),
categories: {
search: intl.formatMessage(messages.search_results),
recent: intl.formatMessage(messages.recent),
people: intl.formatMessage(messages.people),
nature: intl.formatMessage(messages.nature),
foods: intl.formatMessage(messages.food),
activity: intl.formatMessage(messages.activity),
places: intl.formatMessage(messages.travel),
objects: intl.formatMessage(messages.objects),
symbols: intl.formatMessage(messages.symbols),
flags: intl.formatMessage(messages.flags),
custom: intl.formatMessage(messages.custom),
},
};
}
handleClick = emoji => {
if (!emoji.native) {
emoji.native = emoji.colons;
}
this.props.onClose();
this.props.onPick(emoji);
}
handleModifierOpen = () => {
this.setState({ modifierOpen: true });
}
handleModifierClose = () => {
this.setState({ modifierOpen: false });
}
handleModifierChange = modifier => {
this.props.onSkinTone(modifier);
}
render () {
const { loading, style, intl, custom_emojis, skinTone, frequentlyUsedEmojis } = this.props;
if (loading) {
return <div style={{ width: 299 }} />;
}
const title = intl.formatMessage(messages.emoji);
const { modifierOpen } = this.state;
const categoriesSort = [
'recent',
'people',
'nature',
'foods',
'activity',
'places',
'objects',
'symbols',
'flags',
];
categoriesSort.splice(1, 0, ...Array.from(categoriesFromEmojis(custom_emojis)).sort());
return (
<div className={classNames('emoji-picker-dropdown__menu', { selecting: modifierOpen })} style={style} ref={this.setRef}>
<EmojiPicker
perLine={8}
emojiSize={22}
sheetSize={32}
custom={buildCustomEmojis(custom_emojis)}
color=''
emoji=''
set='twitter'
title={title}
i18n={this.getI18n()}
onClick={this.handleClick}
include={categoriesSort}
recent={frequentlyUsedEmojis}
skin={skinTone}
showPreview={false}
backgroundImageFn={backgroundImageFn}
autoFocus
emojiTooltip
/>
<ModifierPicker
active={modifierOpen}
modifier={skinTone}
onOpen={this.handleModifierOpen}
onClose={this.handleModifierClose}
onChange={this.handleModifierChange}
/>
</div>
);
}
}
export default @injectIntl
class EmojiPickerDropdown extends React.PureComponent {
static propTypes = {
custom_emojis: ImmutablePropTypes.list,
frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string),
intl: PropTypes.object.isRequired,
onPickEmoji: PropTypes.func.isRequired,
onSkinTone: PropTypes.func.isRequired,
skinTone: PropTypes.number.isRequired,
};
state = {
active: false,
loading: false,
};
setRef = (c) => {
this.dropdown = c;
}
onShowDropdown = ({ target }) => {
this.setState({ active: true });
if (!EmojiPicker) {
this.setState({ loading: true });
EmojiPickerAsync().then(EmojiMart => {
EmojiPicker = EmojiMart.Picker;
Emoji = EmojiMart.Emoji;
this.setState({ loading: false });
}).catch(() => {
this.setState({ loading: false });
});
}
const { top } = target.getBoundingClientRect();
this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' });
}
onHideDropdown = () => {
this.setState({ active: false });
}
onToggle = (e) => {
if (!this.state.loading && (!e.key || e.key === 'Enter')) {
if (this.state.active) {
this.onHideDropdown();
} else {
this.onShowDropdown(e);
}
}
}
handleKeyDown = e => {
if (e.key === 'Escape') {
this.onHideDropdown();
}
}
setTargetRef = c => {
this.target = c;
}
findTarget = () => {
return this.target;
}
render () {
const { intl, onPickEmoji, onSkinTone, skinTone, frequentlyUsedEmojis } = this.props;
const title = intl.formatMessage(messages.emoji);
const { active, loading, placement } = this.state;
return (
<div className='emoji-picker-dropdown' onKeyDown={this.handleKeyDown}>
<div ref={this.setTargetRef} className='emoji-button' title={title} aria-label={title} aria-expanded={active} role='button' onClick={this.onToggle} onKeyDown={this.onToggle} tabIndex={0}>
<img
className={classNames('emojione', { 'pulse-loading': active && loading })}
alt='🙂'
src={`${assetHost}/emoji/1f602.svg`}
/>
</div>
<Overlay show={active} placement={placement} target={this.findTarget}>
<EmojiPickerMenu
custom_emojis={this.props.custom_emojis}
loading={loading}
onClose={this.onHideDropdown}
onPick={onPickEmoji}
onSkinTone={onSkinTone}
skinTone={skinTone}
frequentlyUsedEmojis={frequentlyUsedEmojis}
/>
</Overlay>
</div>
);
}
}
|
client/pages/Contribute/Contribute.js | b3j0f/lechangement | import './Contribute.css';
import React, { Component } from 'react';
class Contribute extends Component {
render() {
return <div>Contribute</div>;
}
}
export default Contribute;
|
webapp/app/components/SaveCreation/Form/Frequency/index.js | EIP-SAM/SAM-Solution-Node-js | //
// FrequencyFormGroup in form for page SaveCreation
//
import React from 'react';
import { FormGroup, ControlLabel, FormControl } from 'react-bootstrap';
import Option from 'components/Option';
import styles from 'components/SaveCreation/styles.css';
/* eslint-disable react/prefer-stateless-function */
export default class SaveCreationFrequency extends React.Component {
constructor(props) {
super(props);
this.handleFrequencyChange = this.handleFrequencyChange.bind(this);
}
componentWillMount() {
if (!this.props.frequency) {
this.props.frequencySave('No Repeat');
}
}
handleFrequencyChange(e) {
this.props.frequencySave(e.target.value);
}
render() {
return (
<FormGroup controlId="frequency" className={styles.form}>
<ControlLabel>Repeat</ControlLabel>
<FormControl componentClass="select" onChange={this.handleFrequencyChange} defaultValue="No Repeat">
<Option object={{ isActive: this.props.isFrequencyDisabled, value: 'No Repeat', text: 'No Repeat' }} key="item-0" />
<Option object={{ isActive: this.props.isFrequencyDisabled, value: 'Daily', text: 'Daily' }} key="item-1" />
<Option object={{ isActive: this.props.isFrequencyDisabled, value: 'Weekly', text: 'Weekly' }} key="item-2" />
<Option object={{ isActive: this.props.isFrequencyDisabled, value: 'Monthly', text: 'Monthly' }} key="item-3" />
</FormControl>
</FormGroup>
);
}
}
SaveCreationFrequency.propTypes = {
frequency: React.PropTypes.string,
isFrequencyDisabled: React.PropTypes.bool,
frequencySave: React.PropTypes.func,
};
|
examples/dom-bindings/src/index.js | elpic/react-pdf | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(<App />, document.getElementById('root'));
|
example/src/bits/Image.js | RafalFilipek/just-box | import React from 'react';
import { Image } from 'react-native';
import { Box } from 'just-box'
export default ({ src, ...rest }) => (
<Box
as={Image}
source={{uri: src}}
top={0}
left={0}
right={0}
bottom={0}
position="absolute"
style={{ resizeMode: 'cover' }}
{...rest}
/>
); |
fields/types/relationship/RelationshipColumn.js | snowkeeper/keystone | import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
const moreIndicatorStyle = {
color: '#bbb',
fontSize: '.8rem',
fontWeight: 500,
marginLeft: 8,
};
var RelationshipColumn = React.createClass({
displayName: 'RelationshipColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderMany (value) {
if (!value || !value.length) return;
const refList = this.props.col.field.refList;
const items = [];
for (let i = 0; i < 3; i++) {
if (!value[i]) break;
if (i) {
items.push(<span key={'comma' + i}>, </span>);
}
items.push(
<ItemsTableValue interior truncate={false} key={'anchor' + i} to={Keystone.adminPath + '/' + refList.path + '/' + value[i].id}>
{value[i].name}
</ItemsTableValue>
);
}
if (value.length > 3) {
items.push(<span key="more" style={moreIndicatorStyle}>[...{value.length - 3} more]</span>);
}
return (
<ItemsTableValue field={this.props.col.type}>
{items}
</ItemsTableValue>
);
},
renderValue (value) {
if (!value) return;
const refList = this.props.col.field.refList;
return (
<ItemsTableValue to={Keystone.adminPath + '/' + refList.path + '/' + value.id} padded interior field={this.props.col.type}>
{value.name}
</ItemsTableValue>
);
},
render () {
const value = this.props.data.fields[this.props.col.path];
const many = this.props.col.field.many;
return (
<ItemsTableCell>
{many ? this.renderMany(value) : this.renderValue(value)}
</ItemsTableCell>
);
},
});
module.exports = RelationshipColumn;
|
src/components/Navigation/Navigation.js | buildbreakdo/react-starter-kit | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import cx from 'classnames';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Navigation.css';
import Link from '../Link';
class Navigation extends React.Component {
render() {
return (
<div className={s.root} role="navigation">
<Link className={s.link} to="/about">
About
</Link>
<Link className={s.link} to="/contact">
Contact
</Link>
<span className={s.spacer}> | </span>
<Link className={s.link} to="/login">
Log in
</Link>
<span className={s.spacer}>or</span>
<Link className={cx(s.link, s.highlight)} to="/register">
Sign up
</Link>
</div>
);
}
}
export default withStyles(s)(Navigation);
|
app/app/components/AdminPanel/Products/EditProduct.js | lycha/masters-thesis | import React from 'react';
import bootstrap from 'bootstrap';
class EditProduct extends React.Component {
constructor(props) {
super(props);
this.displayName = 'EditProduct';
}
getQuery(e) {
e.preventDefault();
let product = {
id: this.refs.id.value,
name: this.refs.name.value,
description: this.refs.description.value,
slug: this.refs.slug.value
};
$("#editProductModal-"+product.id).modal('toggle');
this.props.updateProduct(product);
}
render() {
return (
<div className="modal fade"
id={"editProductModal-"+this.props.product.id}
tabindex="-1"
role="dialog"
aria-labelledby="myModalLabel"
aria-hidden="false">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button"
className="close"
data-dismiss="modal"
aria-hidden="true">×</button>
<h4 className="modal-title" id="myModalLabel">Edit Product</h4>
</div>
<div className="modal-body">
<form onSubmit={(e) => this.getQuery(e)}
acceptCharset="UTF-8"
className="form-horizontal style-form" id="edit-product">
<div>
<label htmlFor="id"> ID </label>
<input className="form-inline" name="id" type="number" id="id"
ref="id" disabled defaultValue={this.props.product.id}/>
</div>
<div>
<label htmlFor="name"> Name </label>
<input className="form-inline" name="name" type="text" id="name"
ref="name" defaultValue={this.props.product.name}/>
</div>
<div>
<label htmlFor="description"> Description </label>
<input className="form-inline" name="description" type="text" id="description"
ref="description" defaultValue={this.props.product.description}/>
</div>
<div>
<label htmlFor="slug"> URL Name </label>
<input className="form-inline" name="slug" type="text" id="slug"
pattern="[a-z0-9\\-]+"
title="Accepted only small letters, numbers and -"
ref="slug" defaultValue={this.props.product.slug}/>
</div>
<button className="btn btn-theme">Update</button>
</form>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
);
}
}
export default EditProduct;
|
browser/app/js/components/SideBar.js | dvstate/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 ClickOutHandler from 'react-onclickout'
import Scrollbars from 'react-custom-scrollbars/lib/Scrollbars'
import connect from 'react-redux/lib/components/connect'
import logo from '../../img/logo.svg'
let SideBar = ({visibleBuckets, loadBucket, currentBucket, selectBucket, searchBuckets, sidebarStatus, clickOutside, showPolicy}) => {
const list = visibleBuckets.map((bucket, i) => {
return <li className={ classNames({
'active': bucket === currentBucket
}) } key={ i } onClick={ (e) => selectBucket(e, bucket) }>
<a href="" className={ classNames({
'fesli-loading': bucket === loadBucket
}) }>
{ bucket }
</a>
<i className="fesli-trigger" onClick={ showPolicy }></i>
</li>
})
return (
<ClickOutHandler onClickOut={ clickOutside }>
<div className={ classNames({
'fe-sidebar': true,
'toggled': sidebarStatus
}) }>
<div className="fes-header clearfix hidden-sm hidden-xs">
<img src={ logo } alt="" />
<h2>Minio Browser</h2>
</div>
<div className="fes-list">
<div className="input-group ig-dark ig-left ig-search" style={ { display: web.LoggedIn() ? 'block' : 'none' } }>
<input className="ig-text"
type="text"
onChange={ searchBuckets }
placeholder="Search Buckets..." />
<i className="ig-helpers"></i>
</div>
<div className="fesl-inner">
<Scrollbars renderScrollbarVertical={ props => <div className="scrollbar-vertical" /> }>
<ul>
{ list }
</ul>
</Scrollbars>
</div>
</div>
<div className="fes-host">
<i className="fa fa-globe"></i>
<a href="/">
{ window.location.host }
</a>
</div>
</div>
</ClickOutHandler>
)
}
// Subscribe it to state changes that affect only the sidebar.
export default connect(state => {
return {
visibleBuckets: state.visibleBuckets,
loadBucket: state.loadBucket,
currentBucket: state.currentBucket,
sidebarStatus: state.sidebarStatus
}
})(SideBar)
|
internals/templates/containers/HomePage/index.js | vinhtran19950804/procure_react | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
resources/assets/js/components/admin/ListItemTeacher.js | jrm2k6/i-heart-reading | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { showModal } from '../../actions/modals/modalActions';
import { deleteTeacher } from '../../actions/admin/adminDashboardActions';
import UpdateTeacherModal from './modals/UpdateTeacherModal';
const mapStateToProps = (state) => {
return {
};
};
const mapDispatchToProps = (dispatch) => {
return {
showModal: (component, data) => {
dispatch(showModal(component, data));
},
deleteTeacher: (id) => {
dispatch(deleteTeacher(id));
}
};
};
class ListItemTeacher extends Component {
constructor(props) {
super(props);
this.state = {
hovering: false
};
}
render() {
const listItemOptions = (this.state.hovering) ? (
<div className='admin-list-item-option'>
<i className='material-icons admin-list-item-option-edit-icon'
onClick={() => { this.props.showModal(UpdateTeacherModal, {teacher: this.props.teacher}); }}
>
edit
</i>
<i className='material-icons admin-list-item-option-delete-icon'
onClick={() => { this.props.deleteTeacher(this.props.teacher.id); }}
>
delete
</i>
</div>
) : null;
return (
<div className='admin-list-item'
onMouseEnter={() => { this.setState({ hovering: true })}}
onMouseLeave={() => { this.setState({ hovering: false })}}
>
<span>{this.props.teacher.user.name}</span>
<span>{this.props.teacher.num_groups}</span>
{listItemOptions}
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ListItemTeacher)
|
examples/auth-with-shared-root/components/Logout.js | nvartolomei/react-router | import React from 'react'
import auth from '../utils/auth'
const Logout = React.createClass({
componentDidMount() {
auth.logout()
},
render() {
return <p>You are now logged out</p>
}
})
export default Logout
|
src/components/Header/Header.js | loganfreeman/react-is-fun | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Header.css';
import Link from '../Link';
import Navigation from '../Navigation';
import logoUrl from './logo-small.png';
function Header() {
return (
<div className={s.root}>
<div className={s.container}>
<Navigation className={s.nav} />
<Link className={s.brand} to="/">
<img src={logoUrl} width="38" height="38" alt="React" />
<span className={s.brandTxt}>React is fun</span>
</Link>
<div className={s.banner}>
<h1 className={s.bannerTitle}>React</h1>
<p className={s.bannerDesc}>Complex web apps made easy</p>
</div>
</div>
</div>
);
}
export default withStyles(s)(Header);
|
src/components/LabeledContainer.js | mikebarkmin/gestyled | import React from 'react';
import PropTypes from 'prop-types';
import withStyle from './Base';
const LabeledContainer = props =>
<div>
{props.children}
</div>;
LabeledContainer.propTypes = {
/** Label which will be used for the tab */
label: PropTypes.oneOfType([PropTypes.string, PropTypes.element])
};
export default withStyle(LabeledContainer);
|
src/js/Scroller/ScrollArea.js | AlejandroHerr/fotoxjs | // @flow
import React from 'react';
import Measure from 'react-measure';
import type { Dimensions } from './types';
type ScrollAreaProps = {
children: typeof React.Component,
height: number,
position: number,
styles: { [key: string]: string },
onMeasure: (Dimensions) => void,
};
const ScrollArea = ({
children: Children,
height,
position,
styles,
onMeasure }: ScrollAreaProps) => (
<Measure shouldMeasure={height !== 0} whitelist={['height', 'width']} onMeasure={onMeasure}>
<div
className={styles['scroll-area']}
style={{ transform: `translateX(-${position}%)` }}
>
<Children height={height} />
</div>
</Measure>);
export default ScrollArea;
|
app/containers/Wall.js | Salomari1987/client-wall-app | import React from 'react';
import Message from '../components/Message';
import MessageInput from '../components/MessageInput';
import WallStore from '../stores/WallStore';
import WallActions from '../actions/WallActions';
import ReactDOM from 'react-dom';
class Wall extends React.Component {
constructor(props) {
super(props);
this.state = WallStore.getState();
this.onChange = this.onChange.bind(this);
this._fetchMessages = this._fetchMessages.bind(this);
}
componentDidMount() {
WallStore.listen(this.onChange);
WallActions.getLoggedUser();
WallActions.getMessages();
this._fetchMessages();
setInterval(() => WallActions.updateMessagesTimes(), 300000);
}
_fetchMessages () {
socket.on('messageFetch', (d) => {
WallActions.getMessages();
});
}
componentWillUnmount() {
WallStore.unlisten(this.onChange);
}
componentDidUpdate() {
this.scrollToBottom();
}
onChange(state) {
this.setState(state);
}
scrollToBottom () {
const node = ReactDOM.findDOMNode(this.messagesEnd);
if (node) {
node.scrollIntoView({behavior: 'smooth'});
}
}
sendMessage(event) {
event.preventDefault();
WallActions.sendMessage(this.state);
}
render() {
var messages = this.state.messages.map((e, i) => {
return (
<Message ref={(el) => { this.messagesEnd = el; }} author={e.author} body={e.body} ago={e.ago} key={i.toString()} />
);
});
var input = this.state.token ? <MessageInput sendMessage={this.sendMessage.bind(this)} updateMessage={WallActions.updateMessage}/> : null;
return (
<div className={'container' + this.props.wallContainer}>
<div className="row">
<div className="col-md-12">
<div className="panel panel-default">
<div className='panel-body' id={this.props.chatHeight}>
<ul className="chat">
{messages}
</ul>
</div>
{!this.props.input && input}
</div>
</div>
</div>
</div>
);
}
}
export default Wall; |
client/src/components/Admin/AdminSidebar.js | hutchgrant/react-boilerplate | import _ from 'lodash';
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import MyRoutes from './adminRoutes';
import $ from 'jquery';
const ResizeSensor = require('css-element-queries/src/ResizeSensor.js');
const EQ = require('css-element-queries/src/ElementQueries.js');
EQ.init();
class AdminSidebar extends Component {
componentDidMount() {
this.updateWindow();
new ResizeSensor($('.main'), () =>{
this.updateWindow();
});
}
updateWindow() {
let height3 = $( window ).height()-51;
let height1 = $('.nav').height();
let height2 = $('.main').height();
let width = $(window).width();
if(height2 > height3){
$('.sidebar').height(Math.max(height1,height3,height2)+10);
}else{
$('.sidebar').height(Math.max(height1,height3,height2));
}
if(width < 768){
$('.sidebar').removeAttr('style');
}
}
renderMenuList() {
return _.map(MyRoutes.admin, ({name, path, icon}, index) => {
return <li key={index}
className={index === 0 ? "active" : ''}>
<Link to={path}>
{name}
<span style={{fontSize:'16px'}}
className={`pull-right hidden-xs showopacity ${icon}`}>
</span>
</Link>
</li>;
});
}
renderSideBar() {
return <nav className="navbar navbar-sidebar sidebar">
<div className="container-fluid">
<div className="collapse navbar-collapse" id="bs-sidebar-navbar-collapse-1">
<ul className="nav navbar-nav">
{this.renderMenuList()}
<li className="dropdown">
<a className="dropdown-toggle" data-toggle="dropdown">Settings <span className="caret"></span><span style={{fontSize:'16px'}} className="pull-right hidden-xs showopacity glyphicon glyphicon-cog"></span></a>
<ul className="dropdown-menu" role="menu">
<li><Link to='/admin'>Action</Link></li>
<li><Link to='/admin'>Another action</Link></li>
<li><Link to='/admin'>Something else</Link></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
}
render() {
return (
<div className="sidebar">
{this.renderSideBar()}
</div>
);
}
}
export default AdminSidebar; |
react-flux-mui/js/material-ui/docs/src/app/components/pages/components/DatePicker/Page.js | pbogdan/react-flux-mui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import datePickerReadmeText from './README';
import DatePickerExampleSimple from './ExampleSimple';
import datePickerExampleSimpleCode from '!raw!./ExampleSimple';
import DatePickerExampleInline from './ExampleInline';
import datePickerExampleInlineCode from '!raw!./ExampleInline';
import DatePickerExampleToggle from './ExampleToggle';
import datePickerExampleToggleCode from '!raw!./ExampleToggle';
import DatePickerExampleControlled from './ExampleControlled';
import datePickerExampleControlledCode from '!raw!./ExampleControlled';
import DatePickerExampleDisableDates from './ExampleDisableDates';
import datePickerExampleDisableDatesCode from '!raw!./ExampleDisableDates';
import DatePickerExampleInternational from './ExampleInternational';
import datePickerExampleInternationalCode from '!raw!./ExampleInternational';
import datePickerCode from '!raw!material-ui/DatePicker/DatePicker';
const DatePickerPage = () => (
<div>
<Title render={(previousTitle) => `Date Picker - ${previousTitle}`} />
<MarkdownElement text={datePickerReadmeText} />
<CodeExample
title="Simple examples"
code={datePickerExampleSimpleCode}
>
<DatePickerExampleSimple />
</CodeExample>
<CodeExample
title="Inline examples"
code={datePickerExampleInlineCode}
>
<DatePickerExampleInline />
</CodeExample>
<CodeExample
title="Ranged example"
code={datePickerExampleToggleCode}
>
<DatePickerExampleToggle />
</CodeExample>
<CodeExample
title="Controlled example"
code={datePickerExampleControlledCode}
>
<DatePickerExampleControlled />
</CodeExample>
<CodeExample
title="Disabled dates example"
code={datePickerExampleDisableDatesCode}
>
<DatePickerExampleDisableDates />
</CodeExample>
<CodeExample
title="Localised example"
code={datePickerExampleInternationalCode}
>
<DatePickerExampleInternational />
</CodeExample>
<PropTypeDescription code={datePickerCode} />
</div>
);
export default DatePickerPage;
|
test/helpers/shallowRenderHelper.js | pptp/tile-calc | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
src/js/components/Grommet/stories/Messages.js | HewlettPackard/grommet | import React from 'react';
import { Box, FileInput, Form, FormField, Grommet, Heading } from 'grommet';
const messageBundle = {
'form.required': '必填项目',
'fileInput.browse': '浏览',
};
const customMessages = {
messages: {
form: {
required: 'necesario',
},
fileInput: {
browse: 'navegar',
},
},
};
export const Messages = () => (
<>
<Grommet messages={customMessages}>
<Heading level={2}>Custom messages</Heading>
<Box width="medium">
<Form validate="blur">
<FormField name="name" label="Name" required />
<FileInput />
</Form>
</Box>
</Grommet>
<Grommet
messages={{
format: (options) => messageBundle[options.id],
}}
>
<Heading level={2}>Message function</Heading>
<Box width="medium">
<Form validate="blur">
<FormField name="name" label="Name" required />
<FileInput />
</Form>
</Box>
</Grommet>
</>
);
export default {
title: 'Utilities/Grommet/Messages',
};
|
src/mixins/controllable.js | tyfoo/material-ui | import React from 'react';
export default {
propTypes: {
onChange: React.PropTypes.func,
value: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.array,
]),
valueLink: React.PropTypes.shape({
value: React.PropTypes.string.isRequired,
requestChange: React.PropTypes.func.isRequired,
}),
},
getDefaultProps() {
return {
onChange: () => {},
};
},
getValueLink(props) {
return props.valueLink || {
value: props.value,
requestChange: props.onChange,
};
},
};
|
examples/parameterized-routing/pages/blog.js | BlancheXu/test | import React from 'react'
export default class extends React.Component {
static getInitialProps ({ query: { id } }) {
return { id }
}
render () {
return (
<div>
<h1>My {this.props.id} blog post</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</div>
)
}
}
|
client/src/components/utils/FormActions.js | DjLeChuck/recalbox-manager | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
class FormActions extends Component {
static propTypes = {
t: PropTypes.func.isRequired,
reset: PropTypes.func.isRequired,
isSaving: PropTypes.bool.isRequired,
};
static defaultProps = {
isSaving: false,
};
render() {
const { t } = this.props;
return (
<p>
<Button bsStyle="danger" onClick={this.props.reset}>
{t('Annuler')}
</Button>{" "}
<Button bsStyle="success" type="submit" disabled={this.props.isSaving}>
{this.props.isSaving &&
<Glyphicon glyph="refresh" className="glyphicon-spin" />
} {t('Enregistrer')}
</Button>
</p>
);
}
}
export default translate()(FormActions);
|
modules/server.js | yuanziyuer/yuanzi-share | import http from 'http';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import fs from 'fs';
import { createPage, write, writeError, writeNotFound, redirect } from './utils/server-utils';
import routes from './routes/RootRoute';
const webpack = require('webpack');
const config = require('../webpack.config');
var express = require('express');
var app = express();
const compiler = webpack(config[1]);
function renderApp(props, res) {
const markup = renderToString(<RouterContext {...props}/>);
const html = createPage(markup);
write(html, 'text/html', res);
}
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: '__build__',
stats: {
colors: true
}
}));
app.use(require('webpack-hot-middleware')(compiler));
// Do anything you like with the rest of your express application.
app.get('*', function(req, res) {
if (req.url === '/favicon.ico') {
write('haha', 'text/plain', res);
}
// serve JavaScript assets
else if (/__build__/.test(req.url)) {
fs.readFile(`.${req.url}`, (err, data) => {
var ext = req.url.split('.').pop();
var contentTypeMap = {
'js': 'text/javascript',
'css': 'text/css'
};
write(data, contentTypeMap[ext] || '', res);
});
}
// handle all other urls with React Router
else {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
if(error){
writeError('ERROR!', res);
}
else if(redirectLocation){
redirect(redirectLocation, res);
}
else if(renderProps){
renderApp(renderProps, res);
}
else{
writeNotFound(res);
}
});
}
});
var server = http.createServer(app);
server.listen(process.env.PORT || 3000, function() {
console.log('Listening on %j', server.address());
});
|
studenttable/src/index.js | balaSpyrus/wave11 | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {Provider} from 'react-redux';
import {createStore, combineReducers} from 'redux';
import registerServiceWorker from './registerServiceWorker';
import dataReducer from './reducers/datareducer';
const allreducers=combineReducers({
data:dataReducer
})
const store= createStore(allreducers);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
registerServiceWorker();
|
src/containers/NotFound/NotFound.js | Shenseye/fccpinterest | import React from 'react';
export default function NotFound() {
return (
<div className="container">
<h1>Doh! 404!</h1>
<p>These are <em>not</em> the droids you are looking for!</p>
</div>
);
}
|
addons/knobs/src/components/WrapStory.js | nfl/react-storybook | /* eslint no-underscore-dangle: 0 */
import PropTypes from 'prop-types';
import React from 'react';
export default class WrapStory extends React.Component {
constructor(props) {
super(props);
this.knobChanged = this.knobChanged.bind(this);
this.resetKnobs = this.resetKnobs.bind(this);
this.setPaneKnobs = this.setPaneKnobs.bind(this);
this._knobsAreReset = false;
this.state = { storyContent: this.props.initialContent };
}
componentDidMount() {
// Watch for changes in knob editor.
this.props.channel.on('addon:knobs:knobChange', this.knobChanged);
// Watch for the reset event and reset knobs.
this.props.channel.on('addon:knobs:reset', this.resetKnobs);
// Watch for any change in the knobStore and set the panel again for those
// changes.
this.props.knobStore.subscribe(this.setPaneKnobs);
// Set knobs in the panel for the first time.
this.setPaneKnobs();
}
componentWillReceiveProps(props) {
this.setState({ storyContent: props.initialContent });
}
componentWillUnmount() {
this.props.channel.removeListener('addon:knobs:knobChange', this.knobChanged);
this.props.channel.removeListener('addon:knobs:reset', this.resetKnobs);
this.props.knobStore.unsubscribe(this.setPaneKnobs);
}
setPaneKnobs(timestamp = +new Date()) {
const { channel, knobStore } = this.props;
channel.emit('addon:knobs:setKnobs', { knobs: knobStore.getAll(), timestamp });
}
knobChanged(change) {
const { name, value } = change;
const { knobStore, storyFn, context } = this.props;
// Update the related knob and it's value.
const knobOptions = knobStore.get(name);
knobOptions.value = value;
knobStore.markAllUnused();
this.setState({ storyContent: storyFn(context) });
}
resetKnobs() {
const { knobStore, storyFn, context } = this.props;
knobStore.reset();
this.setState({ storyContent: storyFn(context) });
this.setPaneKnobs(false);
}
render() {
return this.state.storyContent;
}
}
WrapStory.defaultProps = {
context: {},
initialContent: {},
storyFn: context => context,
};
WrapStory.propTypes = {
context: PropTypes.object, // eslint-disable-line react/forbid-prop-types
storyFn: PropTypes.func,
channel: React.PropTypes.shape({
on: PropTypes.func,
removeListener: PropTypes.func,
}).isRequired,
knobStore: PropTypes.shape({
channel: PropTypes.func,
get: PropTypes.func,
getAll: PropTypes.func,
markAllUnused: PropTypes.func,
reset: PropTypes.func,
subscribe: PropTypes.func,
unsubscribe: PropTypes.func,
}).isRequired,
initialContent: PropTypes.object, // eslint-disable-line react/forbid-prop-types
};
|
docs/src/app/components/pages/components/Slider/Page.js | spiermar/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import sliderReadmeText from './README';
import SliderExampleSimple from './ExampleSimple';
import sliderExampleSimpleCode from '!raw!./ExampleSimple';
import SliderExampleDisabled from './ExampleDisabled';
import sliderExampleDisabledCode from '!raw!./ExampleDisabled';
import SliderExampleStep from './ExampleStep';
import sliderExampleStepCode from '!raw!./ExampleStep';
import SliderExampleControlled from './ExampleControlled';
import sliderExampleControlledCode from '!raw!./ExampleControlled';
import sliderCode from '!raw!material-ui/Slider/Slider';
const descriptions = {
simple: 'The `defaultValue` property sets the initial position of the slider. The slider appearance changes when ' +
'not at the starting position.',
stepped: 'By default, the slider is continuous. The `step` property causes the slider to move in discrete ' +
'increments.',
value: 'The slider bar can have a set minimum and maximum, and the value can be ' +
'obtained through the value parameter fired on an onChange event.',
};
const SliderPage = () => (
<div>
<Title render={(previousTitle) => `Slider - ${previousTitle}`} />
<MarkdownElement text={sliderReadmeText} />
<CodeExample
title="Simple examples"
description={descriptions.simple}
code={sliderExampleSimpleCode}
>
<SliderExampleSimple />
</CodeExample>
<CodeExample
title="Disabled examples"
code={sliderExampleDisabledCode}
>
<SliderExampleDisabled />
</CodeExample>
<CodeExample
title="Stepped example"
description={descriptions.stepped}
code={sliderExampleStepCode}
>
<SliderExampleStep />
</CodeExample>
<CodeExample
title="Controlled Examples"
description={descriptions.value}
code={sliderExampleControlledCode}
>
<SliderExampleControlled />
</CodeExample>
<PropTypeDescription code={sliderCode} />
</div>
);
export default SliderPage;
|
internals/templates/utils/injectSaga.js | mxstbr/react-boilerplate | import React from 'react';
import hoistNonReactStatics from 'hoist-non-react-statics';
import { ReactReduxContext } from 'react-redux';
import getInjectors from './sagaInjectors';
/**
* Dynamically injects a saga, passes component's props as saga arguments
*
* @param {string} key A key of the saga
* @param {function} saga A root saga that will be injected
* @param {string} [mode] By default (constants.DAEMON) the saga will be started
* on component mount and never canceled or started again. Another two options:
* - constants.RESTART_ON_REMOUNT — the saga will be started on component mount and
* cancelled with `task.cancel()` on component unmount for improved performance,
* - constants.ONCE_TILL_UNMOUNT — behaves like 'RESTART_ON_REMOUNT' but never runs it again.
*
*/
export default ({ key, saga, mode }) => WrappedComponent => {
class InjectSaga extends React.Component {
static WrappedComponent = WrappedComponent;
static contextType = ReactReduxContext;
static displayName = `withSaga(${WrappedComponent.displayName ||
WrappedComponent.name ||
'Component'})`;
constructor(props, context) {
super(props, context);
this.injectors = getInjectors(context.store);
this.injectors.injectSaga(key, { saga, mode }, this.props);
}
componentWillUnmount() {
this.injectors.ejectSaga(key);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return hoistNonReactStatics(InjectSaga, WrappedComponent);
};
const useInjectSaga = ({ key, saga, mode }) => {
const context = React.useContext(ReactReduxContext);
React.useEffect(() => {
const injectors = getInjectors(context.store);
injectors.injectSaga(key, { saga, mode });
return () => {
injectors.ejectSaga(key);
};
}, []);
};
export { useInjectSaga };
|
examples/FacebookTabsExample/SimpleExample.js | iancanderson/react-native-scrollable-tab-view | import React from 'react';
import {
Text,
} from 'react-native';
import ScrollableTabView, {DefaultTabBar, } from 'react-native-scrollable-tab-view';
export default React.createClass({
render() {
return <ScrollableTabView
style={{marginTop: 20, }}
renderTabBar={() => <DefaultTabBar />}
>
<Text tabLabel='Tab #1'>My</Text>
<Text tabLabel='Tab #2'>favorite</Text>
<Text tabLabel='Tab #3'>project</Text>
</ScrollableTabView>;
},
});
|
src/Toolbar/LocationSearch.js | woutervh-/cancun-react | import {IconButton, Input, List, ListItem} from 'react-toolbox';
import classNames from 'classnames';
import React from 'react';
import style from './style';
import {Autocomplete} from './Autocomplete';
import Geocoding from '../Geocoding';
import shallowEqual from 'shallowequal';
export default class LocationSearch extends React.Component {
constructor() {
super();
this.shouldComponentUpdate = this.shouldComponentUpdate.bind(this);
this.isCoordinate = this.isCoordinate.bind(this);
this.matchesForCoordinateQuery = this.matchesForCoordinateQuery.bind(this);
this.matchesForFreeTextQuery = this.matchesForFreeTextQuery.bind(this);
this.updateCurrentQuery = this.updateCurrentQuery.bind(this);
this.handleUpdateInput = this.handleUpdateInput.bind(this);
this.handleInputSubmit = this.handleInputSubmit.bind(this);
this.handleClearClick = this.handleClearClick.bind(this);
this.requestingQuery = '';
this.currentQuery = '';
}
static propTypes = {
sendRequestTimeout: React.PropTypes.number.isRequired,
onSubmit: React.PropTypes.func.isRequired,
onClear: React.PropTypes.func.isRequired
};
static defaultProps = {
sendRequestTimeout: 250,
onSubmit: () => {
},
onClear: () => {
}
};
state = {
results: [],
error: ''
};
shouldComponentUpdate(nextProps, nextState) {
return !(shallowEqual(this.props, nextProps) && shallowEqual(this.state, nextState));
}
isCoordinate(query) {
return /-?\d+(\.\d+)?,\s*-?\d+(\.\d+)?$/.test(query);
}
matchesForCoordinateQuery(query, callback) {
let match = /(-?\d+(\.\d+)?),\s*(-?\d+(\.\d+)?)$/.exec(query);
callback(null, [{location: query, isCoordinate: true, latitude: parseFloat(match[1]), longitude: parseFloat(match[3])}]);
}
matchesForFreeTextQuery(query, callback) {
Geocoding.forwardGeocode(query, (error, results) => {
if (!error) {
callback(error, results.map(result => ({location: result['formattedAddress'], isCoordinate: false, latitude: result['latitude'], longitude: result['longitude']})));
} else {
callback(error, []);
}
});
}
updateCurrentQuery(query, callback, timeout = this.props.sendRequestTimeout) {
let queryMethod;
if (this.isCoordinate(query)) {
timeout = 0;
queryMethod = this.matchesForCoordinateQuery;
} else {
queryMethod = this.matchesForFreeTextQuery;
}
this.requestingQuery = query;
setTimeout(() => {
if (this.requestingQuery == query && this.currentQuery != query) {
this.currentQuery = query;
queryMethod(query, (error, results) => {
if (this.requestingQuery == query) {
this.setState({error, results});
if (!!callback) {
callback(error, results);
}
}
});
} else if (this.requestingQuery == query) {
if (!!callback) {
callback(this.state.error, this.state.results);
}
}
}, timeout);
}
handleUpdateInput(query) {
this.setState({error: ''});
if (query.length > 0) {
this.updateCurrentQuery(query);
}
}
handleInputSubmit(query, index) {
if (query.length > 0) {
if (index >= 0) {
this.props.onSubmit(this.state.results[index]);
} else {
this.updateCurrentQuery(query, (error, results)=> {
if (results.length > 0) {
this.props.onSubmit(results[0]);
} else {
this.setState({error: 'No results found'});
}
}, 0);
}
}
}
handleClearClick() {
this.setState({results: [], error: ''});
this.refs.autocomplete.clear();
this.props.onClear();
}
render() {
return <span>
<Autocomplete
ref="autocomplete"
error={this.state.error}
label="Enter location"
suggestions={this.state.results.map(result => result.location)}
onUpdateInput={this.handleUpdateInput}
onInputSubmit={this.handleInputSubmit}
className={style['inline-block']}/>
<IconButton icon="clear" type="button" onClick={this.handleClearClick} className={style['toolbar-item']}/>
</span>;
}
};
|
app/src/components/NoteToolbar.js | zhanglun/fist | import React, { Component } from 'react';
// https://github.com/olahol/react-tagsinput/blob/master/src/index.js
class NoteToolbarComponent extends Component {
constructor(props) {
super(props);
this.state = {
tags: props.tags,
}
}
_addTags(tag) {
let { tags } = this.state;
let {maxTags} = this.props;
let notExist = tags.every((key) => {
return key != tag;
});
let remainLimit = null;
if(maxTags >= 0) {
remainLimit = tags.length < maxTags;
}
if (notExist && remainLimit) {
tags.push(tag);
this.setState({ tags });
}
this.refs.input.value = '';
this.props.onChange('add', tag, tags);
}
_removeTags(tag) {
let { tags } = this.state;
let removed = null;
if (tag) {
removed = tags.splice(tags.indexOf(tag), 1);
} else {
removed = tags.pop();
}
this.setState({
tags,
});
this.props.onChange('remove', removed, tags);
}
handleRemove(tag) {
this._removeTags(tag);
}
handleKeyDown(event) {
if (!event.target.value && event.keyCode == 8) {
this._removeTags();
}
if (event.target.value && event.keyCode == 13) {
let value = event.target.value;
this._addTags(value);
}
}
renderInput(props) {
// let {onChange, value, ...other} = props;
return (
<input ref="input" type='text' {...props} />
)
}
renderTags(props) {
let { tags } = this.state;
let {
onRemove, tagProps,
} = props;
return tags.map((key) => {
return <span key={key} className={tagProps.className}>{key}
<a className={tagProps.classNameRemove} onClick={(e) => onRemove(key)}>×</a>
</span>;
})
}
render() {
let { tagProps } = this.props;
let inputComponent = this.renderInput({
onKeyDown: this.handleKeyDown.bind(this)
});
let tagsComponent = this.renderTags({
onRemove: this.handleRemove.bind(this),
tagProps,
});
return (
<div className="note-toolbar">
<div className="note-tags-container">
{tagsComponent}
{inputComponent}
</div>
</div>
)
}
}
NoteToolbarComponent.defaultProps = {
className: 'tagsinput',
focusedClassName: 'tagsinput--focused',
tagProps: { className: 'tagsinput-tag', classNameRemove: 'tagsinput-remove' },
inputProps: {
className: 'tagsinput-input',
placeholder: 'Add a tag'
},
};
export default NoteToolbarComponent
|
src/svg-icons/action/date-range.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionDateRange = (props) => (
<SvgIcon {...props}>
<path d="M9 11H7v2h2v-2zm4 0h-2v2h2v-2zm4 0h-2v2h2v-2zm2-7h-1V2h-2v2H8V2H6v2H5c-1.11 0-1.99.9-1.99 2L3 20c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H5V9h14v11z"/>
</SvgIcon>
);
ActionDateRange = pure(ActionDateRange);
ActionDateRange.displayName = 'ActionDateRange';
ActionDateRange.muiName = 'SvgIcon';
export default ActionDateRange;
|
src/docs/components/AppDoc.js | grommet/grommet-docs | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import App from 'grommet/components/App';
import Box from 'grommet/components/Box';
import Split from 'grommet/components/Split';
import Sidebar from 'grommet/components/Sidebar';
import Article from 'grommet/components/Article';
import Header from 'grommet/components/Header';
import Footer from 'grommet/components/Footer';
import Section from 'grommet/components/Section';
import Anchor from 'grommet/components/Anchor';
import DocsArticle from '../../components/DocsArticle';
import Code from '../../components/Code';
App.displayName = 'App';
export default class AppDoc extends Component {
constructor () {
super();
this.state = { priority: 'right' };
}
render () {
const { priority } = this.state;
return (
<DocsArticle title='App'>
<section>
<p>This is the primary Grommet container outer. Typically it will
either contain a <Anchor path='/docs/split'>Split</Anchor> or
an <Anchor path='/docs/article'>Article</Anchor>.</p>
<Box pad={{ between: 'large' }} direction='column'>
<Split fixed={false} flex='right' priority={priority}>
<Sidebar full={false}>
<Box pad='large' colorIndex='grey-5'
justify='center' align='center'
onClick={() => this.setState({ priority: 'right' })}>
Sidebar
</Box>
</Sidebar>
<Box pad='large' colorIndex='light-2'
justify='center' align='center'
onClick={() => this.setState({ priority: 'left' })}>
Main content
</Box>
</Split>
<Article colorIndex='light-2'>
<Header colorIndex='grey-5' justify='center' align='center'>
Header
</Header>
<Section pad='large' justify='center' align='center'>
Sections
</Section>
<Footer colorIndex='grey-5' justify='center' align='center'>
Footer
</Footer>
</Article>
</Box>
</section>
<section>
<h2>Properties</h2>
<dl>
<dt><code>centered true|false</code></dt>
<dd>Whether to centralize or not the content inside the container.
Defaults to true.</dd>
<dt><code>inline true|false</code></dt>
<dd> Whether to render the app relative to the container (inline) or
to the browser window. Defaults to false.</dd>
</dl>
</section>
<section>
<h2>Usage</h2>
<Code preamble={`import App from 'grommet/components/App';`}>
<App>
{'{contents}'}
</App>
</Code>
</section>
</DocsArticle>
);
}
};
|
src/views/Button/index.js | pnicolli/demo-calculator | import React from 'react';
import { func, string } from 'prop-types';
import './styles.css';
const Button = ({
className,
onClick,
text,
}) => (
<button
className={'button'.concat(className ? ` ${className}` : '')}
onClick={onClick}
>
<span>{text}</span>
</button>
);
Button.propTypes = {
className: string,
onClick: func,
text: string,
};
export default Button;
|
app/javascript/mastodon/features/reblogs/index.js | pixiv/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import { fetchReblogs } from '../../actions/interactions';
import { ScrollContainer } from 'react-router-scroll-4';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import ColumnBackButton from '../../components/column_back_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'reblogged_by', props.params.statusId]),
});
@connect(mapStateToProps)
export default class Reblogs extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
};
componentWillMount () {
this.props.dispatch(fetchReblogs(this.props.params.statusId));
}
componentWillReceiveProps(nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this.props.dispatch(fetchReblogs(nextProps.params.statusId));
}
}
render () {
const { accountIds } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
return (
<Column>
<ColumnBackButton />
<ScrollContainer scrollKey='reblogs'>
<div className='scrollable reblogs'>
{accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)}
</div>
</ScrollContainer>
</Column>
);
}
}
|
src/parser/hunter/beastmastery/modules/talents/DireBeast.js | sMteX/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import { formatPercentage } from 'common/format';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import ResourceIcon from 'common/ResourceIcon';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import { encodeTargetString } from 'parser/shared/modules/EnemyInstances';
import ItemDamageDone from 'interface/others/ItemDamageDone';
/**
* Summons a powerful wild beast that attacks the target and roars, increasing your Haste by 5% for 8 sec.
*
* Example log: https://www.warcraftlogs.com/reports/jV7BJPN81AqtDKYp#fight=9&source=167&type=damage-done
*/
const HASTE_PERCENT = 0.05;
const SCENT_OF_BLOOD_FOCUS_INCREASE = 2;
const BASELINE_DIRE_BEAST_REGEN = 10;
class DireBeast extends Analyzer {
focusGained = 0;
focusWasted = 0;
damage = 0;
activeDireBeasts = [];
targetId = null;
hasSoB = false;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.DIRE_BEAST_TALENT.id);
this.hasSoB = this.selectedCombatant.hasTalent(SPELLS.SCENT_OF_BLOOD_TALENT.id);
}
get uptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.DIRE_BEAST_BUFF.id) / this.owner.fightDuration;
}
on_toPlayer_energize(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.DIRE_BEAST_GENERATOR.id) {
return;
}
if (!this.hasSoB) {
this.focusGained += event.resourceChange - event.waste;
this.focusWasted += event.waste;
return;
}
if (event.waste <= BASELINE_DIRE_BEAST_REGEN) { //We waste less than the baseline regen, so we can subtract the Scent of Blood bonus
this.focusGained += event.resourceChange - event.waste - SCENT_OF_BLOOD_FOCUS_INCREASE;
}
if (event.waste >= SCENT_OF_BLOOD_FOCUS_INCREASE) {
this.focusWasted += event.waste - SCENT_OF_BLOOD_FOCUS_INCREASE;
}
}
on_byPlayerPet_damage(event) {
const sourceId = encodeTargetString(event.sourceID, event.sourceInstance);
if (this.activeDireBeasts.includes(sourceId)) {
this.damage += event.amount + (event.absorbed || 0);
}
}
on_byPlayer_summon(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.DIRE_BEAST_SECONDARY_WITH_SCENT.id && spellId !== SPELLS.DIRE_BEAST_SECONDARY_WITHOUT_SCENT.id) {
return;
}
this.targetId = encodeTargetString(event.targetID, event.targetInstance);
this.activeDireBeasts = [];
this.activeDireBeasts.push(this.targetId);
this.targetId = null;
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.DIRE_BEAST_TALENT.id}
value={<>
<ItemDamageDone amount={this.damage} /> <br />
gained {formatPercentage(HASTE_PERCENT * this.uptime)}% Haste <br />
gained {this.focusGained} Focus <ResourceIcon id={RESOURCE_TYPES.FOCUS.id} />
</>}
tooltip={(
<>
You had {formatPercentage(this.uptime)}% uptime on the Dire Beast Haste buff. <br />
You wasted {this.focusWasted} Focus by being too close to Focus cap when Dire Beast gave you Focus.
</>
)}
/>
);
}
}
export default DireBeast;
|
src/component/layout/SideBar.js | babizhu/webApp | /**
* 可伸缩,自适应边栏
*
* 此边栏有两种显示模式
* iconMode 只显示图标
* normal 正常模式
*
* 另外还有个miniMode的显示模式,用于处理此sidebar的显示宽度,当屏幕宽度太小,
* 如手机等设备时,需要强制显示模式为正常模式,并100%屏幕宽度
*
* 此边栏有两种选择模式
* one 每次只允许展开一个子菜单
* muti 允许展开多个子菜单
*
* 问题:
* 当显示模式为iconMode的时候,如果采用muti的选择模式,会感觉有点奇怪(可模拟自行测试),目前未处理
*
*
* Created by liu_kun on 2015/12/3.
*/
import React, { Component } from 'react';
import ReactDom from "react-dom"
import { Steps,Menu, Dropdown, Button, Icon } from 'antd';
import SideBarItem from './SideBarItem';
import SideBarUserItem from './SideBarUserItem';
import '../../css/layout/sidebar.scss'
class SideBar extends Component {
/**
* 缺省情况下,采用正常显示模式加上单选择模式
*/
constructor() {
super();
}
state = {
/**
* 当前被选中的大项
*/
currentIndex: [],
/**
* 当前大项下被选中的具体子菜单
*/
currentSubMenuItemIndex: -1,
selectMode : 'one',//muti,one
};
/**
* 设置该显示那个显示子菜单,这里有两种模式
* 1、每次仅显示一个菜单展开 one
* 2、每次可显示多个菜单展开 muti
*
* @param index
* @param clickOnChild 如果点击的是子节点,不应该收起父菜单
*/
showSubMenu(index, clickOnChild = false ) {
let currentMenuArr = this.state.currentIndex;
if(this.state.selectMode === 'one' ){
currentMenuArr.splice( 0, currentMenuArr.length, index );
}else {
//console.log('clickOnChild='+ clickOnChild)
let pos = currentMenuArr.indexOf(index);
if ( pos !== -1 ) {
if( clickOnChild === false ){
currentMenuArr.splice(pos, 1);
}
} else {
currentMenuArr.push(index);
}
}
this.setState({currentIndex: currentMenuArr});
}
/**
* 点击具体子菜单后触发的动作,通常用于页面跳转或路由(单页面应用程序)
* @param subMenuItem
*/
onClickSubMenuItem(subMenuItem,parent) {
this.setState({currentSubMenuItemIndex: subMenuItem.index});
this.showSubMenu(parent.index, true);
console.log("当前点击的条目为 " +subMenuItem.text + " index=" + subMenuItem.index + " 组件=" + subMenuItem.component);
}
render() {
let userData = {
photoUrl: 'img/face11.jpg',
name: '刘老爷',
address: '中国 重庆市 南岸区'
};
let items = [{
text: '主菜单',
icon: 'ellipsis',
menu: [
{
icon: 'home',
text: '个人门户',
index: 1
}, {
icon: 'desktop',
text: '行政管理',
index: 2,
subMenu: [
{
icon: 'phone',
text: '会议管理',
index: 1,
component: 'app'
},
{
icon: 'book',
text: '设备管理',
index: 2,
component: 'flex'
}
]
},
{
icon: 'folder',
text: '基础管理',
index: 3,
subMenu: [
{
icon: 'user',
text: '用户管理',
index: 3,
component: 'nav'
}
]
}
]
}, {
text: '基础数据',
icon: 'ellipsis',
menu: [
{
icon: 'calendar',
text: '表单管理',
index: 4,
subMenu: [
{
icon: 'phone',
text: '基础数据',
index: 4
},
{
icon: 'book',
text: '我的表单',
index: 5
}
]
}
]
}, {
text: '杂项设置',
icon: 'ellipsis',
menu: [
{
icon: 'shrink',
text: '测试模块',
index: 5,
subMenu: [
{
icon: 'phone',
text: 'assign 测试',
index: 6,
component: 'test'
}
]
}
]
}];
let {miniMode,iconMode,show,selectMode} = this.props;
this.state.selectMode = selectMode;
let widthValue = '';
let showValue = '';
if (miniMode) {
iconMode = false;
widthValue = '100%';
if (show) {
showValue = 'block'
} else {
showValue = 'none';
}
} else {
showValue = 'block';
if (iconMode) {
widthValue = 'auto';
} else {
widthValue = '260px';
}
}
let index = 0;
return (
<div className="sidebar" style={{width:widthValue, display:showValue}}>
<div className="sidebar-content">
<SideBarUserItem userData={userData} iconMode={iconMode}/>
<div className="sidebar-category">
<div className="category-content no-padding">
<ul className="navigation-ul">
{items.map(x => {
return <SideBarItem itemData={x} key={index++}
iconMode={iconMode}
showSubMenu={this.showSubMenu.bind(this)}
onClickSubMenuItem={this.onClickSubMenuItem.bind(this)}
currentIndex={this.state.currentIndex}
currentSubMenuItemIndex={this.state.currentSubMenuItemIndex}
/>
})}
</ul>
</div>
</div>
</div>
</div>
);
}
}
SideBar.propTypes = {};
SideBar.defaultProps = {};
export default SideBar;
//<li className='navigation-item'>
// <Icon type="home"/><span>个人门户</span>
//</li>
//<li className='navigation-item active' onClick={this.subMenuClick.bind(this)}>
//
//<Icon type="play-circle-o"/>
//<span>基础管理</span>
//
//<div className="arrow">
// <Icon type="right"/>
//</div>
//
//<ul className="hidden-ul" style={{display: 'block'}} ref='subMenu'>
// <li>Fixed navbar</li>
// <li>Fixed navbar &sidebar</li>
//<li>Fixed sidebar native scroll</li>
//
//</ul>
//</li>
// <li className='navigation-item'>
// <Icon type="home"/><span>表单管理</span>
// </li>
|
src/main.js | embengineering/react-md-crud | import 'file?name=[name].[ext]!./index.html';
import 'babel-polyfill';
import 'fastclick';
import 'font-awesome-sass-loader';
import './scss/main.scss';
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import injectTapEventPlugin from 'react-tap-event-plugin';
import configureStore from './stores/configureStore';
import Util from './utils';
import App from './containers/App.jsx';
//Needed for React Developer Tools
window.React = React;
//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();
// set data service url
Util.dataService.setUrl('https://emb0624-employees.firebaseio.com');
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('container')
);
|
cdap-ui/app/cdap/components/HeaderBrand/index.js | caskdata/cdap | /*
* Copyright © 2016 Cask Data, 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';
require('./HeaderBrand.less');
export default function HeaderBrand () {
return (
<div className="brand-header">
<a
className="navbar-brand"
href=""
>
<div className="company-logo"></div>
</a>
</div>
);
}
|
fields/types/html/HtmlField.js | mikaoelitiana/keystone | import _ from 'underscore';
import Field from '../Field';
import React from 'react';
import tinymce from 'tinymce';
import { FormInput } from 'elemental';
/**
* TODO:
* - Remove dependency on underscore
*/
var lastId = 0;
function getId() {
return 'keystone-html-' + lastId++;
}
module.exports = Field.create({
displayName: 'HtmlField',
getInitialState () {
return {
id: getId(),
isFocused: false
};
},
initWysiwyg () {
if (!this.props.wysiwyg) return;
var self = this;
var opts = this.getOptions();
opts.setup = function (editor) {
self.editor = editor;
editor.on('change', self.valueChanged);
editor.on('focus', self.focusChanged.bind(self, true));
editor.on('blur', self.focusChanged.bind(self, false));
};
this._currentValue = this.props.value;
tinymce.init(opts);
},
componentDidUpdate (prevProps, prevState) {
if (prevState.isCollapsed && !this.state.isCollapsed) {
this.initWysiwyg();
}
if (_.isEqual(this.props.dependsOn, this.props.currentDependencies)
&& !_.isEqual(this.props.currentDependencies, prevProps.currentDependencies)) {
var instance = tinymce.get(prevState.id);
if (instance) {
tinymce.EditorManager.execCommand('mceRemoveEditor', true, prevState.id);
this.initWysiwyg();
} else {
this.initWysiwyg();
}
}
},
componentDidMount () {
this.initWysiwyg();
},
componentWillReceiveProps (nextProps) {
if (this.editor && this._currentValue !== nextProps.value) {
this.editor.setContent(nextProps.value);
}
},
focusChanged (focused) {
this.setState({
isFocused: focused
});
},
valueChanged () {
var content;
if (this.editor) {
content = this.editor.getContent();
} else if (this.refs.editor) {
content = this.refs.editor.getDOMNode().value;
} else {
return;
}
this._currentValue = content;
this.props.onChange({
path: this.props.path,
value: content
});
},
getOptions () {
var plugins = ['code', 'link'],
options = Object.assign(
{},
Keystone.wysiwyg.options,
this.props.wysiwyg
),
toolbar = options.overrideToolbar ? '' : 'bold italic | alignleft aligncenter alignright | bullist numlist | outdent indent | link',
i;
if (options.enableImages) {
plugins.push('image');
toolbar += ' | image';
}
if (options.enableCloudinaryUploads || options.enableS3Uploads) {
plugins.push('uploadimage');
toolbar += options.enableImages ? ' uploadimage' : ' | uploadimage';
}
if (options.additionalButtons) {
var additionalButtons = options.additionalButtons.split(',');
for (i = 0; i < additionalButtons.length; i++) {
toolbar += (' | ' + additionalButtons[i]);
}
}
if (options.additionalPlugins) {
var additionalPlugins = options.additionalPlugins.split(',');
for (i = 0; i < additionalPlugins.length; i++) {
plugins.push(additionalPlugins[i]);
}
}
if (options.importcss) {
plugins.push('importcss');
var importcssOptions = {
content_css: options.importcss,
importcss_append: true,
importcss_merge_classes: true
};
Object.assign(options.additionalOptions, importcssOptions);
}
if (!options.overrideToolbar) {
toolbar += ' | code';
}
var opts = {
selector: '#' + this.state.id,
toolbar: toolbar,
plugins: plugins,
menubar: options.menubar || false,
skin: options.skin || 'keystone'
};
if (this.shouldRenderField()) {
opts.uploadimage_form_url = options.enableS3Uploads ?
Keystone.adminPath + '/api/s3/upload' :
Keystone.adminPath + '/api/cloudinary/upload';
} else {
Object.assign(opts, {
mode: 'textareas',
readonly: true,
menubar: false,
toolbar: 'code',
statusbar: false
});
}
if (options.additionalOptions){
Object.assign(opts, options.additionalOptions);
}
return opts;
},
getFieldClassName () {
var className = this.props.wysiwyg ? 'wysiwyg' : 'code';
return className;
},
renderField () {
var className = this.state.isFocused ? 'is-focused' : '';
var style = {
height: this.props.height
};
return (
<div className={className}>
<FormInput multiline ref="editor" style={style} onChange={this.valueChanged} id={this.state.id} className={this.getFieldClassName()} name={this.props.path} value={this.props.value} />
</div>
);
},
renderValue () {
return <FormInput multiline noedit value={this.props.value} />;
}
});
|
server/main.js | Anomen/universal-react-redux-starter-kit | global.__CLIENT__ = false;
global.__SERVER__ = true;
import express from 'express';
import cookieParser from 'cookie-parser';
import _debug from 'debug';
import config from '../config';
import webpackProxyMiddleware from './middleware/webpack-proxy';
Object.keys(config.globals).map((key) => {
global[key] = config.globals[key];
});
import React from 'react';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { createMemoryHistory, match, RouterContext } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import HTML from './html';
import configureStore from '../src/redux/configureStore';
import configureXhrClient from '../src/redux/utils/createXhrClient';
import makeRoutes from '../src/routes';
const debug = _debug('app:server');
const paths = config.utils_paths;
const app = express();
// Enable cookies
app.use(cookieParser());
// ------------------------------------
// Apply redux-router
// ------------------------------------
app.use(function (req, res) {
const xhrClient = configureXhrClient(req);
const memoryHistory = createMemoryHistory(req.path);
const store = configureStore(memoryHistory, xhrClient);
const history = syncHistoryWithStore(memoryHistory, store);
// Now that we have the Redux store, we can create our routes. We provide
// the store to the route definitions so that routes have access to it for
// hooks such as `onEnter`.
const routes = makeRoutes(store);
match({history, routes, location: req.url}, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
const component = (
<Provider store={store}>
<div style={{ height: '100%' }}>
<RouterContext {...renderProps}/>
</div>
</Provider>
);
res.send('<!doctype html>\n' + renderToString(
<HTML assets={global.webpackIsomorphicTools.assets()}
component={component}
store={store}/>
));
}
});
});
// ------------------------------------
// Apply Webpack HMR Middleware
// ------------------------------------
if (config.env === 'development') {
if (config.proxy && config.proxy.enabled) {
const options = config.proxy.options;
app.use(webpackProxyMiddleware(options));
}
// Serve static assets from ~/src/static since Webpack is unaware of
// these files. This middleware doesn't need to be enabled outside
// of development since this directory will be copied into ~/dist
// when the application is compiled.
app.use(express.static(paths.client('static')));
} else {
debug(
'Server is being run outside of live development mode. This starter kit ' +
'does not provide any production-ready server functionality. To learn ' +
'more about deployment strategies, check out the "deployment" section ' +
'in the README.'
);
// Serving ~/dist by default. Ideally these files should be served by
// the web server and not the app server, but this helps to demo the
// server in production.
app.use(express.static(paths.base(config.dir_dist)));
}
export default app;
|
b_stateMachine/complex_templates/jsx/wizard/footer.js | Muzietto/react-playground | 'use strict';
import React from 'react';
export default function footer(props) {
props.cancelButton.className += (!props.cancelButton.disabled) ? ' enabled' : '';
props.restartButton.className += (!props.restartButton.disabled) ? ' enabled' : '';
props.saveButton.className += (!props.saveButton.disabled) ? ' enabled' : '';
return (
<div className="footer">
<button
{...props.cancelButton}>Cancel
</button>
<button
{...props.restartButton}>Restart
</button>
<button
{...props.saveButton}>Save
</button>
</div>
);
}
|
src/svg-icons/device/battery-charging-80.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBatteryCharging80 = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h4.93L13 7v2h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9h-4v3.5z"/>
</SvgIcon>
);
DeviceBatteryCharging80 = pure(DeviceBatteryCharging80);
DeviceBatteryCharging80.displayName = 'DeviceBatteryCharging80';
DeviceBatteryCharging80.muiName = 'SvgIcon';
export default DeviceBatteryCharging80;
|
src/components/form/agreement.js | n7best/react-weui | import React from 'react';
import classNames from '../../utils/classnames';
/**
* Agreement style checkbox
*
*/
const Agreement = (props) => {
const { className, children, id, ...others } = props;
const cls = classNames({
'weui-agree': true,
[className]: className
});
return (
<label className={cls} htmlFor={id}>
<input id={id} type="checkbox" className="weui-agree__checkbox" {...others}/>
<span className="weui-agree__text">
{children}
</span>
</label>
);
};
export default Agreement; |
docs/src/sections/ResponsiveEmbedSection.js | SSLcom/Bootsharp | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function ResponsiveEmbedSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="responsive-embed">Responsive embed</Anchor> <small>ResponsiveEmbed</small>
</h2>
<p>Allow browsers to determine video or slideshow dimensions based on the width of their containing block by creating an intrinsic ratio that will properly scale on any device.</p>
<p>You don't need to include <code>frameborder="0"</code> in your <code>iframe</code>s.</p>
<p className="bg-warning">Either <b>16by9</b> or <b>4by3</b> aspect ratio via <code>a16by9</code> or <code>a4by3</code> attribute must be set.</p>
<ReactPlayground codeText={Samples.ResponsiveEmbed} />
<h3><Anchor id="responsive-embed-props">Props</Anchor></h3>
<PropTable component="ResponsiveEmbed"/>
</div>
);
}
|
client/src/app-components/ticket-list.js | opensupports/opensupports | import React from 'react';
import _ from 'lodash';
import {connect} from 'react-redux';
import queryString from 'query-string';
import i18n from 'lib-app/i18n';
import DateTransformer from 'lib-core/date-transformer';
import TicketInfo from 'app-components/ticket-info';
import DepartmentDropdown from 'app-components/department-dropdown';
import Table from 'core-components/table';
import Button from 'core-components/button';
import Tooltip from 'core-components/tooltip';
import Checkbox from 'core-components/checkbox';
import Tag from 'core-components/tag';
import Icon from 'core-components/icon';
import Message from 'core-components/message';
import history from 'lib-app/history';
import PageSizeDropdown from './page-size-dropdown';
class TicketList extends React.Component {
static propTypes = {
departments: React.PropTypes.array,
loading: React.PropTypes.bool,
ticketPath: React.PropTypes.string,
showDepartmentDropdown: React.PropTypes.bool,
tickets: React.PropTypes.arrayOf(React.PropTypes.object),
userId: React.PropTypes.number,
type: React.PropTypes.oneOf([
'primary',
'secondary'
]),
closedTicketsShown: React.PropTypes.bool,
onClosedTicketsShownChange: React.PropTypes.func,
onDepartmentChange: React.PropTypes.func,
showPageSizeDropdown: React.PropTypes.bool
};
static defaultProps = {
showDepartmentDropdown: true,
loading: false,
tickets: [],
departments: [],
ticketPath: '/dashboard/ticket/',
type: 'primary',
closedTicketsShown: false,
showPageSizeDropdown: true
};
state = {
selectedDepartment: 0
};
render() {
const { type, showDepartmentDropdown, onClosedTicketsShownChange, showPageSizeDropdown } = this.props;
const pages = [5, 10, 20, 50];
return (
<div className="ticket-list">
<div className="ticket-list__filters">
<div className="ticket-list__main-filters">
{(type === 'primary') ? this.renderMessage() : null}
{
((type === 'secondary') && showDepartmentDropdown) ?
this.renderDepartmentsDropDown() :
null
}
{onClosedTicketsShownChange ? this.renderFilterCheckbox() : null}
</div>
{
showPageSizeDropdown ?
<PageSizeDropdown className="ticket-list__page-dropdown" pages={pages} onChange={(event) => this.pageSizeChange(event)} /> :
null
}
</div>
<Table {...this.getTableProps()} />
</div>
);
}
renderFilterCheckbox() {
return (
<Checkbox
className="ticket-list__checkbox"
label={i18n("SHOW_CLOSED_TICKETS")}
value={this.props.closedTicketsShown}
onChange={this.props.onClosedTicketsShownChange}
wrapInLabel
/>
);
}
renderDepartmentsDropDown() {
return (
<div className="ticket-list__department-selector">
<DepartmentDropdown {...this.getDepartmentDropdownProps()} />
</div>
);
}
renderMessage() {
switch (queryString.parse(window.location.search)["message"]) {
case 'success':
return (
<Message
onCloseMessage={this.onCloseMessage}
className="create-ticket-form__message"
type="success">
{i18n('TICKET_SENT')}
</Message>
);
case 'fail':
return (
<Message
onCloseMessage={this.onCloseMessage}
className="create-ticket-form__message"
type="error">
{i18n('TICKET_SENT_ERROR')}
</Message>
);
default:
return null;
}
}
pageSizeChange(event) {
const { onPageSizeChange } = this.props;
onPageSizeChange && onPageSizeChange(event.pageSize);
}
getDepartmentDropdownProps() {
const { departments, onDepartmentChange } = this.props;
return {
departments: this.getDepartments(),
onChange: (event) => {
const departmentId = event.index && departments[event.index - 1].id;
this.setState({
selectedDepartment: departmentId
});
onDepartmentChange && onDepartmentChange(departmentId || null);
},
size: 'medium'
};
}
getTableProps() {
const { loading, page, pages, onPageChange } = this.props;
return {
loading,
headers: this.getTableHeaders(),
rows: this.getTableRows(),
pageSize: this.state.tickets,
page,
pages,
onPageChange
};
}
getDepartments() {
let departments = _.clone(this.props.departments);
departments.unshift({
name: i18n('ALL_DEPARTMENTS')
});
return departments;
}
getTableHeaders() {
const { type } = this.props;
if(type == 'primary' ) {
return [
{
key: 'number',
value: i18n('NUMBER'),
className: 'ticket-list__number col-md-1'
},
{
key: 'title',
value: i18n('TITLE'),
className: 'ticket-list__title col-md-6'
},
{
key: 'department',
value: i18n('DEPARTMENT'),
className: 'ticket-list__department col-md-3'
},
{
key: 'date',
value: <div>
{i18n('DATE')}
{this.renderSortArrow('date')}
</div>,
className: 'ticket-list__date col-md-2'
}
];
} else if(type == 'secondary') {
return [
{
key: 'number',
value: i18n('NUMBER'),
className: 'ticket-list__number col-md-1'
},
{
key: 'title',
value: i18n('TITLE'),
className: 'ticket-list__title col-md-4'
},
{
key: 'department',
value: i18n('DEPARTMENT'),
className: 'ticket-list__department col-md-2'
},
{
key: 'author',
value: i18n('AUTHOR'),
className: 'ticket-list__author col-md-2'
},
{
key: 'date',
value: <div>
{i18n('DATE')}
{this.renderSortArrow('date')}
</div>,
className: 'ticket-list__date col-md-2'
}
];
}
}
renderSortArrow(header) {
const { orderBy, showOrderArrows, onChangeOrderBy } = this.props;
return (
showOrderArrows ?
<Icon
name={`arrow-${this.getIconName(header, orderBy)}`}
className="ticket-list__order-icon"
color={this.getIconColor(header, orderBy)}
onClick={() => onChangeOrderBy(header)} /> :
null
);
}
getIconName(header, orderBy) {
return (orderBy && orderBy.value === header && orderBy.asc) ? "up" : "down";
}
getIconColor(header, orderBy) {
return (orderBy && orderBy.value === header) ? "gray" : "white";
}
getTableRows() {
return this.getTickets().map(this.getTicketTableObject.bind(this));
}
getTickets() {
const { tickets } = this.props;
const { selectedDepartment } = this.state;
return (
(selectedDepartment) ?
_.filter(tickets, (ticket) => { return ticket.department.id == selectedDepartment}) :
tickets
);
}
getTicketTableObject(ticket) {
const { date, title, ticketNumber, closed, tags, department, author } = ticket;
const dateTodayWithOutHoursAndMinutes = DateTransformer.getDateToday();
const ticketDateWithOutHoursAndMinutes = Math.floor(DateTransformer.UTCDateToLocalNumericDate(JSON.stringify(date*1)) / 10000);
const stringTicketLocalDateFormat = DateTransformer.transformToString(date, false, true);
const ticketDate = (
((dateTodayWithOutHoursAndMinutes - ticketDateWithOutHoursAndMinutes) > 1) ?
stringTicketLocalDateFormat :
`${(dateTodayWithOutHoursAndMinutes - ticketDateWithOutHoursAndMinutes) ? i18n("YESTERDAY_AT") : i18n("TODAY_AT")} ${stringTicketLocalDateFormat.slice(-5)}`
);
let titleText = (this.isTicketUnread(ticket)) ? title + ' (1)' : title;
return {
number: (
<Tooltip content={<TicketInfo ticket={ticket} />} openOnHover>
{'#' + ticketNumber}
</Tooltip>
),
title: (
<div>
{closed ? <Icon size="sm" name="lock" /> : null}
<Button className="ticket-list__title-link" type="clean" route={{to: this.props.ticketPath + ticketNumber}}>
{titleText}
</Button>
{(tags || []).map((tagName,index) => {
let tag = _.find(this.props.tags, {name:tagName});
return <Tag size='small' name={tag && tag.name} color={tag && tag.color} key={index} />
})}
</div>
),
department: department.name,
author: author.name,
date: ticketDate,
unread: this.isTicketUnread(ticket),
highlighted: this.isTicketUnread(ticket)
};
}
isTicketUnread(ticket) {
const { type, userId } = this.props;
const { unread, author, unreadStaff } = ticket;
if(type === 'primary') {
return unread;
} else if(type === 'secondary') {
if(author.id == userId && author.staff) {
return unread;
} else {
return unreadStaff;
}
}
}
onCloseMessage() {
history.push(window.location.pathname);
}
}
export default connect((store) => {
return {
tags: store.config['tags']
};
})(TicketList);
|
src/components/toolbar.js | bahattincinic/pharmacyonduty-mobile | 'use strict'
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import Button from './button'
class Toolbar extends Component {
_handleBack() {
this.props.navigator.pop()
}
_renderBackButton() {
if (this.props.navigator.getCurrentRoutes().length > 1) {
return (
<View style={styles.back}>
<Button onPress={this._handleBack.bind(this)}>
<View>
<Text style={{color: '#FFF'}}>Geri</Text>
</View>
</Button>
</View>
)
} else {
return (<View/>)
}
}
render() {
return (
<View style={styles.container}>
<View style={{flex: 1}}>
<Text style={styles.title}>
{this.props.title}
</Text>
</View>
{this._renderBackButton()}
</View>
)
}
}
const styles = {
container: {
backgroundColor: '#de0000',
height: 56,
paddingTop: 10,
flexDirection: 'row',
alignItems: 'center',
},
title: {
fontSize: 16,
color: 'white',
marginLeft: 15,
},
back: {
alignItems: 'flex-end',
marginRight: 20,
}
}
module.exports = Toolbar;
|
public/js/components/Auth/index.js | nowordforfree/react-cv | import React from 'react';
import { Tabs, Tab } from 'material-ui/Tabs';
import LoginForm from '../../containers/LoginForm';
import RegistrationForm from '../../containers/RegistrationForm';
export default () => (
<div className="row">
<div className="col-md-offset-2 col-md-8">
<Tabs>
<Tab title="Sign In as registered user" label="Login" value="login">
<LoginForm />
</Tab>
<Tab title="Register as new user" label="Register" value="register">
<RegistrationForm />
</Tab>
</Tabs>
</div>
</div>
);
|
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/LifecycleMethodsInferred.js | ylu1317/flow | // @flow
import React from 'react';
class MyComponent1 extends React.Component {
componentWillReceiveProps(nextProps) {}
}
class MyComponent2 extends React.Component {
shouldComponentUpdate(prevProps, prevState) {}
}
class MyComponent3 extends React.Component {
componentWillUpdate(prevProps, prevState) {}
}
class MyComponent4 extends React.Component {
componentDidUpdate(prevProps, prevState) {}
}
const expression1 = () =>
class extends React.Component {
componentWillReceiveProps(nextProps) {}
}
const expression2 = () =>
class extends React.Component {
shouldComponentUpdate(prevProps, prevState) {}
}
const expression3 = () =>
class extends React.Component {
componentWillUpdate(prevProps, prevState) {}
}
const expression4 = () =>
class extends React.Component {
componentDidUpdate(prevProps, prevState) {}
}
|
components/TabPage2.js | s1hit/react-onsenui-redux-weather-edited | import React from 'react';
import {
Page,
Navigator
} from 'react-onsenui';
import CustomPage from './CustomPage';
const renderPage = (route, navigator) => (
<route.component key={route.key} navigator={navigator} />
);
const TabPage2 = () => (
<Page>
<Navigator
renderPage={renderPage}
initialRoute={{component: CustomPage, key: 'CUSTOM_PAGE'}}
/>
</Page>
);
export default TabPage2;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.