path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/Row.js | HPate-Riptide/react-bootstrap | import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
const propTypes = {
componentClass: elementType,
};
const defaultProps = {
componentClass: 'div',
};
class Row extends React.Component {
render() {
const { componentClass: Component, className, ...props } = this.props;
const [bsProps, elementProps] = splitBsProps(props);
const classes = getClassSet(bsProps);
return (
<Component
{...elementProps}
className={classNames(className, classes)}
/>
);
}
}
Row.propTypes = propTypes;
Row.defaultProps = defaultProps;
export default bsClass('row', Row);
|
app/header.js | vijanny/react-native-DemoPrj | import React, { Component } from 'react';
import {StatusBar ,View,StyleSheet,Text,TouchableHighlight,Image} from 'react-native';
/*
*iconSrcLeft 左侧图标路径 参考iconSrcLeft = require('路径') 传参
*iconOnPressLeft 左侧图标按下响应函数
*iconSrcRight 右侧图标路径 参考iconSrcLeft = require('路径') 传参
*iconOnPressRight 右侧图标按下响应函数
*titleColor 标题演示
*title 标题
*backgroundColor 背景颜色
*height 高度
*/
export default class Header extends Component {
constructor(props) {
super(props);
}
render() {
// 根据当前showText的值决定是否显示text内容
const iconSrcLeft = this.props.iconSrcLeft?this.props.iconSrcLeft:null;
const iconSrcRight = this.props.iconSrcRight?this.props.iconSrcRight:null;
const titleColor = this.props.titleColor?this.props.titleColor:'#000'
return (
<View style={[this.props.style , {backgroundColor:this.props.backgroundColor,flexDirection:"row",height:this.props.height}]}>
<View style={{flex:1,flexDirection:'column',justifyContent:'center',paddingLeft:10}}>
<TouchableHighlight
onPress={this.props.iconOnPressLeft}
style={styles.headerIcon}
underlayColor = '#F5F5F5'
>
<View >
{iconSrcLeft
?
<Image
style={styles.headerIcon}
source={iconSrcLeft}
/>
:
null
}
</View>
</TouchableHighlight>
</View>
<View style={{flex:1,flexDirection:'column',justifyContent:'center'}}>
<View style = {{flexDirection:'row',alignItems:'center',justifyContent:'center'}}>
<Text style={{fontSize:20,color:titleColor}} >{this.props.title}</Text>
</View>
</View>
<View style={{flex:1,flexDirection:'column',justifyContent:'center'}}>
<View style = {{flexDirection:'row',alignItems:'center',justifyContent:'flex-end',paddingRight:10}}>
<TouchableHighlight
onPress={this.props.iconOnPressRight}
style={styles.headerIcon}
underlayColor = '#F5F5F5'
>
<View >
{iconSrcRight
?
<Image
style={styles.headerIcon}
source={iconSrcRight}
/>
:
null
}
</View>
</TouchableHighlight>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
headerIcon:{
width:30,
height:30
},
});
|
tom-binary-tree/src/Counter.js | slorber/scalable-frontend-with-elm-or-redux | import React from 'react'
// EVENTS
export class Increment {
constructor(step) {
this.step = step
}
update(model) {
return { model: model + this.step }
}
}
// APP
export default {
init() {
return { model: 0 }
},
update(model, event) {
return event.update(model)
},
view(model) {
return <p>Count: {model}</p>
}
} |
src/svg-icons/action/open-in-browser.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionOpenInBrowser = (props) => (
<SvgIcon {...props}>
<path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h4v-2H5V8h14v10h-4v2h4c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm-7 6l-4 4h3v6h2v-6h3l-4-4z"/>
</SvgIcon>
);
ActionOpenInBrowser = pure(ActionOpenInBrowser);
ActionOpenInBrowser.displayName = 'ActionOpenInBrowser';
ActionOpenInBrowser.muiName = 'SvgIcon';
export default ActionOpenInBrowser;
|
app/components/Hypno/index.js | brainsandspace/ship | /**
*
* Hypno
*
*/
import React from 'react';
import styled from 'styled-components';
const Wrapper = styled.div`
overflow: hidden;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
// height: 100vh;
.circle {
position: absolute;
height: 20vmin;
width: 20vmin;
border-radius: 50%;
opacity: 1;
background: black;
}
#c1 {
-webkit-transform-origin: center 46%;
transform-origin: center 46%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #edebe9;
-webkit-animation: circleAn1 10s infinite linear;
animation: circleAn1 10s infinite linear;
}
@-webkit-keyframes circleAn1 {
50% {
background: #edede9;
}
to {
background: #edebe9;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn1 {
50% {
background: #edede9;
}
to {
background: #edebe9;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c2 {
-webkit-transform-origin: center 47%;
transform-origin: center 47%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #dcdcd4;
-webkit-animation: circleAn2 10s infinite linear;
animation: circleAn2 10s infinite linear;
}
@-webkit-keyframes circleAn2 {
50% {
background: #d8dcd4;
}
to {
background: #dcdcd4;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn2 {
50% {
background: #d8dcd4;
}
to {
background: #dcdcd4;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c3 {
-webkit-transform-origin: center 48%;
transform-origin: center 48%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #c4cabe;
-webkit-animation: circleAn3 10s infinite linear;
animation: circleAn3 10s infinite linear;
}
@-webkit-keyframes circleAn3 {
50% {
background: #becabe;
}
to {
background: #c4cabe;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn3 {
50% {
background: #becabe;
}
to {
background: #c4cabe;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c4 {
-webkit-transform-origin: center 49%;
transform-origin: center 49%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #a9b8a9;
-webkit-animation: circleAn4 10s infinite linear;
animation: circleAn4 10s infinite linear;
}
@-webkit-keyframes circleAn4 {
50% {
background: #a9b8b1;
}
to {
background: #a9b8a9;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn4 {
50% {
background: #a9b8b1;
}
to {
background: #a9b8a9;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c5 {
-webkit-transform-origin: center 50%;
transform-origin: center 50%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #93a79d;
-webkit-animation: circleAn5 10s infinite linear;
animation: circleAn5 10s infinite linear;
}
@-webkit-keyframes circleAn5 {
50% {
background: #93a7a7;
}
to {
background: #93a79d;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn5 {
50% {
background: #93a7a7;
}
to {
background: #93a79d;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c6 {
-webkit-transform-origin: center 51%;
transform-origin: center 51%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #7e9595;
-webkit-animation: circleAn6 10s infinite linear;
animation: circleAn6 10s infinite linear;
}
@-webkit-keyframes circleAn6 {
50% {
background: #7e8995;
}
to {
background: #7e9595;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn6 {
50% {
background: #7e8995;
}
to {
background: #7e9595;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c7 {
-webkit-transform-origin: center 52%;
transform-origin: center 52%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #6a7681;
-webkit-animation: circleAn7 10s infinite linear;
animation: circleAn7 10s infinite linear;
}
@-webkit-keyframes circleAn7 {
50% {
background: #6a6a81;
}
to {
background: #6a7681;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn7 {
50% {
background: #6a6a81;
}
to {
background: #6a7681;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c8 {
-webkit-transform-origin: center 53%;
transform-origin: center 53%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #58586c;
-webkit-animation: circleAn8 10s infinite linear;
animation: circleAn8 10s infinite linear;
}
@-webkit-keyframes circleAn8 {
50% {
background: #62586c;
}
to {
background: #58586c;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn8 {
50% {
background: #62586c;
}
to {
background: #58586c;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c9 {
-webkit-transform-origin: center 54%;
transform-origin: center 54%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #4e4756;
-webkit-animation: circleAn9 10s infinite linear;
animation: circleAn9 10s infinite linear;
}
@-webkit-keyframes circleAn9 {
50% {
background: #564756;
}
to {
background: #4e4756;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn9 {
50% {
background: #564756;
}
to {
background: #4e4756;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c10 {
-webkit-transform-origin: center 55%;
transform-origin: center 55%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #413541;
-webkit-animation: circleAn10 10s infinite linear;
animation: circleAn10 10s infinite linear;
}
@-webkit-keyframes circleAn10 {
50% {
background: #41353b;
}
to {
background: #413541;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn10 {
50% {
background: #41353b;
}
to {
background: #413541;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c11 {
-webkit-transform-origin: center 56%;
transform-origin: center 56%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #2b2327;
-webkit-animation: circleAn11 10s infinite linear;
animation: circleAn11 10s infinite linear;
}
@-webkit-keyframes circleAn11 {
50% {
background: #2b2323;
}
to {
background: #2b2327;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn11 {
50% {
background: #2b2323;
}
to {
background: #2b2327;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c12 {
-webkit-transform-origin: center 57%;
transform-origin: center 57%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #161212;
-webkit-animation: circleAn12 10s infinite linear;
animation: circleAn12 10s infinite linear;
}
@-webkit-keyframes circleAn12 {
50% {
background: #161412;
}
to {
background: #161212;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn12 {
50% {
background: #161412;
}
to {
background: #161212;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c13 {
-webkit-transform-origin: center 58%;
transform-origin: center 58%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: black;
-webkit-animation: circleAn13 10s infinite linear;
animation: circleAn13 10s infinite linear;
}
@-webkit-keyframes circleAn13 {
50% {
background: black;
}
to {
background: black;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn13 {
50% {
background: black;
}
to {
background: black;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
`;
function Hypno() {
return (
<Wrapper>
<div className="circle" id="c1">
<div className="circle" id="c2">
<div className="circle" id="c3">
<div className="circle" id="c4">
<div className="circle" id="c5">
<div className="circle" id="c6">
<div className="circle" id="c7">
<div className="circle" id="c8">
<div className="circle" id="c9">
<div className="circle" id="c10">
<div className="circle" id="c11">
<div className="circle" id="c12">
<div className="circle" id="c13"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</Wrapper>
);
}
Hypno.propTypes = {
};
export default Hypno;
|
frontend/component/TopicList.js | ivernaloo/practice-node-project | import React from 'react';
import {Link} from 'react-router';
import {getTopicList} from '../lib/client';
export default class TopicList extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
getTopicList({})
.then(ret => this.setState({list: ret.list}))
.catch(err => console.error(err));
}
render() {
const list = Array.isArray(this.state.list) ? this.state.list : [];
return (
<div>
<ul className="list-group">
{list.map((item, i) => {
return (
<Link to={`/topic/${item._id}`} className="list-group-item" key={i}>{item.title}</Link>
)
})}
</ul>
</div>
)
}
}
|
react/features/toolbox/components/web/JitsiPortal.js | jitsi/jitsi-meet | // @flow
import React from 'react';
import DialogPortal from './DialogPortal';
type Props = {
/**
* The component(s) to be displayed within the drawer portal.
*/
children: React$Node,
/**
* Class name used to add custom styles to the portal.
*/
className?: string
};
/**
* Component meant to render a drawer at the bottom of the screen,
* by creating a portal containing the component's children.
*
* @returns {ReactElement}
*/
function JitsiPortal({ children, className }: Props) {
return (
<DialogPortal className = { `drawer-portal ${className ?? ''}` }>
{ children }
</DialogPortal>
);
}
export default JitsiPortal;
|
src/svg-icons/image/hdr-off.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageHdrOff = (props) => (
<SvgIcon {...props}>
<path d="M17.5 15v-2h1.1l.9 2H21l-.9-2.1c.5-.2.9-.8.9-1.4v-1c0-.8-.7-1.5-1.5-1.5H16v4.9l1.1 1.1h.4zm0-4.5h2v1h-2v-1zm-4.5 0v.4l1.5 1.5v-1.9c0-.8-.7-1.5-1.5-1.5h-1.9l1.5 1.5h.4zm-3.5-1l-7-7-1.1 1L6.9 9h-.4v2h-2V9H3v6h1.5v-2.5h2V15H8v-4.9l1.5 1.5V15h3.4l7.6 7.6 1.1-1.1-12.1-12z"/>
</SvgIcon>
);
ImageHdrOff = pure(ImageHdrOff);
ImageHdrOff.displayName = 'ImageHdrOff';
ImageHdrOff.muiName = 'SvgIcon';
export default ImageHdrOff;
|
App.js | emilianoeloi/React | import React from 'react';
class App extends React.Component {
constructor(){
super();
this.state = {
input: '/* add your jsx here */',
output: '',
err: ''
}
this.update = this.update.bind(this);
}
update(e){
let code = e.target.value;
try{
this.setState({
output: babel.transform(code, {
stage: 0,
loose: 'all'
}).code
})
}catch(err){
this.setState({err: err.message});
}
}
render(){
return (
<div>
<header>
{this.state.err}
</header>
<div className="container">
<textarea onChange={this.update}
defaultValue={this.state.input}></textarea>
<pre>{this.state.output}</pre>
</div>
</div>
)
}
}
export default App |
tests/react/ref.js | facebook/flow | // @flow
import React from 'react';
class Foo extends React.Component<{}, void> {}
class Bar extends React.Component<{}, void> {}
<Foo />; // OK
<Foo ref="foo" />; // OK
<Foo ref={null} />; // OK
<Foo ref={undefined} />; // OK
<Foo ref={(foo: number) => {}} />; // Error: `Foo` is not a `number`.
<Foo ref={foo => (foo: Foo)} />; // Error: `Foo` may be null.
<Foo ref={foo => (foo: Foo | null)} />; // OK
<Foo ref={foo => (foo: Bar | null)} />; // Error: `Foo` is not `Bar`.
class FooExact extends React.Component<{||}, void> {}
<FooExact />; // OK
<FooExact ref="foo" />; // OK
<FooExact ref={null} />; // OK
<FooExact ref={undefined} />; // OK
<FooExact ref={(foo: number) => {}} />; // Error: `FooExact` is not a `number`.
<FooExact ref={foo => (foo: FooExact)} />; // Error: `FooExact` may be null.
<FooExact ref={foo => (foo: FooExact | null)} />; // OK
<FooExact ref={foo => (foo: Bar | null)} />; // Error: `FooExact` is not `Bar`.
class NumRefs extends React.Component<{}> {
getChild(i: number) {
return this.refs[i];
}
render() {
var children = [];
for (var i = 0; i < 10; i++) {
children.push(<div ref={i} />);
}
return children;
}
}
|
node_modules/react-router/modules/Link.js | yomolify/cs-webserver | import React from 'react';
var { object, string, func } = React.PropTypes;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
/**
* <Link> components are used to create an <a> element that links to a route.
* When that route is active, the link gets an "active" class name (or the
* value of its `activeClassName` prop).
*
* For example, assuming you have the following route:
*
* <Route name="showPost" path="/posts/:postID" handler={Post}/>
*
* You could use the following component to link to that route:
*
* <Link to="showPost" params={{ postID: "123" }} />
*
* In addition to params, links may pass along query string parameters
* using the `query` prop.
*
* <Link to="showPost" params={{ postID: "123" }} query={{ show:true }}/>
*/
export var Link = React.createClass({
contextTypes: {
router: object
},
propTypes: {
activeStyle: object,
activeClassName: string,
to: string.isRequired,
query: object,
state: object,
onClick: func
},
getDefaultProps() {
return {
className: '',
activeClassName: 'active',
style: {}
};
},
handleClick(event) {
var allowTransition = true;
var clickResult;
if (this.props.onClick)
clickResult = this.props.onClick(event);
if (isModifiedEvent(event) || !isLeftClickEvent(event))
return;
if (clickResult === false || event.defaultPrevented === true)
allowTransition = false;
event.preventDefault();
if (allowTransition)
this.context.router.transitionTo(this.props.to, this.props.query, this.props.state);
},
render() {
var { router } = this.context;
var { to, query } = this.props;
var props = Object.assign({}, this.props, {
href: router.makeHref(to, query),
onClick: this.handleClick
});
// ignore if rendered outside of the context of a router, simplifies unit testing
if (router && router.isActive(to, query)) {
if (props.activeClassName)
props.className += ` ${props.activeClassName}`;
if (props.activeStyle)
Object.assign(props.style, props.activeStyle);
}
return React.createElement('a', props);
}
});
export default Link;
|
app/src/components/Footer/index.js | karatechops/bhamc | import React from 'react';
import Anchor from 'grommet/components/Anchor';
import Box from 'grommet/components/Box';
import Button from 'grommet/components/Button';
import Heading from 'grommet/components/Heading';
import Paragraph from 'grommet/components/Paragraph';
import MapIcon from 'grommet/components/icons/base/Map';
import SocialTwitterIcon from 'grommet/components/icons/base/SocialTwitter';
import SocialFacebookIcon from 'grommet/components/icons/base/SocialFacebookOption';
import { FooterLogo, Divider, FooterColumn, StyledFooter } from './styles';
import aahaLogo from './aaha.jpg';
export const Footer = () =>
<StyledFooter
pad={{
horizontal: 'medium',
vertical: 'medium',
between: 'large',
}}
colorIndex="neutral-1"
align="start"
justify="center"
full="horizontal"
>
<FooterColumn>
<Heading tag="h3" margin="small">
Hospital Hours
</Heading>
<Divider />
<Paragraph margin="none">
Monday - Friday: 7:30 am - 7:30 pm
</Paragraph>
<Paragraph margin="none">
Saturday: 7:30 am - 1:30 pm
</Paragraph>
<Paragraph margin="none">
Appointments Preferred
</Paragraph>
</FooterColumn>
<FooterColumn>
<Heading tag="h3" margin="small">
Location
</Heading>
<Divider />
<Paragraph margin="none">
1221 Belle Haven Road
</Paragraph>
<Paragraph margin="none">
Alexandria, VA 22307
</Paragraph>
<Anchor
reverse
icon={<MapIcon />}
label="View Map"
target="_blank"
href="https://www.google.com/maps/place/Belle+Haven+Animal+Medical+Centre/@38.785937,-77.057076,12z/data=!4m13!1m7!3m6!1s0x89b7b034a51a741d:0x386950d364cdc491!2s1221+Belle+Haven+Rd,+Alexandria,+VA+22307!3b1!8m2!3d38.7804665!4d-77.0554556!3m4!1s0x89b7b034988ea74f:0x846f6f9f2ddc75b!8m2!3d38.780339!4d-77.054958"
style={{
fontWeight: 100,
paddingTop: '6px',
fontSize: '16px',
}}
/>
</FooterColumn>
<FooterColumn>
<Heading tag="h3" margin="small">
Contact
</Heading>
<Divider />
<Paragraph margin="none">
Phone: (703) 721 - 0088
</Paragraph>
<Paragraph margin="none">
E-mail: [email protected]
</Paragraph>
</FooterColumn>
<FooterColumn>
<Heading tag="h3" margin="small">
Social
</Heading>
<Divider />
<Box pad={{ between: 'small' }}>
<Button href="https://twitter.com/bhamcvet" rel="noopener noreferer">
<Box
direction="row"
responsive={false}
pad={{
between: 'small',
horizontal: 'small',
}}
>
<SocialTwitterIcon style={{ verticalAlign: 'middle' }} />
<Paragraph margin="none">
Twitter
</Paragraph>
</Box>
</Button>
<Button href="https://www.facebook.com/BHAMC" rel="noopener noreferer">
<Box
direction="row"
responsive={false}
pad={{
between: 'small',
horizontal: 'small',
}}
>
<SocialFacebookIcon style={{ verticalAlign: 'middle' }} />
<Paragraph margin="none">
Facebook
</Paragraph>
</Box>
</Button>
</Box>
</FooterColumn>
<FooterColumn alignSelf="center">
{ typeof window !== 'undefined' &&
<FooterLogo src={aahaLogo} />
}
</FooterColumn>
</StyledFooter>;
export default Footer; |
src/svg-icons/social/party-mode.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPartyMode = (props) => (
<SvgIcon {...props}>
<path d="M20 4h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 3c1.63 0 3.06.79 3.98 2H12c-1.66 0-3 1.34-3 3 0 .35.07.69.18 1H7.1c-.06-.32-.1-.66-.1-1 0-2.76 2.24-5 5-5zm0 10c-1.63 0-3.06-.79-3.98-2H12c1.66 0 3-1.34 3-3 0-.35-.07-.69-.18-1h2.08c.07.32.1.66.1 1 0 2.76-2.24 5-5 5z"/>
</SvgIcon>
);
SocialPartyMode = pure(SocialPartyMode);
SocialPartyMode.displayName = 'SocialPartyMode';
export default SocialPartyMode;
|
src/app/components/media/MediaPlayerCard.js | meedan/check-web | import React from 'react';
import PropTypes from 'prop-types';
import { Player } from '@meedan/check-ui';
import AspectRatio from '../layout/AspectRatio';
const MediaPlayerCard = props => (
<article className="video-media-card" style={{ position: 'relative' }}>
<AspectRatio
key={props.contentWarning}
contentWarning={props.contentWarning}
warningCreator={props.warningCreator}
warningCategory={props.warningCategory}
>
{ props.coverImage ? (
<img
src={props.coverImage}
alt=""
/>
) : null }
<div className="aspect-ratio__overlay">
<Player
url={props.filePath}
className="video-media-player"
playbackRate={props.playbackRate}
onDuration={d => props.setPlayerState({ duration: d })}
onPause={() => props.setPlayerState({ playing: false, gaps: [] })}
onPlay={() => props.setPlayerState({ playing: true })}
onProgress={p => props.setPlayerState({ progress: p })}
onReady={props.onPlayerReady}
onTimeUpdate={t => props.setPlayerState({ time: t })}
playing={props.playing}
start={props.start}
end={props.end}
gaps={props.gaps}
scrubTo={props.scrubTo}
seekTo={props.seekTo}
/>
</div>
</AspectRatio>
</article>
);
MediaPlayerCard.propTypes = {
contentWarning: PropTypes.bool.isRequired,
warningCreator: PropTypes.string.isRequired,
warningCategory: PropTypes.string.isRequired,
coverImage: PropTypes.string.isRequired,
filePath: PropTypes.string.isRequired,
playbackRate: PropTypes.number,
setPlayerState: PropTypes.func,
onPlayerReady: PropTypes.func,
playing: PropTypes.bool,
start: PropTypes.number,
end: PropTypes.number,
gaps: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.number)),
scrubTo: PropTypes.number,
seekTo: PropTypes.number,
};
MediaPlayerCard.defaultProps = {
playbackRate: 1,
setPlayerState: () => {},
onPlayerReady: () => {},
playing: false,
start: null,
end: null,
gaps: [],
scrubTo: null,
seekTo: null,
};
export default MediaPlayerCard;
|
src/app/components/forms/inputs/DropzoneInput.js | backpackcoder/world-in-flames | import React from 'react'
import {findDOMNode} from 'react-dom'
import Dropzone from 'dropzone'
Dropzone.autoDiscover = false;
export default class DropzoneInput extends React.Component {
componentDidMount() {
let element = $(findDOMNode(this));
let options = this.props.options || {};
element.dropzone(options)
}
render() {
return (
this.props.children
)
}
} |
src/interface/report/FightSelectionPanel.js | FaideWW/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import Toggle from 'react-toggle';
import { Link } from 'react-router-dom';
import { Trans, t } from '@lingui/macro';
import { i18n } from 'interface/RootLocalizationProvider';
import makeAnalyzerUrl from 'interface/common/makeAnalyzerUrl';
import FightSelectionPanelList from './FightSelectionPanelList';
class FightSelectionPanel extends React.PureComponent {
static propTypes = {
report: PropTypes.shape({
fights: PropTypes.array.isRequired,
}).isRequired,
refreshReport: PropTypes.func.isRequired,
};
state = {
killsOnly: false,
};
render() {
const { report, refreshReport } = this.props;
const { killsOnly } = this.state;
return (
<div className="panel">
<div className="panel-heading">
<div className="row">
<div className="col-md-8">
<h2><Trans>Select the fight to parse</Trans></h2>
</div>
<div className="col-md-4 text-right toggle-control action-buttons">
<Toggle
checked={killsOnly}
icons={false}
onChange={event => this.setState({ killsOnly: event.currentTarget.checked })}
id="kills-only-toggle"
/>
<label htmlFor="kills-only-toggle">
{' '}<Trans>Kills only</Trans>
</label>
<Link
to={makeAnalyzerUrl(report)}
onClick={refreshReport}
data-tip={i18n._(t`This will refresh the fights list which can be useful if you're live logging.`)}
>
<span className="glyphicon glyphicon-refresh" aria-hidden="true" /> <Trans>Refresh</Trans>
</Link>
</div>
</div>
</div>
<div className="panel-body" style={{ padding: 0 }}>
<FightSelectionPanelList
report={report}
fights={report.fights}
killsOnly={killsOnly}
/>
</div>
</div>
);
}
}
export default FightSelectionPanel;
|
client/src/app/components/forms/wizards/Wizard.js | zraees/sms-project | import React from 'react'
export default class Wizard extends React.Component {
componentDidMount() {
let self = this;
let element = $(this.refs.wizard);
var stepsCount = $('[data-smart-wizard-tab]').length;
var currentStep = 1;
var validSteps = [];
var $form = element.closest('form');
var $prev = $('[data-smart-wizard-prev]', element);
var $next = $('[data-smart-wizard-next]', element);
function setStep(step) {
currentStep = step;
$('[data-smart-wizard-pane=' + step + ']', element).addClass('active').siblings('[data-smart-wizard-pane]').removeClass('active');
$('[data-smart-wizard-tab=' + step + ']', element).addClass('active').siblings('[data-smart-wizard-tab]').removeClass('active');
$prev.toggleClass('disabled', step == 1)
}
element.on('click', '[data-smart-wizard-tab]', function (e) {
setStep(parseInt($(this).data('smartWizardTab')));
e.preventDefault();
});
$next.on('click', function (e) {
if ($form.data('validator')) {
if (!$form.valid()) {
validSteps = _.without(validSteps, currentStep);
$form.data('validator').focusInvalid();
return false;
} else {
validSteps = _.without(validSteps, currentStep);
validSteps.push(currentStep);
element.find('[data-smart-wizard-tab=' + currentStep + ']')
.addClass('complete')
.find('.step')
.html('<i class="fa fa-check"></i>');
}
}
if (currentStep < stepsCount) {
setStep(currentStep + 1);
} else {
if (validSteps.length < stepsCount) {
var steps = _.range(1, stepsCount + 1)
_(steps).forEach(function (num) {
if (validSteps.indexOf(num) == -1) {
setStep(num);
return false;
}
})
} else {
var data = {};
_.each($form.serializeArray(), function (field) {
data[field.name] = field.value
});
if (_.isFunction(self.props.onComplete)) {
self.props.onComplete(data)
}
}
}
e.preventDefault();
});
$prev.on('click', function (e) {
if (!$prev.hasClass('disabled') && currentStep > 0) {
setStep(currentStep - 1);
}
e.preventDefault();
});
setStep(currentStep);
}
render() {
let {children, onComplete, ...props} = this.props;
return (
<div {...props} ref="wizard">
{children}
</div>
)
}
} |
js/views/create/FriendsListView.js | SamyZ/TravelgramApp | import React from 'react';
import {
View,
Image,
ListView,
TouchableOpacity,
} from 'react-native';
import friendsListStyles from '../../styles/create/friendsListStyles';
import TextOpenSans from '../utils/TextOpenSans';
const FriendsListView = (props) => {
const listContainerStyle = props.friends.getRowCount() === 0 ? friendsListStyles.emptyListContainer : friendsListStyles.listContainer;
return (
<View style={friendsListStyles.mainContainer}>
<View style={friendsListStyles.leftContainer} />
<View style={friendsListStyles.contentContainer}>
<View style={listContainerStyle}>
<ListView
enableEmptySections
keyboardShouldPersistTaps
dataSource={props.friends}
renderRow={rowData => (
<TouchableOpacity onPress={() => props.selectFriend(rowData)}>
<View style={friendsListStyles.friendContainer}>
<Image
style={friendsListStyles.imageContainer}
source={{ uri: rowData.picture }}
/>
<TextOpenSans style={friendsListStyles.usernameFont}>{ rowData.username} </TextOpenSans>
</View>
</TouchableOpacity>
)}
/>
</View>
</View>
</View>
);
};
export default FriendsListView;
|
src/select/index.js | denisraslov/react-spreadsheet-table | import React from 'react';
import PropTypes from 'prop-types';
import Dropdown from './../dropdown';
import keys from './../kit/keymap';
import find from 'lodash.find';
import styles from './styles.css';
class SpreadsheetGridSelect extends React.PureComponent {
constructor(props) {
super(props);
this.onGlobalKeyDown = this.onGlobalKeyDown.bind(this);
this.onItemMouseLeave = this.onItemMouseLeave.bind(this);
this.state = {
isOpen: this.props.isOpen,
selectedId: this.props.selectedId
};
}
static getDerivedStateFromProps({ isOpen, selectedId }, prevState) {
return {
...prevState,
isOpen,
selectedId
};
}
componentDidMount() {
document.addEventListener('keydown', this.onGlobalKeyDown, false);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.onGlobalKeyDown, false);
}
onItemClick(selectedId, item) {
this.setState({
selectedId,
isOpen: false
}, () => {
if (this.props.onChange) {
this.props.onChange(selectedId, item);
}
});
}
onItemMouseEnter(selectedIndex) {
this.setState({
selectedIndex
});
}
onItemMouseLeave() {
this.setState({
selectedIndex: null
});
}
onGlobalKeyDown(e) {
if (this.state.isOpen) {
if (e.keyCode === keys.DOWN) {
e.preventDefault();
if (this.state.selectedIndex || this.state.selectedIndex === 0) {
this.setState({
selectedIndex: this.state.selectedIndex + 1
});
} else {
this.setState({
selectedIndex: 0
});
}
if (this.state.selectedIndex > this.props.items.length - 1) {
this.setState({
selectedIndex: 0
});
}
}
if (e.keyCode === keys.UP) {
e.preventDefault();
if (this.state.selectedIndex || this.state.selectedIndex === 0) {
this.setState({
selectedIndex: this.state.selectedIndex - 1
});
} else {
this.setState({
selectedIndex: this.props.items.length - 1
});
}
if (this.state.selectedIndex < 0) {
this.setState({
selectedIndex: this.props.items.length - 1
});
}
}
if (e.keyCode === keys.ENTER || e.keyCode === keys.TAB) {
if (this.state.selectedIndex || this.state.selectedIndex === 0) {
const selectedItem = this.props.items[this.state.selectedIndex];
this.onItemClick(selectedItem.id, selectedItem);
}
}
e.preventDefault();
}
}
getItemClassName(isSelected) {
return 'SpreadsheetGridSelectItem' +
(isSelected ? ' SpreadsheetGridSelectItem_selected' : '');
}
isHasValue() {
return this.state.selectedId && this.props.items;
}
getHeaderValue() {
let value;
if (this.isHasValue()) {
value = find(this.props.items, {
id: this.state.selectedId
});
value = value ? value.name : value;
} else {
value = this.props.placeholder;
}
return value;
}
getHeaderClassName() {
return 'SpreadsheetGridSelectHeader' +
(this.state.isOpen ? ' SpreadsheetGridSelectHeader_open' : '');
}
renderHeader() {
return (
<div className={this.getHeaderClassName()}>
<div className="SpreadsheetGridSelectValue">
{this.getHeaderValue()}
</div>
</div>
);
}
renderBody() {
const items = this.props.items;
return (
<div>
{
items && items.map((item, i) => {
return (
<div
key={i}
className={this.getItemClassName(i === this.state.selectedIndex)}
onClick={this.onItemClick.bind(this, item.id, item)}
onMouseEnter={this.onItemMouseEnter.bind(this, i)}
onMouseLeave={this.onItemMouseLeave}
>
{item.name}
</div>
);
})
}
</div>
);
}
render() {
return (
<Dropdown
header={this.renderHeader()}
body={this.renderBody()}
isOpen={this.state.isOpen}
/>
);
}
}
const IdPropType = PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]);
SpreadsheetGridSelect.propTypes = {
selectedId: IdPropType,
items: PropTypes.arrayOf(
PropTypes.shape({
id: IdPropType,
value: PropTypes.string
})
),
onChange: PropTypes.func,
placeholder: PropTypes.string,
isOpen: PropTypes.bool
};
SpreadsheetGridSelect.defaultProps = {
items: [],
placeholder: '',
isOpen: false
};
export default SpreadsheetGridSelect; |
examples/todos/components/Footer.js | mjw56/redux | import React from 'react'
import FilterLink from '../containers/FilterLink'
const Footer = () => (
<p>
Show:
{" "}
<FilterLink filter="SHOW_ALL">
All
</FilterLink>
{", "}
<FilterLink filter="SHOW_ACTIVE">
Active
</FilterLink>
{", "}
<FilterLink filter="SHOW_COMPLETED">
Completed
</FilterLink>
</p>
)
export default Footer
|
src/svg-icons/hardware/gamepad.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareGamepad = (props) => (
<SvgIcon {...props}>
<path d="M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z"/>
</SvgIcon>
);
HardwareGamepad = pure(HardwareGamepad);
HardwareGamepad.displayName = 'HardwareGamepad';
HardwareGamepad.muiName = 'SvgIcon';
export default HardwareGamepad;
|
app/javascript/mastodon/features/compose/components/upload_form.js | kibousoft/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import UploadProgressContainer from '../containers/upload_progress_container';
import ImmutablePureComponent from 'react-immutable-pure-component';
import UploadContainer from '../containers/upload_container';
export default class UploadForm extends ImmutablePureComponent {
static propTypes = {
mediaIds: ImmutablePropTypes.list.isRequired,
};
render () {
const { mediaIds } = this.props;
return (
<div className='compose-form__upload-wrapper'>
<UploadProgressContainer />
<div className='compose-form__uploads-wrapper'>
{mediaIds.map(id => (
<UploadContainer id={id} key={id} />
))}
</div>
</div>
);
}
}
|
src/containers/auth/SignupScreen.js | meetfranz/franz | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { inject, observer } from 'mobx-react';
import Signup from '../../components/auth/Signup';
import UserStore from '../../stores/UserStore';
import FeaturesStore from '../../stores/FeaturesStore';
import { globalError as globalErrorPropType } from '../../prop-types';
export default @inject('stores', 'actions') @observer class SignupScreen extends Component {
static propTypes = {
error: globalErrorPropType.isRequired,
};
onSignup(values) {
const { actions, stores } = this.props;
const { canSkipTrial, defaultTrialPlan, pricingConfig } = stores.features.anonymousFeatures;
if (!canSkipTrial) {
Object.assign(values, {
plan: defaultTrialPlan,
currency: pricingConfig.currencyID,
});
}
actions.user.signup(values);
}
render() {
const { stores, error } = this.props;
return (
<Signup
onSubmit={values => this.onSignup(values)}
isSubmitting={stores.user.signupRequest.isExecuting}
loginRoute={stores.user.loginRoute}
error={error}
/>
);
}
}
SignupScreen.wrappedComponent.propTypes = {
actions: PropTypes.shape({
user: PropTypes.shape({
signup: PropTypes.func.isRequired,
}).isRequired,
}).isRequired,
stores: PropTypes.shape({
user: PropTypes.instanceOf(UserStore).isRequired,
features: PropTypes.instanceOf(FeaturesStore).isRequired,
}).isRequired,
};
|
src/helpers/Html.js | bertho-zero/react-redux-universal-hot-example | import React from 'react';
import PropTypes from 'prop-types';
import serialize from 'serialize-javascript';
import Helmet from 'react-helmet';
import config from 'config';
/**
* Wrapper component containing HTML metadata and boilerplate tags.
* Used in server-side code only to wrap the string output of the
* rendered route component.
*
* The only thing this component doesn't (and can't) include is the
* HTML doctype declaration, which is added to the rendered output
* by the server.js file.
*/
const Html = ({
assets, store, content, bundles
}) => {
const head = Helmet.renderStatic();
/* eslint-disable react/no-danger */
return (
<html lang="en-US">
<head>
{head.base.toComponent()}
{head.title.toComponent()}
{head.meta.toComponent()}
{head.link.toComponent()}
{head.script.toComponent()}
<link rel="shortcut icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="manifest" href="/manifest.json" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="application-name" content="React Hot" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="apple-mobile-web-app-title" content="React Hot" />
<meta name="theme-color" content="#3677dd" />
{/* styles (will be present only in production with webpack extract text plugin) */}
{assets.styles
&& Object.keys(assets.styles).map(style => (
<link
href={assets.styles[style]}
key={style}
media="screen, projection"
rel="stylesheet"
type="text/css"
charSet="UTF-8"
/>
))}
{/* (will be present only in development mode) */}
{assets.styles && Object.keys(assets.styles).length === 0 ? (
<style dangerouslySetInnerHTML={{ __html: '#content{display:none}' }} />
) : null}
</head>
<body>
<div id="content" dangerouslySetInnerHTML={{ __html: content }} />
{store && (
<script
dangerouslySetInnerHTML={{
__html: `window.__PRELOADED__=true;window.__data=${serialize(store.getState())};`
}}
charSet="UTF-8"
/>
)}
{assets.javascript && <script src={assets.javascript.main} charSet="UTF-8" />}
{bundles.map(bundle => bundle && <script src={config.assetsPath + bundle.file} key={bundle.id} />)}
{/* (will be present only in development mode) */}
{assets.styles && Object.keys(assets.styles).length === 0 ? (
<script dangerouslySetInnerHTML={{ __html: 'document.getElementById("content").style.display="block";' }} />
) : null}
</body>
</html>
);
/* eslint-enable react/no-danger */
};
Html.propTypes = {
assets: PropTypes.shape({
styles: PropTypes.object,
javascript: PropTypes.object
}),
bundles: PropTypes.arrayOf(PropTypes.any),
content: PropTypes.string,
store: PropTypes.shape({
getState: PropTypes.func
}).isRequired
};
Html.defaultProps = {
assets: {},
bundles: [],
content: ''
};
export default Html;
|
admin/client/App/elemental/DropdownButton/index.js | helloworld3q3q/keystone | /* eslint quote-props: ["error", "as-needed"] */
import React from 'react';
import { css, StyleSheet } from 'aphrodite/no-important';
import Button from '../Button';
function DropdownButton ({ children, ...props }) {
return (
<Button {...props}>
{children}
<span className={css(classes.arrow)} />
</Button>
);
};
// NOTE
// 1: take advantage of `currentColor` by leaving border top color undefined
// 2: even though the arrow is vertically centered, visually it appears too low
// because of lowercase characters beside it
const classes = StyleSheet.create({
arrow: {
borderLeft: '0.3em solid transparent',
borderRight: '0.3em solid transparent',
borderTop: '0.3em solid', // 1
display: 'inline-block',
height: 0,
marginTop: '-0.125em', // 2
verticalAlign: 'middle',
width: 0,
// add spacing
':first-child': {
marginRight: '0.5em',
},
':last-child': {
marginLeft: '0.5em',
},
},
});
module.exports = DropdownButton;
|
docs/app/Examples/collections/Form/FieldVariations/index.js | vageeshb/Semantic-UI-React | import React from 'react'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
const FormFieldVariationsExamples = () => (
<ExampleSection title='Field Variations'>
<ComponentExample
title='Inline'
description='A field can have its label next to instead of above it.'
examplePath='collections/Form/FieldVariations/FormExampleInlineField'
/>
</ExampleSection>
)
export default FormFieldVariationsExamples
|
docs/app/Examples/modules/Dropdown/Types/DropdownExampleInlineTwo.js | shengnian/shengnian-ui-react | import React from 'react'
import { Dropdown, Header, Icon } from 'shengnian-ui-react'
const options = [
{
key: 'today',
text: 'today',
value: 'today',
content: 'Today',
},
{
key: 'this week',
text: 'this week',
value: 'this week',
content: 'This Week',
},
{
key: 'this month',
text: 'this month',
value: 'this month',
content: 'This Month',
},
]
const DropdownExampleInlineTwo = () => (
<Header as='h4'>
<Icon name='trophy' />
<Header.Content>
Trending repos
{' '}
<Dropdown inline header='Adjust time span' options={options} defaultValue={options[0].value} />
</Header.Content>
</Header>
)
export default DropdownExampleInlineTwo
|
src/app/Footer.js | halhenke/life-letters | import React from 'react';
import styles from './Footer.css';
export default class Footer extends React.Component {
render() {
return (
<footer className={styles.footer}>
<p>2015 © Hal Henke</p>
</footer>
);
}
}
|
examples/Accordion.js | 15lyfromsaturn/react-materialize | import React from 'react';
import Collapsible from '../src/Collapsible';
import CollapsibleItem from '../src/CollapsibleItem';
export default
<Collapsible accordion defaultActiveKey={1}>
<CollapsibleItem header='First' icon='filter_drama' eventKey={1}>
Lorem ipsum dolor sit amet.
</CollapsibleItem>
<CollapsibleItem header='Second' icon='place' eventKey={2}>
Lorem ipsum dolor sit amet.
</CollapsibleItem>
<CollapsibleItem header='Third' icon='whatshot' eventKey={3}>
Lorem ipsum dolor sit amet.
</CollapsibleItem>
</Collapsible>;
|
src/ParaRowTextEditor.js | OCMC-Translation-Projects/ioc-liturgical-react | import React from 'react';
import PropTypes from 'prop-types';
import {
Button
, Checkbox
, Col
, ControlLabel
, FormControl
, Glyphicon
, Grid
, Row
, Tab
, Tabs
, Well
} from 'react-bootstrap';
import { get } from 'lodash';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import FontAwesome from 'react-fontawesome';
import axios from 'axios';
import Server from './helpers/Server';
import NotesLister from './NotesLister';
import Grammar from './modules/Grammar';
import Spinner from './helpers/Spinner';
import TextNotesLister from './TextNotesLister';
import ResourceSelector from './modules/ReactSelector';
import WorkflowForm from './helpers/WorkflowForm';
/**
* Display a text to edit, with source and models as rows.
*/
export class ParaRowTextEditor extends React.Component {
constructor(props) {
super(props);
let pdfSubTitle = "";
let prefs = {};
if (props.session.userInfo && props.session.userInfo.prefs) {
prefs = props.session.userInfo.prefs;
if (prefs.includeNotesTransAdvice) {
pdfSubTitle = "A Liturgical Translator's Manual";
}
}
let citeData = [];
if (props.session.dropdowns) {
citeData = props.session.dropdowns.bibTexStylesDropdown;
}
let labels = props.session.labels;
let labelTopics = props.session.labelTopics;
this.state =
{
labels: {
thisClass: labels[labelTopics.ParaTextEditor]
, buttons: labels[labelTopics.button]
, messages: labels[labelTopics.messages]
, search: labels[labelTopics.search]
}
, citeData: citeData
, citeStyle: prefs.bibLatexStyle ? prefs.bibLatexStyle : "authoryear"
, greekSourceValue: ""
, greekSourceId: ""
, showSearchResults: false
, message: get(this.state,"message", labels[labelTopics.search].msg1)
, downloadMessage: ""
,
messageIcon: get(this.state,"messageIcon", this.messageIcons.info)
,
data: {values: [{"id": "", "value:": ""}]}
,
options: {
sizePerPage: 30
, sizePerPageList: [5, 15, 30]
, onSizePerPageList: this.onSizePerPageList
, hideSizePerPage: true
, paginationShowsTotal: true
}
,
showSelectionButtons: false
,
selectedId: ""
,
selectedValue: ""
,
selectedIdPartsPrompt: "Select one or more ID parts, then click on the search icon:"
,
selectedIdParts: [
{key: "domain", label: ""},
{key: "topic", label: ""},
{key: "key", label: ""}
]
, showIdPartSelector: false
, idColumnSize: "80px"
, editorValue: props.value
, currentDocType: props.docType
, currentId: props.idLibrary + "~" + props.idTopic + "~" + props.idKey
, currentIdLibrary: props.idLibrary
, currentIdTopic: props.idTopic
, currentIdKey: props.idKey
, domain: "*"
, selectedBook: "*"
, selectedChapter: "*"
, docProp: "id"
, matcher: "ew"
, query: "~"
+ props.idTopic
+ "~"
+ props.idKey
, pdfId: ""
, pdfTitle: ""
, pdfSubTitle: pdfSubTitle
, pdfAuthor: prefs.author ? prefs.author : ""
, pdfAuthorTitle: prefs.authorTitle ? prefs.authorTitle : ""
, pdfAuthorAffiliation: prefs.authorAffiliation ? prefs.authorAffiliation : ""
, includeAdviceNotes: prefs.includeNotesTransAdvice ? prefs.includeNotesTransAdvice : ""
, includePersonalNotes: prefs.includeNotesUser ? prefs.includeNotesUser : ""
, includeGrammar: prefs.includeGrammar ? prefs.includeGrammar : ""
, combineNotes: prefs.combineNotes ? prefs.combineNotes : ""
, createToc: prefs.createToc ? prefs.createToc : ""
, showDownloadLinks: false
, preparingDownloads: false
, biblatex: "http://ftp.math.purdue.edu/mirrors/ctan.org/macros/latex/contrib/biblatex/doc/biblatex.pdf"
, submitDisabled: true
};
this.fetchData = this.fetchData.bind(this);
this.getDownloadLinks = this.getDownloadLinks.bind(this);
this.getParaRows = this.getParaRows.bind(this);
this.getTabs = this.getTabs.bind(this);
this.getTextArea = this.getTextArea.bind(this);
this.getTitleRow = this.getTitleRow.bind(this);
this.getWorkflowPanel = this.getWorkflowPanel.bind(this);
this.getStatusIcon = this.getStatusIcon.bind(this);
this.getVisibilityIcon = this.getVisibilityIcon.bind(this);
this.handleciteStyleChange = this.handleciteStyleChange.bind(this);
this.handleDownloadRequest = this.handleDownloadRequest.bind(this);
this.handleDownloadCallback = this.handleDownloadCallback.bind(this);
this.handleEditorChange = this.handleEditorChange.bind(this);
this.handleIncludeAdviceNotesChange = this.handleIncludeAdviceNotesChange.bind(this);
this.handleIncludeGrammarChange = this.handleIncludeGrammarChange.bind(this);
this.handleIncludePersonalNotesChange = this.handleIncludePersonalNotesChange.bind(this);
this.handleCombineNotesChange = this.handleCombineNotesChange.bind(this);
this.handleCreateTocChange = this.handleCreateTocChange.bind(this);
this.handlePdfAuthorChange = this.handlePdfAuthorChange.bind(this);
this.handlePdfAuthorAffiliationChange = this.handlePdfAuthorAffiliationChange.bind(this);
this.handlePdfAuthorTitleChange = this.handlePdfAuthorTitleChange.bind(this);
this.handlePdfTitleChange = this.handlePdfTitleChange.bind(this);
this.handlePdfSubTitleChange = this.handlePdfSubTitleChange.bind(this);
this.handlePropsChange = this.handlePropsChange.bind(this);
this.handleStateChange = this.handleStateChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleValueUpdateCallback = this.handleValueUpdateCallback.bind(this);
this.handleWorkflowCallback = this.handleWorkflowCallback.bind(this);
this.notifyParentValueChanged = this.notifyParentValueChanged.bind(this);
this.setMessage = this.setMessage.bind(this);
this.submitDisabled = this.submitDisabled.bind(this);
};
componentWillMount = () => {
this.fetchData();
};
componentWillReceiveProps = (nextProps) => {
let prefs = {};
let pdfSubTitle = get(this.state, "pdfSubTitle", "");
if (nextProps.session.userInfo && nextProps.session.userInfo.prefs) {
prefs = nextProps.session.userInfo.prefs;
if (pdfSubTitle.length === 0 && prefs.includeNotesTransAdvice) {
pdfSubTitle = "A Liturgical Translator's Manual";
}
}
let citeData = [];
if (nextProps.session.dropdowns) {
citeData = nextProps.session.dropdowns.bibTexStylesDropdown;
}
let labels = nextProps.session.labels;
let labelTopics = nextProps.session.labelTopics;
this.setState((prevState, props) => {
return {
labels: {
thisClass: labels[labelTopics.ParaTextEditor]
, buttons: labels[labelTopics.button]
, messages: labels[labelTopics.messages]
, search: labels[labelTopics.search]
}
, message: get(prevState,"message", labels[labelTopics.search].msg1)
, messageIcon: get(prevState,"messageIcon", this.messageIcons.info)
, greekSourceValue: ""
, greekSourceId: ""
, citeData: citeData
, citeStyle: prefs.bibLatexStyle ? prefs.bibLatexStyle : "authoryear"
, pdfSubTitle: pdfSubTitle
, pdfAuthor: prefs.author ? prefs.author : ""
, pdfAuthorTitle: prefs.authorTitle ? prefs.authorTitle : ""
, pdfAuthorAffiliation: prefs.authorAffiliation ? prefs.authorAffiliation : ""
, includeAdviceNotes: prefs.includeNotesTransAdvice ? prefs.includeNotesTransAdvice : ""
, includePersonalNotes: prefs.includeNotesUser ? prefs.includeNotesUser : ""
, includeGrammar: prefs.includeGrammar ? prefs.includeGrammar : ""
, combineNotes: prefs.combineNotes ? prefs.combineNotes : ""
, createToc: prefs.createToc ? prefs.createToc : ""
}
}, function () { return this.handleStateChange("place holder")});
};
// if we need to do something after setState, do it here...
handleStateChange = (parm) => {
this.handlePropsChange();
};
/**
* Because we are passing back the value each time it changes,
* componentWillReceiveProps keeps getting called.
* We don't want that to result in calling fetchData unless
* the docType, library, topic, or key changed.
*/
handlePropsChange = () => {
if (this.state.currentDocType !== this.props.docType
|| this.state.currentIdLibrary !== this.props.idLibrary
|| this.state.currentIdTopic !== this.props.idTopic
|| this.state.currentIdKey !== this.props.idKey
) {
this.fetchData();
}
};
/**
* font-awesome icons for messages
* @type {{info: string, warning: string, error: string}}
*/
messageIcons = {
info: "info-circle"
, warning: "lightbulb-o"
, error: "exclamation-triangle"
// , toggleOn: "eye"
// , toggleOff: "eye-slash"
, toggleOn: "toggle-on"
, toggleOff: "toggle-off"
, simpleSearch: "minus"
, advancedSearch: "bars"
, idPatternSearch: "key"
};
setMessage(message) {
this.setState({
message: message
});
};
fetchData() {
this.setState({
message: this.state.labels.search.msg2
, messageIcon: this.messageIcons.info
});
let config = {
auth: {
username: this.props.session.userInfo.username
, password: this.props.session.userInfo.password
}
};
let parms =
"?t=" + encodeURIComponent(this.props.docType)
+ "&d=" + encodeURIComponent(this.state.domain)
+ "&b=" + encodeURIComponent(this.state.selectedBook)
+ "&c=" + encodeURIComponent(this.state.selectedChapter)
+ "&q=" + encodeURIComponent(this.state.query)
+ "&p=" + encodeURIComponent(this.state.docProp)
+ "&m=" + encodeURIComponent(this.state.matcher)
;
let path = this.props.session.restServer + Server.getWsServerDbApi() + 'docs' + parms;
axios.get(path, config)
.then(response => {
let greekSource = response.data.values.find( o => o.id.startsWith("gr_gr_cog"));
let greekSourceId = "";
let greekSourceValue = "";
let pdfTitle = this.state.pdfTitle;
if (greekSource) {
greekSourceId = greekSource.id;
greekSourceValue = greekSource.value;
if (pdfTitle.length === 0) {
if (greekSourceValue.length > 31) {
let words = greekSourceValue.substring(0,30).split(/[\s,.;]/);
if (words.length > 4) {
pdfTitle = words[0] + " " + words[1] + " " + words[2] + " " + words[3];
} else if (words.length > 3) {
pdfTitle = words[0] + " " + words[1] + " " + words[2];
} else if (words.length > 2) {
pdfTitle = words[0] + " " + words[1];
} else {
pdfTitle = words[0];
}
} else {
pdfTitle = greekSourceValue.substring(0,30);
}
}
}
let thisText = response.data.values.find( o => o.id === (this.props.idLibrary
+ "~"
+ this.props.idTopic
+ "~"
+ this.props.idKey
));
let workflow = {
assignedTo: ""
, status: "EDITING"
, visibility: "PRIVATE"
, statusIcon: "edit"
, visibilityIcon: "share-alt"
};
let originalWorkflow = {
assignedTo: ""
, status: "EDITING"
, visibility: "PRIVATE"
};
try {
if (thisText) {
if (thisText.status) {
let theStatus = thisText.status;
workflow.status = thisText.status;
originalWorkflow.status = theStatus;
workflow.statusIcon = this.getStatusIcon(thisText.status);
}
if (thisText.visibility) {
let theVisibility = thisText.visibility;
workflow.visibility = thisText.visibility;
originalWorkflow.visibility = theVisibility;
workflow.visibilityIcon = this.getVisibilityIcon(thisText.visibility);
}
}
} catch (err) {
console.log(err);
}
let values = response.data.values.filter((row) => {
return row.value.length > 0;
});
response.data.values = values;
let resultCount = 0;
let message = this.state.labels.search.foundNone;
let found = this.state.labels.search.foundMany;
if (values) {
resultCount = values.length;
if (resultCount === 0) {
message = this.state.labels.search.foundNone;
} else if (resultCount === 1) {
message = this.state.labels.search.foundOne;
} else {
message = found
+ " "
+ resultCount
+ ".";
}
}
this.setState({
message: message
, messageIcon: this.messageIcons.info
, showSearchResults: true
, data: response.data
, greekSourceId: greekSourceId
, greekSourceValue: greekSourceValue
, pdfTitle: pdfTitle
, thisText: thisText
, workflow: workflow
, originalWorkflow: originalWorkflow
}
);
})
.catch((error) => {
let message = error.message;
let messageIcon = this.messageIcons.error;
if (error && error.response && error.response.status === 404) {
message = this.state.labels.search.foundNone;
messageIcon = this.messageIcons.warning;
this.setState({data: message, message: message, messageIcon: messageIcon});
}
});
}
handleIncludeAdviceNotesChange = (evt) => {
let pdfSubTitle = this.state.pdfSubTitle;
if (this.state.includeAdviceNotes) {
if (pdfSubTitle && pdfSubTitle.startsWith("A Liturgical Translator's")) {
pdfSubTitle = "";
}
} else {
if (! pdfSubTitle) {
pdfSubTitle = "A Liturgical Translator's Manual";
}
}
this.setState(
{
includeAdviceNotes: evt.target.checked
, pdfSubTitle: pdfSubTitle
});
};
handleIncludePersonalNotesChange = (evt) => {
this.setState({ includePersonalNotes: evt.target.checked });
};
handleIncludeGrammarChange = (evt) => {
this.setState({ includeGrammar: evt.target.checked });
};
handleCombineNotesChange = (evt) => {
this.setState({ combineNotes: evt.target.checked });
};
handleCreateTocChange = (evt) => {
this.setState({ createToc: evt.target.checked });
};
getDownloadLinks = () => {
if (this.state.showDownloadLinks) {
let url = "data/" + this.state.pdfId;
return (
<Row className="App-Download-Row">
<Col className="App-Download-Col" xs={3} md={3}>
<a href={url + ".pdf"} target={"_blank"}>{this.state.labels.buttons.downloadAsPdf}</a>
</Col>
<Col className="App-Download-Col" xs={4} md={4}>
<a href={url + ".tex"} target={"_blank"}>{this.state.labels.buttons.downloadAsTex}</a>
</Col>
<Col className="App-Download-Col" xs={5} md={5}>
<a href={url + ".bib"} target={"_blank"}>{this.state.labels.buttons.downloadAsTexBib}</a>
</Col>
</Row>
);
} else {
if (this.state.preparingDownloads) {
return (
<Row className="App-Download-Row">
<Col className="App-Download-Col" xs={12} md={12}>
<Spinner message={this.state.labels.messages.preparingPdf}/>
</Col>
</Row>
);
} else {
return (<span></span>);
}
}
};
handleciteStyleChange = (selection) => {
this.setState({
citeStyle: selection["value"]
});
};
handleDownloadRequest = () => {
this.setState({
preparingDownloads: true
, showDownloadLinks: false
});
let id = "gr_gr_cog/"
+ this.props.idTopic
+ "/"
+ this.props.idKey
;
let includeAdviceNotes = "false";
let includePersonalNotes = "false";
let includeGrammar = "false";
let combineNotes = "false";
let createToc = "false";
if (this.state.includeAdviceNotes) {
includeAdviceNotes = "true";
}
if (this.state.includePersonalNotes) {
includePersonalNotes = "true";
}
if (this.state.includeGrammar) {
includeGrammar = "true";
}
if (this.state.combineNotes) {
combineNotes = "true";
}
if (this.state.includePersonalNotes) {
includePersonalNotes = "true";
}
if (this.state.createToc) {
createToc = "true";
}
let parms =
"ia=" + encodeURIComponent(includeAdviceNotes)
+ "&ip=" + encodeURIComponent(includePersonalNotes)
+ "&ig=" + encodeURIComponent(includeGrammar)
+ "&cn=" + encodeURIComponent(combineNotes)
+ "&toc=" + encodeURIComponent(createToc)
+ "&al=" + encodeURIComponent(this.props.idLibrary)
+ "&mt=" + encodeURIComponent(this.state.pdfTitle)
+ "&st=" + encodeURIComponent(this.state.pdfSubTitle)
+ "&au=" + encodeURIComponent(this.state.pdfAuthor)
+ "&at=" + encodeURIComponent(this.state.pdfAuthorTitle)
+ "&af=" + encodeURIComponent(this.state.pdfAuthorAffiliation)
+ "&cs=" + encodeURIComponent(this.state.citeStyle)
;
Server.getTextDownloads(
this.props.session.restServer
, this.props.session.userInfo.username
, this.props.session.userInfo.password
, id
, parms
, this.handleDownloadCallback
);
};
getWorkflowPanel = () => {
if (this.props.canChange && ! this.props.idLibrary.includes("_sys_")) {
return (
<Tab eventKey={"workflow"} title={this.state.labels.thisClass.workflowPanel}>
<Well>
<WorkflowForm
session={this.props.session}
callback={this.handleWorkflowCallback}
library={this.props.idLibrary}
status={this.state.workflow.status}
visibility={this.state.workflow.visibility}
/>
</Well>
</Tab>
);
}
};
getStatusIcon = (status) => {
let statusIcon = "edit";
switch (status) {
case ("EDITING"): {
statusIcon = "edit";
break;
}
case ("REVIEWING"): {
statusIcon = "eye-open";
break;
}
case ("FINALIZED"): {
statusIcon = "check";
break;
}
default: {
let statusIcon = "edit";
}
}
return statusIcon;
};
getVisibilityIcon = (visibility) => {
let visibilityIcon = "lock";
switch (visibility) {
case ("PERSONAL"): {
visibilityIcon = "lock"; // user-secret
break;
}
case ("PRIVATE"): {
visibilityIcon = "share-alt";
break;
}
case ("PUBLIC"): {
visibilityIcon = "globe";
break;
}
default: {
let visibilityIcon = "lock";
}
}
return visibilityIcon;
};
handleWorkflowCallback = ( visibility, status, assignedTo ) => {
if (visibility && status) {
let statusIcon = this.getStatusIcon(status);
let visibilityIcon = this.getVisibilityIcon(visibility);
let workflow = this.state.workflow;
workflow.status = status;
workflow.visibility = visibility;
workflow.assignedToUser = assignedTo;
workflow.visibilityIcon = visibilityIcon;
workflow.statusIcon = statusIcon;
this.setState(
{
workflow: workflow
}, this.submitDisabled()
);
}
};
getPdf = () => {
this.setState({
preparingDownloads: true
, showDownloadLinks: false
});
let parms =
"id=" + encodeURIComponent(id)
;
Server.restGetPdf(
this.props.session.restServer
, Server.getDbServerAgesPdfApi()
, this.props.session.userInfo.username
, this.props.session.userInfo.password
, parms
, this.state.pdfFilename
)
.then( response => {
this.setState(
{
data: response
, preparingDownloads: false
, showDownloadLinks: true
}
);
})
.catch( error => {
this.setState(
{
data: {
values:
[
{
"id": ""
, "library": ""
, "topic": ""
, "key": ""
, "value:": ""
}
]
, userMessage: error.userMessage
, developerMessage: error.developerMessage
, messageIcon: error.messageIcon
, status: error.status
, showSearchResults: false
, resultCount: 0
, fetching: false
}
})
})
;
};
handleDownloadCallback = (restCallResult) => {
if (restCallResult && restCallResult.data && restCallResult.data.values) {
let data = restCallResult.data.values[0];
let pdfId = data.pdfId;
let pdfFilename = data.pdfFilename;
this.setState(
{
pdfId: pdfId
, pdfFilename: pdfFilename
, preparingDownloads: false
, showDownloadLinks: true
}
);
}
};
handlePdfStatusCallback = (result) => {
let statusMessage = this.state.labels.messages.couldNotGenerate;
let showPdfButton = false;
if (result.code === 200) {
let statusMessage = "";
showPdfButton = true;
}
this.setState({
fetchingPdf: false
, showPdfButton: showPdfButton
, generationStatusMessage: statusMessage
});
};
getTextArea = () => {
if (this.props.canChange && ! this.props.idLibrary.includes("_sys_")) {
return (
<div className="row">
<Well>
<div>
<ControlLabel>
{this.state.labels.thisClass.yourTranslation
+ " (" + this.props.idLibrary + ")"}
</ControlLabel>
</div>
<textarea
className="App-Modal-Editor-TextArea"
rows="4"
cols="100"
spellCheck="true"
value={this.state.editorValue}
onChange={this.handleEditorChange}
>
</textarea>
<div>
<Button
type="submit"
bsStyle="primary"
disabled={this.state.submitDisabled}
onClick={this.handleSubmit}
>
{this.state.labels.thisClass.submit}
</Button>
<span className="App App-message"><FontAwesome
name={this.state.messageIcon}/>
{this.state.message}
</span>
<span className="App App-Text-Editor-Workflow-Glyph">
<Glyphicon glyph={this.state.workflow.statusIcon}/>
<FontAwesome name={this.state.workflow.visibilityIcon}/>
</span>
</div>
</Well>
</div>
)
} else {
return (<span className="App App-no-display"></span>);
}
};
submitDisabled = () => {
if (this.state.editorValue === this.props.value
&& this.state.originalWorkflow.status === this.state.workflow.status
&& this.state.originalWorkflow.visibility === this.state.workflow.visibility
) {
this.setState({submitDisabled: true});
} else {
this.setState({submitDisabled: false});
}
};
handlePdfAuthorChange = (e) => {
this.setState({pdfAuthor: e.target.value});
};
handlePdfAuthorAffiliationChange = (e) => {
this.setState({pdfAuthorAffiliation: e.target.value});
};
handlePdfAuthorTitleChange = (e) => {
this.setState({pdfAuthorTitle: e.target.value});
};
handlePdfTitleChange = (e) => {
this.setState({pdfTitle: e.target.value});
};
handlePdfSubTitleChange = (e) => {
this.setState({pdfSubTitle: e.target.value});
};
getTitleRow = () => {
return (
<div>
<Row className="App show-grid App-PDF-Title-Row">
<Col xs={3} md={3}>
<ControlLabel>{this.state.labels.thisClass.pdfTitle}:</ControlLabel>
</Col>
<Col xs={9} md={9}>
<FormControl
id={"fxPdfTitle"}
className={"App App-PDF-Title"}
type="text"
value={this.state.pdfTitle}
placeholder={this.state.labels.thisClass.pdfTitle}
onChange={this.handlePdfTitleChange}
/>
</Col>
</Row>
<Row className="App show-grid App-PDF-Title-Row">
<Col xs={3} md={3}>
<ControlLabel>{this.state.labels.thisClass.pdfSubTitle}:</ControlLabel>
</Col>
<Col xs={9} md={9}>
<FormControl
id={"fxPdfSubTitle"}
className={"App App-PDF-Title"}
type="text"
value={this.state.pdfSubTitle}
placeholder={this.state.labels.thisClass.pdfSubTitle}
onChange={this.handlePdfSubTitleChange}
/>
</Col>
</Row>
<Row className="App show-grid App-PDF-Author-Row">
<Col xs={3} md={3}>
<ControlLabel>{this.state.labels.thisClass.pdfAuthor}:</ControlLabel>
</Col>
<Col xs={9} md={9}>
<FormControl
id={"fxPdfAuthor"}
className={"App App-PDF-Author"}
type="text"
value={this.state.pdfAuthor}
placeholder={this.state.labels.thisClass.pdfAuthor}
onChange={this.handlePdfAuthorChange}
/>
</Col>
</Row>
<Row className="App show-grid App-PDF-Author-Row">
<Col xs={3} md={3}>
<ControlLabel>{this.state.labels.thisClass.pdfAuthorTitle}:</ControlLabel>
</Col>
<Col xs={9} md={9}>
<FormControl
id={"fxPdfAuthorTitle"}
className={"App App-PDF-Author"}
type="text"
value={this.state.pdfAuthorTitle}
placeholder={this.state.labels.thisClass.pdfAuthorTitle}
onChange={this.handlePdfAuthorTitleChange}
/>
</Col>
</Row>
<Row className="App show-grid App-PDF-Author-Row">
<Col xs={3} md={3}>
<ControlLabel>{this.state.labels.thisClass.pdfAuthorAffiliation}:</ControlLabel>
</Col>
<Col xs={9} md={9}>
<FormControl
id={"fxPdfAuthorAffiliation"}
className={"App App-PDF-Author"}
type="text"
value={this.state.pdfAuthorAffiliation}
placeholder={this.state.labels.thisClass.pdfAuthorAffiliation}
onChange={this.handlePdfAuthorAffiliationChange}
/>
</Col>
</Row>
<Row className="App show-grid App-PDF-BibStyle-Row">
<Col xs={3} md={3}>
<ControlLabel>{this.state.labels.thisClass.citeStyle}:</ControlLabel>
</Col>
<Col xs={5} md={5}>
<div className="App-PDF-BibStyle-Dropdown">
<ResourceSelector
title={""}
initialValue={this.state.citeStyle}
resources={this.state.citeData}
changeHandler={this.handleciteStyleChange}
multiSelect={false}
/>
</div>
</Col>
<Col xs={4} md={4}>
<a className="App-See-Biblatex" href={this.state.biblatex} target={"_blank"}>{this.state.labels.thisClass.seeBiblatex}</a>
</Col>
</Row>
</div>
);
};
getTabs = () => {
return (
<div className="row">
<Well>
<Tabs id="App-Text-Node-Editor-Tabs" animation={false}>
<Tab eventKey={"textnotes"} title={
this.state.labels.thisClass.textualNotesPanelTitle}>
<Well>
<TextNotesLister
session={this.props.session}
topicId={this.state.currentId}
topicText={this.props.value}
/>
</Well>
</Tab>
<Tab eventKey={"grammar"} title={
this.state.labels.thisClass.grammarPanelTitle}>
<Grammar
session={this.props.session}
idTopic={this.props.idTopic}
idKey={this.props.idKey}
/>
</Tab>
<Tab eventKey={"usernote"} title={
this.state.labels.thisClass.userNotesPanelTitle}>
<Well>
<NotesLister
session={this.props.session}
type={"NoteUser"}
topicId={this.state.currentId}
topicText={this.props.value}
/>
</Well>
</Tab>
<Tab eventKey={"download"} title={
this.state.labels.thisClass.downloadPanelTitle}>
<Well>
<Well>
{this.getTitleRow()}
<Row>
<Col className="App-Info-Row" xs={12} md={12}>
<Checkbox
checked={this.state.combineNotes}
onChange={this.handleCombineNotesChange}
inline={true}
>
{this.state.labels.thisClass.combineNotes}
</Checkbox>
</Col>
</Row>
<Row>
<Col className="App-Info-Row" xs={12} md={12}>
<Checkbox
checked={this.state.createToc}
onChange={this.handleCreateTocChange}
inline={true}
>
{this.state.labels.thisClass.createToc}
</Checkbox>
</Col>
</Row>
<Row className="App-Info-Row">
<Col className="" xs={12} md={12}>
<Checkbox
checked={this.state.includeGrammar}
onChange={this.handleIncludeGrammarChange}
inline={true}
>
{this.state.labels.thisClass.includeGrammar}
</Checkbox>
</Col>
</Row>
<Row className="App-Info-Row">
<Col className="" xs={12} md={12}>
<Checkbox
checked={this.state.includePersonalNotes}
onChange={this.handleIncludePersonalNotesChange}
inline={true}
>
{this.state.labels.thisClass.includePersonalNotes}
</Checkbox>
</Col>
</Row>
<Row>
<Col className="App-Info-Row" xs={12} md={12}>
<Checkbox
checked={this.state.includeAdviceNotes}
onChange={this.handleIncludeAdviceNotesChange}
inline={true}
>
{this.state.labels.thisClass.includeAdviceNotes}
</Checkbox>
</Col>
</Row>
</Well>
<Row className="App-Info-Row">
<Button
type="submit"
bsStyle="primary"
onClick={this.handleDownloadRequest}
>
{this.state.labels.buttons.createFiles}
</Button>
</Row>
{this.getDownloadLinks()}
</Well>
</Tab>
{this.getWorkflowPanel()}
</Tabs>
</Well>
</div>
);
};
handleEditorChange = (event) => {
this.setState({
editorValue: event.target.value
}, this.submitDisabled);
if (this.props.onChange) {
this.props.onChange(event.target.value);
}
};
notifyParentValueChanged = () => {
if (this.props.onSubmit
&& this.state.message === this.state.labels.messages.updated) {
this.props.onSubmit(
this.state.editorValue
);
}
};
handleValueUpdateCallback = (restCallResult) => {
if (restCallResult) {
let message = restCallResult.message;
if (message === "OK") {
message = this.state.labels.messages.updated;
}
this.setState({
message: message
, messageIcon: restCallResult.messageIcon
},this.notifyParentValueChanged);
}
};
handleSubmit = (event) => {
this.setState({
message: this.state.labels.messages.updating
, messageIcon: this.messageIcons.info
});
let parms =
"i=" + encodeURIComponent(
this.props.idLibrary
+ "~"
+ this.props.idTopic
+ "~" + this.props.idKey
)
+ "&t=" + encodeURIComponent("Liturgical")
;
Server.putValue(
this.props.session.restServer
, this.props.session.userInfo.username
, this.props.session.userInfo.password
, {
value: this.state.editorValue
, seq: undefined
, status: this.state.workflow.status
, visibility: this.state.workflow.visibility
}
, parms
, this.handleValueUpdateCallback
);
};
getParaRows = () => {
if (this.state.showSearchResults) {
return (
<div className="row">
<ControlLabel>
{this.state.labels.thisClass.showingMatchesFor + " " + this.props.idTopic + "~" + this.props.idKey}
</ControlLabel>
<Well>
<BootstrapTable
data={this.state.data.values}
trClassName={"App-data-tr"}
striped
hover
pagination
options={ this.state.options }
>
<TableHeaderColumn
isKey
dataField='id'
dataSort={ true }
hidden
>ID</TableHeaderColumn>
<TableHeaderColumn
dataField='library'
dataSort={ true }
width={this.state.idColumnSize}>Domain</TableHeaderColumn>
<TableHeaderColumn
dataField='value'
dataSort={ true }
>Value</TableHeaderColumn>
</BootstrapTable>
</Well>
</div>
)
} else {
return (
<Spinner message={this.state.labels.messages.retrieving}/>
)
}
};
render() {
return (
<div className="App App-Text-Note-Editor">
{(! this.state.showSearchResults) ? <Spinner message={this.state.labels.messages.retrieving}/>
:
<div className="App-ParaRow-Text-Editor">
<Grid>
{this.getParaRows()}
{this.getTextArea()}
{this.getTabs()}
</Grid>
</div>
}
</div>
);
}
}
ParaRowTextEditor.propTypes = {
session: PropTypes.object.isRequired
, docType: PropTypes.string.isRequired
, idLibrary: PropTypes.string.isRequired
, idTopic: PropTypes.string.isRequired
, idKey: PropTypes.string.isRequired
, value: PropTypes.string.isRequired
, canChange: PropTypes.bool.isRequired
, canReview: PropTypes.bool
, onSubmit: PropTypes.func
, onChange: PropTypes.func
};
export default ParaRowTextEditor;
|
stories/killop.js | ramonfm/killop | import React from 'react';
import { storiesOf } from '@kadira/storybook';
import KillopComponent from '../src/components/killop';
import ConnectedKillopComponent from '../src/components/';
storiesOf('KillopComponent', module)
.add('connected to store', () => <ConnectedKillopComponent />)
.add('enabled', () => <KillopComponent status="enabled" />)
.add('disabled', () => <KillopComponent status="disabled" />);
|
Example/index.android.js | cuonghuynhvan/react-native-camera-android-simple | import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
Button
} from 'react-native';
import Camera from 'react-native-camera-android-simple';
const Type = {
FRONT: 'front',
BACK: 'back'
};
const styles = StyleSheet.create({
container: {
flex: 1
},
preview: {
flex: 1
},
captureContainer: {
position: 'absolute',
flexDirection: 'row',
left: 0,
right: 0,
bottom: 40,
alignItems: 'center',
zIndex: 1
},
captureChildContainer: {
flex: 1,
alignItems: 'flex-start'
},
captureButton: {
borderRadius: 64,
borderWidth: 0,
width: 53,
height: 53,
backgroundColor: '#ffffff',
paddingLeft: 0,
paddingRight: 0
},
reverseCameraButton: {
borderWidth: 0,
marginLeft: 34,
width: 53,
height: 53,
paddingLeft: 0,
paddingRight: 0
},
circleBorder: {
width: 59,
height: 59,
justifyContent: 'center',
alignItems: 'center',
borderWidth: 1,
borderRadius: 64,
borderColor: '#ffffff',
backgroundColor: 'transparent'
}
});
export default class Example extends Component {
constructor(props) {
super(props);
this._onCapturePress = this._onCapturePress.bind(this);
this._onReversePress = this._onReversePress.bind(this);
this.state = {
type: Type.BACK
};
}
_onReversePress() {
const { type } = this.state;
this.setState({
type: type === Type.BACK ? Type.FRONT : Type.BACK
});
}
_onCapturePress() {
const options = {};
this.camera.capture({ metadata: options })
.then((data) => {
// Handle you callback data here.
})
.catch((err) => {
// Handle error here
});
}
_renderCameraButtons() {
return (
<View
style={styles.captureContainer}
accessibilityLabel="Camera_Container"
>
<View style={styles.captureChildContainer} />
<View style={styles.circleBorder}>
<Button
onPress={this._onCapturePress}
style={styles.captureButton}
title="[capture]"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
</View>
<View style={styles.captureChildContainer}>
<Button
style={styles.reverseCameraButton}
onPress={this._onReversePress}
title="[Change]"
color="#999999"
accessibilityLabel="Learn more about this purple button"
/>
</View>
</View>
);
}
render() {
const { type } = this.state;
return (
<View
style={styles.preview}
>
<Camera
ref={(instance) => {
this.camera = instance;
}}
style={styles.preview}
type={type}
/>
{this._renderCameraButtons()}
</View>
);
}
}
AppRegistry.registerComponent('Example', () => Example);
|
src/ProjectInput.js | Miloucodaisseur/task_manager | import React from 'react';
import jQuery from 'jquery';
class ProjectInput extends React.Component {
constructor() {
super();
}
onSubmitForm(event) {
event.preventDefault();
let component = this;
let title = this.refs.newProjectTitle.value;
let description = this.refs.newProjectDescription.value;
let newProject = {
id: null,
title: title,
description: description
};
jQuery.ajax({
type: "POST",
url: "https://projectapitask.herokuapp.com/projects.json",
data: JSON.stringify({
project: newProject
}),
contentType: "application/json",
dataType: "json"
})
.done(function(data) {
component.props.onChange();
component.refs.newProjectTitle.value = "";
component.refs.newProjectDescription.value = "";
})
.fail(function(error) {
console.log(error);
});
}
render() {
var style = {
width: '31%',
backgroundColor: '#fff',
margin: '5px',
display: 'inline-block',
verticalAlign: 'top',
padding: '20px'
}
var input = {
height: '35px',
width: '100%',
padding: '0',
borderStyle: 'none',
border: 'none',
outline: '0',
fontSize: '24px',
fontFamily: 'helvetica-light',
color: '#D11F57',
backgroundImage: 'url(http://www.tjinauyeung.nl/plus-icon.png)',
backgroundSize: 'contain',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'right'
}
var textarea = {
marginTop: '20px',
width: '100%',
height: '130px',
borderStyle: 'none',
border: 'none',
outline: '0',
fontSize: '16px'
}
var add = {
width: '140px',
height: '30px',
fontFamily: 'helvetica-light',
fontSize: '12px',
textTransform: 'uppercase',
color: 'white',
padding: '5px',
border: 'none',
backgroundColor: '#00ADB0',
borderRadius: '3px',
letterSpacing: '1px',
outline: '0'
}
var user = {
width: '50px',
height: '50px',
marginRight: '20px',
marginBottom: '20px',
borderRadius: '50%',
display: 'inline-block'
}
var adduser = {
fontWeight: '100',
color: 'lightgrey',
marginTop: '20px'
}
return (
<div style={style}>
<form onSubmit={this.onSubmitForm.bind(this)}>
<input style={input} ref="newProjectTitle" placeholder="Add a new project"/>
<textarea style={textarea} rows="5" placeholder="Add your project description here. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perspiciatis doloremque ad harum numquam dicta voluptatibus voluptates quidem quisquam, nam voluptatum deserunt possimus? Expedita quasi sequi error incidunt molestiae pariatur quod?" ref="newProjectDescription"/>
<h2 style={adduser}>Members:</h2>
<img style={user} src="https://qph.is.quoracdn.net/main-qimg-498de3782ec00063441d03e10b7548c4?convert_to_webp=true" />
<img style={user} src="https://qph.is.quoracdn.net/main-qimg-498de3782ec00063441d03e10b7548c4?convert_to_webp=true" />
<img style={user} src="http://www.tjinauyeung.nl/adduser.jpg" />
<button style={add} type="submit">Add</button>
</form>
</div>
);
}
}
export default ProjectInput;
|
tests/lib/rules/vars-on-top.js | vitorbal/eslint | /**
* @fileoverview Tests for vars-on-top rule.
* @author Danny Fritz
* @author Gyandeep Singh
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const rule = require("../../../lib/rules/vars-on-top"),
EslintTester = require("../../../lib/testers/rule-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
const ruleTester = new EslintTester();
ruleTester.run("vars-on-top", rule, {
valid: [
[
"var first = 0;",
"function foo() {",
" first = 2;",
"}"
].join("\n"),
[
"function foo() {",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" if (true) {",
" first = true;",
" } else {",
" first = 1;",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" var third;",
" var fourth = 1, fifth, sixth = third;",
" var seventh;",
" if (true) {",
" third = true;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var i;",
" for (i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var outer;",
" function inner() {",
" var inner = 1;",
" var outer = inner;",
" }",
" outer = 1;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" //Hello",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" /*",
" Hello Clarice",
" */",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var first;",
" first = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var third;",
" third = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var bar = function(){",
" var third;",
" third = 5;",
" }",
" first = 5;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" first.onclick(function(){",
" var third;",
" third = 5;",
" });",
" first = 5;",
"}"
].join("\n"),
{
code: [
"function foo() {",
" var i = 0;",
" for (let j = 0; j < 10; j++) {",
" alert(j);",
" }",
" i = i + 1;",
"}"
].join("\n"),
parserOptions: {
ecmaVersion: 6
}
},
"'use strict'; var x; f();",
"'use strict'; 'directive'; var x; var y; f();",
"function f() { 'use strict'; var x; f(); }",
"function f() { 'use strict'; 'directive'; var x; var y; f(); }",
{code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", parserOptions: { sourceType: "module" }},
{
code: [
"export var x;",
"var y;",
"var z;"
].join("\n"),
parserOptions: {
ecmaVersion: 6,
sourceType: "module"
}
},
{
code: [
"var x;",
"export var y;",
"var z;"
].join("\n"),
parserOptions: {
ecmaVersion: 6,
sourceType: "module"
}
},
{
code: [
"var x;",
"var y;",
"export var z;"
].join("\n"),
parserOptions: {
ecmaVersion: 6,
sourceType: "module"
}
}
],
invalid: [
{
code: [
"var first = 0;",
"function foo() {",
" first = 2;",
" second = 2;",
"}",
"var second = 0;"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" first = 1;",
" first = 2;",
" first = 3;",
" first = 4;",
" var second = 1;",
" second = 2;",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" if (true) {",
" var second = true;",
" }",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" for (var i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" for (i = 0; i < first; i ++) {",
" var second = i;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" switch (first) {",
" case 10:",
" var hello = 1;",
" break;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" var hello = 1;",
" } catch (e) {",
" alert('error');",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" asdf;",
" } catch (e) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" while (first) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" do {",
" var hello = 1;",
" } while (first == 10);",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" for (var item in first) {",
" item++;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"var foo = () => {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
parserOptions: { ecmaVersion: 6 },
errors: [
{
message: "All 'var' declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: "'use strict'; 0; var x; f();",
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "'use strict'; var x; 'directive'; var y; f();",
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; 0; var x; f(); }",
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }",
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: [
"export function f() {}",
"var x;"
].join("\n"),
parserOptions: {
ecmaVersion: 6,
sourceType: "module"
},
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: [
"var x;",
"export function f() {}",
"var y;"
].join("\n"),
parserOptions: {
ecmaVersion: 6,
sourceType: "module"
},
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: [
"import {foo} from 'foo';",
"export {foo};",
"var test = 1;"
].join("\n"),
parserOptions: {
ecmaVersion: 6,
sourceType: "module"
},
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: [
"export {foo} from 'foo';",
"var test = 1;"
].join("\n"),
parserOptions: {
ecmaVersion: 6,
sourceType: "module"
},
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: [
"export * from 'foo';",
"var test = 1;"
].join("\n"),
parserOptions: {
ecmaVersion: 6,
sourceType: "module"
},
errors: [{message: "All 'var' declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
}
]
});
|
packages/bonde-styleguide/src/cards/Tooltip/Tooltip.js | ourcities/rebu-client | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import Icon from '../../content/Icon/Icon'
import Button from '../../content/Button/Button'
import Backdrop from '../../layout/Backdrop/Backdrop'
import { borderSpacing, borderSpacingPropTypes } from '../../utils'
const CloseButton = styled(({ className, onClose }) => (
<div className={className}>
<Button flat onClick={onClose}>
<Icon name='times' size={12} color='#FFFFFF' />
</Button>
</div>
))`
position: absolute;
top: 12px;
right: 12px;
& > ${Button} {
padding: 0;
min-width: 38px;
}
`
const CardTooltip = styled(({ className, onClose, Content }) => (
<div className={className}>
{onClose && <CloseButton onClose={onClose} />}
<Content />
</div>
))`
color: #FFFFFF;
border-radius: 1px;
background-color: #424242;
box-shadow: 2px 1px 14px 11px rgba(0, 0, 0, 0.04);
padding: 30px;
position: absolute;
z-index: 10;
${props => props.margin && borderSpacing('margin', props.margin)}
${props => props.minWidth && `
min-width: ${props.minWidth}px;
`}
${props => props.width && `
width: ${props.width}px;
`}
${props => props.minHeight && `
min-height: ${props.minHeight}px;
`}
${props => props.small && `
padding: 15px;
`}
&:before {
content: '';
position: absolute;
border: 8px solid transparent;
${props => props.placement.startsWith('left') && `
right: -16px;
border-left-color: #424242;
`}
${props => props.placement.startsWith('right') && `
left: -16px;
border-right-color: #424242;
`}
${props => props.placement.startsWith('top') && `
bottom: -16px;
border-top-color: #424242;
`}
${props => props.placement.startsWith('bottom') && `
top: -16px;
border-bottom-color: #424242;
`}
${props => props.placement.endsWith('top') && `
top: 8%;
`}
${props => props.placement.endsWith('bottom') && `
bottom: 8%;
`}
${props => props.placement.endsWith('left') && `
left: 8%;
`}
${props => props.placement.endsWith('right') && `
right: 8%;
`}
/**
* TODO: Needs to fix middle positions.
*/
${props => ['top-middle', 'bottom-middle'].includes(props.placement) && `
left: calc(50% - 8px);
`}
${props => ['right-middle', 'left-middle'].includes(props.placement) && `
top: calc(50% - 8px);
`}
}
${props => props.placement.startsWith('top') && `
margin-bottom: 8px;
bottom: 103%;
`}
${props => props.placement.startsWith('bottom') && `
margin-top: 8px;
top: 103%;
`}
${props => props.placement.startsWith('left') && `
margin-right: 8px;
right: 103%;
`}
${props => props.placement.startsWith('right') && `
margin-left: 8px;
left: 103%;
`}
${props => props.placement.endsWith('top') && `
top: 0;
`}
${props => props.placement.endsWith('bottom') && `
bottom: 0;
`}
${props => props.placement.endsWith('left') && `
left: 0;
`}
${props => props.placement.endsWith('right') && `
right: 0;
`}
/**
* TODO: Needs to fix middle positions.
*/
${props => ['top-middle', 'bottom-middle'].includes(props.placement) && `
left: calc(50% - 41px);
`}
${props => ['right-middle', 'left-middle'].includes(props.placement) && `
top: calc(50% - 41px);
`}
${props => props.position && props.position.top && `top: ${props.position.top};`}
${props => props.position && props.position.bottom && `bottom: ${props.position.bottom};`}
${props => props.position && props.position.left && `left: ${props.position.left};`}
${props => props.position && props.position.right && `right: ${props.position.right};`}
`
const Tooltip = styled(({ className, children, nolock, backdropClose, show, ...props }) => (
<div className={className}>
{show && !nolock && <Backdrop onClick={backdropClose ? props.onClose : undefined} />}
{show && <CardTooltip {...props} />}
{children}
</div>
))`
display: inline-block;
position: relative;
width: 100%;
`
const { oneOfType, oneOf, node, func, bool, shape, number, string } = PropTypes
Tooltip.propTypes = {
/** The component that will be wrapped with the tooltip. */
children: oneOfType([node, func]).isRequired,
/** The minimum width of tooltip. */
minWidth: number,
/** The minimum height of tooltip. */
minHeight: number,
/** The content that will we rendered inside of the tooltip. */
Content: oneOfType([node, func]).isRequired,
/** If pass this prop, the backdrop will not be rendered. */
nolock: bool,
/** Enable this to show the tooltip. */
show: bool,
/** The function that will be executed to close the tooltip. */
onClose: func,
/** Enable this to execute the `onClose` function when Backdrop was clicked. */
backdropClose: bool,
/** The position that the tooltip will be placed around the target. */
placement: oneOf([
'top-left',
'top-middle',
'top-right',
'right-top',
'right-middle',
'right-bottom',
'bottom-left',
'bottom-middle',
'bottom-right',
'left-top',
'left-middle',
'left-bottom',
]),
/** Manually set the position of tooltip relative to the target. */
position: shape({
top: string,
bottom: string,
left: string,
right: string,
}),
margin: borderSpacingPropTypes
}
Tooltip.defaultProps = {
nolock: false,
backdropClose: false,
show: true,
placement: 'right-top',
position: {},
}
Tooltip.displayName = 'Tooltip'
/* @component */
export default Tooltip
|
routes/GetStarted/GetStarted.js | RickFrom1987/rickfrom1987.com | /**
* React App SDK (https://github.com/kriasoft/react-app)
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import s from './GetStarted.css';
import { title, html } from './GetStarted.md';
class AboutPage extends React.Component {
componentDidMount() {
document.title = title;
}
render() {
return (
<Layout className={s.content}>
<h1>{title}</h1>
<div dangerouslySetInnerHTML={{ __html: html }} />
</Layout>
);
}
}
export default AboutPage;
|
actor-apps/app-web/src/app/components/activity/GroupProfile.react.js | alessandrostone/actor-platform | import React from 'react';
import DialogActionCreators from 'actions/DialogActionCreators';
import LoginStore from 'stores/LoginStore';
import PeerStore from 'stores/PeerStore';
import DialogStore from 'stores/DialogStore';
import InviteUserActions from 'actions/InviteUserActions';
import AvatarItem from 'components/common/AvatarItem.react';
import InviteUser from 'components/modals/InviteUser.react';
import GroupProfileMembers from 'components/activity/GroupProfileMembers.react';
const getStateFromStores = (groupId) => {
const thisPeer = PeerStore.getGroupPeer(groupId);
return {
thisPeer: thisPeer,
isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer)
};
};
class GroupProfile extends React.Component {
static propTypes = {
group: React.PropTypes.object.isRequired
};
componentWillMount() {
DialogStore.addNotificationsListener(this.whenNotificationChanged);
}
componentWillUnmount() {
DialogStore.removeNotificationsListener(this.whenNotificationChanged);
}
componentWillReceiveProps(newProps) {
this.setState(getStateFromStores(newProps.group.id));
}
constructor(props) {
super(props);
this.onNotificationChange = this.onNotificationChange.bind(this);
this.state = getStateFromStores(this.props.group.id);
}
onAddMemberClick(group) {
InviteUserActions.modalOpen(group);
}
onLeaveGroupClick(groupId) {
DialogActionCreators.leaveGroup(groupId);
}
onNotificationChange(event) {
DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked);
}
whenNotificationChanged = () => {
this.setState(getStateFromStores(this.props.group.id));
};
render() {
const group = this.props.group;
const myId = LoginStore.getMyId();
const isNotificationsEnabled = this.state.isNotificationsEnabled;
let memberArea;
let adminControls;
if (group.adminId === myId) {
adminControls = (
<li className="profile__list__item">
<a className="red">Delete group</a>
</li>
);
}
if (DialogStore.isGroupMember(group)) {
memberArea = (
<div>
<div className="notifications">
<label htmlFor="notifications">Enable Notifications</label>
<div className="switch pull-right">
<input checked={isNotificationsEnabled} id="notifications" onChange={this.onNotificationChange.bind(this)} type="checkbox"/>
<label htmlFor="notifications"></label>
</div>
</div>
<GroupProfileMembers groupId={group.id} members={group.members}/>
<ul className="profile__list profile__list--controls">
<li className="profile__list__item">
<a className="link__blue" onClick={this.onAddMemberClick.bind(this, group)}>Add member</a>
</li>
<li className="profile__list__item">
<a className="link__red" onClick={this.onLeaveGroupClick.bind(this, group.id)}>Leave group</a>
</li>
{adminControls}
</ul>
{/*
<footer className="profile__controls">
<a className="button button--wide" onClick={this.onAddMemberClick.bind(this, group)}>Add member</a>
<a className="button button--wide" onClick={this.onLeaveGroupClick.bind(this, group.id)}>Leave group</a>
</footer>
*/}
<InviteUser/>
</div>
);
}
return (
<div className="activity__body profile">
<div className="profile__name">
<AvatarItem image={group.bigAvatar}
placeholder={group.placeholder}
size="medium"
title={group.name}/>
<h3>{group.name}</h3>
</div>
{memberArea}
</div>
);
}
}
export default GroupProfile;
|
src/ui/layout/Auth.js | dhruv-kumar-jha/productivity-frontend | 'use strict';
import React from 'react';
import AuthHeader from 'app/components/common/AuthHeader';
import { I18n } from './I18n';
const Default = (props) => {
return (
<I18n fetch={ false }>
<div className="has-fh">
<AuthHeader />
<main className="body-wrapper">
{ props.children }
</main>
</div>
</I18n>
)
}
export default Default;
|
src/components/Header/Header.js | larsvinter/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react';
import styles from './Header.css';
import withStyles from '../../decorators/withStyles';
import Link from '../Link';
import Navigation from '../Navigation';
@withStyles(styles)
class Header extends Component {
render() {
return (
<div className="Header">
<div className="Header-container">
<a className="Header-brand" href="/" onClick={Link.handleClick}>
<img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" />
<span className="Header-brandTxt">Your Company</span>
</a>
<Navigation className="Header-nav" />
<div className="Header-banner">
<h1 className="Header-bannerTitle">React</h1>
<p className="Header-bannerDesc">Complex web apps made easy</p>
</div>
</div>
</div>
);
}
}
export default Header;
|
static/src/components/notAuthenticatedComponent.js | kdog1425/React-Redux-Flask-Web-Crawler | import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { browserHistory } from 'react-router';
import * as actionCreators from '../actions/auth';
function mapStateToProps(state) {
return {
token: state.auth.token,
userName: state.auth.userName,
isAuthenticated: state.auth.isAuthenticated,
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(actionCreators, dispatch);
}
export function requireNoAuthentication(Component) {
class notAuthenticatedComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
loaded: false,
};
}
componentWillMount() {
this.checkAuth();
}
componentWillReceiveProps(nextProps) {
this.checkAuth(nextProps);
}
checkAuth(props = this.props) {
if (props.isAuthenticated) {
browserHistory.push('/main');
} else {
const token = localStorage.getItem('token');
if (token) {
fetch('api/is_token_valid', {
method: 'post',
credentials: 'include',
headers: {
'Accept': 'application/json', // eslint-disable-line quote-props
'Content-Type': 'application/json',
},
body: JSON.stringify({ token }),
})
.then(res => {
if (res.status === 200) {
this.props.loginUserSuccess(token);
browserHistory.push('/main');
} else {
this.setState({
loaded: true,
});
}
});
} else {
this.setState({
loaded: true,
});
}
}
}
render() {
return (
<div>
{!this.props.isAuthenticated && this.state.loaded
? <Component {...this.props} />
: null
}
</div>
);
}
}
notAuthenticatedComponent.propTypes = {
loginUserSuccess: React.PropTypes.func,
isAuthenticated: React.PropTypes.bool,
};
return connect(mapStateToProps, mapDispatchToProps)(notAuthenticatedComponent);
}
|
src/svg-icons/image/photo-size-select-actual.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoSizeSelectActual = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3C2 3 1 4 1 5v14c0 1.1.9 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zM5 17l3.5-4.5 2.5 3.01L14.5 11l4.5 6H5z"/>
</SvgIcon>
);
ImagePhotoSizeSelectActual = pure(ImagePhotoSizeSelectActual);
ImagePhotoSizeSelectActual.displayName = 'ImagePhotoSizeSelectActual';
ImagePhotoSizeSelectActual.muiName = 'SvgIcon';
export default ImagePhotoSizeSelectActual;
|
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/node_modules/rc-select/es/Select.js | bhathiya/test | import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _extends from 'babel-runtime/helpers/extends';
import React from 'react';
import ReactDOM from 'react-dom';
import createClass from 'create-react-class';
import KeyCode from 'rc-util/es/KeyCode';
import classnames from 'classnames';
import Animate from 'rc-animate';
import classes from 'component-classes';
import { getPropValue, getValuePropValue, isCombobox, isMultipleOrTags, isMultipleOrTagsOrCombobox, isSingleMode, toArray, findIndexInValueByKey, UNSELECTABLE_ATTRIBUTE, UNSELECTABLE_STYLE, preventDefaultEvent, findFirstMenuItem, includesSeparators, splitBySeparators, findIndexInValueByLabel } from './util';
import SelectTrigger from './SelectTrigger';
import FilterMixin from './FilterMixin';
import { SelectPropTypes } from './PropTypes';
function noop() {}
function saveRef(name, component) {
this[name] = component;
}
function chaining() {
for (var _len = arguments.length, fns = Array(_len), _key = 0; _key < _len; _key++) {
fns[_key] = arguments[_key];
}
return function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
for (var i = 0; i < fns.length; i++) {
if (fns[i] && typeof fns[i] === 'function') {
fns[i].apply(this, args);
}
}
};
}
var Select = createClass({
propTypes: SelectPropTypes,
mixins: [FilterMixin],
getDefaultProps: function getDefaultProps() {
return {
prefixCls: 'rc-select',
defaultOpen: false,
labelInValue: false,
defaultActiveFirstOption: true,
showSearch: true,
allowClear: false,
placeholder: '',
onChange: noop,
onFocus: noop,
onBlur: noop,
onSelect: noop,
onSearch: noop,
onDeselect: noop,
showArrow: true,
dropdownMatchSelectWidth: true,
dropdownStyle: {},
dropdownMenuStyle: {},
optionFilterProp: 'value',
optionLabelProp: 'value',
notFoundContent: 'Not Found'
};
},
getInitialState: function getInitialState() {
var props = this.props;
var value = [];
if ('value' in props) {
value = toArray(props.value);
} else {
value = toArray(props.defaultValue);
}
value = this.addLabelToValue(props, value);
value = this.addTitleToValue(props, value);
var inputValue = '';
if (props.combobox) {
inputValue = value.length ? this.getLabelFromProps(props, value[0].key) : '';
}
this.saveInputRef = saveRef.bind(this, 'inputInstance');
this.saveInputMirrorRef = saveRef.bind(this, 'inputMirrorInstance');
var open = props.open;
if (open === undefined) {
open = props.defaultOpen;
}
return {
value: value,
inputValue: inputValue,
open: open
};
},
componentWillMount: function componentWillMount() {
this.adjustOpenState();
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if ('value' in nextProps) {
var value = toArray(nextProps.value);
value = this.addLabelToValue(nextProps, value);
value = this.addTitleToValue(nextProps, value);
this.setState({
value: value
});
if (nextProps.combobox) {
this.setState({
inputValue: value.length ? this.getLabelFromProps(nextProps, value[0].key) : ''
});
}
}
},
componentWillUpdate: function componentWillUpdate(nextProps, nextState) {
this.props = nextProps;
this.state = nextState;
this.adjustOpenState();
},
componentDidUpdate: function componentDidUpdate() {
if (isMultipleOrTags(this.props)) {
var inputNode = this.getInputDOMNode();
var mirrorNode = this.getInputMirrorDOMNode();
if (inputNode.value) {
inputNode.style.width = '';
inputNode.style.width = mirrorNode.clientWidth + 'px';
} else {
inputNode.style.width = '';
}
}
},
componentWillUnmount: function componentWillUnmount() {
this.clearFocusTime();
this.clearBlurTime();
this.clearAdjustTimer();
if (this.dropdownContainer) {
ReactDOM.unmountComponentAtNode(this.dropdownContainer);
document.body.removeChild(this.dropdownContainer);
this.dropdownContainer = null;
}
},
onInputChange: function onInputChange(event) {
var tokenSeparators = this.props.tokenSeparators;
var val = event.target.value;
if (isMultipleOrTags(this.props) && tokenSeparators && includesSeparators(val, tokenSeparators)) {
var nextValue = this.tokenize(val);
this.fireChange(nextValue);
this.setOpenState(false, true);
this.setInputValue('', false);
return;
}
this.setInputValue(val);
this.setState({
open: true
});
if (isCombobox(this.props)) {
this.fireChange([{
key: val
}]);
}
},
onDropdownVisibleChange: function onDropdownVisibleChange(open) {
if (open && !this._focused) {
this.clearBlurTime();
this.timeoutFocus();
this._focused = true;
this.updateFocusClassName();
}
this.setOpenState(open);
},
onKeyDown: function onKeyDown(event) {
var props = this.props;
if (props.disabled) {
return;
}
var keyCode = event.keyCode;
if (this.state.open && !this.getInputDOMNode()) {
this.onInputKeyDown(event);
} else if (keyCode === KeyCode.ENTER || keyCode === KeyCode.DOWN) {
this.setOpenState(true);
event.preventDefault();
}
},
onInputKeyDown: function onInputKeyDown(event) {
var props = this.props;
if (props.disabled) {
return;
}
var state = this.state;
var keyCode = event.keyCode;
if (isMultipleOrTags(props) && !event.target.value && keyCode === KeyCode.BACKSPACE) {
event.preventDefault();
var value = state.value;
if (value.length) {
this.removeSelected(value[value.length - 1].key);
}
return;
}
if (keyCode === KeyCode.DOWN) {
if (!state.open) {
this.openIfHasChildren();
event.preventDefault();
event.stopPropagation();
return;
}
} else if (keyCode === KeyCode.ESC) {
if (state.open) {
this.setOpenState(false);
event.preventDefault();
event.stopPropagation();
}
return;
}
if (state.open) {
var menu = this.refs.trigger.getInnerMenu();
if (menu && menu.onKeyDown(event)) {
event.preventDefault();
event.stopPropagation();
}
}
},
onMenuSelect: function onMenuSelect(_ref) {
var _this = this;
var item = _ref.item;
var value = this.state.value;
var props = this.props;
var selectedValue = getValuePropValue(item);
var selectedLabel = this.getLabelFromOption(item);
var event = selectedValue;
if (props.labelInValue) {
event = {
key: event,
label: selectedLabel
};
}
props.onSelect(event, item);
var selectedTitle = item.props.title;
if (isMultipleOrTags(props)) {
if (findIndexInValueByKey(value, selectedValue) !== -1) {
return;
}
value = value.concat([{
key: selectedValue,
label: selectedLabel,
title: selectedTitle
}]);
} else {
if (isCombobox(props)) {
this.skipAdjustOpen = true;
this.clearAdjustTimer();
this.skipAdjustOpenTimer = setTimeout(function () {
_this.skipAdjustOpen = false;
}, 0);
}
if (value.length && value[0].key === selectedValue) {
this.setOpenState(false, true);
return;
}
value = [{
key: selectedValue,
label: selectedLabel,
title: selectedTitle
}];
this.setOpenState(false, true);
}
this.fireChange(value);
var inputValue = void 0;
if (isCombobox(props)) {
inputValue = getPropValue(item, props.optionLabelProp);
} else {
inputValue = '';
}
this.setInputValue(inputValue, false);
},
onMenuDeselect: function onMenuDeselect(_ref2) {
var item = _ref2.item,
domEvent = _ref2.domEvent;
if (domEvent.type === 'click') {
this.removeSelected(getValuePropValue(item));
}
this.setInputValue('', false);
},
onArrowClick: function onArrowClick(e) {
e.stopPropagation();
if (!this.props.disabled) {
this.setOpenState(!this.state.open, !this.state.open);
}
},
onPlaceholderClick: function onPlaceholderClick() {
if (this.getInputDOMNode()) {
this.getInputDOMNode().focus();
}
},
onOuterFocus: function onOuterFocus(e) {
this.clearBlurTime();
if (!isMultipleOrTagsOrCombobox(this.props) && e.target === this.getInputDOMNode()) {
return;
}
if (this._focused) {
return;
}
this._focused = true;
this.updateFocusClassName();
this.timeoutFocus();
},
onPopupFocus: function onPopupFocus() {
this.maybeFocus(true, true);
},
onOuterBlur: function onOuterBlur() {
var _this2 = this;
this.blurTimer = setTimeout(function () {
_this2._focused = false;
_this2.updateFocusClassName();
var props = _this2.props;
var value = _this2.state.value;
var inputValue = _this2.state.inputValue;
if (isSingleMode(props) && props.showSearch && inputValue && props.defaultActiveFirstOption) {
var options = _this2._options || [];
if (options.length) {
var firstOption = findFirstMenuItem(options);
if (firstOption) {
value = [{
key: firstOption.key,
label: _this2.getLabelFromOption(firstOption)
}];
_this2.fireChange(value);
}
}
} else if (isMultipleOrTags(props) && inputValue) {
_this2.state.inputValue = _this2.getInputDOMNode().value = '';
}
props.onBlur(_this2.getVLForOnChange(value));
}, 10);
},
onClearSelection: function onClearSelection(event) {
var props = this.props;
var state = this.state;
if (props.disabled) {
return;
}
var inputValue = state.inputValue,
value = state.value;
event.stopPropagation();
if (inputValue || value.length) {
if (value.length) {
this.fireChange([]);
}
this.setOpenState(false, true);
if (inputValue) {
this.setInputValue('');
}
}
},
onChoiceAnimationLeave: function onChoiceAnimationLeave() {
this.refs.trigger.refs.trigger.forcePopupAlign();
},
getLabelBySingleValue: function getLabelBySingleValue(children, value) {
var _this3 = this;
if (value === undefined) {
return null;
}
var label = null;
React.Children.forEach(children, function (child) {
if (child.type.isSelectOptGroup) {
var maybe = _this3.getLabelBySingleValue(child.props.children, value);
if (maybe !== null) {
label = maybe;
}
} else if (getValuePropValue(child) === value) {
label = _this3.getLabelFromOption(child);
}
});
return label;
},
getValueByLabel: function getValueByLabel(children, label) {
var _this4 = this;
if (label === undefined) {
return null;
}
var value = null;
React.Children.forEach(children, function (child) {
if (child.type.isSelectOptGroup) {
var maybe = _this4.getValueByLabel(child.props.children, label);
if (maybe !== null) {
value = maybe;
}
} else if (toArray(_this4.getLabelFromOption(child)).join('') === label) {
value = getValuePropValue(child);
}
});
return value;
},
getLabelFromOption: function getLabelFromOption(child) {
return getPropValue(child, this.props.optionLabelProp);
},
getLabelFromProps: function getLabelFromProps(props, value) {
return this.getLabelByValue(props.children, value);
},
getVLForOnChange: function getVLForOnChange(vls_) {
var vls = vls_;
if (vls !== undefined) {
if (!this.props.labelInValue) {
vls = vls.map(function (v) {
return v.key;
});
} else {
vls = vls.map(function (vl) {
return { key: vl.key, label: vl.label };
});
}
return isMultipleOrTags(this.props) ? vls : vls[0];
}
return vls;
},
getLabelByValue: function getLabelByValue(children, value) {
var label = this.getLabelBySingleValue(children, value);
if (label === null) {
return value;
}
return label;
},
getDropdownContainer: function getDropdownContainer() {
if (!this.dropdownContainer) {
this.dropdownContainer = document.createElement('div');
document.body.appendChild(this.dropdownContainer);
}
return this.dropdownContainer;
},
getPlaceholderElement: function getPlaceholderElement() {
var props = this.props,
state = this.state;
var hidden = false;
if (state.inputValue) {
hidden = true;
}
if (state.value.length) {
hidden = true;
}
if (isCombobox(props) && state.value.length === 1 && !state.value[0].key) {
hidden = false;
}
var placeholder = props.placeholder;
if (placeholder) {
return React.createElement(
'div',
_extends({
onMouseDown: preventDefaultEvent,
style: _extends({
display: hidden ? 'none' : 'block'
}, UNSELECTABLE_STYLE)
}, UNSELECTABLE_ATTRIBUTE, {
onClick: this.onPlaceholderClick,
className: props.prefixCls + '-selection__placeholder'
}),
placeholder
);
}
return null;
},
getInputElement: function getInputElement() {
var props = this.props;
var inputElement = props.getInputElement ? props.getInputElement() : React.createElement('input', null);
var inputCls = classnames(inputElement.props.className, _defineProperty({}, props.prefixCls + '-search__field', true));
return React.createElement(
'div',
{ className: props.prefixCls + '-search__field__wrap' },
React.cloneElement(inputElement, {
ref: this.saveInputRef,
onChange: this.onInputChange,
onKeyDown: chaining(this.onInputKeyDown, inputElement.props.onKeyDown),
value: this.state.inputValue,
disabled: props.disabled,
className: inputCls
}),
React.createElement(
'span',
{
ref: this.saveInputMirrorRef,
className: props.prefixCls + '-search__field__mirror'
},
this.state.inputValue,
'\xA0'
)
);
},
getInputDOMNode: function getInputDOMNode() {
return this.topCtrlNode ? this.topCtrlNode.querySelector('input,textarea,div[contentEditable]') : this.inputInstance;
},
getInputMirrorDOMNode: function getInputMirrorDOMNode() {
return this.inputMirrorInstance;
},
getPopupDOMNode: function getPopupDOMNode() {
return this.refs.trigger.getPopupDOMNode();
},
getPopupMenuComponent: function getPopupMenuComponent() {
return this.refs.trigger.getInnerMenu();
},
setOpenState: function setOpenState(open, needFocus) {
var _this5 = this;
var props = this.props,
state = this.state;
if (state.open === open) {
this.maybeFocus(open, needFocus);
return;
}
var nextState = {
open: open
};
if (!open && isSingleMode(props) && props.showSearch) {
this.setInputValue('');
}
if (!open) {
this.maybeFocus(open, needFocus);
}
this.setState(nextState, function () {
if (open) {
_this5.maybeFocus(open, needFocus);
}
});
},
setInputValue: function setInputValue(inputValue) {
var fireSearch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (inputValue !== this.state.inputValue) {
this.setState({
inputValue: inputValue
});
if (fireSearch) {
this.props.onSearch(inputValue);
}
}
},
timeoutFocus: function timeoutFocus() {
var _this6 = this;
if (this.focusTimer) {
this.clearFocusTime();
}
this.focusTimer = setTimeout(function () {
_this6.props.onFocus();
}, 10);
},
clearFocusTime: function clearFocusTime() {
if (this.focusTimer) {
clearTimeout(this.focusTimer);
this.focusTimer = null;
}
},
clearBlurTime: function clearBlurTime() {
if (this.blurTimer) {
clearTimeout(this.blurTimer);
this.blurTimer = null;
}
},
clearAdjustTimer: function clearAdjustTimer() {
if (this.skipAdjustOpenTimer) {
clearTimeout(this.skipAdjustOpenTimer);
this.skipAdjustOpenTimer = null;
}
},
updateFocusClassName: function updateFocusClassName() {
var refs = this.refs,
props = this.props;
if (this._focused) {
classes(refs.root).add(props.prefixCls + '-focused');
} else {
classes(refs.root).remove(props.prefixCls + '-focused');
}
},
maybeFocus: function maybeFocus(open, needFocus) {
if (needFocus || open) {
var input = this.getInputDOMNode();
var _document = document,
activeElement = _document.activeElement;
if (input && (open || isMultipleOrTagsOrCombobox(this.props))) {
if (activeElement !== input) {
input.focus();
this._focused = true;
}
} else {
var selection = this.refs.selection;
if (activeElement !== selection) {
selection.focus();
this._focused = true;
}
}
}
},
addLabelToValue: function addLabelToValue(props, value_) {
var _this7 = this;
var value = value_;
if (props.labelInValue) {
value.forEach(function (v) {
v.label = v.label || _this7.getLabelFromProps(props, v.key);
});
} else {
value = value.map(function (v) {
return {
key: v,
label: _this7.getLabelFromProps(props, v)
};
});
}
return value;
},
addTitleToValue: function addTitleToValue(props, values) {
var _this8 = this;
var nextValues = values;
var keys = values.map(function (v) {
return v.key;
});
React.Children.forEach(props.children, function (child) {
if (child.type.isSelectOptGroup) {
nextValues = _this8.addTitleToValue(child.props, nextValues);
} else {
var value = getValuePropValue(child);
var valueIndex = keys.indexOf(value);
if (valueIndex > -1) {
nextValues[valueIndex].title = child.props.title;
}
}
});
return nextValues;
},
removeSelected: function removeSelected(selectedKey) {
var props = this.props;
if (props.disabled || this.isChildDisabled(selectedKey)) {
return;
}
var label = void 0;
var value = this.state.value.filter(function (singleValue) {
if (singleValue.key === selectedKey) {
label = singleValue.label;
}
return singleValue.key !== selectedKey;
});
var canMultiple = isMultipleOrTags(props);
if (canMultiple) {
var event = selectedKey;
if (props.labelInValue) {
event = {
key: selectedKey,
label: label
};
}
props.onDeselect(event);
}
this.fireChange(value);
},
openIfHasChildren: function openIfHasChildren() {
var props = this.props;
if (React.Children.count(props.children) || isSingleMode(props)) {
this.setOpenState(true);
}
},
fireChange: function fireChange(value) {
var props = this.props;
if (!('value' in props)) {
this.setState({
value: value
});
}
props.onChange(this.getVLForOnChange(value));
},
isChildDisabled: function isChildDisabled(key) {
return toArray(this.props.children).some(function (child) {
var childValue = getValuePropValue(child);
return childValue === key && child.props && child.props.disabled;
});
},
tokenize: function tokenize(string) {
var _this9 = this;
var _props = this.props,
multiple = _props.multiple,
tokenSeparators = _props.tokenSeparators,
children = _props.children;
var nextValue = this.state.value;
splitBySeparators(string, tokenSeparators).forEach(function (label) {
var selectedValue = { key: label, label: label };
if (findIndexInValueByLabel(nextValue, label) === -1) {
if (multiple) {
var value = _this9.getValueByLabel(children, label);
if (value) {
selectedValue.key = value;
nextValue = nextValue.concat(selectedValue);
}
} else {
nextValue = nextValue.concat(selectedValue);
}
}
});
return nextValue;
},
adjustOpenState: function adjustOpenState() {
if (this.skipAdjustOpen) {
return;
}
var open = this.state.open;
if (typeof document !== 'undefined' && this.getInputDOMNode() && document.activeElement === this.getInputDOMNode()) {
open = true;
}
var options = [];
if (open) {
options = this.renderFilterOptions();
}
this._options = options;
if (isMultipleOrTagsOrCombobox(this.props) || !this.props.showSearch) {
if (open && !options.length) {
open = false;
}
}
this.state.open = open;
},
renderTopControlNode: function renderTopControlNode() {
var _this10 = this;
var _state = this.state,
value = _state.value,
open = _state.open,
inputValue = _state.inputValue;
var props = this.props;
var choiceTransitionName = props.choiceTransitionName,
prefixCls = props.prefixCls,
maxTagTextLength = props.maxTagTextLength,
showSearch = props.showSearch;
var className = prefixCls + '-selection__rendered';
var innerNode = null;
if (isSingleMode(props)) {
var selectedValue = null;
if (value.length) {
var showSelectedValue = false;
var opacity = 1;
if (!showSearch) {
showSelectedValue = true;
} else {
if (open) {
showSelectedValue = !inputValue;
if (showSelectedValue) {
opacity = 0.4;
}
} else {
showSelectedValue = true;
}
}
var singleValue = value[0];
selectedValue = React.createElement(
'div',
{
key: 'value',
className: prefixCls + '-selection-selected-value',
title: singleValue.title || singleValue.label,
style: {
display: showSelectedValue ? 'block' : 'none',
opacity: opacity
}
},
value[0].label
);
}
if (!showSearch) {
innerNode = [selectedValue];
} else {
innerNode = [selectedValue, React.createElement(
'div',
{
className: prefixCls + '-search ' + prefixCls + '-search--inline',
key: 'input',
style: {
display: open ? 'block' : 'none'
}
},
this.getInputElement()
)];
}
} else {
var selectedValueNodes = [];
if (isMultipleOrTags(props)) {
selectedValueNodes = value.map(function (singleValue) {
var content = singleValue.label;
var title = singleValue.title || content;
if (maxTagTextLength && typeof content === 'string' && content.length > maxTagTextLength) {
content = content.slice(0, maxTagTextLength) + '...';
}
var disabled = _this10.isChildDisabled(singleValue.key);
var choiceClassName = disabled ? prefixCls + '-selection__choice ' + prefixCls + '-selection__choice__disabled' : prefixCls + '-selection__choice';
return React.createElement(
'li',
_extends({
style: UNSELECTABLE_STYLE
}, UNSELECTABLE_ATTRIBUTE, {
onMouseDown: preventDefaultEvent,
className: choiceClassName,
key: singleValue.key,
title: title
}),
React.createElement(
'div',
{ className: prefixCls + '-selection__choice__content' },
content
),
disabled ? null : React.createElement('span', {
className: prefixCls + '-selection__choice__remove',
onClick: _this10.removeSelected.bind(_this10, singleValue.key)
})
);
});
}
selectedValueNodes.push(React.createElement(
'li',
{
className: prefixCls + '-search ' + prefixCls + '-search--inline',
key: '__input'
},
this.getInputElement()
));
if (isMultipleOrTags(props) && choiceTransitionName) {
innerNode = React.createElement(
Animate,
{
onLeave: this.onChoiceAnimationLeave,
component: 'ul',
transitionName: choiceTransitionName
},
selectedValueNodes
);
} else {
innerNode = React.createElement(
'ul',
null,
selectedValueNodes
);
}
}
return React.createElement(
'div',
{
className: className,
ref: function ref(node) {
return _this10.topCtrlNode = node;
}
},
this.getPlaceholderElement(),
innerNode
);
},
render: function render() {
var _rootCls;
var props = this.props;
var multiple = isMultipleOrTags(props);
var state = this.state;
var className = props.className,
disabled = props.disabled,
allowClear = props.allowClear,
prefixCls = props.prefixCls;
var ctrlNode = this.renderTopControlNode();
var extraSelectionProps = {};
var open = this.state.open;
var options = this._options;
if (!isMultipleOrTagsOrCombobox(props)) {
extraSelectionProps = {
onKeyDown: this.onKeyDown,
tabIndex: 0
};
}
var rootCls = (_rootCls = {}, _defineProperty(_rootCls, className, !!className), _defineProperty(_rootCls, prefixCls, 1), _defineProperty(_rootCls, prefixCls + '-open', open), _defineProperty(_rootCls, prefixCls + '-focused', open || !!this._focused), _defineProperty(_rootCls, prefixCls + '-combobox', isCombobox(props)), _defineProperty(_rootCls, prefixCls + '-disabled', disabled), _defineProperty(_rootCls, prefixCls + '-enabled', !disabled), _defineProperty(_rootCls, prefixCls + '-allow-clear', !!props.allowClear), _rootCls);
var clearStyle = _extends({}, UNSELECTABLE_STYLE, {
display: 'none'
});
if (state.inputValue || state.value.length) {
clearStyle.display = 'block';
}
var clear = React.createElement('span', _extends({
key: 'clear',
onMouseDown: preventDefaultEvent,
style: clearStyle
}, UNSELECTABLE_ATTRIBUTE, {
className: prefixCls + '-selection__clear',
onClick: this.onClearSelection
}));
return React.createElement(
SelectTrigger,
{
onPopupFocus: this.onPopupFocus,
dropdownAlign: props.dropdownAlign,
dropdownClassName: props.dropdownClassName,
dropdownMatchSelectWidth: props.dropdownMatchSelectWidth,
defaultActiveFirstOption: props.defaultActiveFirstOption,
dropdownMenuStyle: props.dropdownMenuStyle,
transitionName: props.transitionName,
animation: props.animation,
prefixCls: props.prefixCls,
dropdownStyle: props.dropdownStyle,
combobox: props.combobox,
showSearch: props.showSearch,
options: options,
multiple: multiple,
disabled: disabled,
visible: open,
inputValue: state.inputValue,
value: state.value,
onDropdownVisibleChange: this.onDropdownVisibleChange,
getPopupContainer: props.getPopupContainer,
onMenuSelect: this.onMenuSelect,
onMenuDeselect: this.onMenuDeselect,
ref: 'trigger'
},
React.createElement(
'div',
{
style: props.style,
ref: 'root',
onBlur: this.onOuterBlur,
onFocus: this.onOuterFocus,
className: classnames(rootCls)
},
React.createElement(
'div',
_extends({
ref: 'selection',
key: 'selection',
className: prefixCls + '-selection\n ' + prefixCls + '-selection--' + (multiple ? 'multiple' : 'single'),
role: 'combobox',
'aria-autocomplete': 'list',
'aria-haspopup': 'true',
'aria-expanded': open
}, extraSelectionProps),
ctrlNode,
allowClear ? clear : null,
multiple || !props.showArrow ? null : React.createElement(
'span',
_extends({
key: 'arrow',
className: prefixCls + '-arrow',
style: UNSELECTABLE_STYLE
}, UNSELECTABLE_ATTRIBUTE, {
onClick: this.onArrowClick
}),
React.createElement('b', null)
)
)
)
);
}
});
Select.displayName = 'Select';
export default Select; |
resources/apps/frontend/src/pages/subscriptions/form.js | johndavedecano/PHPLaravelGymManagementSystem | import React from 'react';
import serialize from 'form-serialize';
import {Form, FormGroup, Input, Label, Button, Row, Col} from 'reactstrap';
import MemberSelect from 'components/Form/Select/MemberSelect';
import SubscriptionStatusSelect from 'components/Form/Select/SubscriptionStatusSelect';
import PackageSelect from 'components/Form/Select/PackageSelect';
import getErrorMessage from 'utils/getErrorMessage';
import notify from 'utils/notify';
import date from 'utils/date';
export default class extends React.Component {
static defaultProps = {
successMessage: 'Successfully submitted',
onSubmit: () => {},
isCreate: false,
status: 'active',
interval: 1,
};
state = {
isSubmitting: false,
};
onSubmit = async event => {
try {
event.preventDefault();
this.setState({isSubmitting: true});
const form = event.target;
const data = serialize(form, {hash: true});
await this.props.onSubmit(data);
this.setState({isSubmitting: false});
notify({
type: 'success',
text: this.props.successMessage,
});
} catch (error) {
notify({
type: 'error',
text: getErrorMessage(error),
});
this.setState({isSubmitting: false});
}
};
render() {
return (
<Form onSubmit={this.onSubmit}>
<Row>
<Col md={6}>
<FormGroup>
<Label for="user_id">Member</Label>
<MemberSelect
name="user_id"
id="user_id"
placeholder="Select Member"
defaultValue={this.props.user_id}
/>
</FormGroup>
</Col>
<Col md={6}>
<FormGroup>
<Label for="package_id">Package</Label>
<PackageSelect
name="package_id"
id="package_id"
placeholder="Select Package"
defaultValue={this.props.package_id}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col md={6}>
<FormGroup>
<Label for="interval">Interval</Label>
<Input
type="number"
name="interval"
id="interval"
required
min={1}
defaultValue={this.props.interval}
/>
</FormGroup>
</Col>
<Col md={6}>
<FormGroup>
<Label for="status">Status</Label>
<SubscriptionStatusSelect
name="status"
id="status"
placeholder="Select Status"
defaultValue={this.props.status}
isDisabled={this.props.isCreate}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col md={6}>
<FormGroup>
<Label for="expires_at">Expiration At</Label>
<input
className="form-control"
type="date"
name="expires_at"
id="expires_at"
required
min={1}
defaultValue={date(this.props.expires_at, 'YYYY-MM-DD')}
disabled={this.props.isCreate}
/>
</FormGroup>
</Col>
<Col md={6}>
<FormGroup>
<Label for="suspended_at">Suspended At</Label>
<input
className="form-control"
type="date"
name="suspended_at"
id="suspended_at"
required
min={1}
defaultValue={date(this.props.suspended_at, 'YYYY-MM-DD')}
disabled={this.props.isCreate}
/>
</FormGroup>
</Col>
</Row>
<Button
color="primary"
className="float-right"
disabled={this.state.isSubmitting}
>
{this.state.isSubmitting ? 'Please Wait...' : 'Submit Form'}
</Button>
</Form>
);
}
}
|
component/Test.js | jimju/BNDemo | 'use strict'
import React, { Component } from 'react';
import {
Text,StyleSheet,View
} from 'react-native';
class Test extends React.Component {
render(){
return(
<View style={styles.content}>
<Text> Hello Test !</Text>
</View>
);
}
}
const styles = StyleSheet.create({
content:{
flex:1,
flexDirection:'column',
}
});
export {Test as default};
|
src/components/topic/stories/BrowseStoriesContainer.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { Grid, Row, Col } from 'react-flexbox-grid/lib';
import { pagedAndSortedLocation } from '../../util/location';
import withPaging from '../../common/hocs/PagedContainer';
import TopicPageTitle from '../TopicPageTitle';
import TopicStoriesContainer from '../provider/TopicStoriesContainer';
const localMessages = {
title: { id: 'topic.influentialStories.title', defaultMessage: 'Browse Stories' },
};
const BrowseStoriesContainer = ({ previousButton, nextButton, linkId }) => (
<Grid>
<Row>
<Col lg={12}>
<TopicPageTitle value={localMessages.title} />
<h1><FormattedMessage {...localMessages.title} /></h1>
<TopicStoriesContainer
border={false}
uid="browse"
extraArgs={{ limit: 100 }}
linkId={linkId}
/>
{ previousButton }
{ nextButton }
</Col>
</Row>
</Grid>
);
BrowseStoriesContainer.propTypes = {
// from the composition chain
intl: PropTypes.object.isRequired,
// from state
links: PropTypes.object,
linkId: PropTypes.string,
// from PagedContainer wrapper
nextButton: PropTypes.node,
previousButton: PropTypes.node,
};
const mapStateToProps = (state, ownProps) => ({
links: state.topics.selected.provider.stories.results.browse ? state.topics.selected.provider.stories.results.browse.link_ids : {},
linkId: ownProps.location.query.linkId,
});
const handlePageChange = (dispatch, props, linkId) => {
// just update the URL
dispatch(push(pagedAndSortedLocation(
props.location,
linkId,
props.sort,
props.filters,
)));
};
export default
injectIntl(
connect(mapStateToProps)(
withPaging(handlePageChange)(
BrowseStoriesContainer
)
)
);
|
docs/app/Examples/elements/Label/Variations/LabelExampleSize.js | vageeshb/Semantic-UI-React | import _ from 'lodash'
import React from 'react'
import { Label } from 'semantic-ui-react'
const sizes = ['mini', 'tiny', 'small', 'medium', 'large', 'big', 'huge', 'massive']
const LabelExampleSize = () => (
<div>
{sizes.map(size => (
<Label key={size} size={size}>
{_.capitalize(size)}
</Label>
))}
</div>
)
export default LabelExampleSize
|
src/components/overlay_tooltip.js | libeanim/sundew-notes | import React from 'react';
import _ from 'lodash';
import { Tooltip, OverlayTrigger } from 'react-bootstrap';
export default function(props){
const id = _.uniqueId('tooltip_');
const tooltip = <Tooltip id={id}>{ props.text }</Tooltip>;
return (
<OverlayTrigger trigger={ props.trigger || ['hover', 'focus'] } placement={ props.placement || 'left' } overlay={ tooltip }>
{ props.children }
</OverlayTrigger>
);
}
|
src/NavBar.js | otsoaUnLoco/wolf-chess | // @flow
import React from 'react';
import ReadFileDialog from './ReadFileDialog';
export default function NavBar(props: {
resetBoard: (void) => void,
readFile: (string) => void
}): React.Element<*> {
return (
<div id="navBar" >
<button type="reset" onClick={props.resetBoard}>New Game</button>
<button type="button">from FEN</button>
<ReadFileDialog readFile={props.readFile} />
<button type="button">set position</button>
</div >
);
}
|
src/svg-icons/image/looks.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLooks = (props) => (
<SvgIcon {...props}>
<path d="M12 10c-3.86 0-7 3.14-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.86-3.14-7-7-7zm0-4C5.93 6 1 10.93 1 17h2c0-4.96 4.04-9 9-9s9 4.04 9 9h2c0-6.07-4.93-11-11-11z"/>
</SvgIcon>
);
ImageLooks = pure(ImageLooks);
ImageLooks.displayName = 'ImageLooks';
ImageLooks.muiName = 'SvgIcon';
export default ImageLooks;
|
packages/arwes/src/Line/sandbox.js | romelperez/ui | import React from 'react';
import Line from './index';
export default () => (
<div style={{ padding: '20px' }}>
<Line animate />
<Line animate layer="success" />
<Line animate layer="alert" />
</div>
);
|
app/components/spinners/material-spinner/component.js | DenQ/electron-react-lex | import React from 'react';
import BaseComponent from 'lex/libs/base/component';
import Spinner from 'react-spinner-material';
export default class MaterialSpinner extends BaseComponent {
render() {
this.decorateStyle();
const { show } = this.props;
return (
<Spinner
size={200}
spinnerColor={this.styles.palette.textColor}
spinnerWidth={15}
visible={show}
/>
);
}
}
|
src/components/UsersWatching/index.js | danbovey/Dekt | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Tooltip from 'rc-tooltip';
import * as showActions from 'actions/show';
import Spinner from 'components/Spinner';
import './styles';
@connect(
state => ({
auth: state.auth,
watching: state.watching
}),
dispatch => ({
showActions: bindActionCreators(showActions, dispatch)
})
)
export default class UsersWatching extends Component {
componentWillMount() {
const show = this.props.show;
if(show.watching == null && show.watching_loading == false) {
this.props.showActions.watching(show.item.show.ids.slug);
}
}
renderUser(user, i, auth = false) {
return (
<Tooltip
placement="bottom"
transitionName="rc-tooltip-zoom"
overlay={<span>{auth ? 'YOU!' : user.username}</span>}
mouseLeaveDelay={0}
key={i}
>
<a href={`https://trakt.tv/users/${user.username}`} target="_blank" rel="noopener" className={auth ? 'me' : ''}>
<img src={user.images ? user.images.avatar.full : 'https://walter.trakt.tv/hotlink-ok/placeholders/medium/fry.png'} alt={user.username} />
</a>
</Tooltip>
);
}
render() {
const {
auth,
show,
watching
} = this.props;
const users = show.watching;
if(!show.watching_loading && users) {
const isWatching = watching.item && watching.item.show && watching.item.show.ids.trakt == show.item.show.ids.trakt;
let usersLength = isWatching ? 9 : 10;
if(users.length > 10) {
usersLength = usersLength - 1;
}
return (
<div className="users-watching">
{users.length > 0 ? (
<div>
<p>{users.length} watching now</p>
<div className="users">
{isWatching ? this.renderUser(auth.user, 0, true) : null}
{users.slice(0, usersLength)
.filter(u => u.username != auth.user.username)
.map((user, i) => this.renderUser(user, i))
}
{users.length > 10 ? (
<a href="#" className="plus-more">+{users.length - 9} more</a>
) : null}
</div>
</div>
) : null}
</div>
);
} else {
return (
<div className="users-watching loading">
<Spinner size="medium" />
</div>
);
}
}
}
|
teoria02/componentes/EstadoTarea.js | mart-dominguez/OFA2017-S01-C02 | import React from 'react';
class EstadoTarea extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.estadoChange(this.props.indice,e.target.name,e.target.value);
}
render(){
return (
<select value={this.props.estado} onChange={this.handleChange} name={this.props.nombre}>
<option value="planificada">Para hacer</option>
<option value="encurso">En Curso</option>
<option value="finalizada">Terminada!</option>
</select>
);
}
}
export default EstadoTarea; |
packages/cf-builder-pagination/example/basic/component.js | mdno/mdno.github.io | import React from 'react';
import { PaginationBuilder } from 'cf-builder-pagination';
function getStartAndEnd(page, pageSize) {
const start = (page - 1) * pageSize;
const end = start + pageSize - 1;
return [start, end];
}
function hasAllItems(items, start, end) {
for (let i = start; i <= end; i++) {
if (!items[i] || items[i].isRequesting) {
return false;
}
}
return true;
}
class BuilderPagination extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
totalCount: 143,
page: 1,
perPage: 20
};
this.handlePageChange = this.handlePageChange.bind(this);
}
componentDidMount() {
this.maybeRequestPage(this.state.page);
}
handlePageChange(page) {
this.maybeRequestPage(page);
}
// This is mimicking what will happen in the API actions/reducers:
maybeRequestPage(page) {
const items = this.state.items.slice();
const [start, end] = getStartAndEnd(page, this.state.perPage);
const needsRequest = !hasAllItems(items, start, end);
if (!needsRequest) {
this.setState({ page });
return;
}
for (let i = start; i <= end; i++) {
if (!items[i]) {
items[i] = {
isRequesting: true
};
}
}
this.setState({ page, items });
setTimeout(() => {
const items = this.state.items.slice();
for (let i = start; i <= end; i++) {
items[i].isRequesting = false;
}
this.setState({ items });
}, 500);
}
render() {
const [start, end] = getStartAndEnd(this.state.page, this.state.perPage);
const loading = !hasAllItems(this.state.items, start, end);
return (
<PaginationBuilder
onPageChange={this.handlePageChange}
loading={loading}
totalCount={this.state.totalCount}
page={this.state.page}
perPage={this.state.perPage}
/>
);
}
}
export default BuilderPagination;
|
public/assets/js/node_modules/react-select/examples/src/app.js | ngocson8b/6jar | /* eslint react/prop-types: 0 */
import React from 'react';
import ReactDOM from 'react-dom';
import Select from 'react-select';
import Contributors from './components/Contributors';
import CustomKeysField from './components/CustomKeysField';
import CustomRenderField from './components/CustomRenderField';
import DisabledUpsellOptions from './components/DisabledUpsellOptions';
import MultiSelectField from './components/MultiSelectField';
import RemoteSelectField from './components/RemoteSelectField';
import SelectedValuesField from './components/SelectedValuesField';
import StatesField from './components/StatesField';
import UsersField from './components/UsersField';
import ValuesAsNumbersField from './components/ValuesAsNumbersField';
var FLAVOURS = [
{ label: 'Chocolate', value: 'chocolate' },
{ label: 'Vanilla', value: 'vanilla' },
{ label: 'Strawberry', value: 'strawberry' },
{ label: 'Cookies and Cream', value: 'cookiescream' },
{ label: 'Peppermint', value: 'peppermint' }
];
var FLAVOURS_WITH_DISABLED_OPTION = FLAVOURS.slice(0);
FLAVOURS_WITH_DISABLED_OPTION.unshift({ label: 'Caramel (You don\'t like it, apparently)', value: 'caramel', disabled: true });
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
ReactDOM.render(
<div>
<StatesField label="States" searchable />
<MultiSelectField label="Multiselect" />
<Contributors label="Contributors" hint="This example uses custom properties for the name and value of options, as well as async options loading" />
<UsersField label="Users (custom options/value)" hint="This example uses Gravatar to render user's image besides the value and the options" />
<ValuesAsNumbersField label="Values as numbers" />
<CustomKeysField label="Custom object keys for options" />
<SelectedValuesField label="Clickable labels (labels as links)" options={FLAVOURS} hint="Open the console to see click behaviour (data/event)" />
<SelectedValuesField label="Disabled option" options={FLAVOURS_WITH_DISABLED_OPTION} hint="You savage! Caramel is the best..." />
<DisabledUpsellOptions label="Disabled option with a link"/>
<SelectedValuesField label="Option Creation (tags mode)" options={FLAVOURS} allowCreate hint="Enter a value that's NOT in the list, then hit return" />
<CustomRenderField label="Custom render options/values" />
<RemoteSelectField label="Remote Options" hint='Type anything in the remote example to asynchronously load options. Valid alternative results are "A", "AA", and "AB"' />
</div>,
document.getElementById('example')
);
|
public/js/app/queryTools/components/TableResult.js | fendy3002/QzQueryTools | import React from 'react'
import lo from 'lodash'
import sa from 'superagent';
var Elem = function({table}){
var renderHead = (fields) => {
var fieldDoms = lo.map(fields, k=> (
<th>{k}</th>
));
return <thead>
<tr>
{fieldDoms}
</tr>
</thead>;
};
var renderTd = (row, fields) => {
return lo.map(fields, k=> {
return <td>{row[k]}</td>;
});
};
var renderData = (data, fields) => {
var trList = lo.map(data, row => {
return <tr>{renderTd(row, fields)}</tr>;
});
return <tbody>{trList}</tbody>;
};
return <div className="box">
<div className="box-header with-border">
<h3 className="box-title">{table.label}</h3>
<div className="box-tools pull-right">
<button type="button" className="btn btn-box-tool" data-widget="collapse">
<i className="fa fa-minus"></i>
</button>
</div>
</div>
<div className="box-body table-responsive no-padding">
<table className="table table-responsive table-condensed table-striped table-bordered">
{renderHead(table.fields)}
{renderData(table.data, table.fields)}
</table>
</div>
</div>;
};
export default Elem; |
src/js/templates/content/post.js | julianburr/wp-react-theme | import React, { Component } from 'react';
import PostMeta from '../../components/post/meta';
import { renderHtml } from '../../utils/render';
export default class ContentPost extends Component {
render () {
const { content } = this.props;
console.log('content.data.data', content.data.data)
return (
<div>
<PostMeta post={content.data.data} />
<h1>{content.data.data.title}</h1>
{renderHtml(content.data.data.content.rendered)}
{/* TODO: next/prev buttons */}
</div>
);
}
}
|
app/component/target-progress.js | TinyTheBrontosaurus/CricketTrainer | import React, { Component } from 'react';
import {
AppRegistry,
Button,
Text
} from 'react-native';
import { Col, Grid } from "react-native-easy-grid";
/**
* A single target for displaying its progress in the darts game. Shows a button that can hit next
* to its progress.
*/
export default class TargetProgress extends Component {
constructor(props) {
super(props);
}
render() {
return <Grid>
<Col size={1}>
<Button
onPress={this.props.callback}
title={"" + this.props.label}
accessibilityLabel={"Hit target " + this.props.label}
disabled={this.props.disabled}
color="#841584"
/>
</Col>
<Col size={1}>
<Text>{this.getHitsSymbol()}</Text>
</Col>
<Col size={1}>
<Text>{(this.props.cleared || "-")}</Text>
</Col>
</Grid>
}
/**
* Cricket progress is typically marked by a \, X, then (X) on a chalkboard. Do the best with
* ASCII art here to return that
* @returns {*} Symbol based on number of hits
*/
getHitsSymbol() {
switch(this.props.hits) {
case 0:
return '-';
case 1:
return '\\';
case 2:
return 'X';
case 3:
default:
return 'O';
}
}
}
AppRegistry.registerComponent('TargetProgress', () => TargetProgress);
|
client/admin/scenes/protected/settings.js | kirinami/portfolio | import React, { Component } from 'react';
import { Breadcrumb, BreadcrumbItem } from 'reactstrap';
import { Link } from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import Loading from '../../components/loading';
import InputField from '../../forms/fields/input-field';
import TextareaField from '../../forms/fields/textarea-field';
import SettingsForm from '../../forms/settings-form';
@inject('alertStore', 'settingsStore')
@observer
export default class Settings extends Component {
settingsForm = new SettingsForm();
async componentDidMount() {
const { alertStore, settingsStore } = this.props;
try {
const response = await settingsStore.loadSettings();
if (response.success) {
this.settingsForm.imports(settingsStore.settings);
}
alertStore.showSuccess(response.message);
} catch (err) {
alertStore.showDanger(err.message);
}
}
async handleSubmit() {
const { alertStore, settingsStore } = this.props;
try {
const form = this.settingsForm.exports();
const response = await settingsStore.updateSettings(form);
alertStore.showSuccess(response.message);
} catch (err) {
alertStore.showDanger(err.message);
}
}
render() {
const { settingsStore } = this.props;
const { isLoading, settings } = settingsStore;
if (isLoading) {
return <Loading/>;
}
return (
<div className="settings-component">
<Breadcrumb>
<BreadcrumbItem>
<Link to="/">Dashboard</Link>
</BreadcrumbItem>
<BreadcrumbItem active>Settings</BreadcrumbItem>
</Breadcrumb>
<div className="row">
<div className="col-12">
<form
className="mb-3"
onSubmit={event => this.settingsForm.onSubmit(event, {
onSuccess: this.handleSubmit.bind(this),
})}>
<div className="card mb-3">
<div className="card-body">
<div className="form-group">
<InputField field={this.settingsForm.select('title')}/>
</div>
<div className="form-group">
<InputField field={this.settingsForm.select('keywords')}/>
</div>
<div className="form-group mb-0">
<TextareaField field={this.settingsForm.select('description')}/>
</div>
</div>
</div>
<div className="card mb-3">
<div className="card-header">
{this.settingsForm.select('block.header').label}
</div>
<div className="card-body">
<div className="form-group">
<InputField field={this.settingsForm.select('block.header.title')}/>
</div>
<div className="form-group mb-0">
<TextareaField field={this.settingsForm.select('block.header.description')}/>
</div>
</div>
</div>
<div className="card mb-3">
<div className="card-header">
{this.settingsForm.select('block.about').label}
</div>
<div className="card-body pb-1">
<div className="row">
{this.settingsForm.select('block.about').map((field, i) => (
<div key={field.id} className="col-md-6">
<div className="card mb-3">
<div className="card-body">
<div className="form-group">
<InputField field={field.select('title')}/>
</div>
<div className="form-group mb-0">
<TextareaField field={field.select('description')}/>
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
<div className="card mb-3">
<div className="card-header">
{this.settingsForm.select('block.portfolio').label}
</div>
<div className="card-body">
<div className="form-group mb-0">
<InputField field={this.settingsForm.select('block.portfolio.heading')}/>
</div>
</div>
</div>
<div className="card mb-3">
<div className="card-header">
{this.settingsForm.select('block.contacts').label}
</div>
<div className="card-body">
<div className="form-group mb-0">
<InputField field={this.settingsForm.select('block.contacts.heading')}/>
</div>
</div>
</div>
<div className="card">
<div className="card-footer bg-white" style={{ borderTop: 'none' }}>
<div className="row">
<div className="col-lg-6 mb-2 mb-lg-0 pt-lg-1-9">
<small className="text-muted">{settings.updatedAt}</small>
</div>
<div className="col-lg-6 text-lg-right">
<button type="submit" className="btn btn-success mr-1 mb-1 mb-lg-0">
<i className="fa fa-fw fa-save"/>
</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
);
}
}
|
news/sources/app.js | pintimes/lifeix-football-app-react | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
StyleSheet,
Navigator
} from 'react-native';
import {Router, routerReducer, Route, Container, Animations, Schema} from 'react-native-redux-router';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import Welcome from './view/welcome';
import Home from './view/home';
import Detail from './view/detail';
import Settings from './view/settings';
import TestView from './view/testView';
import {NavBar, NavBarModal,NavBarLeft} from './common/NavBar';
import TestTip from './common/TestTip';
console.disableYellowBox=true;
let store = createStore(combineReducers({routerReducer}));
export default class App extends Component {
constructor (props) {
super(props)
}
render() {
return this.renderRouter();
}
renderRouter(){
return (
<Provider store={store}>
<Router>
<Schema name="default" sceneConfig={Animations.FlatFloatFromRight}/>
<Schema name="withoutAnimation" sceneConfig={Animations.FlatFloatFromBottom} navBar={NavBarLeft} type="RESET"/>
<Route name="welcome" component={Welcome} initial={true} type="reset" />
<Route name="home" component={Home} schema="default" title="首页" />
<Route name="detail" component={Detail} schema="withoutAnimation" title="详情"/>
<Route name="settings" component={Settings} />
<Route name="testTip" component={TestTip} schema="popup" />
<Route name="testView" component={TestView} />
</Router>
</Provider>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
//backgroundColor: '#CE1126',
},
});
|
src/index.js | budunwang/React-Gallery | import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Main';
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
|
src/main.js | successkrisz/fx-rates-right | import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import AppContainer from './containers/AppContainer'
// ========================================================
// Store Instantiation
// ========================================================
const initialState = window.___INITIAL_STATE__
const store = createStore(initialState)
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = () => {
const routes = require('./routes/index').default(store)
ReactDOM.render(
<AppContainer store={store} routes={routes} />,
MOUNT_NODE
)
}
// This code is excluded from production bundle
if (__DEV__) {
if (module.hot) {
// Development render functions
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
// Wrap render in try/catch
render = () => {
try {
renderApp()
} catch (error) {
console.error(error)
renderError(error)
}
}
// Setup hot module replacement
module.hot.accept('./routes/index', () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
)
}
}
// ========================================================
// Go!
// ========================================================
render()
|
client/app/screens/InviteCreate.js | damienomurchu/snapscreen | import React from 'react';
import { Image, Picker } from 'react-native';
import {
Body,
Card,
CardItem,
Container,
Content,
Button,
Icon,
Item,
Input,
Text,
Toast,
View,
} from 'native-base';
import { createInvite } from '../api';
import { formatShowtime } from '../utils';
const styles = {
content: {
marginVertical: 10,
marginHorizontal: 8,
},
buttonContainer: {
marginTop: 8,
marginHorizontal: 2,
},
h4: {
fontSize: 18,
lineHeight: 24,
},
small: {
fontSize: 14,
},
};
export default class InviteCreateScreen extends React.Component {
static navigationOptions = {
title: 'Create Invite',
};
constructor(props) {
super(props);
this.state = {
invitees: [
{
id: '',
},
],
};
}
_theaterSelected(theater) {
this.setState({
theater,
movieShowtime: null,
});
}
_movieShowtimeSelected(movieShowtime) {
this.setState({ movieShowtime });
}
_handleInviteeChange(index, input) {
// Update list of invitees when text inputs are changed
let invitees = this.state.invitees.slice();
invitees[index] = { id: input, name: input };
this.setState({ invitees });
}
_handleInviteeSubmit(index, event) {
// Ensure there's always an empty invitee input
let invitees = this.state.invitees.slice();
if (invitees[invitees.length - 1].id !== '') {
invitees.push({ id: '' });
this.setState({ invitees });
}
}
_handleSendInvite() {
// Strip off the empty invitee if there is one
let invitees = this.state.invitees.slice();
if (invitees[invitees.length - 1].id === '') {
invitees.pop();
}
// Prepare payload
let payload = {
theater: this.state.theater,
movie: this.state.movieShowtime.movie,
showtime: this.state.movieShowtime.showtime,
invitees: invitees,
};
// Send it!
createInvite(payload)
.then(() => {
Toast.show({
text: 'Invite sent!',
position: 'bottom',
buttonText: 'Okay',
});
this.props.navigation.goBack();
})
.catch(error => {
alert('Error sending invite: ' + JSON.stringify(error));
});
}
_canSendInvite() {
return (
this.state.theater &&
this.state.movieShowtime &&
this.state.invitees[0].id
);
}
render() {
return (
<Container>
<Content style={styles.content}>
<Card>
<CardItem header bordered>
<Icon name="pin" /><Text>THEATER</Text>
</CardItem>
<If condition={this.state.theater}>
<CardItem>
<Body>
<Text style={styles.h4}>{this.state.theater.name}</Text>
<Text style={styles.small}>{this.state.theater.address}</Text>
</Body>
</CardItem>
</If>
<CardItem>
<Button
rounded
light
small
onPress={() =>
this.props.navigation.navigate('SelectTheater', {
onSelect: this._theaterSelected.bind(this),
})}
>
<Text>Select a theater</Text>
</Button>
</CardItem>
</Card>
<Card>
<CardItem header bordered>
<Icon name="clock" />
<Text>MOVIE & SHOWTIME</Text>
</CardItem>
<If condition={this.state.movieShowtime}>
<CardItem>
<Body>
<Text style={styles.h4}>
{this.state.movieShowtime.movie.title}
</Text>
<Text style={styles.small}>
{formatShowtime(this.state.movieShowtime.showtime.time)}
</Text>
</Body>
</CardItem>
</If>
<CardItem>
<Button
rounded
light
small
disabled={!this.state.theater}
onPress={() =>
this.props.navigation.navigate('SelectMovieShowtime', {
theaterID: this.state.theater.id,
onSelect: this._movieShowtimeSelected.bind(this),
})}
>
<Text>Select a movie & showtime</Text>
</Button>
</CardItem>
</Card>
<Card>
<CardItem header bordered>
<Icon name="people" />
<Text>INVITED</Text>
</CardItem>
<CardItem>
<Body>
<For each="invitee" index="idx" of={this.state.invitees}>
<Item underline key={idx}>
<Input
placeholder="Enter an email address"
onChangeText={this._handleInviteeChange.bind(this, idx)}
onSubmitEditing={this._handleInviteeSubmit.bind(
this,
idx
)}
/>
</Item>
</For>
</Body>
</CardItem>
</Card>
<View style={styles.buttonContainer}>
<Button
block
primary
disabled={!this._canSendInvite()}
onPress={this._handleSendInvite.bind(this)}
>
<Text>Send Invite</Text>
</Button>
</View>
</Content>
</Container>
);
}
}
|
src/scripts/views/reclaimPage.js | TayLang/IronPong | import React from 'react'
import ACTIONS from '../actions.js'
import STORE from '../store.js'
import NavBar from './components/navBar'
import Header from './components/header'
var ReclaimPage = React.createClass({
render: function(){
return(
<div className = 'reclaim-page-wrapper'>
<Header />
<NavBar />
<ReclaimForm />
</div>
)
}
})
var ReclaimForm = React.createClass({
handleKeyPress: function(){
},
render: function() {
return(
<div>
<input onKeyPress={this.handleKeyPress} type="text" placeholder="Enter old nickname"/>
</div>
)
}
})
export default ReclaimPage |
renderer/components/File.js | JiniHendrix/reactide | import React from 'react';
import RenameForm from './RenameForm';
import PropTypes from 'prop-types';
const File = ({
file,
dblClickHandler,
selectedItem,
id,
clickHandler,
renameFlag,
renameHandler
}) => {
return (
<li
className={selectedItem.id === id ? 'list-item selected' : 'list-item'}
onDoubleClick={dblClickHandler.bind(null, file)}
onClick={clickHandler.bind(null, id, file.path, file.type)}
>
{renameFlag && selectedItem.id === id ? <RenameForm renameHandler={renameHandler}/> : <span className="icon icon-file-text">{file.name}</span>}
</li>
)
}
File.propTypes = {
file: PropTypes.object.isRequired,
dblClickHandler: PropTypes.func.isRequired,
selectedItem: PropTypes.object.isRequired,
id: PropTypes.number.isRequired,
clickHandler: PropTypes.func.isRequired,
renameFlag: PropTypes.bool.isRequired,
renameHandler: PropTypes.func.isRequired
}
export default File; |
src/components/top-bar.js | mushishi78/content-editor | import React from 'react';
export default class TopBar extends React.Component {
render() {
return !this.props.loggedIn ? null :
<header style={styles.header}>
<nav style={styles.nav}>
{this.iconLink('/mushishi78/content-editor/docs', icons.docs)}
{this.iconLink('https://github.com/mushishi78/content-editor', icons.github)}
{this.logout()}
</nav>
{this.iconLink('/', icons.home)}
{this.breadcrumbs(this.props.href || '')}
</header>
}
iconLink(href, icon) {
return (
<a href={href} style={styles.a}>
<i style={styles.icon} className={icon} />
</a>
);
}
logout() {
return(
<a onClick={this.props.logout.bind(this, undefined)}
href='javascript:void(0)'>
<i style={styles.icon} className={icons.logout} />
</a>
);
}
breadcrumbs(href) {
return href.split('/').map((label, i, array) => {
return !label ? null :
<span style={styles.breadcrumb} key={i}>
<a href={array.slice(0, i + 1).join('/')} style={styles.a}>{label}</a>
{ i < array.length - 1 ? '/' : '' }
</span>
})
}
}
const icons = {
home: 'octicon octicon-home',
logout: 'octicon octicon-log-out',
docs: 'octicon octicon-info',
github: 'octicon octicon-mark-github'
}
const styles = {
header: {
background: '#fff',
fontSize: '1.5em',
padding: '0.3em',
boxShadow: '0 1px 1px 1px rgba(0,0,0,0.5)'
},
nav: {
float: 'right'
},
a: {
color: '#2980b9',
padding: '0 0.2em'
},
breadcrumb: {
display: 'inline-block'
},
icon: {
fontSize: '1em',
color: '#34495e',
padding: '0.05em 0.2em'
}
}
|
src/components/Button.js | drakang4/creative-project-manager | import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { secondary, secondaryDark, blackLight, blackLessLight, black, white } from '../styles/color';
const Button = styled.button`
padding: 16px;
font-size: 16px;
color: ${black};
background-color: ${blackLight};
border: none;
border-radius: 4px;
flex: 1;
${props => props.accent && `
color: ${white};
background-color: ${secondary};
`}
transition: all 0.2s ease;
&:not(:last-child) {
margin-right: 8px;
}
&:hover {
background-color: ${blackLessLight};
${props => props.accent && `
background-color: ${secondaryDark};
`}
}
&:active {
background-color: ${blackLessLight};
${props => props.accent && `
background-color: ${secondaryDark};
`}
}
`;
export default Button;
|
src/svg-icons/image/flip.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFlip = (props) => (
<SvgIcon {...props}>
<path d="M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8 20h2V1h-2v22zm8-6h2v-2h-2v2zM15 5h2V3h-2v2zm4 8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2z"/>
</SvgIcon>
);
ImageFlip = pure(ImageFlip);
ImageFlip.displayName = 'ImageFlip';
ImageFlip.muiName = 'SvgIcon';
export default ImageFlip;
|
src/components/Buttress/Buttress.js | sk-iv/iva-app | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
if(process.env.WEBPACK) require('./Buttress.css');
const Buttress = (props) => {
const {
children,
className,
size,
blend,
image,
style,
alt,
...other
} = props;
const renderImg = {
role: "img",
style: {backgroundImage:`url(${image})`, ...style}
};
const renderTxt = () => {
return(
<div className={'y-middle w-100'}>
{children}
</div>
);
};
return (
<div
className={classNames('buttress-size bg-fill y-middle-wrapper', blend ? 'img-blend' : null, 'buttress-'+size, className)}
{...renderImg}
>
{children ? renderTxt() : null}
</div>
);
};
Buttress.defaultProps= {
size: 60
};
Buttress.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
size: PropTypes.number
};
export default Buttress;
|
app/javascript/mastodon/features/notifications/components/notifications_permission_banner.js | pinfort/mastodon | import React from 'react';
import Icon from 'mastodon/components/icon';
import Button from 'mastodon/components/button';
import IconButton from 'mastodon/components/icon_button';
import { requestBrowserPermission } from 'mastodon/actions/notifications';
import { changeSetting } from 'mastodon/actions/settings';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
const messages = defineMessages({
close: { id: 'lightbox.close', defaultMessage: 'Close' },
});
export default @connect()
@injectIntl
class NotificationsPermissionBanner extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleClick = () => {
this.props.dispatch(requestBrowserPermission());
}
handleClose = () => {
this.props.dispatch(changeSetting(['notifications', 'dismissPermissionBanner'], true));
}
render () {
const { intl } = this.props;
return (
<div className='notifications-permission-banner'>
<div className='notifications-permission-banner__close'>
<IconButton icon='times' onClick={this.handleClose} title={intl.formatMessage(messages.close)} />
</div>
<h2><FormattedMessage id='notifications_permission_banner.title' defaultMessage='Never miss a thing' /></h2>
<p><FormattedMessage id='notifications_permission_banner.how_to_control' defaultMessage="To receive notifications when Mastodon isn't open, enable desktop notifications. You can control precisely which types of interactions generate desktop notifications through the {icon} button above once they're enabled." values={{ icon: <Icon id='sliders' /> }} /></p>
<Button onClick={this.handleClick}><FormattedMessage id='notifications_permission_banner.enable' defaultMessage='Enable desktop notifications' /></Button>
</div>
);
}
}
|
stories/dialogs/delete-wallet.stories.js | LN-Zap/zap-desktop | import React from 'react'
import { storiesOf } from '@storybook/react'
import { DeleteWalletDialog } from 'components/Home'
import { Window } from '../helpers'
storiesOf('Dialogs', module)
.addDecorator(story => <Window>{story()}</Window>)
.add('Delete Wallet', () => (
<DeleteWalletDialog
isOpen
onClose={() => {}}
onDelete={() => {}}
walletDir="/path/to/wallet/would/show/here"
/>
))
|
examples/custom-server-hapi/pages/index.js | BlancheXu/test | import React from 'react'
import Link from 'next/link'
export default () => (
<ul>
<li>
<Link href='/b' as='/a'>
<a>a</a>
</Link>
</li>
<li>
<Link href='/a' as='/b'>
<a>b</a>
</Link>
</li>
</ul>
)
|
src/components/ChatApp/HardwareComponent.js | madhavrathi/chat.susi.ai | import React, { Component } from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import PropTypes from 'prop-types';
import TextField from 'material-ui/TextField';
import Paper from 'material-ui/Paper';
import * as Actions from '../../actions/';
import UserPreferencesStore from '../../stores/UserPreferencesStore';
class HardwareComponent extends Component {
constructor(props) {
super(props);
this.state = {
serverUrl: '',
serverFieldError: false,
checked: false,
validForm: true,
open: false
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.customServerMessage = '';
}
handleSubmit(e) {
e.preventDefault();
// Handle Hardware Logic
const serverUrl = this.state.serverUrl;
console.log(this.state);
console.log(serverUrl);
if(! Actions.connectToWebSocket(serverUrl) ) {
alert('Connection Error. Please verify that Susi Hardware is running on address you mentioned.');
}
}
handleChange(event) {
let state = this.state;
let serverUrl;
if (event.target.name === 'serverUrl') {
serverUrl = event.target.value;
let validServerUrl =
/(ws):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:~+#-]*[\w@?^=%&~+#-])?/i
.test(serverUrl);
state.serverUrl = serverUrl;
state.serverFieldError = !(serverUrl && validServerUrl);
}
if (state.serverFieldError) {
this.customServerMessage
= 'Enter a valid Address';
}
else {
this.customServerMessage = '';
}
if (!state.serverFieldError || !state.checked) {
state.validForm = true;
}
else {
state.validForm = false;
}
this.setState(state);
};
render() {
const headerStyle = {
fontFamily: 'Open Sans',
margin: '5px 0',
fontWeight: '500'
}
const styles = {
'textAlign': 'center',
'padding': '10px 0'
}
return (
<div className="loginForm">
<Paper zDepth={0} style={styles}>
<h3 style={headerStyle}>Enter Socket Web Address</h3>
<form onSubmit={this.handleSubmit}>
<div>
<TextField name="serverUrl"
onChange={this.handleChange}
errorText={this.customServerMessage}
floatingLabelText="Websocket URL" />
</div>
<div>
<RaisedButton
label="Connect"
type="submit"
disabled={!this.state.validForm}
backgroundColor={
UserPreferencesStore.getTheme()==='light' ? '#4285f4' : '#19314B'}
labelColor="#fff"
/>
</div>
</form>
</Paper>
</div>);
}
}
HardwareComponent.propTypes = {
history: PropTypes.object
};
export default HardwareComponent;
|
src/main/internal/adaption/react/ChildrenUtils.js | mcjazzyfunky/js-surface | // external imports
import React from 'react'
// --- ChildrenUtils ------------------------------------------------
const ChildrenUtils = {
forEach: React.Children.forEach,
toArray: React.Children.toArray,
count: React.Children.count
}
// --- exports ------------------------------------------------------
export default ChildrenUtils
|
src/svg-icons/maps/local-car-wash.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalCarWash = (props) => (
<SvgIcon {...props}>
<path d="M17 5c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zm-5 0c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zM7 5c.83 0 1.5-.67 1.5-1.5C8.5 2.5 7 .8 7 .8S5.5 2.5 5.5 3.5C5.5 4.33 6.17 5 7 5zm11.92 3.01C18.72 7.42 18.16 7 17.5 7h-11c-.66 0-1.21.42-1.42 1.01L3 14v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 18c-.83 0-1.5-.67-1.5-1.5S5.67 15 6.5 15s1.5.67 1.5 1.5S7.33 18 6.5 18zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 13l1.5-4.5h11L19 13H5z"/>
</SvgIcon>
);
MapsLocalCarWash = pure(MapsLocalCarWash);
MapsLocalCarWash.displayName = 'MapsLocalCarWash';
MapsLocalCarWash.muiName = 'SvgIcon';
export default MapsLocalCarWash;
|
src/components/TextInput/TextInput.js | joshblack/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import { settings } from 'carbon-components';
import WarningFilled16 from '@carbon/icons-react/lib/warning--filled/16';
import PasswordInput from './PasswordInput';
import ControlledPasswordInput from './ControlledPasswordInput';
import { textInputProps } from './util';
const { prefix } = settings;
const TextInput = React.forwardRef(function TextInput(
{
labelText,
className = `${prefix}--text__input`,
id,
placeholder,
type,
onChange,
onClick,
hideLabel,
invalid,
invalidText,
helperText,
light,
...other
},
ref
) {
const errorId = id + '-error-msg';
const textInputClasses = classNames(`${prefix}--text-input`, className, {
[`${prefix}--text-input--light`]: light,
[`${prefix}--text-input--invalid`]: invalid,
});
const sharedTextInputProps = {
id,
onChange: evt => {
if (!other.disabled) {
onChange(evt);
}
},
onClick: evt => {
if (!other.disabled) {
onClick(evt);
}
},
placeholder,
type,
ref,
className: textInputClasses,
...other,
};
const labelClasses = classNames(`${prefix}--label`, {
[`${prefix}--visually-hidden`]: hideLabel,
[`${prefix}--label--disabled`]: other.disabled,
});
const helperTextClasses = classNames(`${prefix}--form__helper-text`, {
[`${prefix}--form__helper-text--disabled`]: other.disabled,
});
const label = labelText ? (
<label htmlFor={id} className={labelClasses}>
{labelText}
</label>
) : null;
const error = invalid ? (
<div className={`${prefix}--form-requirement`} id={errorId}>
{invalidText}
</div>
) : null;
const input = (
<input {...textInputProps({ invalid, sharedTextInputProps, errorId })} />
);
const helper = helperText ? (
<div className={helperTextClasses}>{helperText}</div>
) : null;
return (
<div className={`${prefix}--form-item ${prefix}--text-input-wrapper`}>
{label}
{helper}
<div
className={`${prefix}--text-input__field-wrapper`}
data-invalid={invalid || null}>
{invalid && (
<WarningFilled16 className={`${prefix}--text-input__invalid-icon`} />
)}
{input}
</div>
{error}
</div>
);
});
TextInput.PasswordInput = PasswordInput;
TextInput.ControlledPasswordInput = ControlledPasswordInput;
TextInput.propTypes = {
/**
* Specify an optional className to be applied to the <input> node
*/
className: PropTypes.string,
/**
* Optionally provide the default value of the <input>
*/
defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Specify whether the <input> should be disabled
*/
disabled: PropTypes.bool,
/**
* Specify a custom `id` for the <input>
*/
id: PropTypes.string.isRequired,
/**
* Provide the text that will be read by a screen reader when visiting this
* control
*/
labelText: PropTypes.node.isRequired,
/**
* Optionally provide an `onChange` handler that is called whenever <input>
* is updated
*/
onChange: PropTypes.func,
/**
* Optionally provide an `onClick` handler that is called whenever the
* <input> is clicked
*/
onClick: PropTypes.func,
/**
* Specify the placeholder attribute for the <input>
*/
placeholder: PropTypes.string,
/**
* Specify the type of the <input>
*/
type: PropTypes.string,
/**
* Specify the value of the <input>
*/
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Specify whether you want the underlying label to be visually hidden
*/
hideLabel: PropTypes.bool,
/**
* Specify whether the control is currently invalid
*/
invalid: PropTypes.bool,
/**
* Provide the text that is displayed when the control is in an invalid state
*/
invalidText: PropTypes.string,
/**
* Provide text that is used alongside the control label for additional help
*/
helperText: PropTypes.node,
/**
* `true` to use the light version.
*/
light: PropTypes.bool,
};
TextInput.defaultProps = {
disabled: false,
type: 'text',
onChange: () => {},
onClick: () => {},
invalid: false,
invalidText: '',
helperText: '',
light: false,
};
export default TextInput;
|
packages/mcs-lite-ui/src/P/P.js | MCS-Lite/mcs-lite | import React from 'react';
import PropTypes from 'prop-types';
import styled, { css } from 'styled-components';
import R from 'ramda';
import isString from '../utils/isString';
const getBaseComponent = R.ifElse(isString, R.always('p'), R.always('div'));
const Component = ({ children, ...otherProps }) =>
React.createElement(getBaseComponent(children), otherProps, children);
Component.displayName = 'Component';
Component.propTypes = {
children: PropTypes.node.isRequired,
};
const P = styled(Component)`
margin: 0;
font-size: ${props => props.theme.fontSize.p};
${props =>
props.color &&
css`
color: ${props.theme.color[props.color]};
`};
`;
P.displayName = 'P';
P.propTypes = {
color: PropTypes.string,
};
export default P;
|
src/index.js | nreoch25/react-package-dev | import React from 'react';
import ReactDOM from 'react-dom';
import Docs from "./docs/Docs";
import './index.css';
import '../node_modules/highlight.js/styles/ocean.css';
ReactDOM.render(<Docs />, document.getElementById('root'));
|
docs/src/app/components/pages/components/IconMenu/Page.js | hai-cea/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 iconMenuReadmeText from './README';
import IconMenuExampleSimple from './ExampleSimple';
import iconMenuExampleSimpleCode from '!raw!./ExampleSimple';
import IconMenuExampleControlled from './ExampleControlled';
import iconMenuExampleControlledCode from '!raw!./ExampleControlled';
import IconMenuExampleScrollable from './ExampleScrollable';
import iconMenuExampleScrollableCode from '!raw!./ExampleScrollable';
import IconMenuExampleNested from './ExampleNested';
import iconMenuExampleNestedCode from '!raw!./ExampleNested';
import iconMenuCode from '!raw!material-ui/IconMenu/IconMenu';
const IconMenusPage = () => (
<div>
<Title render={(previousTitle) => `Icon Menu - ${previousTitle}`} />
<MarkdownElement text={iconMenuReadmeText} />
<CodeExample
title="Icon Menu positioning"
code={iconMenuExampleSimpleCode}
>
<IconMenuExampleSimple />
</CodeExample>
<CodeExample
title="Controlled Icon Menus"
code={iconMenuExampleControlledCode}
>
<IconMenuExampleControlled />
</CodeExample>
<CodeExample
title="Scrollable Icon Menu"
code={iconMenuExampleScrollableCode}
>
<IconMenuExampleScrollable />
</CodeExample>
<CodeExample
title="Nested Icon Menus"
code={iconMenuExampleNestedCode}
>
<IconMenuExampleNested />
</CodeExample>
<PropTypeDescription code={iconMenuCode} />
</div>
);
export default IconMenusPage;
|
node_modules/react-bootstrap/es/MediaListItem.js | Technaesthetic/ua-tools | 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 MediaListItem = function (_React$Component) {
_inherits(MediaListItem, _React$Component);
function MediaListItem() {
_classCallCheck(this, MediaListItem);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
MediaListItem.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('li', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return MediaListItem;
}(React.Component);
export default bsClass('media', MediaListItem); |
app/screens/Options.js | rakasiwi23/currency-converter | import React, { Component } from 'react';
import { ScrollView, StatusBar, Platform, Linking } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import PropTypes from 'prop-types';
import { ListItem, Separator } from '../components/List';
import { connectAlert } from '../components/Alert';
const ICON_PREFIX = Platform.OS === 'ios' ? 'ios' : 'md';
const ICON_COLOR = '#868686';
const ICON_SIZE = 23;
class Options extends Component {
constructor(props) {
super(props);
this.handleThemesPress = this.handleThemesPress.bind(this);
this.handleSitePress = this.handleSitePress.bind(this);
}
handleThemesPress() {
this.props.navigation.navigate('Themes');
}
handleSitePress() {
Linking.openURL('http://fixer.io')
.catch(() => this.props.alertWithType('error', 'Sorry!', "Fixer.io can't be opened right now."));
}
render() {
return (
<ScrollView>
<StatusBar translucent={false} barStyle="default" />
<ListItem
text="Themes"
onPress={this.handleThemesPress}
customIcon={<Icon name={`${ICON_PREFIX}-arrow-forward`} color={ICON_COLOR} size={ICON_SIZE} />}
/>
<Separator />
<ListItem
text="Fixer.io"
onPress={this.handleSitePress}
customIcon={<Icon name={`${ICON_PREFIX}-link`} color={ICON_COLOR} size={ICON_SIZE} />}
/>
<Separator />
</ScrollView>
);
}
}
Options.propTypes = {
navigation: PropTypes.oneOfType([
PropTypes.object,
]).isRequired,
alertWithType: PropTypes.func,
};
Options.defaultProps = {
alertWithType: () => null,
};
export default connectAlert(Options);
|
src/app/components/user/UserTooltip.js | meedan/check-web | import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import { FormattedHTMLMessage, FormattedDate } from 'react-intl';
import { Link } from 'react-router';
import Avatar from '@material-ui/core/Avatar';
import LaunchIcon from '@material-ui/icons/Launch';
import styled from 'styled-components';
import '../../styles/css/tooltip.css';
import { LocalizedRole } from './UserUtil';
import ParsedText from '../ParsedText';
import SocialIcon from '../SocialIcon';
import { truncateLength } from '../../helpers';
import {
black38,
black54,
body2,
caption,
units,
} from '../../styles/js/shared';
import {
StyledTwoColumns,
StyledBigColumn,
} from '../../styles/js/HeaderCard';
const StyledMdLaunch = styled.div`
float: ${props => (props.theme.dir === 'rtl' ? 'left' : 'right')};
svg {
min-width: 20px !important;
min-height: 20px !important;
color: ${black38};
}
`;
const StyledSocialLink = styled.a`
min-width: 20px !important;
min-height: 20px !important;
svg {
min-width: 20px !important;
min-height: 20px !important;
}
`;
const StyledTooltip = styled.div`
max-width: 300px;
`;
const StyledSmallColumnTooltip = styled.div`
flex: 0;
margin-left: ${props => (props.theme.dir === 'rtl' ? units(2) : units(1))};
margin-right: ${props => (props.theme.dir === 'rtl' ? units(1) : units(2))};
justify-content: center;
flex-shrink: 0;
`;
const StyledUserRole = styled.span`
color: ${black54};
font: ${caption};
margin: ${units(1)};
`;
const AccountLink = ({ url, provider }) => (
<StyledSocialLink href={url} target="_blank" rel="noopener noreferrer" style={{ paddingRight: units(1) }}>
<SocialIcon domain={provider} />
</StyledSocialLink>
);
AccountLink.propTypes = {
url: PropTypes.string.isRequired,
provider: PropTypes.string.isRequired,
};
const userRole = ({
user, team, status, role,
}) => {
// Copied from UserUtil.js, minus the Array#find(). Don't know whether these
// if-statements are needed.
if (!user || !team || !team.slug) {
return null;
}
return status === 'requested' ? '' : role;
};
function UserTooltipComponent({ teamUser }) {
const { user } = teamUser;
const { source } = user;
const role = userRole(teamUser);
if (!source) {
return null;
}
// TODO make API give ISO8601 dates
const createdAt = new Date(parseInt(source.created_at, 10) * 1000);
return (
<StyledTooltip>
<StyledTwoColumns>
<StyledSmallColumnTooltip>
<Avatar
className="avatar"
src={source.image}
alt={user.name}
/>
</StyledSmallColumnTooltip>
<StyledBigColumn>
<div className="tooltip__primary-info">
<strong className="tooltip__name" style={{ font: body2, fontWeight: 500 }}>
{user.name}
</strong>
<StyledUserRole>{role ? <LocalizedRole role={role} /> : null}</StyledUserRole>
<Link to={`/check/user/${user.dbid}`} className="tooltip__profile-link" >
<StyledMdLaunch>
<LaunchIcon />
</StyledMdLaunch>
</Link>
<div className="tooltip__description">
<p className="tooltip__description-text" style={{ font: caption }}>
<ParsedText text={truncateLength(source.description, 600)} />
</p>
</div>
</div>
<div className="tooltip__contact-info">
<FormattedDate value={createdAt} year="numeric" month="short" day="numeric">
{dateString => (
<FormattedHTMLMessage
id="userTooltip.dateJoined"
defaultMessage="Joined {date} • {teamsCount, plural, =0 {No workspaces} one {1 workspace} other {# workspaces}}"
values={{
date: dateString,
teamsCount: user.number_of_teams,
}}
/>
)}
</FormattedDate>
</div>
{source.account_sources.edges.map(({ node: { account: { id, url, provider } } }) => (
<AccountLink key={id} url={url} provider={provider} />
))}
</StyledBigColumn>
</StyledTwoColumns>
</StyledTooltip>
);
}
export default Relay.createContainer(UserTooltipComponent, {
fragments: {
teamUser: () => Relay.QL`
fragment on TeamUser {
id
status
role
team {
id
slug
}
user {
id
dbid
name
number_of_teams
source {
id
image
description
created_at
account_sources(first: 10000) {
edges {
node {
account {
id
url
provider
}
}
}
}
}
}
}
`,
},
});
|
src/svg-icons/notification/wifi.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationWifi = (props) => (
<SvgIcon {...props}>
<path d="M1 9l2 2c4.97-4.97 13.03-4.97 18 0l2-2C16.93 2.93 7.08 2.93 1 9zm8 8l3 3 3-3c-1.65-1.66-4.34-1.66-6 0zm-4-4l2 2c2.76-2.76 7.24-2.76 10 0l2-2C15.14 9.14 8.87 9.14 5 13z"/>
</SvgIcon>
);
NotificationWifi = pure(NotificationWifi);
NotificationWifi.displayName = 'NotificationWifi';
NotificationWifi.muiName = 'SvgIcon';
export default NotificationWifi;
|
fields/types/markdown/MarkdownField.js | asifiqbal84/keystone | import Field from '../Field';
import React from 'react';
import { FormInput } from 'elemental';
/**
* TODO:
* - Remove dependency on jQuery
*/
// Scope jQuery and the bootstrap-markdown editor so it will mount
var $ = require('jquery');
require('./lib/bootstrap-markdown');
// Append/remove ### surround the selection
// Source: https://github.com/toopay/bootstrap-markdown/blob/master/js/bootstrap-markdown.js#L909
var toggleHeading = function(e, level) {
var chunk, cursor, selected = e.getSelection(), content = e.getContent(), pointer, prevChar;
if (selected.length === 0) {
// Give extra word
chunk = e.__localize('heading text');
} else {
chunk = selected.text + '\n';
}
// transform selection and set the cursor into chunked text
if ((pointer = level.length + 1, content.substr(selected.start - pointer, pointer) === level + ' ')
|| (pointer = level.length, content.substr(selected.start - pointer, pointer) === level)) {
e.setSelection(selected.start - pointer, selected.end);
e.replaceSelection(chunk);
cursor = selected.start - pointer;
} else if (selected.start > 0 && (prevChar = content.substr(selected.start - 1, 1), !!prevChar && prevChar !== '\n')) {
e.replaceSelection('\n\n' + level + ' ' + chunk);
cursor = selected.start + level.length + 3;
} else {
// Empty string before element
e.replaceSelection(level + ' ' + chunk);
cursor = selected.start + level.length + 1;
}
// Set the cursor
e.setSelection(cursor, cursor + chunk.length);
};
var renderMarkdown = function(component) {
// dependsOn means that sometimes the component is mounted as a null, so account for that & noop
if (!component.refs.markdownTextarea) {
return;
}
var options = {
autofocus: false,
savable: false,
resize: 'vertical',
height: component.props.height,
hiddenButtons: ['Heading'],
// Heading buttons
additionalButtons: [{
name: 'groupHeaders',
data: [{
name: 'cmdH1',
title: 'Heading 1',
btnText: 'H1',
callback: function(e) {
toggleHeading(e, '#');
}
}, {
name: 'cmdH2',
title: 'Heading 2',
btnText: 'H2',
callback: function(e) {
toggleHeading(e, '##');
}
}, {
name: 'cmdH3',
title: 'Heading 3',
btnText: 'H3',
callback: function(e) {
toggleHeading(e, '###');
}
}, {
name: 'cmdH4',
title: 'Heading 4',
btnText: 'H4',
callback: function(e) {
toggleHeading(e, '####');
}
}]
}],
// Insert Header buttons into the toolbar
reorderButtonGroups: ['groupFont', 'groupHeaders', 'groupLink', 'groupMisc', 'groupUtil']
};
if (component.props.toolbarOptions.hiddenButtons) {
var hiddenButtons = ('string' === typeof component.props.toolbarOptions.hiddenButtons) ? component.props.toolbarOptions.hiddenButtons.split(',') : component.props.toolbarOptions.hiddenButtons;
options.hiddenButtons = options.hiddenButtons.concat(hiddenButtons);
}
$(component.refs.markdownTextarea.getDOMNode()).markdown(options);
};
module.exports = Field.create({
displayName: 'MarkdownField',
// Override `shouldCollapse` to check the markdown field correctly
shouldCollapse () {
return this.props.collapse && !this.props.value.md;
},
// only have access to `refs` once component is mounted
componentDidMount () {
if (this.props.wysiwyg) {
renderMarkdown(this);
}
},
// only have access to `refs` once component is mounted
componentDidUpdate () {
if (this.props.wysiwyg) {
renderMarkdown(this);
}
},
renderField () {
var styles = {
padding: 8,
height: this.props.height
};
return <textarea name={this.props.paths.md} style={styles} defaultValue={this.props.value.md} ref="markdownTextarea" className="md-editor__input code" />;
},
renderValue () {
return <FormInput multiline noedit dangerouslySetInnerHTML={{ __html: this.props.value.md.replace(/\n/g, '<br />') }} />;
}
});
|
src/pages/404.js | growcss/growcss-site | import React from 'react';
import Box from 'components/box';
import Layout from 'components/layout';
const NotFound = () => (
<Layout>
<Box>Not found.</Box>
</Layout>
);
export default NotFound;
|
src/components/Home/SiteInfo.js | mattschwartz/mattschwartz | import React from 'react'
export default () => (
<>
<h3 className="section-header">Site Info</h3>
<p>Click <a className="fancy-link" href="https://github.com/mattschwartz/www">here</a> to see the source code</p>
<p>Powered by React and served fresh by AWS</p>
<p>Written by Matt Schwartz, 2019</p>
</>
)
|
src/svg-icons/image/crop.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCrop = (props) => (
<SvgIcon {...props}>
<path d="M17 15h2V7c0-1.1-.9-2-2-2H9v2h8v8zM7 17V1H5v4H1v2h4v10c0 1.1.9 2 2 2h10v4h2v-4h4v-2H7z"/>
</SvgIcon>
);
ImageCrop = pure(ImageCrop);
ImageCrop.displayName = 'ImageCrop';
ImageCrop.muiName = 'SvgIcon';
export default ImageCrop;
|
editor/components/FloatPaper.js | conundrumer/sim-seq | import React from 'react'
import { Paper } from 'material-ui'
import classNames from 'classnames'
export default class FloatPaper extends React.Component {
render() {
return (
<Paper
className={classNames('float-paper', this.props.className)}
circle={this.props.circle}
style={{boxShadow: 'null', pointerEvents: 'auto'}}
transitionEnabled={false}
onTouchStart={e => e.preventDefault()}
onMouseDown={e => e.preventDefault()}
>
{this.props.children}
</Paper>
)
}
}
|
src/components/ProfileIntro.js | planningFor/react-build | import React, { Component } from 'react';
require('../css/ProfileIntro.scss');
/**
* Header component in index page.
*/
const Introduction = () => (
<section className="profile-intro">
<h3>关于我</h3>
<p>大家好,我叫杨雯杰。本科毕业与成都信息工程大学,现就读于电子科技大学计算机科学与工程学院。</p>
<p>我觉得前端是一门多性质的工作,从本科开始就对前端有很大的兴趣。但是很可惜的是,当时忙于完成学习任务,没有对前端进行一些深入的了解。直到读到了研究生阶段,开始规划自己未来的道路,我觉得前端才是我始终如一的兴趣所在。因此,当我踏上前端这条路的时候,我庆幸当时自己的选择,也庆幸自己在这条路上能够越走越远。</p>
<p>希望未来能够成为一个经验丰富的前端开发者。</p>
</section>
);
export default Introduction;
|
react/src/server/frontend/ServerFetchProvider.js | janprasil/mi-vmm-product-quality-rating | import React from 'react';
class ServerFetchProvider extends React.Component {
static childContextTypes = {
serverFetchPromises: React.PropTypes.array,
};
getChildContext() {
return {
serverFetchPromises: this.props.promises,
};
}
props: {
// github.com/facebook/flow/issues/1964
children?: any,
promises: Array<Promise<any>>,
}
render() {
return React.Children.only(this.props.children);
}
}
export default ServerFetchProvider;
|
packages/material-ui-icons/src/SimCardAlert.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M18 2h-8L4.02 8 4 20c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5 15h-2v-2h2v2zm0-4h-2V8h2v5z" /></g>
, 'SimCardAlert');
|
src/js/pages/LoginPage.js | nekuno/client | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import TopNavBar from '../components/ui/TopNavBar';
import SocialBox from '../components/ui/SocialBox';
import translate from '../i18n/Translate';
import LoginActionCreators from '../actions/LoginActionCreators';
import LoginStore from '../stores/LoginStore';
import SocialNetworkService from '../services/SocialNetworkService';
import Framework7Service from '../services/Framework7Service';
@translate('LoginPage')
export default class LoginPage extends Component {
static propTypes = {
// Injected by @translate:
strings: PropTypes.object
};
static contextTypes = {
router: PropTypes.object.isRequired
};
constructor() {
super();
this.goHome = this.goHome.bind(this);
this.goToRegisterPage = this.goToRegisterPage.bind(this);
this.loginByResourceOwner = this.loginByResourceOwner.bind(this);
}
loginByResourceOwner(resource, scope) {
SocialNetworkService.login(resource, scope).then(
() => {
LoginActionCreators.loginUserByResourceOwner(
resource,
SocialNetworkService.getAccessToken(resource),
SocialNetworkService.getRefreshToken(resource)
).then(
() => {
return null; // User is logged in
},
(error) => {
Framework7Service.nekunoApp().alert(error.error);
});
},
(status) => {
Framework7Service.nekunoApp().alert(resource + ' login failed: ' + status.error.message)
});
}
loginAsGuest = function() {
LoginActionCreators.loginUser('guest', 'guest');
};
goToRegisterPage = function() {
this.context.router.push('/register');
};
goHome() {
this.context.router.push('/');
}
render() {
const {strings} = this.props;
return (
<div className="views">
{LoginStore.justLoggedOut ?
<TopNavBar leftText={strings.cancel} centerText={strings.login} onLeftLinkClickHandler={this.goHome}/>
:
<TopNavBar leftText={strings.cancel} centerText={strings.login}/>
}
<div className="view view-main">
<div className="page">
<div id="page-content" className="login-content">
<p className="center">{strings.loginResource}</p>
<SocialBox onClickHandler={this.loginByResourceOwner}/>
<br />
<div className="register-text-block">
<div onClick={this.goToRegisterPage} className="register-text">
<span>{strings.hasInvitation}</span> <a href="javascript:void(0)">{strings.register}</a>
</div>
{/*Uncomment to enable login as guest
<div onClick={this.loginAsGuest} className="register-text">
<span>{strings.wantGuest}</span> <a href="javascript:void(0)">{strings.asGuest}</a>
</div>*/}
</div>
<br />
<br />
<br />
</div>
</div>
</div>
</div>
);
}
}
LoginPage.defaultProps = {
strings: {
login : 'Login',
cancel : 'Cancel',
loginResource: 'Login with a social network',
hasInvitation: 'Do you have an invitation?',
register : 'Register',
wantGuest : 'Do you want to try it?',
asGuest : 'Enter as guest'
}
}; |
server/index.js | amitpaperg/roadmap-planner | import path from 'path'
import http from 'http'
import express from 'express'
import helmet from 'helmet'
import bodyParser from 'body-parser'
import morgan from 'morgan'
import compression from 'compression'
import hpp from 'hpp'
import throng from 'throng'
import React from 'react'
import ReactDOM from 'react-dom/server'
import { createMemoryHistory, RouterContext, match } from 'react-router'
import { Provider } from 'react-redux'
import { trigger } from 'redial'
import { StyleSheetServer } from 'aphrodite'
import Helm from 'react-helmet' // because we are already using helmet
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import DefaultServerConfig from './config'
import webpackConfig from '../tools/webpack.client.dev'
import { compileDev, startDev } from '../tools/dx'
import { configureStore } from '../common/store'
import reducer from '../common/createReducer'
import createRoutes from '../common/routes/root'
export const createServer = (config) => {
const __PROD__ = config.nodeEnv === 'production'
const __TEST__ = config.nodeEnv === 'test'
const app = express()
let assets = null
app.disable('x-powered-by')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
if (__PROD__ || __TEST__) {
app.use(morgan('combined'))
app.use(helmet())
app.use(hpp())
app.use(compression())
if (__PROD__) {
assets = require('../assets.json')
}
} else {
app.use(morgan('dev'))
const compiler = compileDev((webpack(webpackConfig)), config.port)
app.use(webpackDevMiddleware(compiler, {
quiet: true,
watchOptions: {
ignored: /node_modules/
}
}))
app.use(webpackHotMiddleware(compiler, { log: console.log }))
}
app.use(express.static('public'))
app.use('/api/v0/posts', require('./api/posts'))
app.get('*', (req, res) => {
const store = configureStore({
sourceRequest: {
protocol: req.headers['x-forwarded-proto'] || req.protocol,
host: req.headers.host
}
})
const routes = createRoutes(store)
const history = createMemoryHistory(req.originalUrl)
const { dispatch } = store
match({ routes, history}, (err, redirectLocation, renderProps) => {
if (err) {
console.error(err)
return res.status(500).send('Internal server error')
}
if (!renderProps) {
return res.status(404).send('Not found')
}
const { components } = renderProps
// Define locals to be provided to all lifecycle hooks:
const locals = {
path: renderProps.location.pathname,
query: renderProps.location.query,
params: renderProps.params,
// Allow lifecycle hooks to dispatch Redux actions:
dispatch
}
trigger('fetch', components, locals)
.then(() => {
const initialState = store.getState()
const InitialView = (
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
)
// just call html = ReactDOM.renderToString(InitialView)
// to if you don't want Aphrodite. Also change renderFullPage
// accordingly
const data = StyleSheetServer.renderStatic(
() => ReactDOM.renderToString(InitialView)
)
const head = Helm.rewind()
res.status(200).send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charSet="utf-8">
<meta httpEquiv="X-UA-Compatible" content="IE=edge">
${head.title.toString()}
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="/favicon.ico">
${head.meta.toString()}
${head.link.toString()}
<style>
html {
box-sizing: border-box
}
*,
*::before,
*::after {
box-sizing: border-box
}
html {
font-size: 100%;
-ms-overflow-style: scrollbar;
-webkit-tap-highlight-color: rgba(0,0,0,0);
height: 100%;
}
body {
font-size: 1rem;
background-color: #fff;
color: #555;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-family: -apple-system,BlinkMacSystemFont,"Helvetica Neue",Helvetica,Arial,sans-serif;
}
h1,h2,h3,h4,h5,h6 {
margin: 0;
padding: 0;
}
</style>
<style data-aphrodite>${data.css.content}</style>
</head>
<body>
<div id="root">${data.html}</div>
<script>window.renderedClassNames = ${JSON.stringify(data.css.renderedClassNames)};</script>
<script>window.INITIAL_STATE = ${JSON.stringify(initialState)};</script>
<script src="${ __PROD__ ? assets.vendor.js : '/vendor.js' }"></script>
<script async src="${ __PROD__ ? assets.main.js : '/main.js' }" ></script>
</body>
</html>
`)
}).catch(e => console.log(e))
})
})
const server = http.createServer(app)
// Heroku dynos automatically timeout after 30s. Set our
// own timeout here to force sockets to close before that.
// https://devcenter.heroku.com/articles/request-timeout
if (config.timeout) {
server.setTimeout(config.timeout, (socket) => {
const message = `Timeout of ${config.timeout}ms exceeded`
socket.end([
'HTTP/1.1 503 Service Unavailable',
`Date: ${(new Date).toGMTString()}`, // eslint-disable-line
'Content-Type: text/plain',
`Content-Length: ${message.length}`,
'Connection: close',
'',
message
].join(`\r\n`))
})
}
return server
}
export const startServer = (serverConfig) => {
const config = {...DefaultServerConfig, ...serverConfig}
const server = createServer(config)
server.listen(config.port, (err) => {
if (config.nodeEnv === 'production' || config.nodeEnv === 'test') {
if (err) console.log(err)
console.log(`server ${config.id} listening on port ${config.port}`)
} else {
startDev(config.port, err)
}
})
}
if (require.main === module) {
throng({
start: (id) => startServer({ id }),
workers: process.env.WEB_CONCURRENCY || 1,
lifetime: Infinity
})
}
|
app/javascript/mastodon/features/notifications/index.js | increments/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { expandNotifications, scrollTopNotifications } from '../../actions/notifications';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import NotificationContainer from './containers/notification_container';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ColumnSettingsContainer from './containers/column_settings_container';
import { createSelector } from 'reselect';
import { List as ImmutableList } from 'immutable';
import { debounce } from 'lodash';
import ScrollableList from '../../components/scrollable_list';
const messages = defineMessages({
title: { id: 'column.notifications', defaultMessage: 'Notifications' },
});
const getNotifications = createSelector([
state => ImmutableList(state.getIn(['settings', 'notifications', 'shows']).filter(item => !item).keys()),
state => state.getIn(['notifications', 'items']),
], (excludedTypes, notifications) => notifications.filterNot(item => excludedTypes.includes(item.get('type'))));
const mapStateToProps = state => ({
notifications: getNotifications(state),
isLoading: state.getIn(['notifications', 'isLoading'], true),
isUnread: state.getIn(['notifications', 'unread']) > 0,
hasMore: !!state.getIn(['notifications', 'next']),
});
@connect(mapStateToProps)
@injectIntl
export default class Notifications extends React.PureComponent {
static propTypes = {
columnId: PropTypes.string,
notifications: ImmutablePropTypes.list.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
intl: PropTypes.object.isRequired,
isLoading: PropTypes.bool,
isUnread: PropTypes.bool,
multiColumn: PropTypes.bool,
hasMore: PropTypes.bool,
};
static defaultProps = {
trackScroll: true,
};
componentWillUnmount () {
this.handleLoadMore.cancel();
this.handleScrollToTop.cancel();
this.handleScroll.cancel();
this.props.dispatch(scrollTopNotifications(false));
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandNotifications());
}, 300, { leading: true });
handleScrollToTop = debounce(() => {
this.props.dispatch(scrollTopNotifications(true));
}, 100);
handleScroll = debounce(() => {
this.props.dispatch(scrollTopNotifications(false));
}, 100);
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('NOTIFICATIONS', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setColumnRef = c => {
this.column = c;
}
handleMoveUp = id => {
const elementIndex = this.props.notifications.findIndex(item => item.get('id') === id) - 1;
this._selectChild(elementIndex);
}
handleMoveDown = id => {
const elementIndex = this.props.notifications.findIndex(item => item.get('id') === id) + 1;
this._selectChild(elementIndex);
}
_selectChild (index) {
const element = this.column.node.querySelector(`article:nth-of-type(${index + 1}) .focusable`);
if (element) {
element.focus();
}
}
render () {
const { intl, notifications, shouldUpdateScroll, isLoading, isUnread, columnId, multiColumn, hasMore } = this.props;
const pinned = !!columnId;
const emptyMessage = <FormattedMessage id='empty_column.notifications' defaultMessage="You don't have any notifications yet. Interact with others to start the conversation." />;
let scrollableContent = null;
if (isLoading && this.scrollableContent) {
scrollableContent = this.scrollableContent;
} else if (notifications.size > 0 || hasMore) {
scrollableContent = notifications.map((item) => (
<NotificationContainer
key={item.get('id')}
notification={item}
accountId={item.get('account')}
onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown}
/>
));
} else {
scrollableContent = null;
}
this.scrollableContent = scrollableContent;
const scrollContainer = (
<ScrollableList
scrollKey={`notifications-${columnId}`}
trackScroll={!pinned}
isLoading={isLoading}
hasMore={hasMore}
emptyMessage={emptyMessage}
onLoadMore={this.handleLoadMore}
onScrollToTop={this.handleScrollToTop}
onScroll={this.handleScroll}
shouldUpdateScroll={shouldUpdateScroll}
>
{scrollableContent}
</ScrollableList>
);
return (
<Column ref={this.setColumnRef}>
<ColumnHeader
icon='bell'
active={isUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<ColumnSettingsContainer />
</ColumnHeader>
{scrollContainer}
</Column>
);
}
}
|
redux/js/todo/containers/RouteFilterLink.js | quiaro/js-playground | import React from 'react';
import { Link } from 'react-router';
const RouteFilterLink = ({ filter, children }) => (
<Link
to={filter === 'all' ? '' : filter}
activeStyle={{
textDecoration: 'none',
color: 'black',
}}
>
{children}
</Link>
);
export default RouteFilterLink;
|
src/components/marketingStatusLabel/MarketingStatusLabel.js | teamleadercrm/teamleader-ui | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import Icon from '../icon';
import cx from 'classnames';
import theme from './theme.css';
import { IconLockSmallFilled } from '@teamleader/ui-icons';
import { UITextBody, UITextSmall } from '../typography';
class MarketingStatusLabel extends Component {
render() {
const { children, className, fullWidth, size, ...others } = this.props;
const classNames = cx(theme['wrapper'], theme[`is-${size}`], className);
const TextElement = size === 'small' ? UITextSmall : UITextBody;
return (
<Box
{...others}
alignItems="center"
display={fullWidth ? 'flex' : 'inline-flex'}
justifyContent="center"
className={classNames}
paddingHorizontal={2}
>
<TextElement className={theme['text']} marginRight={2}>
{children}
</TextElement>
<Icon className={theme['icon']}>
<IconLockSmallFilled />
</Icon>
</Box>
);
}
}
MarketingStatusLabel.propTypes = {
children: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
fullWidth: PropTypes.bool,
size: PropTypes.oneOf(['small', 'medium']),
};
MarketingStatusLabel.defaultProps = {
fullWidth: false,
size: 'medium',
};
export default MarketingStatusLabel;
|
src/components/app.js | TonCoder/react-music-player | import React, { Component } from 'react';
import MusicPlayer from './MusicPlayer/MusicPlayer';
export default class App extends Component {
constructor(props){
super(props);
this.state = {
"Albums":[
{
"artist": "Trinity",
"albumName": "Tethered",
"coverArt": "http://unrealitymag.com/wp-content/uploads/2015/01/80s_Villains_3.jpg",
"songs": [
{
"songName": "Belly Dancing",
"songUrl": "./songs/Belly Dancing.mp3",
},
{
"songName": "Kehta Hai Pal Pal",
"songUrl": "./songs/Kehta Hai Pal Pal.mp3",
}
]
},
{
"artist": "Trinity",
"albumName": "Stragler",
"coverArt": "http://www.fuse.tv/image/56fe73a1e05e186b2000009b/768/512/the-boxer-rebellion-ocean-by-ocean-album-cover-full-size.jpg",
"songs": [
{
"songName": "Wave Master",
"songUrl": "./songs/Love Mashup 2016 - Kiran Kamath (ApniISP.Com).mp3",
},
{
"songName": "Manjave",
"songUrl": "./songs/Manjave (Apniisp.Com).mp3",
},
{
"songName": "Out Of Control",
"songUrl": "./songs/Out Of Control (Apniisp.Com).mp3",
}
]
}
]
};
};
render() {
return (
<div className="row">
<MusicPlayer albumData={this.state.Albums || {}} albumToShow="Tethered" />
<MusicPlayer albumData={this.state.Albums || {}} albumToShow="Stragler" />
</div>
);
}
}
|
app/javascript/mastodon/features/ui/components/video_modal.js | lindwurm/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Video from 'mastodon/features/video';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Footer from 'mastodon/features/picture_in_picture/components/footer';
import { getAverageFromBlurhash } from 'mastodon/blurhash';
export default class VideoModal extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
statusId: PropTypes.string,
options: PropTypes.shape({
startTime: PropTypes.number,
autoPlay: PropTypes.bool,
defaultVolume: PropTypes.number,
}),
onClose: PropTypes.func.isRequired,
onChangeBackgroundColor: PropTypes.func.isRequired,
};
componentDidMount () {
const { media, onChangeBackgroundColor } = this.props;
const backgroundColor = getAverageFromBlurhash(media.get('blurhash'));
if (backgroundColor) {
onChangeBackgroundColor(backgroundColor);
}
}
render () {
const { media, statusId, onClose } = this.props;
const options = this.props.options || {};
return (
<div className='modal-root__modal video-modal'>
<div className='video-modal__container'>
<Video
preview={media.get('preview_url')}
frameRate={media.getIn(['meta', 'original', 'frame_rate'])}
blurhash={media.get('blurhash')}
src={media.get('url')}
currentTime={options.startTime}
autoPlay={options.autoPlay}
volume={options.defaultVolume}
onCloseVideo={onClose}
detailed
alt={media.get('description')}
/>
</div>
<div className='media-modal__overlay'>
{statusId && <Footer statusId={statusId} withOpenButton onClose={onClose} />}
</div>
</div>
);
}
}
|
src/App.js | rahulpyd/react-dnd-sort-example | import React, { Component } from 'react';
export default class App extends Component {
render() {
return (
<h1>Hello, world.</h1>
);
}
}
|
src/svg-icons/editor/format-align-center.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatAlignCenter = (props) => (
<SvgIcon {...props}>
<path d="M7 15v2h10v-2H7zm-4 6h18v-2H3v2zm0-8h18v-2H3v2zm4-6v2h10V7H7zM3 3v2h18V3H3z"/>
</SvgIcon>
);
EditorFormatAlignCenter = pure(EditorFormatAlignCenter);
EditorFormatAlignCenter.displayName = 'EditorFormatAlignCenter';
EditorFormatAlignCenter.muiName = 'SvgIcon';
export default EditorFormatAlignCenter;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.