path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
public/js/cat_source/es6/components/segments/SegmentCommentsContainer.js | matecat/MateCat | /**
* React Component for the warnings.
*/
import React from 'react'
import _ from 'lodash'
import CommentsStore from '../../stores/CommentsStore'
import CommentsActions from '../../actions/CommentsActions'
import CommentsConstants from '../../constants/CommentsConstants'
import SegmentActions from '../../actions/SegmentActions'
import MBC from '../../utils/mbc.main'
class SegmentCommentsContainer extends React.Component {
constructor(props) {
super(props)
this.state = {
comments: CommentsStore.getCommentsBySegment(
this.props.segment.original_sid,
),
user: CommentsStore.getUser(),
teamUsers: CommentsStore.getTeamUsers(),
sendCommentError: false,
}
this.types = {sticky: 3, resolve: 2, comment: 1}
this.updateComments = this.updateComments.bind(this)
this.setFocusOnInput = this.setFocusOnInput.bind(this)
this.setTeamUsers = this.setTeamUsers.bind(this)
}
closeComments(e) {
e.preventDefault()
e.stopPropagation()
SegmentActions.closeSegmentComment(this.props.segment.sid)
localStorage.setItem(MBC.localStorageCommentsClosed, true)
}
sendComment() {
let text = $(this.commentInput).html()
if (this.commentInput.textContent.trim().length > 0) {
CommentsActions.sendComment(text, this.props.segment.original_sid)
.catch(() => {
this.setState({sendCommentError: true})
})
.then(() => {
this.setState({sendCommentError: false})
setTimeout(() => (this.commentInput.textContent = ''))
})
}
}
resolveThread() {
CommentsActions.resolveThread(this.props.segment.original_sid)
}
updateComments(sid) {
if (_.isUndefined(sid) || sid === this.props.segment.original_sid) {
const comments = CommentsStore.getCommentsBySegment(
this.props.segment.original_sid,
)
const user = CommentsStore.getUser()
this.setState({
comments: comments,
user: user,
})
}
}
setTeamUsers(users) {
this.setState({
teamUsers: users,
})
}
getComments() {
let htmlComments, htmlInsert, resolveButton
const nl2br = function (str, is_xhtml) {
var breakTag =
is_xhtml || typeof is_xhtml === 'undefined' ? '<br />' : '<br>'
return (str + '').replace(
/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,
'$1' + breakTag + '$2',
)
}
var findUser = (id) => {
return _.find(this.state.teamUsers, function (item) {
return item.uid === id
})
}
const parseCommentHtml = function (text) {
var regExp = /{@([0-9]+|team)@}/gm
if (regExp.test(text)) {
text = text.replace(regExp, function (match, id) {
id = id === 'team' ? id : parseInt(id)
var user = findUser(id)
if (user) {
var html =
'<span contenteditable="false" class="tagging-item" data-id="' +
id +
'">' +
user.first_name +
' ' +
user.last_name +
'</span>'
return match.replace(match, html)
}
return match
})
}
return text
}
if (this.state.comments.length > 0) {
let thread_wrap = [],
thread_id = 0,
count = 0,
commentsHtml = [],
threadClass
let comments = this.state.comments.slice()
comments.forEach((comment, i) => {
let html = []
if (comment.thread_id !== thread_id) {
// start a new thread
if (thread_wrap.length > 0) {
commentsHtml.push(
<div
key={'thread-' + i}
className={'mbc-thread-wrap mbc-clearfix ' + threadClass}
data-count={count}
>
{thread_wrap}
</div>,
)
count = 0
}
thread_wrap = []
}
if (Number(comment.message_type) === this.types.comment) {
count++
}
if (comment.thread_id == null) {
threadClass = 'mbc-thread-wrap-active'
} else {
threadClass = 'mbc-thread-wrap-resolved'
}
if (Number(comment.message_type) === this.types.resolve) {
thread_wrap.push(
<div className="mbc-resolved-comment" key={'comment-' + i}>
<span className="mbc-comment-resolved-label">
<span className="mbc-comment-username mbc-comment-resolvedby">
{`${comment.full_name} `}
</span>
<span className="">marked as resolved</span>
</span>
</div>,
)
} else {
let text = nl2br(comment.message)
text = parseCommentHtml(text)
thread_wrap.push(
<div className="mbc-show-comment mbc-clearfix" key={'comment-' + i}>
<span className="mbc-comment-label mbc-comment-username mbc-comment-username-label mbc-truncate">
{comment.full_name}
</span>
<span className="mbc-comment-label mbc-comment-email-label mbc-truncate">
{comment.email}
</span>
<div className="mbc-comment-info-wrap mbc-clearfix">
<span className="mbc-comment-info mbc-comment-time pull-left">
{comment.formatted_date}
</span>
</div>
<p
className="mbc-comment-body"
dangerouslySetInnerHTML={{__html: text}}
/>
</div>,
)
}
thread_id = comment.thread_id
})
// Thread is not resolved
if (
!_.isUndefined(comments.length - 1) &&
!comments[comments.length - 1].thread_id
) {
resolveButton = (
<a
className="ui button mbc-comment-label mbc-comment-btn mbc-comment-resolve-btn pull-right"
onClick={() => this.resolveThread()}
>
Resolve
</a>
)
}
if (thread_wrap.length > 0) {
commentsHtml.push(
<div
key={'thread-' + 900}
className={'mbc-thread-wrap mbc-clearfix ' + threadClass}
data-count={count}
>
{thread_wrap}
{resolveButton}
</div>,
)
}
htmlComments = commentsHtml
}
let loggedUser = !!this.state.user
// Se utente anonimo aggiungere mbc-comment-anonymous-label a mbc-comment-username
htmlInsert = (
<div
className="mbc-thread-wrap mbc-post-comment-wrap mbc-clearfix mbc-first-input"
ref={(container) => (this.container = container)}
>
{/*<div className="mbc-new-message-notification">*/}
{/*<span className="mbc-new-message-icon mbc-new-message-arrowdown">↓</span>*/}
{/*<a className="mbc-new-message-link"/>*/}
{/*</div>*/}
<div className="mbc-post-comment">
<span className="mbc-comment-label mbc-comment-username mbc-comment-username-label mbc-truncate mbc-comment-anonymous-label">
{this.state.user ? this.state.user.full_name : 'Anonymous'}
</span>
{!loggedUser ? (
<a
className="mbc-comment-link-btn mbc-login-link"
onClick={() => {
$('#modal').trigger('openlogin')
}}
>
Login to receive comments
</a>
) : null}
<div
ref={(input) => (this.commentInput = input)}
onKeyPress={(e) => e.key === 'Enter' && this.sendComment()}
className="mbc-comment-input mbc-comment-textarea"
contentEditable={true}
data-placeholder="Write a comment..."
/>
<div>
<a
className="ui primary tiny button mbc-comment-btn mbc-comment-send-btn hide"
onClick={() => this.sendComment()}
>
Comment
</a>
</div>
{this.state.sendCommentError ? (
<div className="mbc-ajax-message-wrap">
<span className="mbc-warnings">
Oops, something went wrong. Please try again later.
</span>
</div>
) : null}
<div></div>
</div>
</div>
)
return (
<div className="mbc-comment-balloon-outer">
<div className="mbc-comment-balloon-inner">
<div className="mbc-triangle mbc-open-view mbc-re-messages" />
<a
className="re-close-balloon shadow-1"
onClick={(e) => this.closeComments(e)}
>
<i className="icon-cancel3 icon" />
</a>
<div className="mbc-comments-wrap" ref={(wrap) => (this.wrap = wrap)}>
{htmlComments}
</div>
{htmlInsert}
</div>
</div>
)
}
addTagging() {
let teamUsers = this.state.teamUsers
if (teamUsers && teamUsers.length > 0) {
$('.mbc-comment-textarea').atwho({
at: '@',
displayTpl: '<li>${first_name} ${last_name}</li>',
insertTpl:
'<span contenteditable="false" class="tagging-item" data-id="${uid}">${first_name} ${last_name}</span>',
data: teamUsers,
searchKey: 'first_name',
limit: teamUsers.length,
})
}
}
scrollToBottom() {
const scrollHeight = this.wrap.scrollHeight
const height = this.wrap.clientHeight
const maxScrollTop = scrollHeight - height
this.wrap.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0
}
setFocusOnInput() {
this.commentInput.focus()
}
componentDidUpdate() {
// const comments = CommentsStore.getCommentsBySegment(this.props.segment.sid);
this.scrollToBottom()
}
componentDidMount() {
this.updateComments(this.props.segment.sid)
this.addTagging()
CommentsStore.addListener(
CommentsConstants.ADD_COMMENT,
this.updateComments,
)
CommentsStore.addListener(
CommentsConstants.STORE_COMMENTS,
this.updateComments,
)
CommentsStore.addListener(CommentsConstants.SET_FOCUS, this.setFocusOnInput)
CommentsStore.addListener(
CommentsConstants.SET_TEAM_USERS,
this.setTeamUsers,
)
this.scrollToBottom()
this.commentInput.focus()
}
componentWillUnmount() {
CommentsStore.removeListener(
CommentsConstants.ADD_COMMENT,
this.updateComments,
)
CommentsStore.removeListener(
CommentsConstants.STORE_COMMENTS,
this.updateComments,
)
CommentsStore.removeListener(
CommentsConstants.SET_FOCUS,
this.setFocusOnInput,
)
CommentsStore.removeListener(
CommentsConstants.SET_TEAM_USERS,
this.setTeamUsers,
)
}
render() {
//if is not splitted or is the first of the splitted group
if (
(!this.props.segment.splitted ||
this.props.segment.sid.split('-')[1] === '1') &&
this.state.comments
) {
if (this.props.segment.openComments) {
return this.getComments()
}
} else {
return null
}
}
}
export default SegmentCommentsContainer
|
src/svg-icons/file/create-new-folder.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let FileCreateNewFolder = (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>
);
FileCreateNewFolder = pure(FileCreateNewFolder);
FileCreateNewFolder.displayName = 'FileCreateNewFolder';
FileCreateNewFolder.muiName = 'SvgIcon';
export default FileCreateNewFolder;
|
src/components/Why.js | jubianchi/semver-check | import React from 'react';
import PropTypes from 'prop-types';
import Quote from './Quote';
const Why = props => (
<div className={`row ${props.className}`}>
<div className="col-12">
<h2>SEMVER CHECKER... WHY?</h2>
<Quote author="semver.org" source="//semver.org/">
<p>In the world of software management there exists a dread place called "dependency hell."</p>
<p>
The bigger your system grows and the more packages you integrate into your software, the more likely
you are to find yourself, one day, in this pit of despair.
</p>
</Quote>
<p>
More and more projects try to follow Semantic Versioning to reduce package versioning nightmare and
every dependency manager implements its own semantic versioner.{' '}
<a href="https://getcomposer.org/">Composer</a> and <a href="https://www.npmjs.org/">NPM</a> for example
don't handle version constraints the same way. It's hard sometimes to be sure how some library version
will behave against some constraint.
</p>
<p>This tiny webapp checks if a given version satisfies another given constraint.</p>
</div>
</div>
);
Why.propTypes = {
className: PropTypes.string,
};
Why.defaultProps = {
className: '',
};
export default Why;
|
src/modules/Externals/routes.js | dannegm/danielgarcia | import React from 'react';
import { Redirect } from 'react-router-dom';
const exact = true;
const routes = [
{
name: 'external.nyungerland',
path: '/nyungerland',
component: () => <Redirect to='https://nyungerland.net/' />,
exact,
},
];
export default routes;
|
src/modules/timeProgress/TimeProgressRenderer.native.js | kuzzmi/rmndrz | import React from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
export default (props, state) =>
<View style={ styles.component }>
<Text style={ styles.text }>
TimeProgress Component
</Text>
</View>;
const styles = StyleSheet.create({
component: {
},
text: {
fontSize: 16,
},
});
|
node_modules/react-bootstrap/es/SplitToggle.js | Technaesthetic/ua-tools | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import DropdownToggle from './DropdownToggle';
var SplitToggle = function (_React$Component) {
_inherits(SplitToggle, _React$Component);
function SplitToggle() {
_classCallCheck(this, SplitToggle);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
SplitToggle.prototype.render = function render() {
return React.createElement(DropdownToggle, _extends({}, this.props, {
useAnchor: false,
noCaret: false
}));
};
return SplitToggle;
}(React.Component);
SplitToggle.defaultProps = DropdownToggle.defaultProps;
export default SplitToggle; |
app/javascript/mastodon/features/account/components/header.js | imas/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import Button from 'mastodon/components/button';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { autoPlayGif, me, isStaff } from 'mastodon/initial_state';
import classNames from 'classnames';
import Icon from 'mastodon/components/icon';
import IconButton from 'mastodon/components/icon_button';
import Avatar from 'mastodon/components/avatar';
import { counterRenderer } from 'mastodon/components/common_counter';
import ShortNumber from 'mastodon/components/short_number';
import { NavLink } from 'react-router-dom';
import DropdownMenuContainer from 'mastodon/containers/dropdown_menu_container';
import AccountNoteContainer from '../containers/account_note_container';
const messages = defineMessages({
unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' },
follow: { id: 'account.follow', defaultMessage: 'Follow' },
cancel_follow_request: { id: 'account.cancel_follow_request', defaultMessage: 'Cancel follow request' },
requested: { id: 'account.requested', defaultMessage: 'Awaiting approval. Click to cancel follow request' },
unblock: { id: 'account.unblock', defaultMessage: 'Unblock @{name}' },
edit_profile: { id: 'account.edit_profile', defaultMessage: 'Edit profile' },
linkVerifiedOn: { id: 'account.link_verified_on', defaultMessage: 'Ownership of this link was checked on {date}' },
account_locked: { id: 'account.locked_info', defaultMessage: 'This account privacy status is set to locked. The owner manually reviews who can follow them.' },
mention: { id: 'account.mention', defaultMessage: 'Mention @{name}' },
direct: { id: 'account.direct', defaultMessage: 'Direct message @{name}' },
unmute: { id: 'account.unmute', defaultMessage: 'Unmute @{name}' },
block: { id: 'account.block', defaultMessage: 'Block @{name}' },
mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' },
report: { id: 'account.report', defaultMessage: 'Report @{name}' },
share: { id: 'account.share', defaultMessage: 'Share @{name}\'s profile' },
media: { id: 'account.media', defaultMessage: 'Media' },
blockDomain: { id: 'account.block_domain', defaultMessage: 'Block domain {domain}' },
unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' },
hideReblogs: { id: 'account.hide_reblogs', defaultMessage: 'Hide boosts from @{name}' },
showReblogs: { id: 'account.show_reblogs', defaultMessage: 'Show boosts from @{name}' },
enableNotifications: { id: 'account.enable_notifications', defaultMessage: 'Notify me when @{name} posts' },
disableNotifications: { id: 'account.disable_notifications', defaultMessage: 'Stop notifying me when @{name} posts' },
pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' },
preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' },
follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' },
favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' },
lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' },
blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' },
domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Blocked domains' },
mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' },
endorse: { id: 'account.endorse', defaultMessage: 'Feature on profile' },
unendorse: { id: 'account.unendorse', defaultMessage: 'Don\'t feature on profile' },
add_or_remove_from_list: { id: 'account.add_or_remove_from_list', defaultMessage: 'Add or Remove from lists' },
admin_account: { id: 'status.admin_account', defaultMessage: 'Open moderation interface for @{name}' },
});
const dateFormatOptions = {
month: 'short',
day: 'numeric',
year: 'numeric',
hour12: false,
hour: '2-digit',
minute: '2-digit',
};
export default @injectIntl
class Header extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map,
identity_props: ImmutablePropTypes.list,
onFollow: PropTypes.func.isRequired,
onBlock: PropTypes.func.isRequired,
onMention: PropTypes.func.isRequired,
onDirect: PropTypes.func.isRequired,
onReblogToggle: PropTypes.func.isRequired,
onNotifyToggle: PropTypes.func.isRequired,
onReport: PropTypes.func.isRequired,
onMute: PropTypes.func.isRequired,
onBlockDomain: PropTypes.func.isRequired,
onUnblockDomain: PropTypes.func.isRequired,
onEndorseToggle: PropTypes.func.isRequired,
onAddToList: PropTypes.func.isRequired,
onEditAccountNote: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
domain: PropTypes.string.isRequired,
};
openEditProfile = () => {
window.open('/settings/profile', '_blank');
}
isStatusesPageActive = (match, location) => {
if (!match) {
return false;
}
return !location.pathname.match(/\/(followers|following)\/?$/);
}
handleMouseEnter = ({ currentTarget }) => {
if (autoPlayGif) {
return;
}
const emojis = currentTarget.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
emoji.src = emoji.getAttribute('data-original');
}
}
handleMouseLeave = ({ currentTarget }) => {
if (autoPlayGif) {
return;
}
const emojis = currentTarget.querySelectorAll('.custom-emoji');
for (var i = 0; i < emojis.length; i++) {
let emoji = emojis[i];
emoji.src = emoji.getAttribute('data-static');
}
}
render () {
const { account, intl, domain, identity_proofs } = this.props;
if (!account) {
return null;
}
const suspended = account.get('suspended');
let info = [];
let actionBtn = '';
let bellBtn = '';
let lockedIcon = '';
let menu = [];
if (me !== account.get('id') && account.getIn(['relationship', 'followed_by'])) {
info.push(<span key='followed_by' className='relationship-tag'><FormattedMessage id='account.follows_you' defaultMessage='Follows you' /></span>);
} else if (me !== account.get('id') && account.getIn(['relationship', 'blocking'])) {
info.push(<span key='blocked' className='relationship-tag'><FormattedMessage id='account.blocked' defaultMessage='Blocked' /></span>);
}
if (me !== account.get('id') && account.getIn(['relationship', 'muting'])) {
info.push(<span key='muted' className='relationship-tag'><FormattedMessage id='account.muted' defaultMessage='Muted' /></span>);
} else if (me !== account.get('id') && account.getIn(['relationship', 'domain_blocking'])) {
info.push(<span key='domain_blocked' className='relationship-tag'><FormattedMessage id='account.domain_blocked' defaultMessage='Domain blocked' /></span>);
}
if (account.getIn(['relationship', 'requested']) || account.getIn(['relationship', 'following'])) {
bellBtn = <IconButton icon='bell-o' size={24} active={account.getIn(['relationship', 'notifying'])} title={intl.formatMessage(account.getIn(['relationship', 'notifying']) ? messages.disableNotifications : messages.enableNotifications, { name: account.get('username') })} onClick={this.props.onNotifyToggle} />;
}
if (me !== account.get('id')) {
if (!account.get('relationship')) { // Wait until the relationship is loaded
actionBtn = '';
} else if (account.getIn(['relationship', 'requested'])) {
actionBtn = <Button className={classNames('logo-button', { 'button--with-bell': bellBtn !== '' })} text={intl.formatMessage(messages.cancel_follow_request)} title={intl.formatMessage(messages.requested)} onClick={this.props.onFollow} />;
} else if (!account.getIn(['relationship', 'blocking'])) {
actionBtn = <Button disabled={account.getIn(['relationship', 'blocked_by'])} className={classNames('logo-button', { 'button--destructive': account.getIn(['relationship', 'following']), 'button--with-bell': bellBtn !== '' })} text={intl.formatMessage(account.getIn(['relationship', 'following']) ? messages.unfollow : messages.follow)} onClick={this.props.onFollow} />;
} else if (account.getIn(['relationship', 'blocking'])) {
actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.unblock, { name: account.get('username') })} onClick={this.props.onBlock} />;
}
} else {
actionBtn = <Button className='logo-button' text={intl.formatMessage(messages.edit_profile)} onClick={this.openEditProfile} />;
}
if (account.get('moved') && !account.getIn(['relationship', 'following'])) {
actionBtn = '';
}
if (account.get('locked')) {
lockedIcon = <Icon id='lock' title={intl.formatMessage(messages.account_locked)} />;
}
if (account.get('id') !== me) {
menu.push({ text: intl.formatMessage(messages.mention, { name: account.get('username') }), action: this.props.onMention });
menu.push({ text: intl.formatMessage(messages.direct, { name: account.get('username') }), action: this.props.onDirect });
menu.push(null);
}
if ('share' in navigator) {
menu.push({ text: intl.formatMessage(messages.share, { name: account.get('username') }), action: this.handleShare });
menu.push(null);
}
if (account.get('id') === me) {
menu.push({ text: intl.formatMessage(messages.edit_profile), href: '/settings/profile' });
menu.push({ text: intl.formatMessage(messages.preferences), href: '/settings/preferences' });
menu.push({ text: intl.formatMessage(messages.pins), to: '/pinned' });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.follow_requests), to: '/follow_requests' });
menu.push({ text: intl.formatMessage(messages.favourites), to: '/favourites' });
menu.push({ text: intl.formatMessage(messages.lists), to: '/lists' });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.mutes), to: '/mutes' });
menu.push({ text: intl.formatMessage(messages.blocks), to: '/blocks' });
menu.push({ text: intl.formatMessage(messages.domain_blocks), to: '/domain_blocks' });
} else {
if (account.getIn(['relationship', 'following'])) {
if (!account.getIn(['relationship', 'muting'])) {
if (account.getIn(['relationship', 'showing_reblogs'])) {
menu.push({ text: intl.formatMessage(messages.hideReblogs, { name: account.get('username') }), action: this.props.onReblogToggle });
} else {
menu.push({ text: intl.formatMessage(messages.showReblogs, { name: account.get('username') }), action: this.props.onReblogToggle });
}
}
menu.push({ text: intl.formatMessage(account.getIn(['relationship', 'endorsed']) ? messages.unendorse : messages.endorse), action: this.props.onEndorseToggle });
menu.push({ text: intl.formatMessage(messages.add_or_remove_from_list), action: this.props.onAddToList });
menu.push(null);
}
if (account.getIn(['relationship', 'muting'])) {
menu.push({ text: intl.formatMessage(messages.unmute, { name: account.get('username') }), action: this.props.onMute });
} else {
menu.push({ text: intl.formatMessage(messages.mute, { name: account.get('username') }), action: this.props.onMute });
}
if (account.getIn(['relationship', 'blocking'])) {
menu.push({ text: intl.formatMessage(messages.unblock, { name: account.get('username') }), action: this.props.onBlock });
} else {
menu.push({ text: intl.formatMessage(messages.block, { name: account.get('username') }), action: this.props.onBlock });
}
menu.push({ text: intl.formatMessage(messages.report, { name: account.get('username') }), action: this.props.onReport });
}
if (account.get('acct') !== account.get('username')) {
const domain = account.get('acct').split('@')[1];
menu.push(null);
if (account.getIn(['relationship', 'domain_blocking'])) {
menu.push({ text: intl.formatMessage(messages.unblockDomain, { domain }), action: this.props.onUnblockDomain });
} else {
menu.push({ text: intl.formatMessage(messages.blockDomain, { domain }), action: this.props.onBlockDomain });
}
}
if (account.get('id') !== me && isStaff) {
menu.push(null);
menu.push({ text: intl.formatMessage(messages.admin_account, { name: account.get('username') }), href: `/admin/accounts/${account.get('id')}` });
}
const content = { __html: account.get('note_emojified') };
const displayNameHtml = { __html: account.get('display_name_html') };
const fields = account.get('fields');
const acct = account.get('acct').indexOf('@') === -1 && domain ? `${account.get('acct')}@${domain}` : account.get('acct');
let badge;
if (account.get('bot')) {
badge = (<div className='account-role bot'><FormattedMessage id='account.badges.bot' defaultMessage='Bot' /></div>);
} else if (account.get('group')) {
badge = (<div className='account-role group'><FormattedMessage id='account.badges.group' defaultMessage='Group' /></div>);
} else {
badge = null;
}
return (
<div className={classNames('account__header', { inactive: !!account.get('moved') })} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>
<div className='account__header__image'>
<div className='account__header__info'>
{!suspended && info}
</div>
<img src={autoPlayGif ? account.get('header') : account.get('header_static')} alt='' className='parallax' />
</div>
<div className='account__header__bar'>
<div className='account__header__tabs'>
<a className='avatar' href={account.get('url')} rel='noopener noreferrer' target='_blank'>
<Avatar account={account} size={90} />
</a>
<div className='spacer' />
{!suspended && (
<div className='account__header__tabs__buttons'>
{actionBtn}
{bellBtn}
<DropdownMenuContainer items={menu} icon='ellipsis-v' size={24} direction='right' />
</div>
)}
</div>
<div className='account__header__tabs__name'>
<h1>
<span dangerouslySetInnerHTML={displayNameHtml} /> {badge}
<small>@{acct} {lockedIcon}</small>
</h1>
</div>
<div className='account__header__extra'>
<div className='account__header__bio'>
{(fields.size > 0 || identity_proofs.size > 0) && (
<div className='account__header__fields'>
{identity_proofs.map((proof, i) => (
<dl key={i}>
<dt dangerouslySetInnerHTML={{ __html: proof.get('provider') }} />
<dd className='verified'>
<a href={proof.get('proof_url')} target='_blank' rel='noopener noreferrer'><span title={intl.formatMessage(messages.linkVerifiedOn, { date: intl.formatDate(proof.get('updated_at'), dateFormatOptions) })}>
<Icon id='check' className='verified__mark' />
</span></a>
<a href={proof.get('profile_url')} target='_blank' rel='noopener noreferrer'><span dangerouslySetInnerHTML={{ __html: ' '+proof.get('provider_username') }} /></a>
</dd>
</dl>
))}
{fields.map((pair, i) => (
<dl key={i}>
<dt dangerouslySetInnerHTML={{ __html: pair.get('name_emojified') }} title={pair.get('name')} className='translate' />
<dd className={`${pair.get('verified_at') ? 'verified' : ''} translate`} title={pair.get('value_plain')}>
{pair.get('verified_at') && <span title={intl.formatMessage(messages.linkVerifiedOn, { date: intl.formatDate(pair.get('verified_at'), dateFormatOptions) })}><Icon id='check' className='verified__mark' /></span>} <span dangerouslySetInnerHTML={{ __html: pair.get('value_emojified') }} />
</dd>
</dl>
))}
</div>
)}
{account.get('id') !== me && !suspended && <AccountNoteContainer account={account} />}
{account.get('note').length > 0 && account.get('note') !== '<p></p>' && <div className='account__header__content translate' dangerouslySetInnerHTML={content} />}
<div className='account__header__joined'><FormattedMessage id='account.joined' defaultMessage='Joined {date}' values={{ date: intl.formatDate(account.get('created_at'), { year: 'numeric', month: 'short', day: '2-digit' }) }} /></div>
</div>
{!suspended && (
<div className='account__header__extra__links'>
<NavLink isActive={this.isStatusesPageActive} activeClassName='active' to={`/accounts/${account.get('id')}`} title={intl.formatNumber(account.get('statuses_count'))}>
<ShortNumber
value={account.get('statuses_count')}
renderer={counterRenderer('statuses')}
/>
</NavLink>
<NavLink exact activeClassName='active' to={`/accounts/${account.get('id')}/following`} title={intl.formatNumber(account.get('following_count'))}>
<ShortNumber
value={account.get('following_count')}
renderer={counterRenderer('following')}
/>
</NavLink>
<NavLink exact activeClassName='active' to={`/accounts/${account.get('id')}/followers`} title={intl.formatNumber(account.get('followers_count'))}>
<ShortNumber
value={account.get('followers_count')}
renderer={counterRenderer('followers')}
/>
</NavLink>
</div>
)}
</div>
</div>
</div>
);
}
}
|
src/svg-icons/notification/live-tv.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationLiveTv = (props) => (
<SvgIcon {...props}>
<path d="M21 6h-7.59l3.29-3.29L16 2l-4 4-4-4-.71.71L10.59 6H3c-1.1 0-2 .89-2 2v12c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.11-.9-2-2-2zm0 14H3V8h18v12zM9 10v8l7-4z"/>
</SvgIcon>
);
NotificationLiveTv = pure(NotificationLiveTv);
NotificationLiveTv.displayName = 'NotificationLiveTv';
NotificationLiveTv.muiName = 'SvgIcon';
export default NotificationLiveTv;
|
app/routes.js | jschlot/swarm | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './modules/core/App';
import Gameview from './modules/gameview';
export default (
<Route path="/" component={App}>
<IndexRoute component={Gameview} />
</Route>
);
|
lib/ui/src/modules/ui/components/stories_panel/stories_tree/tree_decorators_utils.js | rhalff/storybook | import React from 'react';
function getParts(name, highlight) {
const nameParts = [];
let last = 0;
highlight.forEach(([start, end]) => {
if (last < start) {
nameParts.push({
strong: false,
text: name.substring(last, start),
});
}
nameParts.push({
strong: true,
text: name.substring(start, end + 1),
});
last = end + 1;
});
if (last < name.length) {
nameParts.push({
strong: false,
text: name.substring(last, name.length),
});
}
return nameParts;
}
export function highlightNode(node, style) {
const { name, highlight } = node;
if (!highlight || !highlight.length) {
return name;
}
const nameParts = getParts(name, highlight);
return nameParts.filter(part => part.text).map((part, index) => {
const key = `${part.text}-${index}`;
if (part.strong) {
return (
<strong key={key} style={style.highLightText}>
{part.text}
</strong>
);
}
return <span key={key}>{part.text}</span>;
});
}
|
src/components/Footer/Footer.js | balmbees/overwatch | import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.css';
function Footer() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Vingle Inc</span>
</div>
</div>
);
}
export default withStyles(s)(Footer);
|
docs/layouts/CoreLayout/CoreLayout.js | shengnian/shengnian-ui | import React from 'react'
// import Header from '../../components/Header'
import './CoreLayout.scss'
import '../../styles/core.scss'
import Navbar from '../../components/Navbar'
export const CoreLayout = ({ children }) => (
<div className='out-wrapper'>
<Navbar />
<div className='row-fluid'>
{children}
</div>
</div>
)
CoreLayout.propTypes = {
children : React.PropTypes.element.isRequired
}
export default CoreLayout
|
src/index.js | timthesinner/react-vdom | //Copyright (c) 2016 TimTheSinner All Rights Reserved.
'use strict';
/**
* Copyright (c) 2016 TimTheSinner All Rights Reserved.
*
* 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.
*
* @author TimTheSinner
*/
import React from 'react';
import reactEvents from './events';
function dashToCamel(str) {
if (str.includes('-')) {
const parts = str.split('-');
for (var i = 1; i < parts.length; i++) {
parts[i] = parts[i][0].toUpperCase() + parts[i].slice(1);
}
return parts.join('');
}
return str;
}
function keyToReact(key) {
if (key == 'class') {
return 'className';
}
return dashToCamel(key);
}
class Helper {
constructor(that, key) {
this.that = that;
this.key = key;
}
get baseVal() {
return this;
}
get value() {
return this.that.getAttribute(this.key);
}
}
export default class VirtualDOM {
constructor(type = 'svg', props = {}) {
this.type = type;
this.props = { style: {}, ...props };
this.ownerDocument = this;
this.documentElement = this;
this.style = this;
this.rootElement = this;
if (type === 'svg') {
this._ownerSVGElement = this;
}
this.width = new Helper(this, 'width');
this.height = new Helper(this, 'height');
}
get ownerSVGElement() {
return this._ownerSVGElement;
}
getAttribute(key) {
return this.props[key];
}
setAttribute(key, value) {
this.props[keyToReact(key)] = value;
}
removeAttribute(key) {
delete this.props[keyToReact(key)];
}
addEventListener(type, listener, options) {
const reactEvent = reactEvents(type);
if (reactEvent) {
this.props[reactEvent] = event => {
event.target.__data__ = this.__data__ != undefined ? this.__data__ : {};
//event.view = this.rootElement;
if (!event.stopImmediatePropagation) {
listener.call(this, { ...event, stopImmediatePropagation: () => {} });
} else {
listener.call(this, event);
}
};
}
}
setProperty(name, value, priority) {
if (priority) {
console.log(`Encountered priority[${priority}] in setProperty`);
}
this.props.style[dashToCamel(name)] = value;
}
removeProperty(name) {
delete this.props.style[name];
}
createElementNS(uri, name) {
const node = new VirtualDOM(name);
node.parentNode = this;
if (this._ownerSVGElement) {
node._ownerSVGElement = this._ownerSVGElement;
}
node.rootElement = this.rootElement;
return node;
}
insertBefore(child, next) {
if (!next) {
return this.appendChild(child);
} else {
if (Array.isArray(this.children)) {
const index = this.children.indexOf(next);
if (index >= 0) {
this.children.splice(index, 0, child);
} else {
this.children.unshift(child);
}
} else if (this.children) {
this.children = [child, this.children];
} else {
this.children = child;
}
return child;
}
}
querySelector(selector) {
if (selector[0] === '.') {
selector = selector.slice(1);
return this.children.find(c => {
return c.props.className && c.props.className.includes(selector);
});
}
console.log(selector);
}
appendChild(dom) {
if (Array.isArray(this.children)) {
this.children.push(dom);
} else if (this.children) {
this.children = [this.children, dom];
} else {
this.children = dom;
}
return dom;
}
querySelectorAll(selector) {
const { children } = this;
if (!selector) {
if (Array.isArray(children)) {
return children;
} else if (children) {
return [children];
}
}
if (selector[0] === '.') {
selector = selector.slice(1);
if (Array.isArray(children)) {
return children.filter(c => {
return c.props.className && c.props.className.includes(selector);
});
} else if (children) {
if (children.props.className && children.props.className.includes(selector)) {
return [children];
}
}
return [];
}
if (selector[0] === '#') {
selector = selector.slice(1);
if (Array.isArray(children)) {
return children.filter(c => {
return c.props.id && c.props.id.includes(selector);
});
} else if (children) {
if (children.props.id && children.props.id.includes(selector)) {
return [children];
}
}
return [];
}
if (Array.isArray(children)) {
const array = children.filter(c => {
return c.type === selector;
}).concat(...children.map(c => {
return c.querySelectorAll(selector);
}));
return array;
} else if (children) {
const matched = children.querySelectorAll(selector);
if (children.type === selector) {
return [children].concat(matched);
}
return matched;
}
return [];
}
renderChildren() {
const { children } = this;
if (Array.isArray(children)) {
return children.map((c, i) => {
if (!c.render) {
return c;
}
if (!c.props.key) {
c.props.key = this.props.key + '-' + i;
}
return c.render();
});
} else if (children) {
if (!children.render) {
return children;
}
if (!children.props.key) {
children.props.key = this.props.key + '-0';
}
return this.children.render();
}
}
render() {
if (this.props.key) {
this.props['data-virtualid'] = this.props.key;
}
if (this.textContent) {
this.appendChild(this.textContent);
}
return React.createElement(this.type, this.props, this.renderChildren());
}
}
|
src/components/lists/AddressListItem.js | whphhg/vcash-ui | import React from 'react'
import { observer } from 'mobx-react'
const AddressListItem = observer(props => {
const addr = props.wallet.addr.get(props.search.addr[props.index])
return (
<div
className={
'list-item' +
(props.index % 2 === 0 ? ' even' : '') +
(props.wallet.viewing.addr === addr.address ? ' selected' : '')
}
onClick={() => props.wallet.setViewing('addr', addr.address)}
>
<div className="mono" style={{ fontWeight: '400', opacity: '0.7' }}>
<p
className="flex-center"
style={{ letterSpacing: addr.address.length === 34 ? '0.22px' : 0 }}
>
{addr.address}
</p>
</div>
<div className={'flex-center' + (addr.balance > 0 ? ' green' : '')}>
<p style={{ fontWeight: '500' }}>
{new Intl.NumberFormat(props.gui.language, {
minimumFractionDigits: 6,
maximumFractionDigits: 6
}).format(Math.abs(addr.balance))}{' '}
XVC
</p>
</div>
</div>
)
})
export default AddressListItem
|
app/javascript/mastodon/features/following/index.js | summoners-riftodon/mastodon | import React from 'react';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import {
fetchAccount,
fetchFollowing,
expandFollowing,
} from '../../actions/accounts';
import { FormattedMessage } from 'react-intl';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import HeaderContainer from '../account_timeline/containers/header_container';
import ColumnBackButton from '../../components/column_back_button';
import ScrollableList from '../../components/scrollable_list';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'following', props.params.accountId, 'items']),
hasMore: !!state.getIn(['user_lists', 'following', props.params.accountId, 'next']),
});
@connect(mapStateToProps)
export default class Following extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
accountIds: ImmutablePropTypes.list,
hasMore: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchAccount(this.props.params.accountId));
this.props.dispatch(fetchFollowing(this.props.params.accountId));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) {
this.props.dispatch(fetchAccount(nextProps.params.accountId));
this.props.dispatch(fetchFollowing(nextProps.params.accountId));
}
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandFollowing(this.props.params.accountId));
}, 300, { leading: true });
render () {
const { shouldUpdateScroll, accountIds, hasMore } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='account.follows.empty' defaultMessage="This user doesn't follow anyone yet." />;
return (
<Column>
<ColumnBackButton />
<ScrollableList
scrollKey='following'
hasMore={hasMore}
onLoadMore={this.handleLoadMore}
shouldUpdateScroll={shouldUpdateScroll}
prepend={<HeaderContainer accountId={this.props.params.accountId} hideTabs />}
alwaysPrepend
alwaysShowScrollbar
emptyMessage={emptyMessage}
>
{accountIds.map(id =>
<AccountContainer key={id} id={id} withNote={false} />
)}
</ScrollableList>
</Column>
);
}
}
|
common/components/Shell/Spinner.js | kherrick/postpress | import React from 'react'
const Spinner = () => {
return (
<div>
<img src="/spinner.gif" />
</div>
)
}
export default Spinner
|
src/svg-icons/content/unarchive.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentUnarchive = (props) => (
<SvgIcon {...props}>
<path d="M20.55 5.22l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.15.55L3.46 5.22C3.17 5.57 3 6.01 3 6.5V19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.49-.17-.93-.45-1.28zM12 9.5l5.5 5.5H14v2h-4v-2H6.5L12 9.5zM5.12 5l.82-1h12l.93 1H5.12z"/>
</SvgIcon>
);
ContentUnarchive = pure(ContentUnarchive);
ContentUnarchive.displayName = 'ContentUnarchive';
ContentUnarchive.muiName = 'SvgIcon';
export default ContentUnarchive;
|
fields/types/money/MoneyField.js | woody0907/keystone | import Field from '../Field';
import React from 'react';
import { FormInput } from 'elemental';
module.exports = Field.create({
displayName: 'MoneyField',
valueChanged (event) {
var newValue = event.target.value.replace(/[^\d\s\,\.\$€£¥]/g, '');
if (newValue === this.props.value) return;
this.props.onChange({
path: this.props.path,
value: newValue
});
},
renderField () {
return <FormInput name={this.props.path} ref="focusTarget" value={this.props.value} onChange={this.valueChanged} autoComplete="off" />;
}
});
|
src/components/BlockMenu.js | vigetlabs/colonel-kurtz | import Animator from './Animator'
import FocusTrap from 'react-focus-trap'
import Handle from './MenuHandle'
import Item from './MenuItem'
import React from 'react'
import menuItems from '../config/menu'
const defaultProps = {
items: []
}
export default class BlockMenu extends React.Component {
getMenuItem(item) {
let { id } = item
return (
<Item key={id} ref={el => (this[id] = el)} {...item} {...this.props} />
)
}
getMenuItems() {
const { items } = this.props
return items.concat(menuItems).map(this.getMenuItem, this)
}
getMenu() {
if (!this.props.active) return null
return React.createElement(
FocusTrap,
{
active: true,
key: 'menu',
className: 'col-menu',
element: 'nav',
onExit: this.props.onExit,
role: 'navigation'
},
this.getMenuItems()
)
}
render() {
return (
<Animator
className="col-menu-wrapper"
transitionName="col-menu"
transitionEnterTimeout={300}
transitionLeaveTimeout={200}
>
<Handle
key="handle"
ref={el => (this.handle = el)}
onClick={this.props.onOpen}
/>
{this.getMenu()}
</Animator>
)
}
}
BlockMenu.Item = Item
BlockMenu.defaultProps = defaultProps
|
client/src/components/Ping/Ping.js | patferguson/solitaire-react | import React, { Component } from 'react';
import APIClient from '../../api/APIClient';
import _ from 'lodash';
import AsyncButton from '../AsyncButton';
class Ping extends Component {
constructor(props) {
super(props)
// Explicitely set initial state
this.state = {
message: "",
isSendingPing: false,
};
}
/**
* Sends a 'Ping!' message to the server.
* @param callback {React.propTypes.func} Function to call once the API request has returned.
*/
sendPing(callback) {
this.setState(_.assign({}, this.state, {
isSendingPing: true,
}));
// Post a basic ping message to the server and store the response
APIClient.ping((data) => {
this.setState({
message: data["ping_response"],
isSendingPing: false,
});
callback();
});
}
render() {
const PingResponse = (
<span>
<p>
{`Response: ${this.state.message}`}
</p>
</span>
);
return (
<div className="Ping">
<AsyncButton
bsStyle="primary"
asyncFunc={this.sendPing.bind(this)}
btnText="Ping"
btnAsyncText="Pinging.."
/>
{
this.state.isSendingPing ?
(<p>Submitting 'Ping!' message..</p>) : (PingResponse)
}
</div>
);
}
}
export default Ping;
|
Paths/React/05.Building Scalable React Apps/5-react-boilerplate-building-scalable-apps-m5-exercise-files/After/app/components/AppBar/index.js | phiratio/Pluralsight-materials | /**
*
* AppBar
*
*/
import React from 'react';
import FontAwesome from 'react-fontawesome';
import styles from './styles.css';
function AppBar({ toggleDrawer }) {
return (
<div className={styles.appBar}>
<div
className={styles.iconButton}
onClick={toggleDrawer}
>
<FontAwesome
className={styles.icon}
name="bars"
/>
</div>
<div
className={styles.heading}
>
Coder daily
</div>
<div
className={styles.linkContainer}
>
log in
</div>
</div>
);
}
AppBar.propTypes = {
toggleDrawer: React.PropTypes.func.isRequired,
};
export default AppBar;
|
docs/src/app/components/pages/components/RadioButton/ExampleSimple.js | pradel/material-ui | import React from 'react';
import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton';
import ActionFavorite from 'material-ui/svg-icons/action/favorite';
import ActionFavoriteBorder from 'material-ui/svg-icons/action/favorite-border';
const styles = {
block: {
maxWidth: 250,
},
radioButton: {
marginBottom: 16,
},
};
const RadioButtonExampleSimple = () => (
<div>
<RadioButtonGroup name="shipSpeed" defaultSelected="not_light">
<RadioButton
value="light"
label="Simple"
style={styles.radioButton}
/>
<RadioButton
value="not_light"
label="Selected by default"
style={styles.radioButton}
/>
<RadioButton
value="ludicrous"
label="Custom icon"
checkedIcon={<ActionFavorite />}
uncheckedIcon={<ActionFavoriteBorder />}
style={styles.radioButton}
/>
</RadioButtonGroup>
<RadioButtonGroup name="shipName" defaultSelected="community">
<RadioButton
value="enterprise"
label="Disabled unchecked"
disabled={true}
style={styles.radioButton}
/>
<RadioButton
value="community"
label="Disabled checked"
disabled={true}
style={styles.radioButton}
/>
</RadioButtonGroup>
<RadioButtonGroup name="notRight" labelPosition="left" style={styles.block}>
<RadioButton
value="reverse"
label="Label on the left"
style={styles.radioButton}
/>
</RadioButtonGroup>
</div>
);
export default RadioButtonExampleSimple;
|
src/React/Widgets/PieceWiseFunctionEditorWidget/example/index.js | Kitware/paraviewweb | import 'normalize.css';
import React from 'react';
import ReactDOM from 'react-dom';
import PieceWiseFunctionEditorWidget from 'paraviewweb/src/React/Widgets/PieceWiseFunctionEditorWidget';
const container = document.querySelector('.content');
container.style.height = '50%';
container.style.width = '50%';
class PieceWiseTestWidget extends React.Component {
constructor(props) {
super(props);
this.state = {
points: [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
],
};
// Bind callback
this.updatePoints = this.updatePoints.bind(this);
}
updatePoints(points) {
this.setState({ points });
console.log(points);
}
render() {
return (
<PieceWiseFunctionEditorWidget
points={this.state.points}
rangeMin={0}
rangeMax={100}
onChange={this.updatePoints}
visible
/>
);
}
}
ReactDOM.render(<PieceWiseTestWidget />, container);
document.body.style.margin = '10px';
|
src/icons/GraphicEqIcon.js | kiloe/ui | import React from 'react';
import Icon from '../Icon';
export default class GraphicEqIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M14 36h4V12h-4v24zm8 8h4V4h-4v40zM6 28h4v-8H6v8zm24 8h4V12h-4v24zm8-16v8h4v-8h-4z"/></svg>;}
}; |
react/react-svg/src/components/Main.js | yuanzhaokang/myAwesomeSimpleDemo | require('normalize.css/normalize.css');
require('styles/App.css');
import Circle from './circle/Circle';
import React from 'react';
let yeomanImage = require('../images/yeoman.png');
class AppComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
"obj": [{ 'x': 200, 'y': 200 }]
};
this._onClick = this._onClick.bind(this);
}
render() {
return (
<div className="index" onClick={this._onClick}>
<svg width="100%" height="100%">
{this.state.obj.map((c) => {
return <Circle x={c.x} y={c.y} />
})}
</svg>
</div>
);
}
_onClick(event) {
let { clientX, clientY } = event;
let obj = this.state.obj;
console.log(obj);
obj = obj.push({
'x': clientX,
'y': clientY
});
this.setState({
'obj': obj
});
}
}
AppComponent.defaultProps = {
};
export default AppComponent;
|
fields/types/numberarray/NumberArrayFilter.js | vokal/keystone | import React from 'react';
import { findDOMNode } from 'react-dom';
import {
FormField,
FormInput,
FormSelect,
Grid,
} from '../../../admin/client/App/elemental';
const MODE_OPTIONS = [
{ label: 'Exactly', value: 'equals' },
{ label: 'Greater Than', value: 'gt' },
{ label: 'Less Than', value: 'lt' },
{ label: 'Between', value: 'between' },
];
const PRESENCE_OPTIONS = [
{ label: 'At least one element', value: 'some' },
{ label: 'No element', value: 'none' },
];
function getDefaultValue () {
return {
mode: MODE_OPTIONS[0].value,
presence: PRESENCE_OPTIONS[0].value,
value: '',
};
}
var NumberArrayFilter = React.createClass({
propTypes: {
filter: React.PropTypes.shape({
mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)),
presence: React.PropTypes.oneOf(PRESENCE_OPTIONS.map(i => i.value)),
value: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string,
React.PropTypes.shape({
min: React.PropTypes.number,
max: React.PropTypes.number,
}),
]),
}),
},
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
filter: getDefaultValue(),
};
},
// Returns a function that handles a specific type of onChange events for
// either 'minValue', 'maxValue' or simply 'value'
handleValueChangeBuilder (type) {
var self = this;
return function (e) {
switch (type) {
case 'minValue':
self.updateFilter({
value: {
min: e.target.value,
max: self.props.filter.value.max,
},
});
break;
case 'maxValue':
self.updateFilter({
value: {
min: self.props.filter.value.min,
max: e.target.value,
},
});
break;
case 'value':
self.updateFilter({
value: e.target.value,
});
break;
}
};
},
// Update the props with this.props.onChange
updateFilter (changedProp) {
this.props.onChange({ ...this.props.filter, ...changedProp });
},
// Update the filter mode
selectMode (e) {
const mode = e.target.value;
this.updateFilter({ mode });
findDOMNode(this.refs.focusTarget).focus();
},
// Update the presence selection
selectPresence (e) {
const presence = e.target.value;
this.updateFilter({ presence });
findDOMNode(this.refs.focusTarget).focus();
},
// Render the controls, showing two inputs when the mode is "between"
renderControls (presence, mode) {
let controls;
const placeholder = presence.label + ' is ' + mode.label.toLowerCase() + '...';
if (mode.value === 'between') {
// Render "min" and "max" input
controls = (
<Grid.Row xsmall="one-half" gutter={10}>
<Grid.Col>
<FormInput
onChange={this.handleValueChangeBuilder('minValue')}
placeholder="Min."
ref="focusTarget"
type="number"
value={this.props.filter.value.min}
/>
</Grid.Col>
<Grid.Col>
<FormInput
onChange={this.handleValueChangeBuilder('maxValue')}
placeholder="Max."
type="number"
value={this.props.filter.value.max}
/>
</Grid.Col>
</Grid.Row>
);
} else {
// Render one number input
controls = (
<FormInput
onChange={this.handleValueChangeBuilder('value')}
placeholder={placeholder}
ref="focusTarget"
type="number"
value={this.props.filter.value}
/>
);
}
return controls;
},
render () {
const { filter } = this.props;
// Get mode and presence based on their values with .filter
const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0];
const presence = PRESENCE_OPTIONS.filter(i => i.value === filter.presence)[0];
return (
<div>
<FormField>
<FormSelect
onChange={this.selectPresence}
options={PRESENCE_OPTIONS}
value={presence.value}
/>
</FormField>
<FormField>
<FormSelect
onChange={this.selectMode}
options={MODE_OPTIONS}
value={mode.value}
/>
</FormField>
{this.renderControls(presence, mode)}
</div>
);
},
});
module.exports = NumberArrayFilter;
|
components/GoogleAnalytics/GoogleAnalytics.js | saintnikopol/react-static-boilerplate | /**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import React, { Component } from 'react';
import { googleAnalyticsId } from '../../config';
const trackingCode = { __html:
`(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=` +
`function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;` +
`e=o.createElement(i);r=o.getElementsByTagName(i)[0];` +
`e.src='https://www.google-analytics.com/analytics.js';` +
`r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));` +
`ga('create','${googleAnalyticsId}','auto');ga('send','pageview');`,
};
class GoogleAnalytics extends Component {
render() {
return <script dangerouslySetInnerHTML={trackingCode} />;
}
}
export default GoogleAnalytics;
|
website/irulez/src/components/admin_menu/fields/PasswordField.js | deklungel/iRulez | import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import classNames from 'classnames';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import InputAdornment from '@material-ui/core/InputAdornment';
import IconButton from '@material-ui/core/IconButton';
const styles = theme => ({
textField: {
marginLeft: theme.spacing.unit,
marginRight: theme.spacing.unit
},
content: {
overflowY: 'visible'
}
});
class PasswordField extends Component {
state = {
showPassword: false
};
onChange = name => event => {
this.props.handleChange(name, event.target.value);
};
handleClickShowPassword = () => {
this.setState(state => ({ showPassword: !state.showPassword }));
};
render() {
const { classes, field } = this.props;
return (
<TextField
required={field.required}
error={this.state.passwordError}
id={field.id}
className={classNames(classes.margin, classes.textField)}
type={this.state.showPassword ? 'text' : 'password'}
label={field.label}
onChange={this.onChange(field.id)}
fullWidth
InputProps={{
endAdornment: (
<InputAdornment position='end'>
<IconButton aria-label='Toggle password visibility' onClick={this.handleClickShowPassword}>
{this.state.showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
)
}}
/>
);
}
}
export default withStyles(styles)(PasswordField);
|
src/component/CreateTagButton.js | rsuite/rsuite-tag | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button } from 'rsuite';
import omit from 'lodash/omit';
const propTypes = {
inputMaxLength: PropTypes.number,
onInputConfirm: PropTypes.func
};
const defaultProps = {
inputMaxLength: 128
};
class CreateButton extends Component {
constructor(props) {
super(props);
this.state = {
inputVisible: false,
inputValue: ''
};
}
handleShowInput = () => {
this.setState({ inputVisible: true }, () => this.input.focus());
};
bindInput = (ref) => {
this.input = ref;
};
handleInputConfirm = () => {
const { onInputConfirm } = this.props;
const state = this.state;
const inputValue = state.inputValue;
this.setState({
inputVisible: false,
inputValue: ''
});
onInputConfirm && onInputConfirm(inputValue);
};
handleInputChange = (e) => {
this.setState({ inputValue: e.target.value });
};
handleInputKeyDown = (e) => {
if (e.keyCode === 13) { // Press ENTER
this.handleInputConfirm();
}
};
render() {
const { children, inputMaxLength } = this.props;
const props = omit(this.props, [...Object.keys(propTypes), children]);
const { inputVisible, inputValue } = this.state;
return (
<div className="rs-tag-create-button-wrap" {...props}>
{
inputVisible && (
<input
ref={this.bindInput}
type="input"
className="form-control input-sm rs-tag-create-button-input"
value={inputValue}
maxLength={inputMaxLength}
onChange={this.handleInputChange}
onBlur={this.handleInputConfirm}
onKeyDown={this.handleInputKeyDown}
/>
)
}
{
!inputVisible &&
<Button
className="rs-tag-create-button"
size="xs"
onClick={this.handleShowInput}
>{children || '+ 新标签'}</Button>
}
</div>
);
}
}
CreateButton.propTypes = propTypes;
CreateButton.defaultProps = defaultProps;
export default CreateButton;
|
src/templates/page.js | green-arrow/ibchamilton | import React from 'react';
import styled from 'react-emotion';
import Link from 'gatsby-link';
import Container from '../components/Container';
import screenSizes from '../utils/screen-sizes';
const PageLayout = styled(Container)`
@media (min-width: ${screenSizes.MEDIUM}) {
display: flex;
}
`;
const SideNav = styled.div`
display: none;
@media (min-width: ${screenSizes.MEDIUM}) {
display: block;
flex: 0 1 auto;
max-width: 15rem;
}
`;
const SideNavList = styled.ul`
margin-right: 2rem;
padding-right: 2rem;
border-right: 1px solid #cacaca;
li {
font-size: 1.25rem;
list-style: none;
:not(:last-child) {
margin-bottom: 0.5rem;
}
}
`;
const MainContent = styled.div`
flex: 1 0 0;
`;
export default props => {
const { data, pathContext: { rootPageSlug } } = props;
const { markdownRemark: post, allMarkdownRemark: { edges: subPages } } = data;
const showSideNav = !!subPages && subPages.length > 1;
const rootPage = showSideNav && subPages[0].node;
const firstSubPage = showSideNav && subPages[1].node;
return (
<PageLayout>
{showSideNav && (
<SideNav>
<SideNavList>
<li key={rootPageSlug}>
<Link to={firstSubPage.fields.slug}>
{rootPage.frontmatter.title}
</Link>
</li>
{subPages.slice(1, subPages.length).map(({ node }) => {
const { fields: { slug }, frontmatter: { title } } = node;
return (
<li key={slug}>
<Link to={slug}>{title}</Link>
</li>
);
})}
</SideNavList>
</SideNav>
)}
<MainContent>
<div dangerouslySetInnerHTML={{ __html: post.html }} />
</MainContent>
</PageLayout>
);
};
export const query = graphql`
query PageQuery($slug: String!, $subNavSlugRegex: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
allMarkdownRemark(
filter: { fields: { slug: { regex: $subNavSlugRegex } } }
sort: { fields: [fields___slug] }
) {
edges {
node {
fields {
slug
}
frontmatter {
title
}
}
}
}
}
`;
|
pootle/static/js/shared/components/FormElement.js | evernote/zing | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
import FormCheckedInput from './FormCheckedInput';
import FormValueInput from './FormValueInput';
import FormSelectInput from './FormSelectInput';
const FormElement = React.createClass({
propTypes: {
type: React.PropTypes.string,
label: React.PropTypes.string.isRequired,
multiple: React.PropTypes.bool,
name: React.PropTypes.string.isRequired,
handleChange: React.PropTypes.func.isRequired,
value: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.bool,
React.PropTypes.number,
React.PropTypes.string,
React.PropTypes.array,
]).isRequired,
help: React.PropTypes.string,
errors: React.PropTypes.array,
},
/* Lifecycle */
getDefaultProps() {
return {
type: 'text',
};
},
/* Layout */
render() {
const { errors } = this.props;
const fieldId = `id_${this.props.name}`;
const hint = this.props.help;
const InputComponent = {
text: FormValueInput,
email: FormValueInput,
password: FormValueInput,
textarea: FormValueInput,
checkbox: FormCheckedInput,
radio: FormCheckedInput,
select: FormSelectInput,
}[this.props.type];
return (
<div className="field-wrapper">
<label htmlFor={fieldId}>{this.props.label}</label>
<InputComponent id={fieldId} {...this.props} />
{errors && (
<ul className="errorlist">
{errors.map((msg, i) => (
<li key={i}>{msg}</li>
))}
</ul>
)}
{hint && <span className="helptext">{hint}</span>}
</div>
);
},
});
export default FormElement;
|
public/js/components/profile/visitor/activityfeed/activityComp1.react.js | rajikaimal/Coupley | // import React from 'react';
// import Card from 'material-ui/lib/card/card';
// import CardActions from 'material-ui/lib/card/card-actions';
// import CardHeader from 'material-ui/lib/card/card-header';
// import CardMedia from 'material-ui/lib/card/card-media';
// import CardTitle from 'material-ui/lib/card/card-title';
// import FlatButton from 'material-ui/lib/flat-button';
// import CardText from 'material-ui/lib/card/card-text';
// import IconMenu from 'material-ui/lib/menus/icon-menu';
// import MenuItem from 'material-ui/lib/menus/menu-item';
// import IconButton from 'material-ui/lib/icon-button';
// import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert';
// const AvatarExampleSimple = () => (
// <div>
// <IconMenu
// iconButtonElement={<IconButton>
// <MoreVertIcon />
// </IconButton>}
// anchorOrigin={{horizontal: 'left', vertical: 'top'}}
// targetOrigin={{horizontal: 'left', vertical: 'top'}}
// >
// <MenuItem primaryText="Edit" />
// <MenuItem primaryText="Remove" />
// <MenuItem primaryText="Block" />
// </IconMenu>
// </div>
// );
// const style = {
// width: 800,
// margin: 40,
// };
// var CardWithAvatar = React.createClass({
// render: function () {
// return (
// <div style={style}>
// <Card>
// <CardHeader
// title="Diylon"
// subtitle="2016.01.20"
// avatar="http://all4desktop.com/data_images/original/4237684-images.jpg" />
// <div>
// <AvatarExampleSimple />
// </div>
// <CardText>
// :o ;)
// </CardText>
// <CardMedia>
// <img src="http://all4desktop.com/data_images/original/4237684-images.jpg" />
// </CardMedia>
// <CardActions>
// <FlatButton label="Like" />
// <FlatButton label="Comment" />
// <FlatButton label="Share" />
// </CardActions>
// </Card>
// </div>
// );
// }
// });
// export default CardWithAvatar;
|
assets/js/components/Pane.js | basarevych/webfm | import React from 'react';
import PropTypes from 'prop-types';
import { Tooltip } from 'reactstrap';
import { DropTarget } from 'react-dnd';
import DisabledBody from './DisabledBody';
import LoadingBody from './LoadingBody';
import Header from '../containers/Header';
import ContentBody from '../containers/ContentBody';
import InfoBody from '../containers/InfoBody';
import ListBody from '../containers/ListBody';
import * as dragTypes from '../constants/dragTypes';
const paneTarget = {
drop(props, monitor) {
let item = monitor.getItem();
props.onDrop(item.pane, item.name, item.isSelected);
},
canDrop(props, monitor) {
return monitor.getItem().pane !== props.which && props.mode === 'LIST';
}
};
function collect(connect, monitor) {
return {
connectDropTarget: connect.dropTarget(),
isDraggingNode: monitor.canDrop(),
isDraggedOver: monitor.canDrop() && monitor.isOver(),
};
}
@DropTarget(dragTypes.NODE, paneTarget, collect)
class Pane extends React.Component {
static propTypes = {
which: PropTypes.string.isRequired,
mode: PropTypes.string.isRequired,
breakpoint: PropTypes.string.isRequired,
isActive: PropTypes.bool.isRequired,
isDisabled: PropTypes.bool.isRequired,
isLoading: PropTypes.bool.isRequired,
isOtherDragging: PropTypes.bool.isRequired,
isOtherDraggingSelected: PropTypes.bool.isRequired,
isOtherDraggingCopy: PropTypes.bool.isRequired,
connectDropTarget: PropTypes.func,
isDraggingNode: PropTypes.bool,
isDraggedOver: PropTypes.bool,
onDrop: PropTypes.func.isRequired,
onPaneClick: PropTypes.func.isRequired,
};
static defaultProps = {
connectDropTarget: arg => arg,
isDraggingNode: false,
isDraggedOver: false,
};
render() {
let header = null;
let body = null;
if (this.props.isDisabled) {
body = <DisabledBody />;
} else if (this.props.isLoading) {
body = <LoadingBody />;
} else {
if (this.props.mode === 'CONTENTS')
body = <ContentBody which={this.props.which} />;
else if (this.props.mode === 'INFO')
body = <InfoBody which={this.props.which} />;
else
body = <ListBody which={this.props.which} />;
header = (
<React.Fragment>
<Header which={this.props.which} />
<Tooltip
placement={this.props.breakpoint === 'xs' ? 'top' : (this.props.which === 'LEFT' ? 'right' : 'left')}
target={this.props.which + '-view'}
isOpen={
this.props.mode === 'LIST' &&
this.props.isOtherDragging &&
!this.props.isOtherDraggingSelected &&
this.props.isOtherDraggingCopy
}
dangerouslySetInnerHTML={{ __html: __('copy_drop_hint') }}
/>
<Tooltip
placement={this.props.breakpoint === 'xs' ? 'top' : (this.props.which === 'LEFT' ? 'right' : 'left')}
target={this.props.which + '-view'}
isOpen={
this.props.mode === 'LIST' &&
this.props.isOtherDragging &&
this.props.isOtherDraggingSelected &&
this.props.isOtherDraggingCopy
}
dangerouslySetInnerHTML={{ __html: __('copy_drop_selected_hint') }}
/>
<Tooltip
placement={this.props.breakpoint === 'xs' ? 'top' : (this.props.which === 'LEFT' ? 'right' : 'left')}
target={this.props.which + '-view'}
isOpen={
this.props.mode === 'LIST' &&
this.props.isOtherDragging &&
!this.props.isOtherDraggingSelected &&
!this.props.isOtherDraggingCopy
}
dangerouslySetInnerHTML={{ __html: __('move_drop_hint') }}
/>
<Tooltip
placement={this.props.breakpoint === 'xs' ? 'top' : (this.props.which === 'LEFT' ? 'right' : 'left')}
target={this.props.which + '-view'}
isOpen={
this.props.mode === 'LIST' &&
this.props.isOtherDragging &&
this.props.isOtherDraggingSelected &&
!this.props.isOtherDraggingCopy
}
dangerouslySetInnerHTML={{ __html: __('move_drop_selected_hint') }}
/>
<Tooltip
placement={this.props.breakpoint === 'xs' ? 'top' : (this.props.which === 'LEFT' ? 'right' : 'left')}
target={this.props.which + '-view'}
isOpen={
this.props.mode !== 'LIST' &&
this.props.isOtherDragging
}
dangerouslySetInnerHTML={{ __html: __('switch_to_list_hint') }}
/>
</React.Fragment>
);
}
return this.props.connectDropTarget(
<div className="pane" onClick={this.props.onPaneClick}>
<div
id={this.props.which + '-view'}
className={'view rounded' +
(this.props.isDraggedOver
? ' drop-ready'
: (this.props.isDraggingNode
? ' drop-alert'
: (this.props.isActive
? ' active'
: '')))
}
>
{header}
{body}
</div>
</div>
);
}
}
export default Pane;
|
src/client/scripts/client.js | jingcleovil/react-webpack-boilerplate | import React from 'react';
import AppRoot from '../../app/components/AppRoot';
React.render(<AppRoot />, document.body); |
src/components/RewardCalculator.js | jhkmjnhamster/vcash-electron | import React from 'react'
import { translate } from 'react-i18next'
import { action, computed, observable } from 'mobx'
import { inject, observer } from 'mobx-react'
import { Input } from 'antd'
import { calculateIncentive, calculatePoW } from '../utilities/blockRewards'
@translate(['wallet'], { wait: true })
@inject('gui', 'wallet')
@observer
class RewardCalculator extends React.Component {
@observable enteredBlock = ''
constructor (props) {
super(props)
this.t = props.t
this.gui = props.gui
this.wallet = props.wallet
}
/**
* Get block.
* @function block
* @return {number} Entered or current block.
*/
@computed
get block () {
return this.enteredBlock.length === 0
? this.wallet.info.getinfo.blocks
: Math.round(this.enteredBlock)
}
/**
* Get proof-of-work reward.
* @function powReward
* @return {number} Reward.
*/
@computed
get powReward () {
return calculatePoW(this.block)
}
/**
* Get incentive percent of PoW reward.
* @function incentivePercent
* @return {number} Percent.
*/
@computed
get incentivePercent () {
return calculateIncentive(this.block)
}
/**
* Get mining share.
* @function miningReward
* @return {number} Reward.
*/
@computed
get miningReward () {
return this.powReward - this.incentiveReward
}
/**
* Get incentive share.
* @function incentiveReward
* @return {number} Reward.
*/
@computed
get incentiveReward () {
return this.powReward / 100 * this.incentivePercent
}
/**
* Set block.
* @function setBlock
* @param {object} e - Input element event.
*/
@action
setBlock = e => {
const block = typeof e === 'undefined' ? '' : e.target.value
if (block.toString().match(/^[0-9]{0,7}$/) !== null) {
this.enteredBlock = block
}
}
render () {
return (
<div className='flex'>
<div style={{ margin: '0 36px 0 0' }}>
<div className='flex' style={{ margin: '0 0 5px 0' }}>
<i className='material-icons md-16'>extension</i>
<p>{this.t('wallet:block')}</p>
</div>
<div className='flex'>
<i className='material-icons md-16'>stars</i>
<p>{this.t('wallet:powReward')}</p>
</div>
<div className='flex'>
<i className='material-icons md-16'>developer_board</i>
<p>{this.t('wallet:miningReward')}</p>
</div>
<div className='flex'>
<i className='material-icons md-16'>event_seat</i>
<p>{this.t('wallet:incentiveReward')}</p>
</div>
</div>
<div style={{ margin: '0 0 2px 0' }}>
<Input
maxLength={7}
onChange={this.setBlock}
placeholder={this.block}
size='small'
style={{ margin: '0 0 5px 0', width: '60px' }}
value={this.enteredBlock}
/>
<p>
<span style={{ fontWeight: '500' }}>
{new Intl.NumberFormat(this.gui.language, {
minimumFractionDigits: 6,
maximumFractionDigits: 6
}).format(this.powReward)}
</span>{' '}
XVC
</p>
<p>
<span style={{ fontWeight: '500' }}>
{new Intl.NumberFormat(this.gui.language, {
minimumFractionDigits: 6,
maximumFractionDigits: 6
}).format(this.miningReward)}
</span>{' '}
XVC ({100 - this.incentivePercent}%)
</p>
<p>
<span style={{ fontWeight: '500' }}>
{new Intl.NumberFormat(this.gui.language, {
minimumFractionDigits: 6,
maximumFractionDigits: 6
}).format(this.incentiveReward)}
</span>{' '}
XVC ({this.incentivePercent}%)
</p>
</div>
</div>
)
}
}
export default RewardCalculator
|
app/index.js | agrant216/React-Electron-Mtg | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, hashHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import routes from './routes';
import configureStore from './store/configureStore';
import './app.global.css';
const store = configureStore();
const history = syncHistoryWithStore(hashHistory, store);
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
document.getElementById('root')
);
|
src/components/blocks/BlockImage.js | m0sk1t/react_email_editor | import React from 'react';
const BlockImage = ({ blockOptions }) => {
const alt = "cool image!";
return (
<table
width={blockOptions.elements[0].width.match(/\d+/)[0]}
cellPadding="0"
cellSpacing="0"
role="presentation"
>
<tbody>
<tr>
<td
width={blockOptions.elements[0].width.match(/\d+/)[0]}
>
<a
href={blockOptions.elements[0].link}
target="_blank">
<img alt={alt} width={blockOptions.elements[0].width.match(/\d+/)[0]} src={blockOptions.elements[0].source} />
</a>
</td>
</tr>
</tbody>
</table>
);
};
export default BlockImage;
|
client/components/Photo.js | kutyel/learn-redux | import React from 'react'
import { Link } from 'react-router'
import CSSTransitionGroup from 'react-addons-css-transition-group'
const Photo = ({ post: { code, caption, likes, display_src: src, liked }, comments, i, increment, decrement }) => (
<figure className='grid-figure'>
<div className='grid-photo-wrap'>
<Link to={`/view/${code}`}>
<img src={src} alt={caption} className='grid-photo' />
</Link>
<CSSTransitionGroup
transitionName='like'
transitionEnterTimeout={500}
transitionLeaveTimeout={500}>
<span key={likes} className='likes-heart'>{likes}</span>
</CSSTransitionGroup>
</div>
<figcaption>
<p>{caption}</p>
<div className='control-buttons'>
<button onClick={() => liked ? decrement(i) : increment(i)} className={liked && 'liked'}>♥ {likes}</button>
<Link className='button' to={`/view/${code}`}>
<span className='comment-count'>
<span className='speech-bubble' />
{comments[code] ? comments[code].length : 0}
</span>
</Link>
</div>
</figcaption>
</figure >
)
export default Photo
|
app/javascript/mastodon/features/notifications/components/notification.js | primenumber/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { injectIntl, FormattedMessage, defineMessages } from 'react-intl';
import { HotKeys } from 'react-hotkeys';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { me } from 'mastodon/initial_state';
import StatusContainer from 'mastodon/containers/status_container';
import AccountContainer from 'mastodon/containers/account_container';
import FollowRequestContainer from '../containers/follow_request_container';
import Icon from 'mastodon/components/icon';
import Permalink from 'mastodon/components/permalink';
import classNames from 'classnames';
const messages = defineMessages({
favourite: { id: 'notification.favourite', defaultMessage: '{name} favourited your status' },
follow: { id: 'notification.follow', defaultMessage: '{name} followed you' },
ownPoll: { id: 'notification.own_poll', defaultMessage: 'Your poll has ended' },
poll: { id: 'notification.poll', defaultMessage: 'A poll you have voted in has ended' },
reblog: { id: 'notification.reblog', defaultMessage: '{name} boosted your status' },
status: { id: 'notification.status', defaultMessage: '{name} just posted' },
});
const notificationForScreenReader = (intl, message, timestamp) => {
const output = [message];
output.push(intl.formatDate(timestamp, { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' }));
return output.join(', ');
};
export default @injectIntl
class Notification extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
notification: ImmutablePropTypes.map.isRequired,
hidden: PropTypes.bool,
onMoveUp: PropTypes.func.isRequired,
onMoveDown: PropTypes.func.isRequired,
onMention: PropTypes.func.isRequired,
onFavourite: PropTypes.func.isRequired,
onReblog: PropTypes.func.isRequired,
onToggleHidden: PropTypes.func.isRequired,
status: ImmutablePropTypes.map,
intl: PropTypes.object.isRequired,
getScrollPosition: PropTypes.func,
updateScrollBottom: PropTypes.func,
cacheMediaWidth: PropTypes.func,
cachedMediaWidth: PropTypes.number,
unread: PropTypes.bool,
};
handleMoveUp = () => {
const { notification, onMoveUp } = this.props;
onMoveUp(notification.get('id'));
}
handleMoveDown = () => {
const { notification, onMoveDown } = this.props;
onMoveDown(notification.get('id'));
}
handleOpen = () => {
const { notification } = this.props;
if (notification.get('status')) {
this.context.router.history.push(`/statuses/${notification.get('status')}`);
} else {
this.handleOpenProfile();
}
}
handleOpenProfile = () => {
const { notification } = this.props;
this.context.router.history.push(`/accounts/${notification.getIn(['account', 'id'])}`);
}
handleMention = e => {
e.preventDefault();
const { notification, onMention } = this.props;
onMention(notification.get('account'), this.context.router.history);
}
handleHotkeyFavourite = () => {
const { status } = this.props;
if (status) this.props.onFavourite(status);
}
handleHotkeyBoost = e => {
const { status } = this.props;
if (status) this.props.onReblog(status, e);
}
handleHotkeyToggleHidden = () => {
const { status } = this.props;
if (status) this.props.onToggleHidden(status);
}
getHandlers () {
return {
reply: this.handleMention,
favourite: this.handleHotkeyFavourite,
boost: this.handleHotkeyBoost,
mention: this.handleMention,
open: this.handleOpen,
openProfile: this.handleOpenProfile,
moveUp: this.handleMoveUp,
moveDown: this.handleMoveDown,
toggleHidden: this.handleHotkeyToggleHidden,
};
}
renderFollow (notification, account, link) {
const { intl, unread } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className={classNames('notification notification-follow focusable', { unread })} tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage(messages.follow, { name: account.get('acct') }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<Icon id='user-plus' fixedWidth />
</div>
<span title={notification.get('created_at')}>
<FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} />
</span>
</div>
<AccountContainer id={account.get('id')} hidden={this.props.hidden} />
</div>
</HotKeys>
);
}
renderFollowRequest (notification, account, link) {
const { intl, unread } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className={classNames('notification notification-follow-request focusable', { unread })} tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage({ id: 'notification.follow_request', defaultMessage: '{name} has requested to follow you' }, { name: account.get('acct') }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<Icon id='user' fixedWidth />
</div>
<span title={notification.get('created_at')}>
<FormattedMessage id='notification.follow_request' defaultMessage='{name} has requested to follow you' values={{ name: link }} />
</span>
</div>
<FollowRequestContainer id={account.get('id')} withNote={false} hidden={this.props.hidden} />
</div>
</HotKeys>
);
}
renderMention (notification) {
return (
<StatusContainer
id={notification.get('status')}
withDismiss
hidden={this.props.hidden}
onMoveDown={this.handleMoveDown}
onMoveUp={this.handleMoveUp}
contextType='notifications'
getScrollPosition={this.props.getScrollPosition}
updateScrollBottom={this.props.updateScrollBottom}
cachedMediaWidth={this.props.cachedMediaWidth}
cacheMediaWidth={this.props.cacheMediaWidth}
unread={this.props.unread}
/>
);
}
renderFavourite (notification, link) {
const { intl, unread } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className={classNames('notification notification-favourite focusable', { unread })} tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage(messages.favourite, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<Icon id='star' className='star-icon' fixedWidth />
</div>
<span title={notification.get('created_at')}>
<FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} />
</span>
</div>
<StatusContainer
id={notification.get('status')}
account={notification.get('account')}
muted
withDismiss
hidden={!!this.props.hidden}
getScrollPosition={this.props.getScrollPosition}
updateScrollBottom={this.props.updateScrollBottom}
cachedMediaWidth={this.props.cachedMediaWidth}
cacheMediaWidth={this.props.cacheMediaWidth}
/>
</div>
</HotKeys>
);
}
renderReblog (notification, link) {
const { intl, unread } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className={classNames('notification notification-reblog focusable', { unread })} tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage(messages.reblog, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<Icon id='retweet' fixedWidth />
</div>
<span title={notification.get('created_at')}>
<FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} />
</span>
</div>
<StatusContainer
id={notification.get('status')}
account={notification.get('account')}
muted
withDismiss
hidden={this.props.hidden}
getScrollPosition={this.props.getScrollPosition}
updateScrollBottom={this.props.updateScrollBottom}
cachedMediaWidth={this.props.cachedMediaWidth}
cacheMediaWidth={this.props.cacheMediaWidth}
/>
</div>
</HotKeys>
);
}
renderStatus (notification, link) {
const { intl, unread } = this.props;
return (
<HotKeys handlers={this.getHandlers()}>
<div className={classNames('notification notification-status focusable', { unread })} tabIndex='0' aria-label={notificationForScreenReader(intl, intl.formatMessage(messages.status, { name: notification.getIn(['account', 'acct']) }), notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<Icon id='home' fixedWidth />
</div>
<span title={notification.get('created_at')}>
<FormattedMessage id='notification.status' defaultMessage='{name} just posted' values={{ name: link }} />
</span>
</div>
<StatusContainer
id={notification.get('status')}
account={notification.get('account')}
muted
withDismiss
hidden={this.props.hidden}
getScrollPosition={this.props.getScrollPosition}
updateScrollBottom={this.props.updateScrollBottom}
cachedMediaWidth={this.props.cachedMediaWidth}
cacheMediaWidth={this.props.cacheMediaWidth}
/>
</div>
</HotKeys>
);
}
renderPoll (notification, account) {
const { intl, unread } = this.props;
const ownPoll = me === account.get('id');
const message = ownPoll ? intl.formatMessage(messages.ownPoll) : intl.formatMessage(messages.poll);
return (
<HotKeys handlers={this.getHandlers()}>
<div className={classNames('notification notification-poll focusable', { unread })} tabIndex='0' aria-label={notificationForScreenReader(intl, message, notification.get('created_at'))}>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<Icon id='tasks' fixedWidth />
</div>
<span title={notification.get('created_at')}>
{ownPoll ? (
<FormattedMessage id='notification.own_poll' defaultMessage='Your poll has ended' />
) : (
<FormattedMessage id='notification.poll' defaultMessage='A poll you have voted in has ended' />
)}
</span>
</div>
<StatusContainer
id={notification.get('status')}
account={account}
muted
withDismiss
hidden={this.props.hidden}
getScrollPosition={this.props.getScrollPosition}
updateScrollBottom={this.props.updateScrollBottom}
cachedMediaWidth={this.props.cachedMediaWidth}
cacheMediaWidth={this.props.cacheMediaWidth}
/>
</div>
</HotKeys>
);
}
render () {
const { notification } = this.props;
const account = notification.get('account');
const displayNameHtml = { __html: account.get('display_name_html') };
const link = <bdi><Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHtml} /></bdi>;
switch(notification.get('type')) {
case 'follow':
return this.renderFollow(notification, account, link);
case 'follow_request':
return this.renderFollowRequest(notification, account, link);
case 'mention':
return this.renderMention(notification);
case 'favourite':
return this.renderFavourite(notification, link);
case 'reblog':
return this.renderReblog(notification, link);
case 'status':
return this.renderStatus(notification, link);
case 'poll':
return this.renderPoll(notification, account);
}
return null;
}
}
|
09-react-lab-b/src/app/todo-list.js | iproduct/course-node-express-react | import React from 'react';
export default ({todos}) => (
<ul className="todo-list">
{ todos.map(todo => (<li key={todo.id}><span className="id">{todo.id}. </span>
{todo.title} - {todo.status}
<span className="buttons">...</span>
</li>)) }
</ul>
);
|
src/containers/App.js | bplabombarda/3on3bot.com | import React from 'react'
import getSchedule from '../utils/getSchedule'
export default class App extends React.PureComponent {
state = {
date: new Date(2016, 2, 21),
didInvalidate: false,
isFetching: false,
games: [],
}
componentDidMount () {
const schedule = getSchedule(this.state.date)
console.log(schedule)
}
render () {
return (
<h1>Test!</h1>
)
}
} |
portfolio-site/src/scenes/home/navigation/navbar.js | dave5801/Portfolio | import React, { Component } from 'react';
import './navbar.css';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Writings from './../Writings/writings';
import HomePage from './../homepage/homepage';
import About from './../About/about';
import Projects from './../Projects/projects';
class Navbar extends Component {
render() {
return (
<Router>
<div className="Router-Main">
<div className="Navbar-main">
<ul className="Navbar-elements">
<div className="Nav-left">
<li>
<Link to="/" style={{textDecoration: 'none', color: '#8b939b'}}>A Passion for Engineering</Link>
</li>
</div>
<div className="Nav-right">
<li>
<Link to="/writings" style={{textDecoration: 'none', color: '#8b939b'}}>Writings</Link>
</li>
<li>
<Link to="/about" style={{textDecoration: 'none', color: '#8b939b'}}>About</Link>
</li>
<li>
<Link to="/projects" style={{textDecoration: 'none', color: '#8b939b'}}>Projects</Link>
</li>
</div>
</ul>
</div>
<Route exact path="/" component={HomePage} />
<Route path="/writings" component={Writings} />
<Route path="/about" component={About} />
<Route path="/projects" component={Projects} />
</div>
</Router>
);
}
}
export default Navbar; |
app/js/components/Article.js | andy02081224/chenscoffee-2 | 'use strict';
import React from 'react';
const Article = React.createClass({
render() {
return <article className={'article ' + this.props.class}>
<div className="article__cover">
<img src="images/product-detail.jpg" alt=""/>
</div>
<p className="article__content">
臻咖啡座落於安靜的埔心街區,讓您放鬆、聊天,細細品嚐咖啡度過美好時光。
</p>
</article>
}
});
export default Article;
|
docs/app/Examples/collections/Breadcrumb/Variations/BreadcrumbExampleMiniSize.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Breadcrumb } from 'semantic-ui-react'
const BreadcrumbExampleMiniSize = () => (
<Breadcrumb size='mini'>
<Breadcrumb.Section link>Home</Breadcrumb.Section>
<Breadcrumb.Divider icon='right chevron' />
<Breadcrumb.Section link>Registration</Breadcrumb.Section>
<Breadcrumb.Divider icon='right chevron' />
<Breadcrumb.Section active>Personal Information</Breadcrumb.Section>
</Breadcrumb>
)
export default BreadcrumbExampleMiniSize
|
src/index.js | lzm854676408/big-demo |
import React from 'react';
import {render} from 'react-dom';
import {Router,browserHistory} from 'react-router';
import routes from './routes.js';
import './style/commen.css';
import injectTapEventPlugin from 'react-tap-event-plugin';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
render(<Router routes={routes} history={browserHistory} />
,document.getElementById('root'));
|
app/javascript/mastodon/features/account_timeline/index.js | blackle/mastodon | import React from 'react';
import { connect } from 'react-redux';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { fetchAccount } from '../../actions/accounts';
import { expandAccountFeaturedTimeline, expandAccountTimeline } from '../../actions/timelines';
import StatusList from '../../components/status_list';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import HeaderContainer from './containers/header_container';
import ColumnBackButton from '../../components/column_back_button';
import { List as ImmutableList } from 'immutable';
import ImmutablePureComponent from 'react-immutable-pure-component';
const mapStateToProps = (state, { params: { accountId }, withReplies = false }) => {
const path = withReplies ? `${accountId}:with_replies` : accountId;
return {
statusIds: state.getIn(['timelines', `account:${path}`, 'items'], ImmutableList()),
featuredStatusIds: withReplies ? ImmutableList() : state.getIn(['timelines', `account:${accountId}:pinned`, 'items'], ImmutableList()),
isLoading: state.getIn(['timelines', `account:${path}`, 'isLoading']),
hasMore: state.getIn(['timelines', `account:${path}`, 'hasMore']),
};
};
@connect(mapStateToProps)
export default class AccountTimeline extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
statusIds: ImmutablePropTypes.list,
featuredStatusIds: ImmutablePropTypes.list,
isLoading: PropTypes.bool,
hasMore: PropTypes.bool,
withReplies: PropTypes.bool,
};
componentWillMount () {
const { params: { accountId }, withReplies } = this.props;
this.props.dispatch(fetchAccount(accountId));
if (!withReplies) {
this.props.dispatch(expandAccountFeaturedTimeline(accountId));
}
this.props.dispatch(expandAccountTimeline(accountId, { withReplies }));
}
componentWillReceiveProps (nextProps) {
if ((nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) || nextProps.withReplies !== this.props.withReplies) {
this.props.dispatch(fetchAccount(nextProps.params.accountId));
if (!nextProps.withReplies) {
this.props.dispatch(expandAccountFeaturedTimeline(nextProps.params.accountId));
}
this.props.dispatch(expandAccountTimeline(nextProps.params.accountId, { withReplies: nextProps.params.withReplies }));
}
}
handleLoadMore = maxId => {
this.props.dispatch(expandAccountTimeline(this.props.params.accountId, { maxId, withReplies: this.props.withReplies }));
}
render () {
const { shouldUpdateScroll, statusIds, featuredStatusIds, isLoading, hasMore } = this.props;
if (!statusIds && isLoading) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
return (
<Column>
<ColumnBackButton />
<StatusList
prepend={<HeaderContainer accountId={this.props.params.accountId} />}
scrollKey='account_timeline'
statusIds={statusIds}
featuredStatusIds={featuredStatusIds}
isLoading={isLoading}
hasMore={hasMore}
onLoadMore={this.handleLoadMore}
shouldUpdateScroll={shouldUpdateScroll}
/>
</Column>
);
}
}
|
src/widgets/DropdownRow.js | sussol/mobile | /* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import React from 'react';
import { StyleSheet, TextInput } from 'react-native';
import PropTypes from 'prop-types';
import { DropDown } from './DropDown';
import { FlexRow } from './FlexRow';
import { LIGHT_GREY, SUSSOL_ORANGE, APP_FONT_FAMILY } from '../globalStyles';
/**
* Layout component rendering a Dropdown and a TextInput.
*
* @prop {Text} currentOptionText Text to display for the label text prop.
* @prop {Array} options The options of the drop down. See PopoverDropdown.
* @prop {Func} onSelection Callback when selecting a dropdown option.
* @prop {String} dropdownTitle The title of the drop down menu when opened.
* @prop {String} placeholder Placeholder string value, when no value has been chosen/entered.
* @prop {Bool} isDisabled Indicator if this component should not be editable.
*/
export const DropdownRow = ({
currentOptionText,
options,
onSelection,
dropdownTitle,
placeholder,
isDisabled,
onChangeText,
}) => (
<FlexRow alignItems="center" justifyContent="center">
<DropDown
style={localStyles.dropDownStyle}
values={options}
onValueChange={onSelection}
headerValue={dropdownTitle}
isDisabled={!options.length}
/>
<TextInput
editable={!isDisabled}
onChangeText={onChangeText}
value={currentOptionText}
underlineColorAndroid={SUSSOL_ORANGE}
style={localStyles.textInputStyle}
placeholder={placeholder}
placeholderTextColor={LIGHT_GREY}
/>
</FlexRow>
);
const localStyles = StyleSheet.create({
containerStyle: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
iconsContainerStyle: {
flexDirection: 'row-reverse',
justifyContent: 'space-between',
flex: 1,
},
textInputStyle: {
flex: 2,
fontFamily: APP_FONT_FAMILY,
},
dropDownStyle: {
flex: 1,
marginBottom: 0,
marginLeft: 0,
marginTop: 0,
},
});
DropdownRow.defaultProps = {
placeholder: '',
currentOptionText: '',
isDisabled: false,
};
DropdownRow.propTypes = {
currentOptionText: PropTypes.string,
options: PropTypes.array.isRequired,
onSelection: PropTypes.func.isRequired,
dropdownTitle: PropTypes.string.isRequired,
onChangeText: PropTypes.func.isRequired,
placeholder: PropTypes.string,
isDisabled: PropTypes.bool,
};
|
src/components/TextViews.js | KtuluTeam/Ktulu | import React from 'react'
import {
Text,
View,
TouchableOpacity,
Image
} from 'react-native'
import * as cards from '../cards'
import { styles } from '../styles/styles'
export const ReadLoud = ({text}) => {
if (text === '')
return (<View />)
return (
<View style={styles.readLoud}>
<Text style={styles.readLoudText}>
{text}
</Text>
</View>
)
}
export const ManitouInfo = ({text}) => {
if (text === '')
return (<View />)
return (
<View style={styles.manitouInfo}>
<Text style={styles.manitouInfoText}>
{text}
</Text>
</View>
)
}
|
src/svg-icons/device/signal-wifi-1-bar.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi1Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"/><path d="M6.67 14.86L12 21.49v.01l.01-.01 5.33-6.63C17.06 14.65 15.03 13 12 13s-5.06 1.65-5.33 1.86z"/>
</SvgIcon>
);
DeviceSignalWifi1Bar = pure(DeviceSignalWifi1Bar);
DeviceSignalWifi1Bar.displayName = 'DeviceSignalWifi1Bar';
export default DeviceSignalWifi1Bar;
|
src/icons/BatteryLow.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class BatteryLow extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M42.1,384h381.1c5.5,0,9.9-4.5,9.9-10v-54h36.9c5.6,0,10.1-4.5,10.1-10V202c0-5.5-4.5-10-10.1-10H433v-54
c0-5.5-4.3-10-9.9-10H42.1c-5.6,0-10.1,4.5-10.1,10v236C32,379.5,36.5,384,42.1,384z M401,160v32v32h32.2H448v64h-14.8H401v32v32
H224l-32-192H401z"></path>
</g>;
} return <IconBase>
<path d="M42.1,384h381.1c5.5,0,9.9-4.5,9.9-10v-54h36.9c5.6,0,10.1-4.5,10.1-10V202c0-5.5-4.5-10-10.1-10H433v-54
c0-5.5-4.3-10-9.9-10H42.1c-5.6,0-10.1,4.5-10.1,10v236C32,379.5,36.5,384,42.1,384z M401,160v32v32h32.2H448v64h-14.8H401v32v32
H224l-32-192H401z"></path>
</IconBase>;
}
};BatteryLow.defaultProps = {bare: false} |
docs/app/Examples/collections/Table/Variations/TableExampleStriped.js | shengnian/shengnian-ui-react | import React from 'react'
import { Table } from 'shengnian-ui-react'
const TableExampleStriped = () => (
<Table striped>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Date Joined</Table.HeaderCell>
<Table.HeaderCell>E-mail</Table.HeaderCell>
<Table.HeaderCell>Called</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>John Lilki</Table.Cell>
<Table.Cell>September 14, 2013</Table.Cell>
<Table.Cell>jhlilk22@yahoo.com</Table.Cell>
<Table.Cell>No</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jamie Harington</Table.Cell>
<Table.Cell>January 11, 2014</Table.Cell>
<Table.Cell>jamieharingonton@yahoo.com</Table.Cell>
<Table.Cell>Yes</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jill Lewis</Table.Cell>
<Table.Cell>May 11, 2014</Table.Cell>
<Table.Cell>jilsewris22@yahoo.com</Table.Cell>
<Table.Cell>Yes</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>John Lilki</Table.Cell>
<Table.Cell>September 14, 2013</Table.Cell>
<Table.Cell>jhlilk22@yahoo.com</Table.Cell>
<Table.Cell>No</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>John Lilki</Table.Cell>
<Table.Cell>September 14, 2013</Table.Cell>
<Table.Cell>jhlilk22@yahoo.com</Table.Cell>
<Table.Cell>No</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jamie Harington</Table.Cell>
<Table.Cell>January 11, 2014</Table.Cell>
<Table.Cell>jamieharingonton@yahoo.com</Table.Cell>
<Table.Cell>Yes</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jill Lewis</Table.Cell>
<Table.Cell>May 11, 2014</Table.Cell>
<Table.Cell>jilsewris22@yahoo.com</Table.Cell>
<Table.Cell>Yes</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>John Lilki</Table.Cell>
<Table.Cell>September 14, 2013</Table.Cell>
<Table.Cell>jhlilk22@yahoo.com</Table.Cell>
<Table.Cell>No</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
)
export default TableExampleStriped
|
src/svg-icons/hardware/speaker-group.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareSpeakerGroup = (props) => (
<SvgIcon {...props}>
<path d="M18.2 1H9.8C8.81 1 8 1.81 8 2.8v14.4c0 .99.81 1.79 1.8 1.79l8.4.01c.99 0 1.8-.81 1.8-1.8V2.8c0-.99-.81-1.8-1.8-1.8zM14 3c1.1 0 2 .89 2 2s-.9 2-2 2-2-.89-2-2 .9-2 2-2zm0 13.5c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"/><circle cx="14" cy="12.5" r="2.5"/><path d="M6 5H4v16c0 1.1.89 2 2 2h10v-2H6V5z"/>
</SvgIcon>
);
HardwareSpeakerGroup = pure(HardwareSpeakerGroup);
HardwareSpeakerGroup.displayName = 'HardwareSpeakerGroup';
export default HardwareSpeakerGroup;
|
src/js/app/components/devtools.js | ericf89/survey | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
const DevTools = createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-q"
defaultIsVisible={false}
>
<LogMonitor/>
</DockMonitor>
);
export default DevTools;
|
frontend/src/Activity/Queue/QueueConnector.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import * as commandNames from 'Commands/commandNames';
import withCurrentPage from 'Components/withCurrentPage';
import { clearAlbums, fetchAlbums } from 'Store/Actions/albumActions';
import { executeCommand } from 'Store/Actions/commandActions';
import * as queueActions from 'Store/Actions/queueActions';
import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector';
import hasDifferentItems from 'Utilities/Object/hasDifferentItems';
import selectUniqueIds from 'Utilities/Object/selectUniqueIds';
import { registerPagePopulator, unregisterPagePopulator } from 'Utilities/pagePopulator';
import Queue from './Queue';
function createMapStateToProps() {
return createSelector(
(state) => state.artist,
(state) => state.albums,
(state) => state.queue.options,
(state) => state.queue.paged,
createCommandExecutingSelector(commandNames.REFRESH_MONITORED_DOWNLOADS),
(artist, albums, options, queue, isRefreshMonitoredDownloadsExecuting) => {
return {
isArtistFetching: artist.isFetching,
isArtistPopulated: artist.isPopulated,
isAlbumsFetching: albums.isFetching,
isAlbumsPopulated: albums.isPopulated,
albumsError: albums.error,
isRefreshMonitoredDownloadsExecuting,
...options,
...queue
};
}
);
}
const mapDispatchToProps = {
...queueActions,
fetchAlbums,
clearAlbums,
executeCommand
};
class QueueConnector extends Component {
//
// Lifecycle
componentDidMount() {
const {
useCurrentPage,
fetchQueue,
fetchQueueStatus,
gotoQueueFirstPage
} = this.props;
registerPagePopulator(this.repopulate);
if (useCurrentPage) {
fetchQueue();
} else {
gotoQueueFirstPage();
}
fetchQueueStatus();
}
componentDidUpdate(prevProps) {
if (hasDifferentItems(prevProps.items, this.props.items)) {
const albumIds = selectUniqueIds(this.props.items, 'albumId');
if (albumIds.length) {
this.props.fetchAlbums({ albumIds });
} else {
this.props.clearAlbums();
}
}
if (
this.props.includeUnknownArtistItems !==
prevProps.includeUnknownArtistItems
) {
this.repopulate();
}
}
componentWillUnmount() {
unregisterPagePopulator(this.repopulate);
this.props.clearQueue();
this.props.clearAlbums();
}
//
// Control
repopulate = () => {
this.props.fetchQueue();
}
//
// Listeners
onFirstPagePress = () => {
this.props.gotoQueueFirstPage();
}
onPreviousPagePress = () => {
this.props.gotoQueuePreviousPage();
}
onNextPagePress = () => {
this.props.gotoQueueNextPage();
}
onLastPagePress = () => {
this.props.gotoQueueLastPage();
}
onPageSelect = (page) => {
this.props.gotoQueuePage({ page });
}
onSortPress = (sortKey) => {
this.props.setQueueSort({ sortKey });
}
onTableOptionChange = (payload) => {
this.props.setQueueTableOption(payload);
if (payload.pageSize) {
this.props.gotoQueueFirstPage();
}
}
onRefreshPress = () => {
this.props.executeCommand({
name: commandNames.REFRESH_MONITORED_DOWNLOADS
});
}
onGrabSelectedPress = (ids) => {
this.props.grabQueueItems({ ids });
}
onRemoveSelectedPress = (payload) => {
this.props.removeQueueItems(payload);
}
//
// Render
render() {
return (
<Queue
onFirstPagePress={this.onFirstPagePress}
onPreviousPagePress={this.onPreviousPagePress}
onNextPagePress={this.onNextPagePress}
onLastPagePress={this.onLastPagePress}
onPageSelect={this.onPageSelect}
onSortPress={this.onSortPress}
onTableOptionChange={this.onTableOptionChange}
onRefreshPress={this.onRefreshPress}
onGrabSelectedPress={this.onGrabSelectedPress}
onRemoveSelectedPress={this.onRemoveSelectedPress}
{...this.props}
/>
);
}
}
QueueConnector.propTypes = {
useCurrentPage: PropTypes.bool.isRequired,
items: PropTypes.arrayOf(PropTypes.object).isRequired,
includeUnknownArtistItems: PropTypes.bool.isRequired,
fetchQueue: PropTypes.func.isRequired,
fetchQueueStatus: PropTypes.func.isRequired,
gotoQueueFirstPage: PropTypes.func.isRequired,
gotoQueuePreviousPage: PropTypes.func.isRequired,
gotoQueueNextPage: PropTypes.func.isRequired,
gotoQueueLastPage: PropTypes.func.isRequired,
gotoQueuePage: PropTypes.func.isRequired,
setQueueSort: PropTypes.func.isRequired,
setQueueTableOption: PropTypes.func.isRequired,
clearQueue: PropTypes.func.isRequired,
grabQueueItems: PropTypes.func.isRequired,
removeQueueItems: PropTypes.func.isRequired,
fetchAlbums: PropTypes.func.isRequired,
clearAlbums: PropTypes.func.isRequired,
executeCommand: PropTypes.func.isRequired
};
export default withCurrentPage(
connect(createMapStateToProps, mapDispatchToProps)(QueueConnector)
);
|
src/core/Checkbox.js | sateesh2020/letshop | import React, { Component } from 'react';
class Checkbox extends Component {
state = {
isChecked: false,
}
toggleCheckboxChange = () => {
const { handleCheckboxChange, label } = this.props;
this.setState(({ isChecked }) => (
{
isChecked: !isChecked,
}
));
handleCheckboxChange(label);
}
render() {
const { label } = this.props;
const { isChecked } = this.state;
return (
<div className="checkbox">
<label>
<input
type="checkbox"
value={label}
checked={isChecked}
onChange={this.toggleCheckboxChange}
/>
{label}
</label>
</div>
);
}
}
export default Checkbox; |
frontend/src/Components/Filter/Builder/ProtocolFilterBuilderRowValue.js | lidarr/Lidarr | import React from 'react';
import FilterBuilderRowValue from './FilterBuilderRowValue';
const protocols = [
{ id: 'torrent', name: 'Torrent' },
{ id: 'usenet', name: 'Usenet' }
];
function ProtocolFilterBuilderRowValue(props) {
return (
<FilterBuilderRowValue
tagList={protocols}
{...props}
/>
);
}
export default ProtocolFilterBuilderRowValue;
|
src/svg-icons/notification/airline-seat-legroom-reduced.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationAirlineSeatLegroomReduced = (props) => (
<SvgIcon {...props}>
<path d="M19.97 19.2c.18.96-.55 1.8-1.47 1.8H14v-3l1-4H9c-1.65 0-3-1.35-3-3V3h6v6h5c1.1 0 2 .9 2 2l-2 7h1.44c.73 0 1.39.49 1.53 1.2zM5 12V3H3v9c0 2.76 2.24 5 5 5h4v-2H8c-1.66 0-3-1.34-3-3z"/>
</SvgIcon>
);
NotificationAirlineSeatLegroomReduced = pure(NotificationAirlineSeatLegroomReduced);
NotificationAirlineSeatLegroomReduced.displayName = 'NotificationAirlineSeatLegroomReduced';
export default NotificationAirlineSeatLegroomReduced;
|
admin/src/components/PopoutListItem.js | tanbo800/keystone | import blacklist from 'blacklist';
import classnames from 'classnames';
import React from 'react';
var PopoutListItem = React.createClass({
displayName: 'PopoutListItem',
propTypes: {
icon: React.PropTypes.string,
iconHover: React.PropTypes.string,
iconHoverAlt: React.PropTypes.string,
isSelected: React.PropTypes.bool,
label: React.PropTypes.string.isRequired,
onClick: React.PropTypes.func,
},
getInitialState () {
return {
currentIcon: this.props.icon
};
},
setToActive (e) {
this.setState({ currentIcon: e.altKey ? this.props.iconHoverAlt : this.props.iconHover });
},
setToInactive (e) {
this.setState({ currentIcon: this.props.icon });
},
renderIcon () {
if (!this.props.icon) return null;
let iconClassname = classnames('PopoutList__item__icon octicon', ('octicon-' + this.state.currentIcon));
return <span className={iconClassname} />;
},
render () {
let itemClassname = classnames('PopoutList__item', {
'is-selected': this.props.isSelected
});
let props = blacklist(this.props, 'className', 'icon', 'isSelected', 'label');
return (
<button
type="button"
title={this.props.label}
className={itemClassname}
onFocus={this.setToActive}
onBlur={this.setToInactive}
onMouseOver={this.setToActive}
onMouseOut={this.setToInactive}
{...props}
>
{this.renderIcon()}
<span className="PopoutList__item__label">{this.props.label}</span>
</button>
);
}
});
module.exports = PopoutListItem;
|
old-or-not-typescript/learn-redux/shopping-cart/index.js | janaagaard75/framework-investigations | import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import logger from 'redux-logger'
import thunk from 'redux-thunk'
import reducer from './reducers'
import { getAllProducts } from './actions'
import App from './containers/App'
const middleware = process.env.NODE_ENV === 'production' ?
[ thunk ] :
[ thunk, logger() ]
const store = createStore(
reducer,
applyMiddleware(...middleware)
)
store.dispatch(getAllProducts())
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
maodou/posts/client/components/tabs.js | ShannChiang/meteor-react-redux-base | import React from 'react';
export default class extends React.Component {
render() {
return (
<div className={`posts-tab ${this.props.position} ${this.props.color}`}>
<ul className="flex-container">
{
this.props.configs ?
this.props.configs.categories.map((cate, i) =>
<li
key={i}
onClick={(e) => this.props.dispatch(this.props.changeCategory(e, cate))}
className={`${cate===this.props.category ? 'active' : ''} flex-item`}
>
{cate}
</li>
) :
<div />
}
</ul>
</div>
);
}
}
|
src/components/place-form-component.js | havok2905/react-night-entry | import React from 'react';
import ReactDOM from 'react-dom';
import PlaceActions from '../actions/place-actions';
class PlaceForm extends React.Component {
constructor() {
super();
}
clearPlaces() {
PlaceActions.clearPlaces();
this.clearInput();
}
clearInput() {
let node = this.input();
node.value = '';
}
input() {
return ReactDOM.findDOMNode(this.refs.tags);
}
setPlaces() {
this.input().value;
PlaceActions.clearPlaces();
PlaceActions.setPlaces(tags);
}
setAllPlaces() {
PlaceActions.clearPlaces();
PlaceActions.setAllPlaces();
this.clearInput();
}
render() {
return (
<form className='place-form'>
<fieldset>
<label for='tags'>Search for Places</label>
<input name='tags' ref='tags' type='text' placeholder='pizza,beer,bar' />
</fieldset>
<fieldset>
<button type='button' onClick={this.setPlaces.bind(this)} className='button button--save'>Search</button>
<button type='button' onClick={this.setAllPlaces.bind(this)} className='button button--save'>All</button>
<button type='button' onClick={this.clearPlaces.bind(this)} className='button button--destroy'>Clear</button>
</fieldset>
</form>
);
}
}
export default PlaceForm;
|
examples/todo/js/components/TodoApp.js | andimarek/generic-relay | /**
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import AddTodoMutation from '../mutations/AddTodoMutation';
import TodoListFooter from './TodoListFooter';
import TodoTextInput from './TodoTextInput';
import React from 'react';
import Relay from 'react-relay';
class TodoApp extends React.Component {
_handleTextInputSave = (text) => {
Relay.Store.commitUpdate(
new AddTodoMutation({text, viewer: this.props.viewer})
);
}
render() {
var hasTodos = this.props.viewer.totalCount > 0;
return (
<div>
<section className="todoapp">
<header className="header">
<h1>
todos
</h1>
<TodoTextInput
autoFocus={true}
className="new-todo"
onSave={this._handleTextInputSave}
placeholder="What needs to be done?"
/>
</header>
{this.props.children}
{hasTodos &&
<TodoListFooter
todos={this.props.viewer.todos}
viewer={this.props.viewer}
/>
}
</section>
<footer className="info">
<p>
Double-click to edit a todo
</p>
<p>
Created by the <a href="https://facebook.github.io/relay/">
Relay team
</a>
</p>
<p>
Part of <a href="http://todomvc.com">TodoMVC</a>
</p>
</footer>
</div>
);
}
}
export default Relay.createContainer(TodoApp, {
fragments: {
viewer: () => Relay.QL`
fragment on User {
totalCount,
${AddTodoMutation.getFragment('viewer')},
${TodoListFooter.getFragment('viewer')},
}
`,
},
});
|
react-router-tutorial/lessons/07-more-nesting/modules/NavLink.js | zerotung/practices-and-notes | // modules/NavLink.js
import React from 'react'
import { Link } from 'react-router'
export default React.createClass({
render() {
return <Link {...this.props} activeClassName="active"/>
}
})
|
client/src/components/Draftail/decorators/TooltipEntity.js | zerolab/wagtail | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Icon } from 'draftail';
import Tooltip from '../Tooltip/Tooltip';
import Portal from '../../Portal/Portal';
const shortenLabel = (label) => {
let shortened = label;
if (shortened.length > 25) {
shortened = `${shortened.slice(0, 20)}…`;
}
return shortened;
};
class TooltipEntity extends Component {
constructor(props) {
super(props);
this.state = {
showTooltipAt: null,
};
this.onEdit = this.onEdit.bind(this);
this.onRemove = this.onRemove.bind(this);
this.openTooltip = this.openTooltip.bind(this);
this.closeTooltip = this.closeTooltip.bind(this);
}
onEdit(e) {
const { onEdit, entityKey } = this.props;
e.preventDefault();
e.stopPropagation();
onEdit(entityKey);
}
onRemove(e) {
const { onRemove, entityKey } = this.props;
e.preventDefault();
e.stopPropagation();
onRemove(entityKey);
}
openTooltip(e) {
const trigger = e.target.closest('[data-draftail-trigger]');
// Click is within the tooltip.
if (!trigger) {
return;
}
const container = trigger.closest('[data-draftail-editor-wrapper]');
const containerRect = container.getBoundingClientRect();
const rect = trigger.getBoundingClientRect();
this.setState({
showTooltipAt: {
container: container,
top:
rect.top -
containerRect.top -
(document.documentElement.scrollTop || document.body.scrollTop),
left:
rect.left -
containerRect.left -
(document.documentElement.scrollLeft || document.body.scrollLeft),
width: rect.width,
height: rect.height,
},
});
}
closeTooltip() {
this.setState({ showTooltipAt: null });
}
render() {
const { children, icon, label, url } = this.props;
const { showTooltipAt } = this.state;
return (
<a
href={url}
role="button"
// Use onMouseUp to preserve focus in the text even after clicking.
onMouseUp={this.openTooltip}
className="TooltipEntity"
data-draftail-trigger
>
<Icon icon={icon} className="TooltipEntity__icon" />
{children}
{showTooltipAt && (
<Portal
node={showTooltipAt.container}
onClose={this.closeTooltip}
closeOnClick
closeOnType
closeOnResize
>
<Tooltip target={showTooltipAt} direction="top">
{label ? (
<a
href={url}
title={url}
target="_blank"
rel="noreferrer"
className="Tooltip__link"
>
{shortenLabel(label)}
</a>
) : null}
<button className="button Tooltip__button" onClick={this.onEdit}>
Edit
</button>
<button
className="button button-secondary no Tooltip__button"
onClick={this.onRemove}
>
Remove
</button>
</Tooltip>
</Portal>
)}
</a>
);
}
}
TooltipEntity.propTypes = {
entityKey: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
onEdit: PropTypes.func.isRequired,
onRemove: PropTypes.func.isRequired,
icon: PropTypes.oneOfType([
PropTypes.string.isRequired,
PropTypes.object.isRequired,
]).isRequired,
label: PropTypes.string.isRequired,
url: PropTypes.string,
};
TooltipEntity.defaultProps = {
url: null,
};
export default TooltipEntity;
|
node_modules/react-router/es6/IndexRoute.js | qingege/react_draft | import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils';
import { component, components, falsy } from './InternalPropTypes';
var func = React.PropTypes.func;
/**
* An <IndexRoute> is used to specify its parent's <Route indexRoute> in
* a JSX route config.
*/
var IndexRoute = React.createClass({
displayName: 'IndexRoute',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = _createRouteFromReactElement(element);
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0;
}
}
},
propTypes: {
path: falsy,
component: component,
components: components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default IndexRoute; |
example/src/App.js | Splact/react-demiguise | import React, { Component } from 'react';
import Demiguise from 'react-demiguise';
export default class App extends Component {
state = {
loop: 1,
};
onLoopEnd = () => {
console.log(`Loop ${this.state.loop} ended`);
this.setState({
loop: this.state.loop + 1,
});
}
render () {
const messages = [
'Abra cadabra flipendo',
'Macaroni tortellini',
'Lightsaber nintendo',
'Alabif shazam!',
'Salami broccoli ballerina',
'Geth pace Stark',
'Zucchini fresco pizza tombola',
'Tortellini paparazzi',
'Darth algorithm jedi',
'Mozzarella fritti',
];
const delays = [
1500,
1000,
2500,
800,
3000,
1000,
4000,
2000,
];
return (
<div className="demiguise-example">
<Demiguise
messages={ messages }
delay={ delays }
loop
onLoopEnd={ this.onLoopEnd }
/>
</div>
);
}
}
|
src/common/component/netWorkImage.js | liuboshuo/react-native-food | /**
* Created by liushuo on 17/4/27.
*/
import React, { Component } from 'react';
import {
StyleSheet,
View,
Image,
ActivityIndicator,
} from 'react-native';
export default class NetWorkImage extends Component {
constructor (props) {
super(props)
this.state = {
loading:true
}
}
static defaultProps = {
placeholder:{
resizeMode:null,
uri:null
},
loadViewBg:null,
width:0,
height:0,
}
loadHandle(){
this.setState({
loading:false
})
}
render() {
const resizeMode = this.props.placeholder!= null?this.props.placeholder.resizeMode != null ?this.props.placeholder.resizeMode:"stretch" :"stretch";
const loadViewBg = this.props.loadViewBg != null?this.props.loadViewBg:'rgba(0,0,0,.05)';
return (
<View>
<Image onLoad={this.loadHandle.bind(this)}
source={{uri:this.props.uri}}
style={this.props.style? this.props.style:{}}>
{this.props.children}
</Image>
{this.state.loading && <View style={[styles.loadingView,{backgroundColor:loadViewBg}]}>
{
this.props.placeholder == null ?
<ActivityIndicator animating={this.state.loading} size={"small"} />
:
this.props.placeholder.uri != null ?
<Image style={[styles.loadingImage,{width:this.props.width,height:this.props.height,resizeMode:resizeMode}]} source={{uri:this.props.placeholder.uri}}/>
:<ActivityIndicator animating={this.state.loading} size={"small"} />
}
</View>
}
</View>
);
}
}
const styles = StyleSheet.create({
loadingView:{
position: 'absolute',
justifyContent: 'center',
alignItems: 'center',
left: 0,
right: 0,
top: 0,
bottom: 0,
},
loadingImage:{
}
})
|
source/components/SearchBox.js | TroyAlford/axis-wiki | import React from 'react'
import debounce from 'lodash/debounce'
const searchFor = debounce(term => window.routerHistory.push(`/search/${term}`), 500)
export default class SearchBox extends React.Component {
static defaultProps = {
className: '',
placeholder: 'Search... (Ctrl+Shift+F)',
term: '',
}
constructor(props) {
super(props)
this.state = { term: props.term }
}
componentDidMount() { window.addEventListener('keyup', this.onKeyUp) }
componentWillReceiveProps(props) {
if (props.term !== this.state.term) this.setState({ term: props.term })
}
componentWillUnmount() { window.removeEventListener('keyup', this.onKeyUp) }
onKeyUp = (e) => {
if (e.ctrlKey && e.shiftKey && e.code === 'KeyF') {
e.preventDefault()
e.stopPropagation()
this.input.focus()
}
}
createRef = (input) => { this.input = input }
render() {
const { className, placeholder } = this.props
return (
<div className={`search-box ${className}`}>
<input type="text"
placeholder={placeholder}
value={this.state.term}
onChange={(event) => {
this.setState({ term: event.target.value })
searchFor(event.target.value)
}}
ref={this.createRef}
/>
<i className="icon icon-search fa" />
</div>
)
}
}
|
client/src/components/Draftail/decorators/Link.js | wagtail/wagtail | import PropTypes from 'prop-types';
import React from 'react';
import { gettext } from '../../../utils/gettext';
import Icon from '../../Icon/Icon';
import TooltipEntity from '../decorators/TooltipEntity';
const LINK_ICON = <Icon name="link" />;
const BROKEN_LINK_ICON = <Icon name="warning" />;
const MAIL_ICON = <Icon name="mail" />;
const getEmailAddress = (mailto) => mailto.replace('mailto:', '').split('?')[0];
const getPhoneNumber = (tel) => tel.replace('tel:', '').split('?')[0];
const getDomainName = (url) => url.replace(/(^\w+:|^)\/\//, '').split('/')[0];
// Determines how to display the link based on its type: page, mail, anchor or external.
export const getLinkAttributes = (data) => {
const url = data.url || null;
let icon;
let label;
if (!url) {
icon = BROKEN_LINK_ICON;
label = gettext('Broken link');
} else if (data.id) {
icon = LINK_ICON;
label = url;
} else if (url.startsWith('mailto:')) {
icon = MAIL_ICON;
label = getEmailAddress(url);
} else if (url.startsWith('tel:')) {
icon = LINK_ICON;
label = getPhoneNumber(url);
} else if (url.startsWith('#')) {
icon = LINK_ICON;
label = url;
} else {
icon = LINK_ICON;
label = getDomainName(url);
}
return {
url,
icon,
label,
};
};
/**
* Represents a link within the editor's content.
*/
const Link = (props) => {
const { entityKey, contentState } = props;
const data = contentState.getEntity(entityKey).getData();
return <TooltipEntity {...props} {...getLinkAttributes(data)} />;
};
Link.propTypes = {
entityKey: PropTypes.string.isRequired,
contentState: PropTypes.object.isRequired,
};
export default Link;
|
addons/graphql/src/preview.js | nfl/react-storybook | import React from 'react';
import GraphiQL from 'graphiql';
import { fetch } from 'global';
import 'graphiql/graphiql.css';
import FullScreen from './components/FullScreen';
const FETCH_OPTIONS = {
method: 'post',
headers: { 'Content-Type': 'application/json' },
};
function getDefautlFetcher(url) {
return params => {
const body = JSON.stringify(params);
const options = Object.assign({ body }, FETCH_OPTIONS);
return fetch(url, options).then(res => res.json());
};
}
function reIndentQuery(query) {
const lines = query.split('\n');
const spaces = lines[lines.length - 1].length - 1;
return lines.map((l, i) => (i === 0 ? l : l.slice(spaces))).join('\n');
}
export function setupGraphiQL(config) {
return (_query, variables = '{}') => {
const query = reIndentQuery(_query);
const fetcher = config.fetcher || getDefautlFetcher(config.url);
return () =>
<FullScreen>
<GraphiQL query={query} variables={variables} fetcher={fetcher} />
</FullScreen>;
};
}
|
src/svg-icons/action/perm-identity.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPermIdentity = (props) => (
<SvgIcon {...props}>
<path d="M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z"/>
</SvgIcon>
);
ActionPermIdentity = pure(ActionPermIdentity);
ActionPermIdentity.displayName = 'ActionPermIdentity';
export default ActionPermIdentity;
|
enrolment-ui/src/modules/Dashboard/components/Requests.js | overture-stack/enrolment | import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { withTranslation } from 'react-i18next';
import StaffActions from './StaffActions';
import FeesSidebarWidget from '../../Fees';
import { ApplicationRequests } from '../../Applications';
import { UserRequests } from '../../ProjectUsers';
const Requests = ({
profile,
projects,
projectUsers,
t,
}) => {
const ownsProjects = projects.data.length > 0;
const isMember = projectUsers.data.length > 0;
const ownsApprovedProjects = ownsProjects &&
projects.data.filter(project => project.status === 'Approved').length > 0;
return !projects.loading && (
<div className="row dashboard">
<section className="col-md-10 requests">
<div className="requests-header">
<h3>{t('Requests.requestsHeader.title')}</h3>
{!profile.is_staff && <StaffActions />}
</div>
{ownsProjects && <ApplicationRequests />}
{isMember && <UserRequests />}
</section>
{(ownsProjects || profile.is_staff) && (
<section className="col-md-2 projects">
{ownsApprovedProjects && (
<React.Fragment>
<h3>{t('Requests.projects.title')}</h3>
<div className="projects-links">
<Link to={{ pathname: '/projects', hash: '#details' }}>
{t('Requests.projects.projectDetailLink')}
</Link>
<Link to={{ pathname: '/projects', hash: '#addUsers' }}>
{t('Requests.projects.addUserLink')}
</Link>
<Link to={{ pathname: '/projects', hash: '#viewUsers' }}>
{t('Requests.projects.viewUserLink')}
</Link>
</div>
</React.Fragment>
)}
<FeesSidebarWidget />
</section>
)}
</div>
);
};
const mapStateToProps = state => ({
profile: state.profile.data,
projects: state.projects,
projectUsers: state.projectUsers,
});
export default withTranslation()(connect(mapStateToProps, null)(Requests));
|
packages/fyndiq-component-timeline/src/event.js | fyndiq/fyndiq-ui | import React from 'react'
import PropTypes from 'prop-types'
import styles from '../timeline.css'
const Event = ({ icon, children }) => (
<div className={styles.event}>
<div className={styles.icon}>
{React.cloneElement(icon, {
color: null,
})}
</div>
<span>{children}</span>
</div>
)
Event.propTypes = {
icon: PropTypes.element,
children: PropTypes.node,
}
Event.defaultProps = {
icon: null,
children: null,
}
export default Event
|
docs/app/Examples/collections/Grid/Variations/GridExampleVerticalAlignmentRow.js | koenvg/Semantic-UI-React | import React from 'react'
import { Grid, Image } from 'semantic-ui-react'
const GridExampleVerticalAlignmentRow = () => (
<Grid columns={4} centered>
<Grid.Row verticalAlign='top'>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
<br />
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
</Grid.Row>
<Grid.Row verticalAlign='middle'>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
<br />
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
</Grid.Row>
<Grid.Row verticalAlign='bottom'>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
<br />
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/image.png' />
</Grid.Column>
</Grid.Row>
</Grid>
)
export default GridExampleVerticalAlignmentRow
|
src/shared/components/form/colorPickerGroup.js | namroodinc/truth-serum | import React from 'react';
import {pink50, pink900} from 'material-ui/styles/colors';
export default class ColorPickerGroup extends React.Component {
render() {
const { backgroundColor, color, label } = this.props;
return (
<div
className="container__row"
style={{
backgroundColor: backgroundColor || pink900,
color: color || pink50
}}
>
<h3>
{label}
</h3>
<div
className="container__row__flex"
>
{this.props.children}
</div>
</div>
)
}
}
|
examples/with-stencil/packages/web-app/pages/_app.js | JeromeFitz/next.js | import React from 'react'
import App from 'next/app'
import { applyPolyfills, defineCustomElements } from 'test-component/loader'
export default class MyApp extends App {
componentDidMount() {
applyPolyfills().then(() => {
defineCustomElements(window)
})
}
render() {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
|
src/svg-icons/image/movie-filter.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageMovieFilter = (props) => (
<SvgIcon {...props}>
<path d="M18 4l2 3h-3l-2-3h-2l2 3h-3l-2-3H8l2 3H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4zm-6.75 11.25L10 18l-1.25-2.75L6 14l2.75-1.25L10 10l1.25 2.75L14 14l-2.75 1.25zm5.69-3.31L16 14l-.94-2.06L13 11l2.06-.94L16 8l.94 2.06L19 11l-2.06.94z"/>
</SvgIcon>
);
ImageMovieFilter = pure(ImageMovieFilter);
ImageMovieFilter.displayName = 'ImageMovieFilter';
ImageMovieFilter.muiName = 'SvgIcon';
export default ImageMovieFilter;
|
src/Label.js | PeterDaveHello/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Label = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'label',
bsStyle: 'default'
};
},
render() {
let classes = this.getBsClassSet();
return (
<span {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</span>
);
}
});
export default Label;
|
src/main.js | saitodisse/scrap-cerebral-2 | import React from 'react';
import ReactDOM from 'react-dom';
import { Container } from 'cerebral/react';
import Main from './components/Main/index';
import controller from './controller';
import '../vendors/semantic/semantic.css';
ReactDOM.render(
<Container controller={controller}>
<Main />
</Container>,
document.getElementById('root')
);
|
dist/internal/menu/StartMenuLinks.js | Caleydo/ordino | import React from 'react';
import { EStartMenuMode } from '../constants';
export function StartMenuLinks(props) {
return (React.createElement(React.Fragment, null,
props.status === 'success' &&
props.tabs.map((tab) => (React.createElement("li", { className: `nav-item ${props.activeTab === tab ? 'active' : ''}`, key: tab.desc.id },
React.createElement("a", { className: "nav-link", href: `#${tab.desc.id}`, id: `${tab.desc.id}-tab`, role: "tab", "aria-controls": tab.desc.id, "aria-selected": props.activeTab === tab, onClick: (evt) => {
evt.preventDefault();
if (props.mode === EStartMenuMode.OVERLAY && props.activeTab === tab) {
// remove :focus from link to remove highlight color
evt.currentTarget.blur();
// close tab only in overlay mode
props.setActiveTab(null);
}
else {
props.setActiveTab(tab);
}
return false;
} },
tab.desc.icon ? React.createElement("i", { className: tab.desc.icon }) : null,
tab.desc.text)))),
' '));
}
//# sourceMappingURL=StartMenuLinks.js.map |
admin/client/Signin/Signin.js | Yaska/keystone | /**
* The actual Sign In view, with the login form
*/
import assign from 'object-assign';
import classnames from 'classnames';
import React from 'react';
import xhr from 'xhr';
import Alert from './components/Alert';
import Brand from './components/Brand';
import UserInfo from './components/UserInfo';
import LoginForm from './components/LoginForm';
var SigninView = React.createClass({
getInitialState () {
return {
email: '',
password: '',
isAnimating: false,
isInvalid: false,
invalidMessage: '',
signedOut: window.location.search === '?signedout',
};
},
componentDidMount () {
// Focus the email field when we're mounted
if (this.refs.email) {
this.refs.email.select();
}
},
handleInputChange (e) {
// Set the new state when the input changes
const newState = {};
newState[e.target.name] = e.target.value;
this.setState(newState);
},
handleSubmit (e) {
e.preventDefault();
// If either password or mail are missing, show an error
if (!this.state.email || !this.state.password) {
return this.displayError('Please enter an email address and password to sign in.');
}
xhr({
url: `${Keystone.adminPath}/api/session/signin`,
method: 'post',
json: {
email: this.state.email,
password: this.state.password,
},
headers: assign({}, Keystone.csrf.header),
}, (err, resp, body) => {
if (err || body && body.error) {
return body.error === 'invalid csrf'
? this.displayError('Something went wrong; please refresh your browser and try again.')
: this.displayError('The email and password you entered are not valid.');
} else {
// Redirect to where we came from or to the default admin path
if (Keystone.redirect) {
top.location.href = Keystone.redirect;
} else {
top.location.href = this.props.from ? this.props.from : Keystone.adminPath;
}
}
});
},
/**
* Display an error message
*
* @param {String} message The message you want to show
*/
displayError (message) {
this.setState({
isAnimating: true,
isInvalid: true,
invalidMessage: message,
});
setTimeout(this.finishAnimation, 750);
},
// Finish the animation and select the email field
finishAnimation () {
// TODO isMounted was deprecated, find out if we need this guard
if (!this.isMounted()) return;
if (this.refs.email) {
this.refs.email.select();
}
this.setState({
isAnimating: false,
});
},
render () {
const boxClassname = classnames('auth-box', {
'auth-box--has-errors': this.state.isAnimating,
});
return (
<div className="auth-wrapper">
<Alert
isInvalid={this.state.isInvalid}
signedOut={this.state.signedOut}
invalidMessage={this.state.invalidMessage}
/>
<div className={boxClassname}>
<h1 className="u-hidden-visually">{this.props.brand ? this.props.brand : 'Keystone'} Sign In </h1>
<div className="auth-box__inner">
<Brand
logo={this.props.logo}
brand={this.props.brand}
/>
{this.props.user ? (
<UserInfo
adminPath={this.props.from ? this.props.from : Keystone.adminPath}
signoutPath={`${Keystone.adminPath}/signout`}
userCanAccessKeystone={this.props.userCanAccessKeystone}
userName={this.props.user.name}
/>
) : (
<LoginForm
email={this.state.email}
handleInputChange={this.handleInputChange}
handleSubmit={this.handleSubmit}
isAnimating={this.state.isAnimating}
password={this.state.password}
/>
)}
</div>
</div>
<div className="auth-footer">
<span>Powered by </span>
<a href="http://keystonejs.com" target="_blank" title="The Node.js CMS and web application platform (new window)">KeystoneJS</a>
</div>
</div>
);
},
});
module.exports = SigninView;
|
js/components/loaders/ProgressBar.android.js | crod93/googlePlacesEx-react-native | /* @flow */
'use strict';
import React from 'react';
import { ActivityIndicatorIOS, Platform } from 'react-native';
import ProgressBar from "ProgressBarAndroid";
import NativeBaseComponent from 'native-base/Components/Base/NativeBaseComponent';
import computeProps from 'native-base/Utils/computeProps';
export default class SpinnerNB extends NativeBaseComponent {
prepareRootProps() {
var type = {
height: 40
}
var defaultProps = {
style: type
}
return computeProps(this.props, defaultProps);
}
render() {
return(
<ProgressBar {...this.prepareRootProps()} styleAttr = "Horizontal"
indeterminate = {false} progress={this.props.progress ? this.props.progress/100 : 0.5}
color={this.props.color ? this.props.color : this.props.inverse ? this.getTheme().inverseProgressColor :
this.getTheme().defaultProgressColor} />
);
}
}
|
stories/print/DailyViewPrintPDF.js | tidepool-org/viz | /*
* == BSD2 LICENSE ==
* Copyright (c) 2017, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* 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 License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
* == BSD2 LICENSE ==
*/
import React from 'react';
import _ from 'lodash';
import { storiesOf } from '@storybook/react';
import { createPrintView } from '../../src/modules/print/index';
import { MARGIN } from '../../src/modules/print/utils/constants';
import PrintView from '../../src/modules/print/PrintView';
import * as profiles from '../../data/patient/profiles';
/* global PDFDocument, blobStream, window */
const stories = storiesOf('Daily View PDF', module);
let queries;
try {
// eslint-disable-next-line global-require, import/no-unresolved
queries = require('../../local/PDFDataQueries.json');
} catch (e) {
queries = {};
}
function openPDF(dataUtil, { patient }) {
const doc = new PDFDocument({ autoFirstPage: false, bufferPages: true, margin: MARGIN });
const stream = doc.pipe(blobStream());
const opts = {
bgPrefs: queries.daily.bgPrefs,
timePrefs: queries.daily.timePrefs,
patient,
};
const data = queries.daily ? dataUtil.query(queries.daily) : {};
createPrintView('daily', data, opts, doc).render();
PrintView.renderPageNumbers(doc);
doc.end();
stream.on('finish', () => {
window.open(stream.toBlobURL('application/pdf'));
});
}
const notes = `Run the \`accountTool.py export\` from the \`tidepool-org/tools-private\` repo.
Save the resulting file to the \`local/\` directory of viz as \`rawData.json\`.
After generating a PDF in Tidepool web using the same account you just exported data from,
run \`window.downloadPDFDataQueries()\` from the console on a Tidepool Web data view.
Save the resulting file to the \`local/\` directory of viz as \`PDFDataQueries.json\`,
and then use this story to iterate on the Daily Print PDF outside of Tidepool Web!`;
profiles.longName = _.cloneDeep(profiles.standard);
profiles.longName.profile.fullName = 'Super Duper Long Patient Name';
stories.add('standard account', ({ dataUtil }) => (
<button onClick={() => openPDF(dataUtil, { patient: profiles.standard })}>
Open PDF in new tab
</button>
), { notes });
|
app/javascript/mastodon/features/account_gallery/components/media_item.js | imomix/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Permalink from '../../../components/permalink';
class MediaItem extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
};
render () {
const { media } = this.props;
const status = media.get('status');
let content, style;
if (media.get('type') === 'gifv') {
content = <span className='media-gallery__gifv__label'>GIF</span>;
}
if (!status.get('sensitive')) {
style = { backgroundImage: `url(${media.get('preview_url')})` };
}
return (
<div className='account-gallery__item'>
<Permalink
to={`/statuses/${status.get('id')}`}
href={status.get('url')}
style={style}
>
{content}
</Permalink>
</div>
);
}
}
export default MediaItem;
|
packages/icons/src/md/hardware/KeyboardArrowLeft.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdKeyboardArrowLeft(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<polygon points="29.83 33.17 20.66 24 29.83 14.83 27 12 15 24 27 36" />
</IconBase>
);
}
export default MdKeyboardArrowLeft;
|
node_modules/react-scripts/node_modules/case-sensitive-paths-webpack-plugin/demo/src/AppRoot.component.js | vitorgomateus/NotifyMe | import React, { Component } from 'react';
export default class AppRoot extends Component {
// we can't use `connect` in this component, so must do naiively:
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div>
<h1>This is just an empty demo</h1>
<p>(Run the tests.)</p>
</div>
);
}
}
|
app/javascript/mastodon/features/domain_blocks/index.js | MitarashiDango/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import DomainContainer from '../../containers/domain_container';
import { fetchDomainBlocks, expandDomainBlocks } from '../../actions/domain_blocks';
import ScrollableList from '../../components/scrollable_list';
const messages = defineMessages({
heading: { id: 'column.domain_blocks', defaultMessage: 'Blocked domains' },
unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' },
});
const mapStateToProps = state => ({
domains: state.getIn(['domain_lists', 'blocks', 'items']),
hasMore: !!state.getIn(['domain_lists', 'blocks', 'next']),
});
export default @connect(mapStateToProps)
@injectIntl
class Blocks extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
hasMore: PropTypes.bool,
domains: ImmutablePropTypes.orderedSet,
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchDomainBlocks());
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandDomainBlocks());
}, 300, { leading: true });
render () {
const { intl, domains, hasMore, multiColumn } = this.props;
if (!domains) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.domain_blocks' defaultMessage='There are no blocked domains yet.' />;
return (
<Column bindToDocument={!multiColumn} icon='minus-circle' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollableList
scrollKey='domain_blocks'
onLoadMore={this.handleLoadMore}
hasMore={hasMore}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
>
{domains.map(domain =>
<DomainContainer key={domain} domain={domain} />,
)}
</ScrollableList>
</Column>
);
}
}
|
web/lib/netrunner.js | zachasme/netrunner | /* eslint-env browser */
import App from 'lib/shared/components/app';
import * as actions from './shared/actions';
import React from 'react';
actions.bootstrap();
export function renderToDOM(container){
let element = React.createElement(App);
return React.render(element, container);
}
|
demo/index.js | fabiobiondi/react-test-ui-components | import React from 'react';
import { render } from 'react-dom';
import App from './components/App';
render(
<App />,
document.getElementById('root')
);
|
todo_list/src/components/Footer.js | nipe0324/js_samples | import React from 'react'
import FilterLink from '../containers/FilterLink'
import { VisibilityFilters } from '../actions'
const Footer = () => (
<div>
<span>Show: </span>
<FilterLink filter={VisibilityFilters.SHOW_ALL}>
All
</FilterLink>
<FilterLink filter={VisibilityFilters.SHOW_ACTIVE}>
Active
</FilterLink>
<FilterLink filter={VisibilityFilters.SHOW_COMPLETED}>
Completed
</FilterLink>
</div>
)
export default Footer
|
client/page/redirects/columns/source-flag.js | johngodley/redirection | /**
* External dependencies
*/
import React from 'react';
import classnames from 'classnames';
/**
* Internal dependencies
*/
import Badge from 'wp-plugin-components/badge';
/**
* A redirect flag
*
* @param {object} props
* @param {string} props.name - Name to display in the flag
* @param {string} [props.className] - Extra class name
*/
function RedirectFlag( { name, className } ) {
return <Badge className={ classnames( 'redirect-source__flag', className ) }>{ name }</Badge>;
}
export default RedirectFlag;
|
src/components/App.js | QuackenbushDev/github-notetaker | import React, { Component } from 'react';
import SearchGithub from './SearchGithub'
export class App extends Component {
render() {
return (
<div className="main-container">
<nav className="navbar navbar-default" role="navigation">
<div className="col-sm-7 col-sm-offset-2" style={{marginTop: 15}}>
<SearchGithub />
</div>
</nav>
<div className="container">
{ this.props.children }
</div>
</div>
);
}
}
export default App; |
app/components/List/index.js | PeterKow/clientAurity | import React from 'react';
import styles from './styles.css';
function List(props) {
const ComponentToRender = props.component;
let content = (<div></div>);
// If we have items, render them
if (props.items) {
content = props.items.map((item, index) => (
<ComponentToRender key={'item-' + index } item={item} />
));
} else {
// Otherwise render a single component
content = (<ComponentToRender />);
}
return (
<div className={ styles.listWrapper }>
<ul className={ styles.list }>
{ content }
</ul>
</div>
);
}
export default List;
|
local-cli/templates/HelloNavigation/views/chat/ChatScreen.js | clozr/react-native | 'use strict';
import React, { Component } from 'react';
import {
ActivityIndicator,
Button,
ListView,
StyleSheet,
Text,
TextInput,
View,
} from 'react-native';
import KeyboardSpacer from '../../components/KeyboardSpacer';
import Backend from '../../lib/Backend';
export default class ChatScreen extends Component {
static navigationOptions = {
title: (navigation) => `Chat with ${navigation.state.params.name}`,
}
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
messages: [],
dataSource: ds,
myMessage: '',
isLoading: true,
};
}
async componentDidMount() {
let chat;
try {
chat = await Backend.fetchChat(this.props.navigation.state.params.name);
} catch (err) {
// Here we would handle the fact the request failed, e.g.
// set state to display "Messages could not be loaded".
// We should also check network connection first before making any
// network requests - maybe we're offline? See React Native's NetInfo
// module.
this.setState({
isLoading: false,
});
return;
}
this.setState((prevState) => ({
messages: chat.messages,
dataSource: prevState.dataSource.cloneWithRows(chat.messages),
isLoading: false,
}));
}
onAddMessage = async () => {
// Optimistically update the UI
this.addMessageLocal();
// Send the request
try {
await Backend.sendMessage({
name: this.props.navigation.state.params.name,
// TODO Is reading state like this outside of setState OK?
// Can it contain a stale value?
message: this.state.myMessage,
});
} catch (err) {
// Here we would handle the request failure, e.g. call setState
// to display a visual hint showing the message could not be sent.
}
}
addMessageLocal = () => {
this.setState((prevState) => {
if (!prevState.myMessage) {
return prevState;
}
const messages = [
...prevState.messages, {
name: 'Me',
text: prevState.myMessage,
}
];
return {
messages: messages,
dataSource: prevState.dataSource.cloneWithRows(messages),
myMessage: '',
}
});
this.textInput.clear();
}
onMyMessageChange = (event) => {
this.setState({myMessage: event.nativeEvent.text});
}
renderRow = (message) => (
<View style={styles.bubble}>
<Text style={styles.name}>{message.name}</Text>
<Text>{message.text}</Text>
</View>
)
render() {
if (this.state.isLoading) {
return (
<View style={styles.container}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.container}>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
onLayout={this.scrollToBottom}
/>
<View style={styles.composer}>
<TextInput
ref={(textInput) => { this.textInput = textInput; }}
style={styles.textInput}
placeholder="Type a message..."
text={this.state.myMessage}
onSubmitEditing={this.onAddMessage}
onChange={this.onMyMessageChange}
/>
{this.state.myMessage !== '' && (
<Button
title="Send"
onPress={this.onAddMessage}
/>
)}
</View>
<KeyboardSpacer />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 8,
backgroundColor: 'white',
},
listView: {
flex: 1,
alignSelf: 'stretch',
},
bubble: {
alignSelf: 'flex-end',
backgroundColor: '#d6f3fc',
padding: 12,
borderRadius: 4,
marginBottom: 4,
},
name: {
fontWeight: 'bold',
},
composer: {
flexDirection: 'row',
alignItems: 'center',
height: 36,
},
textInput: {
flex: 1,
borderColor: '#ddd',
borderWidth: 1,
padding: 4,
height: 30,
fontSize: 13,
marginRight: 8,
}
});
|
src/svg-icons/action/feedback.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionFeedback = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 12h-2v-2h2v2zm0-4h-2V6h2v4z"/>
</SvgIcon>
);
ActionFeedback = pure(ActionFeedback);
ActionFeedback.displayName = 'ActionFeedback';
ActionFeedback.muiName = 'SvgIcon';
export default ActionFeedback;
|
examples/official-storybook/stories/core/decorators.stories.js | kadirahq/react-storybook | import React from 'react';
// We would need to add this in config.js idiomatically however that would make this file a bit confusing
import { addDecorator } from '@storybook/react';
addDecorator((s, { kind }) =>
kind === 'Core/Decorators' ? (
<>
<p>Global Decorator</p>
{s()}
</>
) : (
s()
)
);
export default {
title: 'Core/Decorators',
decorators: [
(s) => (
<>
<p>Kind Decorator</p>
{s()}
</>
),
],
};
export const All = () => <p>Story</p>;
All.decorators = [
(s) => (
<>
<p>Local Decorator</p>
{s()}
</>
),
];
|
app/components/LocationModule.js | danichim/redshift-material-gui | import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
/**
* Dialog with action buttons. The actions are passed in as an array of React objects,
* in this example [FlatButtons](/#/components/flat-button).
*
* You can also close this dialog by clicking outside the dialog, or with the 'Esc' key.
*/
export default class LocationModule extends React.Component {
state = {
open: false,
lat: 0,
long: 0
};
constructor(props) {
super(props);
let coords = {};
navigator.geolocation.getCurrentPosition(geo => {
this.setState({
lat: geo.coords.latitude,
long: geo.coords.longitude
})
});
}
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.setState({open: false});
};
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Submit"
primary={true}
onTouchTap={this.handleClose}
/>,
];
return (
<div>
<RaisedButton label="Set Location" onTouchTap={this.handleOpen} />
<Dialog
title="Set Location"
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
<p>We detected that your coordinates are:</p>
<p>Latitude: {this.state.lat.toFixed(2)}</p>
<p>Longitude: {this.state.long.toFixed(2)}</p>
</Dialog>
</div>
);
}
}
|
src/js/components/ui/CarouselContinuous/CarouselContinuous.js | nekuno/client | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import styles from './CarouselContinuous.scss';
export default class CarouselContinuous extends Component {
static propTypes = {
items : PropTypes.array.isRequired,
marginRight: PropTypes.number
};
constructor(props) {
super(props);
this.renderItems = this.renderItems.bind(this);
}
renderItems() {
const marginRight = this.props.marginRight;
return this.props.items.map((item, index) => {
return <div key={index} className={styles.item} style={{'marginRight': marginRight + '%'}}>
{item}
</div>
});
}
render() {
return (
<div className={styles.carouselcontinuous} >
{this.renderItems()}
</div>
);
}
}
CarouselContinuous.defaultProps = {
marginRight: 80
}; |
src/components/NavIndexLink.js | Korkemoms/amodahl.no | // @flow
import React from 'react'
import { NavItem } from 'react-bootstrap'
import {IndexLinkContainer} from 'react-router-bootstrap'
/* Purely presentational component */
const NavIndexLink = (props: Object) => {
const {children, to}: {children: Array<mixed>, to: string} = props
return (
<IndexLinkContainer to={to}>
<NavItem role='navigation'>
{children}
</NavItem>
</IndexLinkContainer>
)
}
export default NavIndexLink
|
js/jqwidgets/demos/react/app/chart/datetimexaxisrangeselection/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxChart from '../../../jqwidgets-react/react_jqxchart.js';
class App extends React.Component {
componentDidMount() {
this.refs.myChart.on('rangeSelectionChanging', (event) => {
let args = event.args;
args.instance.description = args.minValue.getFullYear() + " - " + args.maxValue.getFullYear();
});
}
render() {
let source =
{
datatype: 'csv',
datafields: [
{ name: 'Date' },
{ name: 'Open' },
{ name: 'High' },
{ name: 'Low' },
{ name: 'Close' },
{ name: 'Volume' },
{ name: 'AdjClose' }
],
url: '../sampledata/TSLA_stockprice.csv'
};
let dataAdapter = new $.jqx.dataAdapter(source, { async: false, autoBind: true, loadError: (xhr, status, error) => { alert('Error loading "' + source.url + '" : ' + error); } });
let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
let toolTipCustomFormatFn = (value, itemIndex, serie, group, categoryValue, categoryAxis) => {
let dataItem = dataAdapter.records[itemIndex];
return '<DIV style="text-align:left"><b>Date: ' +
categoryValue.getDate() + '-' + months[categoryValue.getMonth()] + '-' + categoryValue.getFullYear() +
'</b><br />Open price: $' + dataItem.Open +
'</b><br />Close price: $' + dataItem.Close +
'</b><br />Daily volume: ' + dataItem.Volume +
'</DIV>';
};
let padding = { left: 5, top: 5, right: 30, bottom: 5 };
let titlePadding = { left: 30, top: 5, right: 0, bottom: 10 };
let xAxis =
{
dataField: 'Date',
minValue: new Date(2012, 0, 1),
maxValue: new Date(2013, 11, 31),
type: 'date',
baseUnit: 'day',
labels:
{
formatFunction: (value) => {
return value.getDate() + '-' + months[value.getMonth()] + '\'' + value.getFullYear().toString().substring(2);
}
},
rangeSelector: {
size: 80,
padding: { /*left: 0, right: 0,*/top: 0, bottom: 0 },
minValue: new Date(2010, 5, 1),
backgroundColor: 'white',
dataField: 'Close',
baseUnit: 'month',
gridLines: { visible: false },
serieType: 'area',
labels: {
formatFunction: (value) => {
return months[value.getMonth()] + '\'' + value.getFullYear().toString().substring(2);
}
}
}
};
let valueAxis =
{
title: { text: 'Price per share [USD]<br><br>' },
labels: { horizontalAlignment: 'right' }
};
let seriesGroups =
[
{
type: 'line',
toolTipFormatFunction: toolTipCustomFormatFn,
series: [
{ dataField: 'Close', displayText: 'Close Price', lineWidth: 1, lineWidthSelected: 1 }
]
}
];
return (
<JqxChart ref='myChart' style={{ width: 850, height: 500 }}
title={'Tesla Motors Stock Price'} description={'(June 2010 - March 2014)'}
enableCrosshairs={true} enableAnimations={true} padding={padding} animationDuration={1500}
titlePadding={titlePadding} source={dataAdapter} xAxis={xAxis}
valueAxis={valueAxis} colorScheme={'scheme01'} seriesGroups={seriesGroups}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.