path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
example/basic/components/Main.js | didierfranc/react-sc | import React from 'react'
import { Main, Link } from './Styled'
export default () => (
<Main>
<Link
weird={true}
href="https://github.com/didierfranc/react-sc"
htmlFor="box"
>
react-sc
</Link>
</Main>
)
|
src/web/components/CreateList.js | faalsh/LamaDesktop | import React from 'react';
import { connect } from 'react-redux'
import * as LamaActions from '../../common/actions'
import { bindActionCreators } from 'redux'
import { StyleSheet, css } from 'aphrodite'
class CreateList extends React.Component {
constructor(props) {
super(props);
this.state = {
title: '',
panelOpen: false
}
}
handleClick(){
const {boardId, actions} = this.props
const {title} = this.state
if(title !== '') {
actions.createList(boardId,title)
this.setState({
title: '',
panelOpen: false
})
}
}
handleClose(){
this.setState({
title: '',
panelOpen: false
})
}
handleChange(e) {
this.setState({
title: e.target.value
})
}
openPanel(){
this.setState({
panelOpen: true
})
}
handleKeyDown(e){
if(e.key === 'Enter'){
const {boardId, actions} = this.props
const {title} = this.state
if(title !== '') {
actions.createList(boardId,title)
this.setState({
title: '',
panelOpen: false
})
}
} else if (e.key === 'Escape') {
this.setState({
title: '',
panelOpen: false
})
}
}
render() {
const keyframes = {
'from': {
opacity: 0,
},
'to': {
opacity: 1,
}
}
const styles = StyleSheet.create({
panel: {
padding: '5px',
margin: '5px',
borderRadius: '3px',
backgroundColor: 'lightgrey',
boxShadow: '0 2px 4px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12)',
height: '100%',
width: '200px',
display: 'flex',
flexDirection: 'column'
},
input: {
width: '185px',
height: '20px',
fontWeight: 'bold',
marginTop: '10px',
marginLeft: '5px',
marginBottom:'10px'
},
panelButton: {
padding: '5px',
width: '70px',
height: '20px',
fontSize: '12px',
background: 'linear-gradient(to bottom,#61BD4F 0,#5AAC44 100%)',
color: 'white',
boxShadow: '0 1px 0 #3F6F21',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
marginLeft: '5px',
marginBottom:'10px'
},
panelBottom: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center'
},
closeButton: {
marginLeft: '15px',
marginBottom: '10px',
fontSize: '25px',
cursor: 'pointer'
},
addButton: {
margin: '3px',
backgroundColor: '#006ba9',
color:'white',
height:'20px',
width: '200px',
padding: '5px',
display: 'flex',
alignItems: 'center',
justifyContent:'center',
cursor: 'pointer',
opacity: '.7',
':hover': {
backgroundColor: '#51bfff'
}
},
// animate: {
// animationName: keyframes,
// animationDuration: '500ms'
// }
})
const AddListForm = () => {
return (
<div className={css(styles.panel, styles.animate)}>
<div>
<input autoFocus onChange={this.handleChange.bind(this)} className={css(styles.input)}
value={this.state.title} placeholder="List title" onKeyDown={this.handleKeyDown.bind(this)}/>
</div>
<div className={css(styles.panelBottom)}>
<div onClick={this.handleClick.bind(this)} className={css(styles.panelButton)}>
Save
</div>
<div onClick={this.handleClose.bind(this)} className={css(styles.closeButton)}>x</div>
</div>
</div>
)
}
const AddListButton = () => {
return (
<div >
<div className={css(styles.addButton)} onClick={this.openPanel.bind(this)}>Add list</div>
</div>
)
}
return this.state.panelOpen? <AddListForm /> : <AddListButton />
}
}
const mapDispatchToProps = dispatch =>({
actions: bindActionCreators(LamaActions,dispatch)
})
export default connect(null, mapDispatchToProps)(CreateList);
|
src/TimePicker/ClockMinutes.js | pradel/material-ui | import React from 'react';
import ClockNumber from './ClockNumber';
import ClockPointer from './ClockPointer';
import {getTouchEventOffsetValues, rad2deg} from './timeUtils';
class ClockMinutes extends React.Component {
static propTypes = {
initialMinutes: React.PropTypes.number,
onChange: React.PropTypes.func,
};
static defaultProps = {
initialMinutes: new Date().getMinutes(),
onChange: () => {},
};
static contextTypes = {
muiTheme: React.PropTypes.object.isRequired,
};
componentDidMount() {
const clockElement = this.refs.mask;
this.center = {
x: clockElement.offsetWidth / 2,
y: clockElement.offsetHeight / 2,
};
this.basePoint = {
x: this.center.x,
y: 0,
};
}
isMousePressed(event) {
if (typeof event.buttons === 'undefined') {
return event.nativeEvent.which;
}
return event.buttons;
}
handleUp = (event) => {
event.preventDefault();
this.setClock(event.nativeEvent, true);
};
handleMove = (event) => {
event.preventDefault();
if (this.isMousePressed(event) !== 1 ) return;
this.setClock(event.nativeEvent, false);
};
handleTouch = (event) => {
event.preventDefault();
this.setClock(event.changedTouches[0], false);
};
setClock(event, finish) {
if (typeof event.offsetX === 'undefined') {
const offset = getTouchEventOffsetValues(event);
event.offsetX = offset.offsetX;
event.offsetY = offset.offsetY;
}
const minutes = this.getMinutes(event.offsetX, event.offsetY);
this.props.onChange(minutes, finish);
}
getMinutes(offsetX, offsetY) {
const step = 6;
const x = offsetX - this.center.x;
const y = offsetY - this.center.y;
const cx = this.basePoint.x - this.center.x;
const cy = this.basePoint.y - this.center.y;
const atan = Math.atan2(cx, cy) - Math.atan2(x, y);
let deg = rad2deg(atan);
deg = Math.round(deg / step ) * step;
deg %= 360;
const value = Math.floor(deg / step) || 0;
return value;
}
getMinuteNumbers() {
const minutes = [];
for (let i = 0; i < 12; i++) {
minutes.push(i * 5);
}
const selectedMinutes = this.props.initialMinutes;
let hasSelected = false;
const numbers = minutes.map((minute) => {
const isSelected = selectedMinutes === minute;
if (isSelected) hasSelected = true;
return (
<ClockNumber
key={minute} isSelected={isSelected} type="minute"
value={minute}
/>
);
});
return {
numbers: numbers,
hasSelected: hasSelected,
selected: selectedMinutes,
};
}
render() {
const styles = {
root: {
height: '100%',
width: '100%',
borderRadius: '100%',
position: 'relative',
pointerEvents: 'none',
boxSizing: 'border-box',
},
hitMask: {
height: '100%',
width: '100%',
pointerEvents: 'auto',
},
};
const {prepareStyles} = this.context.muiTheme;
const minutes = this.getMinuteNumbers();
return (
<div ref="clock" style={prepareStyles(styles.root)} >
<ClockPointer value={minutes.selected} type="minute" />
{minutes.numbers}
<div ref="mask" style={prepareStyles(styles.hitMask)} hasSelected={minutes.hasSelected}
onTouchMove={this.handleTouch} onTouchEnd={this.handleTouch}
onMouseUp={this.handleUp} onMouseMove={this.handleMove}
/>
</div>
);
}
}
export default ClockMinutes;
|
src/templates/blog-post.js | lvjing2/liangcloud | import React from 'react';
import Helmet from 'react-helmet';
// import '../css/blog-post.css'; // make it pretty!
export default function Template({
data // this prop will be injected by the GraphQL query we'll write in a bit
}) {
const { markdownRemark: post } = data; // data.markdownRemark holds our post data
return (
<div className="blog-post-container">
<Helmet title={`Your Blog Name - ${post.frontmatter.title}`} />
<div className="blog-post">
<h1>{post.frontmatter.title}</h1>
<div className="blog-post-content" dangerouslySetInnerHTML={{ __html: post.html }} />
</div>
</div>
);
} |
src/svg-icons/action/visibility-off.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionVisibilityOff = (props) => (
<SvgIcon {...props}>
<path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/>
</SvgIcon>
);
ActionVisibilityOff = pure(ActionVisibilityOff);
ActionVisibilityOff.displayName = 'ActionVisibilityOff';
ActionVisibilityOff.muiName = 'SvgIcon';
export default ActionVisibilityOff;
|
src/components/editor/editor-toolbar.js | stevegood/stringer | import React from 'react'
import {
IconButton,
Toolbar,
ToolbarGroup,
ToolbarSeparator
} from 'material-ui'
// svg icons
import FormatBold from 'material-ui/svg-icons/editor/format-bold'
import FormatUnderlined from 'material-ui/svg-icons/editor/format-underlined'
import FormatItalic from 'material-ui/svg-icons/editor/format-italic'
import InsertPhoto from 'material-ui/svg-icons/editor/insert-photo'
import InsertLink from 'material-ui/svg-icons/editor/insert-link'
import FormatListBulleted from 'material-ui/svg-icons/editor/format-list-bulleted'
import FormatListNumbered from 'material-ui/svg-icons/editor/format-list-numbered'
import Code from 'material-ui/svg-icons/action/code'
import OndemandVideo from 'material-ui/svg-icons/notification/ondemand-video'
import Save from 'material-ui/svg-icons/content/save'
import { styles } from './content-editor-styles'
export const EditorToolbar = (props) => {
return (
<Toolbar style={styles.toolbar}>
<ToolbarGroup firstChild>
<IconButton
onTouchTap={props.onBoldClick}
tooltip='Bold'
tooltipPosition='top-left'>
<FormatBold />
</IconButton>
<IconButton
onTouchTap={props.onUnderlineClick}
tooltip='Underline'
tooltipPosition='top-left'>
<FormatUnderlined />
</IconButton>
<IconButton
onTouchTap={props.onItalicClick}
tooltip='Italic'
tooltipPosition='top-left'>
<FormatItalic />
</IconButton>
<ToolbarSeparator />
<IconButton
tooltip='Bullet list'
tooltipPosition='top-left'>
<FormatListBulleted />
</IconButton>
<IconButton
tooltip='Numbered list'
tooltipPosition='top-left'>
<FormatListNumbered />
</IconButton>
<ToolbarSeparator />
<IconButton
tooltip='Code'
tooltipPosition='top-left'>
<Code />
</IconButton>
<IconButton
tooltip='Link'
tooltipPosition='top-left'>
<InsertLink />
</IconButton>
<IconButton
tooltip='Image'
tooltipPosition='top-left'>
<InsertPhoto />
</IconButton>
<IconButton
tooltip='Video'
tooltipPosition='top-left'>
<OndemandVideo />
</IconButton>
</ToolbarGroup>
<ToolbarGroup>
<ToolbarSeparator />
<IconButton
tooltip='Save'
tooltipPosition='top-left'>
<Save />
</IconButton>
</ToolbarGroup>
</Toolbar>
)
}
|
examples/http/index.js | rayshih/fun-react | // @flow
import React from 'react'
import ReactDOM from 'react-dom'
import {Observable} from 'rx'
import {
createTypes,
caseOf,
createView,
createProgram,
} from '../../src'
import type {UpdateFnR, Reaction} from '../../src'
type Model = {
topic: string,
gifUrl: string
}
/**
* This is an example ported from http://elm-lang.org/examples/http
*/
const Msg = createTypes(
'MorePlease',
'FetchSucceed',
'FetchFail'
)
const getRandomGif = topic => {
const url =
"https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" + topic
const json = fetch(url).then(res => res.json())
return Observable.fromPromise(json)
.map(json => json.data.image_url)
.map(Msg.FetchSucceed)
}
const init = (topic): Reaction<Model> => [
{
topic,
gifUrl: "waiting.gif"
},
[getRandomGif(topic)]
]
const update
: UpdateFnR<Model>
= caseOf({
MorePlease: (event, model) =>
[model, [getRandomGif(model.topic)]],
FetchSucceed: (newUrl, model) =>
[{...model, gifUrl: newUrl}, []],
FetchFail: (event, model) =>
[model, []],
})
const HttpExample = createView('HttpExample', ({model}, {event}) => (
<div>
<h2>{model.topic}</h2>
<button onClick={event(Msg.MorePlease)}>More Please!</button>
<br />
<img src={model.gifUrl} />
</div>
))
const rootEl = document.getElementById('app')
const Program = createProgram({
init: init('cats'),
update,
view: HttpExample,
inputs: () => []
})
ReactDOM.render(<Program />, rootEl)
|
node_modules/react-router/es6/withRouter.js | jwhite4870/moreReactRedux | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import invariant from 'invariant';
import React from 'react';
import hoistStatics from 'hoist-non-react-statics';
import { routerShape } from './PropTypes';
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
export default function withRouter(WrappedComponent, options) {
var withRef = options && options.withRef;
var WithRouter = React.createClass({
displayName: 'WithRouter',
contextTypes: { router: routerShape },
propTypes: { router: routerShape },
getWrappedInstance: function getWrappedInstance() {
!withRef ? process.env.NODE_ENV !== 'production' ? invariant(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : invariant(false) : void 0;
return this.wrappedInstance;
},
render: function render() {
var _this = this;
var router = this.props.router || this.context.router;
var props = _extends({}, this.props, { router: router });
if (withRef) {
props.ref = function (c) {
_this.wrappedInstance = c;
};
}
return React.createElement(WrappedComponent, props);
}
});
WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')';
WithRouter.WrappedComponent = WrappedComponent;
return hoistStatics(WithRouter, WrappedComponent);
} |
packages/react-dom/src/test-utils/ReactTestUtils.js | apaatsio/react | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import {findCurrentFiberUsingSlowPath} from 'react-reconciler/reflection';
import * as ReactInstanceMap from 'shared/ReactInstanceMap';
import {
ClassComponent,
FunctionalComponent,
HostComponent,
HostText,
} from 'shared/ReactTypeOfWork';
import SyntheticEvent from 'events/SyntheticEvent';
import invariant from 'fbjs/lib/invariant';
import {topLevelTypes, mediaEventTypes} from '../events/BrowserEventConstants';
const {findDOMNode} = ReactDOM;
const {
EventPluginHub,
EventPluginRegistry,
EventPropagators,
ReactControlledComponent,
ReactDOMComponentTree,
ReactDOMEventListener,
} = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
function Event(suffix) {}
/**
* @class ReactTestUtils
*/
function findAllInRenderedFiberTreeInternal(fiber, test) {
if (!fiber) {
return [];
}
const currentParent = findCurrentFiberUsingSlowPath(fiber);
if (!currentParent) {
return [];
}
let node = currentParent;
let ret = [];
while (true) {
if (
node.tag === HostComponent ||
node.tag === HostText ||
node.tag === ClassComponent ||
node.tag === FunctionalComponent
) {
const publicInst = node.stateNode;
if (test(publicInst)) {
ret.push(publicInst);
}
}
if (node.child) {
node.child.return = node;
node = node.child;
continue;
}
if (node === currentParent) {
return ret;
}
while (!node.sibling) {
if (!node.return || node.return === currentParent) {
return ret;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
}
/**
* Utilities for making it easy to test React components.
*
* See https://reactjs.org/docs/test-utils.html
*
* Todo: Support the entire DOM.scry query syntax. For now, these simple
* utilities will suffice for testing purposes.
* @lends ReactTestUtils
*/
const ReactTestUtils = {
renderIntoDocument: function(element) {
const div = document.createElement('div');
// None of our tests actually require attaching the container to the
// DOM, and doing so creates a mess that we rely on test isolation to
// clean up, so we're going to stop honoring the name of this method
// (and probably rename it eventually) if no problems arise.
// document.documentElement.appendChild(div);
return ReactDOM.render(element, div);
},
isElement: function(element) {
return React.isValidElement(element);
},
isElementOfType: function(inst, convenienceConstructor) {
return React.isValidElement(inst) && inst.type === convenienceConstructor;
},
isDOMComponent: function(inst) {
return !!(inst && inst.nodeType === 1 && inst.tagName);
},
isDOMComponentElement: function(inst) {
return !!(inst && React.isValidElement(inst) && !!inst.tagName);
},
isCompositeComponent: function(inst) {
if (ReactTestUtils.isDOMComponent(inst)) {
// Accessing inst.setState warns; just return false as that'll be what
// this returns when we have DOM nodes as refs directly
return false;
}
return (
inst != null &&
typeof inst.render === 'function' &&
typeof inst.setState === 'function'
);
},
isCompositeComponentWithType: function(inst, type) {
if (!ReactTestUtils.isCompositeComponent(inst)) {
return false;
}
const internalInstance = ReactInstanceMap.get(inst);
const constructor = internalInstance.type;
return constructor === type;
},
findAllInRenderedTree: function(inst, test) {
if (!inst) {
return [];
}
invariant(
ReactTestUtils.isCompositeComponent(inst),
'findAllInRenderedTree(...): instance must be a composite component',
);
const internalInstance = ReactInstanceMap.get(inst);
return findAllInRenderedFiberTreeInternal(internalInstance, test);
},
/**
* Finds all instance of components in the rendered tree that are DOM
* components with the class name matching `className`.
* @return {array} an array of all the matches.
*/
scryRenderedDOMComponentsWithClass: function(root, classNames) {
return ReactTestUtils.findAllInRenderedTree(root, function(inst) {
if (ReactTestUtils.isDOMComponent(inst)) {
let className = inst.className;
if (typeof className !== 'string') {
// SVG, probably.
className = inst.getAttribute('class') || '';
}
const classList = className.split(/\s+/);
if (!Array.isArray(classNames)) {
invariant(
classNames !== undefined,
'TestUtils.scryRenderedDOMComponentsWithClass expects a ' +
'className as a second argument.',
);
classNames = classNames.split(/\s+/);
}
return classNames.every(function(name) {
return classList.indexOf(name) !== -1;
});
}
return false;
});
},
/**
* Like scryRenderedDOMComponentsWithClass but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
findRenderedDOMComponentWithClass: function(root, className) {
const all = ReactTestUtils.scryRenderedDOMComponentsWithClass(
root,
className,
);
if (all.length !== 1) {
throw new Error(
'Did not find exactly one match (found: ' +
all.length +
') ' +
'for class:' +
className,
);
}
return all[0];
},
/**
* Finds all instance of components in the rendered tree that are DOM
* components with the tag name matching `tagName`.
* @return {array} an array of all the matches.
*/
scryRenderedDOMComponentsWithTag: function(root, tagName) {
return ReactTestUtils.findAllInRenderedTree(root, function(inst) {
return (
ReactTestUtils.isDOMComponent(inst) &&
inst.tagName.toUpperCase() === tagName.toUpperCase()
);
});
},
/**
* Like scryRenderedDOMComponentsWithTag but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
findRenderedDOMComponentWithTag: function(root, tagName) {
const all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName);
if (all.length !== 1) {
throw new Error(
'Did not find exactly one match (found: ' +
all.length +
') ' +
'for tag:' +
tagName,
);
}
return all[0];
},
/**
* Finds all instances of components with type equal to `componentType`.
* @return {array} an array of all the matches.
*/
scryRenderedComponentsWithType: function(root, componentType) {
return ReactTestUtils.findAllInRenderedTree(root, function(inst) {
return ReactTestUtils.isCompositeComponentWithType(inst, componentType);
});
},
/**
* Same as `scryRenderedComponentsWithType` but expects there to be one result
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactComponent} The one match.
*/
findRenderedComponentWithType: function(root, componentType) {
const all = ReactTestUtils.scryRenderedComponentsWithType(
root,
componentType,
);
if (all.length !== 1) {
throw new Error(
'Did not find exactly one match (found: ' +
all.length +
') ' +
'for componentType:' +
componentType,
);
}
return all[0];
},
/**
* Pass a mocked component module to this method to augment it with
* useful methods that allow it to be used as a dummy React component.
* Instead of rendering as usual, the component will become a simple
* <div> containing any provided children.
*
* @param {object} module the mock function object exported from a
* module that defines the component to be mocked
* @param {?string} mockTagName optional dummy root tag name to return
* from render method (overrides
* module.mockTagName if provided)
* @return {object} the ReactTestUtils object (for chaining)
*/
mockComponent: function(module, mockTagName) {
mockTagName = mockTagName || module.mockTagName || 'div';
module.prototype.render.mockImplementation(function() {
return React.createElement(mockTagName, null, this.props.children);
});
return this;
},
/**
* Simulates a top level event being dispatched from a raw event that occurred
* on an `Element` node.
* @param {Object} topLevelType A type from `BrowserEventConstants.topLevelTypes`
* @param {!Element} node The dom to simulate an event occurring on.
* @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
*/
simulateNativeEventOnNode: function(topLevelType, node, fakeNativeEvent) {
fakeNativeEvent.target = node;
ReactDOMEventListener.dispatchEvent(topLevelType, fakeNativeEvent);
},
/**
* Simulates a top level event being dispatched from a raw event that occurred
* on the `ReactDOMComponent` `comp`.
* @param {Object} topLevelType A type from `BrowserEventConstants.topLevelTypes`.
* @param {!ReactDOMComponent} comp
* @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
*/
simulateNativeEventOnDOMComponent: function(
topLevelType,
comp,
fakeNativeEvent,
) {
ReactTestUtils.simulateNativeEventOnNode(
topLevelType,
findDOMNode(comp),
fakeNativeEvent,
);
},
nativeTouchData: function(x, y) {
return {
touches: [{pageX: x, pageY: y}],
};
},
Simulate: null,
SimulateNative: {},
};
/**
* Exports:
*
* - `ReactTestUtils.Simulate.click(Element)`
* - `ReactTestUtils.Simulate.mouseMove(Element)`
* - `ReactTestUtils.Simulate.change(Element)`
* - ... (All keys from event plugin `eventTypes` objects)
*/
function makeSimulator(eventType) {
return function(domNode, eventData) {
invariant(
!React.isValidElement(domNode),
'TestUtils.Simulate expected a DOM node as the first argument but received ' +
'a React element. Pass the DOM node you wish to simulate the event on instead. ' +
'Note that TestUtils.Simulate will not work if you are using shallow rendering.',
);
invariant(
!ReactTestUtils.isCompositeComponent(domNode),
'TestUtils.Simulate expected a DOM node as the first argument but received ' +
'a component instance. Pass the DOM node you wish to simulate the event on instead.',
);
const dispatchConfig =
EventPluginRegistry.eventNameDispatchConfigs[eventType];
const fakeNativeEvent = new Event();
fakeNativeEvent.target = domNode;
fakeNativeEvent.type = eventType.toLowerCase();
// We don't use SyntheticEvent.getPooled in order to not have to worry about
// properly destroying any properties assigned from `eventData` upon release
const targetInst = ReactDOMComponentTree.getInstanceFromNode(domNode);
const event = new SyntheticEvent(
dispatchConfig,
targetInst,
fakeNativeEvent,
domNode,
);
// Since we aren't using pooling, always persist the event. This will make
// sure it's marked and won't warn when setting additional properties.
event.persist();
Object.assign(event, eventData);
if (dispatchConfig.phasedRegistrationNames) {
EventPropagators.accumulateTwoPhaseDispatches(event);
} else {
EventPropagators.accumulateDirectDispatches(event);
}
ReactDOM.unstable_batchedUpdates(function() {
// Normally extractEvent enqueues a state restore, but we'll just always
// do that since we we're by-passing it here.
ReactControlledComponent.enqueueStateRestore(domNode);
EventPluginHub.runEventsInBatch(event, true);
});
};
}
function buildSimulators() {
ReactTestUtils.Simulate = {};
let eventType;
for (eventType in EventPluginRegistry.eventNameDispatchConfigs) {
/**
* @param {!Element|ReactDOMComponent} domComponentOrNode
* @param {?object} eventData Fake event data to use in SyntheticEvent.
*/
ReactTestUtils.Simulate[eventType] = makeSimulator(eventType);
}
}
// Rebuild ReactTestUtils.Simulate whenever event plugins are injected
const oldInjectEventPluginOrder =
EventPluginHub.injection.injectEventPluginOrder;
EventPluginHub.injection.injectEventPluginOrder = function() {
oldInjectEventPluginOrder.apply(this, arguments);
buildSimulators();
};
const oldInjectEventPlugins = EventPluginHub.injection.injectEventPluginsByName;
EventPluginHub.injection.injectEventPluginsByName = function() {
oldInjectEventPlugins.apply(this, arguments);
buildSimulators();
};
buildSimulators();
/**
* Exports:
*
* - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)`
* - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)`
* - ... (All keys from `BrowserEventConstants.topLevelTypes`)
*
* Note: Top level event types are a subset of the entire set of handler types
* (which include a broader set of "synthetic" events). For example, onDragDone
* is a synthetic event. Except when testing an event plugin or React's event
* handling code specifically, you probably want to use ReactTestUtils.Simulate
* to dispatch synthetic events.
*/
function makeNativeSimulator(eventType) {
return function(domComponentOrNode, nativeEventData) {
const fakeNativeEvent = new Event(eventType);
Object.assign(fakeNativeEvent, nativeEventData);
if (ReactTestUtils.isDOMComponent(domComponentOrNode)) {
ReactTestUtils.simulateNativeEventOnDOMComponent(
eventType,
domComponentOrNode,
fakeNativeEvent,
);
} else if (domComponentOrNode.tagName) {
// Will allow on actual dom nodes.
ReactTestUtils.simulateNativeEventOnNode(
eventType,
domComponentOrNode,
fakeNativeEvent,
);
}
};
}
const eventKeys = [].concat(
Object.keys(topLevelTypes),
Object.keys(mediaEventTypes),
);
eventKeys.forEach(function(eventType) {
// Event type is stored as 'topClick' - we transform that to 'click'
const convenienceName =
eventType.indexOf('top') === 0
? eventType.charAt(3).toLowerCase() + eventType.substr(4)
: eventType;
/**
* @param {!Element|ReactDOMComponent} domComponentOrNode
* @param {?Event} nativeEventData Fake native event to use in SyntheticEvent.
*/
ReactTestUtils.SimulateNative[convenienceName] = makeNativeSimulator(
eventType,
);
});
export default ReactTestUtils;
|
js/jqwidgets/demos/react/app/combobox/defaultfunctionality/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxComboBox from '../../../jqwidgets-react/react_jqxcombobox.js';
class App extends React.Component {
render() {
let source = new Array();
for (let i = 0; i < 10; i++) {
let movie = 'avatar.png';
let title = 'Avatar';
let year = 2009;
switch (i) {
case 1:
movie = 'endgame.png';
title = 'End Game';
year = 2006;
break;
case 2:
movie = 'priest.png';
title = 'Priest';
year = 2011;
break;
case 3:
movie = 'unknown.png';
title = 'Unknown';
year = 2011;
break;
case 4:
movie = 'unstoppable.png';
title = 'Unstoppable';
year = 2010;
break;
case 5:
movie = 'twilight.png';
title = 'Twilight';
year = 2008;
break;
case 6:
movie = 'kungfupanda.png';
title = 'Kung Fu Panda';
year = 2008;
break;
case 7:
movie = 'knockout.png';
title = 'Knockout';
year = 2011
break;
case 8:
movie = 'theplane.png';
title = 'The Plane';
year = 2010;
break;
case 9:
movie = 'bigdaddy.png';
title = 'Big Daddy';
year = 1999;
break;
}
let html = '<div style="padding: 0px; margin: 0px; height: 95px; float: left;">' +
'<img width="60" style="float: left; margin-top: 4px; margin-right: 15px;"' +
'src=../../../images/' + movie + '><div style="margin-top: 10px; font-size: 13px;">' +
'<b>Title</b><div>' + title + '</div><div style="margin-top: 10px;"><b>Year</b><div>' + year.toString() + '</div></div></div>';
source[i] = { html: html, title: title };
}
return (
<JqxComboBox width={250} height={25} source={source} selectedIndex={0} />
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/components/machine-profiles.js | DarklyLabs/LaserWeb4 | import React from 'react';
import { dispatch, connect } from 'react-redux';
import {FormGroup, FormControl, ControlLabel, Button, InputGroup, Glyphicon, ButtonGroup, ButtonToolbar} from 'react-bootstrap'
import { addMachineProfile, delMachineProfileId } from '../actions/settings';
import stringify from 'json-stringify-pretty-compact';
import slug from 'slug'
import Icon from './font-awesome';
import { alert, prompt, confirm} from './laserweb';
class MachineProfile extends React.Component {
constructor(props)
{
super(props);
this.handleApply.bind(this);
this.handleSelect.bind(this);
this.handleInput.bind(this);
this.handleSave.bind(this);
let selected = this.props.settings.__selectedProfile || "";
this.state={selected: selected , newLabel: '', newSlug:''}
}
handleApply(e) {
let selected=this._getSelectedProfile()
let profileId = this.state.selected
if (selected) {
confirm("Are you sure? Current settings will be overwritten.",(b)=>{
if (b) this.props.onApply({...selected.settings , __selectedProfile: profileId });
})
}
return ;
}
handleSelect(e){
let value=e.target.value
if (value) this.setState({selected: value});
}
handleDelete(e){
this.props.dispatch(delMachineProfileId(this.state.selected));
this.setState({selected: '', newLabel:'', newSlug:''})
}
handleSave(e) {
let currentProfile = this._getSelectedProfile();
if (currentProfile) this.props.dispatch(addMachineProfile(this.state.selected, {...currentProfile, settings: this.props.settings}))
}
handleAppend(e){
this.props.dispatch(addMachineProfile(this.state.newSlug, {machineLabel: this.state.newLabel, settings: this.props.settings}))
this.setState({selected: this.state.newSlug})
}
handleInput(e){
this.setState({newLabel: e.target.value, newSlug: slug(e.target.value)})
}
_getSelectedProfile()
{
if(typeof this.props.profiles[this.state.selected]!=="undefined")
return this.props.profiles[this.state.selected];
return undefined;
}
render(){
let profileOptions=[];
let description;
let selected;
const disabledApply = !this.state.selected.length
const disabledDelete= disabledApply || (this.props.profiles[this.state.selected] && this.props.profiles[this.state.selected]._locked)
Object.keys(this.props.profiles).forEach((key) => {
let profile=this.props.profiles[key];
profileOptions.push(<option key={key} value={key} >{profile.machineLabel}</option>);
});
if (selected=this._getSelectedProfile()){
let settings=stringify(this.props.profiles[this.state.selected].settings);
let machinedesc=this.props.profiles[this.state.selected].machineDescription;
description=(<details><summary>{machinedesc? machinedesc : "Details" }</summary><pre>{settings}</pre></details>);
}
return (
<div>
<FormGroup controlId="formControlsSelect">
<h5>Apply predefined machine profile</h5>
{this.state.selected ? (<small>Machine Id: <code>{this.state.selected}</code></small>):undefined}
<FormControl componentClass="select" onChange={(e)=>{this.handleSelect(e)}} value={this.state.selected} ref="select" className="full-width">
<option value="">Select a Machine Profile</option>
{profileOptions}
</FormControl>
<ButtonGroup>
<Button bsClass="btn btn-xs btn-info" onClick={(e)=>{this.handleApply(e)}} disabled={disabledApply} title="Applies selected profile"><Icon name="share" /> Apply</Button>
<Button bsClass="btn btn-xs btn-warning" onClick={(e)=>{this.handleSave(e)}} title="Updates selected profile with current configuration" disabled={disabledDelete}><Icon name="pencil" /> Update</Button>
<Button bsClass="btn btn-xs btn-danger" onClick={(e)=>{this.handleDelete(e)}} title="Delete selected profile" disabled={disabledDelete}><Glyphicon glyph="trash" /> Delete</Button>
</ButtonGroup>
<small className="help-block">Use this dialog to apply predefined machine settings. This settings will override current settings. Use with caution.</small>
{description}
</FormGroup>
<FormGroup controlId="formControlsAppend">
<h5>New profile</h5>
{this.state.newSlug ? (<small>Machine Id: <code>{this.state.newSlug}</code></small>):undefined}
<InputGroup>
<FormControl type="text" onChange={(e)=>{this.handleInput(e)}} ref="newLabel" value={this.state.newLabel}/>
<InputGroup.Button>
<Button bsClass="btn btn-success" onClick={(e)=>{this.handleAppend(e)}}><Glyphicon glyph="plus-sign" /></Button>
</InputGroup.Button>
</InputGroup>
<small className="help-block">Use this dialog to add the current settings to a new profile.</small>
</FormGroup>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
profiles: state.machineProfiles,
settings: state.settings
}
};
export {MachineProfile}
export default connect(mapStateToProps)(MachineProfile); |
addons/graphql/src/components/FullScreen/index.js | jribeiro/storybook | import React from 'react';
import PropTypes from 'prop-types';
import style from './style';
export default function FullScreen(props) {
return (
<div style={style.wrapper}>
{props.children}
</div>
);
}
FullScreen.defaultProps = { children: null };
FullScreen.propTypes = { children: PropTypes.node };
|
newclient/scripts/components/user/entities/entities/index.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import styles from './style';
import classNames from 'classnames';
import React from 'react';
import {NewEntityButton} from '../new-entity-button';
import {FEPlaceHolder} from '../../../dynamic-icons/fe-place-holder';
import {Entity} from '../entity';
import {EntityForm} from '../entity-form';
import {DisclosureActions} from '../../../../actions/disclosure-actions';
import { DisclosureStore } from '../../../../stores/disclosure-store';
import {Instructions} from '../../instructions';
import {INSTRUCTION_STEP} from '../../../../../../coi-constants';
import {Toggle} from '../../toggle';
import {BlueButton} from '../../../blue-button';
import AddSection from '../../../add-section';
export class Entities extends React.Component {
shouldComponentUpdate() { return true; }
viewChanged(newView) {
DisclosureActions.changeActiveEntityView(newView);
}
render() {
const {config} = this.context.configState;
let viewToggle;
let entities;
if (this.props.entities) {
entities = this.props.entities.filter(entity => {
return entity.active === this.props.applicationState.activeEntityView;
}).map(
(entity) => {
const entityAppState = this.props.applicationState.entityStates[entity.id];
return (
<Entity
entity={entity}
step={entityAppState ? entityAppState.formStep : -1}
id={entity.id}
editing={entityAppState ? entityAppState.editing : false}
snapshot={entityAppState ? entityAppState.snapshot : undefined}
key={entity.id}
appState={this.props.applicationState}
/>
);
}
);
if (this.props.applicationState.newEntityFormStep < 0 && this.props.entities.length > 0) {
viewToggle = (
<Toggle
values={[
{code: 1, description: 'ACTIVE'},
{code: 0, description: 'INACTIVE'}
]}
selected={this.props.applicationState.activeEntityView}
onChange={this.viewChanged}
className={`${styles.override} ${styles.viewToggle}`}
/>
);
}
}
let newEntitySection;
let entityForm;
let placeholder;
if (this.props.applicationState.newEntityFormStep < 0) {
const newEntityButton = (
<NewEntityButton
onClick={DisclosureActions.newEntityInitiated}
className={`${styles.override} ${styles.newentitybutton}`}
/>
);
let message;
let level;
if (this.props.enforceEntities) {
message = 'You have answered "Yes" to a screening question, but do not have an active Financial Entity. Please add an active Financial Entity or edit your screening questionnaire in order to submit your disclosure.'; //eslint-disable-line max-len
} else if (DisclosureStore.warnActiveEntity(this.props.applicationState.currentDisclosureState.disclosure, config)) {
message = 'You have answered "No" to all screening questions; however, you have an active financial entity. Please consider reviewing the questions or deactivating your Financial Entity.'; //eslint-disable-line max-len
level = 'Warning';
}
newEntitySection = (
<AddSection
level={level}
button={newEntityButton}
message={message}
/>
);
const nextStep = this.props.enforceEntities ? '' : DisclosureActions.nextStep;
const nextButtonClasses =
classNames(styles.noEntitiesButton,
{[styles.disabled]: this.props.enforceEntities});
if (entities.length === 0) {
let text;
if (this.props.applicationState.activeEntityView) {
text = (
<div>
<div>You currently have no active financial entities.</div>
<div>Add new financial entities to view them here.</div>
<div style={{marginTop: 20}}>
<BlueButton className={nextButtonClasses} onClick={nextStep}>
I have no entities to disclose
</BlueButton>
</div>
</div>
);
}
else {
text = (
<div>
<div>You currently have no inactive financial entities.</div>
</div>
);
}
placeholder = (
<div style={{textAlign: 'center'}}>
<FEPlaceHolder className={`${styles.override} ${styles.placeholder}`} />
{text}
</div>
);
}
}
else {
entityForm = (
<EntityForm
step={this.props.applicationState.newEntityFormStep}
className={`${styles.override} ${styles.newentityform}`}
entity={this.props.inProgress}
editing={true}
appState={this.props.applicationState}
/>
);
}
const instructionText = config.general.instructions[INSTRUCTION_STEP.FINANCIAL_ENTITIES];
const contentState = config.general.richTextInstructions ?
config.general.richTextInstructions[INSTRUCTION_STEP.FINANCIAL_ENTITIES] :
undefined;
const instructions = (
<Instructions
text={instructionText}
collapsed={!this.props.instructionsShowing[INSTRUCTION_STEP.FINANCIAL_ENTITIES]}
contentState={contentState}
/>
);
return (
<div className={`${styles.container} ${this.props.className}`}>
{instructions}
<div className={styles.content}>
<div>
<div>
{newEntitySection}
{viewToggle}
</div>
{entityForm}
</div>
{entities}
{placeholder}
</div>
</div>
);
}
}
Entities.contextTypes = {
configState: React.PropTypes.object
};
|
src/components/TableContainer.js | GriddleGriddle/Griddle | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from '../utils/griddleConnect';
import compose from 'recompose/compose';
import mapProps from 'recompose/mapProps';
import getContext from 'recompose/getContext';
import { classNamesForComponentSelector, stylesForComponentSelector, dataLoadingSelector, visibleRowCountSelector } from '../selectors/dataSelectors';
const ComposedContainerComponent = OriginalComponent => compose(
getContext(
{
components: PropTypes.object
}),
//TODO: Should we use withHandlers here instead? I realize that's not 100% the intent of that method
mapProps(props => ({
TableHeading: props.components.TableHeading,
TableBody: props.components.TableBody,
Loading: props.components.Loading,
NoResults: props.components.NoResults,
})),
connect(
(state, props) => ({
dataLoading: dataLoadingSelector(state),
visibleRows: visibleRowCountSelector(state),
className: classNamesForComponentSelector(state, 'Table'),
style: stylesForComponentSelector(state, 'Table'),
})
),
)(props => <OriginalComponent {...props} />);
export default ComposedContainerComponent;
|
web/portal/src/components/Popup/ReImportL10n/index.js | trendmicro/serverless-survey-forms |
// CSS
import styles from './style.css';
import React from 'react';
import PureComponent from 'react-pure-render/component';
import Mixins from '../../../mixins/global';
import Button from '../../Button';
class ReImportL10n extends PureComponent {
constructor(props) {
super(props);
this._btnClickEvent = this._btnClickEvent.bind(this);
}
componentDidMount() {
Mixins.fixScrollbar();
}
componentWillUnmount() {
Mixins.freeScrollbar();
}
render() {
const { selectedL10n, surveyL10n } = this.props;
const originJson = surveyL10n[selectedL10n];
const orderedJson = {};
if (originJson) {
Object.keys(originJson).sort().forEach((key) => {
orderedJson[key] = originJson[key];
});
}
return (
<div className={`${styles.popup} popup`}>
<div className="popup_wrap">
<div className={`${styles.wrap} wrap`}>
<button
type="button"
onClick={this._btnClickEvent}
className="close"
data-type="cancel"
>×
</button>
<div className={`${styles.content} content`}>
<div className={styles.title}>Import</div>
<div className={styles.title}>
{`You are going to save ${selectedL10n} language.`}
</div>
<div className={styles.title}>
Please paste this language’s json.
</div>
<div>
<textarea
id="l10n"
className="textarea"
defaultValue={JSON.stringify(orderedJson, undefined, 4)}
rows="5"
></textarea>
<div id="l10nMsg" className="input__msg"></div>
</div>
<div className={`bottom ${styles.bottom}`}>
<Button
string="Save"
i18nKey={false}
color="ruby"
onClick={this._btnClickEvent}
extraProps={{ 'data-type': 'save' }}
/>
<Button
string="Cancel"
i18nKey={false}
onClick={this._btnClickEvent}
extraProps={{ 'data-type': 'cancel' }}
/>
</div>
</div>
</div>
</div>
</div>
);
}
_btnClickEvent(e) {
const { lang, selectedL10n, surveyL10n, popupActions, questionsActions } = this.props;
const type = e.currentTarget.getAttribute('data-type');
if (type === 'save') {
let l10n = document.getElementById('l10n').value;
const msg = document.getElementById('l10nMsg');
// check l10n json
if (l10n === '') {
msg.innerHTML = 'Please paste this language\'s json.';
} else {
try {
l10n = JSON.parse(l10n);
if (typeof l10n === 'object'
&& l10n instanceof Object
&& !(l10n instanceof Array)
&& !l10n.length) {
// check whether all l10n keys exist
const basicCompared = Object.keys(surveyL10n[lang]).sort();
const l10nCompared = Object.keys(l10n).sort();
const isEqual = basicCompared.length === l10nCompared.length
&& basicCompared.every((ele, idx) => ele === l10nCompared[idx]);
if (!isEqual) {
msg.innerHTML = 'There are some keys can\'t correspond'
+ ' to the default language.';
} else {
msg.innerHTML = '';
questionsActions.importL10n({ [selectedL10n]: l10n });
}
} else {
msg.innerHTML = 'Incorrect json format.';
}
} catch (err) {
msg.innerHTML = 'Incorrect json format.';
}
}
} else {
popupActions.closePopup();
}
}
}
export default ReImportL10n;
|
pnpm-cached/.pnpm-store/1/registry.npmjs.org/react-bootstrap/0.31.0/es/utils/ValidComponentChildren.js | Akkuma/npm-cache-benchmark | // TODO: This module should be ElementChildren, and should use named exports.
import React from 'react';
/**
* Iterates through children that are typically specified as `props.children`,
* but only maps over children that are "valid components".
*
* The mapFunction provided index will be normalised to the components mapped,
* so an invalid component would not increase the index.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for func.
* @return {object} Object containing the ordered map of results.
*/
function map(children, func, context) {
var index = 0;
return React.Children.map(children, function (child) {
if (!React.isValidElement(child)) {
return child;
}
return func.call(context, child, index++);
});
}
/**
* Iterates through children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for context.
*/
function forEach(children, func, context) {
var index = 0;
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
func.call(context, child, index++);
});
}
/**
* Count the number of "valid components" in the Children container.
*
* @param {?*} children Children tree container.
* @returns {number}
*/
function count(children) {
var result = 0;
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
++result;
});
return result;
}
/**
* Finds children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func.
* @param {*} context Context for func.
* @returns {array} of children that meet the func return statement
*/
function filter(children, func, context) {
var index = 0;
var result = [];
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result.push(child);
}
});
return result;
}
function find(children, func, context) {
var index = 0;
var result = undefined;
React.Children.forEach(children, function (child) {
if (result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result = child;
}
});
return result;
}
function every(children, func, context) {
var index = 0;
var result = true;
React.Children.forEach(children, function (child) {
if (!result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (!func.call(context, child, index++)) {
result = false;
}
});
return result;
}
function some(children, func, context) {
var index = 0;
var result = false;
React.Children.forEach(children, function (child) {
if (result) {
return;
}
if (!React.isValidElement(child)) {
return;
}
if (func.call(context, child, index++)) {
result = true;
}
});
return result;
}
function toArray(children) {
var result = [];
React.Children.forEach(children, function (child) {
if (!React.isValidElement(child)) {
return;
}
result.push(child);
});
return result;
}
export default {
map: map,
forEach: forEach,
count: count,
find: find,
filter: filter,
every: every,
some: some,
toArray: toArray
}; |
src/SheetViewer.js | Walther/jazzy | import React from 'react';
class SheetViewer extends React.Component {
writeScale = scale =>
scale
.simple()
.map(name => (name = name[0].toUpperCase() + name.slice(1)))
.join(', ');
writeChords = chords => {
return chords.map(chord => (
<span className="chord">
{chord.root.name().toUpperCase()}
{chord.root.accidental()}
<sup>{chord.symbol}</sup>
</span>
));
};
render() {
const sheet = this.props.sheet;
return (
<div id="sheet">
<div id="info">
<p>Key: {sheet.key}</p>
<p>Scale: {this.writeScale(sheet.scale)}</p>
</div>
<div id="chords">{this.writeChords(sheet.chords)}</div>
</div>
);
}
}
export default SheetViewer;
|
app/shared/wrapped-text/WrappedText.js | fastmonkeys/respa-ui | import PropTypes from 'prop-types';
import React from 'react';
import Linkify from 'react-linkify';
function renderParagraph(text, index, openLinksInNewTab) {
const properties = openLinksInNewTab
? {
rel: 'noopener noreferrer',
target: '_blank',
}
: {};
return (
<div key={index}>
<Linkify properties={properties}>{text}</Linkify>
</div>
);
}
function WrappedText({ text, openLinksInNewTab = false }) {
if (!text) {
return <div />;
}
return (
<div className="wrapped-text">
{text
.split('\n')
.map((paragraph, index) => renderParagraph(paragraph, index, openLinksInNewTab))}
</div>
);
}
WrappedText.propTypes = {
text: PropTypes.string,
openLinksInNewTab: PropTypes.bool,
};
export default WrappedText;
|
packages/ringcentral-widgets/components/Draggable/index.js | u9520107/ringcentral-js-widget | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import styles from './styles.scss';
/* eslint { "react/no-unused-state": 0 } */
class Draggable extends Component {
constructor(props) {
super(props);
this.state = {
dragging: false,
positionX: 0,
positionY: 0,
translateX: props.positionOffsetX,
translateY: props.positionOffsetY,
};
this._isClick = true;
this._onMouseDown = (e) => {
if (e.button !== 0) return;
if (this.state.dragging) {
return;
}
this.setState({
positionX: e.clientX,
positionY: e.clientY,
dragging: true,
});
this._positionXOnMouseDown = e.clientX;
this._positionYOnMouseDown = e.clientY;
this._isClick = true;
window.addEventListener('mousemove', this._onMouseMove, false);
window.addEventListener('mouseup', this._onMouseUp, false);
e.stopPropagation();
e.preventDefault();
};
this._onMouseMove = (e) => {
if (!this.state.dragging) {
return;
}
if (!this.draggableDom) {
return;
}
const {
offsetParent,
offsetLeft: originalPositionX,
offsetTop: originalPositionY,
} = this.draggableDom;
const newPositionX = e.clientX;
const newPositionY = e.clientY;
const child = this.draggableDom.firstChild;
const height = (child && child.clientHeight) || 0;
const width = (child && child.clientWidth) || 0;
if (
Math.abs(newPositionX - this._positionXOnMouseDown) > this.props.clickThreshold ||
Math.abs(newPositionY - this._positionYOnMouseDown) > this.props.clickThreshold
) {
this._isClick = false;
}
this.setState((preState) => {
const newState = {
positionX: newPositionX,
positionY: newPositionY,
translateX: preState.translateX + (newPositionX - preState.positionX),
translateY: preState.translateY + (newPositionY - preState.positionY),
};
if (
(originalPositionX - 10) + newState.translateX > offsetParent.clientWidth ||
(originalPositionX - 10) + newState.translateX < width
) {
delete newState.translateX;
}
if (
(originalPositionY + 10) + newState.translateY > offsetParent.clientHeight - height ||
(originalPositionY + 10) + newState.translateY < 0
) {
delete newState.translateY;
}
return newState;
});
e.stopPropagation();
e.preventDefault();
};
this._onMouseUp = (e) => {
this.setState({
dragging: false,
});
this.props.updatePositionOffset(this.state.translateX, this.state.translateY);
window.removeEventListener('mousemove', this._onMouseMove);
window.removeEventListener('mouseup', this._onMouseUp);
e.stopPropagation();
e.preventDefault();
};
this._onClick = (e) => {
if (!this._isClick) {
return;
}
this.props.onClick(e);
};
}
componentWillUnmount() {
window.removeEventListener('mousemove', this._onMouseMove);
window.removeEventListener('mouseup', this._onMouseUp);
}
render() {
const {
className,
children,
} = this.props;
const style = {
msTransition: `translate(${this.state.translateX}px, ${this.state.translateY}px)`,
WebkitTransition: `translate(${this.state.translateX}px, ${this.state.translateY}px)`,
transform: `translate(${this.state.translateX}px, ${this.state.translateY}px)`,
};
return (
<div
onMouseDown={this._onMouseDown}
ref={(draggableDom) => { this.draggableDom = draggableDom; }}
style={style}
className={classnames(styles.root, className)}
onClick={this._onClick}
>
{children}
</div>
);
}
}
Draggable.propTypes = {
className: PropTypes.string,
children: PropTypes.node.isRequired,
onClick: PropTypes.func,
positionOffsetX: PropTypes.number,
positionOffsetY: PropTypes.number,
updatePositionOffset: PropTypes.func,
clickThreshold: PropTypes.number,
};
Draggable.defaultProps = {
className: null,
onClick: () => null,
positionOffsetX: 0,
positionOffsetY: 0,
updatePositionOffset: () => null,
clickThreshold: 5,
};
export default Draggable;
|
pootle/static/js/admin/components/Project/ProjectController.js | r-o-b-b-i-e/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
import Search from '../Search';
import ProjectAdd from './ProjectAdd';
import ProjectEdit from './ProjectEdit';
const ProjectController = React.createClass({
propTypes: {
items: React.PropTypes.object.isRequired,
model: React.PropTypes.func.isRequired,
onAdd: React.PropTypes.func.isRequired,
onCancel: React.PropTypes.func.isRequired,
onDelete: React.PropTypes.func.isRequired,
onSearch: React.PropTypes.func.isRequired,
onSelectItem: React.PropTypes.func.isRequired,
onSuccess: React.PropTypes.func.isRequired,
searchQuery: React.PropTypes.string.isRequired,
selectedItem: React.PropTypes.object,
view: React.PropTypes.string.isRequired,
},
render() {
const viewsMap = {
add: (
<ProjectAdd
model={this.props.model}
collection={this.props.items}
onSuccess={this.props.onSuccess}
onCancel={this.props.onCancel}
/>
),
edit: (
<ProjectEdit
model={this.props.selectedItem}
collection={this.props.items}
onAdd={this.props.onAdd}
onSuccess={this.props.onSuccess}
onDelete={this.props.onDelete}
/>
),
};
const args = {
count: this.props.items.count,
};
let msg;
if (this.props.searchQuery) {
msg = ngettext('%(count)s project matches your query.',
'%(count)s projects match your query.', args.count);
} else {
msg = ngettext(
'There is %(count)s project.',
'There are %(count)s projects. Below are the most recently added ones.',
args.count
);
}
const resultsCaption = interpolate(msg, args, true);
return (
<div className="admin-app-projects">
<div className="module first">
<Search
fields={['index', 'code', 'fullname', 'disabled']}
onSearch={this.props.onSearch}
onSelectItem={this.props.onSelectItem}
items={this.props.items}
selectedItem={this.props.selectedItem}
searchLabel={gettext('Search Projects')}
searchPlaceholder={gettext('Find project by name, code')}
resultsCaption={resultsCaption}
searchQuery={this.props.searchQuery}
/>
</div>
<div className="module admin-content">
{viewsMap[this.props.view]}
</div>
</div>
);
},
});
export default ProjectController;
|
src/docs/Props.js | wsherman67/UBA | import React from 'react';
import PropTypes from 'prop-types';
const Props = ({props}) => {
return (
<table className="props">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Type</th>
<th>Default</th>
<th>Required</th>
</tr>
</thead>
<tbody>
{
Object.keys(props).map(key => {
return (
<tr key={key}>
<td>{key}</td>
<td>{props[key].description}</td>
<td>{props[key].type.name}</td>
<td>{props[key].defaultValue && props[key].defaultValue.value}</td>
<td>{props[key].required && "X"}</td>
</tr>
);
})
}
</tbody>
</table>
)
}
Props.propTypes = {
props: PropTypes.object.isRequired
};
export default Props;
|
src/app.js | jordilondoner/todos | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import configureStore from './redux/store';
import Header from './components/Header';
import ItemCreator from './components/ItemCreator';
import ItemsList from './components/ItemsList';
import './app.css';
const store = configureStore();
class App extends Component {
render() {
return (
<Provider store={store}>
<div className="app">
<Header />
<div>
<ItemCreator />
<ItemsList />
</div>
</div>
</Provider>
);
}
}
export default App;
|
src/index.js | fullstackreact/google-maps-react | import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import {camelize} from './lib/String';
import {makeCancelable} from './lib/cancelablePromise';
const mapStyles = {
container: {
position: 'absolute',
width: '100%',
height: '100%'
},
map: {
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
top: 0
}
};
const evtNames = [
'ready',
'click',
'dragend',
'recenter',
'bounds_changed',
'center_changed',
'dblclick',
'dragstart',
'heading_change',
'idle',
'maptypeid_changed',
'mousemove',
'mouseout',
'mouseover',
'projection_changed',
'resize',
'rightclick',
'tilesloaded',
'tilt_changed',
'zoom_changed'
];
export {wrapper as GoogleApiWrapper} from './GoogleApiComponent';
export {Marker} from './components/Marker';
export {InfoWindow} from './components/InfoWindow';
export {HeatMap} from './components/HeatMap';
export {Polygon} from './components/Polygon';
export {Polyline} from './components/Polyline';
export {Circle} from './components/Circle';
export {Rectangle} from './components/Rectangle';
export class Map extends React.Component {
constructor(props) {
super(props);
if (!props.hasOwnProperty('google')) {
throw new Error('You must include a `google` prop');
}
this.listeners = {};
this.state = {
currentLocation: {
lat: this.props.initialCenter.lat,
lng: this.props.initialCenter.lng
}
};
this.mapRef=React.createRef();
}
componentDidMount() {
if (this.props.centerAroundCurrentLocation) {
if (navigator && navigator.geolocation) {
this.geoPromise = makeCancelable(
new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
})
);
this.geoPromise.promise
.then(pos => {
const coords = pos.coords;
this.setState({
currentLocation: {
lat: coords.latitude,
lng: coords.longitude
}
});
})
.catch(e => e);
}
}
this.loadMap();
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.google !== this.props.google) {
this.loadMap();
}
if (this.props.visible !== prevProps.visible) {
this.restyleMap();
}
if (this.props.zoom !== prevProps.zoom) {
this.map.setZoom(this.props.zoom);
}
if (this.props.center !== prevProps.center) {
this.setState({
currentLocation: this.props.center
});
}
if (prevState.currentLocation !== this.state.currentLocation) {
this.recenterMap();
}
if (this.props.bounds && this.props.bounds !== prevProps.bounds) {
this.map.fitBounds(this.props.bounds);
}
}
componentWillUnmount() {
const {google} = this.props;
if (this.geoPromise) {
this.geoPromise.cancel();
}
Object.keys(this.listeners).forEach(e => {
google.maps.event.removeListener(this.listeners[e]);
});
}
loadMap() {
if (this.props && this.props.google) {
const {google} = this.props;
const maps = google.maps;
const mapRef = this.mapRef.current;
const node = ReactDOM.findDOMNode(mapRef);
const curr = this.state.currentLocation;
const center = new maps.LatLng(curr.lat, curr.lng);
const mapTypeIds = this.props.google.maps.MapTypeId || {};
const mapTypeFromProps = String(this.props.mapType).toUpperCase();
const mapConfig = Object.assign(
{},
{
mapTypeId: mapTypeIds[mapTypeFromProps],
center: center,
zoom: this.props.zoom,
maxZoom: this.props.maxZoom,
minZoom: this.props.minZoom,
clickableIcons: !!this.props.clickableIcons,
disableDefaultUI: this.props.disableDefaultUI,
zoomControl: this.props.zoomControl,
zoomControlOptions: this.props.zoomControlOptions,
mapTypeControl: this.props.mapTypeControl,
mapTypeControlOptions: this.props.mapTypeControlOptions,
scaleControl: this.props.scaleControl,
streetViewControl: this.props.streetViewControl,
streetViewControlOptions: this.props.streetViewControlOptions,
panControl: this.props.panControl,
rotateControl: this.props.rotateControl,
fullscreenControl: this.props.fullscreenControl,
scrollwheel: this.props.scrollwheel,
draggable: this.props.draggable,
draggableCursor: this.props.draggableCursor,
keyboardShortcuts: this.props.keyboardShortcuts,
disableDoubleClickZoom: this.props.disableDoubleClickZoom,
noClear: this.props.noClear,
styles: this.props.styles,
gestureHandling: this.props.gestureHandling
}
);
Object.keys(mapConfig).forEach(key => {
// Allow to configure mapConfig with 'false'
if (mapConfig[key] === null) {
delete mapConfig[key];
}
});
this.map = new maps.Map(node, mapConfig);
evtNames.forEach(e => {
this.listeners[e] = this.map.addListener(e, this.handleEvent(e));
});
maps.event.trigger(this.map, 'ready');
this.forceUpdate();
}
}
handleEvent(evtName) {
let timeout;
const handlerName = `on${camelize(evtName)}`;
return e => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(() => {
if (this.props[handlerName]) {
this.props[handlerName](this.props, this.map, e);
}
}, 0);
};
}
recenterMap() {
const map = this.map;
const {google} = this.props;
if (!google) return;
const maps = google.maps;
if (map) {
let center = this.state.currentLocation;
if (!(center instanceof google.maps.LatLng)) {
center = new google.maps.LatLng(center.lat, center.lng);
}
// map.panTo(center)
map.setCenter(center);
maps.event.trigger(map, 'recenter');
}
}
restyleMap() {
if (this.map) {
const {google} = this.props;
google.maps.event.trigger(this.map, 'resize');
}
}
renderChildren() {
const {children} = this.props;
if (!children) return;
return React.Children.map(children, c => {
if (!c) return;
return React.cloneElement(c, {
map: this.map,
google: this.props.google,
mapCenter: this.state.currentLocation
});
});
}
render() {
const style = Object.assign({}, mapStyles.map, this.props.style, {
display: this.props.visible ? 'inherit' : 'none'
});
const containerStyles = Object.assign(
{},
mapStyles.container,
this.props.containerStyle
);
return (
<div style={containerStyles} className={this.props.className}>
<div style={style} ref={this.mapRef}>
Loading map...
</div>
{this.renderChildren()}
</div>
);
}
}
Map.propTypes = {
google: PropTypes.object,
zoom: PropTypes.number,
centerAroundCurrentLocation: PropTypes.bool,
center: PropTypes.object,
initialCenter: PropTypes.object,
className: PropTypes.string,
style: PropTypes.object,
containerStyle: PropTypes.object,
visible: PropTypes.bool,
mapType: PropTypes.string,
maxZoom: PropTypes.number,
minZoom: PropTypes.number,
clickableIcons: PropTypes.bool,
disableDefaultUI: PropTypes.bool,
zoomControl: PropTypes.bool,
zoomControlOptions: PropTypes.object,
mapTypeControl: PropTypes.bool,
mapTypeControlOptions: PropTypes.bool,
scaleControl: PropTypes.bool,
streetViewControl: PropTypes.bool,
streetViewControlOptions: PropTypes.object,
panControl: PropTypes.bool,
rotateControl: PropTypes.bool,
fullscreenControl: PropTypes.bool,
scrollwheel: PropTypes.bool,
draggable: PropTypes.bool,
draggableCursor: PropTypes.string,
keyboardShortcuts: PropTypes.bool,
disableDoubleClickZoom: PropTypes.bool,
noClear: PropTypes.bool,
styles: PropTypes.array,
gestureHandling: PropTypes.string,
bounds: PropTypes.object
};
evtNames.forEach(e => (Map.propTypes[camelize(e)] = PropTypes.func));
Map.defaultProps = {
zoom: 14,
initialCenter: {
lat: 37.774929,
lng: -122.419416
},
center: {},
centerAroundCurrentLocation: false,
style: {},
containerStyle: {},
visible: true
};
export default Map;
|
src/modules/widget/Filter.js | lenxeon/react | 'use strict'
import React from 'react'
import classnames from 'classnames'
//import { forEach } from '../utils/objects'
import Button from './Button'
import FilterItem from './FilterItem'
import clickAway from './higherorder/clickaway'
import { requireCss } from './themes'
requireCss('filter')
import {getLang, setLang} from './lang'
setLang('buttons')
@clickAway
export default class Filter extends React.Component {
static displayName = 'Filter'
static propTypes = {
className: React.PropTypes.string,
local: React.PropTypes.bool,
onFilter: React.PropTypes.func,
onSearch: React.PropTypes.func,
options: React.PropTypes.array,
style: React.PropTypes.object,
type: React.PropTypes.string
}
static defaultProps = {
options: []
}
componentWillMount () {
this.initData(this.props.options)
}
componentClickAway () {
this.close()
}
state = {
active: false,
filters: []
}
initData (options) {
options = options.map((d, i) => {
d.optionsIndex = i
return d
})
this.setState({ options })
}
onSearch () {
if (this.props.onSearch) {
this.props.onSearch()
}
}
open () {
this.bindClickAway()
let options = React.findDOMNode(this.refs.options)
options.style.display = 'block'
setTimeout(() => {
this.setState({ active: true })
}, 0)
setTimeout(() => {
options.parentNode.style.overflow = 'visible'
}, 450)
}
close () {
let options = React.findDOMNode(this.refs.options)
options.parentNode.style.overflow = 'hidden'
this.setState({ active: false })
this.unbindClickAway()
setTimeout(() => {
options.style.display = 'none'
}, 450)
}
addFilter () {
let filters = this.state.filters
filters.push({})
this.setState({ filters })
}
removeFilter (index) {
let filters = this.state.filters
filters.splice(index, 1)
this.setState({ filters })
}
clearFilter () {
this.setState({ filters: [], resultText: '' })
this.close()
if (this.props.onFilter) {
this.props.onFilter([])
}
}
onChange (index, filter) {
let filters = this.state.filters,
f = filters[index]
Object.keys(filter).forEach(k => {
f[k] = filter[k]
})
this.setState({ filters })
}
onFilter () {
this.close()
let filters = this.state.filters,
local = this.props.local
this.setState({ resultText: this.formatText(filters) })
if (this.props.onFilter) {
let novs = []
filters.forEach((f, i) => {
if (f.op && f.value) {
let nov = { name: f.name, op: f.op, value: f.value }
if (local) {
nov.func = this.refs[`fi${i}`].getFunc()
}
novs.push(nov)
}
})
this.props.onFilter(novs)
}
}
formatText (filters) {
let text = []
filters.forEach(f => {
if (f.op && f.value) {
text.push(`${f.label} ${f.op} '${f.value}'`)
}
})
return text.join(', ')
}
renderFilters () {
let filters = this.state.filters.map((f, i) => {
return (
<FilterItem onChange={this.onChange.bind(this)} removeFilter={this.removeFilter.bind(this)} ref={`fi${i}`} index={i} key={i} {...f} options={this.state.options} />
)
})
return filters
}
render () {
let className = classnames(
this.props.className,
'rct-filter',
'rct-form-control',
this.state.active ? 'active' : ''
)
return (
<div style={this.props.style} className={className}>
<div onClick={this.open.bind(this)} className="rct-filter-result">
{this.state.resultText}
<i className="search" />
</div>
<div className="rct-filter-options-wrap">
<div ref="options" className="rct-filter-options">
{this.renderFilters()}
<div>
<Button status="success" onClick={this.addFilter.bind(this)}>+</Button>
<Button style={{marginLeft: 10}} onClick={this.clearFilter.bind(this)}>{getLang('buttons.clear')}</Button>
<Button style={{marginLeft: 10}} status="primary" onClick={this.onFilter.bind(this)}>{getLang('buttons.ok')}</Button>
</div>
</div>
</div>
</div>
)
}
}
|
admin/client/components/EditForm.js | Ftonso/keystone | import React from 'react';
import moment from 'moment';
import ConfirmationDialog from './ConfirmationDialog';
import Fields from '../fields';
import FormHeading from './FormHeading';
import AltText from './AltText';
import FooterBar from './FooterBar';
import InvalidFieldType from './InvalidFieldType';
import { Button, Col, Form, FormField, FormInput, ResponsiveText, Row } from 'elemental';
var EditForm = React.createClass({
displayName: 'EditForm',
propTypes: {
data: React.PropTypes.object,
list: React.PropTypes.object,
},
getInitialState () {
return {
values: Object.assign({}, this.props.data.fields),
confirmationDialog: null
};
},
getFieldProps (field) {
var props = Object.assign({}, field);
props.value = this.state.values[field.path];
props.values = this.state.values;
props.onChange = this.handleChange;
props.mode = 'edit';
return props;
},
handleChange (event) {
let values = Object.assign({}, this.state.values);
values[event.path] = event.value;
this.setState({ values });
},
confirmReset(event) {
const confirmationDialog = (
<ConfirmationDialog
body={`Reset your changes to <strong>${this.props.data.name}</strong>?`}
confirmationLabel="Reset"
onCancel={this.removeConfirmationDialog}
onConfirmation={this.handleReset}
/>
);
event.preventDefault();
this.setState({ confirmationDialog });
},
handleReset () {
window.location.reload();
},
confirmDelete() {
const confirmationDialog = (
<ConfirmationDialog
body={`Are you sure you want to delete <strong>${this.props.data.name}?</strong><br /><br />This cannot be undone.`}
confirmationLabel="Delete"
onCancel={this.removeConfirmationDialog}
onConfirmation={this.handleDelete}
/>
);
this.setState({ confirmationDialog });
},
handleDelete () {
let { data, list } = this.props;
list.deleteItem(data.id, err => {
if (err) {
console.error(`Problem deleting ${list.singular}: ${data.name}`);
// TODO: slow a flash message on form
return;
}
top.location.href = `${Keystone.adminPath}/${list.path}`;
});
},
removeConfirmationDialog () {
this.setState({
confirmationDialog: null
});
},
renderKeyOrId () {
var className = 'EditForm__key-or-id';
var list = this.props.list;
if (list.nameField && list.autokey && this.props.data[list.autokey.path]) {
return (
<AltText
normal={list.autokey.path + ': ' + this.props.data[list.autokey.path]}
modified={'ID: ' + String(this.props.data.id)}
component="div"
title="Press <alt> to reveal the ID"
className={className} />
);
} else if (list.autokey && this.props.data[list.autokey.path]) {
return (
<div className={className}>{list.autokey.path}: {this.props.data[list.autokey.path]}</div>
);
} else if (list.nameField) {
return (
<div className={className}>id: {this.props.data.id}</div>
);
}
},
renderNameField () {
var nameField = this.props.list.nameField;
var nameIsEditable = this.props.list.nameIsEditable;
var wrapNameField = field => (
<div className="EditForm__name-field">
{field}
</div>
);
if (nameIsEditable) {
var nameFieldProps = this.getFieldProps(nameField);
nameFieldProps.label = null;
nameFieldProps.size = 'full';
nameFieldProps.inputProps = {
className: 'item-name-field',
placeholder: nameField.label,
size: 'lg',
};
return wrapNameField(
React.createElement(Fields[nameField.type], nameFieldProps)
);
} else {
return wrapNameField(
<h2>{this.props.data.name || '(no name)'}</h2>
);
}
},
renderFormElements () {
var headings = 0;
return this.props.list.uiElements.map((el) => {
if (el.type === 'heading') {
headings++;
el.options.values = this.state.values;
el.key = 'h-' + headings;
return React.createElement(FormHeading, el);
}
if (el.type === 'field') {
var field = this.props.list.fields[el.field];
var props = this.getFieldProps(field);
if ('function' !== typeof Fields[field.type]) {
return React.createElement(InvalidFieldType, { type: field.type, path: field.path, key: field.path });
}
if (props.dependsOn) {
props.currentDependencies = {};
Object.keys(props.dependsOn).forEach(dep => {
props.currentDependencies[dep] = this.state.values[dep];
});
}
props.key = field.path;
return React.createElement(Fields[field.type], props);
}
}, this);
},
renderFooterBar () {
var buttons = [
<Button key="save" type="primary" submit>Save</Button>
];
buttons.push(
<Button key="reset" onClick={this.confirmReset} type="link-cancel">
<ResponsiveText hiddenXS="reset changes" visibleXS="reset" />
</Button>
);
if (!this.props.list.nodelete) {
buttons.push(
<Button key="del" onClick={this.confirmDelete} type="link-delete" className="u-float-right">
<ResponsiveText hiddenXS={`delete ${this.props.list.singular.toLowerCase()}`} visibleXS="delete" />
</Button>
);
}
return (
<FooterBar className="EditForm__footer">
{buttons}
</FooterBar>
);
},
renderTrackingMeta () {
if (!this.props.list.tracking) return null;
var elements = [];
var data = {};
if (this.props.list.tracking.createdAt) {
data.createdAt = this.props.data.fields[this.props.list.tracking.createdAt];
if (data.createdAt) {
elements.push(
<FormField key="createdAt" label="Created on">
<FormInput noedit title={moment(data.createdAt).format('DD/MM/YYYY h:mm:ssa')}>{moment(data.createdAt).format('Do MMM YYYY')}</FormInput>
</FormField>
);
}
}
if (this.props.list.tracking.createdBy) {
data.createdBy = this.props.data.fields[this.props.list.tracking.createdBy];
if (data.createdBy) {
// todo: harden logic around user name
elements.push(
<FormField key="createdBy" label="Created by">
<FormInput noedit>{data.createdBy.name.first} {data.createdBy.name.last}</FormInput>
</FormField>
);
}
}
if (this.props.list.tracking.updatedAt) {
data.updatedAt = this.props.data.fields[this.props.list.tracking.updatedAt];
if (data.updatedAt && (!data.createdAt || data.createdAt !== data.updatedAt)) {
elements.push(
<FormField key="updatedAt" label="Updated on">
<FormInput noedit title={moment(data.updatedAt).format('DD/MM/YYYY h:mm:ssa')}>{moment(data.updatedAt).format('Do MMM YYYY')}</FormInput>
</FormField>
);
}
}
if (this.props.list.tracking.updatedBy) {
data.updatedBy = this.props.data.fields[this.props.list.tracking.updatedBy];
if (data.updatedBy && (!data.createdBy || data.createdBy.id !== data.updatedBy.id || elements.updatedAt)) {
elements.push(
<FormField key="updatedBy" label="Updated by">
<FormInput noedit>{data.updatedBy.name.first} {data.updatedBy.name.last}</FormInput>
</FormField>
);
}
}
return Object.keys(elements).length ? (
<div className="EditForm__meta">
<h3 className="form-heading">Meta</h3>
{elements}
</div>
) : null;
},
render () {
return (
<form method="post" encType="multipart/form-data" className="EditForm-container">
<Row>
<Col lg="3/4">
<Form type="horizontal" className="EditForm" component="div">
<input type="hidden" name="action" value="updateItem" />
<input type="hidden" name={Keystone.csrf.key} value={Keystone.csrf.value} />
{this.renderNameField()}
{this.renderKeyOrId()}
{this.renderFormElements()}
{this.renderTrackingMeta()}
</Form>
</Col>
<Col lg="1/4"><span /></Col>
</Row>
{this.renderFooterBar()}
{this.state.confirmationDialog}
</form>
);
}
});
module.exports = EditForm;
|
imports/ui/components/app-navigation.js | hanstest/hxgny | import React from 'react'
import { Segment } from 'semantic-ui-react'
import PublicNavigation from './public-navigation'
import AuthenticatedNavigation from './authenticated-navigation'
export class AppNavigation extends React.Component {
static renderNavigation(hasUser) {
return hasUser ? <AuthenticatedNavigation /> : <PublicNavigation />
}
render() {
return (
<Segment>
{ AppNavigation.renderNavigation(this.props.hasUser) }
</Segment>
)
}
}
AppNavigation.propTypes = {
hasUser: React.PropTypes.object,
}
|
src/view/user/detail/index.js | fishmankkk/mircowater2.0 | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import styles from './index.less'
const Detail = ({ userDetail }) => {
const { data } = userDetail
const content = []
for (let key in data) {
if ({}.hasOwnProperty.call(data, key)) {
content.push(<div key={key} className={styles.item}>
<div>{key}</div>
<div>{String(data[key])}</div>
</div>)
}
}
return (<div className="content-inner">
<div className={styles.content}>
{content}
</div>
</div>)
}
Detail.propTypes = {
userDetail: PropTypes.object,
}
export default connect(({ userDetail, loading }) => ({ userDetail, loading: loading.models.userDetail }))(Detail)
|
src/components/Item/Details/counter.js | zeachco/rockplusinc.com | import React from 'react';
import { connect } from 'react-redux';
// import { bindActionCreators } from 'redux';
// import { updateItemQuantity, removeFromCart } from '../../../store/actions/cart';
class Counter extends React.Component {
handleClick(e) {
e.preventDefault();
const {item} = this.props;
if (item) {
if (quantity > 1)
updateItemQuantity(item, quantity - 1)
else if (quantity <= 1)
removeFromCart(item);
}
}
render() {
const item = this
.props
.cart
.item
.find((item) => item.id === this.props._id)
return (
<div
className='counter'
onClick={this
.handleClick
.bind(this)}>
{(item)
? <span>{item.quantity}</span>
: ''}
</div>
)
}
}
const mapStateToProps = store => ({cart: store.cart});
export default connect(mapStateToProps)(Counter);
|
packages/react-server-website/components/Markdown.js | emecell/react-server | import PropTypes from 'prop-types';
import React from 'react';
import Remarkable from 'remarkable';
import hljs from '../lib/highlight.js';
import {logging, navigateTo} from 'react-server';
import './Markdown.less';
const logger = logging.getLogger(__LOGGER__);
export default class Markdown extends React.Component {
render() {
let content = this.props.children || this.props.source;
// The markdown handling returns a wad of HTML, so place it directly
// into the component.
return <div className="dangerous-markdown" dangerouslySetInnerHTML={{
__html: this._renderMarkdown(content),
}} />
}
_renderMarkdown(content) {
// Remarkable hljs handling, from documentation
const md = new Remarkable({
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(lang, str).value;
} catch (err) { logger.log(err); }
}
try {
// default to js
return hljs.highlight("javascript", str).value;
} catch (err) { logger.log(err); }
return ''; // use external default escaping
},
});
return md.render(content);
}
componentDidMount() {
// Our markdown documentation contains both internal and external links.
// We want to make sure that external links open in a new tab, and that
// internal links use client transitions for better performance.
[].slice.call(document.querySelectorAll('.dangerous-markdown a')).forEach(a => {
if (isInternal(a)) {
addOnClickHandler(a, this.props);
} else {
addTargetBlank(a);
}
});
}
}
Markdown.propTypes = {
source : PropTypes.string,
reuseDom : PropTypes.bool,
bundleData : PropTypes.bool,
}
Markdown.defaultProps = {
reuseDom : false,
bundleData : true,
}
function isInternal(a) {
const href = a.getAttribute('href');
return href.startsWith('/');
}
// TODO: Let's make this available as a helper from React Server core.
function addOnClickHandler(a, {reuseDom, bundleData}) {
a.onclick = function (e) {
// See Link.jsx in react-server/core/Link
if (!e.metaKey) {
e.preventDefault();
e.stopPropagation();
navigateTo(a.getAttribute('href'), {reuseDom, bundleData});
} else {
// do normal browser navigate
}
}
}
function addTargetBlank(a) {
a.setAttribute('target', '_blank');
}
|
client/src/components/Draftail/blocks/EmbedBlock.js | rsalmaso/wagtail | import PropTypes from 'prop-types';
import React from 'react';
import { gettext } from '../../../utils/gettext';
import MediaBlock from '../blocks/MediaBlock';
/**
* Editor block to display media and edit content.
*/
const EmbedBlock = (props) => {
const { entity, onEditEntity, onRemoveEntity } = props.blockProps;
const { url, title, thumbnail } = entity.getData();
return (
<MediaBlock {...props} src={thumbnail} alt="">
{url ? (
<a
className="Tooltip__link EmbedBlock__link"
href={url}
title={url}
target="_blank"
rel="noreferrer"
>
{title}
</a>
) : null}
<button
className="button Tooltip__button"
type="button"
onClick={onEditEntity}
>
{gettext('Edit')}
</button>
<button
className="button button-secondary no Tooltip__button"
onClick={onRemoveEntity}
>
{gettext('Delete')}
</button>
</MediaBlock>
);
};
EmbedBlock.propTypes = {
blockProps: PropTypes.shape({
entity: PropTypes.object,
}).isRequired,
};
export default EmbedBlock;
|
src/Pagination.js | oPauloChaves/controle-frotas | import React from 'react'
import Pagination from 'react-bootstrap/lib/Pagination'
const BasicPagination = ({ totalCount, activePage, onChangePage }) => {
const pages = Math.ceil(totalCount / 5)
return (
<div className="AppPagination">
<Pagination
prev={<span className="BtnPrev" aria-label="Prev">«</span>}
next={<span className="BtnNext" aria-label="Next">»</span>}
bsSize="medium"
items={pages}
activePage={activePage}
onSelect={onChangePage} />
</div>
)
}
export default BasicPagination
|
app/components/Roster.js | BeAce/react-babel-webpack-eslint-boilerplate | import React from 'react';
import { Switch, Route } from 'react-router-dom';
import FullRoster from './FullRoster';
import Player from './Player';
// The Roster component matches one of two different routes
// depending on the full pathname
const Roster = () =>
(<Switch>
<Route exact path="/roster" component={FullRoster} />
<Route path="/roster/:number" component={Player} />
</Switch>);
export default Roster;
|
src/components/app_home.js | leapon/office-finder | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class Home extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="jumbotron">
<h1 className="display-3">Looking for an office? We can help</h1>
<p className="lead">OfficeFinder is the premier website for finding office information.</p>
<hr className="my-4"/>
<p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
<p className="lead">
<Link className="btn btn-primary btn-lg" to="office/search">Search for office</Link>
</p>
</div>
);
}
}
export default Home;
|
src/components/UserInfo.js | dkadrios/zendrum-stompblock-client | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Avatar } from '@material-ui/core'
import Gravatar from 'react-gravatar'
import Popover from 'react-popover'
import UserRegistration from './UserRegistration'
import UserInfoPopover from './UserInfoPopover'
import styles from '../styles/registration'
import popoverStyle from '../styles/popovers'
import { userShape } from '../reducers/user'
import * as userActions from '../action-creators/user'
const UserInfo = ({ user, showDialog, hideDialog, hidePopover, submitRegistrationForm }) => {
const { checkedRegistration, registered, firstName, lastName, email, dialogVisible, popoverVisible } = user
return (
<div className={styles.userInfo}>
{checkedRegistration && (
<div className={styles.layout}>
<section
onClick={showDialog}
role="button"
tabIndex="0"
>
<div>{registered && 'Registered to:'}</div>
<span className={styles.name}>{`${firstName} ${lastName}`}</span>
</section>
<Popover
isOpen={popoverVisible}
onClick={showDialog}
place="below"
body={<UserInfoPopover showDialog={showDialog} />}
className={popoverStyle.Popover}
onOuterAction={hidePopover}
>
<Avatar onClick={showDialog}>
<Gravatar
email={email}
default="mm"
rating="x"
/>
</Avatar>
</Popover>
</div>
)}
<UserRegistration
active={dialogVisible}
hideDialog={hideDialog}
submitRegistrationForm={submitRegistrationForm}
{...user}
/>
</div>
)
}
UserInfo.propTypes = {
user: PropTypes.shape(userShape).isRequired,
showDialog: PropTypes.func.isRequired,
hideDialog: PropTypes.func.isRequired,
hidePopover: PropTypes.func.isRequired,
submitRegistrationForm: PropTypes.func.isRequired,
}
const mapStateToProps = ({ user }) => ({ user })
const mapDispatchToProps = dispatch => bindActionCreators(userActions, dispatch)
export default connect(
mapStateToProps,
mapDispatchToProps,
)(UserInfo)
|
src/jsx/todoapp.js | MingXingTeam/React-Demo | /**
"this.props" can ref the React Component Attr Object
"getInitialState" is default React method,which contains the state of React Component
"{}" is used to write React Program
**/
/**
how to bind event on DOM in React:
<input onChange={this.onChange} value={this.state.text}>
**/
import React from 'react';
React.createClass({
render: () => {
return (
<ul>
{
this.props.items.map(item => {
return <li key={item.id}>{item.text}</li>;
})
}
</ul>
);
}
});
React.createClass({
getInitialState: () => {
return { items: [], text: '' };
},
onChange: e => {
this.setState({
text: e.target.value
});
},
handleSubmit: e => {
e.preventDefault();
var nextItems = this.state.items.concat([{ text: this.state.text, id: Date().now() }]);
var nextText = '';
this.setState({
items: nextItems, text: nextText
});
},
render: () => {
return '3';
}
});
|
packages/wix-style-react/src/ListItemEditable/test/ListItemEditable.visual.js | wix/wix-style-react | import React from 'react';
import { storiesOf } from '@storybook/react';
import ListItemEditable, { listItemEditableBuilder } from '../ListItemEditable';
import DropdownLayout from '../../DropdownLayout';
import { storyOfAllPermutations } from '../../../test/utils/visual/utils';
const commonProps = {
onApprove: () => null,
onCancel: () => null,
};
const Story = props => <ListItemEditable {...commonProps} {...props} />;
const options = {
props: ['placeholder', 'size', 'status', 'margins'],
};
storyOfAllPermutations(Story, ListItemEditable, options);
storiesOf('ListItemEditable', module).add('builder', () => (
<DropdownLayout
visible
selectedId={1}
options={[
listItemEditableBuilder({
id: 0,
}),
listItemEditableBuilder({
id: 1,
}),
listItemEditableBuilder({
id: 2,
}),
]}
/>
));
|
app/decorators/connect.js | luizvidoto/survivejs-kanban-tutorial | import React from 'react';
const connect = (Component, store) => {
return class Connect extends React.Component {
constructor(props){
super(props);
this.storeChanged = this.storeChanged.bind(this);
this.state = store.getState();
store.listen(this.storeChanged);
}
componentWillUnmount(){
store.unlisten(this.storeChanged);
}
storeChanged(){
this.setState(store.getState());
}
render(){
return <Component {...this.props} {...this.state} />;
}
};
};
export default (store) => {
return (target) => connect(target, store);
};
|
node_modules/react-bootstrap/es/NavbarBrand.js | chenjic215/search-doctor | 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 PropTypes from 'prop-types';
import { prefix } from './utils/bootstrapUtils';
var contextTypes = {
$bs_navbar: PropTypes.shape({
bsClass: PropTypes.string
})
};
var NavbarBrand = function (_React$Component) {
_inherits(NavbarBrand, _React$Component);
function NavbarBrand() {
_classCallCheck(this, NavbarBrand);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavbarBrand.prototype.render = function render() {
var _props = this.props,
className = _props.className,
children = _props.children,
props = _objectWithoutProperties(_props, ['className', 'children']);
var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' };
var bsClassName = prefix(navbarProps, 'brand');
if (React.isValidElement(children)) {
return React.cloneElement(children, {
className: classNames(children.props.className, className, bsClassName)
});
}
return React.createElement(
'span',
_extends({}, props, { className: classNames(className, bsClassName) }),
children
);
};
return NavbarBrand;
}(React.Component);
NavbarBrand.contextTypes = contextTypes;
export default NavbarBrand; |
frontend/src/InteractiveImport/Quality/SelectQualityModalContent.js | geogolem/Radarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Form from 'Components/Form/Form';
import FormGroup from 'Components/Form/FormGroup';
import FormInputGroup from 'Components/Form/FormInputGroup';
import FormLabel from 'Components/Form/FormLabel';
import Button from 'Components/Link/Button';
import LoadingIndicator from 'Components/Loading/LoadingIndicator';
import ModalBody from 'Components/Modal/ModalBody';
import ModalContent from 'Components/Modal/ModalContent';
import ModalFooter from 'Components/Modal/ModalFooter';
import ModalHeader from 'Components/Modal/ModalHeader';
import { inputTypes, kinds } from 'Helpers/Props';
import translate from 'Utilities/String/translate';
class SelectQualityModalContent extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
const {
qualityId,
proper,
real
} = props;
this.state = {
qualityId,
proper,
real
};
}
//
// Listeners
onQualityChange = ({ value }) => {
this.setState({ qualityId: parseInt(value) });
}
onProperChange = ({ value }) => {
this.setState({ proper: value });
}
onRealChange = ({ value }) => {
this.setState({ real: value });
}
onQualitySelect = () => {
this.props.onQualitySelect(this.state);
}
//
// Render
render() {
const {
isFetching,
isPopulated,
error,
items,
onModalClose
} = this.props;
const {
qualityId,
proper,
real
} = this.state;
const qualityOptions = items.map(({ id, name }) => {
return {
key: id,
value: name
};
});
return (
<ModalContent onModalClose={onModalClose}>
<ModalHeader>
{translate('ManualImportSelectQuality')}
</ModalHeader>
<ModalBody>
{
isFetching &&
<LoadingIndicator />
}
{
!isFetching && !!error &&
<div>
{translate('UnableToLoadQualities')}
</div>
}
{
isPopulated && !error &&
<Form>
<FormGroup>
<FormLabel>{translate('Quality')}</FormLabel>
<FormInputGroup
type={inputTypes.SELECT}
name="quality"
value={qualityId}
values={qualityOptions}
onChange={this.onQualityChange}
/>
</FormGroup>
<FormGroup>
<FormLabel>{translate('Proper')}</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="proper"
value={proper}
onChange={this.onProperChange}
/>
</FormGroup>
<FormGroup>
<FormLabel>{translate('Real')}</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="real"
value={real}
onChange={this.onRealChange}
/>
</FormGroup>
</Form>
}
</ModalBody>
<ModalFooter>
<Button onPress={onModalClose}>
{translate('Cancel')}
</Button>
<Button
kind={kinds.SUCCESS}
onPress={this.onQualitySelect}
>
{translate('SelectQuality')}
</Button>
</ModalFooter>
</ModalContent>
);
}
}
SelectQualityModalContent.propTypes = {
qualityId: PropTypes.number.isRequired,
proper: PropTypes.bool.isRequired,
real: PropTypes.bool.isRequired,
isFetching: PropTypes.bool.isRequired,
isPopulated: PropTypes.bool.isRequired,
error: PropTypes.object,
items: PropTypes.arrayOf(PropTypes.object).isRequired,
onQualitySelect: PropTypes.func.isRequired,
onModalClose: PropTypes.func.isRequired
};
export default SelectQualityModalContent;
|
src/components/base/Base.js | saas-plat/saas-plat-appfx | import React from 'react';
export default class Base extends React.Component {
state = {}
render() {
return null;
}
}
|
src/components/board/cell/delete/index.js | ecolman/sudokujs | import React from 'react';
import { Raphael, Set, Path, Text } from 'react-raphael';
import { useDispatch, useSelector } from 'react-redux';
import { actions as boardsActions, selectors as boardsSelectors } from 'redux/boards';
import './styles.less';
function Delete(props) {
const { col, hide, index, row, x, y } = props;
const dispatch = useDispatch();
const showCellNotes = useSelector(state => boardsSelectors.showCellNotes(state, index));
// clear cell value or notes value
const handleClick = () => dispatch(showCellNotes
? boardsActions.CLEAR_CELL_NOTES({ row, col })
: boardsActions.CLEAR_CELL({ row, col })
);
return !hide
? (
<Set>
<Path d={`M ${x - 7} ${y - 9}
A 45 45, 0, 0, 0, ${x + 9} ${y + 9}
L ${x + 9} ${y - 9} Z`}
styleName={'path'}
click={handleClick} />
<Text text={'X'}
x={x + 4}
y={y - 3}
styleName={'text'}
click={handleClick} />
</Set>
)
: null;
}
export default Delete;
|
src/svg-icons/action/accessible.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAccessible = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="4" r="2"/><path d="M19 13v-2c-1.54.02-3.09-.75-4.07-1.83l-1.29-1.43c-.17-.19-.38-.34-.61-.45-.01 0-.01-.01-.02-.01H13c-.35-.2-.75-.3-1.19-.26C10.76 7.11 10 8.04 10 9.09V15c0 1.1.9 2 2 2h5v5h2v-5.5c0-1.1-.9-2-2-2h-3v-3.45c1.29 1.07 3.25 1.94 5 1.95zm-6.17 5c-.41 1.16-1.52 2-2.83 2-1.66 0-3-1.34-3-3 0-1.31.84-2.41 2-2.83V12.1c-2.28.46-4 2.48-4 4.9 0 2.76 2.24 5 5 5 2.42 0 4.44-1.72 4.9-4h-2.07z"/>
</SvgIcon>
);
ActionAccessible = pure(ActionAccessible);
ActionAccessible.displayName = 'ActionAccessible';
ActionAccessible.muiName = 'SvgIcon';
export default ActionAccessible;
|
src/App.js | aldhsu/missile-command | import React, { Component } from 'react';
import Main from './game/main';
export class App extends Component {
constructor() {
super();
this.width = 800;
this.height = 480;
this.maxParticles = 20;
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
this.canvas = this.refs.canvas
const ctx = this.canvas.getContext('2d');
this.main = new Main(ctx, this.width, this.height, this.maxParticles);
this.main.init();
}
getMousePos(canvas, evt) {
const rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
handleClick(event) {
const coords = this.getMousePos(this.canvas, event);
this.main.addSprite(coords);
}
render() {
return (
<canvas onClick={this.handleClick} width={this.width} height={this.height} ref='canvas'/>
);
}
}
|
examples/hello-world/pages/about.js | dstreet/next.js | import React from 'react'
export default () => (
<div>About us</div>
)
|
node_modules/react-icons/fa/tree.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const FaTree = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m36.6 32.9q0 0.5-0.5 1t-1 0.4h-10.3q0.1 0.4 0.2 1.9t0.1 2.5q0 0.5-0.4 0.9t-1 0.4h-7.1q-0.6 0-1-0.4t-0.4-0.9q0-0.9 0.1-2.5t0.2-1.9h-10.4q-0.5 0-1-0.4t-0.4-1 0.4-1l9-9h-5.1q-0.6 0-1-0.5t-0.4-1 0.4-1l9-9h-4.4q-0.6 0-1-0.4t-0.5-1 0.5-1l8.5-8.6q0.5-0.4 1-0.4t1 0.4l8.6 8.6q0.4 0.4 0.4 1t-0.4 1-1 0.4h-4.4l9 9q0.4 0.4 0.4 1t-0.4 1-1 0.5h-5.1l8.9 8.9q0.5 0.5 0.5 1.1z"/></g>
</Icon>
)
export default FaTree
|
app/components/group/group.js | dfmcphee/pinnr | import React from 'react';
import Post from '../post/post.js';
import GroupStore from '../../stores/group-store';
import PostStore from '../../stores/post-store';
import AuthenticationStore from '../../stores/authentication-store';
import { Card } from 'semantic-ui-react';
export default class Group extends React.Component {
constructor(props) {
super(props);
const { groupId } = this.props.params;
this.state = {
authenticated: false,
user: null,
groupId: groupId,
group: {
title: '',
username: '',
hashtag: ''
}
};
AuthenticationStore.init();
GroupStore.init();
PostStore.init(groupId);
}
getGroupStateFromStore() {
return GroupStore.getGroup(this.state.groupId);
}
getPostsStateFromStore() {
return PostStore.getPosts(this.state.groupId);
}
componentWillMount() {
this.updateGroup();
this.updatePosts();
}
updateAuthentication() {
this.setState({
authenticated: AuthenticationStore.isAuthenticated(),
user: AuthenticationStore.getUser()
});
}
componentDidMount() {
GroupStore.addChangeListener(() => this.updateGroup())
PostStore.addChangeListener(() => this.updatePosts())
AuthenticationStore.addChangeListener(() => this.updateAuthentication())
}
componentWillUnmount() {
GroupStore.removeChangeListener(() => this.updateGroup())
PostStore.removeChangeListener(() => this.updatePosts())
AuthenticationStore.removeChangeListener(() => this.updateAuthentication())
}
updateGroup() {
this.setState({
group: this.getGroupStateFromStore()
});
}
updatePosts() {
this.setState({
posts: this.getPostsStateFromStore(this.state.groupId)
});
}
removePost(postId) {
PostStore.removePost(postId);
}
isOwner() {
if (!this.state.user) {
return false;
}
return (this.state.group.UserId === this.state.user.id);
}
posts() {
if (!this.state.posts) {
return;
}
return (
<Card.Group>
{this.state.posts.map(post => (
<Post post={post} key={post.id} onRemove={() => this.removePost(post.id)} owner={this.isOwner()} />
))}
</Card.Group>
);
}
groupDetails() {
if (!this.state.group) {
return;
}
return (
<Card fluid>
<Card.Content>
<Card.Header>
{this.state.group.title}
</Card.Header>
<Card.Meta>
#{this.state.group.hashtag}
</Card.Meta>
<Card.Description>
<a href={`mailto:${this.state.group.url}@inbound.simplifeed.me`}>
{this.state.group.url}@inbound.simplifeed.me
</a>
</Card.Description>
</Card.Content>
</Card>
);
}
render() {
return (
<div className="group">
{this.groupDetails()}
{this.posts()}
</div>
);
}
}
|
src/components/FacebookLogin/FacebookLogin.js | PhilNorfleet/pBot | import React, { Component } from 'react';
import PropTypes from 'prop-types';
class FacebookLogin extends Component {
static propTypes = {
onLogin: PropTypes.func.isRequired,
appId: PropTypes.string.isRequired,
xfbml: PropTypes.bool,
cookie: PropTypes.bool,
scope: PropTypes.string,
autoLoad: PropTypes.bool,
version: PropTypes.string,
language: PropTypes.string,
textButton: PropTypes.string,
typeButton: PropTypes.string,
className: PropTypes.string,
component: PropTypes.func.isRequired
};
static defaultProps = {
textButton: 'Login with Facebook',
typeButton: 'button',
className: '',
scope: 'public_profile,email',
xfbml: false,
cookie: false,
version: '2.3',
language: 'en_US',
autoLoad: false
}
componentDidMount() {
const { appId, xfbml, cookie, version, autoLoad, language } = this.props;
let fbRoot = document.getElementById('fb-root');
if (!fbRoot) {
fbRoot = document.createElement('div');
fbRoot.id = 'fb-root';
document.body.appendChild(fbRoot);
}
window.fbAsyncInit = () => {
window.FB.init({
version: `v${version}`,
appId,
xfbml,
cookie,
});
if (autoLoad || window.location.search.includes('facebookdirect')) {
window.FB.getLoginStatus(this.checkLoginState);
}
};
// Load the SDK asynchronously
((d, id) => {
if (d.getElementById(id)) return;
const js = d.createElement('script');
js.id = id;
js.src = `//connect.facebook.net/${language}/all.js`;
d.body.appendChild(js);
})(document, 'facebook-jssdk');
}
click = () => {
const { scope, appId } = this.props;
if (navigator.userAgent.match('CriOS')) {
window.location.href = `https://www.facebook.com/dialog/oauth?client_id=${appId}` +
`&redirect_uri=${window.location.href}&state=facebookdirect&${scope}`;
} else {
window.FB.login(response => {
if (response.authResponse) {
this.props.onLogin(null, response.authResponse);
} else {
this.props.onLogin(response);
}
}, { scope });
}
};
render() {
const { className, textButton, typeButton, component: WrappedComponent } = this.props;
if (WrappedComponent) return <WrappedComponent facebookLogin={this.click} />;
return (
<button className={className} onClick={this.click} type={typeButton}>
{textButton}
</button>
);
}
}
export default FacebookLogin;
|
Cordial/app/components/splash-screen.js | AwesomePossum446/Cordial | import React from 'react';
import { View, Image, StyleSheet } from 'react-native';
import { Actions, ActionConst } from 'react-native-router-flux';
import {User} from '../models/Model';
const SPLASH_TIME = 500;
const styles = StyleSheet.create({
logo: {
flexDirection: 'row',
alignSelf: 'center',
height: 70,
width: 250,
},
screen: {
flex: 1,
justifyContent: 'center'
}
});
export class Splash extends React.Component {
render() {
return (
<View style={styles.screen}>
<Image
source={require('../assets/img/cordial.png')}
style={styles.logo}
/>
</View>
);
}
}
export default class SplashScreen extends React.Component {
componentDidMount() {
const redirectOptions = {type: ActionConst.REPLACE};
setTimeout(() => {
if (User.me()) {
Actions.tabbar(redirectOptions);
} else {
Actions.welcome(redirectOptions);
}
}, SPLASH_TIME);
}
render() {
return <Splash/>;
}
}
|
packages/vx-demo/components/codeblocks/SimpleLineGlyphCode.js | Flaque/vx | import React from 'react';
import Codeblock from './Codeblock';
export default ({}) => {
return (
<Codeblock>
{`// SimpleLineWithGlyphsChart.js
function SimpleLineWithGlyphsChart({
margin,
dataset,
screenWidth,
screenHeight,
}) {
if (!Array.isArray(dataset)) dataset = [dataset];
const allData = dataset.reduce((rec, d) => {
return rec.concat(d.data)
}, []);
const width = screenWidth / 1.5;
const height = width / 2;
// bounds
const xMax = width - margin.left - margin.right;
const yMax = height - margin.top - margin.bottom;
// accessors
const x = d => d.date;
const y = d => d.value;
// scales
const xScale = Scale.scaleTime({
range: [0, xMax],
domain: extent(allData, x),
});
const yScale = Scale.scaleLinear({
range: [yMax, 0],
domain: [0, max(allData, y)],
nice: true,
clamp: true,
});
const yFormat = yScale.tickFormat ? yScale.tickFormat() : identity;
return (
<svg width={width} height={height}>
<AxisRight
top={margin.top}
left={width - margin.right}
scale={yScale}
numTicks={numTicksForHeight(height)}
label={'value'}
hideZero
/>
<Group
top={margin.top}
left={margin.left}
>
<Grid
xScale={xScale}
yScale={yScale}
width={xMax}
height={yMax}
numTicksRows={numTicksForHeight(height)}
numTicksColumns={numTicksForWidth(width)}
/>
{dataset.map((series, i) => {
return (
<Shape.LinePath
key={'chart-line-{i}'}
data={series.data}
xScale={xScale}
yScale={yScale}
x={x}
y={y}
stroke={series.chart.stroke}
strokeWidth={series.chart.strokeWidth}
strokeDasharray={series.chart.strokeDasharray}
curve={Curve.monotoneX}
glyph={(d, i) => {
return (
<GlyphDot key={'line-point-{i}'}
className={cx('vx-linepath-point')}
cx={xScale(x(d))}
cy={yScale(y(d))}
r={6}
fill={series.chart.stroke}
stroke={series.chart.backgroundColor}
strokeWidth={3}
>
<text
x={xScale(x(d))}
y={yScale(y(d))}
dx={10}
fill={series.chart.stroke}
stroke={series.chart.backgroundColor}
strokeWidth={6}
fontSize={11}
>
{yFormat(y(d))}
</text>
<text
x={xScale(x(d))}
y={yScale(y(d))}
dx={10}
fill={series.chart.stroke}
fontSize={11}
>
{yFormat(y(d))}
</text>
</Glyph.Dot>
);
}}
/>
);
})}
</Group>
<AxisBottom
top={height - margin.bottom}
left={margin.left}
scale={xScale}
numTicks={numTicksForWidth(width)}
label={'time'}
hideTicks
/>
</svg>
);
}
export default withScreenSize(SimpleLineWithGlyphsChart);`}
</Codeblock>
);
}
|
src/js/components/LargePictureIcon/LargePictureIcon.js | shane-arthur/react-redux-and-more-boilerplate | import React, { Component } from 'react';
import PictureWithFrame from '../PictureWithFrame/PictureWithFrame';
import SelectedRadioButton from '../SelectedRadioButton/SelectedRadioButton';
const style = {
display: 'inline-block'
};
export default class LargePictureIcon extends Component {
_formPanelHeader() {
return (<div>
<h3 style={style}>
{this.props.pictureName}
</h3>
<div style={style}>
<SelectedRadioButton
selected={this.props.selected}
onClick={this.props.onClick}
selectedData={this.props.selectedData}
/>
</div>
</div>);
}
render() {
const header = this._formPanelHeader();
return (
<div style={{ width: '375px', height: '375px', border: '1px solid black', textAlign: 'center', borderRadius: '10px', position: 'absolute', opacity: 1, zIndex: 1000, background: '#ffffff' }}>
{header}
<PictureWithFrame pictureName={this.props.pictureName} selectedClass={'toolTip'} />
</div>);
}
} |
src/components/Delegate.js | seripap/wedding.seripap.com | import React, { Component } from 'react';
import { Link } from 'react-router';
import DocumentTitle from 'react-document-title';
import Header from './Header';
export default class Delegate extends Component {
constructor(props) {
super(props);
}
render() {
return (
<DocumentTitle title="Amanda & Dan's Wedding">
<div>
{ this.props.children }
</div>
</DocumentTitle>
);
}
}
|
packages/reactor-kitchensink/src/examples/DragAndDrop/Data/Data.js | markbrocato/extjs-reactor | import React, { Component } from 'react';
import { Panel } from '@extjs/ext-react';
import './styles.css';
Ext.require(['Ext.drag.*']);
export default class Data extends Component {
render() {
return (
<Panel
ref="mainPanel"
padding={5}
shadow
>
<div ref="source" className="data-source">
<div data-days="2" className="handle">Overnight</div>
<div data-days="7" className="handle">Expedited</div>
<div data-days="21" className="handle">Standard</div>
</div>
<div ref="target" className="data-target">Drop delivery option here</div>
</Panel>
)
}
componentDidMount() {
// When the drag starts, the describe method is used to extract the
// relevant data that the drag represents and is pushed into the info
// object for consumption by the target.
this.source = new Ext.drag.Source({
element: this.refs.source,
handle: '.handle',
constrain: this.refs.mainPanel.el,
describe: info => {
info.setData('postage-duration', info.eventTarget.getAttribute('data-days'));
},
listeners: {
dragstart: (source, info) => {
source.getProxy().setHtml(info.eventTarget.innerHTML);
}
},
proxy: {
type: 'placeholder',
cls: 'data-proxy'
}
});
this.target = new Ext.drag.Target({
element: this.refs.target,
validCls: 'data-target-valid',
listeners: {
drop: (target, info) => {
// Get the data from the info object and use it to display the expectation to the user.
info.getData('postage-duration').then(duration => {
const s = Ext.String.format('Your parcel will arrive within {0} days', duration);
Ext.Msg.alert('Delivery set', s);
})
}
}
})
}
componentWillUnmount() {
Ext.destroy(this.source, this.target);
}
} |
src/client/auth/login.react.js | cazacugmihai/este | import './login.styl';
import Component from '../components/component.react';
import React from 'react';
import exposeRouter from '../components/exposerouter';
import {focusInvalidField} from '../lib/validation';
@exposeRouter
export default class Login extends Component {
static propTypes = {
actions: React.PropTypes.object.isRequired,
auth: React.PropTypes.object.isRequired,
msg: React.PropTypes.object.isRequired,
router: React.PropTypes.func
}
onFormSubmit(e) {
e.preventDefault();
const {actions: {auth}, auth: {form}} = this.props;
auth.login(form.fields)
.then(() => this.redirectAfterLogin())
.catch(focusInvalidField(this));
}
redirectAfterLogin() {
const {router} = this.props;
const nextPath = router.getCurrentQuery().nextPath;
router.replaceWith(nextPath || 'home');
}
render() {
const {
actions: {auth: actions},
auth: {form},
msg: {auth: {form: msg}}
} = this.props;
return (
<div className="login">
<form onSubmit={::this.onFormSubmit}>
<fieldset disabled={form.disabled}>
<legend>{msg.legend}</legend>
<input
autoFocus
name="email"
onChange={actions.setFormField}
placeholder={msg.placeholder.email}
value={form.fields.email}
/>
<br />
<input
name="password"
onChange={actions.setFormField}
placeholder={msg.placeholder.password}
type="password"
value={form.fields.password}
/>
<br />
<button
children={msg.button.login}
type="submit"
/>
{form.error &&
<span className="error-message">{form.error.message}</span>
}
<div>{msg.hint}</div>
</fieldset>
</form>
</div>
);
}
}
|
src/client/Utils/LinkButton.js | KleeGroup/interactive-box | import React from 'react';
var LinkButton = React.createClass({
render: function(){
var labelStyle = {
fontSize: '200%',
textTransform: 'none',
verticalAlign: 'middle',
};
// Au click, le bouton appelle la fonction définie dans sa props "handleLinkClick"
return(
<div>
<button style = {labelStyle} className={this.props.className} onClick={this.props.handleLinkClick}>{this.props.text}</button>
</div>
);
}
});
export default LinkButton; |
src/components/dropdown.js | netlify/staticgen | import React from 'react'
import styled from '@emotion/styled'
/**
* Dropdown design credit: http://codepen.io/Thibaut/pen/Jasci
*/
const DropdownContainer = styled.div`
display: block;
width: 100%;
height: 48px;
position: relative;
overflow: hidden;
background: #f2f2f2;
border: 1px solid;
border-color: white #f7f7f7 whitesmoke;
border-radius: 3px;
&:before,
&:after {
content: '';
position: absolute;
z-index: 2;
top: 9px;
right: 10px;
width: 0;
height: 0;
border: 4px dashed;
border-color: #888888 transparent;
pointer-events: none;
@media (max-width: 600px) {
top: 19px;
}
}
&:before {
border-bottom-style: solid;
border-top: none;
}
&:after {
margin-top: 7px;
border-top-style: solid;
border-bottom: none;
}
@media (min-width: 600px) {
display: inline-block;
height: 32px;
width: 150px;
}
/* Dirty fix for Firefox adding padding where it shouldn't. */
@-moz-document url-prefix() {
select {
padding-left: 6px;
}
}
`
const DropdownSelect = styled.select`
font-size: 16px;
height: 48px;
line-height: 2;
position: relative;
width: 130%;
margin: 0;
padding: 8px 8px 8px 10px;
color: #62717a;
background: transparent;
border: 0;
border-radius: 0;
-webkit-appearance: none;
-moz-appearance: none;
/* Fix select appearance on Firefox https://gist.github.com/joaocunha/6273016/ */
text-indent: 0.01px;
text-overflow: '';
&:focus {
z-index: 3;
width: 100%;
color: #394349;
outline: none;
}
@media (min-width: 600px) {
font-size: 14px;
height: 32px;
line-height: 1.2;
}
`
const DropdownOption = styled.option`
margin: 3px;
padding: 6px 8px;
text-shadow: none;
background: #f2f2f2;
border-radius: 3px;
cursor: pointer;
`
const Dropdown = ({ emptyLabel, options, selection, onChange, field }) => (
<DropdownContainer>
<DropdownSelect value={selection} onChange={onChange}>
{emptyLabel && <DropdownOption value="">{emptyLabel}</DropdownOption>}
{options.map(option => (
<DropdownOption key={`${field ? `${field}_` : ''}${option.value}`} value={option.value}>
{option.label}
</DropdownOption>
))}
</DropdownSelect>
</DropdownContainer>
)
export default Dropdown
|
src/components/Header/index.js | wpcfan/hello-react | import React from 'react';
import { Link } from 'react-router';
import './style.css';
const Header = () => (
<header className="mdl-layout__header">
<div className="mdl-layout__header-row">
<span className="mdl-layout-title">My Todo App</span>
<div className="mdl-layout-spacer"></div>
<nav className="mdl-navigation">
<Link className="mdl-navigation__link" to="/">首页</Link>
<Link className="mdl-navigation__link" to="/todo">登录</Link>
<Link className="mdl-navigation__link" to="/about">关于我们</Link>
</nav>
</div>
</header>
);
export default Header;
|
public/app/components/DuckDapp.js | cesardeazevedo/duckdapp | import Home from './Home'
import React from 'react'
import { Link } from 'react-router'
class DuckDapp extends React.Component {
render() {
return (
<div>
<ul>
<li>
<Link to={`/home`}>Home</Link>
</li>
<li>
<Link to={`/about`}>About</Link>
</li>
</ul>
{this.props.children}
</div>
)
}
}
export default DuckDapp
|
react-app/src/components/TopMappers/TopMappers.js | grumd/osu-pps | import React, { Component } from 'react';
import toBe from 'prop-types';
import { connect } from 'react-redux';
import classNames from 'classnames';
import { withRouter } from 'react-router-dom';
import prizeGold from './prize_gold.png';
import prizeSilver from './prize_silver.png';
import prizeBronze from './prize_bronze.png';
import './top-mappers.scss';
// import { FIELDS } from 'constants/mapsData';
import CollapsibleBar from 'components/CollapsibleBar';
import { coefficientSelector, rootSelector } from 'components/Table/Table';
// import ParamLink from 'components/ParamLink/ParamLink';
import { fetchMappersData } from 'reducers/mappers';
import { fetchMapsData } from 'reducers/mapsData';
const mapStateToProps = (state, props) => {
const mode = props.match.params.mode;
return {
// overweightnessMode: rootSelector(state, props)?.searchKey?.[FIELDS.MODE],
isLoadingData: rootSelector(state, props).isLoading,
overweightnessCoefficient: coefficientSelector(state, props),
data: state.mappers[mode].data,
error: state.mappers[mode].error,
isLoading: state.mappers[mode].isLoading,
};
};
const mapDispatchToProps = {
fetchMappersData,
fetchMapsData,
};
class TopMapper extends Component {
static propTypes = {
match: toBe.object,
location: toBe.object,
data: toBe.object,
error: toBe.object,
isLoading: toBe.bool.isRequired,
overweightnessCoefficient: toBe.number,
// overweightnessMode: toBe.string,
};
componentDidMount() {
const { isLoading, data, match, isLoadingData, overweightnessCoefficient } = this.props;
if (!overweightnessCoefficient && !isLoadingData) {
this.props.fetchMapsData(match.params.mode);
}
if (!isLoading && !data) {
this.props.fetchMappersData(match.params.mode);
}
}
componentDidUpdate() {
const { match, isLoading, data, isLoadingData, overweightnessCoefficient } = this.props;
if (!overweightnessCoefficient && !isLoadingData) {
this.props.fetchMapsData(match.params.mode);
}
if (!data && !isLoading) {
this.props.fetchMappersData(match.params.mode);
}
}
render() {
const { isLoading, data, isLoadingData, error, overweightnessCoefficient } = this.props;
// const dataUsed = !data ? [] : match.params.sort === 'total' ? data.top20 : data.top20age;
const dataUsed = !data ? [] : data.top20adj;
let maxOw = 0;
dataUsed.forEach((mapper) => {
mapper.mapsRecorded.forEach((map) => {
if (map.ow > maxOw) {
maxOw = map.ow;
}
});
});
return (
<div className="top-mappers">
<header>
{(isLoading || isLoadingData) && <div className="loading">loading...</div>}
{error && error.message}
{!(isLoading || isLoadingData) && !error && (
<>
<p>
This is the list of ppest pp mappers according to my calculations.
<br /> Using overweightness calculation mode: "adjusted"
<br /> See faq for more info
</p>
</>
)}
</header>
<div className="content">
<div className="top-list">
<ul>
{dataUsed.map((mapper, mapperIndex) => {
return (
<CollapsibleBar
key={mapper.id}
className={classNames({ top: mapperIndex < 3 })}
title={
<>
<span>
<span className="place-number">{mapperIndex + 1}.</span> {mapper.name}
</span>
{mapperIndex < 3 && (
<img src={[prizeGold, prizeSilver, prizeBronze][mapperIndex]} alt=" " />
)}
</>
}
>
<div className="map-row header-row" key="header">
<div className="text">
<a href={`https://osu.ppy.sh/users/${mapper.id}`}>
Link to mapper's profile
</a>
</div>
<div className="pp" />
<div className="overweightness">
overweightness - {(mapper.points * overweightnessCoefficient).toFixed(1)}{' '}
total
</div>
</div>
{mapper.mapsRecorded.map((map) => {
return (
<div className="map-row" key={map.id}>
<div className="text">
<a href={`https://osu.ppy.sh/beatmaps/${map.id}`}>{map.text}</a>
</div>
<div className="pp">{Math.round(map.pp)}pp</div>
<div className="overweightness">
{Math.round(map.ow * overweightnessCoefficient)}
</div>
<div className="graph">
<div
style={{ width: `${Math.round((map.ow / maxOw) * 10000) / 100}%` }}
className="inner-graph"
/>
</div>
</div>
);
})}
{mapper.mapsRecorded.length === 20 && (
<div className="map-row footer-row" key="footer">
<div className="text">
<i>only showing first 20 maps</i>
</div>
</div>
)}
</CollapsibleBar>
);
})}
</ul>
</div>
</div>
</div>
);
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(TopMapper));
|
src/components/App.js | BrisklyPapers/react | import React from 'react';
import Navigation from '../containers/Navigation';
import ResultPage from '../containers/ResultPage';
import FileUploadPage from '../containers/FileUploadPage';
import SearchResults from '../containers/SearchResults';
import DropZone from '../containers/DropZone';
import IndexPageHead from './IndexPageHead';
import IndexPageDescription from './IndexPageDescription';
import Radium from 'radium';
class App extends React.Component {
render() {
return (
<div>
<div style={styles.divOnTop[this.props.cssStyle]}>
<Navigation />
<IndexPageHead />
<ResultPage>
<SearchResults />
</ResultPage>
<FileUploadPage>
<DropZone />
</FileUploadPage>
</div>
<IndexPageDescription />
</div>
)
};
}
var styles = {
divOnTop: {
index: {
backgroundImage: 'url("/home_background_1920cs.jpg")',
height: "100vh",
backgroundSize: 'cover',
backgroundPosition: 'bottom center',
backgroundRepeat: 'no-repeat',
position: "relative"
},
login: {
backgroundImage: 'url("/login_background_1920x420.jpg")',
minHeight: "100vh",
height: "100%",
backgroundSize: '100% 1px',
backgroundPosition: 'bottom center',
backgroundRepeat: 'repeat-y',
position: "relative"
}
}
};
export default Radium(App); |
src/components/navbar.js | kbrgl/kbrgl.github.io | import React from 'react'
import { Link, graphql, StaticQuery } from 'gatsby'
import Image from 'gatsby-image'
import { Container } from './grid'
import externalIcon from '../images/external.svg'
import styles from './navbar.module.css'
const Navbar = () => (
<StaticQuery
query={graphql`
query NavbarQuery {
file(relativePath: { eq: "logo.png" }) {
childImageSharp {
fixed(height: 30) {
...GatsbyImageSharpFixed
}
}
}
}
`}
render={(data) => (
<header className={styles.header}>
<Container>
<div className={styles.headerContent}>
<div>
<Link to="/" className={styles.link}>
<Image fixed={data.file.childImageSharp.fixed} />
<span className={styles.name}>Kabir Goel</span>
</Link>
</div>
<div>
<ul className={styles.list}>
<li>
<Link to="/design" activeClassName={styles.currentLink}>
Art & Design
</Link>
</li>
<li>
<Link to="/notes" activeClassName={styles.currentLink}>
Notes
</Link>
</li>
<li>
<a
target="_blank"
rel="noopener noreferrer"
href="https://www.dropbox.com/s/k3bvk9ls3yzv0a6/r%C3%A9sum%C3%A9.pdf?dl=0"
>
Résumé{' '}
<img
className={styles.external}
src={externalIcon}
alt="External link"
/>
</a>
</li>
</ul>
</div>
</div>
</Container>
</header>
)}
/>
)
export default Navbar
|
blueocean-material-icons/src/js/components/svg-icons/av/video-call.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const AvVideoCall = (props) => (
<SvgIcon {...props}>
<path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4zM14 13h-3v3H9v-3H6v-2h3V8h2v3h3v2z"/>
</SvgIcon>
);
AvVideoCall.displayName = 'AvVideoCall';
AvVideoCall.muiName = 'SvgIcon';
export default AvVideoCall;
|
fields/types/textarray/TextArrayFilter.js | ONode/keystone | import React from 'react';
import { findDOMNode } from 'react-dom';
import {
FormField,
FormInput,
FormSelect,
} from '../../../admin/client/App/elemental';
const MODE_OPTIONS = [
{ label: 'Contains', value: 'contains' },
{ label: 'Exactly', value: 'exactly' },
{ label: 'Begins with', value: 'beginsWith' },
{ label: 'Ends with', value: 'endsWith' },
];
const PRESENCE_OPTIONS = [
{ label: 'At least one element', value: 'some' },
{ label: 'No element', value: 'none' },
];
function getDefaultValue () {
return {
mode: MODE_OPTIONS[0].value,
presence: PRESENCE_OPTIONS[0].value,
value: '',
};
}
var TextArrayFilter = React.createClass({
propTypes: {
filter: React.PropTypes.shape({
mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)),
presence: React.PropTypes.oneOf(PRESENCE_OPTIONS.map(i => i.value)),
value: React.PropTypes.string,
}),
},
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
filter: getDefaultValue(),
};
},
updateFilter (value) {
this.props.onChange({ ...this.props.filter, ...value });
},
selectMode (e) {
const mode = e.target.value;
this.updateFilter({ mode });
findDOMNode(this.refs.focusTarget).focus();
},
selectPresence (e) {
const presence = e.target.value;
this.updateFilter({ presence });
findDOMNode(this.refs.focusTarget).focus();
},
updateValue (e) {
this.updateFilter({ value: e.target.value });
},
render () {
const { filter } = this.props;
const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0];
const presence = PRESENCE_OPTIONS.filter(i => i.value === filter.presence)[0];
const beingVerb = mode.value === 'exactly' ? ' is ' : ' ';
const placeholder = presence.label + beingVerb + mode.label.toLowerCase() + '...';
return (
<div>
<FormField>
<FormSelect
onChange={this.selectPresence}
options={PRESENCE_OPTIONS}
value={presence.value}
/>
</FormField>
<FormField>
<FormSelect
onChange={this.selectMode}
options={MODE_OPTIONS}
value={mode.value}
/>
</FormField>
<FormInput
autoFocus
onChange={this.updateValue}
placeholder={placeholder}
ref="focusTarget"
value={this.props.filter.value}
/>
</div>
);
},
});
module.exports = TextArrayFilter;
|
app/components/ArtistPanel.js | cqlanus/bons | import React from 'react'
import { Link } from 'react-router'
const ArtistPanel = function(props) {
return (
<div>
<Link to={`/artists/${props.artist.id}`}>
<h4>{props.artist.name}</h4>
</Link>
{/* <div className="panel panel-default">
<div className="panel-heading">
<Link to={`/artists/${props.artist.id}`}>
<h4>{props.artist.name}</h4>
</Link>
</div>
<div className="panel-body">
<Link to={`/products/${props.artist.id}`}>
<div className="row">
<img src='/snob.jpeg' width="100" height="100"/>
</div>
</Link>
</div>
</div> */}
</div>
)
}
export default ArtistPanel
|
packages/icons/src/dv/Angular.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function DvAngular(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M4.176 9.954L23.936 3l19.888 6.831L40.7 35.72 23.957 45 7.3 35.844 4.176 9.954zm28.137 23.772h4.22L23.89 6.567 11.673 33.726h4.558l2.449-6.19h10.95l2.683 6.19zm-12.026-9.817h7.766l-4.131-8.627-3.635 8.627z" />
</IconBase>
);
}
export default DvAngular;
|
src/components/news/highlight.js | adrienlozano/stephaniewebsite | import React from 'react';
import Typography from '~/components/typography';
import LinkButton from '~/components/link-button';
import { Box, Flex } from 'rebass';
import styled from 'styled-components';
import format from 'date-fns/format';
const StyledImage = styled.img`
max-width: 100%;
`
export default ({className, article, ...rest}) => {
article = article ? article : {};
let image = article.image ? (<StyledImage src={article.image}></StyledImage>) : null;
return (
<Box className={className} {...rest}>
<Typography component="h4" pb={0} mb={0}>{article.title}</Typography>
<Typography f={1} pt={0} mt={1} color="secondaryAccent">{ format(article.date, "DD MMM, YYYY")}</Typography>
{image}
<Typography>{article.excerpt}</Typography>
<LinkButton href={article.slug}>Read More</LinkButton>
</Box>
)
} |
packages/react-scripts/fixtures/kitchensink/src/features/env/ExpandEnvVariables.js | liamhu/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
export default () => (
<span>
<span id="feature-expand-env-1">{process.env.REACT_APP_BASIC}</span>
<span id="feature-expand-env-2">{process.env.REACT_APP_BASIC_EXPAND}</span>
<span id="feature-expand-env-3">
{process.env.REACT_APP_BASIC_EXPAND_SIMPLE}
</span>
<span id="feature-expand-env-existing">
{process.env.REACT_APP_EXPAND_EXISTING}
</span>
</span>
);
|
react/ShowMore/ShowMore.js | seekinternational/seek-asia-style-guide | import styles from './ShowMore.less';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, ChevronIcon } from 'seek-asia-style-guide/react';
import classnames from 'classnames';
const COLOR_GREY = 'grey';
const COLOR_WHITE = 'white';
const POSITION_CENTER = 'center';
const POSITION_LEFT = 'left';
export default class ShowMore extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
showLessHeight: PropTypes.number.isRequired,
lblShowMore: PropTypes.string,
lblShowLess: PropTypes.string,
disable: PropTypes.bool,
position: PropTypes.oneOf([POSITION_LEFT, POSITION_CENTER]),
color: PropTypes.oneOf([COLOR_WHITE, COLOR_GREY]),
onPanelOpen: PropTypes.func,
onPanelToggle: PropTypes.func
};
static defaultProps = {
lblShowMore: 'Show more',
lblShowLess: 'Show less',
color: COLOR_WHITE,
position: POSITION_CENTER
};
constructor(props) {
super(props);
this.state = {
contentHeight: 0,
isPanelOpened: false
};
this.handleClick = this.handleClick.bind(this);
this.updateDimensions = this.updateDimensions.bind(this);
this.myRef = React.createRef();
}
componentDidMount() {
window.addEventListener('resize', this.updateDimensions);
this.updateDimensions();
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions);
}
updateDimensions() {
this.setState({
contentHeight: this.myRef.current.clientHeight
});
}
handleClick(e) {
const { isPanelOpened } = this.state;
const { onPanelOpen, onPanelToggle = () => {} } = this.props;
e.preventDefault();
if (!isPanelOpened) {
if (typeof onPanelOpen === 'function') {
console.warn('Property of onPanelOpen has been deprecated. Use onPanelToggle instead.');
onPanelOpen();
}
}
onPanelToggle({ status: (!isPanelOpened ? 'open' : 'close') });
this.setState({
isPanelOpened: !isPanelOpened
});
}
render() {
const { isPanelOpened, contentHeight } = this.state;
const { disable, color, showLessHeight, children, lblShowLess, lblShowMore, position } = this.props;
const panelHeight = (isPanelOpened || disable) ? contentHeight : showLessHeight;
return (
<div>
<div
className={styles.panel}
style={{ maxHeight: `${panelHeight}px` }} >
<div ref={this.myRef}>{children}</div>
</div>
{
!disable && contentHeight > showLessHeight && (
<div
className={classnames({
[styles.outCanvasGradientMaskTopWhite]: !isPanelOpened && color === COLOR_WHITE,
[styles.outCanvasGradientMaskTopGrey]: !isPanelOpened && color === COLOR_GREY
})}>
<Button
id='btnShowMore'
color='hyperlink'
className={classnames(styles.button, {
[styles.buttonGrey]: color === COLOR_GREY,
[styles.buttonWhite]: color === COLOR_WHITE,
[styles.buttonLeft]: position === POSITION_LEFT
})}
onClick={this.handleClick}>
<span>
{isPanelOpened ? lblShowLess : lblShowMore}
</span>
<span> <span><ChevronIcon direction={isPanelOpened ? 'up' : 'down'} /></span></span>
</Button>
</div>
)
}
</div>
);
}
}
|
src/components/source/mediaSource/form/SourceFeedForm.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { Field, reduxForm } from 'redux-form';
import { FormattedMessage, injectIntl } from 'react-intl';
import { Row, Col } from 'react-flexbox-grid/lib';
import MenuItem from '@material-ui/core/MenuItem';
import withIntlForm from '../../../common/hocs/IntlForm';
import AppButton from '../../../common/AppButton';
import { emptyString, invalidUrl } from '../../../../lib/formValidators';
import messages from '../../../../resources/messages';
const localMessages = {
typeSyndicated: { id: 'source.feed.add.type.syndicated', defaultMessage: 'Syndicated' },
typeSyndicatedDesc: { id: 'source.feed.add.type.syndicatedDesc', defaultMessage: ' - The RSS or Atom feed will be checked every day and any new stories will be downloaded.' },
typeWebPage: { id: 'source.feed.add.type.webpage', defaultMessage: 'Web Page' },
typeWebPageDesc: { id: 'source.feed.add.type.webpageDesc', defaultMessage: ' - The URL will be downloaded once a week. Each download will be treated as a new story.' },
typePodcast: { id: 'source.feed.add.type.podcast', defaultMessage: 'Podcast' },
typePodcastDesc: { id: 'source.feed.add.type.podcastDesc', defaultMessage: ' - The RSS or Atom feed will be checked every day for new "enclosures" (attached media files). Any new items will be downloaded and converted to a standard audio file for transcription. Transcribed text will be saved as new stories.' },
feedIsActive: { id: 'source.feed.add.active', defaultMessage: 'Feed is Active' },
urlInvalid: { id: 'source.feed.url.invalid', defaultMessage: 'That isn\'t a valid feed URL. Please enter just the full url of one RSS or Atom feed.' },
};
const SourceFeedForm = (props) => {
const { renderTextField, renderSelect, renderCheckbox, buttonLabel, handleSubmit, onSave, pristine, submitting } = props;
const { formatMessage } = props.intl;
return (
<form className="app-form source-feed-form" name="sourceFeedForm" onSubmit={handleSubmit(onSave.bind(this))}>
<Row>
<Col md={2}>
<span className="label unlabeled-field-label">
<FormattedMessage {...messages.feedName} />
</span>
</Col>
<Col md={8}>
<Field
name="name"
component={renderTextField}
fullWidth
/>
</Col>
</Row>
<Row>
<Col md={2}>
<span className="label unlabeled-field-label">
<FormattedMessage {...messages.feedUrl} />
</span>
</Col>
<Col md={8}>
<Field
name="url"
component={renderTextField}
fullWidth
/>
</Col>
</Row>
<Row>
<Col md={2}>
<span className="label unlabeled-field-label">
<FormattedMessage {...messages.feedType} />
</span>
</Col>
<Col md={5} className="feedTypes">
<Field
name="type"
component={renderSelect}
renderValue={(value) => {
if (value === 'syndicated') {
return <FormattedMessage {...localMessages.typeSyndicated} />;
}
if (value === 'web_page') {
return <FormattedMessage {...localMessages.typeWebPage} />;
}
return <FormattedMessage {...localMessages.typePodcast} />;
}}
>
<MenuItem key="syndicated" value="syndicated">
<Col md={1}><FormattedMessage {...localMessages.typeSyndicated} /> </Col>
<Col md={8}><p style={{ whiteSpace: 'normal', width: 800 }}><FormattedMessage {...localMessages.typeSyndicatedDesc} /></p></Col>
</MenuItem>
<MenuItem key="web_page" value="web_page">
<Col md={1}><FormattedMessage {...localMessages.typeWebPage} /> </Col>
<Col md={8}><p style={{ whiteSpace: 'normal', width: 800 }}><FormattedMessage {...localMessages.typeWebPageDesc} /></p></Col>
</MenuItem>
<MenuItem key="podcast" value="podcast">
<Col md={1}><FormattedMessage {...localMessages.typePodcast} /> </Col>
<Col md={8}><p style={{ whiteSpace: 'normal', width: 800 }}><FormattedMessage {...localMessages.typePodcastDesc} /></p></Col>
</MenuItem>
</Field>
</Col>
</Row>
<Row>
<Col md={2}>
<span className="label unlabeled-field-label">
<FormattedMessage {...messages.feedIsActive} />
</span>
</Col>
<Col md={8}>
<Field
name="active"
component={renderCheckbox}
fullWidth
label={formatMessage(messages.feedIsActive)}
value
/>
</Col>
</Row>
<AppButton
type="submit"
className="source-feed-updated"
label={buttonLabel}
primary
disabled={pristine || submitting}
/>
</form>
);
};
SourceFeedForm.propTypes = {
// from compositional chain
intl: PropTypes.object.isRequired,
renderTextField: PropTypes.func.isRequired,
renderSelect: PropTypes.func.isRequired,
renderCheckbox: PropTypes.func.isRequired,
initialValues: PropTypes.object,
handleSubmit: PropTypes.func,
pristine: PropTypes.bool.isRequired,
submitting: PropTypes.bool.isRequired,
onSave: PropTypes.func.isRequired,
buttonLabel: PropTypes.string.isRequired,
};
function validate(values) {
const errors = {};
if (emptyString(values.type)) {
errors.type = messages.required;
}
if (emptyString(values.url)) {
errors.url = messages.required;
}
if (invalidUrl(values.url)) {
errors.url = localMessages.urlInvalid;
}
return errors;
}
const reduxFormConfig = {
form: 'sourceFeedForm',
validate,
};
export default
injectIntl(
withIntlForm(
reduxForm(reduxFormConfig)(
SourceFeedForm
)
)
);
|
packages/flow-runtime-docs/src/components/InstallInstruction.js | codemix/flow-runtime | /* @flow */
import React, { Component } from 'react';
import {observable, computed} from 'mobx';
import {observer} from 'mobx-react';
type Props = {
devPackageNames?: string[];
packageNames?: string[];
};
@observer
export default class InstallInstruction extends Component<Props, void> {
@observable showYarn: boolean = false;
@computed get installCode (): string {
const {devPackageNames, packageNames} = this.props;
const output = [];
if (this.showYarn) {
if (packageNames) {
output.push(...packageNames.map(name => `yarn add ${name}`));
}
if (devPackageNames) {
output.push(...devPackageNames.map(name => `yarn add --dev ${name}`));
}
}
else {
if (packageNames) {
output.push(...packageNames.map(name => `npm install ${name}`));
}
if (devPackageNames) {
output.push(...devPackageNames.map(name => `npm install --dev ${name}`));
}
}
return output.join('\n');
}
handleClickNpm = (e: SyntheticMouseEvent) => {
e.preventDefault();
this.showYarn = false;
};
handleClickYarn = (e: SyntheticMouseEvent) => {
e.preventDefault();
this.showYarn = true;
};
render() {
return (
<div>
<p className="lead">
Install with
{' '}
{this.showYarn ? <a href="#" onClick={this.handleClickNpm}>npm</a> : 'npm'}
{' or '}
{this.showYarn ? 'yarn' : <a href="#" onClick={this.handleClickYarn}>yarn</a>}.</p>
<pre>{this.installCode}</pre>
</div>
);
}
}
|
app/javascript/mastodon/features/compose/components/upload.js | pointlessone/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import classNames from 'classnames';
const messages = defineMessages({
description: { id: 'upload_form.description', defaultMessage: 'Describe for the visually impaired' },
});
export default @injectIntl
class Upload extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
intl: PropTypes.object.isRequired,
onUndo: PropTypes.func.isRequired,
onDescriptionChange: PropTypes.func.isRequired,
onOpenFocalPoint: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
};
state = {
hovered: false,
focused: false,
dirtyDescription: null,
};
handleKeyDown = (e) => {
if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) {
this.handleSubmit();
}
}
handleSubmit = () => {
this.handleInputBlur();
this.props.onSubmit(this.context.router.history);
}
handleUndoClick = e => {
e.stopPropagation();
this.props.onUndo(this.props.media.get('id'));
}
handleFocalPointClick = e => {
e.stopPropagation();
this.props.onOpenFocalPoint(this.props.media.get('id'));
}
handleInputChange = e => {
this.setState({ dirtyDescription: e.target.value });
}
handleMouseEnter = () => {
this.setState({ hovered: true });
}
handleMouseLeave = () => {
this.setState({ hovered: false });
}
handleInputFocus = () => {
this.setState({ focused: true });
}
handleClick = () => {
this.setState({ focused: true });
}
handleInputBlur = () => {
const { dirtyDescription } = this.state;
this.setState({ focused: false, dirtyDescription: null });
if (dirtyDescription !== null) {
this.props.onDescriptionChange(this.props.media.get('id'), dirtyDescription);
}
}
render () {
const { intl, media } = this.props;
const active = this.state.hovered || this.state.focused;
const description = this.state.dirtyDescription || (this.state.dirtyDescription !== '' && media.get('description')) || '';
const focusX = media.getIn(['meta', 'focus', 'x']);
const focusY = media.getIn(['meta', 'focus', 'y']);
const x = ((focusX / 2) + .5) * 100;
const y = ((focusY / -2) + .5) * 100;
return (
<div className='compose-form__upload' tabIndex='0' onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} onClick={this.handleClick} role='button'>
<Motion defaultStyle={{ scale: 0.8 }} style={{ scale: spring(1, { stiffness: 180, damping: 12 }) }}>
{({ scale }) => (
<div className='compose-form__upload-thumbnail' style={{ transform: `scale(${scale})`, backgroundImage: `url(${media.get('preview_url')})`, backgroundPosition: `${x}% ${y}%` }}>
<div className={classNames('compose-form__upload__actions', { active })}>
<button className='icon-button' onClick={this.handleUndoClick}><i className='fa fa-times' /> <FormattedMessage id='upload_form.undo' defaultMessage='Delete' /></button>
{media.get('type') === 'image' && <button className='icon-button' onClick={this.handleFocalPointClick}><i className='fa fa-crosshairs' /> <FormattedMessage id='upload_form.focus' defaultMessage='Crop' /></button>}
</div>
<div className={classNames('compose-form__upload-description', { active })}>
<label>
<span style={{ display: 'none' }}>{intl.formatMessage(messages.description)}</span>
<input
placeholder={intl.formatMessage(messages.description)}
type='text'
value={description}
maxLength={420}
onFocus={this.handleInputFocus}
onChange={this.handleInputChange}
onBlur={this.handleInputBlur}
onKeyDown={this.handleKeyDown}
/>
</label>
</div>
</div>
)}
</Motion>
</div>
);
}
}
|
analysis/warlockaffliction/src/modules/soulshards/SoulShardDetails.js | yajinni/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import ResourceBreakdown from 'parser/shared/modules/resources/resourcetracker/ResourceBreakdown';
import SPELLS from 'common/SPELLS';
import { Panel } from 'interface';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import Statistic from 'parser/ui/Statistic';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import { t } from '@lingui/macro';
import '@wowanalyzer/warlock/src/SoulShardDetails.css';
import SoulShardTracker from './SoulShardTracker';
class SoulShardDetails extends Analyzer {
get suggestionThresholds() {
const shardsWasted = this.soulShardTracker.wasted;
const shardsWastedPerMinute = (shardsWasted / this.owner.fightDuration) * 1000 * 60;
return {
actual: shardsWastedPerMinute,
isGreaterThan: {
minor: 5 / 10, // 5 shards in 10 minute fight
average: 5 / 3, // 5 shards in 3 minute fight
major: 10 / 3, // 10 shards in 3 minute fight
},
style: 'decimal',
};
}
static dependencies = {
soulShardTracker: SoulShardTracker,
};
suggestions(when) {
const shardsWasted = this.soulShardTracker.wasted;
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => suggest('You are wasting Soul Shards. Try to use them and not let them cap and go to waste unless you\'re preparing for bursting adds etc.')
.icon(SPELLS.SOUL_SHARDS.icon)
.actual(t({
id: "warlock.affliction.suggestions.soulShards.wastedPerMinute",
message: `${shardsWasted} Soul Shards wasted (${actual.toFixed(2)} per minute)`
}))
.recommended(`< ${recommended.toFixed(2)} Soul Shards per minute wasted are recommended`));
}
statistic() {
const shardsWasted = this.soulShardTracker.wasted;
return (
<Statistic
position={STATISTIC_ORDER.CORE(3)}
size="flexible"
tooltip={(<>In order for Focus Magic to compete with the other talents on that row, you need to ensure you are getting as much uptime out of the buff as possible. Therefore, if you forget to put the buff on another player or if they player you gave it to is not getting crits very often, then you might need to consider giving the buff to someone else. Ideally, you should aim to trade buffs with another mage who has also taken Focus Magic so you both get the full benefit.</>)}
>
<BoringSpellValueText spell={SPELLS.SOUL_SHARDS}>
{shardsWasted} <small>Wasted Soul Shards</small>
</BoringSpellValueText>
</Statistic>
);
}
tab() {
return {
title: 'Soul Shard usage',
url: 'soul-shards',
render: () => (
<Panel>
<ResourceBreakdown
tracker={this.soulShardTracker}
showSpenders
/>
</Panel>
),
};
}
}
export default SoulShardDetails;
|
src/Dropdown.js | mattBlackDesign/react-materialize | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import idgen from './idgen';
import cx from 'classnames';
const classes = {
'dropdown-content': true
};
class Dropdown extends Component {
constructor (props) {
super(props);
this.renderTrigger = this.renderTrigger.bind(this);
}
componentDidMount () {
const options = this.props.options || {};
$(this._trigger).dropdown(options);
}
componentWillUnmount () {
$(this._trigger).off();
}
render () {
const { children, className, ...props } = this.props;
this.idx = 'dropdown_' + idgen();
delete props.trigger;
delete props.options;
return (
<span>
{ this.renderTrigger() }
<ul {...props} className={cx(classes, className)} id={this.idx}>
{ children }
</ul>
</span>
);
}
renderTrigger () {
const { trigger } = this.props;
return React.cloneElement(trigger, {
ref: (t) => (this._trigger = `[data-activates=${this.idx}]`),
className: cx(trigger.props.className, 'dropdown-button'),
'data-activates': this.idx
});
}
}
Dropdown.propTypes = {
/**
* The node to trigger the dropdown
*/
trigger: PropTypes.node.isRequired,
children: PropTypes.node,
className: PropTypes.string,
/**
* Options hash for the dropdown
* more info: http://materializecss.com/dropdown.html#options
*/
options: PropTypes.shape({
inDuration: PropTypes.number,
outDuration: PropTypes.number,
constrain_width: PropTypes.bool,
hover: PropTypes.bool,
gutter: PropTypes.number,
belowOrigin: PropTypes.bool,
alignment: PropTypes.oneOf(['left', 'right'])
})
};
export default Dropdown;
|
front_end/src/pages/Tiles/TileCreatePage.js | mozilla/splice | import React, { Component } from 'react';
import { connect } from 'react-redux';
import reactMixin from 'react-mixin';
import { Link, Lifecycle } from 'react-router';
import { updateDocTitle } from 'actions/App/AppActions';
import { fetchHierarchy } from 'actions/App/BreadCrumbActions';
import { fetchAccounts } from 'actions/Accounts/AccountActions';
import TileForm from 'components/Tiles/TileForm/TileForm';
@reactMixin.decorate(Lifecycle)
class TileCreatePage extends Component {
constructor(props) {
super(props);
this.routerWillLeave = this.routerWillLeave.bind(this);
}
componentWillMount(){
this.props.Campaign.rows = [];
this.props.AdGroup.rows = [];
this.props.Tile.details = {};
}
componentDidMount(){
this.fetchTileDetails(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.params.adGroupId !== this.props.params.adGroupId) {
this.fetchTileDetails(nextProps);
}
}
render() {
let output = null;
if(this.props.AdGroup.details){
output = (
<div>
<div className="form-module">
<div className="form-module-header">{(this.props.params.adGroupId && this.props.AdGroup.details.name) ? this.props.AdGroup.details.name + ': ' : '' }Create Tile</div>
<div className="form-module-body">
<TileForm editMode={false} {...this.props}/>
</div>
</div>
</div>
);
}
return output;
}
routerWillLeave() {
if(this.props.App.formChanged){
return 'Your progress is not saved. Are you sure you want to leave?';
}
}
fetchTileDetails(props) {
const { dispatch } = props;
updateDocTitle('Create Tile');
if(this.props.params.adGroupId !== undefined) {
dispatch(fetchHierarchy('adGroup', props))
.then(() => {
if (this.props.AdGroup.details.id) {
updateDocTitle(this.props.AdGroup.details.name + ': Create Tile');
}
else{
props.history.replaceState(null, '/error404');
}
});
}
else {
dispatch(fetchAccounts());
}
}
}
TileCreatePage.propTypes = {};
// Which props do we want to inject, given the global state?
function select(state) {
return {
App: state.App,
Account: state.Account,
Campaign: state.Campaign,
AdGroup: state.AdGroup,
Tile: state.Tile,
Init: state.Init
};
}
// Wrap the component to inject dispatch and state into it
export default connect(select)(TileCreatePage);
|
fields/components/NestedFormField.js | Adam14Four/keystone | import React from 'react';
import { StyleSheet, css } from 'aphrodite/no-important';
import { FormField, FormLabel } from 'elemental';
import theme from '../../admin/client/theme';
function NestedFormField ({ children, className, label, ...props }) {
return (
<FormField {...props}>
<FormLabel className={css(classes.label)}>{label}</FormLabel>
{children}
</FormField>
);
};
const classes = StyleSheet.create({
label: {
color: theme.color.gray40,
fontSize: theme.font.size.small,
paddingLeft: '1em',
},
});
module.exports = NestedFormField;
|
node_modules/react-router-dom/es/HashRouter.js | Sweetgrassbuffalo/ReactionSweeGrass-v2 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React from 'react';
import PropTypes from 'prop-types';
import createHistory from 'history/createHashHistory';
import { Router } from 'react-router';
/**
* The public API for a <Router> that uses window.location.hash.
*/
var HashRouter = function (_React$Component) {
_inherits(HashRouter, _React$Component);
function HashRouter() {
var _temp, _this, _ret;
_classCallCheck(this, HashRouter);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret);
}
HashRouter.prototype.render = function render() {
return React.createElement(Router, { history: this.history, children: this.props.children });
};
return HashRouter;
}(React.Component);
HashRouter.propTypes = {
basename: PropTypes.string,
getUserConfirmation: PropTypes.func,
hashType: PropTypes.oneOf(['hashbang', 'noslash', 'slash']),
children: PropTypes.node
};
export default HashRouter; |
packages/es-components/src/components/containers/notification/MessageNotification.js | jrios/es-components | import React from 'react';
import PropTypes from 'prop-types';
import { noop } from 'lodash';
import { useNotification } from './useNotification';
const Notification = useNotification('messageOnly');
function MessageNotification(props) {
return <Notification {...props} />;
}
MessageNotification.propTypes = {
/* The type of notification to render */
type: PropTypes.oneOf(['success', 'info', 'warning', 'danger', 'advisor'])
.isRequired,
/* Display an icon in the notification on a screen >= 768px */
includeIcon: PropTypes.bool,
/* Display a dismiss button that will close the notification */
isDismissable: PropTypes.bool,
role: PropTypes.oneOf(['dialog', 'alert']),
/* Function to execute when the dialog is closed */
onDismiss: PropTypes.func,
children: PropTypes.node
};
MessageNotification.defaultProps = {
includeIcon: false,
isDismissable: false,
children: null,
role: 'dialog',
onDismiss: noop
};
export default MessageNotification;
|
docs/app/Examples/elements/List/Variations/index.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Message } from 'semantic-ui-react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const ListVariations = () => (
<ExampleSection title='Types'>
<ComponentExample
title='Horizontal'
description='A list can be formatted to have items appear horizontally'
examplePath='elements/List/Variations/ListExampleHorizontal'
/>
<ComponentExample examplePath='elements/List/Variations/ListExampleHorizontalOrdered' />
<ComponentExample examplePath='elements/List/Variations/ListExampleHorizontalBulleted' />
<ComponentExample
title='Inverted'
description='A list can be inverted to appear on a dark background'
examplePath='elements/List/Variations/ListExampleInverted'
/>
<ComponentExample
title='Selection'
description='A selection list formats list items as possible choices'
examplePath='elements/List/Variations/ListExampleSelection'
/>
<ComponentExample
title='Animated'
description='A list can animate to set the current item apart from the list'
examplePath='elements/List/Variations/ListExampleAnimated'
>
<Message info>
Be sure content can fit on one line, otherwise text content will reflow when hovered.
</Message>
</ComponentExample>
<ComponentExample
title='Relaxed'
description='A list can relax its padding to provide more negative space'
examplePath='elements/List/Variations/ListExampleRelaxed'
/>
<ComponentExample examplePath='elements/List/Variations/ListExampleRelaxedHorizontal' />
<ComponentExample examplePath='elements/List/Variations/ListExampleVeryRelaxed' />
<ComponentExample examplePath='elements/List/Variations/ListExampleVeryRelaxedHorizontal' />
<ComponentExample
title='Divided'
description='A list can show divisions between content'
examplePath='elements/List/Variations/ListExampleDivided'
/>
<ComponentExample
title='Celled'
description='A list can divide its items into cells'
examplePath='elements/List/Variations/ListExampleCelled'
/>
<ComponentExample examplePath='elements/List/Variations/ListExampleCelledOrdered' />
<ComponentExample examplePath='elements/List/Variations/ListExampleCelledHorizontal' />
<ComponentExample
title='Size'
description='A list can vary in size'
examplePath='elements/List/Variations/ListExampleSizes'
/>
</ExampleSection>
)
export default ListVariations
|
src/repository/screens/repository-code-list.screen.js | Antoine38660/git-point | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { StyleSheet, FlatList, View, Text } from 'react-native';
import { ListItem } from 'react-native-elements';
import { ViewContainer, LoadingListItem } from 'components';
import { colors, fonts, normalize } from 'config';
import { getContents } from '../repository.action';
const mapStateToProps = state => ({
repository: state.repository.repository,
contents: state.repository.contents,
isPendingContents: state.repository.isPendingContents,
});
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
getContents,
},
dispatch
);
const styles = StyleSheet.create({
title: {
color: colors.black,
...fonts.fontPrimaryLight,
},
titleBold: {
color: colors.black,
...fonts.fontPrimarySemiBold,
},
textContainer: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
noCodeTitle: {
fontSize: normalize(18),
textAlign: 'center',
},
container: {
borderBottomColor: colors.greyLight,
borderBottomWidth: 1,
},
});
class RepositoryCodeList extends Component {
props: {
getContents: Function,
repository: Object,
contents: Array,
isPendingContents: boolean,
navigation: Object,
};
componentDidMount() {
const navigationParams = this.props.navigation.state.params;
const url = navigationParams.topLevel
? this.props.repository.contents_url.replace('{+path}', '')
: navigationParams.content.url;
const level = navigationParams.topLevel
? 'top'
: navigationParams.content.name;
this.props.getContents(url, level);
}
sortedContents = contents => {
if (contents) {
return contents.sort((a, b) => {
return a.type === b.type ? 0 : a.type === 'dir' ? -1 : 1; // eslint-disable-line no-nested-ternary
});
}
return null;
};
goToPath = content => {
if (content.type === 'dir') {
return this.props.navigation.navigate('RepositoryCodeList', {
topLevel: false,
content,
});
}
return this.props.navigation.navigate('RepositoryFile', {
content,
});
};
keyExtractor = item => {
return item.path;
};
renderItem = ({ item }) => (
<ListItem
title={item.name}
leftIcon={{
name: item.type === 'dir' ? 'file-directory' : 'file',
color: colors.grey,
type: 'octicon',
}}
titleStyle={item.type === 'dir' ? styles.titleBold : styles.title}
containerStyle={styles.container}
onPress={() => this.goToPath(item)}
underlayColor={colors.greyLight}
/>
);
render() {
const { contents, isPendingContents, navigation } = this.props;
const currentContents = navigation.state.params.topLevel
? contents.top
: contents[navigation.state.params.content.name];
return (
<ViewContainer>
{isPendingContents &&
[...Array(15)].map((item, index) => <LoadingListItem key={index} />) // eslint-disable-line react/no-array-index-key
}
{!isPendingContents &&
currentContents &&
currentContents.length > 0 && (
<FlatList
data={this.sortedContents(currentContents)}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
/>
)}
{!isPendingContents &&
navigation.state.params.topLevel &&
currentContents &&
currentContents.message && (
<View style={styles.textContainer}>
<Text style={styles.noCodeTitle}>{currentContents.message}</Text>
</View>
)}
</ViewContainer>
);
}
}
export const RepositoryCodeListScreen = connect(
mapStateToProps,
mapDispatchToProps
)(RepositoryCodeList);
|
src/components/SCSmallEntry/SCSmallEntry.js | bbonny/movie-matching | import React, { Component } from 'react';
import $ from 'jquery';
import Col from 'react-bootstrap/lib/Col';
import Row from 'react-bootstrap/lib/Row';
import Button from 'react-bootstrap/lib/Button';
class SCSmallEntry extends Component {
addToWishList = (id) => {
$.post('/api/whish?movie_id=' + this.props.result.id);
}
render() {
return (
<div>
<Row>
<Col xs={8} md={8}>
<a href={this.props.result.url} target='_BLANK'>
{this.props.result.label} ({this.props.result.description})
</a>
</Col>
<Col xs={4} md={4}>
<Button onClick={this.addToWishList}>
To Whish List
</Button>
</Col>
</Row>
</div>
)
}
}
export default SCSmallEntry;
|
client/src/components/Home/Leaderboard.js | patteri/slave-cardgame | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router';
import { Row, Col } from 'react-bootstrap';
import StatList from '../Stats/StatList';
const Leaderboard = ({ stats, ...props }) => (
<Row className="Leaderboard">
<Col {...props}>
<StatList
header="Leaderboard"
stats={stats.averageGamePoints}
isPercent
showDetails={false}
/>
<div className="Stats-link">
<Link to="/stats">Show more</Link>
</div>
</Col>
</Row>
);
Leaderboard.propTypes = {
stats: PropTypes.object.isRequired
};
export default Leaderboard;
|
tests/react_imports/es-default.js | JonathanUsername/flow | import React from 'react';
(React.Component: Object); // OK
(React.Component: number); // Error
('Hello, world!': React.Node); // Error: Not in default export.
({}: React.Node); // Error: Not in default export.
(null: React.Missing); // Error: Not in default export.
|
Ethereum-based-Roll4Win/node_modules/react-bootstrap/es/Table.js | brett-harvey/Smart-Contracts | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
import classNames from 'classnames';
import React from 'react';
import { createBootstrapComponent } from './ThemeProvider';
var Table =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Table, _React$Component);
function Table() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = Table.prototype;
_proto.render = function render() {
var _this$props = this.props,
bsPrefix = _this$props.bsPrefix,
className = _this$props.className,
striped = _this$props.striped,
bordered = _this$props.bordered,
hover = _this$props.hover,
size = _this$props.size,
variant = _this$props.variant,
responsive = _this$props.responsive,
props = _objectWithoutPropertiesLoose(_this$props, ["bsPrefix", "className", "striped", "bordered", "hover", "size", "variant", "responsive"]);
var classes = classNames(bsPrefix, className, variant && bsPrefix + "-" + variant, size && bsPrefix + "-" + size, striped && bsPrefix + "-striped", bordered && bsPrefix + "-bordered", hover && bsPrefix + "-hover");
var table = React.createElement("table", _extends({}, props, {
className: classes
}));
if (responsive) {
var responsiveClass = bsPrefix + "-responsive";
if (typeof responsive === 'string') {
responsiveClass = responsiveClass + "-" + responsive;
}
return React.createElement("div", {
className: responsiveClass
}, table);
}
return table;
};
return Table;
}(React.Component);
export default createBootstrapComponent(Table, 'table'); |
page/src/containers/Body.js | swpark6/Dumbledore | import React, { Component } from 'react';
import { Grid, Search, Loader, Sticky } from 'semantic-ui-react';
import _ from 'lodash';
import Table from '../components/Table';
import { getBot, getAllStudent } from '../helper/fetch';
import './Body.css';
class Body extends Component {
constructor(props) {
super(props);
this.state = {
botIsLoading: false,
bots: [],
studentIsLoading: false,
students: [],
value: '',
errMessage: ''
};
this.handleResultSelect = this.handleResultSelect.bind(this);
this.handleSearchChange = this.handleSearchChange.bind(this);
}
async handleResultSelect(e, { result }) {
this.setState({
value: result.botName,
studentIsLoading: true
});
try {
const students = await getAllStudent(result.id);
this.setState({ students, studentIsLoading: false });
} catch (error) {
this.setState({ errMessage: error.message, studentIsLoading: false });
}
}
async handleSearchChange(e, { value }) {
this.setState({ botIsLoading: true, value });
const results = await getBot();
const re = new RegExp(_.escapeRegExp(this.state.value), 'i');
const isMatch = result => re.test(result.botName);
this.setState({
botIsLoading: false,
bots: _.filter(results, isMatch),
});
}
render() {
const {
botIsLoading, studentIsLoading, value, bots, students, errMessage
} = this.state;
const resultRenderer = ({ botName }) => <div className="searchBox">{botName}</div>;
const studentsTable = students.length > 0 ? <Table data={students} /> : '';
return (
<Grid.Row>
<Grid.Row centered className="search">
<Sticky>
<Search
loading={botIsLoading}
onResultSelect={this.handleResultSelect}
onSearchChange={this.handleSearchChange}
results={bots}
value={value}
input={{ placeholder: 'what is bot name...?' }}
resultRenderer={resultRenderer}
fluid
{...this.props}
/>
</Sticky>
</Grid.Row>
{errMessage}
<Grid.Row>
{studentsTable}
{studentIsLoading ? <Loader active size="big">Loading</Loader> : ''}
</Grid.Row>
</Grid.Row>
);
}
}
export default Body;
|
lib/browserRequirements.js | jirokun/survey-designer-js | /* eslint-env browser,jquery */
import React from 'react';
export function RequiredBrowserNoticeForEditor() {
return (
<div>
<p>
ご利用の環境ではこのページを表示することができません。<br />
以下のいずれかのブラウザをご利用ください。</p>
<ul>
<li>Google Chrome 最新版</li>
<li>Firefox 最新版</li>
<li>Microsoft Edge</li>
<li>Microsoft Internet Explorer 11</li>
</ul>
</div>
);
}
export function RequiredBrowserNoticeForRuntime() {
return (
<div>
<p>
ご利用の環境ではこのページを表示することができません。<br />
以下のいずれかのブラウザをご利用ください。</p>
<ul>
<li>Google Chrome 最新版</li>
<li>Firefox 最新版</li>
<li>Microsoft Edge</li>
<li>Microsoft Internet Explorer 9以上</li>
</ul>
</div>
);
}
|
dashboard-ui/app/components/drawer/cloudTable.js | CloudBoost/cloudboost | import React from 'react';
import { Card, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card';
class CloudTable extends React.Component {
constructor () {
super();
this.state = {
};
}
copyToClipboard = (element) => () => {
var $temp = $('<input>');
$('body').append($temp);
$temp.val($(element).text()).select();
document.execCommand('copy');
$temp.remove();
}
render () {
let TABLE = 'Role';
return (
<div>
<div className='method'>
<a id='CloudTable-constructor' name='CloudTable-constructor' className='section-anchor' />
<Card style={{ marginBottom: 16 }} onExpandChange={this.handleExpandChange}>
<CardHeader
title='Create a CloudTable'
actAsExpander
showExpandableButton
style={{ backgroundColor: '#f4f4f4', padding: '10px 16px' }}
/>
<CardMedia>
<div className='method-example' id='api-summary-example'>
<span className='pull-right flag fa fa-clipboard' title='Copy..' onClick={this.copyToClipboard('#pre_create')} />
<pre id='pre_create'>
<span className='code-red'>{
`var`}</span>{` table = `}<span className='code-red'>{`new`}</span>{` CB.CloudTable(`}<span className='code-yellow'>{`"${TABLE}"`}</span>{`);`
}
</pre>
</div>{/* method-example */}
</CardMedia>
<CardTitle title='CloudTable( tableName )' expandable
subtitle='All the tables are in CloudBoost is a type of CloudTable. Pass the table name as a parameter to initialize a CloudTable.' />
<CardText expandable>
<div className='method-description'>
<div className='method-list'>
<h6>Arguments</h6>
<dl className='argument-list'>
<dt>tableName</dt>
<dd className>String <span>Table should not start with a number and should not contain any spaces and special characters.</span></dd>
<div className='clearfix' />
</dl>
<h6>Returns</h6>
<p>A CloudTable object</p>
</div>
</div>
</CardText>
</Card>
<a id='CloudTable-save' name='CloudTable-save' className='section-anchor' />
<Card style={{ marginBottom: 16 }} onExpandChange={this.handleExpandChange}>
<CardHeader
title='Save a created Table'
actAsExpander
showExpandableButton
style={{ backgroundColor: '#f4f4f4', padding: '10px 16px' }}
/>
<CardMedia>
<div className='method-example' id='api-summary-example'>
<span className='pull-right flag fa fa-clipboard' title='Copy..' onClick={this.copyToClipboard('#pre_save')} />
<pre id='pre_save'>
<span className='code-red'>{
`var`}</span>{` table;;
table = `}<span className='code-red'>{`new`}</span>{` CB.CloudTable(`}<span className='code-yellow'>{`"NewTable"`}</span>{`);
table.save().then(`}<span className='code-red'>{`function`}</span>{`(response){
//success response
},`}<span className='code-red'>{`function`}</span>{`(){
//get error response
});`
}
</pre>
</div>{/* method-example */}
</CardMedia>
<CardTitle title='CloudTable.save( [callback] )' expandable
subtitle="Save a CloudTable Object. It will automatically create all default columns for a table. If you want to create a user table or role table then just pass 'User' or 'Role' as an argument while creating cloudtable object." />
<CardText expandable>
<div className='method-description'>
<div className='method-list'>
<h6>Arguments</h6>
<dl>
<dt>callback</dt>
<dd className>Object <span>[optional] if provided must have success and error functions to handle respective response.</span></dd>
<div className='clearfix' />
</dl>
<h6>Returns</h6>
<p>CloudTable Object</p>
</div>
</div>
</CardText>
</Card>
<a id='CloudTable-delete' name='CloudTable-delete' className='section-anchor' />
<Card style={{ marginBottom: 16 }} onExpandChange={this.handleExpandChange}>
<CardHeader
title='Delete a created Table'
actAsExpander
showExpandableButton
style={{ backgroundColor: '#f4f4f4', padding: '10px 16px' }}
/>
<CardMedia>
<div className='method-example' id='api-summary-example'>
<span className='pull-right flag fa fa-clipboard' title='Copy..' onClick={this.copyToClipboard('#pre_delete')} />
<pre id='pre_delete'>
<span className='code-red'>{
`var`}</span>{` table = `}<span className='code-red'>{`new`}</span>{` CB.CloudTable(`}<span className='code-yellow'>{`"${TABLE}"`}</span>{`);
table.delete().then(`}<span className='code-red'>{`function`}</span>{`(response){
//success response
},`}<span className='code-red'>{`function`}</span>{`(){
//get error response
});`
}
</pre>
</div>{/* method-example */}
</CardMedia>
<CardTitle title='CloudTable.delete( [callback] )' expandable
subtitle='Delete a CloudTable object i.e. delete a table of an App.' />
<CardText expandable>
<div className='method-description'>
<div className='method-list'>
<h6>Arguments</h6>
<dl>
<dt>callback</dt>
<dd className>Object <span>[optional] if provided must have success and error functions to handle respective response.</span></dd>
<div className='clearfix' />
</dl>
<h6>Returns</h6>
<p>Success or Error Status</p>
</div>
</div>
</CardText>
</Card>
</div>
</div>
);
}
}
export default CloudTable;
|
src/svg-icons/communication/speaker-phone.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationSpeakerPhone = (props) => (
<SvgIcon {...props}>
<path d="M7 7.07L8.43 8.5c.91-.91 2.18-1.48 3.57-1.48s2.66.57 3.57 1.48L17 7.07C15.72 5.79 13.95 5 12 5s-3.72.79-5 2.07zM12 1C8.98 1 6.24 2.23 4.25 4.21l1.41 1.41C7.28 4 9.53 3 12 3s4.72 1 6.34 2.62l1.41-1.41C17.76 2.23 15.02 1 12 1zm2.86 9.01L9.14 10C8.51 10 8 10.51 8 11.14v9.71c0 .63.51 1.14 1.14 1.14h5.71c.63 0 1.14-.51 1.14-1.14v-9.71c.01-.63-.5-1.13-1.13-1.13zM15 20H9v-8h6v8z"/>
</SvgIcon>
);
CommunicationSpeakerPhone = pure(CommunicationSpeakerPhone);
CommunicationSpeakerPhone.displayName = 'CommunicationSpeakerPhone';
CommunicationSpeakerPhone.muiName = 'SvgIcon';
export default CommunicationSpeakerPhone;
|
actor-apps/app-web/src/app/components/modals/Preferences.react.js | wangkang0627/actor-platform | import React from 'react';
import Modal from 'react-modal';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import { Styles, FlatButton, RadioButtonGroup, RadioButton, DropDownMenu } from 'material-ui';
import { KeyCodes } from 'constants/ActorAppConstants';
import ActorTheme from 'constants/ActorTheme';
import PreferencesActionCreators from 'actions/PreferencesActionCreators';
import PreferencesStore from 'stores/PreferencesStore';
const appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
isOpen: PreferencesStore.isModalOpen()
};
};
@ReactMixin.decorate(IntlMixin)
class PreferencesModal extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = getStateFromStores();
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
}
});
PreferencesStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
PreferencesStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
onChange = () => {
this.setState(getStateFromStores());
};
onClose = () => {
PreferencesActionCreators.hide();
};
onKeyDown = event => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
render() {
let menuItems = [
{ payload: '1', text: 'English' },
{ payload: '2', text: 'Russian' }
];
if (this.state.isOpen === true) {
return (
<Modal className="modal-new modal-new--preferences"
closeTimeoutMS={150}
isOpen={this.state.isOpen}
style={{width: 760}}>
<div className="modal-new__header">
<i className="modal-new__header__icon material-icons">settings</i>
<h3 className="modal-new__header__title">
<FormattedMessage message={this.getIntlMessage('preferencesModalTitle')}/>
</h3>
<div className="pull-right">
<FlatButton hoverColor="rgba(81,145,219,.17)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onClose}
secondary={true}
style={{marginTop: -6}}/>
</div>
</div>
<div className="modal-new__body">
<div className="preferences">
<aside className="preferences__tabs">
<a className="preferences__tabs__tab preferences__tabs__tab--active">General</a>
<a className="preferences__tabs__tab">Notifications</a>
<a className="preferences__tabs__tab">Sidebar colors</a>
<a className="preferences__tabs__tab">Security</a>
<a className="preferences__tabs__tab">Other Options</a>
</aside>
<div className="preferences__body">
<div className="preferences__list">
<div className="preferences__list__item preferences__list__item--general">
<ul>
<li>
<i className="icon material-icons">keyboard</i>
<RadioButtonGroup defaultSelected="default" name="send">
<RadioButton label="Enter – send message, Shift + Enter – new line"
style={{marginBottom: 12}}
value="default"/>
<RadioButton label="Cmd + Enter – send message, Enter – new line"
//style={{marginBottom: 16}}
value="alt"/>
</RadioButtonGroup>
</li>
<li className="language">
<i className="icon material-icons">menu</i>
Language: <DropDownMenu labelStyle={{color: '#5191db'}}
menuItemStyle={{height: '40px', lineHeight: '40px'}}
menuItems={menuItems}
style={{verticalAlign: 'top', height: 52}}
underlineStyle={{display: 'none'}}/>
</li>
</ul>
</div>
<div className="preferences__list__item preferences__list__item--notifications">
<ul>
<li>
<i className="icon material-icons">notifications</i>
<RadioButtonGroup defaultSelected="all" name="notifications">
<RadioButton label="Notifications for activity of any kind"
style={{marginBottom: 12}}
value="all"/>
<RadioButton label="Notifications for Highlight Words and direct messages"
style={{marginBottom: 12}}
value="quiet"/>
<RadioButton label="Never send me notifications"
style={{marginBottom: 12}}
value="disable"/>
</RadioButtonGroup>
<p className="hint">
You can override your desktop notification preference on a case-by-case
basis for channels and groups from the channel or group menu.
</p>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</Modal>
);
} else {
return null;
}
}
}
export default PreferencesModal;
|
app/components/PilotCard/index.js | prudhvisays/newsb | import React from 'react';
import profileImage from '../../Assets/profile-image.gif';
export default class PilotCard extends React.Component { //eslint-disable-line
render() {
const { detailedInfo, pilotName, pilotStatus, totalTask, completedTask, pilotDistance } = this.props;
return (
<a onClick={detailedInfo} style={{ textDecoration: 'none', color: 'inherit' }}>
<div className="trip-card pilot-boxShadow block-card-background marginBottom" style={{ fontSize: '0.7rem', padding: '1em' }}>
<div className="ink-flex" style={{ paddingBottom: '0.3em' }}>
<div className="all-50 ink-flex push-left">
<div className="trip-image">
<div className="trip-pic" style={{ width: '30px', height: '30px', borderRadius: '50%', overflow: 'hidden', margin: 0 }}>
<img src={profileImage} alt="default-card" style={{ height: '30px', width: '100%' }} />
</div>
</div>
<div className="trip-info ink-flex vertical" style={{ marginLeft: '0.7em' }}>
<div className="sub-title">Pilot</div>
<div>{pilotName}</div>
</div>
</div>
<div className="all-50 ink-flex push-right">
<div className="trip-info">
<div className={ pilotStatus !== 'Offline' ? 'ink-label green' : 'ink-label red' }>{pilotStatus}</div>
</div>
</div>
</div>
{/*<div className="second-row ink-flex">*/}
{/*<div className="all-50 ink-flex push-left">*/}
{/*<div className="trip-info ink-flex vertical">*/}
{/*<div className="sub-title">Tasks Completed</div>*/}
{/*<div>{completedTask} of {totalTask}</div>*/}
{/*</div>*/}
{/*</div>*/}
{/*<div className="all-50 ink-flex push-right">*/}
{/*<div className="trip-info ink-flex vertical" style={{ textAlign: 'right' }}>*/}
{/*<div className="sub-title">Travelled so far</div>*/}
{/*<div>{pilotDistance}</div>*/}
{/*</div>*/}
{/*</div>*/}
{/*</div>*/}
</div>
</a>
);
}
}
|
src/containers/MealsContainer/index.js | cernanb/personal-chef-react-app | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container } from 'semantic-ui-react';
import PropTypes from 'prop-types';
import { Link, Route, Switch } from 'react-router-dom';
import { css } from 'glamor';
import NewMeal from '../../components/NewMeal';
import Meal from '../../views/Meal';
const gridContainer = css({
marginTop: '20px',
display: 'grid',
gridTemplateAreas: `"navigation main main"`,
});
const gridNav = css({
gridArea: 'navigation',
});
const gridMain = css({
gridArea: 'main',
});
class MealsContainer extends Component {
render() {
const { meals } = this.props;
return (
<Container>
<div {...gridContainer}>
<div {...gridNav}>
<h1>All Meals</h1>
<ul>
{meals.map(m => (
<Link key={m.id} to={`/meals/${m.id}`}>
<h3 style={{ listStyleType: 'none' }}>{m.name}</h3>
</Link>
))}
</ul>
</div>
<div {...gridMain}>
<Switch>
<Route path="/meals/new" component={NewMeal} />
<Route exact path="/meals/:id" render={() => <Meal />} />
</Switch>
</div>
</div>
</Container>
);
}
}
MealsContainer.propTypes = {
meals: PropTypes.array,
};
export default connect(({ meals }) => ({ meals }))(MealsContainer);
|
src/routes/home/Home.js | jaruesink/ruesinkdds | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Home.css';
class Home extends React.Component {
static propTypes = {
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>Welcome to Our Practice</h1>
<div className={s.row}>
<p>
<img src={'./office_outside.jpg'} alt={'Outside view of the office'} />
We are a small personal family practice. My staff and I take pride in giving quality care and individualized attention to our patients. We value your time and schedule appointments to try to minimize waiting time in our office. We believe that your comfort during treatment is of the utmost importance, and we will do our best to ensure that your office visit will be efficient and pleasant.<br /><br />Our dedication to the education of our patients and staff supports exceptional service in a caring environment.
</p>
</div>
<div className={s.mission}>
<p>Our mission is to help our patients keep their teeth for a lifetime of optimal</p>
<div>
<ul>
<li>health</li>
<li>comfort</li>
<li>function</li>
<li>appearance</li>
</ul>
<img src={'./office_entry.jpg'} alt={'Entry to the office'} />
</div>
</div>
</div>
</div>
);
}
}
export default withStyles(s)(Home);
|
app/containers/LanguageProvider/index.js | balintsoos/app.rezsi.io | /*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { IntlProvider } from 'react-intl';
import { makeSelectLocale } from './selectors';
export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
);
}
}
LanguageProvider.propTypes = {
locale: PropTypes.string,
messages: PropTypes.object,
children: PropTypes.element.isRequired,
};
const mapStateToProps = createSelector(
makeSelectLocale(),
(locale) => ({ locale })
);
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
|
app/javascript/mastodon/features/ui/components/upload_area.js | h3zjp/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import { FormattedMessage } from 'react-intl';
export default class UploadArea extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
onClose: PropTypes.func,
};
handleKeyUp = (e) => {
const keyCode = e.keyCode;
if (this.props.active) {
switch(keyCode) {
case 27:
e.preventDefault();
e.stopPropagation();
this.props.onClose();
break;
}
}
}
componentDidMount () {
window.addEventListener('keyup', this.handleKeyUp, false);
}
componentWillUnmount () {
window.removeEventListener('keyup', this.handleKeyUp);
}
render () {
const { active } = this.props;
return (
<Motion defaultStyle={{ backgroundOpacity: 0, backgroundScale: 0.95 }} style={{ backgroundOpacity: spring(active ? 1 : 0, { stiffness: 150, damping: 15 }), backgroundScale: spring(active ? 1 : 0.95, { stiffness: 200, damping: 3 }) }}>
{({ backgroundOpacity, backgroundScale }) => (
<div className='upload-area' style={{ visibility: active ? 'visible' : 'hidden', opacity: backgroundOpacity }}>
<div className='upload-area__drop'>
<div className='upload-area__background' style={{ transform: `scale(${backgroundScale})` }} />
<div className='upload-area__content'><FormattedMessage id='upload_area.title' defaultMessage='Drag & drop to upload' /></div>
</div>
</div>
)}
</Motion>
);
}
}
|
Realization/frontend/czechidm-core/src/components/advanced/Icon/IdentitySwitchIcon.js | bcvsolutions/CzechIdMng | import React from 'react';
//
import AbstractIcon from './AbstractIcon';
import * as Basic from '../../basic';
/**
* Identity icon - switch uiser.
*
* @author Radek Tomiška
* @since 10.5.0
*/
export default class IdentitySwitchIcon extends AbstractIcon {
renderIcon() {
return (
<Basic.Icon icon="fa:user-secret" { ... this.props } />
);
}
}
|
packages/icons/src/md/device/ScreenLockPortrait.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdScreenLockPortrait(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M20 32a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2v-2c0-2.21 1.79-4 4-4s4 1.79 4 4v2a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-8zm1.6-12v2h4.8v-2a2.4 2.4 0 0 0-4.8 0zM34 2c2.21 0 4 1.79 4 4v36c0 2.21-1.79 4-4 4H14c-2.21 0-4-1.79-4-4V6c0-2.21 1.79-4 4-4h20zm0 36V10H14v28h20z" />
</IconBase>
);
}
export default MdScreenLockPortrait;
|
src/components/Sidebar/SimulateMenu.js | funkBuild/machinist | import React, { Component } from 'react';
import TabbedSection from '../common/TabbedSection';
import SimManager from '../../models/sim_manager';
import PathManager from '../../models/path_manager';
import './SimulateMenu.css';
class SimulateMenu extends Component {
constructor(props){
super(props);
SimManager.initialize();
}
test(){
SimManager.runOperation(PathManager.operations[0]);
/*
SimManager.runLine(
{x: 0, y: 0, z: 0},
{x: 50, y: 50, z: 0},
);
*/
}
get renderContent(){
return (
<TabbedSection text="Test">
<div className="modelInput">
<button onClick={() => this.test()}>Test</button>
</div>
</TabbedSection>
)
}
render() {
return (
<div className="SideMenu SimulateMenu">
<div className="menuHeader">
<img src={ require('../../images/simulate_icon.svg') } />
Simulate
</div>
{ this.renderContent }
</div>
);
}
}
export default SimulateMenu;
|
src/parser/deathknight/blood/modules/features/BloodPlagueUptime.js | fyruna/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import Enemies from 'parser/shared/modules/Enemies';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
class BloodPlagueUptime extends Analyzer {
static dependencies = {
enemies: Enemies,
};
get uptime() {
return this.enemies.getBuffUptime(SPELLS.BLOOD_PLAGUE.id) / this.owner.fightDuration;
}
get uptimeSuggestionThresholds() {
return {
actual: this.uptime,
isLessThan: {
minor: 0.95,
average: 0.9,
major: .8,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.uptimeSuggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest('Your Blood Plague uptime can be improved. Keeping Blood Boil on cooldown should keep it up at all times.')
.icon(SPELLS.BLOOD_PLAGUE.icon)
.actual(`${formatPercentage(actual)}% Blood Plague uptime`)
.recommended(`>${formatPercentage(recommended)}% is recommended`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.BLOOD_PLAGUE.id} />}
value={`${formatPercentage(this.uptime)} %`}
label="Blood Plague uptime"
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(2);
}
export default BloodPlagueUptime;
|
imports/api/client/index.js | mikowals/simple_rss | import React from 'react';
import { hydrateRoot } from 'react-dom';
import { BrowserRouter, Route, Routes, Link } from 'react-router-dom';
import { Meteor } from 'meteor/meteor';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
import { BatchHttpLink } from "@apollo/client/link/batch-http";
import { FeedsPageWithContainer } from '/imports/ui/feeds';
import { ArticlesPageWithStream } from '/imports/ui/articles';
export const client = new ApolloClient({
cache: new InMemoryCache().restore(window.__APOLLO_STATE__),
link: new BatchHttpLink({
uri: '/graphql',
credentials: 'same-origin',
batchInterval: 10}),
connectToDevTools: true
});
export const renderRoutes = () => (
<BrowserRouter>
<ApolloProvider client={client}>
<Routes>
<Route path="*" element={<ArticlesPageWithStream />} />
<Route path="/feeds" element={<FeedsPageWithContainer />} />
<Route path="/articles" element={<ArticlesPageWithStream />} />
</Routes>
</ApolloProvider>
<Link to="/feeds" >Feeds</Link>
<Link to="/articles" >Articles</Link>
</BrowserRouter>
);
Meteor.startup(() => {
hydrateRoot(
document.getElementById('app'),
renderRoutes()
)
});
|
wrappers/json.js | amni/alanmni-portfolio | import React from 'react'
import Helmet from 'react-helmet'
import { config } from 'config'
module.exports = React.createClass({
propTypes () {
return {
route: React.PropTypes.object,
}
},
render () {
const data = this.props.route.page.data
return (
<div>
<Helmet
title={`${config.siteTitle} | ${data.title}`}
/>
<h1>{data.title}</h1>
<p>Raw view of json file</p>
<pre dangerouslySetInnerHTML={{ __html: JSON.stringify(data, null, 4) }} />
</div>
)
},
})
|
webapp/react/browser.js | isucon/isucon6-final | import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import AsyncProps from 'async-props';
// for material-ui https://www.npmjs.com/package/material-ui
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
window.csrfToken = document.documentElement.dataset.csrfToken;
window.apiBaseUrl = location.origin;
const appElem = document.getElementById('app');
render((
<Router
history={browserHistory}
routes={routes}
render={(props) => <AsyncProps {...props} />}
/>
), appElem);
|
admin/src/components/AltText.js | udp/keystone | import React from 'react';
import blacklist from 'blacklist';
import vkey from 'vkey';
var AltText = React.createClass({
getDefaultProps () {
return {
component: 'span',
modifier: '<alt>',
normal: '',
modified: ''
};
},
getInitialState () {
return {
modified: false
};
},
componentDidMount () {
document.body.addEventListener('keydown', this.handleKeyDown, false);
document.body.addEventListener('keyup', this.handleKeyUp, false);
},
componentWillUnmount () {
document.body.removeEventListener('keydown', this.handleKeyDown);
document.body.removeEventListener('keyup', this.handleKeyUp);
},
handleKeyDown (e) {
if (vkey[e.keyCode] !== this.props.modifier) return;
this.setState({
modified: true
});
},
handleKeyUp (e) {
if (vkey[e.keyCode] !== this.props.modifier) return;
this.setState({
modified: false
});
},
render () {
var props = blacklist(this.props, 'component', 'modifier', 'normal', 'modified');
return React.createElement(this.props.component, props, this.state.modified ? this.props.modified : this.props.normal);
}
});
module.exports = AltText;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.