path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/components/NavigationBar.js | Rkiouak/react-redux-python-stocks | import React from 'react'
import { Link } from 'react-router'
const blue = '#337ab7'
const light = '#fff'
const styles = {}
styles.wrapper = {
padding: '10px 20px',
overflow: 'hidden',
background: blue,
color: light
}
styles.link = {
padding: 11,
color: light,
fontWeight: 200
}
styles.activeLink = {
padding: 11,
fontWeight: 200,
background: light,
color: blue
}
class NavigationBar extends React.Component {
static defaultProps = {
user: {
id: 1,
name: 'A User'
}
}
constructor (props, context) {
super(props, context)
this.logOut = this.logOut.bind(this)
}
logOut () {
alert ('log out')
}
render () {
const { user } = this.props
return (
<div style={styles.wrapper}>
<Link to="/" style={styles.link} activeStyle={styles.activeLink}>Stocks</Link>{' '}
{/*<Link to="/resume">Resume</Link>*/}
<Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button>
</div>
)
}
}
export default NavigationBar
|
src/rocks/timeline-tab/toolbar/OverlayPanel.js | animachine/animachine | import React from 'react'
import {Panel} from 'react-matterkit'
export default class OverlayPanel extends React.Component {
render () {
return (
<Panel style={{
position: 'absolute',
zIndex: 200,
boxShadow: '0px 0px 5px 0px rgba(255,255,255,0.5)',//'0px 0px 5px 0px rgba(107,182,196,0.75)',
}}>
{this.props.children}
</Panel>
)
}
}
|
react/src/components/CommandTree/TreeView.js | ozlerhakan/rapid | /**
* Created by hakan on 15/02/2017.
*/
import React from 'react';
import {Treebeard} from 'react-treebeard';
import FontAwesome from 'react-fontawesome';
import data from './data';
import * as filters from './filter';
import styles from './styles';
class TreeView extends React.Component {
constructor(props) {
super(props);
this.state = {data};
this.onToggle = this.onToggle.bind(this);
}
onToggle(node, toggled) {
if (this.state.cursor) {
let temp = this.state.cursor;
temp.active = false;
this.setState({cursor:temp})
}
node.active = true;
if (node.children) {
node.toggled = toggled;
}
this.setState({cursor: node});
if(node.example){
this.props.commandSelected(node);
}
}
onFilterMouseUp(e) {
const filter = e.target.value.trim();
if (!filter) {
return this.setState({data});
}
let filtered = filters.filterTree(data, filter);
filtered = filters.expandFilteredNodes(filtered, filter);
this.setState({data: filtered});
}
render() {
return (
<div>
<div style={styles.searchBox}>
<div className="input-group">
<span className="input-group-addon">
<FontAwesome name="search"/>
</span>
<input type="text"
className="form-control"
placeholder="Search..."
onKeyUp={this.onFilterMouseUp.bind(this)}
/>
</div>
</div>
<Treebeard
data={this.state.data}
onToggle={this.onToggle}
/>
</div>
);
}
}
export default TreeView; |
src/components/article/OrderedList.js | garfieldduck/twreporter-react | 'use strict'
import classNames from 'classnames'
import commonStyles from './Common.scss'
import styles from './OrderedList.scss'
import React from 'react' // eslint-disable-next-line
// lodash
import get from 'lodash/get'
export const OrderedList = ({ content }) => {
if(!Array.isArray(content)) {
return null
}
// TODO cList = content directly.
// Right now it's a workaround here
let cList = get(content, 0)
if (!Array.isArray(cList)) {
cList = content
}
let bArr = []
for(let i=0; i<cList.length; i++) {
bArr.push(<li key={i} className={styles.item}>
<span dangerouslySetInnerHTML={{ __html: cList[i] }} />
</li>)
}
return <ol className={classNames(styles.list, commonStyles['inner-block'],
'text-justify')}>
{ bArr }
</ol>
}
|
website/modules/components/WebExample.js | asaf/react-router | import React from 'react'
import PropTypes from 'prop-types'
import Media from 'react-media'
import { Block } from 'jsxstyle'
import { Route } from 'react-router-dom'
import Bundle from './Bundle'
import FakeBrowser from './FakeBrowser'
import SourceViewer from './SourceViewer'
import Loading from './Loading'
const WebExample = ({ example }) => (
<Bundle load={example.load}>
{(Example) => (
<Bundle load={example.loadSource}>
{(src) => Example && src ? (
<Media query="(min-width: 1170px)">
{(largeScreen) => (
<Block
minHeight="100vh"
background="rgb(45, 45, 45)"
padding="40px"
>
<Route render={({ location }) => (
<FakeBrowser
key={location.key /*force new instance*/}
position={largeScreen ? 'fixed' : 'static'}
width={largeScreen ? '400px' : 'auto'}
height={largeScreen ? 'auto' : '70vh'}
left="290px"
top="40px"
bottom="40px"
>
<Example/>
</FakeBrowser>
)}/>
<SourceViewer
code={src}
fontSize="11px"
marginLeft={largeScreen ? '440px' : null}
marginTop={largeScreen ? null : '40px'}
/>
</Block>
)}
</Media>
) : <Loading/>}
</Bundle>
)}
</Bundle>
)
WebExample.propTypes = {
example: PropTypes.object
}
export default WebExample
|
app/components/Keys/Confirm.js | soosgit/vessel | // @flow
import React, { Component } from 'react';
import { Button, Divider, Header, Icon, List, Segment, Table } from 'semantic-ui-react';
export default class KeysConfirm extends Component {
render() {
const confirmAccount = this.props.keys.confirm;
const encryptWallet = this.props.encryptWallet;
const handleConfirmAction = this.props.handleConfirmAction;
return (
<Segment basic padded>
<Header>
Confirm Account Information
<Header.Subheader>
The key entered corresponds to the following account and permissions
to perform the following actions:
</Header.Subheader>
</Header>
<Table unstackable definition>
<Table.Body>
<Table.Row>
<Table.Cell width={6} textAlign="right">
Account Name
</Table.Cell>
<Table.Cell>
{confirmAccount.account}
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell textAlign="right">
Password Encrypted Wallet
</Table.Cell>
<Table.Cell>
<Icon
name={encryptWallet ? 'checkmark' : 'remove'}
color={encryptWallet ? 'green' : 'red'}
size="large"
/>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell textAlign="right">
<List>
<List.Item>
Vote
</List.Item>
<List.Item>
Create Posts
</List.Item>
<List.Item>
Claim Rewards
</List.Item>
</List>
</Table.Cell>
<Table.Cell>
<Icon
name={(confirmAccount.posting || confirmAccount.active || confirmAccount.owner) ? 'checkmark' : 'remove'}
color={(confirmAccount.posting || confirmAccount.active || confirmAccount.owner) ? 'green' : 'red'}
size="large"
/>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell textAlign="right">
<List>
<List.Item>
Transfer Funds
</List.Item>
<List.Item>
Witness Voting
</List.Item>
</List>
</Table.Cell>
<Table.Cell>
<Icon
name={(confirmAccount.active || confirmAccount.owner) ? 'checkmark' : 'remove'}
color={(confirmAccount.active || confirmAccount.owner) ? 'green' : 'red'}
size="large"
/>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell textAlign="right">
<List>
<List.Item>
Change Account Keys
</List.Item>
<List.Item>
Transfer Ownership
</List.Item>
</List>
</Table.Cell>
<Table.Cell>
<Icon
name={confirmAccount.owner ? 'checkmark' : 'remove'}
color={confirmAccount.owner ? 'green' : 'red'}
size="large"
/>
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
<Divider hidden />
<p>
Please confirm you would like to save this account
with these permissions to this wallet.
</p>
<Segment basic>
<Button
content="Cancel"
color="red"
onClick={handleConfirmAction}
value={false}
/>
<Button
floated="right"
content="Confirm Save"
color="green"
onClick={handleConfirmAction}
value
/>
</Segment>
</Segment>
);
}
}
|
src/components/Editor/Editor.js | cuijiaxu/react-front | import React from 'react'
import { Editor } from 'react-draft-wysiwyg'
import styles from './Editor.less'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
const DraftEditor = (props) => {
return (<Editor toolbarClassName={styles.toolbar} wrapperClassName={styles.wrapper} editorClassName={styles.editor} {...props} />)
}
export default DraftEditor
|
src/components/SetLocale.js | openbasement/openbasement | import { connect } from 'react-redux';
import React from 'react';
import { I18n } from 'react-redux-i18n';
import mapDispatchToProps from '../actions';
import { mapStateToProps } from '../model/state';
@connect(mapStateToProps, mapDispatchToProps)
export default class SetLocaleComponent extends React.Component {
static propTypes = {
actions: React.PropTypes.shape({
setLocale: React.PropTypes.func.isRequired
}),
i18n: React.PropTypes.shape({
locale: React.PropTypes.string.isRequired
})
}
render() {
const { setLocale } = this.props.actions;
const setLocaleTo = (locale) => () => setLocale(locale);
return (
<p>
<b><a onClick={setLocaleTo('en')}>{I18n.t('settings.locale.en')}</a></b>
<b><a onClick={setLocaleTo('pl')}>{I18n.t('settings.locale.pl')}</a></b>
</p>
);
}
}
|
app/containers/PrivateEvents.js | albertmejia/empire_room | import React from 'react';
import privateevents from '../styles/privateevents.scss';
class PrivateEvents extends React.Component {
componentDidMount() {
window.scrollTo(0, 0);
}
render() {
return (
<div className={privateevents.wrapper}>
<div className={privateevents.title}>
<h1>Private Events</h1>
<svg className="filigree" width="75" viewBox="0 0 240.24 76.3"><path className="filigree_path" d="M414.11,443c2.84,0,5.68,1.44,6,4.53,2.7,14.33-8.61,30.65-23.67,31.2-12,.83-22.94-5.32-32.88-11.26C353.43,461.58,345,452.73,333.67,449c-7.24-2.51-16.48-.86-21.31,5.4-4.25,7,7.17,17.22,12.75,10.1.26.34.76,1,1,1.36v3.33c-2.8,3.24-7.25,5.72-11.59,4.36-8.7-2.76-11.52-14.78-6.73-22,4.44-6.13,13-7.59,20-6.1,13.93,2.44,25,12.68,38.92,15.08,5.7,2,11.7-5.11,16.72,0-1.66,4.56-6.65,6.29-11.05,6.88,2.94.79,6.39,2,9.24.25,6-3.54,6.69-11.7,12.38-15.44,5.9-3,10,4.27,15.4,5.45,7.16-1.16,8.09-9.46,4.7-14.72m17.17,4.21c.51-3,3.31-4.37,6.13-4-3,4.12-3.58,11.41,2,13.53,6.65,3.28,10.83-8,17.49-4.61,5.76,3.39,6.58,11.12,11.76,15.13,3,2.28,7,1.2,10.21.22a16.06,16.06,0,0,1-10.46-5.17l.36-2.88c5.36-2.73,10.31,3.17,15.8,1.24,13.32-2.31,24-11.61,37-14.71a23.89,23.89,0,0,1,17.66,1.7c10.08,5.48,8,23.65-3.34,26.27-5.33,1-13.49-3.65-10-9.82q1.53,1.5,3,3c5.55.57,10.53-4,11.11-9.38-1.32-7.33-10.12-10-16.6-9.79-12.1,1.13-21.26,10-30.9,16.48-11,7-22.88,14.47-36.4,14.42-15.66.07-28-16.72-24.85-31.65m-5.7,24.89C430,483.9,442.8,491.19,455.21,488c-4.47,6.25-12.83,9.76-20.06,6,1.24,3.48,1.69,7.9-1.44,10.55-4.27,3.91-6.42,9.29-8.08,14.7-1.73-4.88-3.17-10.11-7.25-13.64A9.33,9.33,0,0,1,416.25,494c-7.12,3.65-15.81.53-20-6a24.86,24.86,0,0,0,29.38-15.91Z" transform="translate(-305.47 -442.95)"/></svg>
</div>
<div className={privateevents.copy}>
<h2>Corporate & Private Room Rentals</h2>
<br/>
<p>The Empire Room is the perfect venue for all your event needs. The beautiful space can be used for a wide range of events big or small. We have excellent packages for Corporate Events, Dinner Banquets, Wedding Receptions, Happy Hour, Birthday Parties, Anniversary Parties, Fundraisers, Concerts or Art Exhibit. Please feel free to email us at <a href="mailto:info@theempireroomsf.com">info@theempireroomsf.com.</a></p>
<br/>
<small><strong>Private Events / Weddings / Product Launches / Formal Affairs / Holiday Parties</strong></small>
</div>
<div className="sevenrooms-form">
<iframe src="https://www.sevenrooms.com/direct/reservation-request/theempireroom/table" height="600" width="505" frameBorder="0"></iframe>
</div>
</div>
);
}
}
export default PrivateEvents;
|
src/components/posts/list.js | plastical/react-theme | // External dependencies
import React from 'react';
// Internal dependencies
import Post from './single';
import Placeholder from '../placeholder';
const PostList = (props) => {
if (!props.posts) {
return null;
}
const posts = props.posts.map((post, i) =>
<Post key={`post-${i}`} {...post} {...props} />
);
return (
<div className="entry_list">
{posts.length > 0 || props.noPreload ?
posts :
<Placeholder />
}
</div>
);
}
export default PostList;
|
src/svg-icons/action/card-giftcard.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionCardGiftcard = (props) => (
<SvgIcon {...props}>
<path d="M20 6h-2.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm11 15H4v-2h16v2zm0-5H4V8h5.08L7 10.83 8.62 12 11 8.76l1-1.36 1 1.36L15.38 12 17 10.83 14.92 8H20v6z"/>
</SvgIcon>
);
ActionCardGiftcard = pure(ActionCardGiftcard);
ActionCardGiftcard.displayName = 'ActionCardGiftcard';
export default ActionCardGiftcard;
|
src/components/forms/FormGroup.js | rokka-io/rokka-dashboard | import PropTypes from 'prop-types'
import React from 'react'
import cx from 'classnames'
import RequiredIndicator from './RequiredIndicator'
const FormGroup = ({
label,
children,
className = null,
required = false,
htmlFor = null,
error = null
}) => (
<div className={cx('rka-form-group', className, { 'has-error': !!error })}>
<label htmlFor={htmlFor} className="rka-label txt-cap">
{label}
<RequiredIndicator required={required} />
</label>
{children}
{error ? <div className="mt-xs txt-xs txt-cranberry">{error}</div> : null}
</div>
)
FormGroup.propTypes = {
label: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
className: PropTypes.string,
required: PropTypes.bool,
error: PropTypes.string
}
export default FormGroup
|
svg/delete-button.js | michael-lowe-nz/NBA-battles | import React from 'react'
module.exports = (dispatch) => (
<svg className="clickable" id="remove" version="1.1" id="Layer_1" x="0px" y="0px"
width="50px" height="50px" viewBox="0 0 100 100" enableBackground="new 0 0 100 100" xmlSpace="preserve">
<circle fill="#FFFFFF" className="delete" stroke="#000000" strokeWidth="1" strokeMiterlimit="10" cx="50" cy="50" r="47.5"/>
<line fill="none" stroke="#000000" className="delete" strokeWidth="1" strokeMiterlimit="10" x1="16.412" y1="83.588" x2="83.587" y2="16.413"/>
<line fill="none" stroke="#000000" className="delete" strokeWidth="1" strokeMiterlimit="10" x1="16.412" y1="16.412" x2="83.587" y2="83.588"/>
</svg>
)
|
client/modules/comments/components/.stories/create_comment.js | mantrajs/mantra-sample-blog-app | import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import CreateComment from '../create_comment';
storiesOf('comments.CreateComment', module)
.add('default view', () => {
return (
<div className='comments'>
<CreateComment postId='the-id' create={action('create comment')}/>
</div>
);
})
.add('with error', () => {
return (
<div className='comments'>
<CreateComment
error='This is the error message'
postId='the-id'
create={action('create comment')}
/>
</div>
);
});
|
src/svg-icons/device/signal-cellular-connected-no-internet-2-bar.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularConnectedNoInternet2Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M14 22V10L2 22h12zm6-12v8h2v-8h-2zm0 12h2v-2h-2v2z"/>
</SvgIcon>
);
DeviceSignalCellularConnectedNoInternet2Bar = pure(DeviceSignalCellularConnectedNoInternet2Bar);
DeviceSignalCellularConnectedNoInternet2Bar.displayName = 'DeviceSignalCellularConnectedNoInternet2Bar';
DeviceSignalCellularConnectedNoInternet2Bar.muiName = 'SvgIcon';
export default DeviceSignalCellularConnectedNoInternet2Bar;
|
packages/mineral-ui-icons/src/IconCheckBoxIndeterminate.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconCheckBoxIndeterminate(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M4 10h16v4H4z"/>
</g>
</Icon>
);
}
IconCheckBoxIndeterminate.displayName = 'IconCheckBoxIndeterminate';
IconCheckBoxIndeterminate.category = 'toggle';
|
Package Storage/lsp_utils/node-runtime/12.20.2/node/lib/node_modules/npm/docs/src/components/home/Terminal.js | dmilith/SublimeText3-dmilith | import React from 'react'
import styled, {keyframes} from 'styled-components'
import {Flex, Box, Button as RebassButton} from 'rebass'
import closeX from '../../images/x.svg'
import {LinkButton} from '../Button'
import bracket from '../../images/bracket.svg'
const TerminalBody = styled(Flex)`
background-color: ${(props) => props.theme.colors.purpleBlack};
border: 2px solid ${(props) => props.theme.colors.purpleBlack};
color: ${(props) => props.theme.colors.white};
flex-direction: column;
max-width: 620px;
width: 100%;
height: 100%;
box-shadow: 0px 0px 17px 1px #dc3bc180;
border-radius: 2px;
top: ${(props) => props.top};
left: ${(props) => props.left};
right: 0;
position: absolute;
`
const Top = styled(Flex)`
background-color: ${(props) => props.theme.colors.white};
height: 18px;
`
const SiteName = styled(Flex)`
font-size: 45px;
font-family: 'Inconsolata', sans-serif;
font-weight: 700;
letter-spacing: 5px;
text-shadow: 3px 2px 4px #abf1e04d;
@media screen and (min-width: ${(props) => props.theme.breakpoints.TABLET}) {
font-size: 70px;
}
`
const Bottom = styled(Flex)`
flex-direction: column;
padding: 30px;
@media screen and (min-width: ${(props) => props.theme.breakpoints.TABLET}) {
font-size: 70px;
padding: 30px 50px;
}
`
const blink = keyframes`
0% {
opacity: 0;
}
50% {
opacity 1;
}
100% {
opacity: 0;
}
`
const Cursor = styled.span`
color: ${(props) => props.theme.colors.red};
text-shadow: none;
opacity: 1;
animation: ${blink};
animation-duration: 3s;
animation-iteration-count: infinite;
animation-fill-mode: both;
`
const Bracket = styled.span`
background: center / contain no-repeat url(${bracket});
width: 25px;
margin-right: 5px;
margin-top: 10px;
`
const Text = styled.span`
font-size: 15px;
font-weight: 400;
letter-spacing: 1px;
line-height: 1.4;
@media screen and (min-width: ${(props) => props.theme.breakpoints.TABLET}) {
font-size: 18px;
}
`
const ModalButton = styled(RebassButton)`
cursor: pointer;
background: center no-repeat url(${closeX});
width: 14px;
height: 14px;
`
const Terminal = ({onClose, top, left}) => {
return (
<TerminalBody m={'auto'} top={top} left={left}>
<Top alignItems='center'>
<ModalButton onClick={onClose} ml={1} p={1} />
</Top>
<Bottom>
<SiteName py={3}><Bracket />npm cli <Cursor>_</Cursor></SiteName>
<Text>
The intelligent package manager for the Node Javascript Platform. Install stuff and get coding!
</Text>
<Box mx={'auto'} my={4}>
<LinkButton to='/cli-commands/npm'>
read docs
</LinkButton>
</Box>
</Bottom>
</TerminalBody>
)
}
export default Terminal
|
docs/src/app/components/pages/components/Slider/ExampleSimple.js | IsenrichO/mui-with-arrows | import React from 'react';
import Slider from 'material-ui/Slider';
/**
* The `defaultValue` property sets the initial position of the slider.
* The slider appearance changes when not at the starting position.
*/
const SliderExampleSimple = () => (
<div>
<Slider />
<Slider defaultValue={0.5} />
<Slider defaultValue={1} />
</div>
);
export default SliderExampleSimple;
|
shared/components/DemoApp/index.js | oyeanuj/react-universally | import 'normalize.css/normalize.css';
import React from 'react';
import Switch from 'react-router-dom/Switch';
import Route from 'react-router-dom/Route';
import Helmet from 'react-helmet';
import config from '../../../config';
import './globals.css';
import Error404 from './Error404';
import Header from './Header';
import AsyncHomeRoute from './AsyncHomeRoute';
import AsyncCounterRoute from './AsyncCounterRoute';
import AsyncAboutRoute from './AsyncAboutRoute';
function DemoApp() {
return (
<div style={{ padding: '2rem' }}>
<Helmet>
<html lang="en" />
<meta charSet="utf-8" />
<meta name="application-name" content={config('htmlPage.defaultTitle')} />
<meta name="description" content={config('htmlPage.description')} />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="msapplication-TileColor" content="#2b2b2b" />
<meta name="msapplication-TileImage" content="/favicons/mstile-144x144.png" />
<meta name="theme-color" content="#2b2b2b" />
<title>
{config('htmlPage.defaultTitle')}
</title>
{/*
A great reference for favicons:
https://github.com/audreyr/favicon-cheat-sheet
It's a pain to manage/generate them. I run both these in order,
and combine their results:
http://realfavicongenerator.net/
http://www.favicomatic.com/
*/}
<link
rel="apple-touch-icon-precomposed"
sizes="152x152"
href="/favicons/apple-touch-icon-152x152.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="144x144"
href="/favicons/apple-touch-icon-144x144.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="120x120"
href="/favicons/apple-touch-icon-120x120.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="114x114"
href="/favicons/apple-touch-icon-114x114.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="76x76"
href="/favicons/apple-touch-icon-76x76.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="72x72"
href="/favicons/apple-touch-icon-72x72.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="57x57"
href="/favicons/apple-touch-icon-57x57.png"
/>
<link
rel="apple-touch-icon-precomposed"
sizes="60x60"
href="/favicons/apple-touch-icon-60x60.png"
/>
<link
rel="apple-touch-icon"
sizes="180x180"
href="/favicons/apple-touch-icon-180x180.png"
/>
<link rel="mask-icon" href="/favicons/safari-pinned-tab.svg" color="#00a9d9" />
<link rel="icon" type="image/png" href="/favicons/favicon-196x196.png" sizes="196x196" />
<link rel="icon" type="image/png" href="/favicons/favicon-128.png" sizes="128x128" />
<link rel="icon" type="image/png" href="/favicons/favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/png" href="/favicons/favicon-32x32.png" sizes="32x32" />
<link rel="icon" sizes="16x16 32x32" href="/favicon.ico" />
<meta name="msapplication-TileColor" content="#2b2b2b" />
<meta name="msapplication-TileImage" content="/favicons/mstile-144x144.png" />
<meta name="msapplication-square70x70logo" content="/favicons/mstile-70x70.png" />
<meta name="msapplication-square150x150logo" content="/favicons/mstile-150x150.png" />
<meta name="msapplication-wide310x150logo" content="/favicons/mstile-310x150.png" />
<meta name="msapplication-square310x310logo" content="/favicons/mstile-310x310.png" />
<link rel="manifest" href="/manifest.json" />
{/*
NOTE: This is simply for quick and easy styling on the demo. Remove
this and the related items from the Content Security Policy in the
global config if you have no intention of using milligram.
*/}
<link
rel="stylesheet"
href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic"
/>
<link
rel="stylesheet"
href="//cdn.rawgit.com/milligram/milligram/master/dist/milligram.min.css"
/>
</Helmet>
<Header />
<div style={{ paddingTop: '2rem', paddingBottom: '2rem' }}>
<Switch>
<Route exact path="/" component={AsyncHomeRoute} />
<Route path="/counter" component={AsyncCounterRoute} />
<Route path="/about" component={AsyncAboutRoute} />
<Route component={Error404} />
</Switch>
</div>
</div>
);
}
export default DemoApp;
|
client/index.js | zosman1/PatriotChat | import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
AsyncStorage,
ScrollView,
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import Button from 'react-native-button';
import SocketIOClient from 'socket.io-client';
// Import other pages:
import Chat from './chat'
import SignIn from './signIn'
const SERVER_IP = `10.0.0.6`;
export default class Main extends React.Component {
constructor(props){
super(props);
this.state = {
user: null,
chats: null
}
this.socket = SocketIOClient(`http://${SERVER_IP}:3030`);
}
static navigationOptions = {
title: 'Groups',
};
// before first dom render check if user is set; if not: navigate to login page
componentWillMount() {
// AsyncStorage.clear();
AsyncStorage.getItem('user').then((user) => {
if (user == null) {
this.props.navigation.navigate('SignIn');
}
else {
this.setState({user: JSON.parse(user)});
// console.warn(this.state.user);
}
});
AsyncStorage.getItem('chats').then((chats) => {
this.setState({chats: JSON.parse(chats)});
});
//fetch chats from server
this.socket.emit('fetch-chats');
this.socket.on('fetch-chats', (chats) => {
AsyncStorage.setItem('chats', JSON.stringify(chats));
this.setState({chats: chats});
})
}
render() {
const { navigate } = this.props.navigation;
return (
<ScrollView style={styles.container}>
{
(this.state.user != null) > 0 &&
Object.keys(this.state.chats).map((key, index) => {
let chat = this.state.chats[key];
return (
<Button
onPress={() => {
navigate('Chat', {user:this.state.user, chat: chat, socket: this.socket})
}}
style={{color: 'white'}}
containerStyle={{margin: 1, padding:10, height:70, overflow:'hidden', backgroundColor: '#006633'}}
>
<Text style={styles.chatTag}> {chat.name} ❯ </Text>
</Button>
);
})
}
</ScrollView>
);
}
}
const App = StackNavigator({
Home: { screen: Main },
Chat: { screen: Chat },
SignIn: { screen: SignIn }
})
const styles = StyleSheet.create({
container: {
flex: 1,
// justifyContent: 'center',
// alignItems: 'center',
// backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: '#006633'
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
chat: {
backgroundColor: '#006633',
// margin: 10,
height: 70,
margin: 0.5,
// justifyContent: 'flex-end',
},
chatTag: {
color: 'white',
}
});
AppRegistry.registerComponent('PatriotChat', () => App);
|
js/components/Header/index.ios.js | ChiragHindocha/stay_fit |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Header, Title, Content, Button, Icon, Left, Right, Body, Text, ListItem, List } from 'native-base';
import { Actions } from 'react-native-router-flux';
import { actions } from 'react-native-navigation-redux-helpers';
import { openDrawer, closeDrawer } from '../../actions/drawer';
import styles from './styles';
const {
pushRoute,
} = actions;
const datas = [
{
route: 'header1',
text: 'Only Title',
},
{
route: 'header2',
text: 'Icon Buttons',
},
{
route: 'header3',
text: 'Text Buttons',
},
{
route: 'header4',
text: 'Icon Button and Text Button',
},
{
route: 'header5',
text: 'Icon and Text Buttons',
},
{
route: 'header6',
text: 'Multiple Icon Buttons',
},
{
route: 'header7',
text: 'Title and Subtitle',
},
{
route: 'header8',
text: 'Custom backgroundColor',
},
];
class HeaderNB extends Component { // eslint-disable-line
static propTypes = {
openDrawer: React.PropTypes.func,
pushRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
pushRoute(route) {
this.props.pushRoute({ key: route, index: 1 }, this.props.navigation.key);
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={this.props.openDrawer}>
<Icon name="menu" />
</Button>
</Left>
<Body>
<Title>Headers</Title>
</Body>
<Right />
</Header>
<Content>
<List
dataArray={datas} renderRow={data =>
<ListItem
button
onPress={() => { Actions[data.route](); this.props.closeDrawer(); }}
>
<Text>{data.text}</Text>
<Right>
<Icon name="arrow-forward" />
</Right>
</ListItem>
}
/>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
closeDrawer: () => dispatch(closeDrawer()),
pushRoute: (route, key) => dispatch(pushRoute(route, key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(HeaderNB);
|
src/components/app.js | ric9176/hoc | import React, { Component } from 'react';
import Header from './Header'
export default class App extends Component {
render() {
return (
<div>
<Header />
{this.props.children}
</div>
);
}
}
|
console-ui/src/pages/ConfigurationManagement/ConfigEditor/ConfigEditor.js | alibaba/nacos | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import $ from 'jquery';
import React from 'react';
import PropTypes from 'prop-types';
import { getParams, request } from '../../../globalLib';
import DiffEditorDialog from '../../../components/DiffEditorDialog';
import SuccessDialog from '../../../components/SuccessDialog';
import validateContent from 'utils/validateContent';
import {
Balloon,
Button,
Dialog,
Field,
Form,
Icon,
Input,
Loading,
Radio,
Select,
Tab,
Message,
ConfigProvider,
} from '@alifd/next';
import './index.scss';
const TabPane = Tab.Item;
const FormItem = Form.Item;
const { Group: RadioGroup } = Radio;
@ConfigProvider.config
class ConfigEditor extends React.Component {
static displayName = 'ConfigEditor';
static propTypes = {
locale: PropTypes.object,
history: PropTypes.object,
};
constructor(props) {
super(props);
this.diffEditorDialog = React.createRef();
this.successDialog = React.createRef();
this.edasAppName = getParams('edasAppName') || '';
this.edasAppId = getParams('edasAppId') || '';
this.inApp = this.edasAppName;
this.field = new Field(this);
this.dataId = getParams('dataId') || 'yanlin';
this.group = getParams('group') || 'DEFAULT_GROUP';
this.tenant = getParams('namespace') || '';
this.state = {
configType: 'text',
codeValue: '',
envname: 'center',
targetEnvName: '',
envlist: [],
envvalues: [],
loading: false,
showmore: false,
activeKey: 'normal',
hasbeta: false,
ips: '',
checkedBeta: false,
tagLst: [],
config_tags: [],
switchEncrypt: false,
tag: [],
};
this.codeValue = '';
this.mode = 'text';
this.ips = '';
this.valueMap = {}; // 存储不同版本的数据
this.searchDataId = getParams('searchDataId') || '';
this.searchGroup = getParams('searchGroup') || '';
}
componentDidMount() {
this.initData();
this.betaips = document.getElementById('betaips');
this.getDataDetail();
this.chontenttab = document.getElementById('chontenttab'); // diff标签
}
initData() {
const { locale = {} } = this.props;
this.setState({
tag: [
{
title: locale.official,
key: 'normal',
},
],
});
if (this.dataId.startsWith('cipher-')) {
this.setState({ switchEncrypt: true });
}
}
initMoacoEditor(language, value) {
if (!window.monaco) {
window.importEditor(() => {
this.monacoEditor = window.monaco.editor.create(document.getElementById('container'), {
value,
language: this.state.configType,
codeLens: true,
selectOnLineNumbers: true,
roundedSelection: false,
readOnly: false,
lineNumbersMinChars: true,
theme: 'vs-dark',
wordWrapColumn: 120,
folding: false,
showFoldingControls: 'always',
wordWrap: 'wordWrapColumn',
cursorStyle: 'line',
automaticLayout: true,
});
});
} else {
this.monacoEditor = window.monaco.editor.create(document.getElementById('container'), {
value,
language: this.state.configType,
codeLens: true,
selectOnLineNumbers: true,
roundedSelection: false,
readOnly: false,
lineNumbersMinChars: true,
theme: 'vs-dark',
wordWrapColumn: 120,
folding: false,
showFoldingControls: 'always',
wordWrap: 'wordWrapColumn',
cursorStyle: 'line',
automaticLayout: true,
});
}
}
toggleMore() {
this.setState({
showmore: !this.state.showmore,
});
}
navTo(url) {
this.serverId = getParams('serverId') || '';
this.tenant = getParams('namespace') || ''; // 为当前实例保存tenant参数
this.props.history.push(
`${url}?serverId=${this.serverId || ''}&dataId=${this.dataId}&group=${this.group}&namespace=${
this.tenant
}`
);
}
openLoading() {
this.setState({
loading: true,
});
}
closeLoading() {
this.setState({
loading: false,
});
}
getDataDetail() {
const { locale = {} } = this.props;
const self = this;
this.tenant = getParams('namespace') || '';
this.serverId = getParams('serverId') || 'center';
const url = `v1/cs/configs?show=all&dataId=${this.dataId}&group=${this.group}`;
request({
url,
beforeSend() {
self.openLoading();
},
success(result) {
if (result != null) {
const data = result;
self.valueMap.normal = data;
self.field.setValue('dataId', data.dataId);
// self.field.setValue('content', data.content);
self.field.setValue('appName', self.inApp ? self.edasAppName : data.appName);
// self.field.setValue('envs', self.serverId);
self.field.setValue('group', data.group);
// self.field.setValue('type', data.type);
self.field.setValue('desc', data.desc);
// self.field.setValue('md5', data.md5);
self.codeValue = data.content || '';
const type = data.type || 'text';
self.setState({
// 设置radio 高亮
configType: type,
});
self.initMoacoEditor(type, self.codeValue);
// self.createCodeMirror('text', self.codeValue);
// self.codeValue = self.commoneditor.doc.getValue();
if (data.configTags != null) {
const tagArr = data.configTags.split(',');
self.setConfigTags(tagArr);
}
const envvalues = [];
const env = {};
self.serverId = env.serverId;
self.targetEnvs = envvalues;
} else {
Dialog.alert({ title: locale.wrong, content: result.message });
}
},
complete() {
self.closeLoading();
},
});
}
goList() {
const tenant = getParams('namespace');
this.props.history.push(
`/configurationManagement?serverId=${this.serverId}&group=${this.searchGroup}&dataId=${this.searchDataId}&namespace=${tenant}`
);
}
createCodeMirror(mode, value) {
const commontarget = this.refs.commoneditor;
commontarget.innerHTML = '';
this.commoneditor = window.CodeMirror(commontarget, {
value,
mode,
lineNumbers: true,
theme: 'xq-light',
lint: true,
gutters: ['CodeMirror-lint-markers'],
extraKeys: {
F1(cm) {
cm.setOption('fullScreen', !cm.getOption('fullScreen'));
},
Esc(cm) {
if (cm.getOption('fullScreen')) cm.setOption('fullScreen', false);
},
},
});
this.commoneditor.on('change', this.codemirrorValueChanged.bind(this));
}
codemirrorValueChanged(doc) {
if (this.diffeditor) {
this.diffeditor.edit.doc.setValue(doc.getValue());
}
}
createDiffCodeMirror(leftCode, rightCode) {
const target = this.diffEditorDialog.current.getInstance();
target.innerHTML = '';
this.diffeditor = window.CodeMirror.MergeView(target, {
value: leftCode || '',
origLeft: null,
orig: rightCode || '',
lineNumbers: true,
mode: this.mode,
theme: 'xq-light',
highlightDifferences: true,
connect: 'align',
collapseIdentical: false,
});
}
changeConfig(value) {
if (value === 0) {
this.createCodeMirror('text', this.codeValue);
this.mode = 'text';
}
if (value === 1) {
this.createCodeMirror('application/json', this.codeValue);
this.mode = 'application/json';
}
if (value === 2) {
this.createCodeMirror('xml', this.codeValue);
this.mode = 'xml';
}
this.setState({
configType: value,
});
}
setCodeValue(value) {
this.setState({
codeValue: value,
});
}
toggleDiff(checked) {
if (checked) {
this.chontenttab.style.display = 'block';
const nowvalue = this.commoneditor.doc.getValue();
if (!this.diffeditor) {
this.createDiffCodeMirror(nowvalue, this.codeValue);
}
} else {
this.chontenttab.style.display = 'none';
// this.diffeditor = null;
// let target = this.refs["diffeditor"];
// target.innerHTML = '';
}
}
publishConfig() {
const { locale = {} } = this.props;
this.field.validate((errors, values) => {
if (errors) {
return;
}
let content = '';
let { configType } = this.state;
if (this.monacoEditor) {
content = this.monacoEditor.getValue();
} else {
content = this.codeValue;
}
if (!content) {
Message.error({
content: locale.submitFailed,
align: 'cc cc',
});
return;
}
if (validateContent.validate({ content, type: configType })) {
this._publishConfig(content);
} else {
Dialog.confirm({
content: '配置信息可能有语法错误, 确定提交吗?',
onOk: () => {
this._publishConfig(content);
},
});
}
});
}
_publishConfig = content => {
const { locale = {} } = this.props;
const self = this;
this.codeValue = content;
this.tenant = getParams('namespace') || '';
this.serverId = getParams('serverId') || 'center';
const payload = {
dataId: this.field.getValue('dataId'),
appName: this.inApp ? this.edasAppId : this.field.getValue('appName'),
group: this.field.getValue('group'),
desc: this.field.getValue('desc'),
config_tags: this.state.config_tags.join(','),
type: this.state.configType,
content,
tenant: this.tenant,
};
const url = 'v1/cs/configs';
request({
type: 'post',
contentType: 'application/x-www-form-urlencoded',
url,
data: payload,
success(res) {
const _payload = {};
_payload.maintitle = locale.toedittitle;
_payload.title = <div>{locale.toedit}</div>;
_payload.content = '';
_payload.dataId = payload.dataId;
_payload.group = payload.group;
if (res != null) {
_payload.isok = true;
const activeKey = self.state.activeKey.split('-')[0];
if (activeKey === 'normal' && self.hasips === true) {
// 如果是在normal面板选择了beta发布
const sufex = new Date().getTime();
self.setState({
tag: [
{ title: locale.official, key: `normal-${sufex}` },
{ title: 'BETA', key: `beta-${sufex}` },
],
hasbeta: true,
activeKey: `beta-${sufex}`,
});
payload.betaIps = payload.betaIps || payload.ips;
self.valueMap.beta = payload; // 赋值beta
self.changeTab(`beta-${sufex}`);
}
if (activeKey === 'normal' && self.hasips === false) {
// 如果是在normal面板选择了发布
self.valueMap.normal = payload; // 赋值正式
}
if (activeKey === 'beta' && self.hasips === true) {
// 如果是在beta面板继续beta发布
self.valueMap.beta = payload; // 赋值beta
}
} else {
_payload.isok = false;
_payload.message = res.message;
}
self.successDialog.current.getInstance().openDialog(_payload);
},
error() {},
});
};
validateChart(rule, value, callback) {
const { locale = {} } = this.props;
const chartReg = /[@#\$%\^&\*]+/g;
if (chartReg.test(value)) {
callback(locale.vdchart);
} else {
callback();
}
}
changeEnv(values) {
this.targetEnvs = values;
this.setState({
envvalues: values,
});
}
changeBeta(selected) {
if (selected) {
this.betaips.style.display = 'block';
} else {
this.betaips.style.display = 'none';
}
this.setState({
checkedBeta: selected,
});
}
getIps(value) {
this.ips = value;
this.setState({
ips: value,
});
}
setConfigTags(value) {
if (value.length > 5) {
value.pop();
}
value.forEach((v, i) => {
if (v.indexOf(',') !== -1 || v.indexOf('=') !== -1) {
value.splice(i, 1);
}
});
this.setState({
config_tags: value,
});
}
onInputUpdate(value) {
if (this.inputtimmer) {
clearTimeout(this.inputtimmer);
}
this.inputtimmer = setTimeout(() => {
const { tagLst } = this.state;
let hastag = false;
tagLst.forEach((v, i) => {
if (v.value === value) {
hastag = true;
}
});
if (!hastag) {
tagLst.push({
value,
label: value,
time: Math.random(),
});
}
this.setState({ tagLst });
}, 500);
}
openDiff(hasips) {
this.hasips = hasips; // 是否包含ips
let leftvalue = this.monacoEditor.getValue(); // this.commoneditor.doc.getValue();
let rightvalue = this.codeValue;
leftvalue = leftvalue.replace(/\r\n/g, '\n').replace(/\n/g, '\r\n');
rightvalue = rightvalue.replace(/\r\n/g, '\n').replace(/\n/g, '\r\n');
// let rightvalue = this.diffeditor.doc.getValue();
// console.log(this.commoneditor, leftvalue==rightvalue)
this.diffEditorDialog.current.getInstance().openDialog(leftvalue, rightvalue);
}
changeTab(value) {
const self = this;
const key = value.split('-')[0];
const data = this.valueMap[key];
this.setState({
activeKey: value,
});
self.field.setValue('dataId', data.dataId);
self.field.setValue('appName', self.inApp ? self.edasAppName : data.appName);
// self.field.setValue('envs', self.serverId);
self.field.setValue('group', data.group);
// self.field.setValue('md5', data.md5);
self.codeValue = data.content || '';
self.createCodeMirror('text', self.codeValue);
if (data.betaIps) {
self.getIps(data.betaIps);
self.changeBeta(true);
} else {
self.getIps('');
self.changeBeta(false);
}
}
newChangeConfig(value) {
this.setState({
configType: value,
});
this.changeModel(value);
}
changeModel(type, value) {
if (!this.monacoEditor) {
$('#container').empty();
this.initMoacoEditor(type, value);
return;
}
const oldModel = this.monacoEditor.getModel();
const oldValue = this.monacoEditor.getValue();
const newModel = window.monaco.editor.createModel(oldValue, type);
this.monacoEditor.setModel(newModel);
if (oldModel) {
oldModel.dispose();
}
}
render() {
const { locale = {} } = this.props;
const { init } = this.field;
const formItemLayout = {
labelCol: { span: 2 },
wrapperCol: { span: 22 },
};
// const list = [{
// value: 0,
// label: 'TEXT'
// }, {
// value: 1,
// label: 'JSON'
// }, {
// value: 2,
// label: 'XML'
// }];
const list = [
{ value: 'text', label: 'TEXT' },
{ value: 'json', label: 'JSON' },
{ value: 'xml', label: 'XML' },
{ value: 'yaml', label: 'YAML' },
{ value: 'html', label: 'HTML' },
{ value: 'properties', label: 'Properties' },
];
const activeKey = this.state.activeKey.split('-')[0];
return (
<div style={{ padding: 10 }}>
<Loading
shape="flower"
style={{ position: 'relative', width: '100%' }}
visible={this.state.loading}
tip="Loading..."
color="#333"
>
<h1 style={{ overflow: 'hidden', height: 50, width: '100%' }}>
<div>{locale.toedit}</div>
</h1>
{this.state.hasbeta ? (
<div style={{ display: 'inline-block', height: 40, width: '80%', overflow: 'hidden' }}>
<Tab
shape={'wrapped'}
onChange={this.changeTab.bind(this)}
lazyLoad={false}
activeKey={this.state.activeKey}
>
{this.state.tag.map(tab => (
<TabPane title={tab.title} key={tab.key} />
))}
</Tab>
</div>
) : (
''
)}
<Form field={this.field}>
<FormItem label="Data ID:" {...formItemLayout}>
<Input
disabled
{...init('dataId', {
rules: [
{ required: true, message: locale.recipientFrom },
{ validator: this.validateChart.bind(this) },
],
})}
/>
</FormItem>
<FormItem label="Group:" {...formItemLayout}>
<Input
disabled
{...init('group', {
rules: [
{ required: true, message: locale.homeApplication },
{ validator: this.validateChart.bind(this) },
],
})}
/>
</FormItem>
<FormItem label="" {...formItemLayout}>
<div>
<a style={{ fontSize: '12px' }} onClick={this.toggleMore.bind(this)}>
{this.state.showmore ? locale.collapse : locale.groupNotEmpty}
</a>
</div>
</FormItem>
<div style={{ height: this.state.showmore ? 'auto' : '0', overflow: 'hidden' }}>
<FormItem label={locale.tags} {...formItemLayout}>
<Select
size="medium"
hasArrow
style={{ width: '100%' }}
autoWidth
mode="tag"
filterLocal
placeholder={locale.pleaseEnterTag}
dataSource={this.state.tagLst}
value={this.state.config_tags}
onChange={this.setConfigTags.bind(this)}
hasClear
/>
</FormItem>
<FormItem label={locale.targetEnvironment} {...formItemLayout}>
<Input {...init('appName')} readOnly={!!this.inApp} />
</FormItem>
</div>
<FormItem label={locale.description} {...formItemLayout}>
<Input.TextArea htmlType="text" multiple rows={3} {...init('desc')} />
</FormItem>
<FormItem label={locale.format} {...formItemLayout}>
<RadioGroup
dataSource={list}
value={this.state.configType}
onChange={this.newChangeConfig.bind(this)}
/>
</FormItem>
<FormItem
label={
<span style={{ marginRight: 5 }}>
{locale.configcontent}
<Balloon
trigger={
<Icon
type="help"
size={'small'}
style={{
color: '#1DC11D',
marginRight: 5,
verticalAlign: 'middle',
marginTop: 2,
}}
/>
}
align="t"
style={{ marginRight: 5 }}
triggerType="hover"
>
<p>{locale.escExit}</p>
<p>{locale.releaseBeta}</p>
</Balloon>
:
</span>
}
{...formItemLayout}
>
<div style={{ clear: 'both', height: 300 }} id="container" />
</FormItem>
<FormItem {...formItemLayout} label="">
<div style={{ textAlign: 'right' }}>
{activeKey === 'beta' ? (
<Button
style={{ marginRight: 10 }}
type="primary"
onClick={this.openDiff.bind(this, true)}
>
{locale.release}
</Button>
) : (
''
)}
{activeKey === 'normal' ? (
<Button
type="primary"
disabled={this.state.hasbeta}
style={{ marginRight: 10 }}
onClick={this.openDiff.bind(this, this.state.checkedBeta)}
>
{this.state.checkedBeta ? locale.release : locale.publish}
</Button>
) : (
<Button
type="primary"
style={{ marginRight: 10 }}
onClick={this.openDiff.bind(this, false)}
>
{locale.publish}
</Button>
)}
<Button type="normal" onClick={this.goList.bind(this)}>
{locale.back}
</Button>
</div>
</FormItem>
</Form>
<DiffEditorDialog
ref={this.diffEditorDialog}
publishConfig={this.publishConfig.bind(this)}
/>
<SuccessDialog ref={this.successDialog} />
</Loading>
</div>
);
}
}
export default ConfigEditor;
|
src/app/components/pages/HomePage.js | ucokfm/admin-lte-react | import React from 'react';
import PageWrapper from '../../../lib/page/PageWrapper';
import PageHeader from '../../../lib/page/PageHeader';
import Breadcrumb from '../../../lib/page/Breadcrumb';
import PageContent from '../../../lib/page/PageContent';
import Box from '../../../lib/widgets/Box';
export default function HomePage() {
return (
<PageWrapper>
<PageHeader
title="Home page"
description="Welcome to the first page"
>
<Breadcrumb
items={[
{ key: 1, icon: 'fa fa-home', title: 'Home', url: '/' },
{ key: 2, title: 'Page' },
]}
/>
</PageHeader>
<PageContent>
<Box
title="Hello, World!"
status="primary"
expandable
removable
>
You can collapse or close this box window using right upper buttons.
</Box>
</PageContent>
</PageWrapper>
);
}
|
src/docs/examples/PasswordInput/ExampleAllFeatures.js | peadar33/react-component | import React from 'react';
import PasswordInput from 'ps-react/PasswordInput';
/** All features enabled */
class ExampleAllFeatures extends React.Component {
constructor(props) {
super(props);
this.state = {
password: ''
};
}
getQuality() {
const length = this.state.password.length;
return length > 10 ? 100 : length * 10;
}
render() {
return (
<div>
<PasswordInput
htmlId="password-input-example-all-features"
name="password"
onChange={ event => this.setState({ password: event.target.value })}
value={this.state.password}
minLength={8}
placeholder="Enter password"
showVisibilityToggle
quality={this.getQuality()}
{...this.props} />
</div>
)
}
}
export default ExampleAllFeatures;
|
src/Parser/Mage/Fire/Modules/Features/CombustionMarqueeBindings.js | hasseboulen/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import SpellLink from 'common/SpellLink';
import ItemLink from 'common/ItemLink';
import Wrapper from 'common/Wrapper';
import Combatants from 'Parser/Core/Modules/Combatants';
import { formatMilliseconds, formatPercentage } from 'common/format';
import AbilityTracker from 'Parser/Core/Modules/AbilityTracker';
import Analyzer from 'Parser/Core/Analyzer';
import SpellUsable from 'Parser/Core/Modules/SpellUsable';
const debug = true;
class CombustionMarqueeBindings extends Analyzer {
static dependencies = {
combatants: Combatants,
spellUsable: SpellUsable,
abilityTracker: AbilityTracker,
};
buffUsedDuringCombustion = false;
combustionDuration = 0;
combustionCastTimestamp = 0;
pyroblastCastTimestamp = 0;
expectedPyroblastCasts = 0;
actualPyroblastCasts = 0;
//Check for Marquee Bindings Item, and calculate the duration of Combustion
//Accounts for the extra 2 seconds from Tier 21 2 Set, and 1 Second per point of Pre Ignited
on_initialized() {
this.active = this.combatants.selected.hasWrists(ITEMS.MARQUEE_BINDINGS_OF_THE_SUN_KING.id);
const hasTierBonus = this.combatants.selected.hasBuff(SPELLS.FIRE_MAGE_T21_2SET_BONUS_BUFF.id);
const preIgnitedCount = this.combatants.selected.traitsBySpellId[SPELLS.PRE_IGNITED_TRAIT.id];
if (hasTierBonus) {
this.combustionDuration = (10 + 2 + preIgnitedCount) * 1000;
} else {
this.combustionDuration = (10 + preIgnitedCount) * 1000;
}
}
//Get the time stamp for Pyroblast to be used elsewhere
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.PYROBLAST.id) {
return;
}
this.pyroblastCastTimestamp = event.timestamp;
}
on_toPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.KAELTHAS_ULTIMATE_ABILITY.id && spellId !== SPELLS.COMBUSTION.id) {
return;
}
if (spellId === SPELLS.COMBUSTION.id) {
this.combustionCastTimestamp = event.timestamp;
//If the player had a Bracer Proc when Combustion was cast, then its expected for them to cast it during Combustion.
if (this.combatants.selected.hasBuff(SPELLS.KAELTHAS_ULTIMATE_ABILITY.id)) {
this.expectedPyroblastCasts += 1;
debug && console.log("Pyroblast Expected During Combustion @ " + formatMilliseconds(event.timestamp - this.owner.fight.start_time));
}
} else {
//If the player gets a Bracer Proc, and there is more than 5 seconds left on the duration of Combustion, then its expected for them to cast it during Combustion.
if (this.combustionEndTime - event.timestamp > 5000) {
this.expectedPyroblastCasts += 1;
debug && console.log("Pyroblast Expected During Combustion @ " + formatMilliseconds(event.timestamp - this.owner.fight.start_time));
}
}
}
//Check to see if the player used their Bracer Proc during Combustion
on_toPlayer_removebuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.KAELTHAS_ULTIMATE_ABILITY.id) {
return;
}
if (event.timestamp - 50 < this.pyroblastCastTimestamp && this.combatants.selected.hasBuff(SPELLS.COMBUSTION.id)) {
this.actualPyroblastCasts += 1;
this.buffUsedDuringCombustion = true;
debug && console.log("Pyroblast Hard Cast During Combustion @ " + formatMilliseconds(event.timestamp - this.owner.fight.start_time));
}
}
on_finished() {
debug && console.log('Combustion Duration MS: ' + this.combustionDuration);
debug && console.log('Expected Pyroblasts: ' + this.expectedPyroblastCasts);
debug && console.log('Actual Pyroblasts: ' + this.actualPyroblastCasts);
}
get bracerBuffUtil() {
return (this.actualPyroblastCasts / this.expectedPyroblastCasts) || 0;
}
get combustionEndTime() {
return this.combustionCastTimestamp + this.combustionDuration;
}
get bracerUtilThresholds() {
return {
actual: this.bracerBuffUtil,
isLessThan: {
minor: 1,
average: .80,
major: .60,
},
style: 'percentage',
};
}
suggestions(when) {
if (this.expectedPyroblastCasts > 0) {
when(this.bracerUtilThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<Wrapper>During <SpellLink id={SPELLS.COMBUSTION.id}/> you had enough time to use {this.expectedPyroblastCasts} procs from your <ItemLink id={ITEMS.MARQUEE_BINDINGS_OF_THE_SUN_KING.id}/>, but you only used {this.actualPyroblastCasts} of them. If there is more than 5 seconds of Combustion left, you should use your proc so that your hard casted <SpellLink id={SPELLS.PYROBLAST.id}/> will do 300% damage and be guaranteed to crit.</Wrapper>)
.icon(ITEMS.MARQUEE_BINDINGS_OF_THE_SUN_KING.icon)
.actual(`${formatPercentage(this.bracerBuffUtil)}% Utilization`)
.recommended(`${formatPercentage(recommended)} is recommended`);
});
}
}
}
export default CombustionMarqueeBindings;
|
src/pages/home.js | fmakdemir/react-boilerplate | import React from 'react';
// icons
import FontIcon from 'material-ui/FontIcon';
// MUI components
import {Card, CardHeader, CardMedia, CardTitle, CardText, CardActions} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import {blue500, blue100} from 'material-ui/styles/colors';
// helpers
import MediaQuery from 'react-responsive';
// redux
import {connect} from 'react-redux';
import {createNotifAction} from 'actions/notif';
// style
import style from './home.less';
const card_img_url = 'https://scontent-otp1-1.xx.fbcdn.net/v/t31.0-8/15369220_1398510840173434_2708508428329075694_o.jpg?oh=d5a9d5233c52eae0429a7c21a7d237ff&oe=593D1BE3';
const IdeaIcon = <FontIcon className='material-icons'>lightbulb_outline</FontIcon>;
const CloseIcon = <FontIcon className='material-icons'>close</FontIcon>;
class Home extends React.Component {
render() {
return (
<div>
<FloatingActionButton
backgroundColor={blue500}
style={{position: 'fixed', right: 10, bottom: 10, zIndex: 2}}
iconStyle={{color: blue100}}
onClick={() => {this.props.onFabClick();}}
>
{IdeaIcon}
</FloatingActionButton>
<div className={style.home}>
<Card
style={{maxWidth: 400}} >
<CardHeader
avatar='https://avatars1.githubusercontent.com/u/1462379?v=3&s=80'
title='From me'
subtitle='with loves'
closeIcon={CloseIcon}
onClick={() => {this.props.onAvatarTap();}} />
<MediaQuery minDeviceHeight={500}>
<CardMedia>
<img src={card_img_url} />
</CardMedia>
<CardTitle
title='Photo by Camalti Photograpy'
subtitle='Kuzalan - Giresun' />
<CardText>
Photo is taken by my friend. Check out by clicking
the link at the bottom.
</CardText>
</MediaQuery>
<CardActions>
<FlatButton
label='Click me'
onClick={this.props.cardAction} />
<FlatButton
label='Camalti Photograpy'
href='https://fb.com/camaltiphotography'
target="_blank"
primary={true} />
</CardActions>
</Card>
</div>
</div>
);
}
}
Home.propTypes = {
onFabClick: React.PropTypes.func.isRequired,
onAvatarTap: React.PropTypes.func.isRequired,
cardAction: React.PropTypes.func.isRequired,
};
// redux mappers
const mapStateToProps = () => {
return {};
};
const mapDispatchToProps = (dispatch) => {
return {
onFabClick: () => {
dispatch(createNotifAction('I am fabolous!'));
},
onAvatarTap: () => {
dispatch(createNotifAction('clicked me!'));
},
cardAction: () => {
dispatch(createNotifAction('wow you listened to a button...'));
},
};
};
// wrap with react redux to connect to store
export default connect(
mapStateToProps,
mapDispatchToProps
)(Home);
|
15/notes/src/NoteItem.js | nanohop/hop_into_react | import React, { Component } from 'react';
import { Button } from 'react-bootstrap';
import FontAwesome from 'react-fontawesome';
class NoteItem extends Component {
render() {
return (
<li
className="list-group-item pull-left note-item"
onClick={this.props.onClick}>
<Button
className="pull-right btn-xs"
onClick={this.props.deleteNote}>
<FontAwesome name='trash' />
</Button>
{this.props.note.title}
</li>
);
}
}
export default NoteItem;
|
js/controls/Control.js | mekto/brouter-online | import Leaflet from 'leaflet';
import React from 'react';
import ReactDOM from 'react-dom';
export default Leaflet.Control.extend({
options: {
position: 'topright',
},
onAdd(map) {
const container = document.createElement('div');
container.className = this.options.className;
Leaflet.DomEvent
.disableClickPropagation(container)
.disableScrollPropagation(container)
.on(container, {contextmenu: Leaflet.DomEvent.stopPropagation});
this.component = ReactDOM.render(
React.createElement(this.getComponentClass(), {map}),
container
);
return container;
}
});
|
examples/using-jest/src/components/layout.js | ChristopherBiscardi/gatsby | import React from 'react'
import PropTypes from 'prop-types'
import { Helmet } from 'react-helmet'
import { StaticQuery, graphql } from 'gatsby'
import Header from './header'
import './layout.css'
const Layout = ({ children }) => (
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`}
render={data => (
<>
<Helmet
title={data.site.siteMetadata.title}
meta={[
{ name: `description`, content: `Sample` },
{ name: `keywords`, content: `sample, something` },
]}
>
<html lang="en" />
</Helmet>
<Header siteTitle={data.site.siteMetadata.title} />
<div
style={{
margin: `0 auto`,
maxWidth: 960,
padding: `0px 1.0875rem 1.45rem`,
paddingTop: 0,
}}
>
{children}
</div>
</>
)}
/>
)
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
|
src/components/panel/list/WhitePanelList.js | UncleYee/crm-ui | import React from 'react';
import WhitePanel from '../WhitePanel';
import {primaryColor} from 'utils/colors';
const styles = {
root: {
},
ul: {
listStyle: 'none',
padding: 0,
margin: 0
},
li: {
padding: '6px 0',
height: 29,
color: '#5d6266',
fontSize: 13,
},
number: {
float: 'right',
marginRight: 1,
color: primaryColor,
},
unit: {
float: 'right'
},
cursor: {
float: 'right',
marginRight: 1,
color: primaryColor,
cursor: 'pointer'
}
};
export default class WhitePanelList extends React.Component {
static propTypes = {
style: React.PropTypes.object,
items: React.PropTypes.array.isRequired,
unit: React.PropTypes.string,
title: React.PropTypes.string,
showTable: React.PropTypes.func, // 数据详情 有则可点
};
constructor(props) {
super(props);
}
show = ({title, flag, click}) => {
if (!click) return;
this.props.showTable(title, flag);
}
render() {
const {style, showTable, ...others} = this.props;
const rootStyle = Object.assign(styles.root, style);
return (
<WhitePanel style={rootStyle} {...others}>
<ul style={styles.ul}>
{
this.props.items.map( (item, index) => {
return (
<li key={index} style={styles.li}>
<span>{item.title}</span>
<span style={styles.unit}>{this.props.unit || '家'}</span>
<span style={item.click ? styles.cursor : styles.number} onClick={ ()=> this.show(item) }>{item.number}</span>
</li>
);
})
}
</ul>
</WhitePanel>
);
}
}
|
website/sections/Testing.js | sahat/boilerplate | import React from 'react';
import cx from 'classnames';
const TESTING_SVG = (
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 50 50">
<path d="M 18.5 2 C 17.1 2 16 3.1 16 4.5 C 16 5.7 16.9 6.70625 18 6.90625 L 18 40.90625 C 18 44.80625 21.1 47.90625 25 47.90625 C 28.9 47.90625 32 44.80625 32 40.90625 L 32 6.90625 C 33.1 6.70625 34 5.7 34 4.5 C 34 3.1 32.9 2 31.5 2 L 18.5 2 z M 18.5 4 L 31.5 4 C 31.8 4 32 4.2 32 4.5 C 32 4.8 31.8 5 31.5 5 L 31 5 L 30 5 L 23 5 L 23 7 L 30 7 L 30 13 L 20 13 L 20 7 L 21 7 L 21 5 L 20 5 L 19 5 L 18.5 5 C 18.2 5 18 4.8 18 4.5 C 18 4.2 18.2 4 18.5 4 z M 26 21 C 27.1 21 28 21.9 28 23 C 28 24.1 27.1 25 26 25 C 24.9 25 24 24.1 24 23 C 24 21.9 24.9 21 26 21 z M 23.5 31 C 24.3 31 25 31.7 25 32.5 C 25 33.3 24.3 34 23.5 34 C 22.7 34 22 33.3 22 32.5 C 22 31.7 22.7 31 23.5 31 z" overflow="visible"></path>
</svg>
);
class Testing extends React.Component {
render() {
const props = this.props;
let description;
switch (props.testing) {
case 'mocha':
description = (
<div>
<strong><a href="https://mochajs.org/" target="_blank">Mocha</a></strong> — Simple, flexible, fun javascript test framework. <strong><a href="http://chaijs.com/" target="_blank">Chai</a></strong> — A BDD / TDD assertion library. <strong><a href="http://sinonjs.org/" target="_blank">Sinon</a></strong> — Test spies, stubs and mocks.
</div>
);
break;
case 'jasmine':
description = (
<div>
<strong><a href="http://jasmine.github.io/edge/introduction.html" target="_blank">Jasmine</a></strong> — A BDD framework for testing JavaScript code. It does not depend on any other JavaScript frameworks.
</div>
);
break;
default:
description = <div className="placeholder"> </div>;
}
let note;
if (props.testing === 'mocha') {
note = (
<div>
<strong>Note: </strong>
<span>Mocha comes bundled with <a href="http://chaijs.com/" target="_blank">Chai</a> and <a href="http://sinonjs.org/" target="_blank">Sinon</a> for complete testing experience.</span>
</div>
);
} else {
note = <div className="placeholder"> </div>;
}
const mochaRadio = (
<label className="radio-inline">
<img className="btn-logo" src="/img/svg/mocha.svg" alt="Mocha"/>
<input type="radio" name="testingRadios" value="mocha" onChange={props.handleChange} checked={props.testing === 'mocha'}/>
<span>Mocha</span>
</label>
);
const jasmineRadio = props.jsFramework === 'angularjs' ? (
<label className="radio-inline">
<img className="btn-logo" src="/img/svg/jasmine.svg" alt="Jasmine"/>
<input type="radio" name="testingRadios" value="jasmine" onChange={props.handleChange} checked={props.testing === 'jasmine'}/>
<span>Jasmine</span>
</label>
) : (
<label className="radio-inline hint--top hint--rounded" data-hint="Coming soon">
<img className="btn-logo disabled" src="/img/svg/jasmine.svg" alt="Jasmine"/>
<input type="radio" name="testingRadios" value="jasmine" onChange={props.handleChange} checked={props.testing === 'jasmine'} disabled/>
<span>Jasmine</span>
</label>
);
const validationError = props.testingValidationError ? (
<div className="text-danger"><i className="fa fa-warning"></i> {props.testingValidationError}</div>
) : null;
if (props.testingValidationError) {
if (props.disableAutoScroll) {
$(this.refs.testing).velocity('scroll', { duration: 0 });
} else {
$(this.refs.testing).velocity('scroll');
}
}
return (
<div ref="testing" className={cx('zoomInBackwards panel', props.testing)}>
<div className="panel-heading">
<h6>{TESTING_SVG}{!props.testing || props.testing === 'none' ? 'Unit Testing' : props.testing}</h6>
</div>
<div className="panel-body">
{description}
<div className="radio-group">
<label className="radio-inline">
<img className="btn-logo" src="/img/svg/none.png" alt="None"/>
<input type="radio" name="testingRadios" value="none" onChange={props.handleChange} checked={props.testing === 'none'}/>
<span>None</span>
</label>
{mochaRadio}
{jasmineRadio}
</div>
{validationError}
{note}
</div>
</div>
);
}
}
export default Testing;
|
.storybook/preview.js | cloudbase/coriolis-web | import React from 'react'
import { addDecorator } from '@storybook/react'
import styled, { createGlobalStyle } from 'styled-components'
import { ThemePalette, ThemeProps } from '@src/components/Theme'
import Fonts from '@src/components/ui/Fonts'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
const Wrapper = styled.div`
display: inline-block;
background: ${ThemePalette.grayscale[7]};
padding: 32px;
`
const GlobalStyle = createGlobalStyle`
${Fonts}
body {
color: ${ThemePalette.black};
font-family: Rubik;
font-size: 14px;
font-weight: ${ThemeProps.fontWeights.regular};
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
`
addDecorator(storyFn => (
<Router>
<Switch>
<Wrapper>
<GlobalStyle />
{storyFn()}
</Wrapper>
</Switch>
</Router>
)
)
|
node_modules/rebass/src/SectionHeader.js | HasanSa/hackathon |
import React from 'react'
import Base from './Base'
import HeadingLink from './HeadingLink'
import Text from './Text'
import config from './config'
/**
* Header for section elements
*/
const SectionHeader = ({
heading,
href,
description,
children,
...props
}, { rebass }) => {
const { scale, borderColor } = { ...config, ...rebass }
return (
<Base
{...props}
tagName='header'
className='SectionHeader'
baseStyle={{
display: 'flex',
alignItems: 'center',
paddingBottom: scale[1],
marginTop: scale[3],
marginBottom: scale[3],
borderBottomWidth: 1,
borderBottomStyle: 'solid',
borderBottomColor: borderColor
}}>
<div style={{
flex: '1 1 auto' }}>
<HeadingLink href={href || `#${heading || ''}`} children={heading} />
{description && (
<Text children={description} />
)}
</div>
{children}
</Base>
)
}
SectionHeader.propTypes = {
/** Section heading */
heading: React.PropTypes.string,
/** Link to section, used in HeadingLink */
href: React.PropTypes.string,
/** Description of section */
description: React.PropTypes.string
}
SectionHeader.contextTypes = {
rebass: React.PropTypes.object
}
export default SectionHeader
|
src/svg-icons/action/perm-data-setting.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPermDataSetting = (props) => (
<SvgIcon {...props}>
<path d="M18.99 11.5c.34 0 .67.03 1 .07L20 0 0 20h11.56c-.04-.33-.07-.66-.07-1 0-4.14 3.36-7.5 7.5-7.5zm3.71 7.99c.02-.16.04-.32.04-.49 0-.17-.01-.33-.04-.49l1.06-.83c.09-.08.12-.21.06-.32l-1-1.73c-.06-.11-.19-.15-.31-.11l-1.24.5c-.26-.2-.54-.37-.85-.49l-.19-1.32c-.01-.12-.12-.21-.24-.21h-2c-.12 0-.23.09-.25.21l-.19 1.32c-.3.13-.59.29-.85.49l-1.24-.5c-.11-.04-.24 0-.31.11l-1 1.73c-.06.11-.04.24.06.32l1.06.83c-.02.16-.03.32-.03.49 0 .17.01.33.03.49l-1.06.83c-.09.08-.12.21-.06.32l1 1.73c.06.11.19.15.31.11l1.24-.5c.26.2.54.37.85.49l.19 1.32c.02.12.12.21.25.21h2c.12 0 .23-.09.25-.21l.19-1.32c.3-.13.59-.29.84-.49l1.25.5c.11.04.24 0 .31-.11l1-1.73c.06-.11.03-.24-.06-.32l-1.07-.83zm-3.71 1.01c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/>
</SvgIcon>
);
ActionPermDataSetting = pure(ActionPermDataSetting);
ActionPermDataSetting.displayName = 'ActionPermDataSetting';
ActionPermDataSetting.muiName = 'SvgIcon';
export default ActionPermDataSetting;
|
packages/xo-web/src/common/action-toggle.js | vatesfr/xo-web | import React from 'react'
import PropTypes from 'prop-types'
import ActionButton from './action-button'
const ActionToggle = ({ className, value, ...props }) => (
<ActionButton {...props} btnStyle={value ? 'success' : null} icon={value ? 'toggle-on' : 'toggle-off'} />
)
ActionToggle.propTypes = {
value: PropTypes.bool,
}
export { ActionToggle as default }
|
src/routes/Hello/index.js | Raphael67/react-restify-mysql | import React from 'react'
import DefaultLayout from '../../layouts/Default'
export default class Hello extends React.Component {
render() {
return (
<DefaultLayout currentPage='hello'>
<div>Hello {this.props.match.params.who}!</div>
</DefaultLayout>
)
}
} |
client/components/settings/bank-accesses/confirm-delete-access.js | ZeHiro/kresus | import React from 'react';
import { connect } from 'react-redux';
import { displayLabel, translate as $t } from '../../../helpers';
import { get, actions } from '../../../store';
import { registerModal } from '../../ui/modal';
import ModalContent from '../../ui/modal/content';
import CancelAndDelete from '../../ui/modal/cancel-and-delete-buttons';
export const DELETE_ACCESS_MODAL_SLUG = 'confirm-delete-access';
const ConfirmDeleteModal = connect(
state => {
let accessId = get.modal(state).state;
let access = get.accessById(state, accessId);
let label = access ? access.label : null;
let customLabel = access ? access.customLabel : null;
return {
label,
customLabel,
accessId
};
},
dispatch => {
return {
deleteAccess(accessId) {
actions.deleteAccess(dispatch, accessId);
}
};
},
({ label, customLabel, accessId }, { deleteAccess }) => {
return {
label,
customLabel,
handleDelete() {
deleteAccess(accessId);
}
};
}
)(props => {
return (
<ModalContent
title={$t('client.confirmdeletemodal.title')}
body={$t('client.settings.erase_access', { name: displayLabel(props) })}
footer={<CancelAndDelete onDelete={props.handleDelete} />}
/>
);
});
registerModal(DELETE_ACCESS_MODAL_SLUG, () => <ConfirmDeleteModal />);
|
app/javascript/mastodon/features/search/index.js | yukimochi/mastodon | import React from 'react';
import SearchContainer from 'mastodon/features/compose/containers/search_container';
import SearchResultsContainer from 'mastodon/features/compose/containers/search_results_container';
const Search = () => (
<div className='column search-page'>
<SearchContainer />
<div className='drawer__pager'>
<div className='drawer__inner darker'>
<SearchResultsContainer />
</div>
</div>
</div>
);
export default Search;
|
client/src/app/admin/panel/tickets/admin-panel-new-tickets.js | opensupports/opensupports | import React from 'react';
import {connect} from 'react-redux';
import i18n from 'lib-app/i18n';
import AdminDataAction from 'actions/admin-data-actions';
import TicketList from 'app-components/ticket-list';
import Header from 'core-components/header';
import Message from 'core-components/message';
class AdminPanelNewTickets extends React.Component {
static defaultProps = {
page: 1,
userId: 0,
departments: [],
tickets: [],
};
state = {
departmentId: null,
pageSize: 10
};
componentDidMount() {
this.retrieveNewTickets({});
}
render() {
const noDepartments = !this.props.departments.length;
return (
<div className="admin-panel-new-tickets">
<Header title={i18n('NEW_TICKETS')} description={i18n('NEW_TICKETS_DESCRIPTION')} />
{(noDepartments) ? <Message showCloseButton={false} className="admin-panel-new-tickets__department-warning" type="warning">{i18n('NO_DEPARTMENT_ASSIGNED')}</Message> : null}
{(this.props.error) ? <Message showCloseButton={false} type="error">{i18n('ERROR_RETRIEVING_TICKETS')}</Message> : <TicketList {...this.getProps()} />}
</div>
);
}
getProps() {
return {
userId: this.props.userId,
departments: this.props.departments,
tickets: this.props.tickets,
type: 'secondary',
loading: this.props.loading,
ticketPath: '/admin/panel/tickets/view-ticket/',
page: this.props.page,
pages: this.props.pages,
onPageChange: event => this.retrieveNewTickets({page: event.target.value}),
onDepartmentChange: departmentId => {
this.setState({departmentId});
this.retrieveNewTickets({page: 1, departmentId});
},
onPageSizeChange: pageSize => {
this.setState({pageSize});
this.retrieveNewTickets({page: 1, pageSize});
}
};
}
retrieveNewTickets({page = this.props.page, departmentId = this.state.departmentId, pageSize = this.state.pageSize }) {
this.props.dispatch(AdminDataAction.retrieveNewTickets({page, departmentId, pageSize}));
}
}
export default connect((store) => {
return {
userId: store.session.userId*1,
departments: store.session.userDepartments,
tickets: store.adminData.newTickets,
page: store.adminData.newTicketsPage,
pages: store.adminData.newTicketsPages,
loading: !store.adminData.newTicketsLoaded,
error: store.adminData.newTicketsError
};
})(AdminPanelNewTickets);
|
src/DatePicker/DatePicker.js | skyiea/wix-style-react | import React from 'react';
import WixComponent from '../BaseComponents/WixComponent';
import PropTypes from 'prop-types';
import ReactDatepicker from 'react-datepicker';
import DatePickerInput from './DatePickerInput';
import moment from 'moment';
import classnames from 'classnames';
import css from './DatePicker.scss';
/**
* DatePicker component
*
* ### Keyboard support
* * `Left`: Move to the previous day.
* * `Right`: Move to the next day.
* * `Up`: Move to the previous week.
* * `Down`: Move to the next week.
* * `PgUp`: Move to the previous month.
* * `PgDn`: Move to the next month.
* * `Home`: Move to the previous year.
* * `End`: Move to the next year.
* * `Enter`/`Esc`/`Tab`: close the calendar. (`Enter` & `Esc` calls `preventDefault`)
*
*/
export default class DatePicker extends WixComponent {
static displayName = 'DatePicker';
static propTypes = {
/** Can provide Input with your custom props */
customInput: PropTypes.node,
dataHook: PropTypes.string,
/** Custom date format */
dateFormat: PropTypes.string,
/** DatePicker instance locale */
locale: PropTypes.string,
/** Is the DatePicker disabled */
disabled: PropTypes.bool,
error: PropTypes.bool,
errorMessage: PropTypes.string,
/** Past dates are unselectable */
excludePastDates: PropTypes.bool,
/** Only the truthy dates are selectable */
filterDate: PropTypes.func,
/** dataHook for the DatePicker's Input */
inputDataHook: PropTypes.string,
/** Called upon every value change */
onChange: PropTypes.func.isRequired,
onEnterPressed: PropTypes.func,
/** placeholder of the Input */
placeholderText: PropTypes.string,
/** Icon for the DatePicker's Input */
prefix: PropTypes.node,
/** Is the input field readOnly */
readOnly: PropTypes.bool,
/** RTL mode */
rtl: PropTypes.bool,
/** Display a selectable yearDropdown */
showYearDropdown: PropTypes.bool,
/** Display a selectable monthDropdown */
showMonthDropdown: PropTypes.bool,
style: PropTypes.object,
/** Theme of the Input */
theme: PropTypes.string,
/** The selected date */
value: PropTypes.object,
/** should the calendar close on day selection */
shouldCloseOnSelect: PropTypes.bool,
/** controls the whether the calendar will be visible or not */
isOpen: PropTypes.bool,
/** called when calendar visibility changes */
setOpen: PropTypes.func
};
static defaultProps = {
style: {
width: 150
},
filterDate: () => true,
shouldCloseOnSelect: true
};
constructor(props) {
super(props);
this.filterDate = this.filterDate.bind(this);
}
filterDate(date) {
if (this.props.excludePastDates) {
if (date < moment().startOf('d')) {
return false;
}
}
return this.props.filterDate(date);
}
renderInput() {
const {
rtl, style, theme, prefix, inputDataHook: dataHook, onEnterPressed,
error, errorMessage, customInput
} = this.props;
return (
<DatePickerInput
{...{
rtl,
style,
theme,
prefix,
dataHook,
onEnterPressed,
error,
errorMessage,
customInput
}}
/>
);
}
render() {
const cssClasses = [css.wrapper];
if (this.props.showYearDropdown || this.props.showMonthDropdown) {
cssClasses.push({'react-datepicker--hide-header': true});
} else {
cssClasses.push({'react-datepicker--hide-header__dropdown': true});
}
return (
<div className={classnames(cssClasses)}>
<ReactDatepicker
{...this.props}
selected={this.props.value}
onChange={val => {
if (this.filterDate(val)) {
this.props.onChange(val);
}
}}
customInput={this.renderInput()}
filterDate={this.filterDate}
readOnly={this.props.readOnly}
showYearDropdown={this.props.showYearDropdown}
scrollableYearDropdown
/>
</div>
);
}
}
|
src/components/partials/speedOption.js | harrison-symes/colour | import React from 'react'
module.exports = (state, dispatch) => {
function renderOptions() {
let arr = []
for (var i = 5000; i >= 200; i = i - 200) {
arr.push(<option value={i}>{i}</option>)
}
return arr
}
return (
<select onChange={(e) => dispatch({type: 'CHANGE_SPEED', payload: e.target.value})}>
{renderOptions()}
</select>
)
}
|
tndata_backend/chat/static/react-chat/src/components/chat.js | izzyalonso/tndata_backend | import _ from 'lodash';
import moment from 'moment';
import React, { Component } from 'react';
import Websocket from './websocket';
import AutoLinkText from 'react-autolink-text';
import ChatForm from './chat_form'
import { slugify, extractVideo } from './utils';
export default class Chat extends Component {
constructor(props) {
super(props);
this.state = {
messages: [],
current: '',
received: '',
}
}
handleMessage(data) {
// NOTE: data should be an object of the form: {from: ..., text: ...}
const new_message = {
id: slugify(data.text) + new Date().valueOf(), // ¯\_(ツ)_/¯
text: data.text,
from: data.from,
from_id: data.from_id,
avatar: data.from === "system" ? '' : data.avatar,
digest: data.digest
}
const messages = _.concat(this.state.messages, [new_message]);
// The `received` state only when I've received the other user's message.
const digest = (data.from_id === this.props.user.userId) ? this.state.received : data.digest;
this.setState({
messages: messages,
current: this.state.current,
received: digest, // Save the digest of the last message recieved.
});
}
onFormSubmit(event) {
event.preventDefault();
// event.target is the form.
// event.target[0] is the first child element (our <input>)
const inputElement = event.target.children[0].children[0];
const message = inputElement.value;
// Format of message to send
const toSend = JSON.stringify({
text: message,
token: this.props.user.token,
});
this.setState({messages: this.state.messages, current: toSend});
inputElement.value = ""; // clear the input.
}
renderMessageList() {
// NOTE: Each object in our array of history looks like:
//
// {
// created_on: "2017-01-05 21:57:39+0000"
// id:63
// read:false
// room:"chat-1-995"
// text:"Hi there"
// user:995
// user_full_name:"Brad Montgomery"
// user_username:"342ec11a7990133827bc6e66f381ee"
// avatar: "//lh5.googleusercontent.com/.../photo.jpg"
// }
// Make sure our history is sorted by date (oldest listed first).
const historySorted = this.props.history.sort(function(a, b) {
if(a.created_on < b.created_on) {
return -1;
}
else if(a.created_on > b.created_on) {
return 1;
}
// must be the same.
return 0;
})
// then map the history attributes to those that we use to
// render new messages.
const history = Array.from(historySorted, function(obj) {
return {
id: obj.id,
text: obj.text,
from: obj.user_full_name,
from_id: obj.user,
avatar: obj.avatar,
created: obj.created_on
}
});
// Combine the history with the current session's messages.
const messages = history.concat(this.state.messages);
let lastDay = null;
let currentDay = null;
return messages.map((msg) => {
currentDay = moment(msg.created).format("dddd, MMMM Do YYYY");
// A Reply is a message from the other user but not the system.
const isReply = this.props.user.userId !== msg.from_id && msg.from !== 'system';
// Only show message times on replies.
const timestamp = isReply ? moment(msg.created).format("LT") : '';
// Only show avatars for actual users.
let avatar = '';
if (this.props.user.avatar && !isReply && msg.from !== 'system') {
avatar = <img src={this.props.user.avatar} className="avatar" role="presentation" />;
}
else if(msg.avatar && msg.from !== 'system') {
avatar = <img src={msg.avatar} className="avatar" role="presentation" />;
}
const chatClasses = (isReply ? 'chatBubble reply' : 'chatBubble') +
(msg.from === 'system' ? ' notice' : '');
// Inline links to youtube videos, if applicable.
const video = extractVideo(msg.text);
let content = msg.text;
if(video) {
content = (
<div>
<div className={chatClasses}>
{avatar}
<AutoLinkText text={msg.text} />
</div>
<iframe width="640"
height="360"
src={video.embedUrl}
frameBorder="0" allowFullScreen />
</div>
);
}
else {
content = (
<div className={chatClasses}>
{avatar}
<AutoLinkText text={msg.text} />
</div>
);
}
content = (
<li key={msg.id}>
{currentDay != lastDay &&
<div className="notice clearfix">{currentDay}</div>}
{content}
<span className="timestamp">{timestamp}</span>
</li>
);
lastDay = currentDay;
return content
});
}
render() {
return (
<div className="chatContainer">
<ul>{this.renderMessageList()}</ul>
<Websocket url={this.props.ws_url}
debug={true}
onMessage={this.handleMessage.bind(this)}
sendMessage={this.state.current}
received={this.state.received} />
<ChatForm
handleSubmit={this.onFormSubmit.bind(this)} />
</div>
);
}
}
|
lib/railspack/templates/registerComponent.js | jdmorlan/railspack | import React from 'react'
import ReactDOM from 'react-dom'
const getProps = (container) => {
const propsString = container.getAttribute("data-react-props")
const props = propsString ? JSON.parse(propsString) : null
return props
}
export const registerComponent = (instance, containerName) => {
const selector = `[data-react-container=${containerName}]`
const containers = document.querySelectorAll(selector)
for (let i = 0; i < containers.length; ++i) {
let container = containers[i];
const props = getProps(container)
const element = React.createElement(instance, props)
ReactDOM.render(element, container)
}
}
|
js/components/missions/TaskRewardModal.js | kort/kort-reloaded | import React from 'react';
import { StyleSheet, View, Text, Image } from 'react-native';
import I18n from 'react-native-i18n';
import { Actions } from 'react-native-router-flux';
import Button from '../shared/Button';
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
flexDirection: 'column',
backgroundColor: '#fff',
justifyContent: 'center',
alignItems: 'center',
},
innerContainer: {
justifyContent: 'center',
alignItems: 'center',
},
innerContainerMissionComplete: {
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
},
icon: {
marginTop: 7,
marginRight: 7,
height: 46,
width: 46,
},
textTitle: {
textAlign: 'center',
fontSize: 18,
marginTop: 5,
},
textMission: {
alignSelf: 'center',
marginTop: 10,
marginBottom: 10,
width: 200,
},
});
const TaskRewardModal = ({ receivedKoins, newKoinsTotal }) => (
<View style={styles.container}>
<View style={styles.innerContainer}>
<Text style={styles.textTitle}>{I18n.t('reward_alert_title')}</Text>
<View style={styles.innerContainerMissionComplete}>
<Image style={styles.icon} source={require('../../assets/img/koin_no_value.png')} />
<Text style={styles.textMission}>
{I18n.t('reward_alert_koins_new', { koin_count_new: receivedKoins })}{'\n'}
{I18n.t('reward_alert_koins_total', { koin_count_total: newKoinsTotal })}
</Text>
</View>
<Button onPress={Actions.pop}>{I18n.t('messagebox_ok')}</Button>
</View>
</View>
);
TaskRewardModal.propTypes = {
receivedKoins: React.PropTypes.any.isRequired,
newKoinsTotal: React.PropTypes.any.isRequired,
};
module.exports = TaskRewardModal;
|
src/parser/warlock/destruction/modules/features/ImmolateUptime.js | FaideWW/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import Enemies from 'parser/shared/modules/Enemies';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
class ImmolateUptime extends Analyzer {
static dependencies = {
enemies: Enemies,
};
get uptime() {
return this.enemies.getBuffUptime(SPELLS.IMMOLATE_DEBUFF.id) / this.owner.fightDuration;
}
get suggestionThresholds() {
return {
actual: this.uptime,
isLessThan: {
minor: 0.9,
average: 0.85,
major: 0.75,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<>Your <SpellLink id={SPELLS.IMMOLATE_DEBUFF.id} /> uptime can be improved. Try to pay more attention to it as it provides a significant amount of Soul Shard Fragments over the fight and is also a big portion of your total damage.</>)
.icon(SPELLS.IMMOLATE_DEBUFF.icon)
.actual(`${formatPercentage(actual)}% Immolate uptime`)
.recommended(`>${formatPercentage(recommended)}% is recommended`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.IMMOLATE_DEBUFF.id} />}
value={`${formatPercentage(this.uptime)} %`}
label="Immolate uptime"
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(3);
}
export default ImmolateUptime;
|
assets/react/src/components/task/task_detail.js | khoa-le/crontask | import React, { Component } from 'react';
import moment from 'moment';
import uuid from 'uuid';
import TaskDetailAction from './task_detail_action.js';
export default class TaskDetail extends Component {
/** @namespace this.props.handleBack */
constructor(props) {
super(props);
this.state = {
task: {},
job: {}
}
if(this.props.data.id){
this.state.task=this.props.data;
}else{
this.state.task={id:uuid.v1()};
}
this.onSaveTask = this.onSaveTask.bind(this);
this.onDeleteTask = this.onDeleteTask.bind(this);
this.onExecuteTask = this.onExecuteTask.bind(this);
}
loadMessagesFromServer() {
}
componentDidMount() {
}
onSaveTask(e) {
e.preventDefault();
let data={
id:this.state.task.id,
name:$("input[name=name]").val(),
command:$("input[name=command]").val(),
periodicity:$("input[name=periodicity]").val()
};
$.ajax(
{
url: 'api/tasks',
headers: {
'Content-Type':'application/json'
},
data: JSON.stringify(data),
dataType: 'json',
method: 'POST',
success: function (data) {
if (data.status == 'SUCCESS') {
this.props.handleBack()
}
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.actionUrl.sendMessage, status, err.toString());
}.bind(this)
}
)
}
onDeleteTask(e) {
e.preventDefault();
$.ajax(
{
url: 'api/tasks/'+this.state.task.id,
type: 'DELETE',
success: function (data) {
this.props.handleBack()
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.actionUrl.sendMessage, status, err.toString());
}.bind(this)
}
)
}
onExecuteTask(e){
e.preventDefault();
$.ajax(
{
url: 'tasks/'+this.state.task.id+'/executions',
dataType: 'json',
method: 'POST',
success: function (data) {
console.log(data);
this.props.handleBack()
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.actionUrl.sendMessage, status, err.toString());
}.bind(this)
}
)
}
render() {
return (
<div className="col-lg-12 animated fadeInRight">
<div className="mail-box-header clearfix">
<div className="pull-left">
<a className="btn btn-white btn-sm" onClick={this.props.handleBack}><i
className="fa fa-long-arrow-left"></i> Back </a>
</div>
<div className="pull-right">
<TaskDetailAction
data={this.state.task}
handleDelete={this.onDeleteTask}
handleBack={this.props.handleBack}
handleExecute={this.onExecuteTask}
/>
</div>
</div>
<div className="mail-box">
<div className="mail-body">
<form id="formUpdate" className="form-horizontal" method="Post">
<div className="form-group">
<label className="col-sm-2 control-label">ID:</label>
<div className="col-sm-10">
<input type="text" className="form-control" defaultValue={this.state.task.id} />
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label">Name:</label>
<div className="col-sm-10">
<input name="name" type="text" className="form-control" defaultValue={this.state.task.name} />
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label">Command:</label>
<div className="col-sm-10">
<input name="command" type="text" className="form-control" defaultValue={this.state.task.command} />
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label">Periodicity:</label>
<div className="col-sm-10">
<input name="periodicity" type="text" className="form-control" defaultValue={this.state.task.periodicity} />
</div>
</div>
<div className="form-group">
<label className="col-sm-2 control-label">Create:</label>
<div className="col-sm-10">
<input type="text" className="form-control" defaultValue={this.state.task.created_at} />
</div>
</div>
<div className="form-group">
<div className="col-sm-10 col-md-offset-2">
<a onClick={this.onSaveTask} className="btn btn-primary">Save</a>
<button type="button" onClick={this.props.handleBack} className="btn btn-default">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
);
}
;
}
TaskDetail.contextTypes = {lang: React.PropTypes.number, t: React.PropTypes.any};
TaskDetail.propTypes = {
handleBack: React.PropTypes.func,
data: React.PropTypes.object,
}; |
client/app/containers/LoginPage/index.js | Kielan/onDemanager | /*
* LoginPage
* User facing auth portal
*/
import React from 'react';
import { connect } from 'react-redux';
import { routeActions } from 'react-router-redux';
import { createSelector } from 'reselect';
import loggedInSelector from 'loggedInSelector';
import {Jumbotron, Input, ButtonInput } from 'react-bootstrap';
import {
loginSubmit
} from 'App/actions';
import LoginForm from 'LoginForm'
import styles from './styles.css';
class LoginPage extends React.Component {
constructor() {
super();
}
render() {
const formState = {data: {username: 'kielan', password: 'mibbit'}}
return (
<Jumbotron>
<LoginForm data={formState} onSubmit={::this._login} />
</Jumbotron>
)
}
_login(username, password) {
console.log('not getting form data', username, password)
this.props.dispatch(loginSubmit(username, password));
}
}
function mapDispatchToProps(dispatch) {
return {
onLogin: (evt) => dispatch(login(username, password)),
dispatch
};
}
export default connect(createSelector(
loggedInSelector,
(username) => ({username})
), mapDispatchToProps)(LoginPage);
|
app/javascript/mastodon/features/status/components/action_bar.js | Kirishima21/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import IconButton from '../../../components/icon_button';
import ImmutablePropTypes from 'react-immutable-proptypes';
import DropdownMenuContainer from '../../../containers/dropdown_menu_container';
import { defineMessages, injectIntl } from 'react-intl';
import { me, isStaff } from '../../../initial_state';
import classNames from 'classnames';
const messages = defineMessages({
delete: { id: 'status.delete', defaultMessage: 'Delete' },
redraft: { id: 'status.redraft', defaultMessage: 'Delete & re-draft' },
direct: { id: 'status.direct', defaultMessage: 'Direct message @{name}' },
mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' },
reply: { id: 'status.reply', defaultMessage: 'Reply' },
reblog: { id: 'status.reblog', defaultMessage: 'Boost' },
reblog_private: { id: 'status.reblog_private', defaultMessage: 'Boost with original visibility' },
cancel_reblog_private: { id: 'status.cancel_reblog_private', defaultMessage: 'Unboost' },
cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' },
favourite: { id: 'status.favourite', defaultMessage: 'Favourite' },
bookmark: { id: 'status.bookmark', defaultMessage: 'Bookmark' },
more: { id: 'status.more', defaultMessage: 'More' },
mute: { id: 'status.mute', defaultMessage: 'Mute @{name}' },
muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' },
unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' },
block: { id: 'status.block', defaultMessage: 'Block @{name}' },
report: { id: 'status.report', defaultMessage: 'Report @{name}' },
share: { id: 'status.share', defaultMessage: 'Share' },
pin: { id: 'status.pin', defaultMessage: 'Pin on profile' },
unpin: { id: 'status.unpin', defaultMessage: 'Unpin from profile' },
embed: { id: 'status.embed', defaultMessage: 'Embed' },
admin_account: { id: 'status.admin_account', defaultMessage: 'Open moderation interface for @{name}' },
admin_status: { id: 'status.admin_status', defaultMessage: 'Open this status in the moderation interface' },
copy: { id: 'status.copy', defaultMessage: 'Copy link to status' },
blockDomain: { id: 'account.block_domain', defaultMessage: 'Block domain {domain}' },
unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' },
unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' },
unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' },
});
const mapStateToProps = (state, { status }) => ({
relationship: state.getIn(['relationships', status.getIn(['account', 'id'])]),
});
export default @connect(mapStateToProps)
@injectIntl
class ActionBar extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
relationship: ImmutablePropTypes.map,
onReply: PropTypes.func.isRequired,
onReblog: PropTypes.func.isRequired,
onFavourite: PropTypes.func.isRequired,
onBookmark: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
onDirect: PropTypes.func.isRequired,
onMention: PropTypes.func.isRequired,
onMute: PropTypes.func,
onUnmute: PropTypes.func,
onBlock: PropTypes.func,
onUnblock: PropTypes.func,
onBlockDomain: PropTypes.func,
onUnblockDomain: PropTypes.func,
onMuteConversation: PropTypes.func,
onReport: PropTypes.func,
onPin: PropTypes.func,
onEmbed: PropTypes.func,
intl: PropTypes.object.isRequired,
};
handleReplyClick = () => {
this.props.onReply(this.props.status);
}
handleReblogClick = (e) => {
this.props.onReblog(this.props.status, e);
}
handleFavouriteClick = () => {
this.props.onFavourite(this.props.status);
}
handleBookmarkClick = (e) => {
this.props.onBookmark(this.props.status, e);
}
handleDeleteClick = () => {
this.props.onDelete(this.props.status, this.context.router.history);
}
handleRedraftClick = () => {
this.props.onDelete(this.props.status, this.context.router.history, true);
}
handleDirectClick = () => {
this.props.onDirect(this.props.status.get('account'), this.context.router.history);
}
handleMentionClick = () => {
this.props.onMention(this.props.status.get('account'), this.context.router.history);
}
handleMuteClick = () => {
const { status, relationship, onMute, onUnmute } = this.props;
const account = status.get('account');
if (relationship && relationship.get('muting')) {
onUnmute(account);
} else {
onMute(account);
}
}
handleBlockClick = () => {
const { status, relationship, onBlock, onUnblock } = this.props;
const account = status.get('account');
if (relationship && relationship.get('blocking')) {
onUnblock(account);
} else {
onBlock(status);
}
}
handleBlockDomain = () => {
const { status, onBlockDomain } = this.props;
const account = status.get('account');
onBlockDomain(account.get('acct').split('@')[1]);
}
handleUnblockDomain = () => {
const { status, onUnblockDomain } = this.props;
const account = status.get('account');
onUnblockDomain(account.get('acct').split('@')[1]);
}
handleConversationMuteClick = () => {
this.props.onMuteConversation(this.props.status);
}
handleReport = () => {
this.props.onReport(this.props.status);
}
handlePinClick = () => {
this.props.onPin(this.props.status);
}
handleShare = () => {
navigator.share({
text: this.props.status.get('search_index'),
url: this.props.status.get('url'),
});
}
handleEmbed = () => {
this.props.onEmbed(this.props.status);
}
handleCopy = () => {
const url = this.props.status.get('url');
const textarea = document.createElement('textarea');
textarea.textContent = url;
textarea.style.position = 'fixed';
document.body.appendChild(textarea);
try {
textarea.select();
document.execCommand('copy');
} catch (e) {
} finally {
document.body.removeChild(textarea);
}
}
render () {
const { status, relationship, intl } = this.props;
const publicStatus = ['public', 'unlisted'].includes(status.get('visibility'));
const pinnableStatus = ['public', 'unlisted', 'private'].includes(status.get('visibility'));
const mutingConversation = status.get('muted');
const account = status.get('account');
const writtenByMe = status.getIn(['account', 'id']) === me;
let menu = [];
if (publicStatus) {
menu.push({ text: intl.formatMessage(messages.copy), action: this.handleCopy });
menu.push({ text: intl.formatMessage(messages.embed), action: this.handleEmbed });
menu.push(null);
}
if (writtenByMe) {
if (pinnableStatus) {
menu.push({ text: intl.formatMessage(status.get('pinned') ? messages.unpin : messages.pin), action: this.handlePinClick });
menu.push(null);
}
menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick });
menu.push({ text: intl.formatMessage(messages.redraft), action: this.handleRedraftClick });
} else {
menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick });
menu.push({ text: intl.formatMessage(messages.direct, { name: status.getIn(['account', 'username']) }), action: this.handleDirectClick });
menu.push(null);
if (relationship && relationship.get('muting')) {
menu.push({ text: intl.formatMessage(messages.unmute, { name: account.get('username') }), action: this.handleMuteClick });
} else {
menu.push({ text: intl.formatMessage(messages.mute, { name: account.get('username') }), action: this.handleMuteClick });
}
if (relationship && relationship.get('blocking')) {
menu.push({ text: intl.formatMessage(messages.unblock, { name: account.get('username') }), action: this.handleBlockClick });
} else {
menu.push({ text: intl.formatMessage(messages.block, { name: account.get('username') }), action: this.handleBlockClick });
}
menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport });
if (account.get('acct') !== account.get('username')) {
const domain = account.get('acct').split('@')[1];
menu.push(null);
if (relationship && relationship.get('domain_blocking')) {
menu.push({ text: intl.formatMessage(messages.unblockDomain, { domain }), action: this.handleUnblockDomain });
} else {
menu.push({ text: intl.formatMessage(messages.blockDomain, { domain }), action: this.handleBlockDomain });
}
}
if (isStaff) {
menu.push(null);
menu.push({ text: intl.formatMessage(messages.admin_account, { name: status.getIn(['account', 'username']) }), href: `/admin/accounts/${status.getIn(['account', 'id'])}` });
menu.push({ text: intl.formatMessage(messages.admin_status), href: `/admin/accounts/${status.getIn(['account', 'id'])}/statuses?id=${status.get('id')}` });
}
}
const shareButton = ('share' in navigator) && publicStatus && (
<div className='detailed-status__button'><IconButton title={intl.formatMessage(messages.share)} icon='share-alt' onClick={this.handleShare} /></div>
);
let replyIcon;
if (status.get('in_reply_to_id', null) === null) {
replyIcon = 'reply';
} else {
replyIcon = 'reply-all';
}
const reblogPrivate = status.getIn(['account', 'id']) === me && status.get('visibility') === 'private';
let reblogTitle;
if (status.get('reblogged')) {
reblogTitle = intl.formatMessage(messages.cancel_reblog_private);
} else if (publicStatus) {
reblogTitle = intl.formatMessage(messages.reblog);
} else if (reblogPrivate) {
reblogTitle = intl.formatMessage(messages.reblog_private);
} else {
reblogTitle = intl.formatMessage(messages.cannot_reblog);
}
return (
<div className='detailed-status__action-bar'>
<div className='detailed-status__button'><IconButton title={intl.formatMessage(messages.reply)} icon={status.get('in_reply_to_account_id') === status.getIn(['account', 'id']) ? 'reply' : replyIcon} onClick={this.handleReplyClick} /></div>
<div className='detailed-status__button' ><IconButton className={classNames({ reblogPrivate })} disabled={!publicStatus && !reblogPrivate} active={status.get('reblogged')} title={reblogTitle} icon='retweet' onClick={this.handleReblogClick} /></div>
<div className='detailed-status__button'><IconButton className='star-icon' animate active={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} /></div>
{shareButton}
<div className='detailed-status__button'><IconButton className='bookmark-icon' active={status.get('bookmarked')} title={intl.formatMessage(messages.bookmark)} icon='bookmark' onClick={this.handleBookmarkClick} /></div>
<div className='detailed-status__action-bar-dropdown'>
<DropdownMenuContainer size={18} icon='ellipsis-h' status={status} items={menu} direction='left' title={intl.formatMessage(messages.more)} />
</div>
</div>
);
}
}
|
news/client.js | HKuz/FreeCodeCamp | import React from 'react';
import {BrowserRouter} from 'react-router-dom';
import { render } from 'react-dom';
import NewsApp from './NewsApp';
const newsMountPoint = document.getElementById('news-app-mount');
const App = (
<BrowserRouter basename='/news'>
<NewsApp />
</BrowserRouter>
);
render(
App,
newsMountPoint
);
|
app/javascript/mastodon/components/avatar_composite.js | lindwurm/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { autoPlayGif } from '../initial_state';
export default class AvatarComposite extends React.PureComponent {
static propTypes = {
accounts: ImmutablePropTypes.list.isRequired,
animate: PropTypes.bool,
size: PropTypes.number.isRequired,
};
static defaultProps = {
animate: autoPlayGif,
};
renderItem (account, size, index) {
const { animate } = this.props;
let width = 50;
let height = 100;
let top = 'auto';
let left = 'auto';
let bottom = 'auto';
let right = 'auto';
if (size === 1) {
width = 100;
}
if (size === 4 || (size === 3 && index > 0)) {
height = 50;
}
if (size === 2) {
if (index === 0) {
right = '1px';
} else {
left = '1px';
}
} else if (size === 3) {
if (index === 0) {
right = '1px';
} else if (index > 0) {
left = '1px';
}
if (index === 1) {
bottom = '1px';
} else if (index > 1) {
top = '1px';
}
} else if (size === 4) {
if (index === 0 || index === 2) {
right = '1px';
}
if (index === 1 || index === 3) {
left = '1px';
}
if (index < 2) {
bottom = '1px';
} else {
top = '1px';
}
}
const style = {
left: left,
top: top,
right: right,
bottom: bottom,
width: `${width}%`,
height: `${height}%`,
backgroundSize: 'cover',
backgroundImage: `url(${account.get(animate ? 'avatar' : 'avatar_static')})`,
};
return (
<div key={account.get('id')} style={style} />
);
}
render() {
const { accounts, size } = this.props;
return (
<div className='account__avatar-composite' style={{ width: `${size}px`, height: `${size}px` }}>
{accounts.take(4).map((account, i) => this.renderItem(account, Math.min(accounts.size, 4), i))}
{accounts.size > 4 && (
<span className='account__avatar-composite__label'>
+{accounts.size - 4}
</span>
)}
</div>
);
}
}
|
node_modules/react-router/es6/IndexRedirect.js | tacrow/tacrow | import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import Redirect from './Redirect';
import { falsy } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes;
var string = _React$PropTypes.string;
var object = _React$PropTypes.object;
/**
* An <IndexRedirect> is used to redirect from an indexRoute.
*/
var IndexRedirect = React.createClass({
displayName: 'IndexRedirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = Redirect.createRouteFromReactElement(element);
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRedirect> does not make sense at the root of your route config') : void 0;
}
}
},
propTypes: {
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default IndexRedirect; |
test/components/map.js | worldbank-cdrp/disaster-risk-explorer | import React from 'react'
import test from 'ava'
import { shallow } from 'enzyme'
import proxyquire from 'proxyquire'
import mockboxGL from 'mapbox-gl-js-mock'
import DataSelection from '../../app/assets/scripts/utils/data-selection'
const { Map } = proxyquire.noCallThru().load('../../app/assets/scripts/components/map', {
'mapbox-gl': mockboxGL
})
test('map test', t => {
const dataSelection = DataSelection({})
const component = shallow(<Map dataSelection={dataSelection} />)
t.truthy(component.hasClass('map'))
// mock mount
const instance = component.instance()
instance._adjustOpacity = () => {}
instance._addZoomControls = () => {}
instance._setMapLanguage = () => {}
t.notThrows(() => instance.componentDidMount())
})
|
geonode/monitoring/frontend/monitoring/src/components/organisms/geonode-layers-analytics/index.js | francbartoli/geonode | /*
#########################################################################
#
# Copyright (C) 2019 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getResponseData, getErrorCount } from '../../../utils';
import HoverPaper from '../../atoms/hover-paper';
import HR from '../../atoms/hr';
import ResponseTable from '../../cels/response-table';
import LayerSelect from '../../cels/layer-select';
import FrequentLayers from '../../cels/frequent-layers';
import styles from './styles';
import actions from './actions';
const mapStateToProps = (state) => ({
interval: state.interval.interval,
response: state.geonodeLayerResponse.response,
errorNumber: state.geonodeLayerError.response,
});
@connect(mapStateToProps, actions)
class GeonodeLayerAnalytics extends React.Component {
static propTypes = {
getResponses: PropTypes.func.isRequired,
resetResponses: PropTypes.func.isRequired,
getErrors: PropTypes.func.isRequired,
resetErrors: PropTypes.func.isRequired,
interval: PropTypes.number,
response: PropTypes.object,
errorNumber: PropTypes.object,
timestamp: PropTypes.instanceOf(Date),
}
constructor(props) {
super(props);
this.get = (layer, interval = this.props.interval) => {
this.setState({ layer });
this.props.getErrors(layer, interval);
this.props.getResponses(layer, interval);
};
this.reset = () => {
this.props.resetErrors();
this.props.resetResponses();
};
}
componentWillReceiveProps(nextProps) {
if (nextProps) {
if (
nextProps.timestamp && nextProps.timestamp !== this.props.timestamp
&& this.state && this.state.layer
) {
this.get(this.state.layer, nextProps.interval);
}
}
}
componentWillUnmount() {
this.reset();
}
render() {
let average = 0;
let max = 0;
let requests = 0;
[
average,
max,
requests,
] = getResponseData(this.props.response);
const errorNumber = getErrorCount(this.props.errorNumber);
return (
<HoverPaper style={styles.content}>
<div style={styles.header}>
<h3>Geonode Layers Analytics</h3>
<LayerSelect onChange={this.get} />
</div>
<HR />
<ResponseTable
average={average}
max={max}
requests={requests}
errorNumber={errorNumber}
/>
<FrequentLayers />
</HoverPaper>
);
}
}
export default GeonodeLayerAnalytics;
|
src/shared/element-react/dist/npm/es6/src/scrollbar/Scrollbar.js | thundernet8/Elune-WWW | import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import { PropTypes, Component } from '../../libs';
import { addResizeListener, removeResizeListener } from '../../libs/utils/resize-event';
import { getScrollBarWidth } from './scrollbar-width';
import { Bar } from './Bar';
export var Scrollbar = function (_Component) {
_inherits(Scrollbar, _Component);
function Scrollbar(props) {
_classCallCheck(this, Scrollbar);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.state = {
sizeWidth: '0',
sizeHeight: '0',
moveX: 0,
moveY: 0
};
return _this;
}
Scrollbar.prototype.componentDidMount = function componentDidMount() {
var _this2 = this;
if (this.native) return;
var handler = this.update.bind(this);
var rafId = requestAnimationFrame(handler);
this.cleanRAF = function () {
cancelAnimationFrame(rafId);
};
if (!this.props.noresize) {
addResizeListener(this.refs.resize, handler);
this.cleanResize = function () {
removeResizeListener(_this2.refs.resize, handler);
};
}
};
Scrollbar.prototype.componentWillUnmount = function componentWillUnmount() {
this.cleanRAF();
this.cleanResize && this.cleanResize();
};
Scrollbar.prototype.handleScroll = function handleScroll() {
var wrap = this.wrap;
this.setState({
moveY: wrap.scrollTop * 100 / wrap.clientHeight,
moveX: wrap.scrollLeft * 100 / wrap.clientWidth
});
};
Scrollbar.prototype.update = function update() {
var heightPercentage = void 0,
widthPercentage = void 0;
var wrap = this.wrap;
if (!wrap) return;
heightPercentage = wrap.clientHeight * 100 / wrap.scrollHeight;
widthPercentage = wrap.clientWidth * 100 / wrap.scrollWidth;
var sizeHeight = heightPercentage < 100 ? heightPercentage + '%' : '';
var sizeWidth = widthPercentage < 100 ? widthPercentage + '%' : '';
this.setState({ sizeHeight: sizeHeight, sizeWidth: sizeWidth });
};
Scrollbar.prototype.render = function render() {
var _this3 = this;
/* eslint-disable */
var _props = this.props,
native = _props.native,
viewStyle = _props.viewStyle,
wrapStyle = _props.wrapStyle,
viewClass = _props.viewClass,
children = _props.children,
viewComponent = _props.viewComponent,
wrapClass = _props.wrapClass,
noresize = _props.noresize,
className = _props.className,
others = _objectWithoutProperties(_props, ['native', 'viewStyle', 'wrapStyle', 'viewClass', 'children', 'viewComponent', 'wrapClass', 'noresize', 'className']);
var _state = this.state,
moveX = _state.moveX,
moveY = _state.moveY,
sizeWidth = _state.sizeWidth,
sizeHeight = _state.sizeHeight;
/* eslint-enable */
var style = wrapStyle;
var gutter = getScrollBarWidth();
if (gutter) {
var gutterWith = '-' + gutter + 'px';
if (Array.isArray(wrapStyle)) {
style = Object.assign.apply(null, [].concat(wrapStyle, [{ marginRight: gutterWith, marginBottom: gutterWith }]));
} else {
style = Object.assign({}, wrapStyle, { marginRight: gutterWith, marginBottom: gutterWith });
}
}
var view = React.createElement(viewComponent, {
className: this.classNames('el-scrollbar__view', viewClass),
style: viewStyle,
ref: 'resize'
}, children);
var nodes = void 0;
if (!native) {
var wrap = React.createElement(
'div',
{ ref: 'wrap',
key: 0,
style: style,
onScroll: this.handleScroll.bind(this),
className: this.classNames(wrapClass, 'el-scrollbar__wrap', gutter ? '' : 'el-scrollbar__wrap--hidden-default')
},
view
);
nodes = [wrap, React.createElement(Bar, { key: 1, move: moveX, size: sizeWidth, getParentWrap: function getParentWrap() {
return _this3.wrap;
} }), React.createElement(Bar, { key: 2, move: moveY, size: sizeHeight, getParentWrap: function getParentWrap() {
return _this3.wrap;
}, vertical: true })];
} else {
nodes = [React.createElement(
'div',
{ key: 0, ref: 'wrap', className: this.classNames(wrapClass, 'el-scrollbar__wrap'), style: style },
view
)];
}
return React.createElement('div', { className: this.classNames('el-scrollbar', className) }, nodes);
};
_createClass(Scrollbar, [{
key: 'wrap',
get: function get() {
return this.refs.wrap;
}
}]);
return Scrollbar;
}(Component);
Scrollbar.propTypes = {
native: PropTypes.bool,
wrapStyle: PropTypes.object,
wrapClass: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
viewClass: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
viewStyle: PropTypes.object,
className: PropTypes.string,
viewComponent: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
noresize: PropTypes.bool
};
Scrollbar.defaultProps = {
viewComponent: 'div'
}; |
src/components/ArticleTypeSelect.js | guryanov-a/react-search | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { searchQuery } from '../api';
import Select from './Select';
import {
changeSearchOffset,
changeSearchOffsetEnd,
changeCurrentPage,
chooseArticleType,
} from "../actions";
class ArticleTypeSelect extends Component {
componentDidUpdate(prevProps) {
if(this.props.tabs !== prevProps.tabs) {
const { state, dispatch } = this.props;
searchQuery(state, dispatch);
}
}
render() {
const {
articleTypes,
handleChange,
} = this.props;
return <Select
activeValue={articleTypes.filter(articleType => articleType.isActive)[0].name}
onChange={handleChange}
options={articleTypes}
className="filter-select"
/>;
}
}
const mapStateToProps = (state) => ({
state,
articleTypes: state.articleTypes,
searchResultsLimit: state.searchResultsLimit,
});
const mergeProps = (stateProps, dispatchProps, ownProps) => {
return Object.assign({}, ownProps, stateProps, dispatchProps, {
handleChange(e) {
const { searchResultsLimit } = stateProps;
ownProps.history.push(e.target.value === 'all' ? '/' : e.target.value);
dispatchProps.dispatch(changeSearchOffset(0));
dispatchProps.dispatch(changeSearchOffsetEnd(searchResultsLimit));
dispatchProps.dispatch(changeCurrentPage(0));
dispatchProps.dispatch(chooseArticleType(e.target.value));
},
})
};
ArticleTypeSelect = withRouter(connect(
mapStateToProps,
null,
mergeProps,
)(ArticleTypeSelect));
export default ArticleTypeSelect;
|
packages/material-ui-icons/src/CreateNewFolder.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let CreateNewFolder = props =>
<SvgIcon {...props}>
<path d="M20 6h-8l-2-2H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-1 8h-3v3h-2v-3h-3v-2h3V9h2v3h3v2z" />
</SvgIcon>;
CreateNewFolder = pure(CreateNewFolder);
CreateNewFolder.muiName = 'SvgIcon';
export default CreateNewFolder;
|
docs/src/app/components/pages/components/Divider/ExampleMenu.js | xmityaz/material-ui | import React from 'react';
import Divider from 'material-ui/Divider';
import {Menu, MenuItem} from 'material-ui/Menu';
const style = {
// Without this, the menu overflows the CodeExample container.
float: 'left',
};
const DividerExampleMenu = () => (
<Menu desktop={true} style={style}>
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Help & feedback" />
<Divider />
<MenuItem primaryText="Sign out" />
</Menu>
);
export default DividerExampleMenu;
|
src/components/common/Card.js | richardstrutt/umbrella | import React from 'react';
import {View} from 'react-native';
const Card = (props) => {
return(
<View style={styles.containerStyle}>
{props.children}
</View>
);
};
const styles = {
containerStyle: {
borderWidth:1,
borderRadius:2,
borderColor:'#ddd',
borderBottomWidth:0,
shadowColor:'#000',
shadowOffset:{width:0,height:2},
shadowOpacity:0.1,
shadowRadius:2,
elevation:1,
marginLeft:5,
marginRight:5,
marginTop:10
}
};
export {Card};
|
sources/js/tos.js | lshap/streetlivesnyc | 'use strict';
import React from 'react';
module.exports.TermsOfService = React.createClass({
render: function() {
return (
<div className="StaticPage-container">
<div className="tos-content">
<div className="title">StreetlivesNYC Terms of Service</div>
<div className="subtitle">Effective Date April 23 2016</div>
<p>
StreetlivesNYC and the users of StreetlivesNYC have a mutual interest in the success of our community online. There are legal terms required for the operation of a site that hosts a community and provides a place for free speech that we both require knowledge of and must adhere to.
</p>
<p>
The user’s (your) rights and StreetlivesNYC’s (our) rights are laid out in this Terms of Service agreement ("user agreement" or "agreement") between StreetlivesNYC ("we", "our," "us") and you. This agreement sets the terms of your use of StreetlivesNYC (the Service). It's purpose is to create a legal framework intended to encourage a tolerant and equitable place for our community to grow.
</p>
<div className="subheader">Legal Contract</div>
<ul>
<li>
This agreement is a legal contract between you and us. You acknowledge that you have read, understood, and agree to be bound by the terms of this agreement. If you do not agree to this, you should not use StreetlivesNYC. Please also look at the StreetlivesNYC Privacy Policy– it explains what we collect and how we use your information.
</li>
</ul>
<div className="subtitle">Access to StreetlivesNYC</div>
<ul>
<li>
StreelivesNYC is a public platform. In order to make the site as easy as possible to use, we do not require users to ‘log-in’ or create an account to contribute to the site.
</li>
<li>
Without advance notice and at any time, we may, for violations of this agreement or for any other reason we choose:
<ul>
<li>
Suspend access to StreetlivesNYC,
</li>
<li>
Suspend or terminate your User ID (if you have created one), and/or
</li>
<li>
Remove any of your User Content from StreetlivesNYC.
</li>
</ul>
</li>
<li>
We reserve the right to monitor and moderate StreetlivesNYC in any and all areas of user content, and your use of the Service means you agree to such monitoring and moderation. At the same time, we do not guarantee we will monitor and moderate any and all areas of user content.
</li>
</ul>
<div className="subtitle">StreetlivesNYC is for your personal and community lawful use</div>
<ul>
<li>
StreetlivesNYC is designed and supported for personal use only. You may not use StreetlivesNYC to break the law, violate an individual's privacy, or infringe any person’s or entity’s intellectual property or any other proprietary rights.
</li>
</ul>
<div className="subtitle">
StreetlivesNYC is for sharing beneficial information
</div>
<ul>
<li>
StreetlivesNYC is intended to be a place for you to share your firsthand informed opinion on how you navigate New York City, its programs and services – to let each other know what works, what doesn’t and why.
<ul>
<li>
We are not responsible for any decisions you make based on something you read on StreetlivesNYC.
</li>
</ul>
</li>
</ul>
<div className="subtitle">
StreetlivesNYC isn’t a marketplace
</div>
<ul>
<li>
StreetlivesNYC is not intended to be a marketplace for any goods or services. Any content including transactions or linking to transactions are liable to be removed by our moderation.
</li>
<li>
If you connect with another user on StreetlivesNYC and conduct a transaction, be aware that StreetlivesNYC is not in any way responsible for the transaction or the outcome of that transaction and you should take great care in proceeding with any such arrangement.
</li>
<li>
Above and beyond our intent to remove any content pertaining to transactions, you may absolutely not use StreetlivesNYC to conduct or arrange to conduct transactions for any illegal goods or services.
</li>
</ul>
<div className="subtitle">
StreetlivesNYC is free
</div>
<ul>
<li>
We will never ask you for payment to use StreetlivesNYC. It is a free service and community platform
</li>
</ul>
<div className="subheader">Content</div>
<div className="subtitle">StreetlivesNYC Content</div>
<ul>
<li>
StreetlivesNYC contains or may contain graphics, text, photographs, images, video, audio, software, code, website compilation, website "look and feel," which we call "StreetlivesNYC Content." StreetlivesNYC content is protected by the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License
</li>
<li>
We grant you the right to access and distribute the StreetlivesNYC content in the manner described under this agreement:
<ul>
<li>
You are free to:
<ul>
<li>
Share — copy and redistribute the material in any medium or format
</li>
<li>
Adapt — remix, transform, and build upon the material
</li>
</ul>
</li>
<li>
Under the following terms:
<ul>
<li>
Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use
</li>
<li>
NonCommercial — You may not use the material for commercial purposes.
</li>
<li>
ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.
</li>
<li>
No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits.
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div className="subtitle">Your Content</div>
<ul>
<li>
You retain the rights to your intellectual property, copyrighted content or information that you submit to StreetlivesNYC.
</li>
<li>
You agree that having your content hosted on StreetlivesNYC places your intellectual property, copyrighted content or information in the public domain and you thereby waive any liability that StreetlivesNYC may have to protect your intellectual property, etc. from being shared without your consent.
</li>
<li>
StreetlivesNYC will attempt to contact you if we are made aware of your intellectual property, etc. being shared, so you may pursue your rights. This communication with you encompases the entire limit of StreetlivesNYC’s involvement in your pursuit of your rights to your intellectual property, etc.
</li>
<li>
You agree that you have the right to submit anything you post, and that your user content does not violate the copyright, trademark, trade secret or any other personal, intellectual or proprietary right of any other party.
</li>
<li>
If you are aware of your intellectual property etc. being shared on StreetlivesNYC without your consent, please write to us at rights@streetlives.nyc supplying a legitimate request under the terms of the DMCA as below.
</li>
<li>
Please take a look at StreetlivesNYC's Privacy Policy for an explanation of how we may use or share information submitted by you or collected from you.
</li>
</ul>
<div className="subtitle">We do not endorse User Content</div>
<ul>
<li>
We take no responsibility for, we do not expressly or implicitly endorse, and we do not assume any liability for any user content submitted by you to StreetlivesNYC.
</li>
<li>
User content does not represent the opinion of StreetlivesNYC, its founders, partners, staff or agents.
</li>
</ul>
<div className="subtitle">Links and StreetlivesNYC</div>
<ul>
<li>
StreetlivesNYC’s desire to allow users to share beneficial information including the posting of links and hyperlinks to external, third-party sites. Whilst we attempt when moderating the site to assess the legality and appropriateness of user content including links, we are not responsible for the content or actions of any third party websites or services associated with posted links.
</li>
<li>
You agree to take sole legal responsibility for any links you post, and neither this agreement nor our privacy policy applies to any content on other websites related to those links. You should consult the terms and privacy policies of those other websites to understand your rights
</li>
</ul>
<div className="subheader">StreetlivesNYC Rules</div>
<div className="subtitle">Your participation on StreetlivesNYC</div>
<ul>
<li>
You also agree to follow the StreetlivesNYC Content Guidelines. These guidelines are intended to keep people safe, protect children, keep StreetlivesNYC running, and to encourage personal responsibility for what you do on StreetlivesNYC.
</li>
</ul>
<div className="subtitle">Don’t spam the StreetlivesNYC Community</div>
<ul>
<li>
You may not post any graphics, text, photographs, images, video, audio or other material that we deem to be junk or spam. Cluttering StreetlivesNYC with this sort of content reduces the quality of information for others. For guidance, see our rules about spam
</li>
</ul>
<div className="subtitle">Don’t try to break StreetlivesNYC</div>
<ul>
<li>
You agree not to interrupt the serving of StreetlivesNYC, introduce malicious code onto StreetlivesNYC, make it difficult for anyone else to use StreetlivesNYC due to your actions, attempt to manipulate StreetlivesNYC, or assist anyone in misusing StreetlivesNYC in any way
</li>
<li>
We support the responsible reporting of security vulnerabilities. To report a StreetlivesNYC security issue, please send an email to dev@streetlives.nyc
</li>
<li>
If you produce or maintain a browser extension or application, you agree not to purposefully negate any user's actions, to delete or edit their content on StreetlivesNYC or block any Service Provider’s operational or location information.
</li>
</ul>
<div className="subtitle">Children using StreetlivesNYC</div>
<ul>
<li>
StreetlivesNYC is not directed at people under the age of 16, and StreetlivesNYC. If you know of anyone under the age of 16 who is accessing StreetlivesNYC, please contact us at rights@streetlives.nyc
</li>
</ul>
<div className="subheader">DMCA</div>
<div className="subtitle">Copyright, the DMCA, & Takedowns</div>
<ul>
<li>
We will respond to legitimate requests under the Digital Millennium Copyright Act ("DMCA"), and we retain the right to remove user content on StreetlivesNYC that we deem to be infringing the copyright of others. If you become aware of user content on StreetlivesNYC that infringes your copyright rights, you may submit a properly formatted DMCA request (see 17 U.S.C. § 512) to rights@streetlives.nyc.
</li>
<li>
Misrepresentations of infringement can result in liability for monetary damages. You may want to consult an attorney before taking any action pursuant to the DMCA. Any DMCA request should be sent to rights@streetlives.nyc. Subject line: Attn: Copyright Agent
</li>
<li>
Please send our Copyright Agent the following information:
<ul>
<li>
The electronic or physical signature of the owner of the copyright or the person authorized to act on the owner's behalf;
</li>
<li>
Identification of the copyrighted work claimed to have been infringed, or a representative list of such works;
</li>
<li>
The URL or Internet location of the materials claimed to be infringing or to be the subject of infringing activity, or information reasonably sufficient to permit us to locate the material;
</li>
<li>
Your name, address, telephone number and email address
</li>
<li>
A statement by you that you have a good faith belief that the disputed use of the material is not authorized by the copyright owner, its agent or the law; and
</li>
<li>
A statement by you, made under penalty of perjury, that the above information in your notice is accurate and that you are the copyright owner or are authorized to act on the copyright owner's behalf.
</li>
</ul>
</li>
</ul>
<div className="subtitle">Your right to file a counter-notice</div>
<ul>
<li>
If we remove your user content in response to a copyright or trademark notice, please write to us a rights@streetlives.nyc, Subject Line: Copyrighted Content Removed and we will provide you with a copy of the notice. If you believe your user content was wrongly removed due to a mistake or misidentification of the material, you can file a counter-notice with us that includes the following:
<ul>
<li>
Your physical or electronic signature;
</li>
<li>
Identification of the material that has been removed or to which access has been disabled and where the material was located online before it was removed or access to it was disabled;
</li>
<li>
A statement by you, under penalty of perjury, that you have a good faith belief that the material was removed or disabled as a result of mistake or misidentification of the material to be removed or disabled; and
</li>
<li>
Your name, address, and telephone number, and a statement that you consent to the jurisdiction of federal district court for the judicial district in which the address is located, or if your address is outside of the United States, for any judicial district in which the service provider may be found, and that you will accept service of process from the person who provided notification under DMCA 512 subsection (c)(1)(c) or an agent of such person.
</li>
</ul>
</li>
<li>
Upon receiving a counter-notice we will forward it to the complaining party and tell them we will restore your content within 10 business days. If that party does not notify us that they have filed an action to enjoin your use of that content on StreetlivesNYC before that period passes, we will consider restoring your user content to the site.
</li>
<li>
At such time as we provision User Accounts It will be StreetlivesNYC's policy to close the accounts of users we identify as repeat infringers. We apply this policy at our discretion and in appropriate circumstances, such as when a user has repeatedly been charged with infringing the copyrights or other intellectual property rights of others.
</li>
</ul>
<div className="subtitle">A few more legalities</div>
<ul>
<li>
Please read the following very carefully. Each of the following sections applies to the maximum extent permitted by law. Where jurisdictions do not allow disclaimers of implied warranties or the limitation of liability in contracts, the contents of this section may not apply.
</li>
</ul>
<div className="subtitle">Indemnity</div>
<ul>
<li>
All the things you do and all the information you submit or post to StreetlivesNYC remain your responsibility. Indemnity is basically a way of saying that you will not hold us legally liable for any of your user content or actions that infringe the law or the rights of a third party or person in any way.
</li>
<li>
Specifically, you agree to hold StreetlivesNYC, its affiliates, officers, directors, employees, agents, and third party service providers as exist now or will exist at any time in the future harmless from and defend them against any claims, costs, damages, losses, expenses, and any other liabilities, including attorneys’ fees and costs, arising out of or related to your access to or use of StreetlivesNYC, your violation of this user agreement, and/or your violation of the rights of any third party or person.
</li>
</ul>
<div className="subtitle">Disclaimer of warranties</div>
<ul>
<li>
StreetlivesNYC is provided "as is" and without warranty of any kind. To the maximum extent permitted by law, we and our affiliates and third party service providers now, or at any time in the future disclaim any and all warranties, express or implied, including (but not limited to) implied warranties of merchantability, fitness for a particular purpose, and non-infringement of proprietary rights, or any other warranty, condition, guarantee or representation, whether oral or electronic. You are solely responsible for any damage to your computer or mobile device, loss of use, or loss of your user content. We do not guarantee that StreetlivesNYC will always work properly.
</li>
</ul>
<div className="subtitle">Limitation of liability</div>
<ul>
<li>
We will not be liable for any special, consequential, indirect, incidental, punitive, reliance, or exemplary damages, whether in tort, contract, or any other legal theory, arising out of or in any way connected with this agreement or your use of or attempt to use StreetlivesNYC, including (but not limited to) damages for loss of profits, goodwill, use, or data. This limitation on liability shall not be affected even if we have been advised of the possibility of such damages. Some states do not allow for the exclusion of implied warranties or the limitation or exclusion of liability for incidental or consequential damages, so the above exclusions may not apply to you. You may have other rights that vary from state to state.
</li>
<li>
You agree to release us, our affiliates, and third-party service providers, and each associated director, employee, agents, and officers now or at any time in the future, from claims, demands and damages (actual and consequential), of every kind and nature, known and unknown, disclosed or undisclosed, arising out of or in any way connected to your use of StreetlivesNYC.
</li>
</ul>
<div className="subtitle">Governing law</div>
<ul>
<li>
We want you to enjoy StreetlivesNYC, so if you have an issue or dispute, you agree to raise it and try to resolve it with us informally. You can contact us with feedback and concerns here or by emailing us at rights@streetlives.nyc
</li>
<li>
The headings in this agreement are for convenience and do not control any of its provisions.
</li>
<li>
Any claim or dispute between you and us arising out of or relating to this user agreement, in whole or in part, shall be governed by the laws of the State of New York without respect to its conflict of laws provisions. We agree and you agree to submit to the personal jurisdiction and venue of the state and federal court located in Kings County, Brooklyn.
</li>
</ul>
<div className="subtitle">Severability and enforcement</div>
<ul>
<li>
If any provision of this user agreement is held invalid or unenforceable, that provision will be modified to the extent necessary to render it enforceable without losing its intent. If no such modification is possible, that provision will be severed from the rest of this agreement.
</li>
<li>
If we do not enforce any right or provision in this user agreement, that is not to be deemed a waiver of our right to do so in the future.
</li>
</ul>
<div className="subtitle">Changes to this Terms of Service</div>
<ul>
<li>
This Terms of Service is the entire agreement between you and us concerning StreetlivesNYC. It supersedes all prior or contemporaneous agreements between you and us. We may modify this user agreement at any time. If we make changes to this agreement that materially affect your rights, we will provide advance notice and keep this edition available as an archive on the StreetlivesNYC website. By continuing to use StreetlivesNYC after a change to this agreement, you agree to those changes.
</li>
</ul>
</div>
</div>)
}
})
|
src/svg-icons/image/photo-camera.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoCamera = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImagePhotoCamera = pure(ImagePhotoCamera);
ImagePhotoCamera.displayName = 'ImagePhotoCamera';
ImagePhotoCamera.muiName = 'SvgIcon';
export default ImagePhotoCamera;
|
node/webpack/react/piece/piece.js | wushi27/nodejs201606 | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
//small component
var Search = React.createClass({
checkSth:function(){
var inputValue = this.refs.myInput.value;
alert(inputValue);
},
render:function(){
return (
<div>
{this.props.searchType}:
<input type="text" ref="myInput"/>
<button onClick={this.checkSth}>Search</button>
</div>
);
}
});
var Page = React.createClass({
render:function(){
return(
<div>
<Search searchType="Title"></Search>
</div>
);
}
});
ReactDOM.render(
<Page />,document.getElementById('test')
); |
src/mixins/material-ui-theme.js | SRI-SAVE/react-components | /*
Copyright 2016 SRI International
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// See why this is here, there ...
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
// http://material-ui.com/#/get-started
// This is to eliminate warnings of "parent-based and owner-based contexts differ"
// https://gist.github.com/jimfb/0eb6e61f300a8c1b2ce7
import React from 'react';
import ThemeManager from 'material-ui/lib/styles/theme-manager';
import LightRawTheme from 'material-ui/lib/styles/raw-themes/light-raw-theme';
export default {
childContextTypes: {
muiTheme: React.PropTypes.object,
},
getChildContext() {
return {
muiTheme: ThemeManager.getMuiTheme(LightRawTheme),
};
},
}
|
src/pages/list.js | Lokiedu/libertysoil-site | /*
This file is a part of libertysoil.org website
Copyright (C) 2016 Loki Education (Social Enterprise)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import PropTypes from 'prop-types';
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { CommentsByCategory as CommentsByCategoryPropType } from '../prop-types/comments';
import { MapOfPosts as MapOfPostsPropType } from '../prop-types/posts';
import {
MapOfUsers as MapOfUsersPropType,
CurrentUser as CurrentUserPropType
} from '../prop-types/users';
import { API_HOST } from '../config';
import ApiClient from '../api/client';
import {
Page,
PageMain,
PageBody,
PageContent
} from '../components/page';
import CreatePost from '../components/create-post';
import Header from '../components/header';
import HeaderLogo from '../components/header-logo';
import Footer from '../components/footer';
import Sidebar from '../components/sidebar';
import SidebarAlt from '../components/sidebarAlt';
import LoadableRiver from '../components/loadable-river';
import AddedTags from '../components/post/added-tags';
import Breadcrumbs from '../components/breadcrumbs/breadcrumbs';
import SideSuggestedUsers from '../components/side-suggested-users';
import { ActionsTrigger } from '../triggers';
import { createSelector, currentUserSelector } from '../selectors';
import {
resetCreatePostForm,
updateCreatePostForm
} from '../actions/posts';
import { clearRiver } from '../actions/river';
export const LOAD_MORE_LIMIT = 4;
export class UnwrappedListPage extends React.Component {
static displayName = 'UnwrappedListPage';
static propTypes = {
comments: CommentsByCategoryPropType.isRequired,
create_post_form: PropTypes.shape({
text: PropTypes.string.isRequired
}),
current_user: CurrentUserPropType.isRequired,
is_logged_in: PropTypes.bool.isRequired,
posts: MapOfPostsPropType.isRequired,
river: PropTypes.arrayOf(PropTypes.string).isRequired,
ui: PropTypes.shape({
progress: PropTypes.shape({
loadRiverInProgress: PropTypes.boolean
})
}).isRequired,
users: MapOfUsersPropType.isRequired
};
static async fetchData(router, store, client) {
const trigger = new ActionsTrigger(client, store.dispatch);
store.dispatch(clearRiver());
await Promise.all([
trigger.loadPostRiver(),
trigger.loadPersonalizedSuggestions(),
trigger.loadUserRecentTags()
]);
}
constructor(props, ...args) {
super(props, ...args);
this.triggers = new ActionsTrigger(
new ApiClient(API_HOST),
props.dispatch
);
}
handleForceLoadPosts = async () => {
const { river } = this.props;
const res = this.triggers.loadPostRiver(river.size);
return Array.isArray(res) && res.length > LOAD_MORE_LIMIT;
}
handleAutoLoadPosts = async (isVisible) => {
if (!isVisible) {
return undefined;
}
const { river, ui } = this.props;
let displayLoadMore = true;
if (isVisible && !ui.getIn(['progress', 'loadRiverInProgress'])) {
const res = await this.triggers.loadPostRiver(river.size);
displayLoadMore = Array.isArray(res) && res.length > LOAD_MORE_LIMIT;
}
return displayLoadMore;
};
render() {
const {
current_user,
create_post_form,
resetCreatePostForm,
ui,
updateCreatePostForm,
} = this.props;
const i_am_following = this.props.following.get(current_user.get('id'));
const actions = { resetCreatePostForm, updateCreatePostForm };
return (
<div>
<Helmet title="News Feed of " />
<Header
current_user={current_user}
is_logged_in={this.props.is_logged_in}
>
<HeaderLogo />
<Breadcrumbs title="News Feed" />
</Header>
<Page>
<PageMain>
<PageBody>
<Sidebar />
<PageContent>
<CreatePost
actions={actions}
addedGeotags={create_post_form.get('geotags')}
addedHashtags={create_post_form.get('hashtags')}
addedSchools={create_post_form.get('schools')}
defaultText={create_post_form.get('text')}
triggers={this.triggers}
userRecentTags={current_user.get('recent_tags')}
/>
<LoadableRiver
comments={this.props.comments}
current_user={current_user}
loadMoreLimit={LOAD_MORE_LIMIT}
posts={this.props.posts}
river={this.props.river}
triggers={this.triggers}
ui={ui}
users={this.props.users}
waiting={ui.getIn(['progress', 'loadRiverInProgress'])}
onAutoLoad={this.handleAutoLoadPosts}
onForceLoad={this.handleForceLoadPosts}
/>
</PageContent>
<SidebarAlt>
<AddedTags
geotags={create_post_form.get('geotags')}
hashtags={create_post_form.get('hashtags')}
schools={create_post_form.get('schools')}
truncated
/>
<SideSuggestedUsers
current_user={current_user}
i_am_following={i_am_following}
triggers={this.triggers}
users={current_user.get('suggested_users')}
/>
</SidebarAlt>
</PageBody>
</PageMain>
</Page>
<Footer />
</div>
);
}
}
const selector = createSelector(
currentUserSelector,
state => state.get('comments'),
state => state.get('create_post_form'),
state => state.get('following'),
state => state.get('posts'),
state => state.get('river'),
state => state.get('schools'),
state => state.get('users'),
state => state.get('ui'),
(current_user, comments, create_post_form, following, posts, river, schools, users, ui) => ({
comments,
create_post_form,
following,
posts,
river,
schools,
users,
ui,
...current_user
})
);
const ListPage = connect(selector, dispatch => ({
dispatch,
...bindActionCreators({ resetCreatePostForm, updateCreatePostForm }, dispatch)
}))(UnwrappedListPage);
export default ListPage;
|
docs/src/app/components/pages/components/Drawer/ExampleOpenSecondary.js | IsenrichO/mui-with-arrows | import React from 'react';
import Drawer from 'material-ui/Drawer';
import AppBar from 'material-ui/AppBar';
import RaisedButton from 'material-ui/RaisedButton';
export default class DrawerOpenRightExample extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
}
handleToggle = () => this.setState({open: !this.state.open});
render() {
return (
<div>
<RaisedButton
label="Toggle Drawer"
onTouchTap={this.handleToggle}
/>
<Drawer width={200} openSecondary={true} open={this.state.open} >
<AppBar title="AppBar" />
</Drawer>
</div>
);
}
}
|
client/src/components/Room.js | egdbear/simple-chat | import React from 'react';
import { ListItem } from 'material-ui/List';
import Divider from 'material-ui/Divider';
export default class Room extends React.Component {
constructor(props) {
super(props);
this.navigate = this.navigate.bind(this);
}
navigate(roomId) {
this.props.history.push(`dashboard/${roomId}`);
}
render() {
const props = this.props;
return (
<div>
<ListItem key={props.id} primaryText={props.name} onClick={() => this.navigate(props._id)}>
</ListItem>
<Divider inset={false} />
</div>
)
}
}
|
jenkins-design-language/src/js/components/material-ui/svg-icons/editor/linear-scale.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const EditorLinearScale = (props) => (
<SvgIcon {...props}>
<path d="M19.5 9.5c-1.03 0-1.9.62-2.29 1.5h-2.92c-.39-.88-1.26-1.5-2.29-1.5s-1.9.62-2.29 1.5H6.79c-.39-.88-1.26-1.5-2.29-1.5C3.12 9.5 2 10.62 2 12s1.12 2.5 2.5 2.5c1.03 0 1.9-.62 2.29-1.5h2.92c.39.88 1.26 1.5 2.29 1.5s1.9-.62 2.29-1.5h2.92c.39.88 1.26 1.5 2.29 1.5 1.38 0 2.5-1.12 2.5-2.5s-1.12-2.5-2.5-2.5z"/>
</SvgIcon>
);
EditorLinearScale.displayName = 'EditorLinearScale';
EditorLinearScale.muiName = 'SvgIcon';
export default EditorLinearScale;
|
docs/server.js | koaninc/draft-js-plugins | /**
* NOTE: This file must be run with babel-node as Node is not yet compatible
* with all of ES6 and we also use JSX.
*/
import url from 'url';
import React from 'react';
import express from 'express';
import webpack from 'webpack';
import { renderToStaticMarkup } from 'react-dom/server';
import config from './webpack.config.dev';
import Html from './template';
/**
* Render the entire web page to a string. We use render to static markup here
* to avoid react hooking on to the document HTML that will not be managed by
* React. The body prop is a string that contains the actual document body,
* which react will hook on to.
*
* We also take this opportunity to prepend the doctype string onto the
* document.
*
* @param {object} props
* @return {string}
*/
const renderDocumentToString = (props) =>
`<!doctype html>${renderToStaticMarkup(<Html {...props} />)}`;
const app = express();
const compiler = webpack(config);
app.use('/css', express.static('buildTemplate/css'));
app.use('/images', express.static('buildTemplate/images'));
app.use('/data', express.static('buildTemplate/data'));
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
}));
app.use(require('webpack-hot-middleware')(compiler));
// Send the boilerplate HTML payload down for all get requests. Routing will be
// handled entirely client side and we don't make an effort to pre-render pages
// before they are served when in dev mode.
app.get('*', (req, res) => {
const html = renderDocumentToString({
bundle: `${config.output.publicPath}app.js`,
});
res.send(html);
});
// NOTE: url.parse can't handle URLs without a protocol explicitly defined. So
// if we parse '//localhost:8888' it doesn't work. We manually add a protocol even
// though we are only interested in the port.
const { port } = url.parse(`http:${config.output.publicPath}`);
app.listen(port, 'localhost', (err) => {
if (err) {
console.error(err); // eslint-disable-line no-console
return;
}
console.log(`Dev server listening at http://localhost:${port}`); // eslint-disable-line no-console
});
|
demo-react-redux/app/index.js | renhongl/Summary |
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer from './reducer/reducer';
import { Router, Route, browserHistory } from 'react-router';
import Dashboard from './page/dashboard';
import TestPage from './page/test';
const state = {
time: new Date(),
todo: ['看电视', '玩游戏'],
};
const store = createStore(reducer, state);
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={Dashboard} />
<Route path="/test" component={TestPage} />
</Router>
</Provider>,
document.querySelector('#app')
)
|
resources/src/js/components/Sidebar/components/NavBarBody.js | aberon10/thermomusic.com | 'use strict';
// Dependencies
import React from 'react';
import PropTypes from 'prop-types';
// Components
import NavListItems from './NavListItems';
import { addClassModal } from '../../ModalForm/utils';
const links = [
{
url: '/user',
name: 'Explorar'
},
{
url: '/music',
name: 'Tu Música'
},
{
url: '/music/top',
name: 'Top 10'
}
];
class NavBarBody extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="nav-bar__body">
<ul className="nav-list group">
<NavListItems
links={links}
typeLink="3"
/>
</ul>
<div className="group">
<a href="#" onClick={addClassModal} data-id-modal="modal-form-playlist">NUEVA PLAYLIST</a>
</div>
</div>
);
}
}
NavBarBody.defaultProps = {
linksRecentlyArtist: []
};
NavBarBody.propTypes = {
linksRecentlyArtist: PropTypes.array.isRequired
};
export default NavBarBody;
|
app/javascript/mastodon/features/ui/components/video_modal.js | abcang/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Video from 'mastodon/features/video';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Footer from 'mastodon/features/picture_in_picture/components/footer';
import { getAverageFromBlurhash } from 'mastodon/blurhash';
export default class VideoModal extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
statusId: PropTypes.string,
options: PropTypes.shape({
startTime: PropTypes.number,
autoPlay: PropTypes.bool,
defaultVolume: PropTypes.number,
}),
onClose: PropTypes.func.isRequired,
onChangeBackgroundColor: PropTypes.func.isRequired,
};
componentDidMount () {
const { media, onChangeBackgroundColor } = this.props;
const backgroundColor = getAverageFromBlurhash(media.get('blurhash'));
if (backgroundColor) {
onChangeBackgroundColor(backgroundColor);
}
}
render () {
const { media, statusId, onClose } = this.props;
const options = this.props.options || {};
return (
<div className='modal-root__modal video-modal'>
<div className='video-modal__container'>
<Video
preview={media.get('preview_url')}
frameRate={media.getIn(['meta', 'original', 'frame_rate'])}
blurhash={media.get('blurhash')}
src={media.get('url')}
currentTime={options.startTime}
autoPlay={options.autoPlay}
volume={options.defaultVolume}
onCloseVideo={onClose}
detailed
alt={media.get('description')}
/>
</div>
<div className='media-modal__overlay'>
{statusId && <Footer statusId={statusId} withOpenButton onClose={onClose} />}
</div>
</div>
);
}
}
|
app/components/ScoreBoard.js | RamonGebben/drone-fight-scoreboard | import React, { Component } from 'react';
import Fighter from './Fighter';
import Faker from 'Faker';
const defaultStartingScore = 3;
const colorPallet = ['2176ae', '57b8ff', 'b66d0d', 'fbb13c', 'fe6847'];
const startColors = getRandomColors(2);
const startState = {
fighters: [
{
score: defaultStartingScore,
inTheGame: true,
color: startColors[0],
},
{
score: defaultStartingScore,
inTheGame: true,
color: startColors[1],
}
],
gameOver: false,
winner: null,
showRules: false,
};
function getRandomColor() {
return colorPallet[Math.floor(Math.random()*colorPallet.length)];
}
function getRandomColors(amount) {
const chosenColors = [];
for (let i = 0; i < amount; i++) {
let color = getRandomColor();
if (chosenColors.includes(color)) {
color = getRandomColor();
}
chosenColors.push(color);
}
return chosenColors;
}
class ScoreBoard extends Component {
constructor(props) {
super(props);
this.state = Object.assign({}, startState);
}
onScoreClick(fighterIndex) {
const fighters = [].concat(this.state.fighters);
const fighter = fighters[fighterIndex];
fighter.score = fighter.score - 1;
if (fighter.score === 0) {
fighter.inTheGame = false;
const fightersStillInTheGame = fighters.filter(f => f.inTheGame === true);
if (fightersStillInTheGame.length === 1) {
return this.setState({ gameOver: true, winner: fightersStillInTheGame[0] });
}
}
return this.setState({ fighters });
}
onAddFighter() {
const newFighter = {
score: defaultStartingScore,
inTheGame: true,
color: getRandomColor(),
};
const colorAlreadyTakes = this.state.fighters
.map(f => f.color)
.includes(newFighter.color);
if (colorAlreadyTakes) {
newFighter.color = getRandomColor();
}
const fighters = this.state.fighters.concat(newFighter);
this.setState({ fighters });
}
resetPlayingField() {
this.setState({
fighters: [
{
score: defaultStartingScore,
inTheGame: true,
color: this.state.fighters[0].color,
},
{
score: defaultStartingScore,
inTheGame: true,
color: this.state.fighters[1].color,
}
],
gameOver: false,
winner: null,
});
}
toggleRules() {
this.setState({ showRules: !this.state.showRules });
}
render() {
return (
<div className="score-board-container">
<header />
{!this.state.gameOver ? <div className="playing-field">
{this.state.fighters.map((fighter, i) => (
<Fighter
{...fighter}
key={i}
onScoreClick={this.onScoreClick.bind(this, i)}
/>
))}
<div className="button" onClick={this.toggleRules.bind(this)}>Show rules</div>
</div> :
<div className="game-over">
<h1>Game Over</h1>
<h2>Winner:</h2>
<Fighter {...this.state.winner} />
<div className="button" onClick={this.resetPlayingField.bind(this)}>Rematch</div>
</div>
}
{this.state.showRules &&
<div className="rules">
<h3>Rules of Drone Combat</h3>
<p>Standard drone combat consists of two drones fighting head to head in a pre-defined arena. The objective is to knock the opponent’s drone to the floor while avoiding your own drone hitting the floor.</p>
<p>Combat starts with each drone ready-to-fly and idling in a designated landing zone or ring. At the sound of the buzzer, each drone lifts into the air.</p>
<p>Each player begins with 3 points. One point is deducted each time a player’s drone touches the floor. The first player to reach 0 points is declared the loser.</p>
<p>If combat results in both drones hitting the floor at the same time or within 3 seconds of each other, then both players loses a point. However, a game-winning point or “kill” point can NOT be obtained if both drones hit the floor at the same time or within 3 seconds of each other (ie. The winning drone must NOT hit the floor with 3 seconds of the losing drone hitting the floor for final kill point).</p>
<p>Each time a drone crashes, Pilots have 90 seconds to lift off again. During this time they are permitted to enter the arena to make emergency repairs, replace batteries & parts or make adjustments to their drone. Pilots have 90 seconds to get their drone flying or they are eliminated from the match. During this time the healthy drone is allowed to land and rest. If for any reason a drone hits the floor outside of the ring upon landing or otherwise crashes or can’t lift-off again, it will lose a point as if it had crashed in combat.</p>
<p>Matches end at 5 minutes. The drone with the highest score will be declared the winner. If there is a tie, the winner will be determined by tennis ball firing squad or sudden death.</p>
<div className="button" onClick={this.toggleRules.bind(this)}>Close</div>
</div>}
</div>
);
}
}
export default ScoreBoard;
|
src/components/gradients/rgb-gradient.js | mapbox/react-colorpickr | import React from 'react';
import PropTypes from 'prop-types';
import themeable from 'react-themeable';
import { autokey } from '../../autokey';
function RGBGradient({ theme, active, color, opacityLow, opacityHigh }) {
const themer = autokey(themeable(theme));
if (!active) return <noscript />;
return (
<>
<div
{...themer('gradient', `gradient${color.toUpperCase()}High`)}
style={{ opacity: opacityHigh }}
/>
<div
{...themer('gradient', `gradient${color.toUpperCase()}Low`)}
style={{ opacity: opacityLow }}
/>
</>
);
}
RGBGradient.propTypes = {
theme: PropTypes.object.isRequired,
active: PropTypes.bool.isRequired,
color: PropTypes.string.isRequired,
opacityLow: PropTypes.number.isRequired,
opacityHigh: PropTypes.number.isRequired
};
export { RGBGradient };
|
src/modules/Home/components/Users.js | YBox-POS/possys | import React from 'react';
import { Text, ScrollView, Image, View, StyleSheet, Dimensions } from 'react-native';
import styled from 'styled-components/native';
import { List, ListItem, Button} from 'react-native-elements';
import * as action from "../duck"
//获取屏幕宽高
const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;
const Users = ({ users, followUser, unfollowUser }) => (
<ScrollView
style={{
flex: 1,
}}
contentContainerStyle={{ marginBottom:100 }}
>
{/* <Image style={styles.images} source={require('../../../asset/img/a.gif')} /> */}
{Object.values(users).map(({ id, name, username, following }) => (
<ListItem
title={name}
avatar={{uri: 'https://m.jandou.com/file/images/avatar.jpg'}}
key={`user-${id}`}
onPress={() => {console.log('你点击的是列表'+id)}}
leftIcon={
{/* <Button
color={"#fff"}
iconRight
buttonStyle={{backgroundColor: '#00D9C7', borderRadius: 5}}
onPress={() => (action.deleteUser(id))}
title={"删除"}
/> */}
}
rightIcon={
<Button
color={"#fff"}
iconRight
buttonStyle={{backgroundColor: '#00D9C7', borderRadius: 5}}
onPress={() => {following ? unfollowUser(id) : followUser(id);console.log(following ? '已取消关注' : '已关注')}}
title={following ? '取消关注' : '关注'}
/>
}
/>
))}
{/* <Button
color={"#fff"}
iconRight
buttonStyle={{backgroundColor: '#FF557C', borderRadius: 5, marginTop:20}}
onPress={() => {alert("屏幕宽度:"+SCREEN_WIDTH+"\n屏幕高度:"+SCREEN_HEIGHT)}}
title={"获取屏幕宽度"}
/> */}
</ScrollView>
)
const styles = StyleSheet.create({
images: {
width: SCREEN_WIDTH,
height: 150
}
});
export default Users;
|
src/svg-icons/content/link.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentLink = (props) => (
<SvgIcon {...props}>
<path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/>
</SvgIcon>
);
ContentLink = pure(ContentLink);
ContentLink.displayName = 'ContentLink';
ContentLink.muiName = 'SvgIcon';
export default ContentLink;
|
examples/todomvc/containers/TodoApp.js | ngbrown/redux | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { Connector } from 'redux/react';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions/TodoActions';
export default class TodoApp extends Component {
render() {
return (
<Connector select={state => ({ todos: state.todos })}>
{this.renderChild}
</Connector>
);
}
renderChild({ todos, dispatch }) {
const actions = bindActionCreators(TodoActions, dispatch);
return (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
);
}
}
|
react-demos/seats-reservation/src/Section.js | konvajs/site | import React from 'react';
import { Rect, Group, Text } from './react-konva';
import SubSection from './SubSection';
import {
SECTION_TOP_PADDING,
getSectionWidth,
getSubsectionWidth,
} from './layout';
export default React.memo(
({
section,
height,
x,
y,
onHoverSeat,
onSelectSeat,
onDeselectSeat,
selectedSeatsIds,
}) => {
const containerRef = React.useRef();
// caching will boost rendering
// we just need to recache on some changes
React.useEffect(() => {
containerRef.current.cache();
}, [section, selectedSeatsIds]);
const width = getSectionWidth(section);
let lastSubsectionX = 0;
return (
<Group y={y} x={x} ref={containerRef}>
<Rect
width={width}
height={height}
fill="white"
strokeWidth={1}
stroke="lightgrey"
cornerRadius={5}
/>
{section.subsections.map((subsection) => {
const subWidth = getSubsectionWidth(subsection);
const pos = lastSubsectionX;
lastSubsectionX += subWidth;
return (
<SubSection
x={pos}
y={SECTION_TOP_PADDING}
key={subsection.name}
data={subsection}
width={subWidth}
height={height}
onHoverSeat={onHoverSeat}
onSelectSeat={onSelectSeat}
onDeselectSeat={onDeselectSeat}
selectedSeatsIds={selectedSeatsIds}
/>
);
})}
<Text
text={section.name}
height={SECTION_TOP_PADDING}
width={width}
align="center"
verticalAlign="middle"
fontSize={20}
/>
</Group>
);
}
);
|
app/components/Menu/MenuList.js | cdiezmoran/playgrounds-desktop | // @flow
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import jwtDecode from 'jwt-decode';
import $ from 'jquery';
class MenuList extends Component {
props: {
path: string
}
static redeemClick(e) {
e.preventDefault();
$('#redeemItemModal').modal();
}
render() {
const { path } = this.props;
const token = localStorage.getItem('id_token');
const currentUser = jwtDecode(token);
return (
<div className="menu-list container">
<div className="menu-category">
<span className="menu-title">Main</span>
<ul className="menu-ul">
{currentUser.isDeveloper && path === '/dashboard' &&
<p className="menu-link active"><Link to="/dashboard">Dashboard</Link></p>
}
{currentUser.isDeveloper && path !== '/dashboard' &&
<p className="menu-link"><Link to="/dashboard">Dashboard</Link></p>
}
{path === '/' &&
<p className="menu-link active"><Link to="/">Browse</Link></p>
}
{path !== '/' &&
<p className="menu-link"><Link to="/">Browse</Link></p>
}
</ul>
</div>
<div className="menu-category">
<span className="menu-title">Library</span>
<ul className="menu-ul">
{path === '/games/library' &&
<p className="menu-link active"><Link to="/games/library">Your library</Link></p>
}
{path !== '/games/library' &&
<p className="menu-link"><Link to="/games/library">Your library</Link></p>
}
<p className="menu-link"><a href="#redeem" onClick={MenuList.redeemClick}>Redeem Key</a></p>
</ul>
</div>
</div>
);
}
}
export default MenuList;
|
src/app/components/search/AllItems.js | meedan/check-web | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Search from './Search';
import ErrorBoundary from '../error/ErrorBoundary';
import { safelyParseJSON } from '../../helpers';
export default function AllItems({ routeParams }) {
return (
<ErrorBoundary component="AllItems">
<Search
searchUrlPrefix={`/${routeParams.team}/all-items`}
mediaUrlPrefix={`/${routeParams.team}/media`}
title={<FormattedMessage id="search.allClaimsTitle" defaultMessage="All items" />}
query={safelyParseJSON(routeParams.query, {})}
teamSlug={routeParams.team}
hideFields={[
'country', 'cluster_teams', 'cluster_published_reports',
]}
/>
</ErrorBoundary>
);
}
AllItems.propTypes = {
routeParams: PropTypes.shape({
team: PropTypes.string.isRequired,
query: PropTypes.string, // JSON-encoded value; can be empty/null/invalid
}).isRequired,
};
|
client/util/react-intl-test-helper.js | Skrpk/mern-sagas | /**
* Components using the react-intl module require access to the intl context.
* This is not available when mounting single components in Enzyme.
* These helper functions aim to address that and wrap a valid,
* English-locale intl context around them.
*/
import React from 'react';
import { IntlProvider, intlShape } from 'react-intl';
import Enzyme, { mount, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
// You can pass your messages to the IntlProvider. Optional: remove if unneeded.
const messages = require('../../Intl/localizationData/en');
// Create the IntlProvider to retrieve context for wrapping around.
const intlProvider = new IntlProvider({ locale: 'en', messages }, {});
export const { intl } = intlProvider.getChildContext();
/**
* When using React-Intl `injectIntl` on components, props.intl is required.
*/
const nodeWithIntlProp = node => {
return React.cloneElement(node, { intl });
};
export const shallowWithIntl = node => {
return shallow(nodeWithIntlProp(node), { context: { intl } });
};
export const mountWithIntl = node => {
return mount(nodeWithIntlProp(node), {
context: { intl },
childContextTypes: { intl: intlShape },
});
};
|
src/html.js | innocentiv/vinnocenti | import React from 'react';
let stylesStr;
if (process.env.NODE_ENV === `production`) {
try {
stylesStr = require(`!raw-loader!../public/styles.css`);
} catch (e) {
console.log(e);
}
}
module.exports = class HTML extends React.Component {
render() {
let css;
if (process.env.NODE_ENV === `production`) {
css = (
<style
id="gatsby-inlined-css"
dangerouslySetInnerHTML={{ __html: stylesStr }}
/>
);
}
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
{this.props.headComponents}
{css}
</head>
<body>
{this.props.preBodyComponents}
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: this.props.body }}
/>
{this.props.postBodyComponents}
</body>
</html>
);
}
};
|
app/react-icons/fa/volume-up.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaVolumeUp extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m18.6 7.9v24.2q0 0.6-0.4 1t-1 0.5-1-0.5l-7.4-7.4h-5.9q-0.6 0-1-0.4t-0.4-1v-8.6q0-0.6 0.4-1t1-0.4h5.9l7.4-7.4q0.4-0.5 1-0.5t1 0.5 0.4 1z m8.6 12.1q0 1.7-0.9 3.2t-2.5 2q-0.3 0.2-0.6 0.2-0.6 0-1-0.5t-0.4-1q0-0.4 0.2-0.8t0.7-0.5 0.7-0.5 0.7-0.8 0.3-1.3-0.3-1.3-0.7-0.8-0.7-0.5-0.7-0.5-0.2-0.8q0-0.6 0.4-1t1-0.5q0.3 0 0.6 0.2 1.5 0.6 2.5 2t0.9 3.2z m5.7 0q0 3.4-1.9 6.3t-5 4.2q-0.3 0.1-0.5 0.1-0.7 0-1.1-0.4t-0.4-1q0-0.9 0.9-1.3 1.2-0.7 1.7-1 1.6-1.2 2.5-3t1-3.9-1-3.9-2.5-3q-0.5-0.3-1.7-1-0.9-0.4-0.9-1.3 0-0.6 0.4-1t1-0.4q0.3 0 0.6 0.1 3.1 1.3 5 4.2t1.9 6.3z m5.7 0q0 5.1-2.8 9.4t-7.5 6.4q-0.3 0.1-0.6 0.1-0.6 0-1-0.5t-0.4-1q0-0.8 0.8-1.3 0.2-0.1 0.5-0.2t0.5-0.2q1.1-0.6 1.9-1.2 2.7-2 4.2-5t1.6-6.5-1.6-6.4-4.2-5.1q-0.8-0.6-1.9-1.2-0.1 0-0.5-0.2t-0.5-0.2q-0.8-0.5-0.8-1.3 0-0.6 0.4-1t1-0.5q0.3 0 0.6 0.1 4.7 2.1 7.5 6.4t2.8 9.4z"/></g>
</IconBase>
);
}
}
|
demo/footer/footer.js | Graf009/react-mdl | import React from 'react';
import ReactDOM from 'react-dom';
import { Footer, Section, DropDownSection, LinkList } from '../../src/Footer';
class Demo extends React.Component {
render() {
return (
<div>
<Footer size="mega">
<Section type="middle">
<DropDownSection title="Features">
<LinkList>
<a href="#">About</a>
<a href="#">Terms</a>
<a href="#">Partners</a>
<a href="#">Updates</a>
</LinkList>
</DropDownSection>
<DropDownSection title="Details">
<LinkList>
<a href="#">Specs</a>
<a href="#">Tools</a>
<a href="#">Resources</a>
</LinkList>
</DropDownSection>
<DropDownSection title="Technology">
<LinkList>
<a href="#">How it works</a>
<a href="#">Patterns</a>
<a href="#">Usage</a>
<a href="#">Products</a>
<a href="#">Contracts</a>
</LinkList>
</DropDownSection>
<DropDownSection title="FAQ">
<LinkList>
<a href="#">Questions</a>
<a href="#">Answers</a>
<a href="#">Contact Us</a>
</LinkList>
</DropDownSection>
</Section>
<Section type="bottom" logo="Title">
<LinkList>
<a href="#">Help</a>
<a href="#">Privacy & Terms</a>
</LinkList>
</Section>
</Footer>
<br/><br/><br/>
<Footer size="mini">
<Section type="left" logo="Title">
<LinkList>
<a href="#">Help</a>
<a href="#">Privacy & Terms</a>
</LinkList>
</Section>
</Footer>
</div>
);
}
}
ReactDOM.render(<Demo />, document.getElementById('app'));
|
src/carousel.js | bpicolo/nuka-carousel | 'use strict';
import React from 'react';
import tweenState from 'react-tween-state';
import decorators from './decorators';
import assign from 'object-assign';
import ExecutionEnvironment from 'exenv';
React.initializeTouchEvents(true);
const addEvent = function(elem, type, eventHandle) {
if (elem == null || typeof (elem) === 'undefined') {
return;
}
if (elem.addEventListener) {
elem.addEventListener(type, eventHandle, false);
} else if (elem.attachEvent) {
elem.attachEvent('on' + type, eventHandle);
} else {
elem['on'+type] = eventHandle;
}
};
const removeEvent = function(elem, type, eventHandle) {
if (elem == null || typeof (elem) === 'undefined') {
return;
}
if (elem.removeEventListener) {
elem.removeEventListener(type, eventHandle, false);
} else if (elem.detachEvent) {
elem.detachEvent('on' + type, eventHandle);
} else {
elem['on'+type] = null;
}
};
const Carousel = React.createClass({
displayName: 'Carousel',
mixins: [tweenState.Mixin],
propTypes: {
cellAlign: React.PropTypes.oneOf(['left', 'center', 'right']),
cellSpacing: React.PropTypes.number,
data: React.PropTypes.func,
decorators: React.PropTypes.array,
dragging: React.PropTypes.bool,
easing: React.PropTypes.string,
edgeEasing: React.PropTypes.string,
framePadding: React.PropTypes.string,
initialSlideHeight: React.PropTypes.number,
initialSlideWidth: React.PropTypes.number,
slidesToShow: React.PropTypes.number,
slidesToScroll: React.PropTypes.number,
slideWidth: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]),
speed: React.PropTypes.number,
vertical: React.PropTypes.bool,
width: React.PropTypes.string
},
getDefaultProps() {
return {
cellAlign: 'left',
cellSpacing: 0,
data: function() {},
decorators: decorators,
dragging: true,
easing: 'easeOutCirc',
edgeEasing: 'easeOutElastic',
framePadding: '0px',
slidesToShow: 1,
slidesToScroll: 1,
slideWidth: 1,
speed: 500,
vertical: false,
width: '100%'
}
},
getInitialState() {
return {
currentSlide: 0,
dragging: false,
frameWidth: 0,
left: 0,
top: 0,
slideCount: 0,
slideWidth: 0
}
},
componentWillMount() {
this.setInitialDimensions();
},
componentDidMount() {
this.setDimensions();
this.bindEvents();
this.setExternalData();
},
componentWillReceiveProps(nextProps) {
this.setDimensions();
},
componentWillUnmount() {
this.unbindEvents();
},
render() {
var self = this;
var children = React.Children.count(this.props.children) > 1 ? this.formatChildren(this.props.children) : this.props.children;
return (
<div className={['slider', this.props.className || ''].join(' ')} ref="slider" style={assign(this.getSliderStyles(), this.props.style || {})}>
<div className="slider-frame"
ref="frame"
style={this.getFrameStyles()}
{...this.getTouchEvents()}
{...this.getMouseEvents()}
onClick={this.handleClick}>
<ul className="slider-list" ref="list" style={this.getListStyles()}>
{children}
</ul>
</div>
{this.props.decorators ?
this.props.decorators.map(function(Decorator, index) {
return (
<div
style={assign(self.getDecoratorStyles(Decorator.position), Decorator.style || {})}
className={'slider-decorator-' + index}
key={index}>
<Decorator.component
currentSlide={self.state.currentSlide}
slideCount={self.state.slideCount}
slidesToShow={self.props.slidesToShow}
slidesToScroll={self.props.slidesToScroll}
nextSlide={self.nextSlide}
previousSlide={self.previousSlide}
goToSlide={self.goToSlide} />
</div>
)
})
: null}
<style type="text/css" dangerouslySetInnerHTML={{__html: self.getStyleTagStyles()}}/>
</div>
)
},
// Touch Events
touchObject: {},
getTouchEvents() {
var self = this;
return {
onTouchStart(e) {
self.touchObject = {
startX: event.touches[0].pageX,
startY: event.touches[0].pageY
}
},
onTouchMove(e) {
var direction = self.swipeDirection(
self.touchObject.startX,
e.touches[0].pageX,
self.touchObject.startY,
e.touches[0].pageY
);
if (direction !== 0) {
e.preventDefault();
}
self.touchObject = {
startX: self.touchObject.startX,
startY: self.touchObject.startY,
endX: e.touches[0].pageX,
endY: e.touches[0].pageY,
length: Math.round(Math.sqrt(Math.pow(e.touches[0].pageX - self.touchObject.startX, 2))),
direction: direction
}
self.setState({
left: self.props.vertical ? 0 : (self.state.slideWidth * self.state.currentSlide + (self.touchObject.length * self.touchObject.direction)) * -1,
top: self.props.vertical ? (self.state.slideWidth * self.state.currentSlide + (self.touchObject.length * self.touchObject.direction)) * -1 : 0
});
},
onTouchEnd(e) {
self.handleSwipe(e);
},
onTouchCancel(e) {
self.handleSwipe(e);
}
}
},
clickSafe: true,
getMouseEvents() {
var self = this;
if (this.props.dragging === false) {
return null;
}
return {
onMouseDown(e) {
self.touchObject = {
startX: e.clientX,
startY: e.clientY
};
self.setState({
dragging: true
});
},
onMouseMove(e) {
if (!self.state.dragging) {
return;
}
var direction = self.swipeDirection(
self.touchObject.startX,
e.clientX,
self.touchObject.startY,
e.clientY
);
if (direction !== 0) {
e.preventDefault();
}
var length = self.props.vertical ? Math.round(Math.sqrt(Math.pow(e.clientY - self.touchObject.startY, 2)))
: Math.round(Math.sqrt(Math.pow(e.clientX - self.touchObject.startX, 2)))
self.touchObject = {
startX: self.touchObject.startX,
startY: self.touchObject.startY,
endX: e.clientX,
endY: e.clientY,
length: length,
direction: direction
};
self.setState({
left: self.props.vertical ? 0 : self.getTargetLeft(self.touchObject.length * self.touchObject.direction),
top: self.props.vertical ? self.getTargetLeft(self.touchObject.length * self.touchObject.direction) : 0
});
},
onMouseUp(e) {
if (!self.state.dragging) {
return;
}
self.handleSwipe(e);
},
onMouseLeave(e) {
if (!self.state.dragging) {
return;
}
self.handleSwipe(e);
}
}
},
handleClick(e) {
if (this.clickSafe === true) {
e.preventDefault();
e.stopPropagation();
e.nativeEvent.stopPropagation();
}
},
handleSwipe(e) {
if (typeof (this.touchObject.length) !== 'undefined' && this.touchObject.length > 44) {
this.clickSafe = true;
} else {
this.clickSafe = false;
}
if (this.touchObject.length > (this.state.slideWidth / this.props.slidesToShow) / 5) {
if (this.touchObject.direction === 1) {
if (this.state.currentSlide >= React.Children.count(this.props.children) - this.props.slidesToScroll) {
this.animateSlide(tweenState.easingTypes[this.props.edgeEasing]);
} else {
this.nextSlide();
}
} else if (this.touchObject.direction === -1) {
if (this.state.currentSlide <= 0) {
this.animateSlide(tweenState.easingTypes[this.props.edgeEasing]);
} else {
this.previousSlide();
}
}
} else {
this.goToSlide(this.state.currentSlide);
}
this.touchObject = {};
this.setState({
dragging: false
});
},
swipeDirection(x1, x2, y1, y2) {
var xDist, yDist, r, swipeAngle;
xDist = x1 - x2;
yDist = y1 - y2;
r = Math.atan2(yDist, xDist);
swipeAngle = Math.round(r * 180 / Math.PI);
if (swipeAngle < 0) {
swipeAngle = 360 - Math.abs(swipeAngle);
}
if ((swipeAngle <= 45) && (swipeAngle >= 0)) {
return 1;
}
if ((swipeAngle <= 360) && (swipeAngle >= 315)) {
return 1;
}
if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
return -1;
}
if (this.props.vertical === true) {
if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
return 1;
} else {
return -1;
}
}
return 0;
},
// Action Methods
goToSlide(index) {
var self = this;
if (index >= React.Children.count(this.props.children) || index < 0) {
return;
}
this.setState({
currentSlide: index
}, function() {
self.animateSlide();
self.setExternalData();
});
},
nextSlide() {
var self = this;
if ((this.state.currentSlide + this.props.slidesToScroll) >= React.Children.count(this.props.children)) {
return;
}
this.setState({
currentSlide: this.state.currentSlide + this.props.slidesToScroll
}, function() {
self.animateSlide();
self.setExternalData();
});
},
previousSlide() {
var self = this;
if ((this.state.currentSlide - this.props.slidesToScroll) < 0) {
return;
}
this.setState({
currentSlide: this.state.currentSlide - this.props.slidesToScroll
}, function() {
self.animateSlide();
self.setExternalData();
});
},
// Animation
animateSlide(easing, duration, endValue) {
this.tweenState(this.props.vertical ? 'top' : 'left', {
easing: easing || tweenState.easingTypes[this.props.easing],
duration: duration || this.props.speed,
endValue: endValue || this.getTargetLeft()
});
},
getTargetLeft(touchOffset) {
var offset;
switch (this.props.cellAlign) {
case 'left': {
offset = 0;
offset -= this.props.cellSpacing * (this.state.currentSlide);
break;
}
case 'center': {
offset = (this.state.frameWidth - this.state.slideWidth) / 2;
offset -= this.props.cellSpacing * (this.state.currentSlide);
break;
}
case 'right': {
offset = this.state.frameWidth - this.state.slideWidth;
offset -= this.props.cellSpacing * (this.state.currentSlide);
break;
}
}
if (this.props.vertical) {
offset = offset / 2;
}
offset -= touchOffset || 0;
return ((this.state.slideWidth * this.state.currentSlide) - offset) * -1;
},
// Bootstrapping
bindEvents() {
var self = this;
if (ExecutionEnvironment.canUseDOM) {
addEvent(window, 'resize', self.onResize);
addEvent(document, 'readystatechange', self.onReadyStateChange);
}
},
onResize() {
this.setDimensions();
},
onReadyStateChange(event) {
this.setDimensions();
},
unbindEvents() {
var self = this;
if (ExecutionEnvironment.canUseDOM) {
removeEvent(window, 'resize', self.onResize);
removeEvent(document, 'readystatechange', self.onReadyStateChange);
}
},
formatChildren(children) {
var self = this;
return React.Children.map(children, function(child, index) {
return <li className="slider-slide" style={self.getSlideStyles()} key={index}>{child}</li>
});
},
setInitialDimensions() {
var self = this, slideWidth, frameWidth, frameHeight, slideHeight;
slideWidth = this.props.vertical ? (this.props.initialSlideHeight || 0) : (this.props.initialSlideWidth || 0);
slideHeight = this.props.initialSlideHeight ? this.props.initialSlideHeight * this.props.slidesToShow : 0;
frameHeight = slideHeight + ((this.props.cellSpacing / 2) * (this.props.slidesToShow - 1));
this.setState({
frameWidth: this.props.vertical ? frameHeight : '100%',
slideCount: React.Children.count(this.props.children),
slideWidth: slideWidth
}, function() {
self.setLeft();
self.setExternalData();
});
},
setDimensions() {
var self = this, slideWidth, firstSlide, frame, frameHeight, slideHeight;
frame = React.findDOMNode(this.refs.frame);
firstSlide = frame.childNodes[0].childNodes[0];
if (firstSlide) {
firstSlide.style.height = 'auto';
slideHeight = firstSlide.offsetHeight * this.props.slidesToShow;
} else {
slideHeight = 100;
}
if (typeof this.props.slideWidth !== 'number') {
slideWidth = parseInt(this.props.slideWidth);
} else {
if (this.props.vertical) {
slideWidth = (slideHeight / this.props.slidesToShow) * this.props.slideWidth;
} else {
slideWidth = (frame.offsetWidth / this.props.slidesToShow) * this.props.slideWidth;
}
}
if (!this.props.vertical) {
slideWidth -= this.props.cellSpacing * ((100 - (100 / this.props.slidesToShow)) / 100);
}
frameHeight = slideHeight + ((this.props.cellSpacing / 2) * (this.props.slidesToShow - 1));
this.setState({
frameWidth: this.props.vertical ? frameHeight : frame.offsetWidth,
slideCount: React.Children.count(this.props.children),
slideWidth: slideWidth,
left: this.props.vertical ? 0 : this.getTargetLeft(),
top: this.props.vertical ? this.getTargetLeft() : 0
}, function() {
self.setLeft()
});
},
setLeft() {
this.setState({
left: this.props.vertical ? 0 : this.getTargetLeft(),
top: this.props.vertical ? this.getTargetLeft() : 0
})
},
// Data
setExternalData() {
if (this.props.data) {
this.props.data();
}
},
// Styles
getListStyles() {
var listWidth = this.state.slideWidth * React.Children.count(this.props.children);
var spacingOffset = this.props.cellSpacing * React.Children.count(this.props.children);
return {
position: 'relative',
display: 'block',
top: this.getTweeningValue('top'),
left: this.getTweeningValue('left'),
margin: this.props.vertical ? (this.props.cellSpacing / 2) * -1 + 'px 0px'
: '0px ' + (this.props.cellSpacing / 2) * -1 + 'px',
padding: 0,
height: this.props.vertical ? listWidth + spacingOffset : 'auto',
width: this.props.vertical ? 'auto' : listWidth + spacingOffset,
cursor: this.state.dragging === true ? 'pointer' : 'inherit',
transform: 'translate3d(0, 0, 0)',
WebkitTransform: 'translate3d(0, 0, 0)',
boxSizing: 'border-box',
MozBoxSizing: 'border-box'
}
},
getFrameStyles() {
return {
position: 'relative',
display: 'block',
overflow: 'hidden',
height: this.props.vertical ? this.state.frameWidth || 'initial' : 'auto',
margin: this.props.framePadding,
padding: 0,
transform: 'translate3d(0, 0, 0)',
WebkitTransform: 'translate3d(0, 0, 0)',
boxSizing: 'border-box',
MozBoxSizing: 'border-box'
}
},
getSlideStyles() {
return {
display: this.props.vertical ? 'block' : 'inline-block',
listStyleType: 'none',
verticalAlign: 'top',
width: this.props.vertical ? '100%' : this.state.slideWidth,
height: 'auto',
boxSizing: 'border-box',
MozBoxSizing: 'border-box',
marginLeft: this.props.vertical ? 'auto' : this.props.cellSpacing / 2,
marginRight: this.props.vertical ? 'auto' : this.props.cellSpacing / 2,
marginTop: this.props.vertical ? this.props.cellSpacing / 2 : 'auto',
marginBottom: this.props.vertical ? this.props.cellSpacing / 2 : 'auto'
}
},
getSliderStyles() {
return {
position: 'relative',
display: 'block',
width: this.props.width,
height: 'auto',
boxSizing: 'border-box',
MozBoxSizing: 'border-box',
visibility: this.state.slideWidth ? 'visible' : 'hidden'
}
},
getStyleTagStyles() {
return '.slider-slide > img {width: 100%; display: block;}'
},
getDecoratorStyles(position) {
switch (position) {
case 'TopLeft': {
return {
position: 'absolute',
top: 0,
left: 0
}
}
case 'TopCenter': {
return {
position: 'absolute',
top: 0,
left: '50%',
transform: 'translateX(-50%)',
WebkitTransform: 'translateX(-50%)'
}
}
case 'TopRight': {
return {
position: 'absolute',
top: 0,
right: 0
}
}
case 'CenterLeft': {
return {
position: 'absolute',
top: '50%',
left: 0,
transform: 'translateY(-50%)',
WebkitTransform: 'translateY(-50%)'
}
}
case 'CenterCenter': {
return {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%,-50%)',
WebkitTransform: 'translate(-50%, -50%)'
}
}
case 'CenterRight': {
return {
position: 'absolute',
top: '50%',
right: 0,
transform: 'translateY(-50%)',
WebkitTransform: 'translateY(-50%)'
}
}
case 'BottomLeft': {
return {
position: 'absolute',
bottom: 0,
left: 0
}
}
case 'BottomCenter': {
return {
position: 'absolute',
bottom: 0,
left: '50%',
transform: 'translateX(-50%)',
WebkitTransform: 'translateX(-50%)'
}
}
case 'BottomRight': {
return {
position: 'absolute',
bottom: 0,
right: 0
}
}
default: {
return {
position: 'absolute',
top: 0,
left: 0
}
}
}
}
});
Carousel.ControllerMixin = {
getInitialState() {
return {
carousels: {}
}
},
setCarouselData(carousel) {
var data = this.state.carousels;
data[carousel] = this.refs[carousel];
this.setState({
carousels: data
});
}
}
export default Carousel;
|
app/javascript/mastodon/components/icon_button.js | pinfort/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Icon from 'mastodon/components/icon';
import AnimatedNumber from 'mastodon/components/animated_number';
export default class IconButton extends React.PureComponent {
static propTypes = {
className: PropTypes.string,
title: PropTypes.string.isRequired,
icon: PropTypes.string.isRequired,
onClick: PropTypes.func,
onMouseDown: PropTypes.func,
onKeyDown: PropTypes.func,
onKeyPress: PropTypes.func,
size: PropTypes.number,
active: PropTypes.bool,
pressed: PropTypes.bool,
expanded: PropTypes.bool,
style: PropTypes.object,
activeStyle: PropTypes.object,
disabled: PropTypes.bool,
inverted: PropTypes.bool,
animate: PropTypes.bool,
overlay: PropTypes.bool,
tabIndex: PropTypes.string,
counter: PropTypes.number,
obfuscateCount: PropTypes.bool,
};
static defaultProps = {
size: 18,
active: false,
disabled: false,
animate: false,
overlay: false,
tabIndex: '0',
};
state = {
activate: false,
deactivate: false,
}
componentWillReceiveProps (nextProps) {
if (!nextProps.animate) return;
if (this.props.active && !nextProps.active) {
this.setState({ activate: false, deactivate: true });
} else if (!this.props.active && nextProps.active) {
this.setState({ activate: true, deactivate: false });
}
}
handleClick = (e) => {
e.preventDefault();
if (!this.props.disabled) {
this.props.onClick(e);
}
}
handleKeyPress = (e) => {
if (this.props.onKeyPress && !this.props.disabled) {
this.props.onKeyPress(e);
}
}
handleMouseDown = (e) => {
if (!this.props.disabled && this.props.onMouseDown) {
this.props.onMouseDown(e);
}
}
handleKeyDown = (e) => {
if (!this.props.disabled && this.props.onKeyDown) {
this.props.onKeyDown(e);
}
}
render () {
const style = {
fontSize: `${this.props.size}px`,
width: `${this.props.size * 1.28571429}px`,
height: `${this.props.size * 1.28571429}px`,
lineHeight: `${this.props.size}px`,
...this.props.style,
...(this.props.active ? this.props.activeStyle : {}),
};
const {
active,
className,
disabled,
expanded,
icon,
inverted,
overlay,
pressed,
tabIndex,
title,
counter,
obfuscateCount,
} = this.props;
const {
activate,
deactivate,
} = this.state;
const classes = classNames(className, 'icon-button', {
active,
disabled,
inverted,
activate,
deactivate,
overlayed: overlay,
'icon-button--with-counter': typeof counter !== 'undefined',
});
if (typeof counter !== 'undefined') {
style.width = 'auto';
}
return (
<button
aria-label={title}
aria-pressed={pressed}
aria-expanded={expanded}
title={title}
className={classes}
onClick={this.handleClick}
onMouseDown={this.handleMouseDown}
onKeyDown={this.handleKeyDown}
onKeyPress={this.handleKeyPress}
style={style}
tabIndex={tabIndex}
disabled={disabled}
>
<Icon id={icon} fixedWidth aria-hidden='true' /> {typeof counter !== 'undefined' && <span className='icon-button__counter'><AnimatedNumber value={counter} obfuscate={obfuscateCount} /></span>}
</button>
);
}
}
|
src/components/Nav.js | tableau-app/app | import React from 'react';
import { Link, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import Headroom from 'react-headroom';
import styled from 'styled-components';
import FlatButton from 'material-ui/FlatButton';
import Logout from './Logout';
const Title = styled.div`
font-size: 2em;
font-family: 'Petit Formal Script', cursive;
`;
const Div = styled.div`
background: #eee;
padding: 10px;
font-size: 1.25em;
font-weight: bold;
font-family: 'Petit Formal Script', cursive;
`;
const SignoutWrapper = styled.div`
text-align: right;
font-family: 'Raleway', sans-serif;
`;
const ButtonStyle = {
width: '150px',
height: '50px',
fontFamily: 'Raleway, sans-serif',
};
const Username = ({ name }) => (
<span> {name} </span>
);
function Nav({user, posts}) {
return (
<Headroom >
<Div>
<Title>
<h1><Link to="/feed">Tableau</Link></h1>
</Title>
<SignoutWrapper>
<Link to="/AddPic"><FlatButton style={ButtonStyle}>Upload</FlatButton></Link>
{user ? <Username style={{ margin: '0 5px'}} name={user.username} /> : <Redirect to="/" />}
<Logout />
</SignoutWrapper>
</Div>
</Headroom>
);
}
const mapStateToProps = state => ({ user: state.user });
export default connect(
mapStateToProps
)(Nav);
|
src/Parser/Warlock/Demonology/Modules/Items/T20_2set.js | enragednuke/WoWAnalyzer | import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
const CALL_DREADSTALKERS_COOLDOWN = 15000;
class T20_2set extends Analyzer {
static dependencies = {
combatants: Combatants,
};
_expectedCooldownEnd = null;
procs = 0;
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id);
}
on_byPlayer_cast(event) {
if (event.ability.guid !== SPELLS.CALL_DREADSTALKERS.id) {
return;
}
if (this._expectedCooldownEnd && event.timestamp < this._expectedCooldownEnd) {
this.procs += 1;
}
this._expectedCooldownEnd = event.timestamp + CALL_DREADSTALKERS_COOLDOWN;
}
item() {
return {
id: `spell-${SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id}`,
icon: <SpellIcon id={SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id} />,
title: <SpellLink id={SPELLS.WARLOCK_DEMO_T20_2P_BONUS.id} />,
result: <span>{this.procs} resets of <SpellLink id={SPELLS.CALL_DREADSTALKERS.id} /> cooldown.</span>,
};
}
}
export default T20_2set;
|
app/javascript/mastodon/components/modal_root.js | KnzkDev/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class ModalRoot extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
onClose: PropTypes.func.isRequired,
};
state = {
revealed: !!this.props.children,
};
activeElement = this.state.revealed ? document.activeElement : null;
handleKeyUp = (e) => {
if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27)
&& !!this.props.children) {
this.props.onClose();
}
}
componentDidMount () {
window.addEventListener('keyup', this.handleKeyUp, false);
}
componentWillReceiveProps (nextProps) {
if (!!nextProps.children && !this.props.children) {
this.activeElement = document.activeElement;
this.getSiblings().forEach(sibling => sibling.setAttribute('inert', true));
} else if (!nextProps.children) {
this.setState({ revealed: false });
}
if (!nextProps.children && !!this.props.children) {
this.activeElement.focus();
this.activeElement = null;
}
}
componentDidUpdate (prevProps) {
if (!this.props.children && !!prevProps.children) {
this.getSiblings().forEach(sibling => sibling.removeAttribute('inert'));
}
if (this.props.children) {
requestAnimationFrame(() => {
this.setState({ revealed: true });
});
}
}
componentWillUnmount () {
window.removeEventListener('keyup', this.handleKeyUp);
}
getSiblings = () => {
return Array(...this.node.parentElement.childNodes).filter(node => node !== this.node);
}
setRef = ref => {
this.node = ref;
}
render () {
const { children, onClose } = this.props;
const { revealed } = this.state;
const visible = !!children;
if (!visible) {
return (
<div className='modal-root' ref={this.setRef} style={{ opacity: 0 }} />
);
}
return (
<div className='modal-root' ref={this.setRef} style={{ opacity: revealed ? 1 : 0 }}>
<div style={{ pointerEvents: visible ? 'auto' : 'none' }}>
<div role='presentation' className='modal-root__overlay' onClick={onClose} />
<div role='dialog' className='modal-root__container'>{children}</div>
</div>
</div>
);
}
}
|
app/components/Menu.js | ikhsanalatsary/react-mini-shop | import React from 'react';
import { Nav, Navbar, NavItem, NavDropdown, MenuItem, FormGroup, FormControl } from 'react-bootstrap';
import { Link, IndexLink } from 'react-router';
const styles = {
textDecoration: 'none',
textTransform: 'uppercase',
fontWeight: 800,
fontSize: 20 + 'px',
color: '#08489D'
}
const Menu = (props) => {
return (
<Navbar fixedTop>
<Navbar.Header>
<Navbar.Brand>
<a style={styles} href='#'>
React Mini Shop
</a>
</Navbar.Brand>
</Navbar.Header>
<Navbar.Form pullLeft>
<FormGroup>
<FormControl className='search'
type="text" placeholder="Search"
onKeyPress={props.onSearch}/>
</FormGroup>
</Navbar.Form>
<Nav pullRight>
<NavItem eventKey={1} href="#cart">
<button>
<i className="ion-bag"></i>
</button>
</NavItem>
<NavDropdown eventKey={3} title="" id="basic-nav-dropdown">
<MenuItem eventKey={3.1} href='#category/phone'>
Phone
</MenuItem>
<MenuItem eventKey={3.2} href='#category/accessories'>
Accessories
</MenuItem>
<MenuItem eventKey={3.3} href='#category/pad'>
Pad
</MenuItem>
</NavDropdown>
</Nav>
</Navbar>
);
}
export default Menu;
|
docs/src/app/components/pages/components/Badge/ExampleSimple.js | ngbrown/material-ui | import React from 'react';
import Badge from 'material-ui/Badge';
import IconButton from 'material-ui/IconButton';
import NotificationsIcon from 'material-ui/svg-icons/social/notifications';
const BadgeExampleSimple = () => (
<div>
<Badge
badgeContent={4}
primary={true}
>
<NotificationsIcon />
</Badge>
<Badge
badgeContent={10}
secondary={true}
badgeStyle={{top: 12, right: 12}}
>
<IconButton tooltip="Notifications">
<NotificationsIcon />
</IconButton>
</Badge>
</div>
);
export default BadgeExampleSimple;
|
src/ui/sidebar/component-inspection/ComponentInspector.js | circuitsim/circuit-simulator | import React from 'react';
import radium from 'radium';
import Color from 'color';
import R from 'ramda';
import EditNumeric from './editable-types/Number';
import EditTypeSelect from './editable-types/TypeSelect';
import Button from '../../components/Button';
import camelToSpace from '../../utils/camelToSpace';
import CircuitComponents from '../../diagram/components';
const lookupComponent = viewProps => CircuitComponents[viewProps.typeID];
const { PropTypes } = React;
const lighten = s => new Color(s).lighten(0.2).rgbString();
const darken = s => new Color(s).darken(0.2).rgbString();
const getStyles = ({COLORS, STYLES}) => ({
container: {
display: 'flex',
padding: '10px',
margin: '5px 5px',
backgroundColor: COLORS.insetBackground,
borderRadius: '4px',
boxShadow: [
`inset 0.5px 0.5px 1px 0px ${darken(COLORS.insetBackground)}`,
`inset -0.5px -0.5px 1px 0px ${lighten(COLORS.insetBackground)}`,
`-0.5px -0.5px 1px 0px ${darken(COLORS.background)}`,
`0.5px 0.75px 0.75px 0px ${lighten(COLORS.background)}`
].join(', ')
},
outerBase: {
display: 'flex',
flexDirection: 'column',
width: '100%',
flexGrow: '1'
},
content: {
outer: {
justifyContent: 'space-around',
alignItems: 'flex-start'
}
},
empty: {
outer: {
justifyContent: 'center',
alignItems: 'center'
},
inner: {
alignSelf: 'center'
}
},
title: STYLES.title
});
class ComponentInspector extends React.Component {
constructor(props) {
super(props);
this.onEditComponent = this.onEditComponent.bind(this);
this.handleDelete = this.handleDelete.bind(this);
}
onEditComponent(editable, value) {
const {id} = this.props.selectedComponent;
this.props.oneditComponent(id, editable, value);
}
handleDelete() {
this.props.onDeleteComponent(this.props.selectedComponent.id);
}
render() {
const {
selectedComponent,
style
} = this.props;
const styles = getStyles(this.context.theme);
return (
<div style={R.merge(style, styles.container)}>
{(() => {
if (selectedComponent) {
const { typeID, editables } = selectedComponent;
const { editablesSchema } = lookupComponent(selectedComponent);
// these control which editables are shown
const typeSelectors = R.pickBy((schema) => schema.type === 'type-select', editablesSchema);
const editableNames = R.isEmpty(typeSelectors)
? R.keys(editables)
: R.pipe(
R.mapObjIndexed((selector, key) => {
return [
key,
selector.options[editables[key].value]
];
}),
R.values,
R.flatten
)(typeSelectors);
const editComponents = editableNames.map(editableName => {
let EditComponent;
switch (editablesSchema[editableName].type) {
case 'number': {
EditComponent = EditNumeric;
break;
}
case 'type-select': {
EditComponent = EditTypeSelect;
break;
}
default:
return null;
}
return (
<EditComponent
key={editableName}
editable={editableName}
value={editables[editableName].value}
componentId={selectedComponent.id}
unit={editablesSchema[editableName].unit}
onChangeValue={this.onEditComponent}
bounds={editablesSchema[editableName].bounds}
options={R.keys(editablesSchema[editableName].options)}
/>
);
});
return (
<div style={R.merge(styles.outerBase, styles.content.outer)}>
<div style={styles.title}>
{camelToSpace(typeID)}
</div>
{editComponents}
<Button style={styles.button}
onClick={this.handleDelete}
danger
>
<span>Delete</span>
</Button>
</div>
);
} else {
return (
<div style={R.merge(styles.outerBase, styles.empty.outer)}>
<span style={styles.empty.inner}>No component selected</span>
</div>
);
}
})()}
</div>
);
}
}
ComponentInspector.propTypes = {
style: PropTypes.object,
// state
selectedComponent: PropTypes.shape({
typeID: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
editables: PropTypes.object
}),
// action creators
oneditComponent: PropTypes.func.isRequired,
onDeleteComponent: PropTypes.func.isRequired
};
ComponentInspector.contextTypes = {
theme: PropTypes.object.isRequired
};
export default radium(ComponentInspector);
|
src/BreadcrumbItem.js | albertojacini/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import SafeAnchor from './SafeAnchor';
import warning from 'react/lib/warning';
const BreadcrumbItem = React.createClass({
propTypes: {
/**
* If set to true, renders `span` instead of `a`
*/
active: React.PropTypes.bool,
/**
* HTML id for the wrapper `li` element
*/
id: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]),
/**
* HTML id for the inner `a` element
*/
linkId: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]),
/**
* `href` attribute for the inner `a` element
*/
href: React.PropTypes.string,
/**
* `title` attribute for the inner `a` element
*/
title: React.PropTypes.node,
/**
* `target` attribute for the inner `a` element
*/
target: React.PropTypes.string
},
getDefaultProps() {
return {
active: false,
};
},
render() {
const {
active,
className,
id,
linkId,
children,
href,
title,
target,
...props } = this.props;
warning(!(href && active), '[react-bootstrap] `href` and `active` properties cannot be set at the same time');
const linkProps = {
href,
title,
target,
id: linkId
};
return (
<li id={id} className={classNames(className, { active })}>
{
active ?
<span {...props}>
{ children }
</span> :
<SafeAnchor {...props} {...linkProps}>
{ children }
</SafeAnchor>
}
</li>
);
}
});
export default BreadcrumbItem;
|
src/routes/indexGatherGoods.js | daxiangaikafei/QBGoods | import React from 'react'
import { Route, IndexRoute, Router } from 'dva/router'
import CoreLayout from '../containers/layout'
import GatherGoods from 'views/GatherGoods/page'
export default function (ref) {
return (
<Router history={ref.history}>
<Route path='/' component={CoreLayout} name="我有好物">
<IndexRoute component={GatherGoods} name="聚好货"/>
<Route path='/GatherGoods' component={GatherGoods} name="聚好货" />
</Route>
</Router>
)
}
|
examples/with-graphql-hooks/pages/_app.js | BlancheXu/test | import App from 'next/app'
import React from 'react'
import withGraphQLClient from '../lib/with-graphql-client'
import { ClientContext } from 'graphql-hooks'
class MyApp extends App {
render () {
const { Component, pageProps, graphQLClient } = this.props
return (
<ClientContext.Provider value={graphQLClient}>
<Component {...pageProps} />
</ClientContext.Provider>
)
}
}
export default withGraphQLClient(MyApp)
|
docs/src/app/components/CodeExample/index.js | rscnt/material-ui | import React from 'react';
import {parse} from 'react-docgen';
import CodeBlock from './CodeBlock';
import ClearFix from 'material-ui/internal/ClearFix';
import Paper from 'material-ui/Paper';
class CodeExample extends React.Component {
static propTypes = {
children: React.PropTypes.node,
code: React.PropTypes.string.isRequired,
component: React.PropTypes.bool,
description: React.PropTypes.string,
layoutSideBySide: React.PropTypes.bool,
title: React.PropTypes.string,
};
static defaultProps = {
component: true,
};
static contextTypes = {
muiTheme: React.PropTypes.object,
};
render() {
const {
children,
code,
component,
layoutSideBySide,
} = this.props;
const palette = this.context.muiTheme.rawTheme.palette;
const canvasColor = palette.canvasColor;
const styles = {
root: {
backgroundColor: canvasColor,
marginBottom: 32,
},
exampleBlock: {
borderRadius: '0 0 2px 0',
padding: '14px 24px 24px',
margin: 0,
width: layoutSideBySide ? '45%' : null,
float: layoutSideBySide ? 'right' : null,
},
};
const docs = component ? parse(code) : {};
return (
<Paper style={styles.root}>
<CodeBlock
title={this.props.title}
description={this.props.description || docs.description}
>
{code}
</CodeBlock>
<ClearFix style={styles.exampleBlock}>{children}</ClearFix>
</Paper>
);
}
}
export default CodeExample;
|
index.ios.js | bestofsong/rn-nav-tab-redux | 'use strict'
import React from 'react'
import {AppRegistry} from 'react-native'
import App from './app/app'
AppRegistry.registerComponent('navExpRedux', () => App)
|
benchmarks/dom-comparison/src/app/Benchmark/index.js | risetechnologies/fela | /**
* The MIT License (MIT)
* Copyright (c) 2017 Paul Armstrong
* https://github.com/paularmstrong/react-component-benchmark
*/
/* global $Values */
/**
* @flow
*/
import * as Timing from './timing';
import React, { Component } from 'react';
import { getMean, getMedian, getStdDev } from './math';
import type { BenchResultsType, FullSampleTimingType, SampleTimingType } from './types';
export const BenchmarkType = {
MOUNT: 'mount',
UPDATE: 'update',
UNMOUNT: 'unmount'
};
const shouldRender = (cycle: number, type: $Values<typeof BenchmarkType>): boolean => {
switch (type) {
// Render every odd iteration (first, third, etc)
// Mounts and unmounts the component
case BenchmarkType.MOUNT:
case BenchmarkType.UNMOUNT:
return !((cycle + 1) % 2);
// Render every iteration (updates previously rendered module)
case BenchmarkType.UPDATE:
return true;
default:
return false;
}
};
const shouldRecord = (cycle: number, type: $Values<typeof BenchmarkType>): boolean => {
switch (type) {
// Record every odd iteration (when mounted: first, third, etc)
case BenchmarkType.MOUNT:
return !((cycle + 1) % 2);
// Record every iteration
case BenchmarkType.UPDATE:
return true;
// Record every even iteration (when unmounted)
case BenchmarkType.UNMOUNT:
return !(cycle % 2);
default:
return false;
}
};
const isDone = (
cycle: number,
sampleCount: number,
type: $Values<typeof BenchmarkType>
): boolean => {
switch (type) {
case BenchmarkType.MOUNT:
return cycle >= sampleCount * 2 - 1;
case BenchmarkType.UPDATE:
return cycle >= sampleCount - 1;
case BenchmarkType.UNMOUNT:
return cycle >= sampleCount * 2;
default:
return true;
}
};
const sortNumbers = (a: number, b: number): number => a - b;
type BenchmarkPropsType = {
component: typeof React.Component,
forceLayout?: boolean,
getComponentProps: Function,
onComplete: (x: BenchResultsType) => void,
sampleCount: number,
timeout: number,
type: $Values<typeof BenchmarkType>
};
type BenchmarkStateType = {
componentProps: Object,
cycle: number,
running: boolean
};
/**
* Benchmark
* TODO: documentation
*/
export default class Benchmark extends Component<BenchmarkPropsType, BenchmarkStateType> {
_raf: ?Function;
_startTime: number;
_samples: Array<SampleTimingType>;
static displayName = 'Benchmark';
static defaultProps = {
sampleCount: 50,
timeout: 10000, // 10 seconds
type: BenchmarkType.MOUNT
};
static Type = BenchmarkType;
constructor(props: BenchmarkPropsType, context?: {}) {
super(props, context);
const cycle = 0;
const componentProps = props.getComponentProps({ cycle });
this.state = {
componentProps,
cycle,
running: false
};
this._startTime = 0;
this._samples = [];
}
componentWillReceiveProps(nextProps: BenchmarkPropsType) {
if (nextProps) {
this.setState(state => ({ componentProps: nextProps.getComponentProps(state.cycle) }));
}
}
componentWillUpdate(nextProps: BenchmarkPropsType, nextState: BenchmarkStateType) {
if (nextState.running && !this.state.running) {
this._startTime = Timing.now();
}
}
componentDidUpdate() {
const { forceLayout, sampleCount, timeout, type } = this.props;
const { cycle, running } = this.state;
if (running && shouldRecord(cycle, type)) {
this._samples[cycle].scriptingEnd = Timing.now();
// force style recalc that would otherwise happen before the next frame
if (forceLayout) {
this._samples[cycle].layoutStart = Timing.now();
if (document.body) {
document.body.offsetWidth;
}
this._samples[cycle].layoutEnd = Timing.now();
}
}
if (running) {
const now = Timing.now();
if (!isDone(cycle, sampleCount, type) && now - this._startTime < timeout) {
this._handleCycleComplete();
} else {
this._handleComplete(now);
}
}
}
componentWillUnmount() {
if (this._raf) {
window.cancelAnimationFrame(this._raf);
}
}
render() {
const { component: Component, type } = this.props;
const { componentProps, cycle, running } = this.state;
if (running && shouldRecord(cycle, type)) {
this._samples[cycle] = { scriptingStart: Timing.now() };
}
return running && shouldRender(cycle, type) ? <Component {...componentProps} /> : null;
}
start() {
this._samples = [];
this.setState(() => ({ running: true, cycle: 0 }));
}
_handleCycleComplete() {
const { getComponentProps, type } = this.props;
const { cycle } = this.state;
let componentProps;
if (getComponentProps) {
// Calculate the component props outside of the time recording (render)
// so that it doesn't skew results
componentProps = getComponentProps({ cycle });
// make sure props always change for update tests
if (type === BenchmarkType.UPDATE) {
componentProps['data-test'] = cycle;
}
}
this._raf = window.requestAnimationFrame(() => {
this.setState((state: BenchmarkStateType) => ({
cycle: state.cycle + 1,
componentProps
}));
});
}
getSamples(): Array<FullSampleTimingType> {
return this._samples.reduce(
(
memo: Array<FullSampleTimingType>,
{ scriptingStart, scriptingEnd, layoutStart, layoutEnd }: SampleTimingType
): Array<FullSampleTimingType> => {
memo.push({
start: scriptingStart,
end: layoutEnd || scriptingEnd || 0,
scriptingStart,
scriptingEnd: scriptingEnd || 0,
layoutStart,
layoutEnd
});
return memo;
},
[]
);
}
_handleComplete(endTime: number) {
const { onComplete } = this.props;
const samples = this.getSamples();
this.setState(() => ({ running: false, cycle: 0 }));
const runTime = endTime - this._startTime;
const sortedElapsedTimes = samples.map(({ start, end }) => end - start).sort(sortNumbers);
const sortedScriptingElapsedTimes = samples
.map(({ scriptingStart, scriptingEnd }) => scriptingEnd - scriptingStart)
.sort(sortNumbers);
const sortedLayoutElapsedTimes = samples
.map(({ layoutStart, layoutEnd }) => (layoutEnd || 0) - (layoutStart || 0))
.sort(sortNumbers);
onComplete({
startTime: this._startTime,
endTime,
runTime,
sampleCount: samples.length,
samples: samples,
max: sortedElapsedTimes[sortedElapsedTimes.length - 1],
min: sortedElapsedTimes[0],
median: getMedian(sortedElapsedTimes),
mean: getMean(sortedElapsedTimes),
stdDev: getStdDev(sortedElapsedTimes),
meanLayout: getMean(sortedLayoutElapsedTimes),
meanScripting: getMean(sortedScriptingElapsedTimes)
});
}
}
|
lesson-7/todos/src/components/editNotesPage/EditNotesPage.js | msd-code-academy/lessons | import React from 'react'
import NoteList from './NoteList'
import { actionTypes, fetchNotesAsync } from '../../Reducer'
import { connect } from 'react-redux'
class EditNotesPage extends React.Component {
componentWillMount() {
this.props.dispatch(fetchNotesAsync());
}
editNote = editedNote => {
this.props.dispatch({ type: actionTypes.NOTE_UPDATED, editedNote })
}
removeNoteFromList = deletedNoteUuid => () => {
this.props.dispatch({ type: actionTypes.NOTE_DELETED, deletedNoteUuid })
}
render() {
const notes = this.props.notes
const noteCount = notes.length
return (<NoteList
notes={notes}
removeNoteFromList={this.removeNoteFromList}
editNote={this.editNote} />)
}
}
function mapStateToProps(state) {
return {
notes: state.notes
};
}
export default connect(mapStateToProps)(EditNotesPage); |
blueocean-material-icons/src/js/components/svg-icons/communication/screen-share.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const CommunicationScreenShare = (props) => (
<SvgIcon {...props}>
<path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.11-.9-2-2-2H4c-1.11 0-2 .89-2 2v10c0 1.1.89 2 2 2H0v2h24v-2h-4zm-7-3.53v-2.19c-2.78 0-4.61.85-6 2.72.56-2.67 2.11-5.33 6-5.87V7l4 3.73-4 3.74z"/>
</SvgIcon>
);
CommunicationScreenShare.displayName = 'CommunicationScreenShare';
CommunicationScreenShare.muiName = 'SvgIcon';
export default CommunicationScreenShare;
|
src/entypo/ChevronThinLeft.js | cox-auto-kc/react-entypo | import React from 'react';
import EntypoIcon from '../EntypoIcon';
const iconClass = 'entypo-svgicon entypo--ChevronThinLeft';
let EntypoChevronThinLeft = (props) => (
<EntypoIcon propClass={iconClass} {...props}>
<path d="M13.891,17.418c0.268,0.272,0.268,0.709,0,0.979c-0.268,0.27-0.701,0.271-0.969,0l-7.83-7.908c-0.268-0.27-0.268-0.707,0-0.979l7.83-7.908c0.268-0.27,0.701-0.27,0.969,0c0.268,0.271,0.268,0.709,0,0.979L6.75,10L13.891,17.418z"/>
</EntypoIcon>
);
export default EntypoChevronThinLeft;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.