path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
examples/src/App.js | Chrisui/react-hotkeys | import { HotKeys, GlobalHotKeys, ObserveKeys, getApplicationKeyMap } from 'react-hotkeys';
import React from 'react';
import Node from './Node';
import HOCWrappedNode from './HOCWrappedNode';
const keyMap = {
DELETE: { name: 'Disable square', sequence: 'backspace', action: 'keyup'},
EXPAND: { name: 'Expand square area', sequence: 'alt+up' },
CONTRACT: { name: 'Reduce square area', sequence: 'alt+down' },
MOVE_UP: { name: 'Move square up', sequence: 'up' },
MOVE_DOWN: { name: 'Move square down', sequence: 'down' },
MOVE_LEFT: { name: 'Move square left', sequence: 'left' },
MOVE_RIGHT: { name: 'Move square right', sequence: 'right' }
};
const globalKeyMap = {
KONAMI: { name: 'Konami code', sequence: 'up up down down left right left right b a enter' },
LOG_DOWN: { name: 'Log Cmd Down', sequence: 'command', action: 'keydown'},
LOG_UP: { name: 'Log Cmd Up', sequence: 'command', action: 'keyup'},
SHOW_DIALOG: { name: 'Display keyboard shortcuts', sequence: 'shift+?', action: 'keyup' },
};
const styles = {
DIALOG: {
width: 600,
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
padding: '0 24',
backgroundColor: 'white',
zIndex: 100,
color: 'rgba(0,0,0,0.87)'
},
KEYMAP_TABLE_CELL: {
padding: 8
}
};
class App extends React.Component {
static logCommandKeyDown() {
console.log('command down');
}
static logCommandKeyUp() {
console.log('command up');
}
constructor(props, context) {
super(props, context);
this.onKonami = this.onKonami.bind(this);
this.state = {
konamiTime: false,
showDialog: false,
filter: '',
};
}
onKonami() {
this.setState({konamiTime: true});
}
renderDialog() {
if (this.state.showDialog) {
const keyMap = getApplicationKeyMap();
const { filter } = this.state;
const _filter = filter.toUpperCase();
return (
<HotKeys
keyMap={{CLOSE_DIALOG: 'Escape' }}
handlers={{ CLOSE_DIALOG: () => this.setState({ showDialog: false })} }
>
<div style={styles.DIALOG}>
<h2>
Keyboard shortcuts
</h2>
<ObserveKeys only={'Escape'}>
<input
autoFocus
onChange={({target: {value}}) => this.setState({ filter: value })}
value={filter}
placeholder='Filter'
/>
</ObserveKeys>
<table>
<tbody>
{ Object.keys(keyMap).reduce((memo, actionName) => {
if (filter.length === 0 || actionName.indexOf(_filter) !== -1) {
const { sequences, name } = keyMap[actionName];
memo.push(
<tr key={name || actionName}>
<td style={styles.KEYMAP_TABLE_CELL}>
{ name }
</td>
<td style={styles.KEYMAP_TABLE_CELL}>
{ sequences.map(({sequence}) => <span key={sequence}>{sequence}</span>) }
</td>
</tr>
)
}
return memo;
}, []) }
</tbody>
</table>
</div>
</HotKeys>
);
}
}
render() {
const {konamiTime} = this.state;
const globalHandlers = {
KONAMI: this.onKonami,
LOG_DOWN: this.constructor.logCommandKeyDown,
LOG_UP: this.constructor.logCommandKeyUp,
SHOW_DIALOG: () => this.setState({ showDialog: !this.state.showDialog })
};
const className = konamiTime ? 'viewport konamiTime' : 'viewport';
return (
<React.StrictMode>
<GlobalHotKeys
keyMap={globalKeyMap}
handlers={globalHandlers}
global
/>
{ this.renderDialog() }
<HotKeys keyMap={keyMap}>
<div className="app">
<div className="tips">
<ul>
<li>Select a node and move it with your arrow keys</li>
<li>Expand or contract a node with `alt+up` or `alt+down` respectively</li>
<li>Delete a node with `delete` or `backspace`</li>
<li>How about the konami code? `up up down down left right left right b a enter`</li>
<li>Want to get started? <a href="https://github.com/greena13/react-hotkeys/blob/master/README.md">Read the guide.</a></li>
</ul>
</div>
<div className={className}>
<HOCWrappedNode />
<div>
{Array.apply(null, new Array(10)).map((e, i) => <Node key={i} />)}
</div>
</div>
</div>
</HotKeys>
</React.StrictMode>
);
}
}
export default App;
|
src/helpers/validation/getErrorMessage.js | expdevelop/ultrastore | import React from 'react'
import Container from 'components/Container/Container'
import List from 'components/List/List'
import Title from 'components/Title/Title'
import isEmpty from '../app/isEmpty'
export default function getErrorMessage(err, isReact) {
if (isEmpty(err))
return null;
if (typeof err === 'string')
return err;
let error = 'Ошибка';
if (!!err.length && isReact) {
return (
<Container type="article">
<Title center>Ошибка</Title>
<List data={err}/>
</Container>
)
}
if (!!err.length) {
const errors = err.join('\n');
return `Ошибки: ${errors}`;
}
if (err.status != null) {
const status = parseInt(err.status, 10);
if (status === 0) {
error += `: нет подключения к сети.`
} else {
error += `: ${err.status}`
}
}
if (err.statusText != null) {
if (!isEmpty(err.statusText))
error += `, ${err.statusText}`
}
return error;
}
|
src/js/components/icons/base/History.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-history`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'history');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M1,12 C1,18.075 5.925,23 12,23 C18.075,23 23,18.075 23,12 C23,5.925 18.075,1 12,1 C7.563,1 4,4 2,7.5 M1,1 L1,8 L8,8 M16,17 L12,13 L12,6"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'History';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
react-apollo/src/containers/NotFoundPage/index.js | strapi/strapi-examples | /**
*
* NotFoundPage
* This is the component that will show when you have a 404
*/
import React from 'react';
function NotFoundPage(props) {
return (
<div>
<p>The page you're looking for doesn't exist.</p>
</div>
);
}
export default NotFoundPage;
|
app/components/PointListItem/index.js | GuiaLa/guiala-web-app | /**
*
* PointListItem
*
*/
import React from 'react';
import { Link } from 'react-router';
import {Card, CardActions, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import Star from 'Star';
import AddToItinerary from 'AddToItinerary';
import FlatButton from 'material-ui/FlatButton';
import MoreHoriz from 'material-ui/svg-icons/navigation/more-horiz'
import styles from './styles.css';
const lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
function PointListItem({ name, slug, description = lorem , region, _id, place }) {
return (
<div className={ styles.wrapper }>
<Card>
<CardMedia
overlayContentStyle={{background: 'linear-gradient(to top, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)'}}
overlayContainerStyle={{background: 'linear-gradient(to bottom, rgba(0,0,0,0.45) 0%,rgba(0,0,0,0.3) 24%,rgba(0,0,0,0) 100%)'}}
overlay={<CardTitle title={name} subtitle={region || 'região'} />}
>
<img src={require('../../assets/anjos.jpg')} />
</CardMedia>
<CardText>
{ description.split(/\s+/).slice(0,20).join(" ")+"..." }
</CardText>
<CardActions>
<FlatButton label={<Star _id={_id} />} />
<FlatButton label={<AddToItinerary _id={_id} />} />
<FlatButton label={<Link to={`/${place}/${slug}`}><MoreHoriz /></Link>} />
</CardActions>
</Card>
</div>
);
}
export default PointListItem;
|
frontend/src/components/Timer/index.js | XiaocongDong/mongodb-backup-manager | import React, { Component } from 'react';
import time from 'utility/time';
export default class Timer extends Component {
constructor(props) {
super(props);
this.timer = null;
this.state = {
remain: null
};
this.getRemain = this.getRemain.bind(this);
this.updateRemain = this.updateRemain.bind(this);
}
componentDidMount() {
this.timer = setInterval(this.updateRemain, 1000);
}
getRemain() {
const endTime = this.props.endTime;
const endDate = new Date(endTime);
const now = new Date();
return endDate - now;
}
updateRemain() {
const remain = time.getTimeStringFromMilliseconds(this.getRemain());
this.setState({
remain
})
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
const remain = this.state.remain;
return (
<span className="timer">
{ remain || ""}
</span>
)
}
} |
core/js/index.js | orgdown/orgdown-notebook | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render((
<App />
), document.getElementById('content')); |
fields/types/location/LocationFilter.js | asifiqbal84/keystone | import _ from 'underscore';
import classNames from 'classnames';
import React from 'react';
import { FormField, FormInput, FormRow, SegmentedControl } from 'elemental';
const MODE_OPTIONS = [
{ label: 'Exactly', value: 'exactly' },
{ label: 'Contains', value: 'contains' }
];
const TOGGLE_OPTIONS = [
{ label: 'Matches', value: false },
{ label: 'Does NOT Match', value: true }
];
var TextFilter = React.createClass({
getInitialState () {
return {
inverted: TOGGLE_OPTIONS[0].value,
city: '',
state: '',
code: '',
country: ''
};
},
componentDidMount () {
// focus the text focusTarget
React.findDOMNode(this.refs.focusTarget).focus();
},
toggleInverted (value) {
this.setState({
inverted: value
});
},
render () {
let { modeLabel, modeValue } = this.state;
return (
<div>
<FormField>
<SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={this.state.inverted} onChange={this.toggleInverted} />
</FormField>
<FormField>
<FormInput ref="focusTarget" placeholder="Address" />
</FormField>
<FormRow>
<FormField width="two-thirds">
<FormInput placeholder="City" value={this.state.city} />
</FormField>
<FormField width="one-third">
<FormInput placeholder="State" value={this.state.state} />
</FormField>
<FormField width="one-third" style={{ marginBottom: 0 }}>
<FormInput placeholder="Postcode" value={this.state.code} />
</FormField>
<FormField width="two-thirds" style={{ marginBottom: 0 }}>
<FormInput placeholder="Country" value={this.state.country} />
</FormField>
</FormRow>
</div>
);
}
});
module.exports = TextFilter;
|
src/svg-icons/action/flip-to-back.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionFlipToBack = (props) => (
<SvgIcon {...props}>
<path d="M9 7H7v2h2V7zm0 4H7v2h2v-2zm0-8c-1.11 0-2 .9-2 2h2V3zm4 12h-2v2h2v-2zm6-12v2h2c0-1.1-.9-2-2-2zm-6 0h-2v2h2V3zM9 17v-2H7c0 1.1.89 2 2 2zm10-4h2v-2h-2v2zm0-4h2V7h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2zM5 7H3v12c0 1.1.89 2 2 2h12v-2H5V7zm10-2h2V3h-2v2zm0 12h2v-2h-2v2z"/>
</SvgIcon>
);
ActionFlipToBack = pure(ActionFlipToBack);
ActionFlipToBack.displayName = 'ActionFlipToBack';
ActionFlipToBack.muiName = 'SvgIcon';
export default ActionFlipToBack;
|
examples/example-react/components/Header.js | risetechnologies/fela | import React from 'react'
import { createComponentWithProxy } from 'react-fela'
const Header = ({ title, className }) => (
<div className={className}>{title}</div>
)
const rule = () => ({
'@media (min-width: 1024px)': {
color: 'red',
},
color: 'rgb(50, 50, 50)',
fontSize: 100,
padding: 50,
':hover': { animationDuration: '500ms' },
'@supports (-webkit-flex:1)': {
fontFamily: 'Impact',
},
'@media (min-width: 480px)': {
color: 'blue',
},
'@media (max-width: 800px)': {
'@supports (-webkit-flex:1)': {
fontSize: 180,
},
fontSize: '40px',
},
animationDuration: '2s',
animationIterationCount: 'infinite',
animationName: {
'0%': { color: 'green' },
'50%': { color: 'blue' },
'80%': { color: 'purple' },
'100%': { color: 'green' },
},
})
export default createComponentWithProxy(rule, Header)
|
src/svg-icons/places/beach-access.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesBeachAccess = (props) => (
<SvgIcon {...props}>
<path d="M13.127 14.56l1.43-1.43 6.44 6.443L19.57 21zm4.293-5.73l2.86-2.86c-3.95-3.95-10.35-3.96-14.3-.02 3.93-1.3 8.31-.25 11.44 2.88zM5.95 5.98c-3.94 3.95-3.93 10.35.02 14.3l2.86-2.86C5.7 14.29 4.65 9.91 5.95 5.98zm.02-.02l-.01.01c-.38 3.01 1.17 6.88 4.3 10.02l5.73-5.73c-3.13-3.13-7.01-4.68-10.02-4.3z"/>
</SvgIcon>
);
PlacesBeachAccess = pure(PlacesBeachAccess);
PlacesBeachAccess.displayName = 'PlacesBeachAccess';
PlacesBeachAccess.muiName = 'SvgIcon';
export default PlacesBeachAccess;
|
code-samples/js/ViroMediaPlayer/Viro360Theatre.js | viromedia/viro |
'use strict';
/**
* Pull in all imports required for the controls within this scene.
*/
import React, { Component } from 'react';
import {StyleSheet} from 'react-native';
import {
AppRegistry,
ViroScene,
ViroVideo,
ViroSceneNavigator,
ViroMaterials,
Viro360Video,
ViroButton,
ViroImage,
ViroNode,
ViroAnimations,
} from 'react-viro';
var createReactClass = require('create-react-class');
/**
* Set all the image and asset references required in this scene.
*/
var buttonSize = 0.25;
var VIDEO_REF = "videoref";
/**
* Several references to video sources (wether it be local or on AWS) stored in an array.
*/
var videos = [
{uri:'https://s3-us-west-2.amazonaws.com/viro/MediaDemo360_1.mp4'},
{uri:'https://s3-us-west-2.amazonaws.com/viro/MediaDemo360_2.mp4'}
];
var Viro360Theatre = createReactClass({
getInitialState() {
return {
videoControlsAnimation:"fadeIn",
videoPaused: false,
loopVideo: true,
videoIndex: 0,
runAnimation: false,
}
},
/**
* Renders a scene that contains a 360 video and Video Controls.
*/
render: function() {
return (
<ViroScene onClick={this._onVideoTapped} reticleEnabled={this.state.videoControlsAnimation=="fadeIn"}>
<Viro360Video ref={VIDEO_REF} source={videos[this.state.videoIndex]} volume={1.0}
loop={this.state.loopVideo} paused={this.state.videoPaused} />
{this._renderVideoControl()}
</ViroScene>
);
},
_onVideoTapped(){
var videoControlsAnimationState = this.state.videoControlsAnimation;
if (videoControlsAnimationState=="fadeIn"){
videoControlsAnimationState="fadeOut";
} else {
videoControlsAnimationState="fadeIn";
}
this.setState({
videoControlsAnimation:videoControlsAnimationState,
runAnimation: true,
});
},
/**
* Render a set of Video UI Controls. This includes (in the order displayed from left to right):
* Restart, Previous Video, Play/Pause, Next Video, Volume.
*/
_renderVideoControl(){
return(
<ViroNode position={[0,-0.8,0]} opacity={1.0}
animation={{name : this.state.videoControlsAnimation, run : this.state.runAnimation, loop : false}} >
<ViroImage
scale={[1.4, 1.2, 1]}
position={[0, -0.27,-2.1]}
source={require("./res/player_controls_container.png")} />
<ViroButton
position={[-buttonSize-0.1,0,-2]}
scale={[1, 1, 1]}
width={buttonSize}
height={buttonSize}
source={require("./res/previous.png")}
hoverSource={require("./res/previous_hover.png")}
clickSource={require("./res/previous_hover.png")}
onClick={this._playPreviousVideo} />
{this._renderPlayControl()}
<ViroButton
position={[buttonSize+0.1, 0,-2]}
scale={[1, 1, 1]}
width={buttonSize}
height={buttonSize}
source={require("./res/skip.png")}
hoverSource={require("./res/skip_hover.png")}
clickSource={require("./res/skip_hover.png")}
onClick={this._playNextVideo} />
<ViroButton
position={[-0.3, -0.4 ,-2]}
scale={[1, 1, 1]}
width={0.5}
height={0.5}
source={require("./res/icon_2D.png")}
hoverSource={require("./res/icon_2D_hover.png")}
clickSource={require("./res/icon_2D_hover.png")}
onClick={this._launchTheatreScene} />
<ViroButton
position={[0.3, -0.4 ,-2]}
scale={[1, 1, 1]}
width={0.5}
height={0.5}
source={require("./res/icon_360_hover.png")}
hoverSource={require("./res/icon_360_hover.png")}
clickSource={require("./res/icon_360_hover.png")} />
</ViroNode>
);
},
/**
* Renders either the play or pause icon depending on video state.
*/
_renderPlayControl(){
if (this.state.videoPaused){
return (
<ViroButton
position={[0,0,-2]}
scale={[1, 1, 1]}
width={buttonSize}
height={buttonSize}
source={require("./res/play.png")}
hoverSource={require("./res/play_hover.png")}
clickSource={require("./res/play_hover.png")}
transformBehaviors={["billboard"]}
onClick={this._togglePauseVideo}/>
);
} else {
return (
<ViroButton
position={[0,0,-2]}
scale={[1, 1, 1]}
width={buttonSize}
height={buttonSize}
source={require("./res/pause.png")}
hoverSource={require("./res/pause_hover.png")}
clickSource={require("./res/pause_hover.png")}
transformBehaviors={["billboard"]}
onClick={this._togglePauseVideo}/>
);
}
},
_launchTheatreScene(){
this.props.sceneNavigator.jump("ViroTheatre", {scene:require('./ViroTheatre')});
},
_togglePauseVideo() {
this.setState({
videoPaused: !this.state.videoPaused,
})
},
/**
* Play the previous video by setting the videoIndex.
*/
_playPreviousVideo(){
var currentVideo = this.state.videoIndex;
if (currentVideo - 1 > -1){
this.setState({
videoIndex: (currentVideo - 1),
videoPaused: false
});
}
},
/**
* Play the next video by setting the videoIndex.
*/
_playNextVideo(){
var currentVideo = this.state.videoIndex;
if (currentVideo + 1 < videos.length){
this.setState({
videoIndex: (currentVideo + 1),
videoPaused: false
});
}
},
});
ViroAnimations.registerAnimations({
fadeOut:{properties:{opacity: 0.0}, duration: 500},
fadeIn:{properties:{opacity: 1.0}, duration: 500},
});
module.exports = Viro360Theatre;
|
website/components/Navbar/utils/makeSection.js | Pop-Code/keystone | import React from 'react';
import Link from 'gatsby-link';
import Item from '../Item';
export default function makeSection (currentPath, layer, pathname) {
return layer.map((section, idx) => {
const locationArray = pathname.split('/');
const currentSection = locationArray[locationArray.length - 1];
const menuItems = section.items.map((item, i) => {
const newPath = currentPath + section.slug;
// Secondary items
if (item.items) {
const subItems = item.items.map((subItem, sid) => (
<Item
isActive={currentSection === subItem.slug.split('/')[1] || (!subItem.slug && currentSection === item.slug.split('/')[1])}
key={subItem.slug + '__' + sid}
title={subItem.label}
url={newPath + item.slug + subItem.slug}
depth={2}
/>
));
return (
<div>
<Item
url={newPath + item.slug + item.items[0].slug}
title={item.section}
depth={1}
isExpandable
/>
{locationArray[2] === item.slug.split('/')[1] && subItems}
</div>
);
}
// Primary items
return (
<Item
isActive={
locationArray.length === 2
? !item.slug
: currentSection === item.slug.split('/')[1]
}
key={item.slug + '__' + i}
title={item.label}
url={newPath + item.slug}
depth={1}
/>
);
});
// Sections
return (
<div key={'section__' + idx}>
<Link to={section.slug} css={styles.sectionTitle}>
{section.section}
</Link>
{locationArray[1] === section.slug.split('/')[1] && menuItems}
</div>
);
});
}
const styles = {
sectionTitle: {
display: 'block',
color: 'white',
fontSize: '1rem',
textTransform: 'uppercase',
fontWeight: '600',
textDecoration: 'none',
padding: '0.625rem 1.875rem',
},
};
|
docs/app/Examples/elements/Segment/Groups/SegmentExampleSegments.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Segment } from 'semantic-ui-react'
const SegmentExampleSegments = () => (
<Segment.Group>
<Segment>Top</Segment>
<Segment>Middle</Segment>
<Segment>Middle</Segment>
<Segment>Middle</Segment>
<Segment>Bottom</Segment>
</Segment.Group>
)
export default SegmentExampleSegments
|
packages/icons/src/public.js | yldio/joyent-portal | import React from 'react';
import Rotate from './rotate';
import calcFill from './fill';
export default ({
fill = null,
light = false,
disabled = false,
direction = 'down',
colors = {},
style = {},
...rest
}) => (
<Rotate direction={direction}>
{({ style: rotateStyle }) => (
<svg
viewBox="0 0 12 16"
width="12"
height="16"
style={{ ...style, ...rotateStyle }}
{...rest}
>
<path
fill={calcFill({ fill, disabled, light, colors })}
d="M6,13H6a1,1,0,0,1-1-1V10A1,1,0,0,1,6,9H6a1,1,0,0,1,1,1v2A1,1,0,0,1,6,13Zm4-7V4A4,4,0,0,0,2,4H4c0-1.65.35-2,2-2s2,.35,2,2V6H2A2,2,0,0,0,0,8v6a2,2,0,0,0,2,2h8a2,2,0,0,0,2-2V8A2,2,0,0,0,10,6Zm0,7a1,1,0,0,1-1,1H3a1,1,0,0,1-1-1V9A1,1,0,0,1,3,8H9a1,1,0,0,1,1,1Z"
/>
</svg>
)}
</Rotate>
);
|
app/containers/Web3Alerts/NoInjected.js | VonIobro/ab-web | import React from 'react';
import { Wrapper } from './styles';
const NoInjected = () => (
<Wrapper theme="warning">
<h2>Account doesn´t exists or locked</h2>
<p>
Please, create or unlock MetaMask account
</p>
</Wrapper>
);
export default NoInjected;
|
src/components/cv.js | ateixeira/andreteixeira.info | import React from 'react';
import Info from "./cv/info"
import WorkExperience from "./cv/workexperience"
import AwardsSkills from "./cv/awardskills"
import data from "../data/seed"
module.exports = React.createClass({
// RENDER
render: function() {
return (
<div className="cv">
<div className="box">
<h1>CURRICULUM VITAE</h1>
<Info />
<WorkExperience experiences={data.EXPERIENCES}/>
<AwardsSkills skills={data.SKILLS}/>
</div>
<br/>
</div>
);
}
}); |
src/components/layout/sidebar/Sidebar.js | Gisto/Gisto | import React from 'react';
import { isEmpty, map, trim, startCase } from 'lodash/fp';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import styled, { withTheme } from 'styled-components';
import { SIDEBAR_WIDTH } from 'constants/config';
import { filterSnippetsList, isTag } from 'utils/snippets';
import * as snippetActions from 'actions/snippets';
import SnippetsList from 'components/layout/sidebar/SnippetsList';
import Snippet from 'components/layout/sidebar/Snippet';
import Icon from 'components/common/Icon';
const SideBarWrapper = styled.div`
width: ${SIDEBAR_WIDTH}px;
background: ${(props) => props.theme.baseAppColor};
display: flex;
flex-direction: column;
overflow: auto;
`;
const SearchFilters = styled.div`
color: ${(props) => props.theme.baseAppColor};
padding: 10px 20px;
background: ${(props) => props.theme.lightText};
z-index: 1;
border-top: 1px solid ${(props) => props.theme.borderColor};
box-shadow: 0 1px 2px ${(props) => props.theme.boxShadow};
font-size: 12px;
`;
const ClearAll = styled.a`
cursor: pointer;
color: ${(props) => props.theme.colorDanger};
white-space: nowrap;
`;
const Tag = styled.span`
border: 1px solid ${(props) => props.theme.baseAppColor};
color: ${(props) => props.theme.baseAppColor};
padding: 1px 3px;
border-radius: 3px;
margin-right: 3px;
`;
export const Sidebar = ({
snippets,
filterText,
filterTags,
filterLanguage,
clearFilters,
removeTag,
filterStatus,
filterTruncated,
filterUntagged,
theme
}) => {
const searchType = () => {
if (!isEmpty(trim(filterText))) {
return isTag(filterText) ? 'free text tag' : 'free text';
}
if (!isEmpty(filterTags)) {
return (
<span>
{'tags '}{' '}
{map(
(tag) => (
<Tag key={ tag }>
{tag}
<Icon
type="close"
clickable
size={ 12 }
onClick={ () => removeTag(tag) }
color={ theme.baseAppColor }/>
</Tag>
),
filterTags
)}
</span>
);
}
if (!isEmpty(trim(filterLanguage))) {
return `language: ${filterLanguage}`;
}
if (!isEmpty(filterStatus)) {
return startCase(filterStatus);
}
if (filterTruncated === true) {
return 'large files';
}
if (filterUntagged === true) {
return 'untagged';
}
return '';
};
const shouldShowFilteredBy =
!isEmpty(trim(filterText)) ||
!isEmpty(trim(filterTags)) ||
!isEmpty(trim(filterStatus)) ||
!isEmpty(trim(filterLanguage)) ||
filterTruncated ||
filterUntagged;
const snippetList = map(
(snippet) => <Snippet key={ snippet.id } snippet={ snippet }/>,
filterSnippetsList(
snippets,
filterText,
filterTags,
filterLanguage,
filterStatus,
filterTruncated,
filterUntagged
)
);
return (
<SideBarWrapper>
{shouldShowFilteredBy && (
<SearchFilters>
Filtered by <strong>{searchType()}</strong>
<ClearAll onClick={ () => clearFilters() }>
<Icon type="close-circle" size={ 12 } color={ theme.colorDanger }/>
<strong>clear</strong>
</ClearAll>
</SearchFilters>
)}
<SnippetsList>{snippetList}</SnippetsList>
</SideBarWrapper>
);
};
const mapStateToProps = (state) => ({
snippets: state.snippets.snippets,
filterText: state.snippets.filter.text,
filterTags: state.snippets.filter.tags,
filterLanguage: state.snippets.filter.language,
filterStatus: state.snippets.filter.status,
filterTruncated: state.snippets.filter.truncated,
filterUntagged: state.snippets.filter.untagged
});
Sidebar.propTypes = {
snippets: PropTypes.object,
theme: PropTypes.object,
filterText: PropTypes.string,
filterTags: PropTypes.array,
filterLanguage: PropTypes.string,
filterStatus: PropTypes.string,
clearFilters: PropTypes.func,
removeTag: PropTypes.func,
filterTruncated: PropTypes.bool,
filterUntagged: PropTypes.bool
};
export default withTheme(
connect(
mapStateToProps,
{
clearFilters: snippetActions.clearAllFilters,
removeTag: snippetActions.removeTagFromFilter
}
)(Sidebar)
);
|
fields/components/columns/ArrayColumn.js | tony2cssc/keystone | import React from 'react';
import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell';
import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue';
var ArrayColumn = React.createClass({
displayName: 'ArrayColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value || !value.length) return null;
return value.join(', ');
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = ArrayColumn;
|
blueocean-material-icons/src/js/components/svg-icons/image/brightness-2.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageBrightness2 = (props) => (
<SvgIcon {...props}>
<path d="M10 2c-1.82 0-3.53.5-5 1.35C7.99 5.08 10 8.3 10 12s-2.01 6.92-5 8.65C6.47 21.5 8.18 22 10 22c5.52 0 10-4.48 10-10S15.52 2 10 2z"/>
</SvgIcon>
);
ImageBrightness2.displayName = 'ImageBrightness2';
ImageBrightness2.muiName = 'SvgIcon';
export default ImageBrightness2;
|
imports/ui/containers/feed/commentItem.js | jiyuu-llc/jiyuu | import React from 'react';
import { composeWithTracker } from 'react-komposer';
import { Comments } from '/lib/collections';
import {CommentItem} from '../../components/feed/commentItem.jsx';
const composer = ( postId, onData ) => {
if (Meteor.subscribe('comments').ready()) {
var comment = Comments.findOne({postId:postId.postId});
console.log(comment);
onData( null, { comment } );
}
};
export default composeWithTracker( composer, CommentItem)( CommentItem );
|
app/client/containers/DevTools/index.js | bhargav175/dictionary-offline | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="H"
changePositionKey="W">
<LogMonitor />
</DockMonitor>
); |
Shuttle.ProcessManagement/site.react/src/Alerts.js | Shuttle/Shuttle.Esb.Samples | import React from 'react';
import Alert from 'react-bootstrap/Alert'
import state from './state';
export default class Alerts extends React.Component {
render() {
if (!state.alerts.messages) {
return undefined;
}
return state.alerts.messages.map(message => (
<Alert key={message.name} variant={alert.success} className={"alert-dismissible"} dismissable show onClose={() => state.alerts.remove(alert)}>
{alert.message}
</Alert>
));
}
} |
src/Parser/Paladin/Retribution/Modules/PaladinCore/BoWProcTracker.js | enragednuke/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
import SpellUsable from 'Parser/Core/Modules/SpellUsable';
class BoWProcTracker extends Analyzer {
static dependencies = {
combatants: Combatants,
spellUsable: SpellUsable,
};
overwrittenBoWProcs = 0;
totalBoWProcs = 0;
on_initialized() {
this.active = this.combatants.selected.hasTalent(SPELLS.BLADE_OF_WRATH_TALENT.id);
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.BLADE_OF_WRATH_PROC.id) {
return;
}
this.totalBoWProcs += 1;
if (this.spellUsable.isOnCooldown(SPELLS.BLADE_OF_JUSTICE.id)) {
this.spellUsable.endCooldown(SPELLS.BLADE_OF_JUSTICE.id);
}
}
on_byPlayer_refreshbuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.BLADE_OF_WRATH_PROC.id) {
return;
}
this.overwrittenBoWProcs += 1;
this.totalBoWProcs += 1;
}
get suggestionThresholds() {
const missedProcsPercent = this.overwrittenBoWProcs / this.totalBoWProcs;
return {
actual: missedProcsPercent,
isGreaterThan: {
minor: 0,
average: 0.05,
major: 0.1,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(<span>You wasted {formatPercentage(actual)}% <SpellLink id={SPELLS.BLADE_OF_WRATH_PROC.id} /> procs</span>)
.icon(SPELLS.BLADE_OF_WRATH_PROC.icon)
.actual(`${formatNumber(this.overwrittenBoWProcs)} missed proc(s)`)
.recommended(`Wasting none is recommended`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.BLADE_OF_WRATH_PROC.id} />}
value={`${formatNumber(this.totalBoWProcs)}`}
label="Blade of Wrath procs"
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL(2);
}
export default BoWProcTracker;
|
react/src/index.js | tbauer516/rpimirror | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
// import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// registerServiceWorker();
|
src/Option.js | hannahsquier/react-select | import React from 'react';
import classNames from 'classnames';
const Option = React.createClass({
propTypes: {
children: React.PropTypes.node,
className: React.PropTypes.string, // className (based on mouse position)
instancePrefix: React.PropTypes.string.isRequired, // unique prefix for the ids (used for aria)
isDisabled: React.PropTypes.bool, // the option is disabled
isFocused: React.PropTypes.bool, // the option is focused
isSelected: React.PropTypes.bool, // the option is selected
onFocus: React.PropTypes.func, // method to handle mouseEnter on option element
onSelect: React.PropTypes.func, // method to handle click on option element
onUnfocus: React.PropTypes.func, // method to handle mouseLeave on option element
option: React.PropTypes.object.isRequired, // object that is base for that option
optionIndex: React.PropTypes.number, // index of the option, used to generate unique ids for aria
},
blockEvent (event) {
event.preventDefault();
event.stopPropagation();
if ((event.target.tagName !== 'A') || !('href' in event.target)) {
return;
}
if (event.target.target) {
window.open(event.target.href, event.target.target);
} else {
window.location.href = event.target.href;
}
},
handleMouseDown (event) {
event.preventDefault();
event.stopPropagation();
this.props.onSelect(this.props.option, event);
},
handleMouseEnter (event) {
this.onFocus(event);
},
handleMouseMove (event) {
this.onFocus(event);
},
handleTouchEnd(event){
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if(this.dragging) return;
this.handleMouseDown(event);
},
handleTouchMove (event) {
// Set a flag that the view is being dragged
this.dragging = true;
},
handleTouchStart (event) {
// Set a flag that the view is not being dragged
this.dragging = false;
},
onFocus (event) {
if (!this.props.isFocused) {
this.props.onFocus(this.props.option, event);
}
},
render () {
var { option, instancePrefix, optionIndex } = this.props;
var className = classNames(this.props.className, option.className);
return option.disabled ? (
<div className={className}
onMouseDown={this.blockEvent}
onClick={this.blockEvent}>
{this.props.children}
</div>
) : (
<div className={className}
style={option.style}
role="option"
onMouseDown={this.handleMouseDown}
onMouseEnter={this.handleMouseEnter}
onMouseMove={this.handleMouseMove}
onTouchStart={this.handleTouchStart}
onTouchMove={this.handleTouchMove}
onTouchEnd={this.handleTouchEnd}
id={instancePrefix + '-option-' + optionIndex}
title={option.title}>
{this.props.children}
</div>
);
}
});
module.exports = Option;
|
lib-es/elements/addons.js | bokuweb/re-bulma | 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 React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from '../../build/styles';
import { getCallbacks } from '../helper/helper';
export default class Addons extends Component {
createControlClassName() {
return [styles.control, styles.hasAddons, this.props.className, this.props.hasAddonsCentered ? styles.hasAddonsCentered : '', this.props.hasAddonsRight ? styles.hasAddonsRight : ''].join(' ').trim();
}
cloneWithProps() {
if (React.Children.count(this.props.children) === 1) {
return this.props.children && React.cloneElement(this.props.children, {
color: this.props.color,
hasAddons: true
});
}
return this.props.children.map((child, i) => React.cloneElement(child, {
color: this.props.color,
key: i,
hasAddons: true
}));
}
renderHelp() {
if (!this.props.help) return null;
return React.createElement(
'span',
{ className: [styles.help, styles[this.props.help.color]].join(' ') },
this.props.help.text
);
}
render() {
return React.createElement(
'span',
null,
React.createElement(
'p',
_extends({
className: this.createControlClassName(),
style: this.props.style
}, getCallbacks(this.props)),
this.props.children && this.cloneWithProps()
),
this.renderHelp()
);
}
}
Addons.propTypes = {
className: PropTypes.string,
style: PropTypes.object,
children: PropTypes.any,
color: PropTypes.oneOf(['isPrimary', 'isInfo', 'isSuccess', 'isWarning', 'isDanger', 'isLink', 'isWhite', 'isLight', 'isDark', 'isBlack', 'isLink']),
help: PropTypes.shape({
text: PropTypes.string,
color: PropTypes.oneOf(['isPrimary', 'isInfo', 'isSuccess', 'isWarning', 'isDanger'])
}),
hasAddonsCentered: PropTypes.bool,
hasAddonsRight: PropTypes.bool
};
Addons.defaultProps = {
style: {},
className: ''
}; |
bai/src/pages/About/index.js | blackinai/blackinai.github.io | import { CssBaseline, ThemeProvider } from '@material-ui/core';
import React from 'react';
import AboutHeader from '../../components/AboutHeader';
import CommunityValues from '../../components/CommunityValues';
import Footer from '../../components/Footer';
import JoinUs from '../../components/JoinUs';
import Navbar from '../../components/Navbar';
import TeamMembers from '../../components/TeamMembers';
import Loader from '../../loader';
import theme from './../../theme';
function About() {
return (
<ThemeProvider theme={theme}>
<Loader />
<CssBaseline />
<Navbar />
<AboutHeader />
<CommunityValues />
<TeamMembers />
<JoinUs />
<Footer />
</ThemeProvider>
);
}
export default About; |
react-shrine-network-aware-code-splitting/src/components/ProductImage/ProductZoomImage/ProductZoomImage.js | GoogleChromeLabs/adaptive-loading | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import Magnifier from 'react-magnifier';
import ProductImageWrapper from '../../../hoc/ProductImageWrapper/ProductImageWrapper';
const ProductZoomImage = ({ product, close }) => (
<ProductImageWrapper title={product.title} close={close}>
<Magnifier src={product.imageUrl} width={500} />
</ProductImageWrapper>
);
export default ProductZoomImage;
|
docs/src/new-components/basics/tooltip/TooltipNote.stories.js | storybooks/react-storybook | import React from 'react';
import { storiesOf } from '@storybook/react';
import WithTooltip from './WithTooltip';
import TooltipNote from './TooltipNote';
storiesOf('basics/tooltip/TooltipNote', module)
.addParameters({
component: TooltipNote,
})
.addDecorator(storyFn => (
<div style={{ height: '300px' }}>
<WithTooltip hasChrome={false} placement="top" trigger="click" startOpen tooltip={storyFn()}>
<div>Tooltip</div>
</WithTooltip>
</div>
))
.add('default', () => <TooltipNote note="Lorem ipsum dolor" />);
|
test/integration/css-fixtures/single-global-src/src/pages/_app.js | azukaru/next.js | import React from 'react'
import App from 'next/app'
import '../../styles/global.css'
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
|
teoria02/componentes/UnaTarea.js | mart-dominguez/OFA2017-S01-C02 | import React from 'react';
import EditarUnaTarea from './EditarUnaTarea';
class UnaTarea extends React.Component {
constructor(props) {
super(props);
this.state = {editar:false};
this.toggleEditar = this.toggleEditar.bind(this);
}
toggleEditar(){
let aux = !this.state.editar;
this.setState({editar: aux});
}
render(){
let tarea = undefined;
if(this.state.editar) {
tarea =<EditarUnaTarea indice={this.props.indice} onTareaChange={this.props.actualizar} tarea={this.props.tarea} guardar={this.toggleEditar}></EditarUnaTarea>
}else{
tarea = <li>
<strong>{this.props.tarea.titulo}</strong>
<span>{this.props.tarea.estado}</span>
<button onClick={this.toggleEditar}>editar</button>
</li>
}
return tarea;
}
}
export default UnaTarea; |
src/components/Book/Main/Views/Common/tpl.js | LifeSourceUA/lifesource.ua | /**
* [IL]
* Library Import
*/
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
/**
* [IS]
* Style Import
*/
import Styles from './Styles/main.scss';
import Grid from 'theme/Grid.scss';
import Palette from 'theme/Palette';
/**
* [IBP]
* Pixel Perfect and Breakpoints
*/
import BP from 'lib/breakpoints';
import Label from 'components/Assets/LabelEdge.js';
import Content from 'components/Assets/Content.js';
import Book from 'components/Assets/Book.js';
import Arrow from 'components/Assets/Arrow.js';
import Ua from 'components/Assets/UA.js';
// import Ru from 'components/Assets/RU.js';
function Common(props) {
const { mediaType } = props;
const seriesBooks = BP.isTabletPortrait(mediaType) || BP.isDesktop(mediaType) ? (
<div className={ Styles.seriesBooks }>
<Label className={ Styles.labelStart } color1={ Palette.midGray }/>
серия книг
<Label className={ Styles.labelEnd } color1={ Palette.midGray }/>
</div>
) : null;
const arrowBack = BP.isDesktop(mediaType) || BP.isTabletPortrait(mediaType) ? (
<div className={ Styles.arrowBack }>
<div className={ Styles.circle }>
<Arrow color={ Palette.red }/>
</div>
{ BP.isDesktop(mediaType) ? 'перейти к списку книг' : null }
</div>
) : null;
const language = BP.isDesktop(mediaType) || BP.isTabletPortrait(mediaType) ? (
<div className={ Styles.language }>
<Ua className={ Styles.flag }/>
{ BP.isDesktop(mediaType) ? (<span className={ Styles.text }>Історії про справжніх</span>) : null }
{ BP.isDesktop(mediaType) ? <Arrow className={ Styles.arrow } color={ Palette.darkGray }/> : null }
</div>
) : null;
const secondAuthor = BP.isTabletPortrait(mediaType) || BP.isDesktop(mediaType) ? (
<h2 className={ Styles.author }>Лори Пекхем
<label className={ Styles.dot }/>
</h2>
) : null;
const description = BP.isDesktop(mediaType) ? (
<p className={ Styles.description }>Вы когда-нибудь чувствовали,
что ваши отношения рушатся? Задумывались ли вы, почему не можете найти того единственного и неповторимого?
</p>
) : null;
const hoverBook = BP.isDesktop(mediaType) ? (
<div className={ Styles.hoverBook }><Book className={ Styles.book } color={ Palette.green }/></div>
) : null;
const popupClasses = cx({
[Styles.popup]: true,
[Styles.active]: false
});
const poapWindow = BP.isDesktop(mediaType) ? (
<div className={ popupClasses }>
<ul className={ Styles.list }>
<li className={ Styles.item }>Вступление</li>
<li className={ Styles.item }>Предисловие</li>
<li className={ Styles.item }>
<ul className={ Styles.sublist }>
<li className={ Styles.item }>Как сносить удары судьбы</li>
<li className={ Styles.item }>Как бороться с ленью</li>
<li className={ Styles.item }>Что такое смерение</li>
<li className={ Styles.item }>Когда нужно уступать</li>
<li className={ Styles.item }>Компромисс</li>
</ul>
</li>
<li className={ Styles.item }>Умеем ли мы слушать?</li>
<li className={ Styles.item }>Искусство слушать</li>
<li className={ Styles.item }>Нехорошо быть одному</li>
<li className={ Styles.item }>Умеем ли мы слушать?</li>
<li className={ Styles.item }>Искусство слушать</li>
<li className={ Styles.item }>Нехорошо быть одному</li>
<li className={ Styles.item }>Умеем ли мы слушать?</li>
<li className={ Styles.item }>Искусство слушать</li>
<li className={ Styles.item }>Нехорошо быть одному</li>
</ul>
</div>
) : null;
const content = BP.isTabletPortrait(mediaType) || BP.isDesktop(mediaType) ? (
<a className={ Styles.tableOfContents }>
<Content color={ Palette.darkGray }/>
Оглавление
{ poapWindow }
</a>
) : null;
const wrap = cx({
[Grid.container]: true,
[Styles.wrap]: true
});
return (
<section className={ Styles.mainComponent }>
<section className={ wrap }>
<div className={ Styles.containerContent }>
{ arrowBack }
<div className={ Styles.content }>
<div className={ Styles.image }>
{ hoverBook }
<div className={ Styles.topLayer }/>
<div className={ Styles.middleLayer }/>
<div className={ Styles.bottomLayer }/>
<span className={ Styles.labelNum }>
<Label className={ Styles.label } color1={ Palette.midGray }/>
5
</span>
<span className={ Styles.labelNew }>
<Label className={ Styles.label } color={ Palette.red } color1={ Palette.red }/>
</span>
</div>
<div className={ Styles.info }>
<h1 className={ Styles.title }>Истории о настоящих героях</h1>
<div className={ Styles.authors }>
{ secondAuthor }
<h2 className={ Styles.author }>Алехандро Буйон</h2>
</div>
<div className={ Styles.tags }>
<div className={ Styles.new }>
<Label
className={ Styles.labelStart }
color={ Palette.red }
color1={ Palette.red }
/>
новинка
<Label className={ Styles.labelEnd } color={ Palette.red } color1={ Palette.red }/>
</div>
{ seriesBooks }
<div className={ Styles.class }>здоровье и семья</div>
</div>
<div className={ Styles.buttons }>
{ content }
<a className={ Styles.read }>
<Book className={ Styles.book } color={ Palette.green }/>
Читать фрагмент книги
</a>
</div>
{ description }
</div>
</div>
{ language }
</div>
</section>
</section>
);
}
/**
* [CPT]
* Component prop types
*/
Common.propTypes = {
mediaType: PropTypes.string.isRequired
};
/**
* [IE]
* Export
*/
export default Common;
|
packages/editor/src/components/Icons/List.js | strues/boldr | import React from 'react';
import Icon from './Icon';
const List = props => (
<Icon viewBox="0 0 512 512" {...props}>
<path d="M500 124H140c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h360c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm12 148v-32c0-6.627-5.373-12-12-12H140c-6.627 0-12 5.373-12 12v32c0 6.627 5.373 12 12 12h360c6.627 0 12-5.373 12-12zm0 160v-32c0-6.627-5.373-12-12-12H140c-6.627 0-12 5.373-12 12v32c0 6.627 5.373 12 12 12h360c6.627 0 12-5.373 12-12zM92 128V64c0-6.627-5.373-12-12-12H16C9.373 52 4 57.373 4 64v64c0 6.627 5.373 12 12 12h64c6.627 0 12-5.373 12-12zm0 160v-64c0-6.627-5.373-12-12-12H16c-6.627 0-12 5.373-12 12v64c0 6.627 5.373 12 12 12h64c6.627 0 12-5.373 12-12zm0 160v-64c0-6.627-5.373-12-12-12H16c-6.627 0-12 5.373-12 12v64c0 6.627 5.373 12 12 12h64c6.627 0 12-5.373 12-12z" />
</Icon>
);
List.defaultProps = { name: 'List' };
export default List;
|
src/svg-icons/action/open-in-new.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionOpenInNew = (props) => (
<SvgIcon {...props}>
<path d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"/>
</SvgIcon>
);
ActionOpenInNew = pure(ActionOpenInNew);
ActionOpenInNew.displayName = 'ActionOpenInNew';
ActionOpenInNew.muiName = 'SvgIcon';
export default ActionOpenInNew;
|
src/parser/warrior/arms/CHANGELOG.js | sMteX/WoWAnalyzer | import React from 'react';
import { Aelexe, Zerotorescue, Sharrq, Matardarix, Korebian } from 'CONTRIBUTORS';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
export default [
{
date: new Date('2019-02-03'),
changes: <>Added a suggestion to not use <SpellLink id={SPELLS.SWEEPING_STRIKES.id} /> during <SpellLink id={SPELLS.COLOSSUS_SMASH.id} /> / <SpellLink id={SPELLS.WARBREAKER_TALENT.id} />.</>,
contributors: [Korebian],
},
{
date: new Date('2019-02-02'),
changes: <>Added more information to the <SpellLink id={SPELLS.CRUSHING_ASSAULT_TRAIT.id} /> module. Added <SpellLink id={SPELLS.LORD_OF_WAR.id} /> module.</>,
contributors: [Korebian],
},
{
date: new Date('2018-12-12'),
changes: <>Updated for patch 8.1, <SpellLink id={SPELLS.CHARGE.id} /> is no longer on the GCD and <SpellLink id={SPELLS.EXECUTIONERS_PRECISION_TRAIT.id} /> have been replaced by <SpellLink id={SPELLS.STRIKING_THE_ANVIL.id} />.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-28'),
changes: <>Added <SpellLink id={SPELLS.CRUSHING_ASSAULT_TRAIT.id} /> module.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-15'),
changes: <>Fixed Overpower events where stacks were applied before casts</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-14'),
changes: <>Added a suggestion on using <SpellLink id={SPELLS.SLAM.id} /> while <SpellLink id={SPELLS.MORTAL_STRIKE.id} /> is available.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-12'),
changes: <>Added <SpellLink id={SPELLS.FERVOR_OF_BATTLE_TALENT.id} /> in Talents module.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-10'),
changes: <>Modified <SpellLink id={SPELLS.MORTAL_STRIKE.id} /> analysis to get it more accurate with the execution phase.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-07'),
changes: <>Added Rage usage tab and suggestions on rage wast, removed the doughnut chart for rage usage</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-06'),
changes: <>Added cooldown tracker tab</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-05'),
changes: <>New:<ul><li>Checklist</li><li>Talents module</li><li><SpellLink id={SPELLS.EXECUTIONERS_PRECISION_TRAIT.id} /> module</li><li><SpellLink id={SPELLS.SEISMIC_WAVE.id} /> module</li><li><SpellLink id={SPELLS.TEST_OF_MIGHT.id} /> module</li><li>rage usage module</li><li>suggestions regarding <SpellLink id={SPELLS.DEFENSIVE_STANCE_TALENT.id} /></li></ul>Fixed:<ul><li><SpellLink id={SPELLS.ANGER_MANAGEMENT_TALENT.id} /> cooldown reduction calculation</li></ul></>,
contributors: [Matardarix],
},
{
date: new Date('2018-10-12'),
changes: <>Fixed some spell IDs and ability information. Updated Config.</>,
contributors: [Sharrq],
},
{
date: new Date('2018-06-30'),
changes: <>Update all abilities to new BFA values, removed incompatible modules and added an <SpellLink id={SPELLS.ANGER_MANAGEMENT_TALENT.id} /> statistic.</>,
contributors: [Zerotorescue],
},
{
date: new Date('2018-06-16'),
changes: <>Fixed a rare crash when casting <SpellLink id={SPELLS.EXECUTE.id} /> on a non-boss target.</>,
contributors: [Aelexe],
},
];
|
src/app-client.js | keshan3262/weather | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import {Provider} from 'react-redux';
import configureStore from './stores/configureStore';
import Layout from './components/Layout';
import LoginPage from './components/LoginPage';
import SignupPage from './components/SignupPage';
import WeatherPage from './components/WeatherPage';
import axios from 'axios';
import NotFoundPage from './components/NotFoundPage';
import reactCookie from 'react-cookie';
var store = configureStore({
weather: {now: {}, forecast: []},
cities: {data: []},
signupLoginLogout: {}
});
window.onload = () => {
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path='/' component={Layout}>
<IndexRoute component={LoginPage}/>
<Route path='/signup' component={SignupPage}/>
<Route path='/weather' component={WeatherPage}
onEnter={(nextState, replace, callback) => {
var sessionID = reactCookie.load('sessionID');
console.log(sessionID);
if (sessionID == null) {
replace('/');
callback();
}
else
axios.get('/api/cities').then((res) => {
callback();
}).catch((err) => {
if (err.response == null) {
callback(err);
}
else {
var status = err.response.status;
if ((status >= 400) && (status < 404)) {
replace('/');
callback();
}
else
callback(err);
}
});
}}/>
<Route path="*" component={NotFoundPage}/>
</Route>
</Router>
</Provider>,
document.getElementById('container')
);
} |
datarequester/src/App.js | e-nettet/CustomerConsentWallet | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import NavBar from './NavBar.js';
import ApplyForConcentForm from './ApplyForConcentForm.js';
class App extends Component {
render() {
return (
<div>
<NavBar />
<div className="container theme-showcase" role="main">
<div className="jumbotron">
<div className="page-header">
<h3>Welcome to Data Requestor</h3>
</div>
<ApplyForConcentForm />
</div>
</div>
</div>
);
}
}
export default App;
|
tests/react_children/tabs.js | MichaelDeBoey/flow | // @flow
/**
* This test represents a pattern which is commonly used to make tab bars, but
* this pattern is also used in many other places.
*/
import React from 'react';
class Tab extends React.Component<{}, void> {}
class NotTab extends React.Component<{}, void> {}
type TabBarNode =
| void
| null
| boolean
| React$Element<typeof Tab>
| Array<TabBarNode>; // NOTE: This is intentionally `Array<T>` and not
// `Iterable<T>` because `strings` are `Iterable<string>`
// which is then `Iterable<Iterable<string>>` recursively
// making strings valid children when we use
// `Iterable<T>`.
class TabBar extends React.Component<{children: TabBarNode}, void> {}
<TabBar />; // Error: `children` is required.
<TabBar><Tab/></TabBar>; // OK: We can have a single tab.
<TabBar><Tab/><Tab/></TabBar>; // OK: We can have two tabs.
<TabBar> <Tab/><Tab/></TabBar>; // Error: Spaces are strings.
<TabBar><Tab/> <Tab/></TabBar>; // Error: Spaces are strings.
<TabBar><Tab/><Tab/> </TabBar>; // Error: Spaces are strings.
// OK: We can have a single tab on multiple lines.
<TabBar>
<Tab/>
</TabBar>;
// OK: We can have a multiple tabs on multiple lines.
<TabBar>
<Tab/>
<Tab/>
<Tab/>
</TabBar>;
// OK: We can have an array of tabs.
<TabBar>
{[
<Tab/>,
<Tab/>,
<Tab/>,
]}
</TabBar>;
// OK: We can have two arrays of tabs.
<TabBar>
{[
<Tab/>,
<Tab/>,
]}
{[
<Tab/>,
<Tab/>,
]}
</TabBar>;
<TabBar><NotTab/></TabBar>; // Error: We can only have tab components.
<TabBar><NotTab/><NotTab/></TabBar>; // Error: We can only have tab components.
// Error: Nope, can't sneak a non-tab in there.
<TabBar>
<Tab/>
<NotTab/>
<Tab/>
<Tab/>
</TabBar>;
// OK: Booleans are allowed in the type.
<TabBar>
{Math.random() > 0.5 && <Tab/>}
</TabBar>;
// OK: Booleans are allowed in the type.
<TabBar>
{Math.random() > 0.5 && <Tab/>}
{Math.random() > 0.5 && <Tab/>}
</TabBar>;
|
front/client/components/CommunityList/index.js | ytorii/tebukuro | import React from 'react'
import CommunityListModel from '../../models/CommunityList'
const CommunityList = ({CommunityList}) => {
return (
<table>
<thead>
<tr>
<th>name</th>
</tr>
</thead>
<tbody>
{
CommunityList.communities.map((community) => {
return (
<tr key={community.id}>
<td>{community.name}</td>
</tr>
)
})
}
</tbody>
</table>
)
}
CommunityList.propTypes = {
CommunityList : React.PropTypes.instanceOf(CommunityListModel).isRequired,
}
export default CommunityList
|
packages/react-vis/src/legends/discrete-color-legend.js | uber/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import PropTypes from 'prop-types';
import DiscreteColorLegendItem from 'legends/discrete-color-legend-item';
import {DISCRETE_COLOR_RANGE} from 'theme';
import {getCombinedClassName} from 'utils/styling-utils';
function DiscreteColorLegend({
className,
colors,
height,
items,
onItemClick,
onItemMouseEnter,
onItemMouseLeave,
orientation,
style,
width
}) {
return (
<div
className={getCombinedClassName(
'rv-discrete-color-legend',
orientation,
className
)}
style={{width, height, ...style}}
>
{items.map((item, i) => (
<DiscreteColorLegendItem
title={item.title ? item.title : item}
color={item.color ? item.color : colors[i % colors.length]}
strokeDasharray={item.strokeDasharray}
strokeStyle={item.strokeStyle}
strokeWidth={item.strokeWidth}
disabled={Boolean(item.disabled)}
orientation={orientation}
key={i}
onClick={onItemClick ? e => onItemClick(item, i, e) : null}
onMouseEnter={
onItemMouseEnter ? e => onItemMouseEnter(item, i, e) : null
}
onMouseLeave={
onItemMouseEnter ? e => onItemMouseLeave(item, i, e) : null
}
/>
))}
</div>
);
}
DiscreteColorLegend.displayName = 'DiscreteColorLegendItem';
DiscreteColorLegend.propTypes = {
className: PropTypes.string,
items: PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.shape({
title: PropTypes.oneOfType([PropTypes.string, PropTypes.element])
.isRequired,
color: PropTypes.string,
disabled: PropTypes.bool
}),
PropTypes.string.isRequired,
PropTypes.element
])
).isRequired,
onItemClick: PropTypes.func,
onItemMouseEnter: PropTypes.func,
onItemMouseLeave: PropTypes.func,
height: PropTypes.number,
width: PropTypes.number,
orientation: PropTypes.oneOf(['vertical', 'horizontal'])
};
DiscreteColorLegend.defaultProps = {
className: '',
colors: DISCRETE_COLOR_RANGE,
orientation: 'vertical'
};
export default DiscreteColorLegend;
|
app/javascript/mastodon/features/domain_blocks/index.js | pinfort/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import DomainContainer from '../../containers/domain_container';
import { fetchDomainBlocks, expandDomainBlocks } from '../../actions/domain_blocks';
import ScrollableList from '../../components/scrollable_list';
const messages = defineMessages({
heading: { id: 'column.domain_blocks', defaultMessage: 'Blocked domains' },
unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' },
});
const mapStateToProps = state => ({
domains: state.getIn(['domain_lists', 'blocks', 'items']),
hasMore: !!state.getIn(['domain_lists', 'blocks', 'next']),
});
export default @connect(mapStateToProps)
@injectIntl
class Blocks extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
hasMore: PropTypes.bool,
domains: ImmutablePropTypes.orderedSet,
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchDomainBlocks());
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandDomainBlocks());
}, 300, { leading: true });
render () {
const { intl, domains, shouldUpdateScroll, hasMore, multiColumn } = this.props;
if (!domains) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.domain_blocks' defaultMessage='There are no blocked domains yet.' />;
return (
<Column bindToDocument={!multiColumn} icon='minus-circle' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollableList
scrollKey='domain_blocks'
onLoadMore={this.handleLoadMore}
hasMore={hasMore}
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
>
{domains.map(domain =>
<DomainContainer key={domain} domain={domain} />,
)}
</ScrollableList>
</Column>
);
}
}
|
src/SegmentedControl/macOs/Tabs/index.js | gabrielbull/react-desktop | import React, { Component } from 'react';
import Tab from './Tab';
import styles from '../style/10.11';
class Tabs extends Component {
select(item) {
this.refs[item.props.tabId].setState({ selected: true });
}
unselect(item) {
this.refs[item.props.tabId].setState({ selected: false });
}
render() {
const { style } = this.props;
let children;
// todo: use Children.map
if (!this.props.children) {
return null;
} else if (
Object.prototype.toString.call(this.props.children) !== '[object Array]'
) {
children = [this.props.children];
} else {
children = [...this.props.children];
}
let tabs = [];
let hasSelected = false;
for (let i = 0, len = children.length; i < len; ++i) {
let props = children[i].props;
if (props.selected) hasSelected = true;
if (i === 0) props = { ...props, firstChild: true };
if (i === len - 1) props = { ...props, lastChild: true };
if (
children[i + 1] &&
children[i + 1].props &&
children[i + 1].props.selected
) {
props = { ...props, nextSelected: true };
}
tabs = [...tabs, props];
}
if (!hasSelected && tabs[0]) tabs[0].selected = true;
let prevSelectedIndex = null;
let afterSelected = false;
for (let i = 0, len = tabs.length; i < len; ++i) {
if (afterSelected) {
tabs[i] = { ...tabs[i], afterSelected: true };
afterSelected = false;
}
if (tabs[i].selected) {
afterSelected = true;
prevSelectedIndex = i - 1;
}
}
if (prevSelectedIndex >= 0 && tabs[prevSelectedIndex])
tabs[prevSelectedIndex] = {
...tabs[prevSelectedIndex],
prevSelected: true
};
return (
<div style={{ ...styles.tabs, ...style }}>{this.renderTabs(tabs)}</div>
);
}
renderTabs(tabs) {
const children = [];
for (let i = 0, len = tabs.length; i < len; ++i) {
children.push(
<Tab key={i} {...tabs[i]}>
{tabs[i].title}
</Tab>
);
}
return children;
}
}
export default Tabs;
|
packages/icons/src/md/image/CameraRoll.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdCameraRoll(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M28 11h16v30H28c0 2.21-1.79 4-4 4H8c-2.21 0-4-1.79-4-4V11c0-2.21 1.79-4 4-4h2V5c0-1.1.9-2 2-2h8c1.1 0 2 .9 2 2v2h2c2.21 0 4 1.79 4 4zm-4 26v-4h-4v4h4zm0-18v-4h-4v4h4zm8 18v-4h-4v4h4zm0-18v-4h-4v4h4zm8 18v-4h-4v4h4zm0-18v-4h-4v4h4z" />
</IconBase>
);
}
export default MdCameraRoll;
|
node_modules/semantic-ui-react/src/collections/Form/FormSelect.js | mowbell/clickdelivery-fed-test | import React from 'react'
import {
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
import Select from '../../addons/Select'
import FormField from './FormField'
/**
* Sugar for <Form.Field control={Select} />.
* @see Form
* @see Select
*/
function FormSelect(props) {
const { control } = props
const rest = getUnhandledProps(FormSelect, props)
const ElementType = getElementType(FormSelect, props)
return <ElementType {...rest} control={control} />
}
FormSelect._meta = {
name: 'FormSelect',
parent: 'Form',
type: META.TYPES.COLLECTION,
}
FormSelect.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** A FormField control prop. */
control: FormField.propTypes.control,
}
FormSelect.defaultProps = {
as: FormField,
control: Select,
}
export default FormSelect
|
src/bookmarks/BookmarkButton.js | Sekhmet/busy | import React from 'react';
import { injectIntl } from 'react-intl';
import { SimpleTooltipOrigin } from '../widgets/tooltip/SimpleTooltip';
import Icon from '../widgets/Icon';
const BookmarkButton = ({ post, bookmarks, toggleBookmark, intl }) =>
<SimpleTooltipOrigin message={
intl.formatMessage({
id: bookmarks[post.id]
? '@tooltip_remove_bookmark'
: '@tooltip_add_bookmark',
defaultMessage: bookmarks[post.id] ?
'Remove from bookmarks' :
'Add in bookmarks',
})}
>
<a onClick={() => toggleBookmark(post.id)} className="PostFeedList__cell__bookmark">
<Icon
name={bookmarks[post.id] ? 'bookmark' : 'bookmark_border'}
/>
</a>
</SimpleTooltipOrigin>;
export default injectIntl(BookmarkButton);
|
app/pods/mockup/builder/container.js | slightlytyler/mocksy | 'use strict'
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import {
setCurrentTemplate
} from 'pods/templates/actions';
import {
currentTemplateSelector,
currentTemplateSetIdSelector,
currentTemplateSetSelector
} from 'pods/templates/selectors';
import { setCurrentScreenshot } from 'pods/screenshots/actions';
import { currentScreenshotSelector } from 'pods/screenshots/selectors';
import {
addSize,
removeSize,
updateSize
} from 'pods/sizes/actions';
import { sizesRecordsSelector } from 'pods/sizes/selectors';
import IndexComponent from './component';
function mapStateToProps(state) {
const { present } = state;
return {
templates: currentTemplateSetSelector(present),
currentTemplate: currentTemplateSelector(present),
currentTemplateSetId: currentTemplateSetIdSelector(present),
currentScreenshot: currentScreenshotSelector(present),
sizes: sizesRecordsSelector(present)
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
setCurrentTemplate,
setCurrentScreenshot,
addSize,
removeSize,
updateSize
}, dispatch);
}
function mergeProps(stateProps, dispatchProps, ownProps) {
return Object.assign({}, stateProps, {
actions: {
...dispatchProps
}
})
}
export default connect(
mapStateToProps,
mapDispatchToProps,
mergeProps
)(IndexComponent);
|
libs/composites/interfaces/react-dom-server-interface-composite.js | tuantle/hyperflow | /**
* Copyright 2018-present Tuan Le.
*
* Licensed under the MIT License.
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*------------------------------------------------------------------------
*
* @module ReactDOMServerComponentComposite
* @description - A React DOM server component interface factory composite.
*
* @author Tuan Le ([email protected])
*/
/* @flow */
'use strict'; // eslint-disable-line
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {
ENV,
// isNonEmptyString,
isFunction,
isObject,
isSchema,
fallback,
log
} from '../../utils/common-util';
import Composite from '../../../src/composite';
export default Composite({
template: {
/**
* @description - Initialized and check that factory is valid for this composite.
*
* @method $initReactDOMServerComponentComposite
* @return void
*/
$initReactDOMServerComponentComposite () {
const intf = this;
if (ENV.DEVELOPMENT) {
if (!isSchema({
name: `string`,
type: `string`,
incoming: `function`,
outgoing: `function`,
getInterfacedComponent: `function`
}).of(intf) || intf.type !== `interface`) {
log(`error`, `ReactDOMServerComponentComposite.$init - Interface is invalid. Cannot apply composite.`);
}
}
},
/**
* @description - Render app top level component to the target environment.
*
* @method renderToTarget
* @param {string} targetId
* @param {object} option
* @return [stream|string]
*/
renderToTarget (targetId, option = {
useStaticMarkup: false,
useNodeStream: false
}) {
const intf = this;
const Component = intf.getInterfacedComponent(option);
if (ENV.DEVELOPMENT) {
if (!intf.isStreamActivated()) {
log(`error`, `ReactDOMServerComponentComposite.renderToTarget - Interface:${intf.name} render to target cannot be call before event stream activation.`);
}
// if (!isNonEmptyString(targetId)) {
// log(`error`, `ReactDOMServerComponentComposite.renderToTarget - Interface:${intf.name} target Id key is invalid.`);
// }
if (!(isFunction(Component) || isObject(Component))) {
log(`error`, `ReactDOMServerComponentComposite.renderToTarget - Interface:${intf.name} React component is invalid.`);
}
}
const {
useStaticMarkup,
useNodeStream
} = fallback({
useStaticMarkup: false,
useNodeStream: false
}).of(option);
let render;
if (useStaticMarkup) {
render = useNodeStream ? ReactDOMServer.renderToStaticNodeStream : ReactDOMServer.renderToStaticMarkup;
} else {
render = useNodeStream ? ReactDOMServer.renderToNodeStream : ReactDOMServer.renderToString;
}
log(`info1`, `Rendering to target Id:${targetId} for interface:${intf.name}.`);
const html = render(
<Component/>
);
intf.outgoing(`on-component-${intf.name}-render-to-target`).emit(() => html);
return html;
}
}
});
|
src/components/Homepage.js | NemethNorbert/restaurant-website | import React from 'react';
import Slider from 'react-slick';
import LeftArrow from './LeftArrow';
import RightArrow from './RightArrow';
import {NavLink} from 'reactstrap';
import { NavLink as RRNavLink } from 'react-router-dom';
class Homepage extends React.PureComponent {
render() {
const settings = {
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 5000,
centerMode: false,
pauseOnHover:true,
focusOnSelect: true,
nextArrow: <RightArrow {...this.props} />,
prevArrow: <LeftArrow {...this.props} />
};
return (
<div className="">
<div className="row menuWrapper clearfix">
<div className="container">
<div className="menuBox text-center">
<div className="menuTitle">
<p className="lead">Térj be hozzánk</p>
<p className="menuText">Elegáns kényelem, figyelmes kiszolgálást és a bisztrók üde, ráérős hangulata fogad a plázai forgatagban is. Ropogós szendvicsek, friss saláták és francia finomságok várják, hogy belefeledkezz az ízek kavalkádjába.</p>
</div>
</div>
<NavLink to={process.env.PUBLIC_URL+'/Pekseg'} tag={RRNavLink} className="menu menu1">
<div className="menuImage"></div>
<div className="wrapp text-center">
<div className="menuTitle">
<h3 className="lead">Pékség</h3>
<p className="menuText">francia pékárú</p>
</div>
</div>
</NavLink>
<NavLink to={process.env.PUBLIC_URL+'/Etelek'} tag={RRNavLink} className="menu menu2">
<div className="menuImage"></div>
<div className="wrapp text-center">
<div className="menuTitle">
<h3 className="lead">Ételek</h3>
<p className="menuText">francia pékárú</p>
</div>
</div>
</NavLink>
<NavLink to={process.env.PUBLIC_URL+'/Italok'} tag={RRNavLink} className="menu small1">
<div className="menuImage"></div>
<div className="wrapp text-center">
<div className="menuTitle">
<h3 className="lead">Italok</h3>
<p className="menuText">francia pékárú</p>
</div>
</div>
</NavLink>
<NavLink to={process.env.PUBLIC_URL+'/Etelek'} tag={RRNavLink} className="menu small2">
<div className="menuImage"></div>
<div className="wrapp text-center">
<div className="menuTitle">
<h3 className="lead">Desszertek</h3>
<p className="menuText">francia pékárú</p>
</div>
</div>
</NavLink>
</div>
</div>
<div className="row text-align bg-clear pad line">
<div className="col-lg-4 col-md-4 lineWrapper">
<h3 className="lead text-center">Mi a titkunk?</h3>
<hr className="hr bg-brown"/>
<div className="padB text-center">Egy csipetnyi Franciaország, egy kiskanálnyi Itália és a harmónikus ízek szenvedélyes szeretete.</div>
</div>
<div className="col-lg-4 col-md-4 text-center padB lineWrapper">
<img src={process.env.PUBLIC_URL + "/pictures/brand/linepic1.png"} className="linepic"/>
</div>
<div className="col-lg-4 col-md-4 lineWrapper">
<h3 className="lead text-center">Mániánk a minőség</h3>
<hr className="hr bg-brown"/>
<div className="padB text-center">Ha a minőség van terítéken, nem ismerünk pardont. Csakis a legkiválóbb alapanyagokból és eljárásokkal dolgozunk, gondosan válogatott és fejlesztett receptek alapján.</div>
<NavLink to={process.env.PUBLIC_URL+'/About'} tag={RRNavLink} className="btn btn-outline-brown">A titok</NavLink>
</div>
</div>
<div className="row bigline bg-look text-center">
<div className="col-lg-6 col-md-6 lineWrapper text-white pad">
<h3 className="lead text-center">Menj biztosra!</h3>
<hr className="hr bg-brown"/>
<div className="padB text-center">Találd meg a kedvencedet villámgyorsan! Vegára vágysz vagy oda vagy az olasz szalámiért? Keress akár típusra vagy hozzávalóra is!</div>
</div>
<div className="col-lg-6 col-md-6 lineWrapper">
<NavLink to={process.env.PUBLIC_URL+'/Etelek'} tag={RRNavLink}><img src={process.env.PUBLIC_URL + "/pictures/brand/biglinepic.png"} className="searchImg" /></NavLink>
</div>
</div>
<div className="row text-align bg-clear pad line">
<div className="col-lg-4 col-md-4 col-sm-6 lineWrapper bg-line2">
<h3 className="lead text-center">Franciaországból a tányérodra</h3>
<div className="padB text-center">frissen, ropogósan</div>
</div>
<div className="col-lg-4 col-md-4 col-sm-6 text-center padB lineWrapper">
<img src={process.env.PUBLIC_URL + "/pictures/brand/linepic2.png"} className="linepic"/>
</div>
<div className="col-lg-4 col-md-4 col-sm-12 lineWrapper mobfixer">
<h3 className="lead text-center">Melegen ajánljuk</h3>
<hr className="hr bg-brown"/>
<div className="padB text-center">Francia receptúra alapján készült péktermékeinket minden reggel mi magunk sütjük házi pékségünkben. Mi sem természetesebb, hogy szendvicdseinket is a frissen sült bagettekből és ciabbatákból készítjük. Így lesz ropogós a szendvics, Párizst idéző a croissant és omlós a muffin.</div>
</div>
</div>
<div className="container text-center" style={{width:"90%"}}>
<NavLink to={process.env.PUBLIC_URL+'/Galeria'} tag={RRNavLink}><div className="galeria"><div className="galeriaText">Galéria</div></div></NavLink>
<Slider {...settings} className="galeriaSlider">
<div className="sliderBox text-white">
<blockquote className="blockquote sliderText">
<p className="mb-0">„Kurvajó minden”</p>
<footer className="blockquote-footer text-silent">Rólunk írta - Egy random arc</footer>
</blockquote>
</div>
<div className="sliderBox text-white">
<blockquote className="blockquote sliderText">
<p className="mb-0">„Igazi olasz sonka”</p>
<footer className="blockquote-footer text-silent">Rólunk írta - Egy random arc</footer>
</blockquote>
</div>
<div className="sliderBox text-white">
<blockquote className="blockquote sliderText">
<p className="mb-0">„Egy gasztronomiai csoda”</p>
<footer className="blockquote-footer text-silent">Rólunk írta - Egy random arc</footer>
</blockquote>
</div>
<div className="sliderBox text-white">
<blockquote className="blockquote sliderText">
<p className="mb-0">„Minden nap itt reggelizem”</p>
<footer className="blockquote-footer text-silent">Rólunk írta - Egy random arc</footer>
</blockquote>
</div>
</Slider>
</div>
<div className="row bigline bg-contact">
<div className="col-lg-6 col-md-6 lineWrapper text-center">
<NavLink to={process.env.PUBLIC_URL+'/Etelek'} tag={RRNavLink}><img src={process.env.PUBLIC_URL + "/pictures/brand/google.png"} className="google" /></NavLink>
</div>
<div className="col-lg-6 col-md-6 lineWrapper text-white pad">
<h3 className="lead text-center">Elérhetőségeink</h3>
<hr className="hr bg-brown"/>
<table className="table cont text-center">
<tbody>
<tr>
<th scope="row"><i className="fa fa-map-marker" aria-hidden="true"></i></th>
<td>1138 Budapest, Váci út 178.,<br />Duna Plaza II. emelet</td>
</tr>
<tr>
<th scope="row"><i className="fa fa-phone-square" aria-hidden="true"></i></th>
<td>(1) 465 1666</td>
</tr>
<tr>
<th scope="row"><i className="fa fa-envelope" aria-hidden="true"></i></th>
<td>[email protected]</td>
</tr>
</tbody>
</table>
<div className="pad text-center">
<div><h3><i className="fa fa-clock-o" aria-hidden="true"></i> Nyitvatartás</h3></div>
<div>Hétfőtől szombatig: 9.00-21.00<br/>vasárnap: 9.00-19.00</div>
</div>
</div>
</div>
</div>
);
}
}
export default Homepage;
|
spec/javascripts/jsx/gradezilla/default_gradebook/components/AssignmentColumnHeaderSpec.js | venturehive/canvas-lms | /*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import { mount, ReactWrapper } from 'enzyme';
import AssignmentColumnHeader from 'jsx/gradezilla/default_gradebook/components/AssignmentColumnHeader';
import CurveGradesDialogManager from 'jsx/gradezilla/default_gradebook/CurveGradesDialogManager';
import AssignmentMuterDialogManager from 'jsx/gradezilla/shared/AssignmentMuterDialogManager';
import SetDefaultGradeDialogManager from 'jsx/gradezilla/shared/SetDefaultGradeDialogManager';
import { findFlyoutMenuContent, findMenuItem } from './helpers/columnHeaderHelpers';
function createAssignmentProp ({ assignment } = {}) {
return {
courseId: '42',
htmlUrl: 'http://assignment_htmlUrl',
id: '1',
invalid: false,
muted: false,
name: 'Assignment #1',
omitFromFinalGrade: false,
pointsPossible: 13,
published: true,
submissionTypes: ['online_text_entry'],
...assignment
};
}
function createStudentsProp () {
return [
{
id: '11',
name: 'Clark Kent',
isInactive: false,
submission: {
score: 7,
submittedAt: null
}
},
{
id: '13',
name: 'Barry Allen',
isInactive: false,
submission: {
score: 8,
submittedAt: new Date('Thu Feb 02 2017 16:33:19 GMT-0500 (EST)')
}
},
{
id: '15',
name: 'Bruce Wayne',
isInactive: false,
submission: {
score: undefined,
submittedAt: undefined
}
}
];
}
function defaultProps ({ props, sortBySetting, assignment, curveGradesAction } = {}) {
return {
assignment: createAssignmentProp({ assignment }),
assignmentDetailsAction: {
disabled: false,
onSelect () {},
},
curveGradesAction: {
isDisabled: false,
onSelect () {},
...curveGradesAction
},
downloadSubmissionsAction: {
hidden: false,
onSelect () {}
},
enterGradesAsSetting: {
hidden: false,
onSelect () {},
selected: 'points',
showGradingSchemeOption: true
},
muteAssignmentAction: {
disabled: false,
onSelect () {}
},
reuploadSubmissionsAction: {
hidden: false,
onSelect () {}
},
setDefaultGradeAction: {
disabled: false,
onSelect () {}
},
showUnpostedMenuItem: true,
sortBySetting: {
direction: 'ascending',
disabled: false,
isSortColumn: true,
onSortByGradeAscending: sinon.stub(),
onSortByGradeDescending: sinon.stub(),
onSortByLate: sinon.stub(),
onSortByMissing: sinon.stub(),
onSortByUnposted: sinon.stub(),
settingKey: 'grade',
...sortBySetting
},
students: createStudentsProp(),
submissionsLoaded: true,
addGradebookElement () {},
removeGradebookElement () {},
onMenuClose () {},
...props
};
}
function mountComponent (props, mountOptions = {}) {
return mount(<AssignmentColumnHeader {...props} />, mountOptions);
}
function mountAndOpenOptions (props, mountOptions = {}) {
const wrapper = mountComponent(props, mountOptions);
wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
return wrapper;
}
QUnit.module('AssignmentColumnHeader', {
setup () {
this.props = defaultProps({
props: {
addGradebookElement: this.stub(),
removeGradebookElement: this.stub(),
onMenuClose: this.stub()
}
});
this.wrapper = mountComponent(this.props);
},
teardown () {
this.wrapper.unmount();
}
});
test('renders the assignment name in a link', function () {
const link = this.wrapper.find('.assignment-name Link');
equal(link.length, 1);
equal(link.text().trim(), 'Assignment #1');
equal(link.props().href, 'http://assignment_htmlUrl');
});
test('renders the points possible', function () {
const pointsPossible = this.wrapper.find('.assignment-points-possible');
equal(pointsPossible.length, 1);
equal(pointsPossible.text().trim(), 'Out of 13');
});
test('renders a PopoverMenu', function () {
const optionsMenu = this.wrapper.find('PopoverMenu');
equal(optionsMenu.length, 1);
});
test('does not render a PopoverMenu if assignment is not published', function () {
const props = defaultProps({ assignment: { published: false } });
const wrapper = mountComponent(props);
const optionsMenu = wrapper.find('PopoverMenu');
equal(optionsMenu.length, 0);
});
test('renders a PopoverMenu with a trigger', function () {
const optionsMenuTrigger = this.wrapper.find('PopoverMenu .Gradebook__ColumnHeaderAction');
equal(optionsMenuTrigger.length, 1);
});
test('calls addGradebookElement prop on open', function () {
notOk(this.props.addGradebookElement.called);
this.wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
ok(this.props.addGradebookElement.called);
});
test('calls removeGradebookElement prop on close', function () {
notOk(this.props.removeGradebookElement.called);
this.wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
this.wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
ok(this.props.removeGradebookElement.called);
});
test('calls onMenuClose prop on close', function () {
this.wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
this.wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
strictEqual(this.props.onMenuClose.callCount, 1);
});
test('adds a class to the trigger when the PopoverMenu is opened', function () {
const optionsMenuTrigger = this.wrapper.find('PopoverMenu .Gradebook__ColumnHeaderAction');
optionsMenuTrigger.simulate('click');
ok(optionsMenuTrigger.hasClass('menuShown'));
});
test('renders a title for the More icon based on the assignment name', function () {
const optionsMenuTrigger = this.wrapper.find('PopoverMenu IconMoreSolid');
equal(optionsMenuTrigger.props().title, 'Assignment #1 Options');
});
QUnit.module('AssignmentColumnHeader: "Enter Grades as" Settings', function (hooks) {
let props;
let wrapper;
function getMenuItem (text) {
const content = new ReactWrapper(wrapper.node.enterGradesAsMenuContent, wrapper.node);
return content.findWhere(component => component.name() === 'MenuItem' && component.text() === text);
}
function getMenuItemFlyout (text) {
const content = new ReactWrapper(wrapper.node.optionsMenuContent, wrapper.node);
return content.findWhere(component => component.name() === 'MenuItemFlyout' && component.text().trim() === text);
}
function mountAndOpenMenu () {
wrapper = mountAndOpenOptions(props);
getMenuItemFlyout('Enter Grades as').find('button').simulate('mouseOver');
}
hooks.beforeEach(function () {
props = defaultProps();
});
hooks.afterEach(function () {
wrapper.unmount();
});
test('renders when "hidden" is false', function () {
wrapper = mountAndOpenOptions(props);
strictEqual(getMenuItemFlyout('Enter Grades as').length, 1);
});
test('does not render when "hidden" is true', function () {
props.enterGradesAsSetting.hidden = true;
wrapper = mountAndOpenOptions(props);
strictEqual(getMenuItemFlyout('Enter Grades as').length, 0);
});
test('includes the "Points" option', function () {
mountAndOpenMenu();
strictEqual(getMenuItem('Points').length, 1);
});
test('includes the "Percentage" option', function () {
mountAndOpenMenu();
strictEqual(getMenuItem('Percentage').length, 1);
});
test('includes the "Grading Scheme" option when "showGradingSchemeOption" is true', function () {
props.enterGradesAsSetting.showGradingSchemeOption = true;
mountAndOpenMenu();
strictEqual(getMenuItem('Grading Scheme').length, 1);
});
test('excludes the "Grading Scheme" option when "showGradingSchemeOption" is false', function () {
props.enterGradesAsSetting.showGradingSchemeOption = false;
mountAndOpenMenu();
strictEqual(getMenuItem('Grading Scheme').length, 0);
});
test('optionally renders the "Points" option as selected', function () {
props.enterGradesAsSetting.selected = 'points';
mountAndOpenMenu();
strictEqual(getMenuItem('Points').prop('selected'), true);
});
test('optionally renders the "Percentage" option as selected', function () {
props.enterGradesAsSetting.selected = 'percent';
mountAndOpenMenu();
strictEqual(getMenuItem('Percentage').prop('selected'), true);
});
test('optionally renders the "Grading Scheme" option as selected', function () {
props.enterGradesAsSetting.showGradingSchemeOption = true;
props.enterGradesAsSetting.selected = 'gradingScheme';
mountAndOpenMenu();
strictEqual(getMenuItem('Grading Scheme').prop('selected'), true);
});
test('calls the onSelect callback with "points" when "Points" is selected', function () {
let selected;
props.enterGradesAsSetting.selected = 'percent';
props.enterGradesAsSetting.onSelect = (value) => { selected = value };
mountAndOpenMenu();
getMenuItem('Points').simulate('click');
equal(selected, 'points');
});
test('calls the onSelect callback with "percent" when "Percentage" is selected', function () {
let selected;
props.enterGradesAsSetting.onSelect = (value) => { selected = value };
mountAndOpenMenu();
getMenuItem('Percentage').simulate('click');
equal(selected, 'percent');
});
test('calls the onSelect callback with "gradingScheme" when "Grading Scheme" is selected', function () {
let selected;
props.enterGradesAsSetting.showGradingSchemeOption = true;
props.enterGradesAsSetting.onSelect = (value) => { selected = value };
mountAndOpenMenu();
getMenuItem('Grading Scheme').simulate('click');
equal(selected, 'gradingScheme');
});
});
QUnit.module('AssignmentColumnHeader: Sort by Settings', {
setup () {
this.mountAndOpenOptions = mountAndOpenOptions;
},
teardown () {
this.wrapper.unmount();
}
});
test('sort by does not allow multiple selects', function () {
const flyout = findFlyoutMenuContent.call(this, defaultProps(), 'Sort by');
strictEqual(flyout.find('MenuItemGroup').prop('allowMultiple'), false);
});
test('selects "Grade - Low to High" when sorting by grade ascending', function () {
const props = defaultProps({ sortBySetting: { direction: 'ascending' } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - Low to High');
strictEqual(menuItem.prop('selected'), true);
});
test('does not select "Grade - Low to High" when isSortColumn is false', function () {
const props = defaultProps({ sortBySetting: { isSortColumn: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - Low to High');
strictEqual(menuItem.prop('selected'), false);
});
test('clicking "Grade - Low to High" calls onSortByGradeAscending', function () {
const onSortByGradeAscending = this.stub();
const props = defaultProps({ sortBySetting: { onSortByGradeAscending } });
findMenuItem.call(this, props, 'Sort by', 'Grade - Low to High').simulate('click');
strictEqual(onSortByGradeAscending.callCount, 1);
});
test('clicking "Grade - Low to High" focuses menu trigger', function () {
const onSortByGradeAscending = this.stub();
const props = defaultProps({ sortBySetting: { onSortByGradeAscending } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - Low to High');
const focusStub = this.stub(this.wrapper.instance(), 'focusAtEnd')
menuItem.simulate('click');
equal(focusStub.callCount, 1);
});
test('"Grade - Low to High" is optionally disabled', function () {
const props = defaultProps({ sortBySetting: { disabled: true } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - Low to High');
strictEqual(menuItem.prop('disabled'), true);
});
test('selects "Grade - High to Low" when sorting by grade descending', function () {
const props = defaultProps({ sortBySetting: { direction: 'descending' } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('selected'), true);
});
test('does not select "Grade - High to Low" when isSortColumn is false', function () {
const props = defaultProps({ sortBySetting: { isSortColumn: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('selected'), false);
});
test('clicking "Grade - High to Low" calls onSortByGradeDescending', function () {
const onSortByGradeDescending = this.stub();
const props = defaultProps({ sortBySetting: { onSortByGradeDescending } });
findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low').simulate('click');
strictEqual(onSortByGradeDescending.callCount, 1);
});
test('clicking "Grade - High to Low" focuses menu trigger', function () {
const onSortByGradeDescending = this.stub();
const props = defaultProps({ sortBySetting: { onSortByGradeDescending } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
const focusStub = this.stub(this.wrapper.instance(), 'focusAtEnd')
menuItem.simulate('click');
equal(focusStub.callCount, 1);
});
test('"Grade - High to Low" is optionally disabled', function () {
const props = defaultProps({ sortBySetting: { disabled: true } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('disabled'), true);
});
test('selects "Missing" when sorting by missing', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'missing' } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Missing');
strictEqual(menuItem.prop('selected'), true);
});
test('does not select "Missing" when isSortColumn is false', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'missing', isSortColumn: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('selected'), false);
});
test('clicking "Missing" calls onSortByMissing', function () {
const onSortByMissing = this.stub();
const props = defaultProps({ sortBySetting: { onSortByMissing } });
findMenuItem.call(this, props, 'Sort by', 'Missing').simulate('click');
strictEqual(onSortByMissing.callCount, 1);
});
test('clicking "Missing" focuses menu trigger', function () {
const onSortByMissing = this.stub();
const props = defaultProps({ sortBySetting: { onSortByMissing } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Missing');
const focusStub = this.stub(this.wrapper.instance(), 'focusAtEnd')
menuItem.simulate('click');
equal(focusStub.callCount, 1);
});
test('"Missing" is optionally disabled', function () {
const props = defaultProps({ sortBySetting: { disabled: true } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Missing');
strictEqual(menuItem.prop('disabled'), true);
});
test('selects "Late" when sorting by late', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'late' } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Late');
strictEqual(menuItem.prop('selected'), true);
});
test('does not select "Late" when isSortColumn is false', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'late', isSortColumn: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('selected'), false);
});
test('clicking "Late" calls onSortByLate', function () {
const onSortByLate = this.stub();
const props = defaultProps({ sortBySetting: { onSortByLate } });
findMenuItem.call(this, props, 'Sort by', 'Late').simulate('click');
strictEqual(onSortByLate.callCount, 1);
});
test('clicking "Late" focuses menu trigger', function () {
const onSortByLate = this.stub();
const props = defaultProps({ sortBySetting: { onSortByLate } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Late');
const focusStub = this.stub(this.wrapper.instance(), 'focusAtEnd')
menuItem.simulate('click');
equal(focusStub.callCount, 1);
});
test('"Late" is optionally disabled', function () {
const props = defaultProps({ sortBySetting: { disabled: true } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Late');
strictEqual(menuItem.prop('disabled'), true);
});
test('selects "Unposted" when sorting by unposted', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'unposted' } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Unposted');
strictEqual(menuItem.prop('selected'), true);
});
test('does not select "Unposted" when isSortColumn is false', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'unposted', isSortColumn: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('selected'), false);
});
test('clicking "Unposted" calls onSortByUnposted', function () {
const onSortByUnposted = this.stub();
const props = defaultProps({ sortBySetting: { onSortByUnposted } });
findMenuItem.call(this, props, 'Sort by', 'Unposted').simulate('click');
strictEqual(onSortByUnposted.callCount, 1);
});
test('clicking "Unposted" focuses menu trigger', function () {
const onSortByUnposted = this.stub();
const props = defaultProps({ sortBySetting: { onSortByUnposted } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Unposted');
const focusStub = this.stub(this.wrapper.instance(), 'focusAtEnd')
menuItem.simulate('click');
equal(focusStub.callCount, 1);
});
test('"Unposted" is optionally disabled', function () {
const props = defaultProps({ sortBySetting: { disabled: true } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Unposted');
strictEqual(menuItem.prop('disabled'), true);
});
test('"Unposted" menu item is optionally excluded from the menu', function () {
const props = defaultProps({ props: { showUnpostedMenuItem: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Unposted');
notOk(menuItem);
});
QUnit.module('AssignmentColumnHeader: Curve Grades Dialog', {
teardown () {
this.wrapper.unmount();
}
});
test('menu item is present in the popover menu', function () {
this.wrapper = mountAndOpenOptions(defaultProps());
const menuItem = document.querySelector('[data-menu-item-id="curve-grades"]');
equal(menuItem.textContent, 'Curve Grades');
notOk(menuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('Curve Grades menu item is disabled when isDisabled is true', function () {
const props = defaultProps({ curveGradesAction: { isDisabled: true } });
this.wrapper = mountAndOpenOptions(props);
const menuItem = document.querySelector('[data-menu-item-id="curve-grades"]');
ok(menuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('Curve Grades menu item is enabled when isDisabled is false', function () {
this.wrapper = mountAndOpenOptions(defaultProps());
const menuItem = document.querySelector('[data-menu-item-id="curve-grades"]');
notOk(menuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('clicking the menu item invokes onSelect with correct callback', function () {
const onSelect = this.stub();
const props = defaultProps({ curveGradesAction: { onSelect } });
this.wrapper = mountAndOpenOptions(props);
const menuItem = document.querySelector('[data-menu-item-id="curve-grades"]');
menuItem.click();
equal(onSelect.callCount, 1);
equal(onSelect.getCall(0).args[0], this.wrapper.instance().focusAtEnd);
});
test('the Curve Grades dialog has focus when it is invoked', function () {
const props = defaultProps();
const curveGradesActionOptions = {
isAdmin: true,
contextUrl: 'http://contextUrl',
submissionsLoaded: true
};
const curveGradesProps = CurveGradesDialogManager.createCurveGradesAction(
props.assignment, props.students, curveGradesActionOptions
);
props.curveGradesAction.onSelect = curveGradesProps.onSelect;
this.wrapper = mountAndOpenOptions(props, { attachTo: document.querySelector('#fixtures') });
const specificMenuItem = document.querySelector('[data-menu-item-id="curve-grades"]');
specificMenuItem.click();
const allDialogCloseButtons = document.querySelectorAll('.ui-dialog-titlebar-close.ui-state-focus');
const dialogCloseButton = allDialogCloseButtons[allDialogCloseButtons.length - 1];
equal(document.activeElement, dialogCloseButton);
dialogCloseButton.click();
});
QUnit.module('AssignmentColumnHeader: Message Students Who Action', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('shows the menu item in an enabled state', function () {
this.wrapper = mountAndOpenOptions(this.props);
const menuItem = document.querySelector('[data-menu-item-id="message-students-who"]');
equal(menuItem.textContent, 'Message Students Who');
notOk(menuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('disables the menu item when submissions are not loaded', function () {
this.props.submissionsLoaded = false;
this.wrapper = mountAndOpenOptions(this.props);
const menuItem = document.querySelector('[data-menu-item-id="message-students-who"]');
equal(menuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'), 'true');
});
test('clicking the menu item invokes the Message Students Who dialog with correct callback', function () {
this.wrapper = mountAndOpenOptions(this.props);
const messageStudents = this.stub(window, 'messageStudents');
const menuItem = document.querySelector('[data-menu-item-id="message-students-who"]');
menuItem.click();
equal(messageStudents.callCount, 1);
equal(messageStudents.getCall(0).args[0].onClose, this.wrapper.instance().focusAtEnd);
});
QUnit.module('AssignmentColumnHeader: Mute/Unmute Assignment Action', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('shows the enabled "Mute Assignment" option when assignment is not muted', function () {
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="assignment-muter"]');
equal(specificMenuItem.textContent, 'Mute Assignment');
notOk(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('shows the enabled "Unmute Assignment" option when assignment is muted', function () {
this.props.assignment.muted = true;
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="assignment-muter"]');
equal(specificMenuItem.textContent, 'Unmute Assignment');
notOk(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('disables the option when prop muteAssignmentAction.disabled is truthy', function () {
this.props.muteAssignmentAction.disabled = true;
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="assignment-muter"]');
equal(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'), 'true');
});
test('clicking the menu item invokes onSelect with correct callback', function () {
this.props.muteAssignmentAction.onSelect = this.stub();
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="assignment-muter"]');
specificMenuItem.click();
equal(this.props.muteAssignmentAction.onSelect.callCount, 1);
equal(this.props.muteAssignmentAction.onSelect.getCall(0).args[0], this.wrapper.instance().focusAtEnd);
});
test('the Assignment Muting dialog has focus when it is invoked', function () {
const dialogManager = new AssignmentMuterDialogManager(this.props.assignment, 'http://url', true);
this.props.muteAssignmentAction.onSelect = dialogManager.showDialog;
this.wrapper = mountAndOpenOptions(this.props, { attachTo: document.querySelector('#fixtures') });
const specificMenuItem = document.querySelector('[data-menu-item-id="assignment-muter"]');
specificMenuItem.click();
const allDialogCloseButtons = document.querySelectorAll('.ui-dialog-titlebar-close.ui-state-focus');
const dialogCloseButton = allDialogCloseButtons[allDialogCloseButtons.length - 1];
equal(document.activeElement, dialogCloseButton);
dialogCloseButton.click();
});
QUnit.module('AssignmentColumnHeader: non-standard assignment', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('renders 0 points possible when the assignment has no possible points', function () {
this.props.assignment.pointsPossible = undefined;
this.wrapper = mountComponent(this.props);
const pointsPossible = this.wrapper.find('.assignment-points-possible');
equal(pointsPossible.length, 1);
equal(pointsPossible.text().trim(), 'Out of 0');
});
test('renders a muted icon when the assignment is muted', function () {
this.props.assignment.muted = true;
this.wrapper = mountComponent(this.props);
const link = this.wrapper.find('.assignment-name Link');
const icon = link.find('IconMutedSolid');
const expectedLinkTitle = 'This assignment is muted';
equal(link.length, 1);
deepEqual(link.props().title, expectedLinkTitle);
equal(icon.length, 1);
equal(icon.props().title, expectedLinkTitle);
});
test('renders a warning icon when the assignment does not count towards final grade', function () {
this.props.assignment.omitFromFinalGrade = true;
this.wrapper = mountComponent(this.props);
const link = this.wrapper.find('.assignment-name Link');
const icon = link.find('IconWarningSolid');
const expectedLinkTitle = 'This assignment does not count toward the final grade';
equal(link.length, 1);
deepEqual(link.props().title, expectedLinkTitle);
equal(icon.length, 1);
equal(icon.props().title, expectedLinkTitle);
});
test('renders a warning icon when the assignment has zero points possible', function () {
this.props.assignment.pointsPossible = 0;
this.wrapper = mountComponent(this.props);
const link = this.wrapper.find('.assignment-name Link');
const icon = link.find('IconWarningSolid');
const expectedLinkTitle = 'This assignment has no points possible and cannot be included in grade calculation';
equal(link.length, 1);
deepEqual(link.props().title, expectedLinkTitle);
equal(icon.length, 1);
equal(icon.props().title, expectedLinkTitle);
});
test('renders a warning icon when the assignment has null points possible', function () {
this.props.assignment.pointsPossible = null;
this.wrapper = mountComponent(this.props);
const link = this.wrapper.find('.assignment-name Link');
const icon = link.find('IconWarningSolid');
const expectedLinkTitle = 'This assignment has no points possible and cannot be included in grade calculation';
equal(link.length, 1);
deepEqual(link.props().title, expectedLinkTitle);
equal(icon.length, 1);
equal(icon.props().title, expectedLinkTitle);
});
QUnit.module('AssignmentColumnHeader: Set Default Grade Action', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('shows the menu item in an enabled state', function () {
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="set-default-grade"]');
equal(specificMenuItem.textContent, 'Set Default Grade');
strictEqual(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'), null);
});
test('disables the menu item when the disabled prop is true', function () {
this.props.setDefaultGradeAction.disabled = true;
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="set-default-grade"]');
equal(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'), 'true');
});
test('clicking the menu item invokes onSelect with correct callback', function () {
this.props.setDefaultGradeAction.onSelect = this.stub();
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="set-default-grade"]');
specificMenuItem.click();
equal(this.props.setDefaultGradeAction.onSelect.callCount, 1);
equal(this.props.setDefaultGradeAction.onSelect.getCall(0).args[0], this.wrapper.instance().focusAtEnd);
});
test('the Set Default Grade dialog has focus when it is invoked', function () {
const dialogManager =
new SetDefaultGradeDialogManager(this.props.assignment, this.props.students, 1, '1', true, true);
this.props.setDefaultGradeAction.onSelect = dialogManager.showDialog;
this.wrapper = mountAndOpenOptions(this.props, { attachTo: document.querySelector('#fixtures') });
const specificMenuItem = document.querySelector('[data-menu-item-id="set-default-grade"]');
specificMenuItem.click();
const allDialogCloseButtons = document.querySelectorAll('.ui-dialog-titlebar-close.ui-state-focus');
const dialogCloseButton = allDialogCloseButtons[allDialogCloseButtons.length - 1];
equal(document.activeElement, dialogCloseButton);
dialogCloseButton.click();
});
QUnit.module('AssignmentColumnHeader: Download Submissions Action', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('shows the menu item in an enabled state', function () {
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="download-submissions"]');
equal(specificMenuItem.textContent, 'Download Submissions');
notOk(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('does not render the menu item when the hidden prop is true', function () {
this.props.downloadSubmissionsAction.hidden = true;
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="download-submissions"]');
equal(specificMenuItem, null);
});
test('clicking the menu item invokes onSelect with correct callback', function () {
this.props.downloadSubmissionsAction.onSelect = this.stub();
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="download-submissions"]');
specificMenuItem.click();
equal(this.props.downloadSubmissionsAction.onSelect.callCount, 1);
equal(this.props.downloadSubmissionsAction.onSelect.getCall(0).args[0], this.wrapper.instance().focusAtEnd);
});
QUnit.module('AssignmentColumnHeader: Reupload Submissions Action', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('shows the menu item in an enabled state', function () {
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="reupload-submissions"]');
equal(specificMenuItem.textContent, 'Re-Upload Submissions');
strictEqual(specificMenuItem.parentElement.getAttribute('aria-disabled'), null);
});
test('does not render the menu item when the hidden prop is true', function () {
this.props.reuploadSubmissionsAction.hidden = true;
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="reupload-submissions"]');
equal(specificMenuItem, null);
});
test('clicking the menu item invokes the onSelect property with correct callback', function () {
this.props.reuploadSubmissionsAction.onSelect = this.stub();
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="reupload-submissions"]');
specificMenuItem.click();
equal(this.props.reuploadSubmissionsAction.onSelect.callCount, 1);
equal(this.props.reuploadSubmissionsAction.onSelect.getCall(0).args[0], this.wrapper.instance().focusAtEnd);
});
QUnit.module('AssignmentColumnHeader#handleKeyDown', function (hooks) {
hooks.beforeEach(function () {
this.wrapper = mountComponent(defaultProps(), { attachTo: document.querySelector('#fixtures') });
this.preventDefault = sinon.spy();
});
hooks.afterEach(function () {
this.wrapper.unmount();
});
this.handleKeyDown = function (which, shiftKey = false) {
return this.wrapper.node.handleKeyDown({ which, shiftKey, preventDefault: this.preventDefault });
};
QUnit.module('with focus on assignment link', {
setup () {
this.wrapper.node.assignmentLink.focus();
}
});
test('Tab sets focus on options menu trigger', function () {
this.handleKeyDown(9, false); // Tab
equal(document.activeElement, this.wrapper.node.optionsMenuTrigger);
});
test('prevents default behavior for Tab', function () {
this.handleKeyDown(9, false); // Tab
strictEqual(this.preventDefault.callCount, 1);
});
test('returns false for Tab', function () {
// This prevents additional behavior in Grid Support Navigation.
const returnValue = this.handleKeyDown(9, false); // Tab
strictEqual(returnValue, false);
});
test('does not handle Shift+Tab', function () {
// This allows Grid Support Navigation to handle navigation.
const returnValue = this.handleKeyDown(9, true); // Shift+Tab
equal(typeof returnValue, 'undefined');
});
QUnit.module('with focus on options menu trigger', {
setup () {
this.wrapper.node.optionsMenuTrigger.focus();
}
});
test('Shift+Tab sets focus on assignment link', function () {
this.handleKeyDown(9, true); // Shift+Tab
strictEqual(this.wrapper.node.assignmentLink.focused, true);
});
test('prevents default behavior for Shift+Tab', function () {
this.handleKeyDown(9, true); // Shift+Tab
strictEqual(this.preventDefault.callCount, 1);
});
test('returns false for Shift+Tab', function () {
// This prevents additional behavior in Grid Support Navigation.
const returnValue = this.handleKeyDown(9, true); // Shift+Tab
strictEqual(returnValue, false);
});
test('does not handle Tab', function () {
// This allows Grid Support Navigation to handle navigation.
const returnValue = this.handleKeyDown(9, false); // Tab
equal(typeof returnValue, 'undefined');
});
test('Enter opens the options menu', function () {
this.handleKeyDown(13); // Enter
const optionsMenu = this.wrapper.find('PopoverMenu');
strictEqual(optionsMenu.node.show, true);
});
test('returns false for Enter on options menu', function () {
// This prevents additional behavior in Grid Support Navigation.
const returnValue = this.handleKeyDown(13); // Enter
strictEqual(returnValue, false);
});
QUnit.module('without focus');
test('does not handle Tab', function () {
const returnValue = this.handleKeyDown(9, false); // Tab
equal(typeof returnValue, 'undefined');
});
test('does not handle Shift+Tab', function () {
const returnValue = this.handleKeyDown(9, true); // Shift+Tab
equal(typeof returnValue, 'undefined');
});
test('does not handle Enter', function () {
const returnValue = this.handleKeyDown(13); // Enter
equal(typeof returnValue, 'undefined');
});
});
QUnit.module('AssignmentColumnHeader: focus', {
setup () {
this.wrapper = mountComponent(defaultProps(), { attachTo: document.querySelector('#fixtures') });
},
teardown () {
this.wrapper.unmount();
}
});
test('#focusAtStart sets focus on the assignment link', function () {
this.wrapper.node.focusAtStart();
strictEqual(this.wrapper.node.assignmentLink.focused, true);
});
test('#focusAtEnd sets focus on the options menu trigger', function () {
this.wrapper.node.focusAtEnd();
equal(document.activeElement, this.wrapper.node.optionsMenuTrigger);
});
|
assets/javascripts/kitten/components/action/social-button-icon/stories.js | KissKissBankBank/kitten | import React from 'react'
import {
FacebookButtonIcon,
TwitterButtonIcon,
LinkedinButtonIcon,
InstagramButtonIcon,
YoutubeButtonIcon,
} from './index'
import { DocsPage } from 'storybook/docs-page'
export default {
component: SocialButtonIcon,
title: 'Action/SocialButtonIcon',
parameters: {
docs: {
page: () => (
<DocsPage filepath={__filename} importString="SocialButtonIcon" />
),
},
},
decorators: [
story => (
<div className="story-Container story-Grid story-Grid--thin">
{story()}
</div>
),
],
}
export const SocialButtonIcon = () => (
<>
<FacebookButtonIcon>Facebook</FacebookButtonIcon>
<TwitterButtonIcon>Twitter</TwitterButtonIcon>
<InstagramButtonIcon>Instagram</InstagramButtonIcon>
<LinkedinButtonIcon>Linkedin</LinkedinButtonIcon>
<YoutubeButtonIcon>Youtube</YoutubeButtonIcon>
</>
)
|
node_modules/react-images/src/components/Header.js | ed1d1a8d/macweb | import PropTypes from 'prop-types';
import React from 'react';
import { css, StyleSheet } from 'aphrodite/no-important';
import defaults from '../theme';
import { deepMerge } from '../utils';
import Icon from './Icon';
function Header ({
customControls,
onClose,
showCloseButton,
closeButtonTitle,
...props,
}, {
theme,
}) {
const classes = StyleSheet.create(deepMerge(defaultStyles, theme));
return (
<div className={css(classes.header)} {...props}>
{customControls ? customControls : <span />}
{!!showCloseButton && (
<button
title={closeButtonTitle}
className={css(classes.close)}
onClick={onClose}
>
<Icon fill={!!theme.close && theme.close.fill || defaults.close.fill} type="close" />
</button>
)}
</div>
);
}
Header.propTypes = {
customControls: PropTypes.array,
onClose: PropTypes.func.isRequired,
showCloseButton: PropTypes.bool,
};
Header.contextTypes = {
theme: PropTypes.object.isRequired,
};
const defaultStyles = {
header: {
display: 'flex',
justifyContent: 'space-between',
height: defaults.header.height,
},
close: {
background: 'none',
border: 'none',
cursor: 'pointer',
outline: 'none',
position: 'relative',
top: 0,
verticalAlign: 'bottom',
// increase hit area
height: 40,
marginRight: -10,
padding: 10,
width: 40,
},
};
module.exports = Header;
|
react-router-tutorial/lessons/11-productionish-server/modules/Repos.js | zerotung/practices-and-notes | import React from 'react'
import NavLink from './NavLink'
export default React.createClass({
render() {
return (
<div>
<h2>Repos</h2>
<ul>
<li><NavLink to="/repos/reactjs/react-router">React Router</NavLink></li>
<li><NavLink to="/repos/facebook/react">React</NavLink></li>
</ul>
{this.props.children}
</div>
)
}
})
|
src/svg-icons/social/party-mode.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPartyMode = (props) => (
<SvgIcon {...props}>
<path d="M20 4h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 3c1.63 0 3.06.79 3.98 2H12c-1.66 0-3 1.34-3 3 0 .35.07.69.18 1H7.1c-.06-.32-.1-.66-.1-1 0-2.76 2.24-5 5-5zm0 10c-1.63 0-3.06-.79-3.98-2H12c1.66 0 3-1.34 3-3 0-.35-.07-.69-.18-1h2.08c.07.32.1.66.1 1 0 2.76-2.24 5-5 5z"/>
</SvgIcon>
);
SocialPartyMode = pure(SocialPartyMode);
SocialPartyMode.displayName = 'SocialPartyMode';
SocialPartyMode.muiName = 'SvgIcon';
export default SocialPartyMode;
|
packages/core/__deprecated__/Arwes/sandbox.js | romelperez/arwes | import React from 'react';
import Arwes from './index';
export default () => (
<Arwes animate background='/images/background.jpg' pattern='/images/glow.png'>
<h2>SciFi UI Framework</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
</p>
</Arwes>
);
|
src/components/seo.js | benjaminmodayil/modayilme | import React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import { StaticQuery, graphql } from 'gatsby';
function SEO({ description, lang, meta, keywords, title }) {
return (
<StaticQuery
query={detailsQuery}
render={(data) => {
const metaDescription = description || data.site.siteMetadata.description;
return (
<Helmet
htmlAttributes={{
lang,
}}
title={title}
titleTemplate={`%s | ${data.site.siteMetadata.title}`}
meta={[
{
name: `description`,
content: metaDescription,
},
{
property: `og:title`,
content: title,
},
{
property: `og:description`,
content: metaDescription,
},
{
property: `og:type`,
content: `website`,
},
{
name: `twitter:card`,
content: `summary`,
},
{
name: `twitter:creator`,
content: data.site.siteMetadata.author,
},
{
name: `twitter:title`,
content: title,
},
{
name: `twitter:description`,
content: metaDescription,
},
]
.concat(
keywords.length > 0
? {
name: `keywords`,
content: keywords.join(`, `),
}
: []
)
.concat(meta)}
/>
);
}}
/>
);
}
SEO.defaultProps = {
lang: `en`,
meta: [],
keywords: [],
};
SEO.propTypes = {
description: PropTypes.string,
lang: PropTypes.string,
meta: PropTypes.array,
keywords: PropTypes.arrayOf(PropTypes.string),
title: PropTypes.string.isRequired,
};
export default SEO;
const detailsQuery = graphql`
query DefaultSEOQuery {
site {
siteMetadata {
title
description
author
}
}
}
`;
|
demo/prism-async-light.js | conorhastings/react-syntax-highlighter | import React from 'react';
import { render } from 'react-dom';
import SyntaxHighlighter from '../src/prism-async-light';
import prismStyles from './styles/prism';
import ExamplesLinks from './examples-links';
import clike from '../src/languages/prism/clike';
import javascript from '../src/languages/prism/javascript';
import jsx from '../src/languages/prism/jsx';
import markup from '../src/languages/prism/markup';
import markupTemplating from '../src/languages/prism/markup-templating';
SyntaxHighlighter.registerLanguage('clike', clike);
SyntaxHighlighter.registerLanguage('javascript', javascript);
SyntaxHighlighter.registerLanguage('jsx', jsx);
SyntaxHighlighter.registerLanguage('markup', markup);
SyntaxHighlighter.registerLanguage('markup-templating', markupTemplating);
const availableStyles = prismStyles;
const availableLanguages = [
'clike',
'javascript',
'jsx',
'markup',
'markup-templating'
];
class Component extends React.Component {
constructor() {
super();
const initialCodeString = `function createStyleObject(classNames, style) {
return classNames.reduce((styleObject, className) => {
return {...styleObject, ...style[className]};
}, {});
}
function createClassNameString(classNames) {
return classNames.join(' ');
}
// this comment is here to demonstrate an extremely long line length, well beyond what you should probably allow in your own code, though sometimes you'll be highlighting code you can't refactor, which is unfortunate but should be handled gracefully
function createChildren(style, useInlineStyles) {
let childrenCount = 0;
return children => {
childrenCount += 1;
return children.map((child, i) => createElement({
node: child,
style,
useInlineStyles,
key:\`code-segment-$\{childrenCount}-$\{i}\`
}));
}
}
function createElement({ node, style, useInlineStyles, key }) {
const { properties, type, tagName, value } = node;
if (type === "text") {
return value;
} else if (tagName) {
const TagName = tagName;
const childrenCreator = createChildren(style, useInlineStyles);
const props = (
useInlineStyles
?
{ style: createStyleObject(properties.className, style) }
:
{ className: createClassNameString(properties.className) }
);
const children = childrenCreator(node.children);
return <TagName key={key} {...props}>{children}</TagName>;
}
}
`;
this.state = {
code: initialCodeString,
showLineNumbers: false,
wrapLongLines: false,
style: 'atom-dark',
styleSrc: require('../src/styles/prism/atom-dark').default,
language: 'jsx',
languageSrc: require(`../src/languages/prism/jsx`).default
};
}
render() {
return (
<div className="demo__root demo__root--prism-async-light">
<header>
<h1>React Syntax Highlighter Demo</h1>
<ExamplesLinks />
</header>
<main>
<aside className="options__container">
<div className="options__option options__option--language">
<select
className="select"
value={this.state.language}
onChange={e =>
this.setState({
languageSrc: require(`../src/languages/prism/${
e.target.value
}`).default,
language: e.target.value
})
}
>
{availableLanguages.map(l => (
<option key={l} value={l}>
{l}
</option>
))}
</select>
</div>
<div className="options__option options__option--theme">
<select
className="select"
value={this.state.selectedStyle}
onChange={e =>
this.setState({
styleSrc: require(`../src/styles/prism/${e.target.value}`)
.default,
style: e.target.value
})
}
>
{availableStyles.map(s => (
<option key={s} value={s}>
{s}
</option>
))}
</select>
</div>
<div className="options__option options__option--line-numbers">
<label htmlFor="showLineNumbers" className="option__label">
<input
type="checkbox"
className="option__checkbox"
checked={this.state.showLineNumbers}
onChange={() =>
this.setState({
showLineNumbers: !this.state.showLineNumbers
})
}
id="showLineNumbers"
/>
<span className="label__text">Show line numbers</span>
</label>
</div>
<div className="options__option options__option--wrap-long-lines">
<label htmlFor="wrapLongLines" className="option__label">
<input
type="checkbox"
className="option__checkbox"
checked={this.state.wrapLongLines}
onChange={() =>
this.setState({
wrapLongLines: !this.state.wrapLongLines
})
}
id="wrapLongLines"
/>
<span className="label__text">Wrap long lines</span>
</label>
</div>
</aside>
<article className="example__container">
<div className="textarea__wrapper">
<textarea
style={{ flex: 1, marginTop: 11 }}
rows={40}
value={this.state.code}
onChange={e => this.setState({ code: e.target.value })}
/>
</div>
<SyntaxHighlighter
style={this.state.styleSrc}
showLineNumbers={this.state.showLineNumbers}
wrapLines={true}
wrapLongLines={this.state.wrapLongLines}
lineProps={lineNumber => ({
style: { display: 'block', cursor: 'pointer' },
onClick() {
alert(`Line Number Clicked: ${lineNumber}`);
}
})}
language={this.state.language}
>
{this.state.code}
</SyntaxHighlighter>
</article>
</main>
</div>
);
}
}
render(<Component />, document.getElementById('app'));
|
src/components/common/svg-icons/places/rv-hookup.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesRvHookup = (props) => (
<SvgIcon {...props}>
<path d="M20 17v-6c0-1.1-.9-2-2-2H7V7l-3 3 3 3v-2h4v3H4v3c0 1.1.9 2 2 2h2c0 1.66 1.34 3 3 3s3-1.34 3-3h8v-2h-2zm-9 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm7-6h-4v-3h4v3zM17 2v2H9v2h8v2l3-3z"/>
</SvgIcon>
);
PlacesRvHookup = pure(PlacesRvHookup);
PlacesRvHookup.displayName = 'PlacesRvHookup';
PlacesRvHookup.muiName = 'SvgIcon';
export default PlacesRvHookup;
|
src/components/App.js | HackArdennes2017/Project06 | import React from 'react'
import { Switch, Route } from 'react-router'
import { Provider } from 'react-redux'
import routes from 'routes'
export default (store, Router, routerProps) =>
<Provider store={store}>
<Router {...routerProps}>
<Switch>
{routes.map(route => <Route key={route.path} {...route} />)}
</Switch>
</Router>
</Provider>
|
docs/src/CodeExample.js | JimiHFord/react-bootstrap | import React from 'react';
export default class CodeExample extends React.Component {
render() {
return (
<pre className="cm-s-solarized cm-s-light">
<code>
{this.props.codeText}
</code>
</pre>
);
}
componentDidMount() {
if (CodeMirror === undefined) {
return;
}
CodeMirror.runMode(
this.props.codeText,
this.props.mode,
React.findDOMNode(this).children[0]
);
}
}
|
examples/huge-apps/routes/Course/components/Dashboard.js | ryardley/react-router | import React from 'react';
class Dashboard extends React.Component {
render () {
return (
<div>
<h3>Course Dashboard</h3>
</div>
);
}
}
export default Dashboard;
|
client/modules/core/components/.stories/new_poll_form.js | thancock20/voting-app | import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import { withKnobs, text, boolean, number, object } from '@kadira/storybook-addon-knobs';
import { setComposerStub } from 'react-komposer';
import NewPollForm from '../new_poll_form.jsx';
storiesOf('core.NewPollForm', module)
.addDecorator(withKnobs)
.add('default view', () => {
return (
<NewPollForm createPoll={action('createPoll')}/>
);
});
|
src/svg-icons/editor/monetization-on.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorMonetizationOn = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1.41 16.09V20h-2.67v-1.93c-1.71-.36-3.16-1.46-3.27-3.4h1.96c.1 1.05.82 1.87 2.65 1.87 1.96 0 2.4-.98 2.4-1.59 0-.83-.44-1.61-2.67-2.14-2.48-.6-4.18-1.62-4.18-3.67 0-1.72 1.39-2.84 3.11-3.21V4h2.67v1.95c1.86.45 2.79 1.86 2.85 3.39H14.3c-.05-1.11-.64-1.87-2.22-1.87-1.5 0-2.4.68-2.4 1.64 0 .84.65 1.39 2.67 1.91s4.18 1.39 4.18 3.91c-.01 1.83-1.38 2.83-3.12 3.16z"/>
</SvgIcon>
);
EditorMonetizationOn = pure(EditorMonetizationOn);
EditorMonetizationOn.displayName = 'EditorMonetizationOn';
EditorMonetizationOn.muiName = 'SvgIcon';
export default EditorMonetizationOn;
|
client/modules/App/components/DevTools.js | GTDev87/stylizer | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-w"
>
<LogMonitor />
</DockMonitor>
);
|
src/components/internal/ConfirmationOverlay.js | GetAmbassador/react-ions | import React from 'react'
import PropTypes from 'prop-types'
import optclass from './OptClass'
import Button from '../Button'
import colors from '../internal/colors'
const ConfirmationOverlay = ({ prompt, handleConfirmation }) => {
const getTextStyle = () => {
return {
fontSize: '14px',
fontWeight: '600',
color: colors.primary4,
margin: '0 0 24px',
display: 'block'
}
}
const getButtonWrapperStyle = () => {
return {
display: 'flex',
justifyContent: 'flex-end',
marginRight: '-12px'
}
}
return (
<div>
<span style={getTextStyle()}>{prompt || 'Are you sure?'}</span>
<div style={getButtonWrapperStyle()}>
<Button onClick={handleConfirmation.bind(this, false)} optClass='danger-alt'>Cancel</Button>
<Button onClick={handleConfirmation.bind(this, true)}>Yes</Button>
</div>
</div>
)
}
ConfirmationOverlay.propTypes = {
prompt: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
handleConfirmation: PropTypes.func.isRequired
}
export default ConfirmationOverlay
|
app/containers/AlgorithmContainer.js | omeryagmurlu/algoriv | import React, { Component } from 'react';
import _pickBy from 'lodash.pickby';
import _mapValues from 'lodash.mapvalues';
import { makeCancelable, cancelCatch, AlgorithmError } from 'app/utils';
import AnimatorContainer from 'app/containers/AnimatorContainer';
import LoadingView from 'app/views/LoadingView';
const snapshot = (payload, object) => {
payload.push(JSON.parse(JSON.stringify(object))); // get rid of reference
};
const snapProxy = (frames, fn) =>
(...params) => snapshot(frames, fn(...params)); // params passed to frame are passed to snap
const filterObjectByKeys = (obj, arr) => _pickBy(obj, (v, k) => (typeof arr[k] !== 'undefined'));
export const framer = (logic, snap) => (input) => {
const frames = [];
return Promise.resolve(logic(input, snapProxy(frames, snap)))
.then((optEndInput) => {
if (frames.length === 0) {
throw AlgorithmError('Algorithm must frame at least once');
}
return [frames, optEndInput];
});
};
const AlgorithmFactory = ({
logic: algLogic,
input: algInput,
initInputs: algInitInput,
snap: algSnap,
modules: algModules,
modulesInputProps: algModulesInputProps,
info: algInfo,
}) => ((() => class AlgorithmPrototype extends Component {
logic = (input) => framer(algLogic, algSnap)(input).then(([frames, optEndInput]) => {
this.setState({ callback: () => {
this.lastLogicEndInput = typeof optEndInput === 'object' ? optEndInput : {};
} });
return frames;
})
constructor(props) {
super(props);
this.state = {
input: { ...algInput }, // BUGFIX: multiple instances, deepCopy needed
frames: null,
callback: null,
updating: true
};
this.cancellables = [];
this.lastLogicEndInput = {};
}
componentDidMount() {
this.cancellable(this.logic(algInput))
.then(frames => {
this.setState({ frames, updating: false });
}).catch(cancelCatch);
// .catch(err => {
// throw new Error(`Algorithm can't init, ${err}`);
// });
}
componentWillUnmount() {
this.lastLogicEndInput = {};
this.cancelRunning();
}
cancellable = prom => {
const cancellable = makeCancelable(prom);
this.cancellables.push(cancellable);
return cancellable.promise;
}
cancelRunning = () => {
while (this.cancellables.length > 0) {
this.cancellables.pop().cancel();
}
}
inputHandler(inputObj, cb) {
const overridedNewInput = { ...inputObj, ...this.lastLogicEndInput };
this.lastLogicEndInput = {};
this.setState({ updating: true });
const currentNewInput = { ...this.state.input, ...overridedNewInput };
this.cancellable(this.logic(
filterObjectByKeys(currentNewInput, algInput)
)).then(frames => {
this.setState(prev => {
prev.input = {
...prev.input,
...overridedNewInput,
};
prev.frames = frames;
prev.updating = false;
return prev;
}, cb);
}).catch(cancelCatch).catch(err => {
throw new Error(`Input is faulty, ${err}`);
});
}
getInput = () => _mapValues(filterObjectByKeys(this.state.input, algInput), (v, k) => ({
value: v,
update: (newInput, cb = () => {}) => this.inputHandler({
[k]: newInput
}, cb)
}))
render() {
const inputProps = algModulesInputProps(this.getInput());
return (
<LoadingView
{...this.props}
overlay={this.state.frames ? (<AnimatorContainer
{...this.props}
frames={this.state.frames}
callback={this.state.callback}
algorithmInfo={algInfo}
algorithmStatic={_mapValues((typeof algModules === 'function' ? algModules(this.props.app.settings) : algModules), (v, k) => ({
...v,
input: inputProps[k]
}))}
algorithmInitInput={algInitInput(this.getInput())}
/>) : null}
disabled={!this.state.updating}
message={!this.state.frames ? 'Loading Algorithm' : 'Evaluating'}
tooLongTime={3000}
tooLongMessage="Algorithm logic is taking too long to compute"
tooLongEscape={() => {
this.cancelRunning();
if (!this.state.frames) {
return this.props.app.goBack();
}
return this.setState({ updating: false });
}}
/>
);
}
})({}));
export default AlgorithmFactory;
|
new-lamassu-admin/src/components/tables/Stripes.js | naconner/lamassu-server | import React from 'react'
import { Td } from 'src/components/fake-table/Table'
import { ReactComponent as StripesSvg } from 'src/styling/icons/stripes.svg'
const Stripes = ({ width }) => (
<Td width={width}>
<StripesSvg />
</Td>
)
export default Stripes
|
test/integration/jsconfig-paths/pages/resolve-order.js | flybayer/next.js | import React from 'react'
import api from '@lib/api'
export default function ResolveOrder() {
return <div>{api()}</div>
}
|
docs/src/app/components/pages/components/TextField/ExampleCustomize.js | kittyjumbalaya/material-components-web | import React from 'react';
import TextField from 'material-ui/TextField';
import {orange500, blue500} from 'material-ui/styles/colors';
const styles = {
errorStyle: {
color: orange500,
},
underlineStyle: {
borderColor: orange500,
},
floatingLabelStyle: {
color: orange500,
},
floatingLabelFocusStyle: {
color: blue500,
},
};
const TextFieldExampleCustomize = () => (
<div>
<TextField
hintText="Styled Hint Text"
hintStyle={styles.errorStyle}
/><br />
<TextField
hintText="Custom error color"
errorText="This field is required."
errorStyle={styles.errorStyle}
/><br />
<TextField
hintText="Custom Underline Color"
underlineStyle={styles.underlineStyle}
/><br />
<TextField
hintText="Custom Underline Focus Color"
underlineFocusStyle={styles.underlineStyle}
/><br />
<TextField
floatingLabelText="Styled Floating Label Text"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
/>
</div>
);
export default TextFieldExampleCustomize;
|
test/js/AR/onPinchRotateTest.js | viromedia/viro | /**
* Copyright (c) 2017-present, Viro Media, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import {
ViroScene,
ViroARScene,
ViroARPlane,
ViroARPlaneSelector,
ViroBox,
ViroMaterials,
ViroNode,
ViroOrbitCamera,
ViroImage,
ViroVideo,
ViroSkyBox,
Viro360Video,
ViroText,
ViroQuad
} from 'react-viro';
import TimerMixin from 'react-timer-mixin';
var createReactClass = require('create-react-class');
var testARScene = createReactClass({
mixins: [TimerMixin],
getInitialState: function() {
return {
surfaceSize : [0,0,0],
center : [0,0,0],
rotation : [0,0,0],
scale : [1,1,1],
}
},
render: function() {
return (
<ViroARScene ref="arscene" >
<ViroARPlane onAnchorUpdated={this._onPlaneUpdate}>
<ViroQuad materials={"transparent"} scale={this.state.surfaceSize} position={this.state.center}
rotation={[-90, 0, 0]} onClick={this._onSurfaceClickUsingPosition}/>
</ViroARPlane>
{this._getBox()}
</ViroARScene>
);
},
_getBox() {
if (this.state.boxLocation != undefined) {
return (
<ViroNode ref={(component)=>{this.boxRef = component}} position={this.state.boxLocation}
onDrag={()=>{}} scale={this.state.scale} rotation={this.state.rotation} dragType={"FixedToWorld"} >
<ViroBox position={[0,.075,0]} scale={[.15, .15,.15]}
onPinch={this._onPinch} onRotate={this._onRotate}/>
</ViroNode>
)
}
},
_onPlaneUpdate(updateDict) {
this.setState({
surfaceSize : [updateDict.width, updateDict.height, 1],
center : updateDict.center,
})
},
_onSurfaceClickCameraForward() {
this.refs["arscene"].getCameraOrientationAsync().then((orientation) => {
this.refs["arscene"].performARHitTestWithRay(orientation.forward).then((results)=>{
if (results.length > 0) {
for (var i = 0; i < results.length; i++) {
let result = results[i];
if (result.type == "ExistingPlaneUsingExtent") {
this.setState({
boxLocation : result.transform.position
});
return;
}
}
}
})
});
},
_onSurfaceClickUsingPosition(position) {
console.log(position);
this.refs["arscene"].performARHitTestWithPosition(position).then((results)=>{
if (results.length > 0) {
for (var i = 0; i < results.length; i++) {
let result = results[i];
if (result.type == "ExistingPlaneUsingExtent") {
this.setState({
boxLocation : result.transform.position
});
return;
}
}
}
})
},
_onRotate(rotateState, rotationFactor, source) {
if (rotateState == 3) {
this.setState({
rotation : [this.state.rotation[0], this.state.rotation[1] - rotationFactor, this.state.rotation[2]]
});
return;
}
this.boxRef.setNativeProps({rotation:[this.state.rotation[0], this.state.rotation[1] - rotationFactor, this.state.rotation[2]]});
},
/*
Pinch scaling should be relative to its last value *not* the absolute value of the
scale factor. So while the pinching is ongoing set scale through setNativeProps
and multiply the state by that factor. At the end of a pinch event, set the state
to the final value and store it in state.
*/
_onPinch(pinchState, scaleFactor, source) {
var newScale = this.state.scale.map((x)=>{return x * scaleFactor})
if (pinchState == 3) {
this.setState({
scale : newScale
});
return;
}
this.boxRef.setNativeProps({scale:newScale});
},
});
ViroMaterials.createMaterials({
transparent: {
shininess: 2.0,
lightingModel: "Constant",
diffuseColor: "#0000cc55"
},
});
module.exports = testARScene;
|
frontend/src/Components/NotFound.js | geogolem/Radarr | import PropTypes from 'prop-types';
import React from 'react';
import PageContent from 'Components/Page/PageContent';
import translate from 'Utilities/String/translate';
import styles from './NotFound.css';
function NotFound({ message }) {
return (
<PageContent title={translate('MIA')}>
<div className={styles.container}>
<div className={styles.message}>
{message}
</div>
<img
className={styles.image}
src={`${window.Radarr.urlBase}/Content/Images/404.png`}
/>
</div>
</PageContent>
);
}
NotFound.propTypes = {
message: PropTypes.string.isRequired
};
NotFound.defaultProps = {
message: 'You must be lost, nothing to see here.'
};
export default NotFound;
|
node_modules/react-router/es/IndexRoute.js | soniacq/LearningReact | import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils';
import { component, components, falsy } from './InternalPropTypes';
var func = React.PropTypes.func;
/**
* An <IndexRoute> is used to specify its parent's <Route indexRoute> in
* a JSX route config.
*/
/* eslint-disable react/require-render-return */
var IndexRoute = React.createClass({
displayName: 'IndexRoute',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = _createRouteFromReactElement(element);
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0;
}
}
},
propTypes: {
path: falsy,
component: component,
components: components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default IndexRoute; |
src/routes/Counter/components/Counter.js | Dylan1312/pool-elo | import React from 'react'
import Match from './Match'
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
playerOne: "",
playerTwo: "",
result: ""
}
this.baseState = this.state
}
resetState(){
this.state = this.baseState
}
render() {
let self = this;
let props = this.props
function submitMatch() {
if(self.state.playerOne != "" && self.state.playerTwo != "" && self.state.result != "" && self.state.playerOne != self.state.playerTwo)
{
props.submitMatch(
self.state.playerOne,
self.state.playerTwo,
self.state.result
)
self.resetState()
}
}
function handleChange(event) {
self.setState({
[event.target.name]: event.target.value
});
}
return (
<div style={{margin: '0 auto'}}>
<h2>Add a match</h2>
<div className='form form-inline'>
<div className='form-group'>
<label >Player One</label>
<select name="playerOne" className='form-control'
onChange={handleChange}
value={this.state.playerOne}>
<option value="">Choose</option>
{props.players.filter((player) => player.name != this.state.playerTwo).map(
player => <option key={player.name}
value={player.name}>{player.name}</option>
)}
</select>
</div>
<div className='form-group'>
<label>Player Two</label>
<select
name="playerTwo" className='form-control'
onChange={handleChange}
value={this.state.playerTwo}>
<option value="">Choose</option>
{props.players.filter((player) => player.name != this.state.playerOne).map(
player => <option key={player.name}
value={player.name}>{player.name}</option>
)}
</select>
</div>
<div className='form-group'>
<label>Winner</label>
<select name="result" className='form-control'onChange={handleChange} value={this.state.result}>
<option value=""></option>
<option value={self.state.playerOne}>{self.state.playerOne}</option>
<option value={self.state.playerTwo}>{self.state.playerTwo}</option>
</select>
<button className='btn btn-default' onClick={submitMatch}>Submit
</button>
</div>
</div>
<h2>The League</h2>
<table className='table table-striped table-bordered'>
<tbody>
{props.players.sort(function(a, b) {
return b.elo - a.elo;
}).filter(
function(player){ return props.matches.map(function(match){ return match.playerOne}).includes(player.name) || props.matches.map(function(match){ return match.playerTwo}).includes(player.name) }
).map(
(player, index) => <tr key={index}><th>{index+1}</th><td>{player.name}</td><td>{player.elo}</td></tr>
)}
</tbody>
</table>
<h2>Past Matches</h2>
<ul style={{listStyle: "none"}}>
{props.matches.map(
(match) => <Match match={match}></Match>
)}
</ul>
</div>
)
}
}
Counter.propTypes = {
submitMatch: React.PropTypes.func.isRequired,
players: React.PropTypes.array,
match: React.PropTypes.object
}
export default Counter
|
src/app/components/public/Details.js | cherishstand/OA-react | import React, { Component } from 'react';
import Header from './Header';
// require('es6-promise').polyfill();
import {Link} from 'react-router'
import Subheader from 'material-ui/Subheader';
import AppBar from 'material-ui/AppBar';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import ArrowBaclIcon from 'material-ui/svg-icons/navigation/arrow-back';
import Template from './template';
import IconButton from 'material-ui/IconButton';
import ChevronRight from 'material-ui/svg-icons/navigation/chevron-right';
import ExitToApp from 'material-ui/svg-icons/action/exit-to-app';
import { BASIC_URL } from '../../constants/Config';
import Picklist from './Picklist';
import DatePick from './DatePick';
import Alert from './Alert';
import Loading from './Loading';
const styles = {
sub: {
lineHeight: '30px',
paddingLeft: 0
},
head: {
textAlign: 'center',
height: 45,
lineHeight: '45px',
backgroundColor:'rgb(255, 255, 255)'
},
title:{
height: 45,
lineHeight: '45px',
overflow: 'initial',
color: 'rgb(33, 33, 33)',
fontSize: 18
},
edit: {
height: 45,
lineHeight: '45px',
color: 'rgb(94, 149, 201)',
width: 48,
fontSize: 14
},
disable: {
color: 'rgba(0, 0, 0, 0.5)'
},
chevron: {
margin: '10px 0',
width: 20,
height: 20
}
}
class Head extends Component {
constructor(props, context){
super(props, context)
}
render() {
return(
<AppBar
style={styles.head}
titleStyle={styles.title}
title='客户详情'
iconStyleRight={{marginTop: 0}}
iconStyleLeft={{marginTop: 0, marginRight: 0}}
iconElementLeft={this.context.disable ?
<div onTouchTap={this.props.handleCancel} style={styles.edit}>取消</div> :
<IconButton onTouchTap={this.context.router.goBack}><ArrowBaclIcon color="#5e95c9"/></IconButton>
}
iconElementRight={this.context.disable ?
<div onTouchTap={this.props.handleSave} style={styles.edit}>保存</div> :
<IconButton onTouchTap={this.props.toogleEdit}><ExitToApp color="#5e95c9"/></IconButton>
}
/>
)
}
}
Head.contextTypes = {
disable: React.PropTypes.bool.isRequired,
router: React.PropTypes.object,
handleSave: React.PropTypes.any
}
const changeTopic = {};
class Details extends Component {
constructor(props, context){
super(props, context);
this.props.fetchPost(this.props.location.query.url, this.props.params.id, this.props.location.query.mode)
this.state = {
data: {},
disable: false,
typeList: {},
open: false,
}
this.handleChange = (event, idx, v) => {
const name = event.target.name;
const value = event.target.value;
changeTopic[name] = value;
this.setState({data: Object.assign({}, this.state.data, changeTopic)})
}
this.toogleEdit = () => {
this.setState({disable: !this.state.disable})
}
this.handleSave = () => {
this.setState({open: true})
}
this.handleCancel = () => {
this.setState({open: true})
}
this.handleClose = () => {
this.setState({open: false})
}
this.handleSubmit = (event) => {
event.preventDefault();
let form = document.querySelector('form')
let path = this.props.location.pathname
fetch(`${BASIC_URL}${path}`, {
method: 'PUT',
body: new FormData(form)
})
this.setState({open: false,disable: false})
}
}
componentWillUpdate(){
return false
}
componentWillReceiveProps(nextProps){
this.state.data = nextProps.state.data.topic;
this.state.typeList = nextProps.state.data.replies;
}
getChildContext() {
return {
disable: this.state.disable,
handleSave: this.handleSave
}
}
render() {
let layout = [];
const {data, typeList, disable, open} = this.state;
for(let key in typeList){
if(key !== 'pick_list'){
layout.push
(
<div key={key}>
<Subheader style={styles.sub}>{typeList[key].blocklabel}</Subheader>
<div className='basic-msg'>
{typeList[key].fields&&typeList[key].fields.map((field, index) => {
if(field.uitype === '15'){
return <div key={index} className='list-item'>
<label>{field.fieldlabel}:</label>
{
disable ?
<div>
{data.pick_list.hasOwnProperty(field.fieldname) ?
<Picklist list={data.pick_list[field.fieldname]} {...field} value={data[field.fieldname]}/> :
<span name={field.fieldname} data-type={field.fieldtype}></span>}
{<ChevronRight color='#6d6c6c' style={styles.chevron}/>}
</div>
: <span>{data[field.fieldname]}</span>
}
</div>
} else if(field.uitype === '51'){
return <div key={index} className='list-item'>
<label>{field.fieldlabel}:</label>
<span>{data[field.fieldname]}{disable ? <ChevronRight color='#6d6c6c' style={styles.chevron}/> : null}</span>
</div>
} else if (field.uitype === '5'){
return <div key={index} className='list-item'>
<label>{field.fieldlabel}:</label>
<div>
<DatePick date={data.hasOwnProperty(field.fieldname) ? new Date(data[field.fieldname]) : null} name={field.fieldname} />
{disable ? <ChevronRight color='#6d6c6c' style={{width: 20, height: 20}}/> : null}
</div>
</div>
} else if(field.uitype === '19' || field.uitype === '21'){
return <div key={index} className='list-item'>
<label>{field.fieldlabel}:</label>
<textarea
rows={5}
value={data.hasOwnProperty(field.fieldname) ? data[field.fieldname] : ' '}
onChange={this.handleChange}
name={field.fieldname}
data-type={field.fieldtype}
/>
</div>
} else {
return <div key={index} className='list-item'>
<label>{field.fieldlabel}:</label>
<input type='text'
value={data.hasOwnProperty(field.fieldname) ? data[field.fieldname] : ' '}
onChange={this.handleChange}
name={field.fieldname}
data-type={field.fieldtype}
disabled={disable ? false : 'disabled'}
/>
</div>
}
})}
</div>
</div>
)
}
}
return (
<div>
<div className="fiexded">
<Head toogleEdit={this.toogleEdit} handleSave={this.handleSave} handleCancel={this.handleCancel}/>
</div>
{
this.props.state.isFetching ? <Loading /> :
<div style={{padding: '45px 6px 0 6px'}} >
<form onSubmit={this.handleSubmit}>
{layout}
</form>
</div>
}
<Alert open={open} handleClose={this.handleClose} handleSave={this.handleSave} onSubmit={this.handleSubmit} toogleEdit={this.toogleEdit}/>
</div>
)
}
}
Details.childContextTypes = {
disable: React.PropTypes.bool.isRequired,
handleSave: React.PropTypes.any
}
export default Template({
component: Details,
})
|
src/components/PendingChallengeDetail.js | jrzimmerman/bestrida-rn | import React from 'react';
import {
Dimensions,
View,
StatusBar,
Text,
TouchableOpacity
} from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import SegmentMap from './SegmentMap';
import styles from '../styles/styles';
import pendingStyles from '../styles/pendingStyles';
import * as challengeActions from '../actions/challenges';
import * as segmentActions from '../actions/segments';
export class PendingChallengeDetail extends React.Component {
constructor(props) {
super(props);
this.handleAccept = this.handleAccept.bind(this);
this.handleDecline = this.handleDecline.bind(this);
}
componentDidMount() {
const { dispatch } = this.props;
const { challenge } = this.props.navigation.state.params;
dispatch(segmentActions.getSegment(challenge.segment.id));
}
componentWillUnmount() {
this.props.dispatch(segmentActions.clearSegment());
}
handleAccept(challengeId, userId) {
const { dispatch, navigation } = this.props;
dispatch(challengeActions.acceptChallenge(challengeId, userId));
dispatch(challengeActions.pendingChallenges(userId));
navigation.goBack();
}
handleDecline(challengeId, userId) {
const { dispatch, navigation } = this.props;
dispatch(challengeActions.declineChallenge(challengeId, userId));
dispatch(challengeActions.pendingChallenges(userId));
navigation.goBack();
}
render() {
const { segments } = this.props;
const { challenge, userId } = this.props.navigation.state.params;
const { height, width } = Dimensions.get('window');
let segmentMap;
if (segments && segments.segment && segments.segment.map) {
segmentMap = (
<View style={styles.challengeMapView}>
<SegmentMap
height={height * 0.275}
width={width * 0.9}
map={segments.segment.map}
/>
</View>
);
}
let challengeFooter;
if (userId && challenge.challengee.id === userId) {
challengeFooter = (
<View style={pendingStyles.challengeOptions}>
<TouchableOpacity
onPress={() => this.handleDecline(challenge.id, userId)}
style={pendingStyles.challengeOptionsDecline}
>
<Text style={pendingStyles.challengeOptionsDeclineText}>
Decline
</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.handleAccept(challenge.id, userId)}
style={pendingStyles.challengeOptionsAccept}
>
<Text style={pendingStyles.challengeOptionsAcceptText}>Accept</Text>
</TouchableOpacity>
</View>
);
} else if (userId && challenge.challenger.id === userId) {
challengeFooter = (
<TouchableOpacity
onPress={() => this.handleDecline(challenge.id, userId)}
style={styles.button}
>
<Text style={styles.buttonText}>Cancel Challenge</Text>
</TouchableOpacity>
);
}
return (
<View style={styles.container}>
<StatusBar barStyle="light-content" />
<View style={styles.challengeTitleView}>
<Text style={styles.challengeTitleText}>
{challenge.segment.name}
</Text>
</View>
<View style={styles.challengeDetailView}>
<View style={styles.detailRowView}>
<Text style={styles.challengeDetailTitle}>Start Date</Text>
<Text style={styles.challengeDetailText}>
{new Date(challenge.created).toDateString()}
</Text>
</View>
<View style={styles.detailRowView}>
<Text style={styles.challengeDetailTitle}>End Date</Text>
<Text style={styles.challengeDetailText}>
{new Date(challenge.expires).toDateString()}
</Text>
</View>
<View style={styles.detailRowView}>
<Text style={styles.challengeDetailTitle}>Distance</Text>
<Text style={styles.challengeDetailText}>
{`${(challenge.segment.distance / 1609.34).toFixed(2)} Miles` ||
'0'}
</Text>
</View>
<View style={styles.detailRowView}>
<Text style={styles.challengeDetailTitle}>Location</Text>
<Text style={styles.challengeDetailText}>
{`${challenge.segment.city
? `${challenge.segment.city},`
: ''} ${challenge.segment.state}`}
</Text>
</View>
<View style={styles.detailRowView}>
<Text style={styles.challengeDetailTitle}>Activity Type</Text>
<Text style={styles.challengeDetailText}>
{challenge.segment.activityType || 'Not Available'}
</Text>
</View>
<View style={styles.detailRowView}>
<Text style={styles.challengeDetailTitle}>Average Grade</Text>
<Text style={styles.challengeDetailText}>{`${challenge.segment
.averageGrade} %`}</Text>
</View>
<View style={styles.detailRowView}>
<Text style={styles.challengeDetailTitle}>Climb Category</Text>
<Text style={styles.challengeDetailText}>
{challenge.segment.climbCategory || 'Not Available'}
</Text>
</View>
<View style={styles.detailRowView}>
<Text style={styles.challengeDetailTitle}>Elevation Gain</Text>
<Text style={styles.challengeDetailText}>
{`${challenge.segment.totalElevationGain} meters`}
</Text>
</View>
</View>
{segmentMap}
<View style={styles.challengeFooterView}>{challengeFooter}</View>
</View>
);
}
}
const { func, number, shape } = PropTypes;
PendingChallengeDetail.propTypes = {
dispatch: func,
challenge: shape({}),
userId: number,
navigation: shape({}),
segments: shape({})
};
const mapStateToProps = state => ({
userId: state.user.auth.userId,
segments: state.segments
});
export default connect(mapStateToProps)(PendingChallengeDetail);
|
examples/styled-components/src/containers/Home.js | calvinrbnspiess/react-static | import React from 'react'
import { getSiteProps } from 'react-static'
//
import logoImg from '../logo.png'
export default getSiteProps(() => (
<div>
<h1 style={{ textAlign: 'center' }}>Welcome to</h1>
<img src={logoImg} alt="" />
</div>
))
|
app/containers/NotFoundPage/index.js | thuy616/react-d3-charts | /**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
packages/core/admin/admin/src/pages/AuthPage/components/Oops/index.js | wistityhq/strapi | import React from 'react';
import { useIntl } from 'react-intl';
import { useQuery } from '@strapi/helper-plugin';
import { Box } from '@strapi/design-system/Box';
import { Main } from '@strapi/design-system/Main';
import { Flex } from '@strapi/design-system/Flex';
import { Link } from '@strapi/design-system/Link';
import { Typography } from '@strapi/design-system/Typography';
import UnauthenticatedLayout, {
Column,
LayoutContent,
} from '../../../../layouts/UnauthenticatedLayout';
import Logo from '../../../../components/UnauthenticatedLogo';
const Oops = () => {
const { formatMessage } = useIntl();
const query = useQuery();
const message =
query.get('info') ||
formatMessage({
id: 'Auth.components.Oops.text',
defaultMessage: 'Your account has been suspended.',
});
return (
<UnauthenticatedLayout>
<Main>
<LayoutContent>
<Column>
<Logo />
<Box paddingTop={6} paddingBottom={7}>
<Typography as="h1" variant="alpha">
{formatMessage({ id: 'Auth.components.Oops.title', defaultMessage: 'Oops...' })}
</Typography>
</Box>
<Typography>{message}</Typography>
<Box paddingTop={4}>
<Typography>
{formatMessage({
id: 'Auth.components.Oops.text.admin',
defaultMessage: 'If this is a mistake, please contact your administrator.',
})}
</Typography>
</Box>
</Column>
</LayoutContent>
<Flex justifyContent="center">
<Box paddingTop={4}>
<Link to="/auth/login">
{formatMessage({ id: 'Auth.link.signin', defaultMessage: 'Sign in' })}
</Link>
</Box>
</Flex>
</Main>
</UnauthenticatedLayout>
);
};
export default Oops;
|
client/modules/Search/components/SearchForm/SearchForm.js | XuHaoJun/tiamat | import React from 'react';
class SearchForm extends React.Component {
render() {
return 'test';
}
}
export default SearchForm;
|
src/js/components/Retail/Login/partial/LoginFormOTP.js | ajainsyn/project | import React from 'react';
import { Link } from 'react-router-dom';
const LoginFormOTP = ({...props}) => {
return (
<div className="retail-login">
<div className="retail-login-header">
<h3>
Enter your One Time Password (OTP)
<span className="info-otp">Please check your registred mobile number 85xxxxxx25 for OTP</span>
</h3>
</div>
<form className="form-default">
<div className="form-box">
<label htmlFor="otp" className="form-label">One Time Passowrd (OTP)</label>
<input id="otp" name="otp" className="form-input" type="text" />
</div>
<div className="buttons">
<button className="btn btn-primary" onClick={props.backToLogin} >Back to login</button>
<Link to="/my-account" className="btn btn-default">Login to SYN Bank</Link>
</div>
</form>
</div>
)};
export default LoginFormOTP; |
src/parser/monk/brewmaster/CHANGELOG.js | sMteX/WoWAnalyzer | import React from 'react';
import { emallson, Zerotorescue } from 'CONTRIBUTORS';
import ITEMS from 'common/ITEMS';
import ItemLink from 'common/ItemLink';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
export default [
{
date: new Date('2019-04-11'),
changes: <>Fixed a bug in the Mitigation Values tab that caused Mastery's base 8% to be counted towards contribution by Mastery Rating.</>,
contributors: [emallson],
},
{
date: new Date('2019-03-10'),
changes: <>Fixed a bug in the <SpellLink id={SPELLS.IRONSKIN_BREW.id} /> normalizer that led to a crash in the new timeline.</>,
contributors: [Zerotorescue],
},
{
date: new Date('2019-02-16'),
changes: <>Removed <SpellLink id={SPELLS.BREATH_OF_FIRE.id} /> from the checklist.</>,
contributors: [emallson],
},
{
date: new Date('2019-01-31'),
changes: <>Added Mitigation Values tab showing estimated stat values for damage mitigation.</>,
contributors: [emallson],
},
{
date: new Date('2018-12-30'),
changes: <>Added <SpellLink id={SPELLS.STRAIGHT_NO_CHASER.id} /> module.</>,
contributors: [emallson],
},
{
date: new Date('2018-12-29'),
changes: <>Added <SpellLink id={SPELLS.GIFT_OF_THE_OX_1.id} /> healing statistic.</>,
contributors: [emallson],
},
{
date: new Date('2018-10-26'),
changes: <>Added <SpellLink id={SPELLS.CELESTIAL_FORTUNE_HEAL.id} /> healing statistic and table.</>,
contributors: [emallson],
},
{
date: new Date('2018-10-22'),
changes: <>The <SpellLink id={SPELLS.MASTERY_ELUSIVE_BRAWLER.id} /> module now loads on-demand, improving load times for lower-end devices.</>,
contributors: [emallson],
},
{
date: new Date('2018-10-15'),
changes: <>Added <SpellLink id={SPELLS.PURIFYING_BREW.id} /> checklist item.</>,
contributors: [emallson],
},
{
date: new Date('2018-10-02'),
changes: <>Re-enabled the <SpellLink id={SPELLS.MASTERY_ELUSIVE_BRAWLER.id} /> module and added additional distribution information to it.</>,
contributors: [emallson],
},
{
date: new Date('2018-09-27'),
changes: 'Updated Stagger plot to show very quick purifies more accurately.',
contributors: [emallson],
},
{
date: new Date('2018-09-22'),
changes: <>Updated <SpellLink id={SPELLS.IRONSKIN_BREW.id} /> and <SpellLink id={SPELLS.BREATH_OF_FIRE.id} /> suggestions to use hits mitigated instead of uptime.</>,
contributors: [emallson],
},
{
date: new Date('2018-09-22'),
changes: <>Added support for <SpellLink id={SPELLS.FIT_TO_BURST.id} />.</>,
contributors: [emallson],
},
{
date: new Date('2018-09-13'),
changes: <>Added support for <SpellLink id={SPELLS.ELUSIVE_FOOTWORK.id} />.</>,
contributors: [emallson],
},
{
date: new Date('2018-08-11'),
changes: <>Added support for <SpellLink id={SPELLS.STAGGERING_STRIKES.id} />.</>,
contributors: [emallson],
},
{
date: new Date('2018-07-22'),
changes: <>Updated support for <ItemLink id={ITEMS.SOUL_OF_THE_GRANDMASTER.id} /> and temporarily disabled the <SpellLink id={SPELLS.MASTERY_ELUSIVE_BRAWLER.id} /> module pending new formula coefficients.</>,
contributors: [emallson],
},
{
date: new Date('2018-07-18'),
changes: <>Added support for <SpellLink id={SPELLS.LIGHT_BREWING_TALENT.id} />.</>,
contributors: [emallson],
},
{
date: new Date('2018-07-15'),
changes: <>Added <SpellLink id={SPELLS.TRAINING_OF_NIUZAO.id} /> support.</>,
contributors: [emallson],
},
{
date: new Date('2018-06-16'),
changes: <>Updated <SpellLink id={SPELLS.IRONSKIN_BREW.id} /> cooldown and duration and added <SpellLink id={SPELLS.GUARD_TALENT.id} />, along with other changes in beta build 26812.</>,
contributors: [emallson],
},
];
|
app/containers/ThemeProvider/index.js | juanda99/arasaac-frontend | /*
*
* ThemeProvider
*
* this component connects the redux state theme to the
*
*/
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import { makeSelectDirection } from 'containers/LanguageProvider/selectors';
import customTheme from './customTheme'
export class ThemeProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
const theme = customTheme(this.props.theme, this.props.direction)
return (
<MuiThemeProvider muiTheme={theme}>
{React.Children.only(this.props.children)}
</MuiThemeProvider>
)
}
}
ThemeProvider.propTypes = {
theme: PropTypes.string,
children: PropTypes.element.isRequired,
direction: PropTypes.string.isRequired,
}
const mapStateToProps = (state) => {
const theme = state.get('theme')
const direction = makeSelectDirection()(state)
return ({
theme,
direction
})
}
function mapDispatchToProps(dispatch) {
return {
dispatch
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ThemeProvider)
|
src/components/Link/Link.js | AaronHartigan/DudeTruck | /**
* 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 history from '../../history';
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
class Link extends React.Component {
static propTypes = {
to: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
onClick: PropTypes.func,
};
static defaultProps = {
onClick: null,
};
handleClick = event => {
if (this.props.onClick) {
this.props.onClick(event);
}
if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}
if (event.defaultPrevented === true) {
return;
}
event.preventDefault();
history.push(this.props.to);
};
render() {
const { to, children, ...props } = this.props;
return (
<a href={to} {...props} onClick={this.handleClick}>
{children}
</a>
);
}
}
export default Link;
export { Link as LinkTest };
|
src/components/Navigation/SideNavbar.js | strongharris/Dashboard | import React from 'react';
import { Link } from 'react-router-dom';
const SideNavbar = () => {
return (
<div id="menubar" className="menubar-inverse ">
<div className="menubar-fixed-panel">
<div>
<a className="btn btn-icon-toggle btn-default menubar-toggle" data-toggle="menubar" href="javascript:void(0);">
<i className="fa fa-bars"></i>
</a>
</div>
<div className="expanded">
<a href="/">
<span className="text-lg text-bold text-primary ">MATERIAL ADMIN</span>
</a>
</div>
</div>
<div className="menubar-scroll-panel">
<ul id="main-menu" className="gui-controls">
<li>
<a href="/" className="active">
<div className="gui-icon"><i className="md md-home"></i></div>
<span className="title">Home</span>
</a>
</li>
<li>
<a href="#/management/survey" >
<div className="gui-icon"><i className="md md-web"></i></div>
<span className="title">Survey</span>
</a>
</li>
<li>
<a href="javascript:void(0)" >
<div className="gui-icon"><i className="md md-account-child"></i></div>
<span className="title">Account</span>
</a>
</li>
<li className="gui-folder">
<a>
<div className="gui-icon"><i className="md md-insert-chart"></i></div>
<span className="title">Analytic</span>
</a>
<ul>
<li><a href="#/analytic/background"><span className="title">Community Field Study</span></a></li>
</ul>
</li>
<li className="gui-folder">
<a>
<div className="gui-icon"><i className="fa fa-folder-open fa-fw"></i></div>
<span className="title">Data</span>
</a>
<ul>
<li><a href="#/data/background"><span className="title">Community Field Study</span></a></li>
</ul>
</li>
</ul>
<div className="menubar-foot-panel">
<small className="no-linebreak hidden-folded">
<span className="opacity-75">Copyright © SZC</span> <strong>Impact Learning</strong>
</small>
</div>
</div>
</div>
);
}
export default SideNavbar;
|
src/fit-items-popover/index.js | SodhanaLibrary/react-examples | import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import App from './app';
render( <AppContainer><App/></AppContainer>, document.querySelector("#app"));
if (module.hot) {
module.hot.accept('./app.js', () => {
const App = require('./app.js').default;
render(
<AppContainer>
<App/>
</AppContainer>,
document.querySelector("#app")
);
});
}
|
src/components/Popup/Popup.js | Barylskyigb/simple-debts-react-native | import React from 'react';
import {
View,
KeyboardAvoidingView,
Platform,
Text,
ViewPropTypes
} from 'react-native';
import PropTypes from 'prop-types';
import Modal from 'react-native-modal';
import styles from './Popup.styles';
import KeyboardDismissingView from '../KeyboardDismissingView/KeyboardDismissingView';
import ButtonDeprecated from '../Button/ButtonDeprecated';
const Popup = ({
onBackdropPress,
style,
containerStyle,
children,
title,
noMargin,
cancelBtnProps,
confirmBtnProps,
...rest
}) => (
<Modal
onBackdropPress={onBackdropPress}
onBackButtonPress={onBackdropPress}
backdropOpacity={0.5}
animationIn="fadeIn"
animationOut="fadeOut"
avoidKeyboard
style={noMargin && { margin: 0 }}
useNativeDriver
hideModalContentWhileAnimating
{...rest}
>
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : null}
keyboardVerticalOffset={-50}
style={[styles.container, containerStyle]}
>
<KeyboardDismissingView style={styles.popup}>
{title && <Text style={styles.title}>{title}</Text>}
{title && <View style={styles.divider} />}
<View style={[styles.body, style]}>{children}</View>
{(cancelBtnProps || confirmBtnProps) && (
<View style={styles.btnsContainer}>
{cancelBtnProps && (
<ButtonDeprecated
title="CANCEL"
{...cancelBtnProps}
style={[styles.btn, cancelBtnProps.style]}
textStyle={styles.btnText}
/>
)}
{confirmBtnProps && (
<ButtonDeprecated
title="OK"
{...confirmBtnProps}
style={[styles.btn, confirmBtnProps.style]}
textStyle={styles.btnText}
/>
)}
</View>
)}
</KeyboardDismissingView>
</KeyboardAvoidingView>
</Modal>
);
Popup.propTypes = {
onBackdropPress: PropTypes.func.isRequired,
style: ViewPropTypes.style,
containerStyle: ViewPropTypes.style,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]).isRequired,
title: PropTypes.string,
noMargin: PropTypes.bool,
cancelBtnProps: PropTypes.object,
confirmBtnProps: PropTypes.object
};
Popup.defaultProps = {
style: null,
title: null,
noMargin: false,
cancelBtnProps: null,
confirmBtnProps: null
};
export default Popup;
|
src/botPage/view/react-components/HeaderWidgets.js | binary-com/binary-bot | import React from 'react';
const ServerTime = ({ api }) => {
const [hasApiResponse, setHasApiResponse] = React.useState(false);
const [date, setDate] = React.useState();
const [dateString, setDateString] = React.useState();
const updateTime = () => {
if (!date) return;
date.setSeconds(date.getSeconds() + 1);
const year = date.getUTCFullYear();
const month = `0${date.getMonth() + 1}`.slice(-2);
const day = `0${date.getUTCDate()}`.slice(-2);
const hours = `0${date.getUTCHours()}`.slice(-2);
const minutes = `0${date.getUTCMinutes()}`.slice(-2);
const seconds = `0${date.getUTCSeconds()}`.slice(-2);
setDateString(`${year}-${month}-${day} ${hours}:${minutes}:${seconds} GMT`);
};
const getServerTime = () => {
api.send({ time: 1 }).then(response => {
const newDate = new Date(response.time * 1000);
setDate(newDate);
setHasApiResponse(true);
});
};
React.useEffect(() => {
getServerTime();
const updateTimeInterval = setInterval(updateTime, 1000);
const serverTimeInterval = setInterval(getServerTime, 30000);
return () => {
clearInterval(updateTimeInterval);
clearInterval(serverTimeInterval);
};
}, [hasApiResponse]);
React.useEffect(() => updateTime(), [date]);
return <b>{dateString}</b>;
};
export default ServerTime;
|
src/v2/stories/Buttons.stories.js | aredotna/ervell | import React from 'react'
import { storiesOf } from '@storybook/react'
import theme from 'v2/styles/theme'
import Specimen from 'v2/stories/__components__/Specimen'
import States from 'v2/stories/__components__/States'
import GenericButton from 'v2/components/UI/GenericButton'
import { DividerButton, FilledButton } from 'v2/components/UI/Buttons'
storiesOf('Button', module)
.add('GenericButton', () => (
<States
states={[{}, { disabled: true }, { hover: true }, { active: true }]}
>
<GenericButton>Button</GenericButton>
</States>
))
.add('GenericButton - colors', () => (
<Specimen>
{theme.meta.colorNames.map(color => (
<States
key={color}
states={[{}, { disabled: true }, { hover: true }, { active: true }]}
>
<GenericButton color={color}>{color}</GenericButton>
</States>
))}
</Specimen>
))
.add('GenericButton - sizes', () => (
<Specimen>
{theme.fontSizes.map((size, i) => (
<States
key={size}
states={[{}, { disabled: true }, { hover: true }, { active: true }]}
>
<GenericButton f={i}>{`f={${i}}`}</GenericButton>
</States>
))}
</Specimen>
))
.add('GenericButton - minWidth', () => (
<Specimen>
<GenericButton minWidth="7em">Yes</GenericButton>{' '}
<GenericButton minWidth="7em">No</GenericButton>{' '}
<GenericButton minWidth="7em">Maybe</GenericButton>
</Specimen>
))
.add('GenericButton - dark backgrounds', () => (
<Specimen>
<States
bg="white"
states={[{}, { disabled: true }, { hover: true }, { active: true }]}
>
<GenericButton>Submit</GenericButton>
</States>
<States
bg="state.premium"
states={[{}, { disabled: true }, { hover: true }, { active: true }]}
>
<GenericButton color="white">Submit</GenericButton>
</States>
</Specimen>
))
.add('DividerButton', () => (
<States
states={[{}, { disabled: true }, { hover: true }, { active: true }]}
>
<DividerButton>Submit</DividerButton>
</States>
))
.add('DividerButton - colors', () => (
<Specimen>
{theme.meta.colorNames.map(color => (
<States
key={color}
states={[{}, { disabled: true }, { hover: true }, { active: true }]}
>
<DividerButton color={color}>{color}</DividerButton>
</States>
))}
</Specimen>
))
.add('DividerButton - sizes', () => (
<Specimen>
{theme.fontSizes.map((size, i) => (
<States
key={size}
states={[{}, { disabled: true }, { hover: true }, { active: true }]}
>
<DividerButton f={i}>{`f={${i}}`}</DividerButton>
</States>
))}
</Specimen>
))
.add('FilledButton', () => (
<States
bg="gray.regular"
states={[{}, { disabled: true }, { hover: true }, { active: true }]}
>
<FilledButton>Button</FilledButton>
</States>
))
.add('FilledButton - colors', () => (
<Specimen>
{theme.meta.colorNames.map(color => (
<States
key={color}
states={[{}, { disabled: true }, { hover: true }, { active: true }]}
>
<FilledButton color={color}>{color}</FilledButton>
</States>
))}
</Specimen>
))
.add('FilledButton - sizes', () => (
<Specimen>
{theme.fontSizes.map((size, i) => (
<States
bg="gray.regular"
key={size}
states={[{}, { disabled: true }, { hover: true }, { active: true }]}
>
<FilledButton f={i}>{`f={${i}}`}</FilledButton>
</States>
))}
</Specimen>
))
|
node_modules/react-element-to-jsx-string/AnonymousStatelessComponent.js | Snatch-M/fesCalendar | import React from 'react';
export default function(props) {
const {children} = props; // eslint-disable-line react/prop-types
return <div>{children}</div>;
}
|
src/components/experience.js | DoWhileGeek/resume | import React from 'react'
const PageBreak = () => <div className="page-break" />
export default ({ company, title, dateRange, children, pageBreak = false }) => {
return (
<>
<div className="experience-container">
<div className="experience-header">
<span>
<b>{title}</b> at {company}
</span>
{dateRange}
</div>
<ul className="duties-list">{children}</ul>
</div>
{pageBreak && <PageBreak />}
</>
)
}
|
packages/material-ui-icons/src/LibraryAdd.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let LibraryAdd = props =>
<SvgIcon {...props}>
<path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z" />
</SvgIcon>;
LibraryAdd = pure(LibraryAdd);
LibraryAdd.muiName = 'SvgIcon';
export default LibraryAdd;
|
src/Parser/Core/Modules/Items/Legion/AntorusTheBurningThrone/TarratusKeystone.js | hasseboulen/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import ItemHealingDone from 'Main/ItemHealingDone';
/*
* Tarratus Keystone -
* Use: Open a portal at an ally's location that releases brilliant light, restoring 1633313 health split amongst injured allies within 20 yds. (1 Min, 30 Sec Cooldown)
*/
class TarratusKeystone extends Analyzer {
static dependencies = {
combatants: Combatants,
};
healing = 0;
on_initialized() {
this.active = this.combatants.selected.hasTrinket(ITEMS.TARRATUS_KEYSTONE.id);
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.TARRATUS_KEYSTONE.id) {
this.healing += (event.amount || 0) + (event.absorbed || 0);
}
}
item() {
return {
item: ITEMS.TARRATUS_KEYSTONE,
result: <ItemHealingDone amount={this.healing} />,
};
}
}
export default TarratusKeystone;
|
modules/RoutingContext.js | Nedomas/react-router | import React from 'react'
import invariant from 'invariant'
import getRouteParams from './getRouteParams'
const { array, func, object } = React.PropTypes
/**
* A <RoutingContext> renders the component tree for a given router state
* and sets the history object and the current location in context.
*/
const RoutingContext = React.createClass({
propTypes: {
history: object.isRequired,
createElement: func.isRequired,
location: object.isRequired,
routes: array.isRequired,
params: object.isRequired,
components: array.isRequired
},
getDefaultProps() {
return {
createElement: React.createElement
}
},
childContextTypes: {
history: object.isRequired,
location: object.isRequired
},
getChildContext() {
return {
history: this.props.history,
location: this.props.location
}
},
createElement(component, props) {
return component == null ? null : this.props.createElement(component, props)
},
render() {
const { history, location, routes, params, components } = this.props
let element = null
if (components) {
element = components.reduceRight((element, components, index) => {
if (components == null)
return element // Don't create new children use the grandchildren.
const route = routes[index]
const routeParams = getRouteParams(route, params)
const props = {
history,
location,
params,
route,
routeParams,
routes
}
if (element)
props.children = element
if (typeof components === 'object') {
const elements = {}
for (const key in components)
if (components.hasOwnProperty(key))
elements[key] = this.createElement(components[key], props)
return elements
}
return this.createElement(components, props)
}, element)
}
invariant(
element === null || element === false || React.isValidElement(element),
'The root route must render a single element'
)
return element
}
})
export default RoutingContext
|
client/extensions/woocommerce/woocommerce-services/views/shipping-label/label-purchase-modal/rates-step/index.js | Automattic/woocommerce-services | /** @format */
/**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { localize } from 'i18n-calypso';
import { find, forEach, isEmpty, mapValues, some } from 'lodash';
import formatCurrency from '@automattic/format-currency';
import Gridicon from 'gridicons';
/**
* Internal dependencies
*/
import ShippingRates from './list';
import StepContainer from '../step-container';
import { hasNonEmptyLeaves } from 'woocommerce/woocommerce-services/lib/utils/tree';
import {
toggleStep,
updateRate,
} from 'woocommerce/woocommerce-services/state/shipping-label/actions';
import {
getShippingLabel,
isLoaded,
getFormErrors,
getTotalPriceBreakdown,
} from 'woocommerce/woocommerce-services/state/shipping-label/selectors';
import { getAllPackageDefinitions } from 'woocommerce/woocommerce-services/state/packages/selectors';
import { getOrderShippingTotal } from 'woocommerce/lib/order-values/totals';
import {
getOrderShippingMethod,
getOrderCurrency
} from 'woocommerce/lib/order-values';
import { getOrder } from 'woocommerce/state/sites/orders/selectors';
const ratesSummary = ( selectedRates, availableRates, total, packagesSaved, translate ) => {
if ( ! packagesSaved ) {
return translate( 'Unsaved changes made to packages' );
}
if ( some( mapValues( availableRates, rateObject => isEmpty( rateObject.default.rates ) ) ) ) {
return translate( 'No rates found' );
}
if ( ! total ) {
return '';
}
const packageIds = Object.keys( selectedRates );
// Show the service name and cost when only one service/package exists
if ( 1 === packageIds.length ) {
const packageId = packageIds[ 0 ];
const selectedRate = selectedRates[ packageId ];
const packageRates = availableRates[ packageId ].default.rates;
const rateInfo = find( packageRates, [ 'service_id', selectedRate ] );
if ( rateInfo ) {
return translate( '%(serviceName)s: %(rate)s', {
args: {
serviceName: rateInfo.title,
rate: formatCurrency( rateInfo.rate, 'USD' ),
},
} );
}
return '';
}
// Otherwise, just show the total
return translate( 'Total rate: %(total)s', {
args: {
total: formatCurrency( total, 'USD' ),
},
} );
};
const getRatesStatus = ( { retrievalInProgress, errors, available, form } ) => {
if ( retrievalInProgress ) {
return { isProgress: true };
}
if ( hasNonEmptyLeaves( errors ) ) {
return { isError: true };
}
if ( isEmpty( available ) ) {
return {};
}
if ( ! form.packages.saved ) {
return { isWarning: true };
}
return { isSuccess: true };
};
const showCheckoutShippingInfo = props => {
const { shippingMethod, shippingCost, translate, currency } = props;
// Use a temporary HTML element in order to let the DOM API convert HTML entities into text
const shippingMethodDiv = document.createElement( 'div' );
shippingMethodDiv.innerHTML = shippingMethod;
const decodedShippingMethod = shippingMethodDiv.textContent;
// Add suffix for non USD.
const shippingCostSuffix = ( typeof currency != 'undefined' && 'USD' !== currency ) ? currency : '';
if ( shippingMethod ) {
let shippingInfo;
if ( 0 < shippingCost ) {
shippingInfo = translate(
'Customer paid a {{shippingMethod/}} of {{shippingCost/}} for shipping',
{
components: {
shippingMethod: (
<span>{ decodedShippingMethod }</span>
),
shippingCost: (
<span className="rates-step__shipping-info-cost">
{ formatCurrency( shippingCost, currency ) } { shippingCostSuffix }
</span>
),
},
}
);
} else {
shippingInfo = translate( 'Your customer selected {{shippingMethod/}}', {
components: {
shippingMethod: (
<span className="rates-step__shipping-info-method">{ decodedShippingMethod }</span>
),
},
} );
}
return (
<div className="rates-step__shipping-info">
<Gridicon icon="info-outline" />
<div >{ shippingInfo }</div>
</div>
);
}
};
const RatesStep = props => {
const {
siteId,
orderId,
form,
allPackages,
values,
available,
errors,
ratesTotal,
translate,
currency,
} = props;
const summary = ratesSummary( values, available, ratesTotal, form.packages.saved, translate );
const toggleStepHandler = () => props.toggleStep( orderId, siteId, 'rates' );
const updateRateHandler = ( packageId, serviceId, carrierId, signatureRequired ) =>
props.updateRate( orderId, siteId, packageId, serviceId, carrierId, signatureRequired );
// Preselect rates for packages that have only one rate available.
forEach( form.packages.selected, ( selectedRate, pckgId ) => {
// Skip preselection for already selected values.
if( "" !== values[ pckgId ] ) {
return;
}
if ( ( ! isEmpty( available ) ) && ( pckgId in available ) && ( 1 === available[ pckgId ].default.rates.length ) ) {
const signatureRequired = false; // Don't preselect signature.
const { service_id } = available[ pckgId ].default.rates[ 0 ];
updateRateHandler( pckgId, service_id, signatureRequired );
}
} );
return (
<StepContainer
title={ translate( 'Shipping rates' ) }
summary={ summary }
expanded={ ! isEmpty( available ) }
toggleStep={ toggleStepHandler }
{ ...getRatesStatus( props ) }
>
{ ! isEmpty( available ) && showCheckoutShippingInfo( props ) }
<ShippingRates
id="rates"
orderId={ orderId }
siteId={ siteId }
currency={ currency }
showRateNotice={ false }
selectedPackages={ form.packages.selected }
allPackages={ allPackages }
selectedRates={ values }
availableRates={ available }
updateRate={ updateRateHandler }
errors={ errors }
/>
</StepContainer>
);
};
RatesStep.propTypes = {
siteId: PropTypes.number.isRequired,
orderId: PropTypes.number.isRequired,
form: PropTypes.object.isRequired,
values: PropTypes.object.isRequired,
available: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired,
toggleStep: PropTypes.func.isRequired,
updateRate: PropTypes.func.isRequired,
};
const mapStateToProps = ( state, { orderId, siteId } ) => {
const loaded = isLoaded( state, orderId, siteId );
const shippingLabelState = getShippingLabel( state, orderId, siteId );
const priceBreakdown = getTotalPriceBreakdown( state, orderId, siteId );
const order = getOrder( state, orderId, siteId );
return {
...shippingLabelState.form.rates,
form: shippingLabelState.form,
errors: loaded && getFormErrors( state, orderId, siteId ).rates,
ratesTotal: priceBreakdown ? priceBreakdown.total : 0,
allPackages: getAllPackageDefinitions( state, siteId ),
shippingCost: getOrderShippingTotal( order ),
shippingMethod: getOrderShippingMethod( order ),
currency: getOrderCurrency( order ),
};
};
const mapDispatchToProps = dispatch => {
return bindActionCreators( { toggleStep, updateRate }, dispatch );
};
export default connect(
mapStateToProps,
mapDispatchToProps
)( localize( RatesStep ) );
|
app/jsx/navigation_header/trays/GroupsTray.js | djbender/canvas-lms | /*
* Copyright (C) 2015 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import I18n from 'i18n!GroupsTray'
import React from 'react'
import {bool, arrayOf, shape, string} from 'prop-types'
import {View} from '@instructure/ui-layout'
import {Heading, List, Spinner} from '@instructure/ui-elements'
import {Link} from '@instructure/ui-link'
export default function GroupsTray({groups, hasLoaded}) {
return (
<View as="div" padding="medium">
<Heading level="h3" as="h2">
{I18n.t('Groups')}
</Heading>
<hr role="presentation" />
<List variant="unstyled" margin="small 0" itemSpacing="small">
{hasLoaded ? (
groups
.map(group => (
<List.Item key={group.id}>
<Link isWithinText={false} href={`/groups/${group.id}`}>
{group.name}
</Link>
</List.Item>
))
.concat([
<List.Item key="hr">
<hr role="presentation" />
</List.Item>,
<List.Item key="all">
<Link isWithinText={false} href="/groups">
{I18n.t('All Groups')}
</Link>
</List.Item>
])
) : (
<List.Item>
<Spinner size="small" renderTitle={I18n.t('Loading')} />
</List.Item>
)}
</List>
</View>
)
}
GroupsTray.propTypes = {
groups: arrayOf(
shape({
id: string.isRequired,
name: string.isRequired
})
).isRequired,
hasLoaded: bool.isRequired
}
GroupsTray.defaultProps = {
groups: []
}
|
test/integration/image-component/custom-resolver/pages/client-side.js | zeit/next.js | import React from 'react'
import Image from 'next/image'
const myLoader = ({ src, width, quality }) => {
return `https://customresolver.com/${src}?w~~${width},q~~${quality}`
}
const MyImage = (props) => {
return <Image loader={myLoader} {...props}></Image>
}
const Page = () => {
return (
<div>
<p id="client-side">Image Client Side Test</p>
<MyImage
id="basic-image"
src="foo.jpg"
loading="eager"
width={300}
height={400}
quality={60}
/>
<Image
id="unoptimized-image"
unoptimized
src="https://arbitraryurl.com/foo.jpg"
loading="eager"
width={300}
height={400}
/>
</div>
)
}
export default Page
|
internals/templates/containers/HomePage/index.js | VeloCloud/website-ui | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
src/tags/size.js | JimLiu/bbcode-to-react | // https://github.com/vishnevskiy/bbcodejs/blob/master/src/coffee/tags.coffee
import React from 'react';
import Tag from '../tag';
export default class SizeTag extends Tag {
toHTML() {
const size = this.params.size;
if (isNaN(size)) {
return this.getContent();
}
return [`<span style="font-size:${size}px">`, this.getContent(), '</span>'];
}
toReact() {
const size = this.params.size;
if (isNaN(size)) {
return this.getComponents();
}
return (
<span style={{ fontSize: `${size}px` }}>{this.getComponents()}</span>
);
}
}
|
demo/components/Head.js | flybears/component-react | /**
* Created by flybear on 15/11/18.
*/
import React from 'react'
export default class Head extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
console.log("---")
}
render() {
return (
<header>
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<a className="navbar-brand" href="javascript:">Brand</a>
</div>
<div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul className="nav navbar-nav">
<li className="active"><a href="javascript:">Link <span className="sr-only">(current)</span></a></li>
<li><a href="javascript:">Link</a></li>
<li className="dropdown">
<a href="javascript:" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span className="caret"></span></a>
<ul className="dropdown-menu">
<li><a href="javascript:">Action</a></li>
<li><a href="javascript:">Another action</a></li>
<li><a href="javascript:">Something else here</a></li>
<li role="separator" className="divider"></li>
<li><a href="javascript:">Separated link</a></li>
<li role="separator" className="divider"></li>
<li><a href="javascript:">One more separated link</a></li>
</ul>
</li>
</ul>
<div className="nav navbar-nav navbar-right lh50">
<button className="btn btn-primary m-r-sm" onClick={this.handleClick} >登陆</button>
<button className="btn btn-default" href="javascript:">注册</button>
</div>
</div>
</div>
</nav>
</header>
)
}
} |
opentech/static_src/src/app/src/components/MessagesList/index.js | OpenTechFund/WebApp | import React from 'react'
import PropTypes from 'prop-types'
import MessageBar from '@components/MessageBar'
const MessagesList = ({ children }) => {
return (
<ul className="messages">
{ children }
</ul>
)
}
MessagesList.propTypes = {
children: PropTypes.oneOfType([PropTypes.arrayOf(MessageBar), MessageBar])
}
export default MessagesList
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.