path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
actor-apps/app-web/src/app/components/DialogSection.react.js
dut3062796s/actor-platform
import _ from 'lodash'; import React from 'react'; import { PeerTypes } from 'constants/ActorAppConstants'; import PeerUtils from 'utils/PeerUtils'; import MessagesSection from 'components/dialog/MessagesSection.react'; import TypingSection from 'components/dialog/TypingSection.react'; import ComposeSection from 'components/dialog/ComposeSection.react'; import ToolbarSection from 'components/ToolbarSection.react'; import ActivitySection from 'components/ActivitySection.react'; import ConnectionState from 'components/common/ConnectionState.react'; import ActivityStore from 'stores/ActivityStore'; import DialogStore from 'stores/DialogStore'; import MessageStore from 'stores/MessageStore'; import GroupStore from 'stores/GroupStore'; import DialogActionCreators from 'actions/DialogActionCreators'; // On which scrollTop value start loading older messages const LoadMessagesScrollTop = 100; const initialRenderMessagesCount = 20; const renderMessagesStep = 20; let renderMessagesCount = initialRenderMessagesCount; let lastPeer = null; let lastScrolledFromBottom = 0; const getStateFromStores = () => { const messages = MessageStore.getAll(); let messagesToRender; if (messages.length > renderMessagesCount) { messagesToRender = messages.slice(messages.length - renderMessagesCount); } else { messagesToRender = messages; } return { peer: DialogStore.getSelectedDialogPeer(), messages: messages, messagesToRender: messagesToRender }; }; class DialogSection extends React.Component { constructor(props) { super(props); this.state = getStateFromStores(); ActivityStore.addChangeListener(this.fixScrollTimeout.bind(this)); DialogStore.addSelectListener(this.onSelectedDialogChange); MessageStore.addChangeListener(this.onMessagesChange); } componentWillUnmount() { ActivityStore.removeChangeListener(this.fixScrollTimeout.bind(this)); DialogStore.removeSelectListener(this.onSelectedDialogChange); MessageStore.removeChangeListener(this.onMessagesChange); } componentDidMount() { const peer = DialogStore.getSelectedDialogPeer(); if (peer) { DialogActionCreators.onConversationOpen(peer); this.fixScroll(); this.loadMessagesByScroll(); } } componentDidUpdate() { this.fixScroll(); this.loadMessagesByScroll(); } render() { const peer = this.state.peer; let mainContent; if (peer) { let isMember = true, memberArea; if (peer.type === PeerTypes.GROUP) { const group = GroupStore.getGroup(peer.id); isMember = DialogStore.isGroupMember(group); } if (isMember) { memberArea = ( <div> <TypingSection/> <ComposeSection peer={peer}/> </div> ); } else { memberArea = ( <section className="compose compose--disabled row center-xs middle-xs"> <h3>You are not a member</h3> </section> ); } mainContent = ( <section className="dialog" onScroll={this.loadMessagesByScroll}> <ConnectionState/> <div className="messages"> <MessagesSection messages={this.state.messagesToRender} peer={peer} ref="MessagesSection"/> </div> {memberArea} </section> ); } else { mainContent = ( <section className="dialog dialog--empty row center-xs middle-xs"> <ConnectionState/> <h2>Select dialog or start a new one.</h2> </section> ); } return ( <section className="main"> <ToolbarSection/> <div className="flexrow"> {mainContent} <ActivitySection/> </div> </section> ); } fixScrollTimeout = () => { setTimeout(this.fixScroll, 50); }; fixScroll = () => { const node = React.findDOMNode(this.refs.MessagesSection); if (node) { node.scrollTop = node.scrollHeight - lastScrolledFromBottom - node.offsetHeight; } }; onSelectedDialogChange = () => { lastScrolledFromBottom = 0; renderMessagesCount = initialRenderMessagesCount; if (lastPeer != null) { DialogActionCreators.onConversationClosed(lastPeer); } lastPeer = DialogStore.getSelectedDialogPeer(); DialogActionCreators.onConversationOpen(lastPeer); }; onMessagesChange = _.debounce(() => { this.setState(getStateFromStores()); }, 10, {maxWait: 50, leading: true}); loadMessagesByScroll = _.debounce(() => { let node = React.findDOMNode(this.refs.MessagesSection); let scrollTop = node.scrollTop; lastScrolledFromBottom = node.scrollHeight - scrollTop - node.offsetHeight; // was node.scrollHeight - scrollTop if (node.scrollTop < LoadMessagesScrollTop) { DialogActionCreators.onChatEnd(this.state.peer); if (this.state.messages.length > this.state.messagesToRender.length) { renderMessagesCount += renderMessagesStep; if (renderMessagesCount > this.state.messages.length) { renderMessagesCount = this.state.messages.length; } this.setState(getStateFromStores()); } } }, 5, {maxWait: 30}); } export default DialogSection;
src/index.js
FranciscoHerrera/floggit-whiteboard-client
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './reduxStore'; import './common/css/master.css'; import Home from './pages/Home'; ReactDOM.render( <Provider store={store}> <Home /> </Provider>, document.getElementById('root'));
frontend/src/index.js
generalelectrix/color_organist
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render(<App />, document.getElementById('root'));
docs/src/pages/docs/index.js
colindresj/nuclear-js
import React from 'react' import Redirect from '../../layouts/redirect' import { BASE_URL } from '../../globals' export default React.createClass({ render() { return <Redirect to={BASE_URL} /> } })
examples/webpack/src/components/RandomButton.js
sapegin/react-styleguidist
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import sample from 'lodash/sample'; import './RandomButton.css'; /** * Button that changes label on every click. */ export default class RandomButton extends Component { static propTypes = { /** * List of possible labels. */ variants: PropTypes.array.isRequired, }; constructor(props) { super(); this.state = { label: sample(props.variants), }; } handleClick = () => { this.setState({ label: sample(this.props.variants), }); }; render() { return ( <button className="random-button" onClick={this.handleClick}> {this.state.label} </button> ); } }
node_modules/react-bootstrap/es/Pagination.js
darklilium/Factigis_2
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; 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 classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import PaginationButton from './PaginationButton'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { activePage: React.PropTypes.number, items: React.PropTypes.number, maxButtons: React.PropTypes.number, /** * When `true`, will display the first and the last button page */ boundaryLinks: React.PropTypes.bool, /** * When `true`, will display the default node value ('&hellip;'). * Otherwise, will display provided node (when specified). */ ellipsis: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]), /** * When `true`, will display the default node value ('&laquo;'). * Otherwise, will display provided node (when specified). */ first: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]), /** * When `true`, will display the default node value ('&raquo;'). * Otherwise, will display provided node (when specified). */ last: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]), /** * When `true`, will display the default node value ('&lsaquo;'). * Otherwise, will display provided node (when specified). */ prev: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]), /** * When `true`, will display the default node value ('&rsaquo;'). * Otherwise, will display provided node (when specified). */ next: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]), onSelect: React.PropTypes.func, /** * You can use a custom element for the buttons */ buttonComponentClass: elementType }; var defaultProps = { activePage: 1, items: 1, maxButtons: 0, first: false, last: false, prev: false, next: false, ellipsis: true, boundaryLinks: false }; var Pagination = function (_React$Component) { _inherits(Pagination, _React$Component); function Pagination() { _classCallCheck(this, Pagination); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Pagination.prototype.renderPageButtons = function renderPageButtons(activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps) { var pageButtons = []; var startPage = void 0; var endPage = void 0; var hasHiddenPagesAfter = void 0; if (maxButtons) { var hiddenPagesBefore = activePage - parseInt(maxButtons / 2, 10); startPage = Math.max(hiddenPagesBefore, 1); hasHiddenPagesAfter = items >= startPage + maxButtons; if (!hasHiddenPagesAfter) { endPage = items; startPage = items - maxButtons + 1; if (startPage < 1) { startPage = 1; } } else { endPage = startPage + maxButtons - 1; } } else { startPage = 1; endPage = items; } for (var pagenumber = startPage; pagenumber <= endPage; pagenumber++) { pageButtons.push(React.createElement( PaginationButton, _extends({}, buttonProps, { key: pagenumber, eventKey: pagenumber, active: pagenumber === activePage }), pagenumber )); } if (boundaryLinks && ellipsis && startPage !== 1) { pageButtons.unshift(React.createElement( PaginationButton, { key: 'ellipsisFirst', disabled: true, componentClass: buttonProps.componentClass }, React.createElement( 'span', { 'aria-label': 'More' }, ellipsis === true ? '\u2026' : ellipsis ) )); pageButtons.unshift(React.createElement( PaginationButton, _extends({}, buttonProps, { key: 1, eventKey: 1, active: false }), '1' )); } if (maxButtons && hasHiddenPagesAfter && ellipsis) { pageButtons.push(React.createElement( PaginationButton, { key: 'ellipsis', disabled: true, componentClass: buttonProps.componentClass }, React.createElement( 'span', { 'aria-label': 'More' }, ellipsis === true ? '\u2026' : ellipsis ) )); if (boundaryLinks && endPage !== items) { pageButtons.push(React.createElement( PaginationButton, _extends({}, buttonProps, { key: items, eventKey: items, active: false }), items )); } } return pageButtons; }; Pagination.prototype.render = function render() { var _props = this.props, activePage = _props.activePage, items = _props.items, maxButtons = _props.maxButtons, boundaryLinks = _props.boundaryLinks, ellipsis = _props.ellipsis, first = _props.first, last = _props.last, prev = _props.prev, next = _props.next, onSelect = _props.onSelect, buttonComponentClass = _props.buttonComponentClass, className = _props.className, props = _objectWithoutProperties(_props, ['activePage', 'items', 'maxButtons', 'boundaryLinks', 'ellipsis', 'first', 'last', 'prev', 'next', 'onSelect', 'buttonComponentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); var buttonProps = { onSelect: onSelect, componentClass: buttonComponentClass }; return React.createElement( 'ul', _extends({}, elementProps, { className: classNames(className, classes) }), first && React.createElement( PaginationButton, _extends({}, buttonProps, { eventKey: 1, disabled: activePage === 1 }), React.createElement( 'span', { 'aria-label': 'First' }, first === true ? '\xAB' : first ) ), prev && React.createElement( PaginationButton, _extends({}, buttonProps, { eventKey: activePage - 1, disabled: activePage === 1 }), React.createElement( 'span', { 'aria-label': 'Previous' }, prev === true ? '\u2039' : prev ) ), this.renderPageButtons(activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps), next && React.createElement( PaginationButton, _extends({}, buttonProps, { eventKey: activePage + 1, disabled: activePage >= items }), React.createElement( 'span', { 'aria-label': 'Next' }, next === true ? '\u203A' : next ) ), last && React.createElement( PaginationButton, _extends({}, buttonProps, { eventKey: items, disabled: activePage >= items }), React.createElement( 'span', { 'aria-label': 'Last' }, last === true ? '\xBB' : last ) ) ); }; return Pagination; }(React.Component); Pagination.propTypes = propTypes; Pagination.defaultProps = defaultProps; export default bsClass('pagination', Pagination);
examples/src/app.js
katienreed/react-select
/* eslint react/prop-types: 0 */ import React from 'react'; import Select from 'react-select'; import CustomRenderField from './components/CustomRenderField'; import MultiSelectField from './components/MultiSelectField'; import RemoteSelectField from './components/RemoteSelectField'; import SelectedValuesField from './components/SelectedValuesField'; import StatesField from './components/StatesField'; import UsersField from './components/UsersField'; import ValuesAsNumbersField from './components/ValuesAsNumbersField'; import DisabledUpsellOptions from './components/DisabledUpsellOptions'; var FLAVOURS = [ { label: 'Chocolate', value: 'chocolate' }, { label: 'Vanilla', value: 'vanilla' }, { label: 'Strawberry', value: 'strawberry' }, { label: 'Cookies and Cream', value: 'cookiescream' }, { label: 'Peppermint', value: 'peppermint' } ]; var FLAVOURS_WITH_DISABLED_OPTION = FLAVOURS.slice(0); FLAVOURS_WITH_DISABLED_OPTION.unshift({ label: 'Caramel (You don\'t like it, apparently)', value: 'caramel', disabled: true }); function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } React.render( <div> <StatesField label="States" searchable /> <UsersField label="Users (custom options/value)" hint="This example uses Gravatar to render user's image besides the value and the options" /> <ValuesAsNumbersField label="Values as numbers" /> <MultiSelectField label="Multiselect"/> <SelectedValuesField label="Clickable labels (labels as links)" options={FLAVOURS} hint="Open the console to see click behaviour (data/event)" /> <SelectedValuesField label="Disabled option" options={FLAVOURS_WITH_DISABLED_OPTION} hint="You savage! Caramel is the best..." /> <DisabledUpsellOptions label="Disable option with an upsell link"/> <SelectedValuesField label="Option Creation (tags mode)" options={FLAVOURS} allowCreate hint="Enter a value that's not in the list, then hit enter" /> <CustomRenderField label="Custom render options/values" /> <CustomRenderField label="Custom render options/values (multi)" multi delimiter="," /> <RemoteSelectField label="Remote Options" hint='Type anything in the remote example to asynchronously load options. Valid alternative results are "A", "AA", and "AB"' /> </div>, document.getElementById('example') );
src/routes/Home/components/HomeView.js
amaurisquezada/battleship
import React from 'react' export const HomeView = () => ( <div> <h4>Welcome!</h4> </div> ) export default HomeView
src/layouts/CoreLayout/CoreLayout.js
aurel-tackoen/spencer.io
import React from 'react' import Header from '../../components/Header' import classes from './CoreLayout.scss' import '../../styles/core.scss' export const CoreLayout = ({ children }) => ( <div className='container text-center'> <Header /> <div className={classes.mainContainer}> {children} </div> </div> ) CoreLayout.propTypes = { children: React.PropTypes.element.isRequired } export default CoreLayout
src/components/Box/BoxHeader.js
wundery/wundery-ui-react
import React from 'react'; import classnames from 'classnames'; function BoxHeader({ noPadding, compact, children, center }) { const className = classnames('ui-box-header', { 'ui-box-header-no-padding': noPadding, 'ui-box-header-compact': compact, 'ui-box-header-center': center, }); return ( <div className={className}> {children} </div> ); } BoxHeader.propTypes = { children: React.PropTypes.node, // Specifies whether padding should be removed noPadding: React.PropTypes.bool, compact: React.PropTypes.bool, center: React.PropTypes.bool, }; export default BoxHeader;
src/svg-icons/editor/border-outer.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderOuter = (props) => ( <SvgIcon {...props}> <path d="M13 7h-2v2h2V7zm0 4h-2v2h2v-2zm4 0h-2v2h2v-2zM3 3v18h18V3H3zm16 16H5V5h14v14zm-6-4h-2v2h2v-2zm-4-4H7v2h2v-2z"/> </SvgIcon> ); EditorBorderOuter = pure(EditorBorderOuter); EditorBorderOuter.displayName = 'EditorBorderOuter'; EditorBorderOuter.muiName = 'SvgIcon'; export default EditorBorderOuter;
popup/src/scripts/components/search/PeopleSearchList.js
CaliAlec/ChromeIGStory
import React, { Component } from 'react'; import {connect} from 'react-redux'; import Tooltip from '@material-ui/core/Tooltip'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemText from '@material-ui/core/ListItemText'; import ListItemAvatar from '@material-ui/core/ListItemAvatar'; import Avatar from '@material-ui/core/Avatar'; import IconButton from '@material-ui/core/IconButton'; import DownloadIcon from '@material-ui/icons/GetApp'; import CircularProgress from '@material-ui/core/CircularProgress'; import InstagramApi from '../../../../../utils/InstagramApi'; import {fetchStory} from '../../../../../utils/Utils'; import {setCurrentStoryObject} from '../../utils/PopupUtils'; import AnalyticsUtil from '../../../../../utils/AnalyticsUtil'; class PeopleSearchList extends Component { constructor(props){ super(props); this.state = { selectedIndex: -1, downloadingIndex: -1, isDownloadingStory: false } } handleRequestChange (event, index) { var selectedResult = this.props.results[index]; selectedResult.id = selectedResult.pk; fetchStory(selectedResult, false, (story) => { setCurrentStoryObject('USER_STORY', story); }); this.setState({ selectedIndex: index, }); AnalyticsUtil.track("Search List Item Clicked", { type: "user", result: { id: selectedResult.pk, username: selectedResult.username } }); } getMenuItem(index) { return ( <Tooltip title="Download" > <IconButton onClick={() => { if(!this.state.isDownloadingStory) { var selectedResult = this.props.results[index]; selectedResult.id = selectedResult.pk; this.setState({ isDownloadingStory: true, downloadingIndex: index }); fetchStory(selectedResult, true, (story) => { this.setState({isDownloadingStory: false}); if(!story) { // show 'No Story Available' Snackbar message setCurrentStoryObject(null, null); } }); } }}> {(this.state.isDownloadingStory && this.state.downloadingIndex === index) ? <CircularProgress size={24}/> : <DownloadIcon />} </IconButton> </Tooltip> ); } render() { const peopleSearchListData = this.props.results.map((user, key) => { return ( <ListItem key={key} button selected={this.state.selectedIndex === key} onClick={event => this.handleRequestChange(event, key)} > <ListItemAvatar> <Avatar src={user.profile_pic_url} /> </ListItemAvatar> <ListItemText primary={user.username} secondary={user.full_name} /> {this.getMenuItem(key)} </ListItem> ) }); return ( <List onChange={this.handleRequestChange.bind(this)}> {peopleSearchListData} </List> ) } } export default PeopleSearchList;
app/components/ListItem/index.js
iFatansyReact/react-boilerplate-imagine
import React from 'react'; import Item from './Item'; import Wrapper from './Wrapper'; function ListItem(props) { return ( <Wrapper> <Item> {props.item} </Item> </Wrapper> ); } ListItem.propTypes = { item: React.PropTypes.any, }; export default ListItem;
votrfront/js/MojePredmetyPage.js
fmfi-svt/votr
import React from 'react'; import { ZapisnyListSelector } from './ZapisnyListSelector'; import { CacheRequester, Loading } from './ajax'; import { coursesStats, renderCredits, renderWeightedStudyAverage } from './coursesStats'; import { classForSemester, humanizeTerminHodnotenia, humanizeTypVyucby, plural } from './humanizeAISData'; import { PageLayout, PageTitle } from './layout'; import { Link, queryConsumer } from './router'; import { sortAs, SortableTable } from './sorting'; export var MojePredmetyColumns = [ { label: "Semester", shortLabel: <abbr title="Semester">Sem.</abbr>, prop: "semester", preferDesc: true }, { label: "Názov predmetu", prop: "nazov", cell: (hodnotenie, query) => ( <Link href={{ ...query, modal: "detailPredmetu", modalPredmetKey: hodnotenie.predmet_key, modalAkademickyRok: hodnotenie.akademicky_rok }} > {hodnotenie.nazov} </Link> ), expansionMark: true }, { label: "Skratka predmetu", prop: "skratka", hiddenClass: ["hidden-xs", "hidden-sm"] }, { label: "Kredit", prop: "kredit", process: sortAs.number }, { label: "Typ výučby", prop: "typ_vyucby", cell: (hodnotenie, query) => humanizeTypVyucby(hodnotenie.typ_vyucby), hiddenClass: ["hidden-xs"] }, { label: "Hodnotenie", prop: "hodn_znamka", cell: hodnotenie => `${hodnotenie.hodn_znamka ? hodnotenie.hodn_znamka : ""}${ hodnotenie.hodn_znamka ? " - " : ""}${ hodnotenie.hodn_znamka_popis}` }, { label: "Dátum hodnotenia", prop: "hodn_datum", process: sortAs.date, hiddenClass: ["hidden-xs", "hidden-sm"] }, { label: "Termín hodnotenia", prop: "hodn_termin", cell: hodnotenie => humanizeTerminHodnotenia(hodnotenie.hodn_termin), hiddenClass: ["hidden-xs", "hidden-sm"] } ]; MojePredmetyColumns.defaultOrder = 'd0a1'; export function MojePredmetyPageContent() { return queryConsumer(query => { var cache = new CacheRequester(); var {zapisnyListKey} = query; var [hodnotenia, message] = cache.get('get_hodnotenia', zapisnyListKey) || []; if (!hodnotenia) { return <Loading requests={cache.missing} />; } var stats = coursesStats(hodnotenia); var footer = fullTable => ( <tr> <td className={fullTable ? "" : "hidden-xs hidden-sm"} /> <td colSpan="2"> Celkom {stats.spolu.count}{" "} {plural(stats.spolu.count, "predmet", "predmety", "predmetov")} {" ("} {stats.zima.count} v zime, {stats.leto.count} v lete) </td> <td>{renderCredits(stats.spolu)} ({renderCredits(stats.zima)}&nbsp;+&nbsp;{renderCredits(stats.leto)})</td> <td className={fullTable ? "" : "hidden-xs"} /> <td>{renderWeightedStudyAverage(hodnotenia)}</td> <td className={fullTable ? "" : "hidden-xs hidden-sm"} /> <td className={fullTable ? "" : "hidden-xs hidden-sm"} /> </tr> ); return <SortableTable items={hodnotenia} columns={MojePredmetyColumns} queryKey="predmetySort" expandedContentOffset={1} message={message} footer={footer} rowClassName={hodnotenie => classForSemester(hodnotenie.semester)} />; }); } export function MojePredmetyPage() { return ( <PageLayout> <ZapisnyListSelector> <div className="header"> <PageTitle>Moje predmety</PageTitle> </div> <MojePredmetyPageContent /> </ZapisnyListSelector> </PageLayout> ); }
src/svg-icons/device/battery-50.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery50 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V13h10V5.33z"/><path d="M7 13v7.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13H7z"/> </SvgIcon> ); DeviceBattery50 = pure(DeviceBattery50); DeviceBattery50.displayName = 'DeviceBattery50'; DeviceBattery50.muiName = 'SvgIcon'; export default DeviceBattery50;
app/App.js
luketlancaster/github-notetaker
import React from 'react'; import Router from 'react-router'; import routes from './config/routes'; Router.run(routes, (Root, state) => { React.render(<Root {...state}/>, document.getElementById('app')) })
examples/forms-material-ui/src/components/forms-create-overlay/Hook.js
lore/lore-forms
import React from 'react'; import createReactClass from 'create-react-class'; import moment from 'moment'; export default createReactClass({ displayName: 'Hook', render: function() { return lore.forms.tweet.create({ blueprint: 'overlay' }); } });
src/js/routes.js
VitorHP/TI3
import React from 'react'; import { IndexRoute, Route } from 'react-router'; import LobbyContainer from './containers/lobby_container'; import TableContainer from './containers/table_container'; import AppContainer from './containers/app_container'; import MainMenu from './components/main_menu'; import RacesScreenContainer from './containers/races_screen_container'; export default ( <Route path="/" component={AppContainer}> <IndexRoute component={MainMenu}/> <Route path="races" component={RacesScreenContainer}/> <Route path="table" component={TableContainer}/> </Route> )
src/components/Footer/Footer.js
dorono/resistance-calendar-frontend
import React from 'react'; import { Link } from 'react-router-dom'; import { Copyright } from '../'; import styles from './Footer.sass'; function footerLinks() { /* eslint-disable jsx-a11y/href-no-hash */ return ( <div className={styles.linksWrapper}> <Link to="/">Home</Link> <a href="https://www.facebook.com/resistancecalendar" target="_blank" rel="noopener noreferrer" > Facebook </a> <a href="https://twitter.com/ResistCalendar" target="_blank" rel="noopener noreferrer" > Twitter </a> <Link to="/privacy-policy">Privacy Policy</Link> </div> ); /* eslint-enable jsx-a11y/href-no-hash */ } const Footer = () => { const year = (new Date()).getFullYear(); return ( <footer className={styles.footer}> {footerLinks()} <Copyright year={year} /> </footer> ); }; Footer.propTypes = {}; export default Footer;
www/imports/component/TextareaClean.js
terraswat/hexagram
// TextAreaClean.js // A textarea to contain text that contains only printable characters. import React, { Component } from 'react'; import PropTypes from 'prop-types'; import utils from '/imports/common/utils.js'; export default class TextareaClean extends Component { constructor (props) { super(props); this.state = { value: this.props.value }; // Save our selves. this.componentDidMount = this.componentDidMount.bind(this); this.handleKeyPress = this.handleKeyPress.bind(this); this.handleChange = this.handleChange.bind(this); } componentDidMount () { // Set focus on this textarea if the parent did not override. if (!this.props.noFocus) { $(this.textarea).focus(); } } handleChange (event) { // This handles updates to the textarea directly by the user, // including cutting and pasting, and a user keypress. var val = event.target.value; // Skip this if we already validated with the key press. if (this.alreadyValidated) { this.alreadyValidated = false; } else { // Drop unprintables from the updated text. we need to look at the // entire text because we don't know what changed. utils.dropUnprintables(val); } // Let the parent know. this.props.onChange(val); } handleKeyPress (event) { // Don't allow unprintables here except newLine. // This does not capture cutting or pasting in the textarea. // If this is an unprintable character... if (utils.unprintableAsciiCode(event.which, true)) { // Prevent the display from being updated with the bad value. event.preventDefault(); } else { // Mark this character as validated. this.alreadyValidated = true; } } render () { return ( <textarea onKeyPress = {this.handleKeyPress} onChange = {this.handleChange} value = {this.props.value} className = {this.props.className} placeholder = {this.props.placeholder} rows = {this.props.rows} cols = {this.props.cols} ref={(textarea) => { this.textarea = textarea; }} /> ); } } TextareaClean.propTypes = { // Function to call when the textarea changes. onChange: PropTypes.func.isRequired, // Value of the textarea that the parent owns. value: PropTypes.string.isRequired, // An application-unique class to add to the textarea. className: PropTypes.string, // Text to display when the textarea is empty. placeholder: PropTypes.string, // Number of rows and columns. rows: PropTypes.string, cols: PropTypes.string, // True means to not set focus to this element. noFocus: PropTypes.bool, }; TextareaClean.defaultProps = { rows: '10', cols: '20', noFocus: false, };
src/components/LaborRightsSingle/Body.js
goodjoblife/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import { StickyContainer, Sticky } from 'react-sticky'; import cn from 'classnames'; import { Section, Wrapper, Heading } from 'common/base'; import GradientMask from 'common/GradientMask'; import MarkdownParser from './MarkdownParser'; import styles from './Body.module.css'; import LeftBanner from '../ExperienceSearch/Banners/Banner1'; const Body = ({ title, seoText, description, content, permissionBlock }) => ( <Section Tag="main" pageTop> <Wrapper size="m"> <Heading size="l" bold marginBottom> {title} </Heading> <div className={cn('subheadingM', styles.description)}>{description}</div> </Wrapper> <Wrapper size="l"> <div className={styles.contentWrapper}> <StickyContainer className={cn(styles.leftBanner)}> <Sticky disableCompensation> {({ style }) => ( <div style={style}> <LeftBanner /> </div> )} </Sticky> </StickyContainer> <div className={styles.content}> <GradientMask show={permissionBlock !== null}> <MarkdownParser content={content} /> </GradientMask> {permissionBlock} </div> </div> {seoText && <div className={styles.seoText}>{seoText}</div>} </Wrapper> </Section> ); Body.propTypes = { title: PropTypes.string, seoText: PropTypes.string, description: PropTypes.string.isRequired, content: PropTypes.string.isRequired, permissionBlock: PropTypes.element, }; Body.defaultProps = { title: '', description: '', content: '', permissionBlock: null, }; export default Body;
src/components/LaborRightsSingle/index.js
chejen/GoodJobShare
import React from 'react'; import Helmet from 'react-helmet'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Loader from 'common/Loader'; import { formatTitle, formatCanonicalPath, formatUrl, } from 'utils/helmetHelper'; import NotFound from 'common/NotFound'; import CallToAction from 'common/CallToAction'; import Body from './Body'; import Footer from './Footer'; import { fetchMetaListIfNeeded, fetchDataIfNeeded, } from '../../actions/laborRightsSingle'; import status from '../../constants/status'; import { SITE_NAME } from '../../constants/helmetData'; class LaborRightsSingle extends React.Component { static fetchData({ store: { dispatch }, params: { id } }) { return dispatch(fetchMetaListIfNeeded()).then(() => dispatch(fetchDataIfNeeded(id)) ); } componentDidMount() { this.props.fetchMetaListIfNeeded().then(() => { this.props.fetchDataIfNeeded(this.props.params.id); }); } componentDidUpdate() { this.props.fetchMetaListIfNeeded().then(() => { this.props.fetchDataIfNeeded(this.props.params.id); }); } render() { const { id, title, description, content, coverUrl, } = this.props.data ? this.props.data.toJS() : {}; const { seoTitle = title || '', seoDescription, seoText, } = this.props.data ? this.props.data.toJS() : {}; return ( <main> <Helmet title={seoTitle} meta={[ { name: 'description', content: seoDescription }, { property: 'og:url', content: formatCanonicalPath(`/labor-rights/${id}`) }, { property: 'og:title', content: formatTitle(seoTitle, SITE_NAME) }, { property: 'og:description', content: seoDescription }, { property: 'og:image', content: formatUrl(coverUrl) }, ]} link={[ { rel: 'canonical', href: formatCanonicalPath(`/labor-rights/${id}`) }, ]} /> {this.props.status === status.FETCHING && <Loader />} { this.props.status === status.ERROR && this.props.error.get('message') === 'Not found' && <NotFound /> } { this.props.status === status.FETCHED && <div> <Body title={title} seoText={seoText} description={description} content={content} /> <Footer id={id} prev={this.props.prev} next={this.props.next} /> <CallToAction imgSrc="https://image.goodjob.life/cta-01.png" marginTop /> </div> } </main> ); } } LaborRightsSingle.propTypes = { params: React.PropTypes.object.isRequired, data: ImmutablePropTypes.map, prev: ImmutablePropTypes.map, next: ImmutablePropTypes.map, fetchMetaListIfNeeded: React.PropTypes.func.isRequired, fetchDataIfNeeded: React.PropTypes.func.isRequired, status: React.PropTypes.string.isRequired, error: ImmutablePropTypes.map, }; export default LaborRightsSingle;
client/components/common/FormRenderWrappers.js
zhakkarn/Mail-for-Good
/* eslint-disable */ import React from 'react'; import { Combobox, DropdownList } from 'react-widgets'; import { Field } from 'redux-form'; import TextEditor from '../../containers/common/TextEditor'; // Ref redux-form http://redux-form.com/6.0.5/docs/GettingStarted.md/ // Ref react-widgets https://jquense.github.io/react-widgets/ (for examples see https://github.com/erikras/redux-form/blob/master/examples/react-widgets/src/ReactWidgetsForm.js) // Ref react-rte https://github.com/sstur/react-rte /* Helper wrapper functions for react-widgets from the redux-form examples page. const renderSelectList = ({ input, ...rest }) => <SelectList {...input} onBlur={() => input.onBlur()} {...rest}/>; const renderDropdownList = ({ input, ...rest }) => <DropdownList {...input} {...rest}/>; const renderMultiselect = ({ input, ...rest }) => <Multiselect {...input} onBlur={() => input.onBlur()} value={input.value || []} // requires value to be an array {...rest}/>; */ const savedLabel = <div className="label label-success">Saved</div>; const notSavedLabel = <div className="label label-danger">Not saved</div>; export const renderSettingsDropdownList = ({ input, label, type, meta: { touched, error, warning }, exists, helpText, ...data }) => ( <div style={{ marginBottom: "1em" }}> <label>{label} - { exists ? savedLabel : notSavedLabel }</label> <p className="form-text text-muted">{helpText}</p> <div> <DropdownList {...input} {...data} /> {touched && ((error && <span className="text-red"><i className="fa fa-exclamation" /> {error}</span>) || (warning && <span>{warning}</span>))} </div> </div> ); export const renderDropdownList = ({ input, label, type, meta: { touched, error, warning }, ...data }) => ( <div> <label>{label}</label> <div> <DropdownList {...input} {...data} /> {touched && ((error && <span className="text-red"><i className="fa fa-exclamation" /> {error}</span>) || (warning && <span>{warning}</span>))} </div> </div> ); export const renderCombobox = ({ input, label, type, meta: { touched, error, warning }, ...data }) => ( <div> <label>{label}</label> <div> <Combobox {...input} {...data} suggest={true} filter="contains" /> {touched && ((error && <span className="text-red"><i className="fa fa-exclamation" /> {error}</span>) || (warning && <span>{warning}</span>))} </div> </div> ); export const renderSettingsField = ({ input, label, type, meta: { touched, error, warning }, exists, helpText, placeholder }) => { return ( <div style={{ marginBottom: "1em" }}> <label>{label} - { exists ? savedLabel : notSavedLabel }</label> <p className="form-text text-muted">{helpText}</p> <div> <input className="form-control" {...input} placeholder={placeholder} type={type}/> {touched && ((error && <span className="text-red"><i className="fa fa-exclamation" /> {error}</span>) || (warning && <span>{warning}</span>))} </div> </div> )}; export const renderField = ({ input, label, type, meta: { touched, error, warning } }) => { return ( <div> <label>{label}</label> <div> <input className={getInputClassFromType(type)} {...input} placeholder={label} type={type}/> {touched && ((error && <span className="text-red"><i className="fa fa-exclamation" /> {error}</span>) || (warning && <span>{warning}</span>))} </div> </div> )}; export const renderEditorTypeRadio = ({ input, label, type, meta: { touched, error, warning } }) => ( <div> <label>{label}</label> <div className="form-group"> <label><Field component="input" type="radio" name={input.name} value="Plaintext" /> Plaintext</label> <br /> <label><Field component="input" type="radio" name={input.name} value="HTML" /> HTML</label> <br /> {touched && ((error && <span className="text-red"><i className="fa fa-exclamation" /> {error}</span>) || (warning && <span>{warning}</span>))} </div> </div> ); export const renderTextEditor = ({ input, label, type, meta: { touched, error, warning }, textEditorValue, textEditorType, emailBody }) => ( <div> <label>{label}</label> <div> <Field name={emailBody ? emailBody : 'emailBody'} value={() => input.value} onChange={() => input.onChange} component={TextEditor} textEditorValue={textEditorValue} textEditorType={textEditorType} /> {touched && ((error && <span className="text-red"><i className="fa fa-exclamation" /> {error}</span>) || (warning && <span>{warning}</span>))} </div> </div> ); function getInputClassFromType(type) { let properClass = '' switch (type) { case "datetime-local": case "email": case "password": case "search": case "tel": case "text": case "url": properClass="form-control"; break; case "checkbox": case "radio": properClass="form-check-input"; break; } return properClass; }
src/Notification.js
rolandsusans/react-bootstrap-table
import React, { Component } from 'react'; import { ToastContainer, ToastMessage } from '@allenfang/react-toastr'; const ToastrMessageFactory = React.createFactory(ToastMessage.animation); class Notification extends Component { // allow type is success,info,warning,error notice(type, msg, title) { this.refs.toastr[type]( msg, title, { mode: 'single', timeOut: 5000, extendedTimeOut: 1000, showAnimation: 'animated bounceIn', hideAnimation: 'animated bounceOut' }); } render() { return ( <ToastContainer ref='toastr' toastMessageFactory={ ToastrMessageFactory } id='toast-container' className='toast-top-right'/> ); } } export default Notification;
mm-react/src/components/docs/Ckeditor.js
Ameobea/tickgrinder
//! Creates a ckeditor instance. Contains options for taking callbacks involved with saving changes. /* global CKEDITOR */ import React from 'react'; import { connect } from 'dva'; /** * After the CKEditor plugin has loaded, initialize the editor */ function awaitCk(rand) { setTimeout(() => { let ckeditorLoaded = true; try{ CKEDITOR; } catch(e) { if(e.name == 'ReferenceError') { ckeditorLoaded = false; } } if(ckeditorLoaded) { CKEDITOR.replace( `ckeditor-${rand}` ); } else { awaitCk(rand); } }, 50); } class CKEditor extends React.Component { componentDidMount() { // add a script tag onto the document that loads the CKEditor script let ckeditor_src = document.createElement('script'); ckeditor_src.type = 'text/javascript'; ckeditor_src.async = true; ckeditor_src.src='/ckeditor/ckeditor.js'; document.getElementById('ckeditor-' + this.props.rand).appendChild(ckeditor_src); // wait for the CKEditor script to load and then initialize the editor awaitCk(this.props.rand); // register our id as the active editor instance this.props.dispatch({type: 'documents/setEditorId', id: this.props.rand}); } shouldComponentUpdate(...args) { return false; } render() { return ( <textarea id={'ckeditor-' + this.props.rand} /> ); } } CKEditor.propTypes = { rand: React.PropTypes.number.isRequired, }; export default connect()(CKEditor);
docs/app/Examples/views/Comment/Variations/CommentExampleMinimal.js
clemensw/stardust
import React from 'react' import { Button, Comment, Form, Header } from 'semantic-ui-react' const CommentExampleMinimal = () => ( <Comment.Group minimal> <Header as='h3' dividing>Comments</Header> <Comment> <Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/matt.jpg' /> <Comment.Content> <Comment.Author as='a'>Matt</Comment.Author> <Comment.Metadata> <span>Today at 5:42PM</span> </Comment.Metadata> <Comment.Text>How artistic!</Comment.Text> <Comment.Actions> <a>Reply</a> </Comment.Actions> </Comment.Content> </Comment> <Comment> <Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/elliot.jpg' /> <Comment.Content> <Comment.Author as='a'>Elliot Fu</Comment.Author> <Comment.Metadata> <span>Yesterday at 12:30AM</span> </Comment.Metadata> <Comment.Text> <p>This has been very useful for my research. Thanks as well!</p> </Comment.Text> <Comment.Actions> <a>Reply</a> </Comment.Actions> </Comment.Content> <Comment.Group> <Comment> <Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/jenny.jpg' /> <Comment.Content> <Comment.Author as='a'>Jenny Hess</Comment.Author> <Comment.Metadata> <span>Just now</span> </Comment.Metadata> <Comment.Text>Elliot you are always so right :)</Comment.Text> <Comment.Actions> <a>Reply</a> </Comment.Actions> </Comment.Content> </Comment> </Comment.Group> </Comment> <Comment> <Comment.Avatar as='a' src='http://semantic-ui.com/images/avatar/small/joe.jpg' /> <Comment.Content> <Comment.Author as='a'>Joe Henderson</Comment.Author> <Comment.Metadata> <span>5 days ago</span> </Comment.Metadata> <Comment.Text>Dude, this is awesome. Thanks so much</Comment.Text> <Comment.Actions> <a>Reply</a> </Comment.Actions> </Comment.Content> </Comment> <Form reply onSubmit={e => e.preventDefault()}> <Form.TextArea /> <Button content='Add Reply' labelPosition='left' icon='edit' primary /> </Form> </Comment.Group> ) export default CommentExampleMinimal
app/javascript/mastodon/features/compose/components/search.js
summoners-riftodon/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Overlay from 'react-overlays/lib/Overlay'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { searchEnabled } from '../../../initial_state'; const messages = defineMessages({ placeholder: { id: 'search.placeholder', defaultMessage: 'Search' }, }); class SearchPopout extends React.PureComponent { static propTypes = { style: PropTypes.object, }; render () { const { style } = this.props; const extraInformation = searchEnabled ? <FormattedMessage id='search_popout.tips.full_text' defaultMessage='Simple text returns statuses you have written, favourited, boosted, or have been mentioned in, as well as matching usernames, display names, and hashtags.' /> : <FormattedMessage id='search_popout.tips.text' defaultMessage='Simple text returns matching display names, usernames and hashtags' />; return ( <div style={{ ...style, position: 'absolute', width: 285 }}> <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( <div className='search-popout' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})` }}> <h4><FormattedMessage id='search_popout.search_format' defaultMessage='Advanced search format' /></h4> <ul> <li><em>#example</em> <FormattedMessage id='search_popout.tips.hashtag' defaultMessage='hashtag' /></li> <li><em>@username@domain</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li> <li><em>URL</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li> <li><em>URL</em> <FormattedMessage id='search_popout.tips.status' defaultMessage='status' /></li> </ul> {extraInformation} </div> )} </Motion> </div> ); } } @injectIntl export default class Search extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, submitted: PropTypes.bool, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, onShow: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { expanded: false, }; handleChange = (e) => { this.props.onChange(e.target.value); } handleClear = (e) => { e.preventDefault(); if (this.props.value.length > 0 || this.props.submitted) { this.props.onClear(); } } handleKeyDown = (e) => { if (e.key === 'Enter') { e.preventDefault(); this.props.onSubmit(); } else if (e.key === 'Escape') { document.querySelector('.ui').parentElement.focus(); } } noop () { } handleFocus = () => { this.setState({ expanded: true }); this.props.onShow(); } handleBlur = () => { this.setState({ expanded: false }); } render () { const { intl, value, submitted } = this.props; const { expanded } = this.state; const hasValue = value.length > 0 || submitted; return ( <div className='search'> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.placeholder)}</span> <input className='search__input' type='text' placeholder={intl.formatMessage(messages.placeholder)} value={value} onChange={this.handleChange} onKeyUp={this.handleKeyDown} onFocus={this.handleFocus} onBlur={this.handleBlur} /> </label> <div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}> <i className={`fa fa-search ${hasValue ? '' : 'active'}`} /> <i aria-label={intl.formatMessage(messages.placeholder)} className={`fa fa-times-circle ${hasValue ? 'active' : ''}`} /> </div> <Overlay show={expanded && !hasValue} placement='bottom' target={this}> <SearchPopout /> </Overlay> </div> ); } }
src/chat/ui/NavBackAbs.js
elarasu/roverz-chat
import React from 'react'; import { TouchableOpacity, StyleSheet, } from 'react-native'; import { Icon } from 'react-native-elements'; import { Actions } from 'react-native-router-flux'; import PropTypes from 'prop-types'; import { isIphoneX } from 'react-native-iphone-x-helper'; import { AppColors } from '../../theme/'; const styles = StyleSheet.create({ container: { position: 'absolute', top: 20, left: 20, padding: 5, backgroundColor: AppColors.brand().nA_style, borderRadius: 40, }, }); const icon = AppColors.brand().nA_Icon; export default class NavBackAbs extends React.Component { constructor(props) { super(props); this.state = { title: this.props.title, }; } componentWillMount() { /* this.setState({ title: Application.base.instance, }); */ } componentDidMount() { } render() { return ( <TouchableOpacity style={[styles.container, { top: isIphoneX() ? 40 : 20 }]} onPress={Actions.pop} > <Icon name="arrow-back" size={30} color={icon} width={30} /> </TouchableOpacity> ); } } NavBackAbs.defaultProps = { title: '', }; NavBackAbs.propTypes = { title: PropTypes.string, };
admin/client/components/FooterBar.js
mikaoelitiana/keystone
import React from 'react'; import blacklist from 'blacklist'; var FooterBar = React.createClass({ propTypes: { style: React.PropTypes.object }, getDefaultProps () { return { style: {} }; }, getInitialState () { return { position: 'relative', width: 'auto', height: 'auto', top: 0 }; }, componentDidMount () { // Bail in IE8 because React doesn't support the onScroll event in that browser // Conveniently (!) IE8 doesn't have window.getComputedStyle which we also use here if (!window.getComputedStyle) return; var footer = this.refs.footer; this.windowSize = this.getWindowSize(); var footerStyle = window.getComputedStyle(footer); this.footerSize = { x: footer.offsetWidth, y: footer.offsetHeight + parseInt(footerStyle.marginTop || '0') }; window.addEventListener('scroll', this.recalcPosition, false); window.addEventListener('resize', this.recalcPosition, false); this.recalcPosition(); }, getWindowSize () { return { x: window.innerWidth, y: window.innerHeight }; }, recalcPosition () { var wrapper = this.refs.wrapper; this.footerSize.x = wrapper.offsetWidth; var offsetTop = 0; var offsetEl = wrapper; while (offsetEl) { offsetTop += offsetEl.offsetTop; offsetEl = offsetEl.offsetParent; } var maxY = offsetTop + this.footerSize.y; var viewY = window.scrollY + window.innerHeight; var newSize = this.getWindowSize(); var sizeChanged = (newSize.x !== this.windowSize.x || newSize.y !== this.windowSize.y); this.windowSize = newSize; var newState = { width: this.footerSize.x, height: this.footerSize.y }; if (viewY > maxY && (sizeChanged || this.mode !== 'inline')) { this.mode = 'inline'; newState.top = 0; newState.position = 'absolute'; this.setState(newState); } else if (viewY <= maxY && (sizeChanged || this.mode !== 'fixed')) { this.mode = 'fixed'; newState.top = window.innerHeight - this.footerSize.y; newState.position = 'fixed'; this.setState(newState); } }, render () { var wrapperStyle = { height: this.state.height, marginTop: 60, position: 'relative' }; var footerProps = blacklist(this.props, 'children', 'style'); var footerStyle = Object.assign({}, this.props.style, { position: this.state.position, top: this.state.top, width: this.state.width, height: this.state.height }); return ( <div ref="wrapper" style={wrapperStyle}> <div ref="footer" style={footerStyle} {...footerProps}>{this.props.children}</div> </div> ); } }); module.exports = FooterBar;
packages/web/examples/NumberBox/src/index.js
appbaseio/reactivesearch
import React from 'react'; import ReactDOM from 'react-dom'; import { ReactiveBase, NumberBox, ResultList, ReactiveList } from '@appbaseio/reactivesearch'; import './index.css'; const Main = () => ( <ReactiveBase app="good-books-ds" url="https://a03a1cb71321:75b6603d-9456-4a5a-af6b-a487b309eb61@appbase-demo-ansible-abxiydt-arc.searchbase.io" enableAppbase > <div className="row reverse-labels"> <div className="col"> <NumberBox componentId="BookSensor" dataField="average_rating_rounded" data={{ label: 'Book Rating', start: 2, end: 5, }} labelPosition="left" /> </div> <div className="col" style={{ backgroundColor: '#fafafa' }}> <ReactiveList componentId="SearchResult" dataField="original_title" from={0} size={3} className="result-list-container" pagination react={{ and: 'BookSensor', }} render={({ data }) => ( <ReactiveList.ResultListWrapper> {data.map(item => ( <ResultList key={item._id}> <ResultList.Image src={item.image} /> <ResultList.Content> <ResultList.Title> <div className="book-title" dangerouslySetInnerHTML={{ __html: item.original_title, }} /> </ResultList.Title> <ResultList.Description> <div className="flex column justify-space-between"> <div> <div> by{' '} <span className="authors-list"> {item.authors} </span> </div> <div className="ratings-list flex align-center"> <span className="stars"> {Array(item.average_rating_rounded) .fill('x') .map((i, index) => ( <i className="fas fa-star" key={index} /> )) // eslint-disable-line } </span> <span className="avg-rating"> ({item.average_rating} avg) </span> </div> </div> <span className="pub-year"> Pub {item.original_publication_year} </span> </div> </ResultList.Description> </ResultList.Content> </ResultList> ))} </ReactiveList.ResultListWrapper> )} /> </div> </div> </ReactiveBase> ); ReactDOM.render(<Main />, document.getElementById('root'));
src/components/common/NavBarCancel.js
jinqiupeter/mtsr
import React from 'react'; import {StyleSheet, Platform, View, Text} from 'react-native'; import {Actions} from 'react-native-router-flux'; import dismissKeyboard from 'dismissKeyboard'; import * as components from '../'; export default () => { return <components.NavBarLeftButton text='取消' onPress={() => { dismissKeyboard(); Actions.pop(); }} textStyle={styles.text} />; } const styles = StyleSheet.create({ text: { fontSize: 14, } });
web/app/data/load.js
bitemyapp/serials
// @flow import {map, flatten} from 'lodash' import {Promise} from 'es6-promise' import React from 'react' type Route = { handler: { load:Function; } } export function loadAll(routes:Array<Route>, params:Object, query:Object, onData:(data:any)=>void) { var data = {loaded: false}; routes .filter(route => route.handler.load) .forEach(function(route) { // ok, they're allowed to do more than one, right? var promises = route.handler.load(params, query) return map(promises, function(promise, name) { if (!promise.then) { // it isn't a promise, it's a value // resolve it promise = Promise.resolve(promise) } return promise.then(function(d) { data[name] = d data.loaded = true onData(data) }, throwError) }) }) } function throwError(err) { throw err } // store the last one :) var lastHandler:any var lastState:any var lastData:any var innerRender:any function nothing() {} export function run(ren:Function, onUrlChange:Function = nothing):Function { innerRender = ren return function(Handler, state) { lastHandler = Handler lastState = state lastData = {loaded: false} onUrlChange(Handler, state) // render once without any data render() // render again every time any of the promises resolve loadAll(state.routes, state.params, state.query, render) } } export function render(data:any = lastData) { lastData = data var Handler = lastHandler var state = lastState innerRender(Handler, state, data) } // global reload export function reloadHandler() { loadAll(lastState.routes, lastState.params, lastState.query, render) }
src/js/components/icons/base/PlatformPiedPiper.js
odedre/grommet-final
/** * @description PlatformPiedPiper SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M0,19.4210526 C2.2736843,19.4210526 4.04210525,18.6631579 4.04210525,18.6631579 C4.04210525,18.6631579 7.0736842,11.0842105 11.368421,11.0842105 C14.6526316,11.0842105 15.1578947,13.6105264 15.1578947,13.6105264 C15.1578947,13.6105264 19.9578947,4.26315788 24,3 C20.2105263,6.03157895 20.7157895,9.31578948 18.9473684,10.831579 C17.1789474,12.3473684 17.1789477,10.8381579 15.1578951,14.375 C10.6105267,14.8802632 9.125,16.3894739 6.06315789,18.1578947 C11.3684206,15.6315794 12.3789474,15.3789474 17.1789474,15.631579 C17.6828892,15.6581022 17.9368421,15.8842105 17.6842105,16.3894737 C16.951256,17.8553827 16.4037001,20.0617486 15.4105263,19.9263158 C9.85263157,19.1684211 6.56842104,20.431579 3.78947367,20.431579 C1.0105263,20.431579 0,19.9263158 0,19.4210526 Z"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-platform-pied-piper`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'platform-pied-piper'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fillRule="evenodd" d="M0,19.4210526 C2.2736843,19.4210526 4.04210525,18.6631579 4.04210525,18.6631579 C4.04210525,18.6631579 7.0736842,11.0842105 11.368421,11.0842105 C14.6526316,11.0842105 15.1578947,13.6105264 15.1578947,13.6105264 C15.1578947,13.6105264 19.9578947,4.26315788 24,3 C20.2105263,6.03157895 20.7157895,9.31578948 18.9473684,10.831579 C17.1789474,12.3473684 17.1789477,10.8381579 15.1578951,14.375 C10.6105267,14.8802632 9.125,16.3894739 6.06315789,18.1578947 C11.3684206,15.6315794 12.3789474,15.3789474 17.1789474,15.631579 C17.6828892,15.6581022 17.9368421,15.8842105 17.6842105,16.3894737 C16.951256,17.8553827 16.4037001,20.0617486 15.4105263,19.9263158 C9.85263157,19.1684211 6.56842104,20.431579 3.78947367,20.431579 C1.0105263,20.431579 0,19.9263158 0,19.4210526 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'PlatformPiedPiper'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/parser/priest/shadow/modules/spells/VampiricTouch.js
FaideWW/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import Enemies from 'parser/shared/modules/Enemies'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage } from 'common/format'; import SmallStatisticBox, { STATISTIC_ORDER } from 'interface/others/SmallStatisticBox'; class VampiricTouch extends Analyzer { static dependencies = { enemies: Enemies, }; get uptime() { return this.enemies.getBuffUptime(SPELLS.VAMPIRIC_TOUCH.id) / this.owner.fightDuration; } get suggestionThresholds() { return { actual: this.uptime, isLessThan: { minor: 0.95, average: 0.90, major: 0.8, }, style: 'percentage', }; } suggestions(when) { const { isLessThan: { minor, average, major, }, } = this.suggestionThresholds; when(this.uptime).isLessThan(minor) .addSuggestion((suggest, actual, recommended) => { return suggest(<span>Your <SpellLink id={SPELLS.VAMPIRIC_TOUCH.id} /> uptime can be improved. Try to pay more attention to your <SpellLink id={SPELLS.VAMPIRIC_TOUCH.id} /> on the boss.</span>) .icon(SPELLS.VAMPIRIC_TOUCH.icon) .actual(`${formatPercentage(actual)}% Vampiric Touch uptime`) .recommended(`>${formatPercentage(recommended)}% is recommended`) .regular(average).major(major); }); } statistic() { return ( <SmallStatisticBox position={STATISTIC_ORDER.CORE(3)} icon={<SpellIcon id={SPELLS.VAMPIRIC_TOUCH.id} />} value={`${formatPercentage(this.uptime)} %`} label="Vampiric Touch uptime" /> ); } } export default VampiricTouch;
apps/mk-app-versions/action.js
ziaochina/mk-demo
import React from 'react' import { action as MetaAction, AppLoader } from 'mk-meta-engine' import config from './config' class action { constructor(option) { this.metaAction = option.metaAction this.config = config.current this.webapi = this.config.webapi } onInit = ({ component, injections }) => { this.component = component this.injections = injections injections.reduce('init') this.load() } load = async () => { const response = await this.webapi.version.query() this.injections.reduce('load', response) } } export default function creator(option) { const metaAction = new MetaAction(option), o = new action({ ...option, metaAction }), ret = { ...metaAction, ...o } metaAction.config({ metaHandlers: ret }) return ret }
src/applications/static-pages/health-care-manage-benefits/refill-track-prescriptions-page/components/AuthContent/index.js
department-of-veterans-affairs/vets-website
// Node modules. import React from 'react'; import PropTypes from 'prop-types'; import Telephone, { CONTACTS, } from '@department-of-veterans-affairs/component-library/Telephone'; // Relative imports. import CernerCallToAction from '../../../components/CernerCallToAction'; import { getCernerURL } from 'platform/utilities/cerner'; import { mhvUrl } from 'platform/site-wide/mhv/utilities'; import ServiceProvidersList from 'platform/user/authentication/components/ServiceProvidersList'; export const AuthContent = ({ authenticatedWithSSOe, cernerFacilities, otherFacilities, }) => ( <> <CernerCallToAction cernerFacilities={cernerFacilities} otherFacilities={otherFacilities} linksHeaderText="Refill prescriptions from:" myHealtheVetLink={mhvUrl( authenticatedWithSSOe, 'web/myhealthevet/refill-prescriptions', )} myVAHealthLink={getCernerURL('/pages/medications/current')} /> <div> <div itemScope itemType="http://schema.org/Question"> <h2 itemProp="name" id="how-can-the-va-prescription-re"> How can VA’s prescription tools help me manage my health care? </h2> <div itemProp="acceptedAnswer" itemScope itemType="http://schema.org/Answer" > <div itemProp="text"> <div className="processed-content"> <p> These web- and mobile-based services help you manage your VA prescriptions online. </p> <p> <strong>With these tools, you can:</strong> </p> <ul> <li>Refill your VA prescriptions online</li> <li>View your past and current VA prescriptions</li> <li> Track the delivery of each prescription mailed within the past 30 days </li> <li> Get email notifications to let you know when to expect your prescriptions </li> <li> Create lists to keep track of all your medicines (including prescriptions, over-the-counter medicines, herbal remedies, and supplements) </li> </ul> </div> </div> </div> </div> <div itemScope itemType="http://schema.org/Question"> <h2 itemProp="name" id="am-i-eligible-to-use-this-tool"> Am I eligible to use this tool? </h2> <div itemProp="acceptedAnswer" itemScope itemType="http://schema.org/Answer" > <div itemProp="text"> <div className="processed-content"> <p> You can use these tools if you meet all of the requirements listed below. </p> <p> <strong>All of these must be true. You:</strong> </p> <ul> <li> Are enrolled in VA health care, <strong>and</strong> </li> <li> Are registered as a patient in a VA health facility,{' '} <strong>and</strong> </li> <li> Have a refillable prescription from a VA doctor that you’ve filled at a VA pharmacy and that’s being handled by the VA Mail Order Pharmacy </li> </ul> <p> <a href="/health-care/how-to-apply/"> Find out how to apply for VA health care </a> </p> <p> <strong>And you must have one of these free accounts:</strong> </p> <ServiceProvidersList /> </div> </div> </div> </div> <div itemScope itemType="http://schema.org/Question"> <h2 itemProp="name" id="once-im-signed-in-how-do-i-get"> Once I&apos;m signed in, how do I get started? </h2> <div itemProp="acceptedAnswer" itemScope itemType="http://schema.org/Answer" > <div itemProp="text"> <div className="processed-content"> <h3> If you’re refilling and tracking prescriptions on My HealtheVet </h3> <p> On your Welcome page, you’ll find a module for{' '} <strong>Pharmacy</strong>. Within that module, you’ll find these 3 options: </p> <ul> <li> <strong>Refill VA Prescriptions</strong> </li> <li> <strong>Track Delivery</strong> </li> <li> <strong>Medications List</strong> </li> </ul> <p> Click on the link you want. You’ll get instructions on the next page to get started. </p> <h3> If you’re refilling and tracking prescriptions on My VA Health </h3> <p> In the navigation menu, you’ll find a section titled{' '} <strong>Pharmacy</strong>. Within that section, you’ll find these 2 options: </p> <ul> <li> <strong>View current medications</strong>, and </li> <li> <strong>View comprehensive medications</strong> </li> </ul> <p> Choose the medication list you want. For each medication, you’ll then find options to refill and renew. </p> </div> </div> </div> </div> <div itemScope itemType="http://schema.org/Question"> <h2 itemProp="name" id="can-i-use-this-tool-to-refill-"> Can I use these tools to refill and track all my VA prescriptions? </h2> <div itemProp="acceptedAnswer" itemScope itemType="http://schema.org/Answer" > <div itemProp="text"> <div className="processed-content"> <p> <strong> You can refill and track most of your VA prescriptions, including: </strong> </p> <ul> <li>VA medicines that you’ve refilled or renewed</li> <li>Wound care supplies</li> <li>Diabetic supplies</li> <li> Other products and supplies sent through the VA Mail Order Pharmacy </li> </ul> <p> Your VA health care team may decide not to ship medicines that you don’t need right away, medicines that aren’t commonly prescribed, or those that require you to be closely monitored. In these cases, you’ll need to pick up your prescription from the VA health facility where you get care. </p> <p> You can’t refill some medicines, like certain pain medications and narcotics. You’ll need to get a new prescription from your VA provider each time you need more of these medicines. </p> <p> <strong>Note: </strong> If you receive care at both Mann-Grandstaff VA medical center and another VA facility, you may need to use both web portals to refill and track VA prescriptions. </p> </div> </div> </div> </div> <div itemScope itemType="http://schema.org/Question"> <h2 itemProp="name" id="where-will-va-send-my-prescrip"> Where will VA send my prescriptions? </h2> <div itemProp="acceptedAnswer" itemScope itemType="http://schema.org/Answer" > <div itemProp="text"> <div className="processed-content"> <p> Our mail order pharmacy will send your prescriptions to the address we have on file for you. We ship to all addresses in the United States and its territories. We don’t ship prescriptions to foreign countries. </p> <p> <strong>Important note:</strong> Changing your address within My HealtheVet or My VA Health doesn’t change your address for prescription shipments. </p> <p> <strong> To change your address on file with VA for prescription shipments: </strong> </p> <ul> <li> Go to your <a href="/profile/">VA.gov profile</a>.<br /> Click <strong>Edit</strong> next to each address you’d like to change, including your mailing and home address. Or if you haven’t yet added an address, click on the link to add your address. Then fill out the form and click{' '} <strong>Update</strong> to save your changes. You can also add or edit other contact, personal, and military service information. </li> <li> Or contact the VA health facility where you get care to have them update your address on file. <br /> <a href="/find-locations/">Find your VA health facility</a> </li> </ul> </div> </div> </div> </div> <div itemScope itemType="http://schema.org/Question"> <h2 itemProp="name" id="how-long-will-my-prescriptions"> When will I get my prescriptions, and when should I reorder? </h2> <div itemProp="acceptedAnswer" itemScope itemType="http://schema.org/Answer" > <div itemProp="text"> <div className="processed-content"> <p> Prescriptions usually arrive within 3 to 5 days. You can find specific information about your order on the website of the delivery service shown in My HealtheVet or My VA Health. </p> <p> To make sure you have your medicine in time, please request your refill at least 10 days before you need more medicine. </p> </div> </div> </div> </div> <div itemScope itemType="http://schema.org/Question"> <h2 itemProp="name" id="will-my-personal-health-inform"> Will my personal health information be protected? </h2> <div itemProp="acceptedAnswer" itemScope itemType="http://schema.org/Answer" > <div itemProp="text"> <div className="processed-content"> <p> Yes. Our health management portals are secure websites. We follow strict security policies and practices to protect your personal health information. </p> <p> If you print or download anything from the website (like prescription details), you’ll need to take responsibility for protecting that information. <br /> <a href="https://www.myhealth.va.gov/mhv-portal-web/web/myhealthevet/protecting-your-personal-health-information" target="_blank" rel="noopener noreferrer" > Get tips for protecting your personal health information </a> </p> </div> </div> </div> </div> <div itemScope itemType="http://schema.org/Question"> <h2 itemProp="name" id="what-if-i-have-more-questions"> What if I have more questions? </h2> <div itemProp="acceptedAnswer" itemScope itemType="http://schema.org/Answer" > <div itemProp="text"> <div className="processed-content"> <h3>For My HealtheVet questions</h3> <p>You can:</p> <ul> <li> Read the{' '} <a rel="noreferrer noopener" href="https://www.myhealth.va.gov/mhv-portal-web/web/myhealthevet/faqs#PrescriptionRefill" > prescription refill FAQs </a>{' '} on the My HealtheVet web portal </li> <li> Call the My HealtheVet help desk at{' '} <a href="tel:18773270022" aria-label="8 7 7. 3 2 7. 0 0 2 2."> 877-327-0022 </a>{' '} (TTY: <Telephone contact={CONTACTS.HELP_TTY} /> ). We’re here Monday through Friday, 8:00 a.m. to 8:00 p.m. ET. </li> <li> Or{' '} <a rel="noreferrer noopener" href="https://www.myhealth.va.gov/mhv-portal-web/web/myhealthevet/contact-mhv" > contact us online </a> </li> </ul> <h3>For My VA Health questions</h3> <p> Call My VA Health support anytime at{' '} <a href="tel:18009621024" aria-label="8 0 0. 9 6 2. 1 0 2 4."> {' '} 800-962-1024 </a> . </p> </div> </div> </div> </div> </div> </> ); AuthContent.propTypes = { authenticatedWithSSOe: PropTypes.bool.isRequired, cernerfacilities: PropTypes.arrayOf( PropTypes.shape({ facilityId: PropTypes.string.isRequired, isCerner: PropTypes.bool.isRequired, usesCernerAppointments: PropTypes.string, usesCernerMedicalRecords: PropTypes.string, usesCernerMessaging: PropTypes.string, usesCernerRx: PropTypes.string, usesCernerTestResults: PropTypes.string, }).isRequired, ), otherfacilities: PropTypes.arrayOf( PropTypes.shape({ facilityId: PropTypes.string.isRequired, isCerner: PropTypes.bool.isRequired, usesCernerAppointments: PropTypes.string, usesCernerMedicalRecords: PropTypes.string, usesCernerMessaging: PropTypes.string, usesCernerRx: PropTypes.string, usesCernerTestResults: PropTypes.string, }).isRequired, ), }; export default AuthContent;
app/containers/NotFoundPage/index.js
nikb747/threejs-react-proto
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
spec/javascripts/jsx/files/components/FilePreviewSpec.js
djbender/canvas-lms
/* * Copyright (C) 2016 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import ReactDOM from 'react-dom' import {mount} from 'enzyme' import FilePreview from 'jsx/files/FilePreview' import Folder from 'compiled/models/Folder' import File from 'compiled/models/File' import FilesCollection from 'compiled/collections/FilesCollection' let filesCollection = {} const folderCollection = {} let file1 = {} let file2 = {} let file3 = {} let currentFolder = {} QUnit.module('File Preview Rendering', { setup() { // Initialize a few things to view in the preview. filesCollection = new FilesCollection() file1 = new File( { id: '1', cid: 'c1', name: 'Test File.file1', 'content-type': 'unknown/unknown', size: 1000000, created_at: new Date().toISOString(), updated_at: new Date().toISOString() }, {preflightUrl: ''} ) file2 = new File( { id: '2', cid: 'c2', name: 'Test File.file2', 'content-type': 'unknown/unknown', size: 1000000, created_at: new Date().toISOString(), updated_at: new Date().toISOString() }, {preflightUrl: ''} ) file3 = new File( { id: '3', cid: 'c3', name: 'Test File.file3', 'content-type': 'unknown/unknown', size: 1000000, created_at: new Date().toISOString(), updated_at: new Date().toISOString(), url: 'test/test/test.png' }, {preflightUrl: ''} ) filesCollection.add(file1) filesCollection.add(file2) filesCollection.add(file3) currentFolder = new Folder() currentFolder.files = filesCollection }, teardown() { const filesCollection = {} const folderCollection = {} const file1 = {} const file2 = {} const file3 = {} const currentFolder = {} } }) test('clicking the info button should render out the info panel', () => { const component = mount( <FilePreview isOpen query={{ preview: '1' }} currentFolder={currentFolder} /> ) $('.ef-file-preview-header-info').click() equal( $('tr:contains("Name")') .find('td') .text(), 'Test File.file1' ) // click it again to hide it $('.ef-file-preview-header-info').click() equal($('tr:contains("Name")').length, 0) component.unmount() }) test('opening the preview for one file should show navigation buttons for the previous and next files in the current folder', () => { const component = mount( <FilePreview isOpen query={{ preview: '2' }} currentFolder={currentFolder} /> ) const arrows = $('.ef-file-preview-container-arrow-link') equal(arrows.length, 2, 'there are two arrows shown') ok( arrows[0].href.match('preview=1'), 'The left arrow link has an incorrect href (`preview` query string does not exist or points to the wrong id)' ) ok( arrows[1].href.match('preview=3'), 'The right arrow link has an incorrect href (`preview` query string does not exist or points to the wrong id)' ) component.unmount() }) test('download button should be rendered on the file preview', () => { const component = mount( <FilePreview isOpen query={{ preview: '3' }} currentFolder={currentFolder} /> ) const downloadBtn = $('.ef-file-preview-header-download')[0] ok(downloadBtn, 'download button renders') ok(downloadBtn.href.includes(file3.get('url')), 'the download button url is correct') component.unmount() }) test('clicking the close button calls closePreview with the correct url', () => { let closePreviewCalled = false const component = mount( <FilePreview isOpen query={{ preview: '3', search_term: 'web', sort: 'size', order: 'desc' }} collection={filesCollection} closePreview={url => { closePreviewCalled = true ok(url.includes('sort=size')) ok(url.includes('order=desc')) ok(url.includes('search_term=web')) }} /> ) const closeButton = $('.ef-file-preview-header-close')[0] ok(closeButton) closeButton.click() ok(closePreviewCalled) component.unmount() })
DemoApp/lib/profile-header/index.js
andyfen/react-native-UIKit
import React from 'react'; import { StyleSheet, Image, View, Dimensions, } from 'react-native'; const { width } = Dimensions.get('window'); const styles = StyleSheet.create({ container: { paddingBottom: 30, }, backgroundImg: { resizeMode: 'cover', height: 150, }, profileImg: { borderWidth: 2, borderColor: '#fff', borderRadius: 4, width: 100, height: 100, position: 'absolute', alignSelf: 'center', top: 75, left: (width / 2) - 50, }, shadow: { position: 'absolute', alignSelf: 'center', top: 75, left: (width / 2) - 50, borderRadius: 4, width: 100, height: 100, shadowColor: '#D8D8D8', shadowRadius: 2, shadowOffset: { width: 0, height: 1, }, shadowOpacity: 0.8, }, title: { flex: 1, textAlign: 'center', fontSize: 30, marginTop: 35, marginBottom: 10, fontWeight: '300', }, summary: { paddingHorizontal: 10, }, }); const ProfileHeader = ({ profileImg, backgroundImg, circle, blurRadius }) => ( <View style={styles.container}> <Image blurRadius={blurRadius} source={{ uri: backgroundImg }} style={styles.backgroundImg} /> <View style={[styles.shadow, { borderRadius: circle ? 50 : 0 }]} /> <Image source={{ uri: profileImg }} style={[styles.profileImg, { borderRadius: circle ? 50 : 0 }]} /> </View> ); ProfileHeader.defaultProps = { circle: false, blurRadius: 0, }; ProfileHeader.propTypes = { title: React.PropTypes.string, summary: React.PropTypes.string, profileImg: React.PropTypes.string, backgroundImg: React.PropTypes.string, circle: React.PropTypes.bool, blurRadius: React.PropTypes.number, }; export default ProfileHeader;
lib/views/LayoutSectionView.js
tuomashatakka/reduced-dark-ui
'use babel' import React from 'react' import Field from '../components/layout/Field' const LayoutSection = (props) => { return ( <section className='section'> <Field scope='layout.uiScale' style='primary' /> <Field scope='layout.spacing' style='primary' /> <Field scope='layout.fixedTabBar' style='minor' /> <Field scope='layout.fixedProjectRoot' style='minor' /> <Field scope='layout.collapsing' style='major' /> <Field scope='layout.tabPosition' style='minor' /> <Field scope='layout.tabClosePosition' style='minor' /> <Field scope='layout.SILLYMODE' style='minor' /> <Field scope='decor.animations.duration' style='minor' /> </section> ) } export default LayoutSection
src/Root.js
streamr-app/streamr-web
import React from 'react' import { Provider } from 'react-redux' import configureStore from './configureStore' import { ConnectedRouter } from 'react-router-redux' import { Route } from 'react-router-dom' import Application, { history } from './components/Application' const store = configureStore(history) ;(function () { const { change } = require('redux-form') window.changeForm = (...args) => store.dispatch(change(...args)) })() export default () => ( <Provider store={store}> <ConnectedRouter history={history}> <Route path='/' component={Application} /> </ConnectedRouter> </Provider> )
conference-management-system-front-end/src/components/paperManage.js
Kokosowys/conference-management-system
import React from 'react'; class PaperManage extends React.Component { render() { //var item = this.props.item; return ( <div className="userDiv"> <div> <p>this is your paper</p> </div> <br/><br/> </div> ) } }; export default PaperManage;
blueprints/dumb/files/__root__/components/__name__/__name__.js
blinkmobile/things-mgr
import React from 'react' type Props = { }; export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } export default <%= pascalEntityName %>
examples/reactstrap/programmatic-submission.js
mkatanski/strap-forms
import React from 'react' import { Label } from 'reactstrap' import Form from './components/Form' import Input from './components/Input' import Group from './components/Group' class MyForm extends React.Component { handleSubmit = () => { // eslint-disable-next-line console.log('Programmatic submission') } render() { return ( <div> <p>Form to submit</p> <Form onSubmit={this.handleSubmit} ref={(ref) => { this.form = ref }}> <Group> <Label htmlFor="name"> Your name <sup>&lowast;</sup> </Label> <Input name="name" required /> </Group> </Form> <div> <p>External button</p> <button onClick={() => this.form.submit()}>Programmatic submission</button> </div> </div> ) } } export default MyForm
blueocean-material-icons/src/js/components/svg-icons/action/speaker-notes.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionSpeakerNotes = (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-2zM8 14H6v-2h2v2zm0-3H6V9h2v2zm0-3H6V6h2v2zm7 6h-5v-2h5v2zm3-3h-8V9h8v2zm0-3h-8V6h8v2z"/> </SvgIcon> ); ActionSpeakerNotes.displayName = 'ActionSpeakerNotes'; ActionSpeakerNotes.muiName = 'SvgIcon'; export default ActionSpeakerNotes;
examples/basic-jsx/src/index.js
4Catalyzer/found
import Link from 'found/Link'; import Redirect from 'found/Redirect'; import Route from 'found/Route'; import createBrowserRouter from 'found/createBrowserRouter'; import makeRouteConfig from 'found/makeRouteConfig'; import PropTypes from 'prop-types'; import React from 'react'; import ReactDOM from 'react-dom'; function LinkItem(props) { return ( <li> <Link {...props} activeStyle={{ fontWeight: 'bold' }} /> </li> ); } const propTypes = { children: PropTypes.node, }; function App({ children }) { return ( <div> <ul> <LinkItem to="/">Main</LinkItem> <ul> <LinkItem to="/foo">Foo</LinkItem> <LinkItem to="/bar">Bar (async)</LinkItem> <LinkItem to="/baz">Baz (redirects to Foo)</LinkItem> <LinkItem to="/qux">Qux (missing)</LinkItem> </ul> </ul> {children} </div> ); } App.propTypes = propTypes; const BrowserRouter = createBrowserRouter({ routeConfig: makeRouteConfig( <Route path="/" Component={App}> <Route Component={() => <div>Main</div>} /> <Route path="foo" Component={() => <div>Foo</div>} /> <Route path="bar" getComponent={() => import('./Bar').then((m) => m.default)} getData={() => new Promise((resolve) => { setTimeout(resolve, 1000, 'Bar'); }) } render={({ Component, props }) => Component && props ? ( <Component {...props} /> ) : ( <div> <small>Loading&hellip;</small> </div> ) } /> <Redirect from="baz" to="/foo" /> </Route>, ), /* eslint-disable react/prop-types */ renderError: ({ error }) => ( <div>{error.status === 404 ? 'Not found' : 'Error'}</div> ), /* eslint-enable react/prop-types */ }); ReactDOM.render(<BrowserRouter />, document.getElementById('root'));
client/extensions/woocommerce/woocommerce-services/views/live-rates-carriers-list/carriers-list.js
Automattic/woocommerce-services
/** * External dependencies */ import React from 'react' import { localize } from 'i18n-calypso' import { Tooltip } from '@wordpress/components' /** * Internal dependencies */ import Card from 'components/card' import CarrierIcon from '../../components/carrier-icon' import Gridicon from 'gridicons' const Actions = localize( ( { translate } ) => { return ( <> { /* eslint-disable-next-line wpcalypso/jsx-classname-namespace */} <a className="button is-compact" href="admin.php?page=wc-settings&tab=shipping&section">{ translate( 'Add to shipping zones' ) }</a> <Tooltip position="top left" text={ translate( 'To be displayed at checkout, this carrier must be added as a shipping method to selected shipping zones' ) } > <div> <Gridicon icon="help-outline" size={ 18 }/> </div> </Tooltip> </> ) }) const CarrierDiscount = localize( ( { translate, name, } ) => translate( 'Discounted %(carrierName)s shipping labels', { args: { carrierName: name, }, })) const carrierItemMap = { 'wc_services_usps': ( { translate } ) => ( <div className="live-rates-carriers-list__element element-usps"> <div className="live-rates-carriers-list__icon"> <CarrierIcon carrier="usps" size={ 18 } /> </div> <div className="live-rates-carriers-list__carrier">{ translate( 'USPS' ) }</div> <div className="live-rates-carriers-list__features"> <ul> <li>{ translate( 'Ship with the largest delivery network in the United States' ) }</li> <li> <CarrierDiscount name={ translate( 'USPS' ) } /> </li> <li> { translate( 'Live rates for %(carrierName)s at checkout', { args: { carrierName: translate( 'USPS' ), }, })} </li> </ul> </div> <div className="live-rates-carriers-list__actions"><Actions /></div> </div> ), 'wc_services_dhlexpress': ({ translate }) => ( <div className="live-rates-carriers-list__element element-dhlexpress"> <div className="live-rates-carriers-list__icon"> <CarrierIcon carrier="dhlexpress" size={ 18 } /> </div> <div className="live-rates-carriers-list__carrier">{ translate( 'DHL Express' ) }</div> <div className="live-rates-carriers-list__features"> <ul> <li>{ translate( 'Express delivery from the experts in international shipping' ) }</li> <li><CarrierDiscount name={ translate( 'DHL Express' ) } /></li> <li> { translate( 'Live rates for %(carrierName)s at checkout', { args: { carrierName: translate( 'DHL Express' ), }, })} </li> </ul> </div> <div className="live-rates-carriers-list__actions"><Actions /></div> </div> ), } const CarriersList = ({ translate, carrierIds }) => { return ( <Card className="live-rates-carriers-list__wrapper"> <div className="live-rates-carriers-list__heading"> <div className="live-rates-carriers-list__icon"/> <div className="live-rates-carriers-list__carrier">{ translate( 'Carrier' ) }</div> <div className="live-rates-carriers-list__features">{ translate( 'Features' ) }</div> <div className="live-rates-carriers-list__actions"/> </div> {carrierIds.map( ( carrierId ) => { const CarrierView = carrierItemMap[ carrierId ] if ( ! CarrierView ) { return null } return ( <CarrierView key={ carrierId } translate={ translate } /> ) })} </Card> ) } export default localize( CarriersList )
src/app/components/pages/BlankPage.js
ucokfm/admin-lte-react
import React from 'react'; import PageWrapper from '../../../lib/page/PageWrapper'; import PageHeader from '../../../lib/page/PageHeader'; import Breadcrumb from '../../../lib/page/Breadcrumb'; import PageContent from '../../../lib/page/PageContent'; export default function BlankPage() { return ( <PageWrapper> <PageHeader title="Blank page" description="it all starts here" > <Breadcrumb items={[ { key: 1, icon: 'fa fa-dashboard', title: 'Home', url: '/' }, { key: 2, title: 'Examples' }, { key: 3, title: 'Blank page' }, ]} /> </PageHeader> <PageContent> <div className="box"> <div className="box-header with-border"> <h3 className="box-title">Title</h3> <div className="box-tools pull-right"> <button type="button" className="btn btn-box-tool"> <i className="fa fa-minus"></i> </button> <button type="button" className="btn btn-box-tool"> <i className="fa fa-times"></i> </button> </div> </div> <div className="box-body"> Start creating your amazing application! </div> <div className="box-footer"> Footer </div> </div> </PageContent> </PageWrapper> ); }
src/components/video_detail.js
polettoweb/ReactReduxStarter
import React from 'react'; const VideoDetail = ({video}) => { if (!video) { return <div>Loading...</div>; } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;
src/index.js
zestxjest/learn-redux-async-action
import 'babel-polyfill'; import React from 'react'; import {render} from 'react-dom'; import Root from './containers/Root' render( <Root />, document.getElementById('root') )
actor-apps/app-web/src/app/components/sidebar/ContactsSection.react.js
damoguyan8844/actor-platform
import _ from 'lodash'; import React from 'react'; import { Styles, RaisedButton } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; import ContactStore from 'stores/ContactStore'; import ContactActionCreators from 'actions/ContactActionCreators'; import AddContactStore from 'stores/AddContactStore'; import AddContactActionCreators from 'actions/AddContactActionCreators'; import ContactsSectionItem from './ContactsSectionItem.react'; import AddContactModal from 'components/modals/AddContact.react.js'; const ThemeManager = new Styles.ThemeManager(); const getStateFromStores = () => { return { isAddContactModalOpen: AddContactStore.isModalOpen(), contacts: ContactStore.getContacts() }; }; class ContactsSection extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } componentWillUnmount() { ContactActionCreators.hideContactList(); ContactStore.removeChangeListener(this.onChange); AddContactStore.removeChangeListener(this.onChange); } constructor(props) { super(props); this.state = getStateFromStores(); ContactActionCreators.showContactList(); ContactStore.addChangeListener(this.onChange); AddContactStore.addChangeListener(this.onChange); ThemeManager.setTheme(ActorTheme); } onChange = () => { this.setState(getStateFromStores()); }; openAddContactModal = () => { AddContactActionCreators.openModal(); }; render() { let contacts = this.state.contacts; let contactList = _.map(contacts, (contact, i) => { return ( <ContactsSectionItem contact={contact} key={i}/> ); }); let addContactModal; if (this.state.isAddContactModalOpen) { addContactModal = <AddContactModal/>; } return ( <section className="sidebar__contacts"> <ul className="sidebar__list sidebar__list--contacts"> {contactList} </ul> <footer> <RaisedButton label="Add contact" onClick={this.openAddContactModal} style={{width: '100%'}}/> {addContactModal} </footer> </section> ); } } export default ContactsSection;
node_modules/react-bootstrap/es/MediaListItem.js
lucketta/got-quote-generator
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var MediaListItem = function (_React$Component) { _inherits(MediaListItem, _React$Component); function MediaListItem() { _classCallCheck(this, MediaListItem); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MediaListItem.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('li', _extends({}, elementProps, { className: classNames(className, classes) })); }; return MediaListItem; }(React.Component); export default bsClass('media', MediaListItem);
docs/app/Examples/modules/Progress/Variations/index.js
Rohanhacker/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const ProgressVariationsExamples = () => ( <ExampleSection title='Variations'> <ComponentExample title='Inverted' description='A progress bar can have its colors inverted.' examplePath='modules/Progress/Variations/ProgressExampleInverted' /> <ComponentExample title='Attached' description='A progress bar can show progress of an element.' examplePath='modules/Progress/Variations/ProgressExampleAttached' /> <ComponentExample title='Size' description='A progress bar can vary in size.' examplePath='modules/Progress/Variations/ProgressExampleSize' /> <ComponentExample title='Color' description='A progress bar can have different colors.' examplePath='modules/Progress/Variations/ProgressExampleColor' /> <ComponentExample title='Inverted Color' description='These colors can also be inverted for improved contrast on dark backgrounds.' examplePath='modules/Progress/Variations/ProgressExampleInvertedColor' /> </ExampleSection> ) export default ProgressVariationsExamples
app/javascript/mastodon/components/column_back_button.js
mecab/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; class ColumnBackButton extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; handleClick = () => { if (window.history && window.history.length === 1) this.context.router.push("/"); else this.context.router.goBack(); } render () { return ( <div role='button' tabIndex='0' onClick={this.handleClick} className='column-back-button'> <i className='fa fa-fw fa-chevron-left column-back-button__icon'/> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </div> ); } } export default ColumnBackButton;
src/app/components/media/OcrButton.js
meedan/check-web
import React from 'react'; import PropTypes from 'prop-types'; import Relay from 'react-relay/classic'; import { graphql, commitMutation } from 'react-relay/compat'; import { FormattedMessage } from 'react-intl'; import MenuItem from '@material-ui/core/MenuItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import DescriptionOutlinedIcon from '@material-ui/icons/DescriptionOutlined'; import { withSetFlashMessage } from '../FlashMessage'; const OcrButton = ({ projectMediaId, projectMediaType, hasExtractedText, setFlashMessage, onClick, }) => { const [pending, setPending] = React.useState(false); const handleError = () => { setPending(false); setFlashMessage(( <FormattedMessage id="ocrButton.defaultErrorMessage" defaultMessage="Could not extract text from image" description="Warning displayed if an error occurred when extracting text from image" /> ), 'error'); }; const handleSuccess = () => { setPending(false); setFlashMessage(( <FormattedMessage id="ocrButton.textExtractedSuccessfully" defaultMessage="Text extraction completed" description="Banner displayed when text extraction operation for an image is done" /> ), 'success'); }; const handleClick = () => { setPending(true); commitMutation(Relay.Store, { mutation: graphql` mutation OcrButtonExtractTextMutation($input: ExtractTextInput!) { extractText(input: $input) { project_media { id extracted_text: annotation(annotation_type: "extracted_text") { data } } } } `, variables: { input: { id: projectMediaId, }, }, onCompleted: (response, error) => { if (error) { handleError(); } else { handleSuccess(); } }, onError: () => { handleError(); }, }); onClick(); }; if (projectMediaType !== 'UploadedImage' || hasExtractedText) { return null; } return ( <MenuItem id="ocr-button__extract-text" onClick={handleClick} disabled={pending} > <ListItemIcon> <DescriptionOutlinedIcon /> </ListItemIcon> { pending ? <FormattedMessage id="ocrButton.inProgress" defaultMessage="Text extraction in progress…" description="Message displayed while text is being extracted from an image" /> : <FormattedMessage id="ocrButton.label" defaultMessage="Image text extraction" description="Button label - when this button is clicked, text is extracted from image" /> } </MenuItem> ); }; OcrButton.defaultProps = { hasExtractedText: false, }; OcrButton.propTypes = { projectMediaId: PropTypes.string.isRequired, projectMediaType: PropTypes.string.isRequired, hasExtractedText: PropTypes.bool, onClick: PropTypes.func.isRequired, setFlashMessage: PropTypes.func.isRequired, }; export default withSetFlashMessage(OcrButton);
src/svg-icons/image/brightness-7.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrightness7 = (props) => ( <SvgIcon {...props}> <path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6zm0-10c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"/> </SvgIcon> ); ImageBrightness7 = pure(ImageBrightness7); ImageBrightness7.displayName = 'ImageBrightness7'; export default ImageBrightness7;
examples/custom-server-micro/pages/index.js
nelak/next.js
import React from 'react' import Link from 'next/link' export default () => ( <ul> <li><Link href='/b' as='/a'><a>a</a></Link></li> <li><Link href='/a' as='/b'><a>b</a></Link></li> </ul> )
src/mention/__tests__/fixtures/initializeEditor.js
catalinmiron/react-tinymce-mention
import 'babel/polyfill'; import React from 'react'; import TinyMCE from 'react-tinymce'; import Mention from '../../Mention'; import simpleDataSource from './simple'; const plugins = [ 'autolink', 'autoresize', 'code', 'image', 'link', 'media', 'mention', 'tabfocus' ]; export default function initializeEditor() { var domNode = createContainer(); React.render( <div> <TinyMCE content={''} config={{ extended_valid_elements: 'blockquote[dir|style|cite|class|dir<ltr?rtl],iframe[src|frameborder|style|scrolling|class|width|height|name|align],pre', menubar: false, plugins: plugins.join(','), skin: 'kindling', statusbar: false, theme: 'kindling', toolbar: 'bold italic underline strikethrough | bullist numlist blockquote | link unlink | image media | removeformat code' }} /> <Mention dataSource={simpleDataSource} delimiter={'@'} /> </div> , domNode); return window.tinymce; } function createContainer() { const root = document.createElement('div'); const id = 'root'; root.setAttribute('id', id); document.body.appendChild(root); return document.getElementById(id); }
src/components/soporte/chat_servidor.js
bombe-software/demos
//NPM packages import React, { Component } from 'react'; import { connect } from "react-redux"; //Actions import { fetchConversaciones } from "../../actions"; //Components import Chat from "./chat"; /** * @class ChatServidor * @author Vicroni <[email protected]> * @author Someone <none> * @version 1.0 <1/12/17> * @description: * El objetivo de la clase es contolar el * aspecto grafico del chat servidor */ class ChatServidor extends Component { /** * Inicializa el state en donde se colocan * el @const id_externo en donde se pone la * que esta teniendo lugar * @constructor */ constructor(props) { super(props); this.state = { id_externo: 0 }; } /** * Carga de manera logica las conversaciones y * renderiza el conmportamiento grafico * @method componentDidMount * @function props.fetchConversaciones Llamada ajax para obtener las conversaciones */ componentDidMount() { this.props.fetchConversaciones(this.props.id_local) } /** * Enlista las conversaciones de manera grafica * @method listConversaciones * @param conversaciones Un array con todas las conversaciones */ listConversaciones(conversaciones) { return _.map(conversaciones, conversacion => { return ( <div key={conversacion.id_remitente} onClick={() => { this.updateIdExterno(conversacion.id_remitente) }}> <div className="panel-block"> {conversacion.nombre_usuario} </div> </div> ); }); } updateIdExterno(id) { this.setState({ id_externo: id }); } /** * Es una forma de capturar cualquier error en la clase * y que este no crashe el programa, ayuda con la depuracion * de errores * @method componentDidCatch * @const info Es más informacion acerca del error * @const error Es el titulo del error */ componentDidCatch(error, info) { console.log("Error: " + error); console.log("Info: " + info); } render() { return ( <div className="hero"> <div className="columns"> <div className="column is-2-desktop is-4-tablet is-offset-2-desktop is-offset-1-tablet is-10-mobile is-offset-1-mobile"> <div className="panel user-list"> <div className="panel-heading">Usuarios</div> {this.listConversaciones(this.props.conversaciones)} </div> </div> <div className="column is-6-desktop is-6-tablet is-10-mobile is-offset-1-mobile"> <Chat id_local={this.props.id_local} id_externo={this.state.id_externo} /> </div> </div> </div> ); } } function mapStateToProps(state) { return { conversaciones: state.mensajes.conversaciones }; } export default connect(mapStateToProps, { fetchConversaciones })(ChatServidor);
message/src/MessageBox.js
zhufengnodejs/201701node
import React, { Component } from 'react'; import 'bootstrap/dist/css/bootstrap.css' class MessageBox extends Component { render() { return ( <div className="panel panel-default"> <div className="panel-heading"> <h3 className="text-center">珠峰留言板</h3> </div> <div className="panel-body"> <ul className="list-group"> <li className="list-group-item"> 张三:今天下雨 <span className="pull-right">2017年5月23日10:07:59</span> </li> </ul> </div> <div className="panel-footer"> <form> <div className="form-group"> <label htmlFor="name">姓名</label> <input type="text" className="form-control" id="name" placeholder="姓名"/> </div> <div className="form-group"> <label htmlFor="content">内容</label> <textarea className="form-control" id="content" cols="30" rows="10"></textarea> </div> <div className="container"> <button type="submit" className="btn btn-primary">提交</button> </div> </form> </div> </div> ); } } export default MessageBox;
src/scripts/views/DataView.js
recordbleach/recordBleach_front_end
import React from 'react' import Header from './header' import Footer from './footer' import ACTIONS from '../actions' import $ from 'jquery' const DataInputView = React.createClass({ render: function() { return( <div className = 'dataInputView'> <Header/> <Petition /> <Footer /> </div> ) } }) const Petition = React.createClass({ getInitialState: function(){ return { setProfileClass: "untoggled", profileButtonSymbol: "+", setArrestClass: "untoggled", arrestButtonSymbol: "+", setChargeClass: "untoggled", chargeButtonSymbol: "+", setOverturnClass: "untoggled", overturnButtonSymbol: "+", setAgencyClass: "untoggled", agencyButtonSymbol: "+" } }, _toggleProfileButton: function(){ this.setState({ setProfileClass:this.state.profileButtonSymbol === '+' ? 'toggled' : 'untoggled', profileButtonSymbol: this.state.profileButtonSymbol === '+' ? '-' : '+' }) }, _toggleArrestButton: function(){ this.setState({ setArrestClass:this.state.arrestButtonSymbol === '+' ? 'toggled' : 'untoggled', arrestButtonSymbol: this.state.arrestButtonSymbol === '+' ? '-' : '+' }) }, _toggleChargeButton: function(){ this.setState({ setChargeClass:this.state.chargeButtonSymbol === '+' ? 'toggled' : 'untoggled', chargeButtonSymbol: this.state.chargeButtonSymbol === '+' ? '-' : '+' }) }, _toggleOverturnButton: function(){ this.setState({ setOverturnClass:this.state.overturnButtonSymbol === '+' ? 'toggled' : 'untoggled', overturnButtonSymbol: this.state.overturnButtonSymbol === '+' ? '-' : '+' }) }, _toggleAgencyButton: function(){ this.setState({ setAgencyClass:this.state.agencyButtonSymbol === '+' ? 'toggled' : 'untoggled', agencyButtonSymbol: this.state.agencyButtonSymbol === '+' ? '-' : '+' }) }, _handleRadioInput: function(inputArray) { for(var i = 0; i < inputArray.length; i++) { var genderObj = inputArray[i] if(genderObj.checked) { return genderObj.value } } }, _formatDate: function(dateString) { var splitDateArray = dateString.split('-') var formattedDateString = splitDateArray.join('') var formattedDateNumber = parseInt(formattedDateString) return formattedDateNumber }, _courtBool: function(courtInputArray) { var courtObj = { county: false, municipal: false, district: false } for(var i = 0; i < courtInputArray.length; i++) { var courtInputObj = courtInputArray[i] if(courtInputObj.checked) { var courtTrueValue = courtInputObj.value } } for(var prop in courtObj) { if(prop === courtTrueValue) { courtObj[prop] = true } } return courtObj }, _handleSaveAndLogout: function(evt) { evt.preventDefault() this._handlePetitionSubmit(evt) ACTIONS._logoutUser() }, _handleSubmitAndDestroy: function(evt) { console.log(evt) evt.preventDefault() // this._handlePetitionSubmit(evt) ACTIONS._destroyUser() }, _handlePetitionSubmit: function(evt) { evt.preventDefault() ACTIONS._submitPetition({ legal_name: document.getElementsByClassName('legalName')[0].value, dob: this._formatDate(document.getElementsByClassName('dob')[0].value), ssn: document.getElementsByClassName('ssn')[0].value, dl: document.getElementsByClassName('dl')[0].value, address: document.getElementsByClassName('currentAddress')[0].value, city: document.getElementsByClassName('currentCity')[0].value, state: document.getElementsByClassName('currentState')[0].value, county: document.getElementsByClassName('currentCounty')[0].value, zip: document.getElementsByClassName('currentZip')[0].value, sex: this._handleRadioInput(document.getElementsByClassName('gender')), race: this._handleRadioInput(document.getElementsByClassName('race')), offense_date:this._formatDate(document.getElementsByClassName('offenseDate')[0].value), offense_county: document.getElementsByClassName('arrestCounty')[0].value, arresting_agency: document.getElementsByClassName('arrestingAgency')[0].value, arrest_date: this._formatDate(document.getElementsByClassName('arrestDate')[0].value), a_address: document.getElementsByClassName('TOAAddress')[0].value, a_city: document.getElementsByClassName('TOACity')[0].value, a_state: document.getElementsByClassName('TOAState')[0].value, a_county: document.getElementsByClassName('TOACounty')[0].value, charged: this._handleRadioInput(document.getElementsByClassName('charged')), charge_date:this._formatDate(document.getElementsByClassName('chargeDate')[0].value), charged_offenses: document.getElementsByClassName('offenses')[0].value, charge_cause_number: document.getElementsByClassName('cause')[0].value, court_name: document.getElementsByClassName('courtName')[0].value, court_city: document.getElementsByClassName('courtCity')[0].value, court_county: document.getElementsByClassName('courtCounty')[0].value, county_court_at_law: this._courtBool(document.getElementsByClassName('court')).county, municipal_court: this._courtBool(document.getElementsByClassName('court')).municipal, district_court: this._courtBool(document.getElementsByClassName('court')).district, acquittal: this._handleRadioInput(document.getElementsByClassName('acquittal')), acquittal_date:this._formatDate(document.getElementsByClassName('acquittalDate')[0].value), dismissal: this._handleRadioInput(document.getElementsByClassName('dismiss')), dismissal_date:this._formatDate(document.getElementsByClassName('dismissDate')[0].value), convicted: this._handleRadioInput(document.getElementsByClassName('convicted')), conviction_date:this._formatDate(document.getElementsByClassName('convictionDate')[0].value), pardon:this._handleRadioInput(document.getElementsByClassName('pardon')), pardon_date:this._formatDate(document.getElementsByClassName('pardonDate')[0].value), overturned:this._handleRadioInput(document.getElementsByClassName('overturn')), overturned_date:this._formatDate(document.getElementsByClassName('overturnDate')[0].value), probation:this._handleRadioInput(document.getElementsByClassName('overturn')), deferred_adjudication:this._handleRadioInput(document.getElementsByClassName('adjudication')), user_id: parseInt(localStorage.currentUser) }) }, render: function() { var toggleProfileClass = { className: this.state.setProfileClass } var toggleArrestClass = { className: this.state.setArrestClass } var toggleChargeClass = { className: this.state.setChargeClass } var toggleOverturnClass = { className: this.state.setOverturnClass } var toggleAgencyClass = { className: this.state.setAgencyClass } return( <div className = 'petition'> <form> {/* PERSONAL PROFILE*/} <h3 onClick={this._toggleProfileButton}>{this.state.profileButtonSymbol} Personal Profile</h3> <div id = 'profile' className={toggleProfileClass.className}> <p>Full legal name:</p><input type ='text' className = 'legalName'/> <p>Date of birth:</p><input type = 'date' className = 'dob'/> <p>Social Security Number (include dashes):</p><input type = 'password' className = 'ssn' /> <p>Driver's License (leave blank if not applicable):</p><input type = 'text' className = 'dl' /> <p>Race:</p> <input type = 'radio' className = 'race' value = 'Hispanic or Latino' />Hispanic or Latino <br /> <input type = 'radio' className = 'race' value = 'American Indian or Alaska Native' />American Indian or Alaska Native <br /> <input type = 'radio' className = 'race' value = 'Asian' />Asian <br /> <input type = 'radio' className = 'race' value = 'Black or African American' />Black or African American <br /> <input type = 'radio' className = 'race' value = 'Native Hawaiian or Other Pacific Islander' />Native Hawaiian or Other Pacific Islander <br /> <input type = 'radio' className = 'race' value = 'White' />White <br /> <p>Gender:</p> <input type = 'radio' value = 'male' className = 'gender' name = 'gender'/>Male<br/> <input type = 'radio' value = 'female' className = 'gender' name = 'gender'/>Female <div className = 'address'>Current address: <input type = 'text' placeholder = 'address' className = 'currentAddress'/> <input type = 'text' placeholder = 'city' className = 'currentCity'/> <input type = 'text' placeholder = 'state' className = 'currentState'/> <input type = 'text' placeholder = 'zipcode' className = 'currentZip'/> <input type = 'text' placeholder = 'county' className = 'currentCounty'/> </div> </div> {/* ARREST PROFILE*/} <h3 onClick={this._toggleArrestButton}>{this.state.arrestButtonSymbol}Arrest</h3> <div id = 'arrest' className={toggleArrestClass.className}> <div className = 'address'>Address at time of the arrest: <input type = 'text' placeholder = 'address' className = 'TOAAddress'/> <input type = 'text' placeholder = 'city' className = 'TOACity'/> <input type = 'text' placeholder = 'state' className = 'TOAState'/> <input type = 'text' placeholder = 'zipcode' className = 'TOAZip'/> <input type = 'text' placeholder = 'county' className = 'TOACounty'/> </div> <p>Date of the offense (may be different than the date of the arrest):</p><input type = 'date' className = 'offenseDate'/> <p>Date of the arrest:</p><input type = 'date' className = 'arrestDate'/> <p>Location of the arrest: <input type = 'text' placeholder = 'city' className = 'arrestCity'/><br/> <input type = 'text' placeholder = 'county' className = 'arrestCounty'/> </p> <p>Agency that arrested you:</p><input type = 'text' className = 'arrestingAgency'/> <p>Arrest Offense (exactly as it is written on your record):</p><input type = 'text' className = 'arrestOffense' /> </div> {/* CHARGE PROFILE*/} <h3 onClick={this._toggleChargeButton}>{this.state.chargeButtonSymbol}Charge</h3> <div id = 'charge' className={toggleChargeClass.className}> <p>Charged:</p> <input type = 'radio' className = 'charged' value = 'yes'/>Yes<br/> <input type = 'radio' className = 'charged' value = 'no'/>No <p>Date of charge:</p><input type = 'date' className = 'chargeDate'/> <p>List all the offenses:</p> <textarea placeholder = 'Offenses' className = 'offenses'></textarea> <p>Court where charges were filed:</p> County: <input type = 'text' className = 'courtCounty'/> City: <input type = 'text' className = 'courtCity'/> Name: <input type = 'text' className = 'courtName'/> <p>Court Type:</p> <input type = 'radio' className = 'court' value = 'county'/>County<br/> <input type = 'radio' className = 'court' value = 'municipal'/>Municipal<br/> <input type = 'radio' className = 'court' value = 'district'/>District <p>Cause # (exactly as written on criminal history):</p><input type = 'text' className = 'cause' /> </div> {/* OVERTURN PROFILE*/} <h3 onClick={this._toggleOverturnButton}>{this.state.overturnButtonSymbol}Disposition</h3> <div id = 'overturn' className={toggleOverturnClass.className}> <p>Convicted:</p> <input type = 'radio' className = 'convicted' value = 'yes' name = 'convicted'/>Yes<br/> <input type = 'radio' className = 'convicted' value = 'no' name = 'convicted'/>No<br/> <input type = 'date' className = 'convictionDate' /> <p>Dismissed:</p> <input type = 'radio' className = 'dismiss' value = 'yes' name = 'dismiss'/>Yes<br/> <input type = 'radio' className = 'dismiss' value = 'no' name = 'dismiss'/>No<br/> <input type = 'date' className = 'dismissDate' /> <p>Pardoned:</p> <input type = 'radio' className = 'pardon' value = 'yes' name = 'pardon'/>Yes<br/> <input type = 'radio' className = 'pardon' value = 'no' name = 'pardon'/>No<br/> <input type = 'date' className = 'pardonDate' /> <p>Overturned:</p> <input type = 'radio' className = 'overturn' value = 'yes' name = 'overturn'/>Yes<br/> <input type = 'radio' className = 'overturn' value = 'no' name = 'overturn'/>No<br/> <input type = 'date' className = 'overturnDate' /> <p>Acquitted:</p> <input type = 'radio' className = 'acquittal' value = 'yes' name = 'acquittal'/>Yes<br/> <input type = 'radio' className = 'acquittal' value = 'no' name = 'acquittal'/>No<br/> <input type = 'date' className = 'acquittalDate' /> <p>Assigned Probation:</p> <input type = 'radio' className = 'probation' value = 'yes' name = 'probation'/>Yes<br/> <input type = 'radio' className = 'probation' value = 'no' name = 'probation'/>No <p>Assigned Deferred Adjudication:</p> <input type = 'radio' className = 'adjudication' value = 'yes' name = 'adjudication' />Yes<br/> <input type = 'radio' className = 'adjudication' value = 'no' name = 'adjudication'/>No </div> {/* AGENCY PROFILE*/} <h3 onClick={this._toggleAgencyButton}>{this.state.agencyButtonSymbol}Agency</h3> <div id = 'agency' className={toggleAgencyClass.className}>Address of arresting agency: <input type = 'text' placeholder = 'address' className = 'agency'/> <input type = 'text' placeholder = 'city' className = 'agency'/> <input type = 'text' placeholder = 'state' className = 'agency'/> <input type = 'text' placeholder = 'zipcode' className = 'agency'/> <input type = 'text' placeholder = 'county' className = 'agency'/> </div> <p>ONCE YOU HIT SUBMIT YOUR FORMS WILL BE GENERATED AND EMAILED TO THE ADDRESS YOU PROVIDED. ALL INFORMATION WILL BE REMOVED FROM THIS SITE</p> <button type= 'submit' onClick = {this._handleSubmitAndDestroy}>Submit</button> <button type= 'submit' onClick = {this._handleSaveAndLogout}>Save and Logout</button> </form> </div> ) } }) export default DataInputView
src/svg-icons/action/supervisor-account.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSupervisorAccount = (props) => ( <SvgIcon {...props}> <path d="M16.5 12c1.38 0 2.49-1.12 2.49-2.5S17.88 7 16.5 7C15.12 7 14 8.12 14 9.5s1.12 2.5 2.5 2.5zM9 11c1.66 0 2.99-1.34 2.99-3S10.66 5 9 5C7.34 5 6 6.34 6 8s1.34 3 3 3zm7.5 3c-1.83 0-5.5.92-5.5 2.75V19h11v-2.25c0-1.83-3.67-2.75-5.5-2.75zM9 13c-2.33 0-7 1.17-7 3.5V19h7v-2.25c0-.85.33-2.34 2.37-3.47C10.5 13.1 9.66 13 9 13z"/> </SvgIcon> ); ActionSupervisorAccount = pure(ActionSupervisorAccount); ActionSupervisorAccount.displayName = 'ActionSupervisorAccount'; ActionSupervisorAccount.muiName = 'SvgIcon'; export default ActionSupervisorAccount;
src/components/panels/index.js
mr47/react-redux-kit
/** * Created by mr470 on 02.04.2016. */ "use strict"; import React, { Component } from 'react'; class LeftPanel extends Component{ render() { const { children } = this.props; return ( <div className="column column-25"> {children} </div> ); } } class RightPanel extends Component{ render() { const { children } = this.props; return ( <div className="column column-75"> {children} </div> ); } } export { RightPanel, LeftPanel }
src/pages/chou-chou.js
vitorbarbosa19/ziro-online
import React from 'react' import BrandGallery from '../components/BrandGallery' export default () => ( <BrandGallery brand='Chou Chou' /> )
client/src/screens/new-group.screen.js
srtucker22/chatty
import { _ } from 'lodash'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { ActivityIndicator, Button, Image, StyleSheet, Text, View, } from 'react-native'; import { graphql, compose } from 'react-apollo'; import AlphabetListView from 'react-native-alpha-listview'; import update from 'immutability-helper'; import Icon from 'react-native-vector-icons/FontAwesome'; import { connect } from 'react-redux'; import SelectedUserList from '../components/selected-user-list.component'; import USER_QUERY from '../graphql/user.query'; // eslint-disable-next-line const sortObject = o => Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {}); const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, cellContainer: { alignItems: 'center', flex: 1, flexDirection: 'row', flexWrap: 'wrap', paddingHorizontal: 12, paddingVertical: 6, }, cellImage: { width: 32, height: 32, borderRadius: 16, }, cellLabel: { flex: 1, fontSize: 16, paddingHorizontal: 12, paddingVertical: 8, }, selected: { flexDirection: 'row', }, loading: { justifyContent: 'center', flex: 1, }, navIcon: { color: 'blue', fontSize: 18, paddingTop: 2, }, checkButtonContainer: { paddingRight: 12, paddingVertical: 6, }, checkButton: { borderWidth: 1, borderColor: '#dbdbdb', padding: 4, height: 24, width: 24, }, checkButtonIcon: { marginRight: -4, // default is 12 }, }); const SectionHeader = ({ title }) => { // inline styles used for brevity, use a stylesheet when possible const textStyle = { textAlign: 'center', color: '#fff', fontWeight: '700', fontSize: 16, }; const viewStyle = { backgroundColor: '#ccc', }; return ( <View style={viewStyle}> <Text style={textStyle}>{title}</Text> </View> ); }; SectionHeader.propTypes = { title: PropTypes.string, }; const SectionItem = ({ title }) => ( <Text style={{ color: 'blue' }}>{title}</Text> ); SectionItem.propTypes = { title: PropTypes.string, }; class Cell extends Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { isSelected: props.isSelected(props.item), }; } componentWillReceiveProps(nextProps) { this.setState({ isSelected: nextProps.isSelected(nextProps.item), }); } toggle() { this.props.toggle(this.props.item); } render() { return ( <View style={styles.cellContainer}> <Image style={styles.cellImage} source={{ uri: 'https://reactjs.org/logo-og.png' }} /> <Text style={styles.cellLabel}>{this.props.item.username}</Text> <View style={styles.checkButtonContainer}> <Icon.Button backgroundColor={this.state.isSelected ? 'blue' : 'white'} borderRadius={12} color={'white'} iconStyle={styles.checkButtonIcon} name={'check'} onPress={this.toggle} size={16} style={styles.checkButton} /> </View> </View> ); } } Cell.propTypes = { isSelected: PropTypes.func, item: PropTypes.shape({ username: PropTypes.string.isRequired, }).isRequired, toggle: PropTypes.func.isRequired, }; class NewGroup extends Component { static navigationOptions = ({ navigation }) => { const { state } = navigation; const isReady = state.params && state.params.mode === 'ready'; return { title: 'New Group', headerRight: ( isReady ? <Button title="Next" onPress={state.params.finalizeGroup} /> : undefined ), }; }; constructor(props) { super(props); let selected = []; if (this.props.navigation.state.params) { selected = this.props.navigation.state.params.selected; } this.state = { selected: selected || [], friends: props.user ? _.groupBy(props.user.friends, friend => friend.username.charAt(0).toUpperCase()) : [], }; this.finalizeGroup = this.finalizeGroup.bind(this); this.isSelected = this.isSelected.bind(this); this.toggle = this.toggle.bind(this); } componentDidMount() { this.refreshNavigation(this.state.selected); } componentWillReceiveProps(nextProps) { const state = {}; if (nextProps.user && nextProps.user.friends && nextProps.user !== this.props.user) { state.friends = sortObject( _.groupBy(nextProps.user.friends, friend => friend.username.charAt(0).toUpperCase()), ); } if (nextProps.selected) { Object.assign(state, { selected: nextProps.selected, }); } this.setState(state); } componentWillUpdate(nextProps, nextState) { if (!!this.state.selected.length !== !!nextState.selected.length) { this.refreshNavigation(nextState.selected); } } refreshNavigation(selected) { const { navigation } = this.props; navigation.setParams({ mode: selected && selected.length ? 'ready' : undefined, finalizeGroup: this.finalizeGroup, }); } finalizeGroup() { const { navigate } = this.props.navigation; navigate('FinalizeGroup', { selected: this.state.selected, friendCount: this.props.user.friends.length, userId: this.props.user.id, }); } isSelected(user) { return ~this.state.selected.indexOf(user); } toggle(user) { const index = this.state.selected.indexOf(user); if (~index) { const selected = update(this.state.selected, { $splice: [[index, 1]] }); return this.setState({ selected, }); } const selected = [...this.state.selected, user]; return this.setState({ selected, }); } render() { const { user, loading } = this.props; // render loading placeholder while we fetch messages if (loading || !user) { return ( <View style={[styles.loading, styles.container]}> <ActivityIndicator /> </View> ); } return ( <View style={styles.container}> {this.state.selected.length ? <View style={styles.selected}> <SelectedUserList data={this.state.selected} remove={this.toggle} /> </View> : undefined} {_.keys(this.state.friends).length ? <AlphabetListView style={{ flex: 1 }} data={this.state.friends} cell={Cell} cellHeight={30} cellProps={{ isSelected: this.isSelected, toggle: this.toggle, }} sectionListItem={SectionItem} sectionHeader={SectionHeader} sectionHeaderHeight={22.5} /> : undefined} </View> ); } } NewGroup.propTypes = { loading: PropTypes.bool.isRequired, navigation: PropTypes.shape({ navigate: PropTypes.func, setParams: PropTypes.func, state: PropTypes.shape({ params: PropTypes.object, }), }), user: PropTypes.shape({ id: PropTypes.number, friends: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number, username: PropTypes.string, })), }), selected: PropTypes.arrayOf(PropTypes.object), }; const userQuery = graphql(USER_QUERY, { options: ownProps => ({ variables: { id: ownProps.auth.id } }), props: ({ data: { loading, user } }) => ({ loading, user, }), }); const mapStateToProps = ({ auth }) => ({ auth, }); export default compose( connect(mapStateToProps), userQuery, )(NewGroup);
src/containers/ContactList.js
jp7internet/react-apz
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link, withRouter } from 'react-router-dom'; import Button from '../components/Button'; import { contactDelete, contactFetch } from '../actions'; class ContactList extends Component { componentWillMount() { this.props.onLoad(); } render() { return ( <div> <Link to="/new" className="btn btn-primary"> Create Contact </Link> <table className="table"> <thead> <tr> <th>Name</th> <th>Phone</th> <th>Email</th> <th colSpan={2}></th> </tr> </thead> <tbody> { this.props.contactList.map(({ id, name, phone, email }, index) => ( <tr key={index}> <td>{name}</td> <td>{phone}</td> <td>{email}</td> <td><Link to={`/edit/${id}`} className="btn btn-primary">Edit</Link></td> <td> <Button buttonType="btn-danger" onClick={() => this.props.onClickDelete(id)}> Delete </Button> </td> </tr> )) } </tbody> </table> </div> ); } } const mapStateToProps = state => ({ ...state.contacts }); const mapDispatchToProps = dispatch => ({ onClickDelete: id => dispatch(contactDelete(id)), onLoad: () => dispatch(contactFetch()) }); export default connect(mapStateToProps, mapDispatchToProps)(withRouter(ContactList));
src/svg-icons/content/weekend.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentWeekend = (props) => ( <SvgIcon {...props}> <path d="M21 10c-1.1 0-2 .9-2 2v3H5v-3c0-1.1-.9-2-2-2s-2 .9-2 2v5c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-5c0-1.1-.9-2-2-2zm-3-5H6c-1.1 0-2 .9-2 2v2.15c1.16.41 2 1.51 2 2.82V14h12v-2.03c0-1.3.84-2.4 2-2.82V7c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ContentWeekend = pure(ContentWeekend); ContentWeekend.displayName = 'ContentWeekend'; ContentWeekend.muiName = 'SvgIcon'; export default ContentWeekend;
docs/app/Examples/collections/Message/Variations/MessageExampleFloating.js
shengnian/shengnian-ui-react
import React from 'react' import { Message } from 'shengnian-ui-react' const MessageExampleFloating = () => ( <Message floating> Way to go! </Message> ) export default MessageExampleFloating
react/features/toolbox/components/Toolbox.web.js
KalinduDN/kalindudn.github.io
/* @flow */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import UIEvents from '../../../../service/UI/UIEvents'; import { setDefaultToolboxButtons, setToolboxAlwaysVisible } from '../actions'; import { abstractMapStateToProps, showCustomToolbarPopup } from '../functions'; import Notice from './Notice'; import PrimaryToolbar from './PrimaryToolbar'; import SecondaryToolbar from './SecondaryToolbar'; declare var APP: Object; declare var config: Object; declare var interfaceConfig: Object; /** * Implements the conference toolbox on React/Web. */ class Toolbox extends Component { /** * App component's property types. * * @static */ static propTypes = { /** * Indicates if the toolbox should always be visible. */ _alwaysVisible: React.PropTypes.bool, /** * Handler dispatching setting default buttons action. */ _setDefaultToolboxButtons: React.PropTypes.func, /** * Handler dispatching reset always visible toolbox action. */ _setToolboxAlwaysVisible: React.PropTypes.func, /** * Represents conference subject. */ _subject: React.PropTypes.string, /** * Flag showing whether to set subject slide in animation. */ _subjectSlideIn: React.PropTypes.bool, /** * Property containing toolbox timeout id. */ _timeoutID: React.PropTypes.number }; /** * Invokes reset always visible toolbox after mounting the component and * registers legacy UI listeners. * * @returns {void} */ componentDidMount(): void { this.props._setToolboxAlwaysVisible(); APP.UI.addListener( UIEvents.SHOW_CUSTOM_TOOLBAR_BUTTON_POPUP, showCustomToolbarPopup); // FIXME The redux action SET_DEFAULT_TOOLBOX_BUTTONS and related source // code such as the redux action creator setDefaultToolboxButtons and // _setDefaultToolboxButtons were introduced to solve the following bug // in the implementation of features/toolbar at the time of this // writing: getDefaultToolboxButtons uses interfaceConfig which is not // in the redux store at the time of this writing yet interfaceConfig is // modified after getDefaultToolboxButtons is called. // SET_DEFAULT_TOOLBOX_BUTTONS represents/implements an explicit delay // of the invocation of getDefaultToolboxButtons until, heuristically, // all existing changes to interfaceConfig have been applied already in // our known execution paths. this.props._setDefaultToolboxButtons(); } /** * Unregisters legacy UI listeners. * * @returns {void} */ componentWillUnmount(): void { APP.UI.removeListener( UIEvents.SHOW_CUSTOM_TOOLBAR_BUTTON_POPUP, showCustomToolbarPopup); } /** * Implements React's {@link Component#render()}. * * @inheritdoc * @returns {ReactElement} */ render(): ReactElement<*> { return ( <div className = 'toolbox'> { this._renderSubject() } { this._renderToolbars() } <div id = 'sideToolbarContainer' /> </div> ); } /** * Returns React element representing toolbox subject. * * @returns {ReactElement} * @private */ _renderSubject(): ReactElement<*> | null { const { _subjectSlideIn, _subject } = this.props; const classNames = [ 'subject' ]; if (!_subject) { return null; } if (_subjectSlideIn) { classNames.push('subject_slide-in'); } else { classNames.push('subject_slide-out'); } // XXX: Since chat is now not reactified we have to dangerously set // inner HTML into the component. This has to be refactored while // reactification of the Chat.js const innerHtml = { __html: _subject }; return ( <div className = { classNames.join(' ') } // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML = { innerHtml } id = 'subject' /> ); } /** * Renders primary and secondary toolbars. * * @returns {ReactElement} * @private */ _renderToolbars(): ReactElement<*> | null { // In case we're not in alwaysVisible mode the toolbox should not be // shown until timeoutID is initialized. if (!this.props._alwaysVisible && this.props._timeoutID === null) { return null; } return ( <div className = 'toolbox-toolbars'> <Notice /> <PrimaryToolbar /> <SecondaryToolbar /> </div> ); } } /** * Maps parts of Redux actions to component props. * * @param {Function} dispatch - Redux action dispatcher. * @returns {{ * _setDefaultToolboxButtons: Function, * _setToolboxAlwaysVisible: Function * }} * @private */ function _mapDispatchToProps(dispatch: Function): Object { return { /** * Dispatches a (redux) action to set the default toolbar buttons. * * @returns {Object} Dispatched action. */ _setDefaultToolboxButtons() { dispatch(setDefaultToolboxButtons()); }, /** * Dispatches a (redux) action to reset the permanent visibility of * the Toolbox. * * @returns {Object} Dispatched action. */ _setToolboxAlwaysVisible() { dispatch(setToolboxAlwaysVisible( config.alwaysVisibleToolbar === true || interfaceConfig.filmStripOnly)); } }; } /** * Maps parts of toolbox state to component props. * * @param {Object} state - Redux state. * @private * @returns {{ * _alwaysVisible: boolean, * _audioMuted: boolean, * _subjectSlideIn: boolean, * _videoMuted: boolean * }} */ function _mapStateToProps(state: Object): Object { const { alwaysVisible, subject, subjectSlideIn, timeoutID } = state['features/toolbox']; return { ...abstractMapStateToProps(state), /** * Indicates if the toolbox should always be visible. * * @private * @type {boolean} */ _alwaysVisible: alwaysVisible, /** * Property containing conference subject. * * @private * @type {string} */ _subject: subject, /** * Flag showing whether to set subject slide in animation. * * @private * @type {boolean} */ _subjectSlideIn: subjectSlideIn, /** * Property containing toolbox timeout id. * * @private * @type {number} */ _timeoutID: timeoutID }; } export default connect(_mapStateToProps, _mapDispatchToProps)(Toolbox);
src/svg-icons/action/play-for-work.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPlayForWork = (props) => ( <SvgIcon {...props}> <path d="M11 5v5.59H7.5l4.5 4.5 4.5-4.5H13V5h-2zm-5 9c0 3.31 2.69 6 6 6s6-2.69 6-6h-2c0 2.21-1.79 4-4 4s-4-1.79-4-4H6z"/> </SvgIcon> ); ActionPlayForWork = pure(ActionPlayForWork); ActionPlayForWork.displayName = 'ActionPlayForWork'; ActionPlayForWork.muiName = 'SvgIcon'; export default ActionPlayForWork;
client/src/components/Dashboard.js
jobn/iceman
// @flow import React, { Component } from 'react'; export default class Dashboard extends Component<*> { render() { return ( <h1>Dashboard</h1> ); } }
plugins/subschema-plugin-contentwrapper/src/index.js
jspears/subschema-devel
import React, { Component } from 'react'; import PropTypes from 'subschema-prop-types'; import { FREEZE_OBJ } from 'subschema-utils'; function strip(obj) { return !obj ? FREEZE_OBJ : Object.keys(obj).reduce(function (ret, key) { if (key == 'dataType' || key == 'fieldAttrs' || obj[key] == null) { return ret; } ret[key] = obj[key]; return ret; }, {}); } export class ContentWrapper extends Component { static defaultProps = { type : 'span', content: '' }; static propTypes = { content : PropTypes.expression, type : PropTypes.domType, value : PropTypes.any, onChange : PropTypes.any, title : PropTypes.any, className : PropTypes.cssClass, id : PropTypes.any, name : PropTypes.any, fieldAttrs: PropTypes.any }; render() { const { type, content, dataType, children, context, path, fieldAttrs, title, ...props } = this.props; const allProps = { ...strip(fieldAttrs), title: title === false ? void(0) : title, ...props, }; if (typeof type == 'string') { return React.createElement(type, { ...allProps, dangerouslySetInnerHTML: { __html: content } }); } const Type = type; return <Type {...allProps}/>; } } export default ({ types: { ContentWrapper } })
examples/docs/src/Containers/GettingStarted.js
react-material-design/react-material-design
import React from 'react'; const GettingStarted = () => ( <div> <h1>Getting Started</h1> <p>More to come...</p> <p>To install run: yarn add react-material-design</p> <p>Once installed import the react-material-design components you'll be usings like so: import {'{'} FAB {'}'} from 'react-material-design';</p> </div> ); export default GettingStarted;
src/decorators/withViewport.js
magnusbae/arcadian-rutabaga
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = {width: 1366, height: 768}; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = {width: window.innerWidth, height: window.innerHeight}; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport}/>; } handleResize(value) { this.setState({viewport: value}); // eslint-disable-line react/no-set-state } }; } export default withViewport;
src/admin/components/Profesor.js
zeljkoX/e-learning
import React from 'react'; import {State, History} from 'react-router'; import { Menu, Mixins, Styles, RaisedButton, TextField, SelectField } from 'material-ui'; import Content from '../../components/layout/Content'; import ContentHeader from '../../components/layout/ContentHeader'; class Profesor extends React.Component { render() { var profesori = [ { payload: '1', text: 'Never' }, { payload: '2', text: 'Every Night' }, { payload: '3', text: 'Weeknights' }, { payload: '4', text: 'Weekends' }, { payload: '5', text: 'Weekly' }, ]; var menu = [{name:'Uredi', link:'profesori/edit'},{name:'Brisi', link:'profesori/remove'}]; return ( <Content> <ContentHeader title='Odredjen profesor' menu={menu}/> <form style={{margin: '0 auto', position: 'relative', width: 600}}> <TextField hintText="Ime" disabled={true} floatingLabelText="Ime" style={{display: 'block', width: 350, margin: '0 auto'}}/> <TextField hintText="Prezime" disabled={true} floatingLabelText="Prezime" style={{display: 'block', width: 350, margin: '0 auto'}} /> <TextField hintText="Email" disabled={true} floatingLabelText="Email" style={{display: 'block', width: 350, margin: '0 auto'}} /> <TextField hintText="Sifra" disabled={true} floatingLabelText="Sifra" style={{display: 'block', width: 350, margin: '0 auto'}} /> <TextField hintText="Skype" disabled={true} floatingLabelText="Skype" style={{display: 'block', width: 350, margin: '0 auto'}} /> <SelectField floatingLabelText="Profesor" hintText="Odaberite profesora" style={{display: 'block', width: 350, margin: '0 auto'}} menuItems={profesori} /> <SelectField floatingLabelText="Kurs" hintText="Odaberite profesora" style={{display: 'block', width: 350, margin: '0 auto'}} menuItems={profesori} /> </form> </Content> ); } } export default Profesor;
src/slides/stream-of-events.js
philpl/talk-observe-the-future
import React from 'react' import { Appear, Image, Text, S, Slide } from 'spectacle' import Marbles from '../components/marbles' export default ( <Slide transition={[ 'slide' ]}> <Marbles/> </Slide> )
src/components/ScoreGraph.js
tgevaert/react-redux-hearts
import React from 'react'; import { connect } from 'react-redux'; import { getPlayers, getScoreTotals } from '../reducers'; const GraphRowLabel = ({label}) => (<div className={"graph label"}>{label}</div>); const GraphLine = ({size}) => { const colors = ["#388e3c", "#ffd600", "#e65100", "#d50000", "#d50000"]; const barStyle = { flexBasis: Math.max(Math.min(size, 100), 0) + "%", backgroundColor: colors[Math.max(Math.floor(size / 25), 0)], }; return ( <div className={"graph row"}> <div className={"graph row bar"} style={barStyle}>{size}</div> <div className={"graph row blank"}></div> </div> ); }; const ScoreGraphPresentation = ({playerNames, scores}) => { const graphRowLabels = playerNames.map((playerName, i) => <GraphRowLabel key={i} label={playerName} />); const graphLines = scores.map((score, i) => <GraphLine key={i} size={score} />); return ( <div className={"graph"}> <div className={"labels"}> {graphRowLabels} </div> <div className={"bars"}> {graphLines} </div> </div> ) } const mapStateToProps = (state) => { const playerNames = getPlayers(state).map((player) => player.name); const scores = getScoreTotals(state); return {playerNames: playerNames, scores: scores}; } export default connect(mapStateToProps)(ScoreGraphPresentation);
yycomponent/breadcrumb/Breadcrumb.js
77ircloud/yycomponent
import React from 'react'; import { Breadcrumb as _Breadcrumb } from 'antd'; class Breadcrumb extends React.Component{ constructor(props){ super(props); } render(){ return (<_Breadcrumb {...this.props}/>); } } export default Breadcrumb
imports/ui/components/footer/Footer/Footer.js
pletcher/cltk_frontend
import React from 'react'; import FlatButton from 'material-ui/FlatButton'; import IconButton from 'material-ui/IconButton'; import PropTypes from 'prop-types'; import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; export default class Footer extends React.Component { getChildContext() { return { muiTheme: getMuiTheme(baseTheme) }; } render() { const date = new Date(); const year = date.getFullYear(); const styles = { circleButton: { width: 'auto', height: 'auto', }, circleButtonIcon: { color: '#ffffff', }, }; return ( <footer className="bg-dark"> <div className="container"> <div className="row"> <div className="col-md-8 col-md-offset-2 col-sm-9 col-sm-offset-1 text-center"> <h3 className="logo">CLTK Archive</h3> <div className="footer-nav"> <FlatButton label="HOME" href="/" /> <FlatButton label="READ" href="/browse" /> <FlatButton label="SEARCH" href="/search" /> <FlatButton label="CONTRIBUTE" target="_blank" href="http://github.com/cltk/cltk" rel="noopener noreferrer" /> <FlatButton label="CLTK.ORG" href="//cltk.org/" target="_blank" rel="noopener noreferrer" /> </div> </div> </div> <div className="row"> <div className="col-sm-12 text-center"> <ul className="list-inline social-list mb0"> <li> <IconButton style={styles.circleButton} iconStyle={styles.circleButtonIcon} href="http://github.com/cltk" iconClassName="mdi mdi-github-circle" /> </li> <li> <IconButton style={styles.circleButton} iconStyle={styles.circleButtonIcon} href="http://twitter.com/@cltkarchive" iconClassName="mdi mdi-twitter" /> </li> <li> <IconButton style={styles.circleButton} iconStyle={styles.circleButtonIcon} href="http://plus.google.com/+cltkarchive" iconClassName="mdi mdi-google-plus" /> </li> </ul> <span className="copyright-information fade-1-4"> Copyright Classical Languages ToolKit, {year}. All of the media presented on this site originating from the CLTK are available through the Creative Commons Attribution 4.0 International, Free Culture License. Media originating from other sources are specific to the contributor. Review specific corpora information here: <a href="https://github.com/cltk" target="_blank">https://github.com/cltk</a>. </span> </div> </div> </div> </footer> ); } }; Footer.childContextTypes = { muiTheme: PropTypes.object.isRequired, };
modules/plugins/italic/ItalicButton.js
devrieda/arc-reactor
import React from 'react'; import MenuButton from '../../components/MenuButton'; import ToggleMarkup from '../../helpers/Manipulation/ToggleMarkup'; import SelectedContent from '../../helpers/SelectedContent'; const ItalicButton = React.createClass({ statics: { getName: () => "italic", isVisible: (content, selection) => { const selContent = new SelectedContent(selection, content); return !selContent.isHeader(); } }, propTypes: MenuButton.propTypes, getDefaultProps() { return { type: "em", text: "Italic", icon: "fa-italic" }; }, handlePress() { const guids = this.props.selection.guids(); const offsets = this.props.selection.offsets(); const position = this.props.selection.position(); const result = this._toggleMarkup().execute(guids, offsets, { type: this.props.type }); return { content: result.content, position: position }; }, _toggleMarkup() { return new ToggleMarkup(this.props.content); }, render() { return ( <MenuButton {...this.props} onPress={this.handlePress} /> ); } }); export default ItalicButton;
ux/editor/TextEditorView.js
rameshvk/j0
'use strict'; require('./TextEditorView.less'); import React from 'react'; import ReactDOM from 'react-dom'; import BaseComponent from '../BaseComponent'; import Caret from './Caret'; import InvisibleInput from './InvisibleInput'; import TextSelectionView from './TextSelectionView'; import getTextNodeInfoForPoint from '../../dom/getTextNodeInfoForPoint'; import MouseModel from './MouseModel'; import AttentionManager from './AttentionManager'; export default class TextEditorView extends BaseComponent { constructor(props) { super(props); this._onMouseDown = ee => this.onMouseDown(ee); this._caret = Caret.create({isActive: false, isCollapsed: true}); this._mouseModel = null; this._attentionManager = new AttentionManager(); } componentDidMount() { this._mouseModel = new MouseModel(this.props.selection, ReactDOM.findDOMNode(this)); this._attentionManager.startTracking(ReactDOM.findDOMNode(this)); // TODO: do this via events this.props.selection.setAttentionManager(this._attentionManager); } componentWillUnmount() { this._mouseModel.cleanup(); } onMouseDown(ee) { const clickCount = this._mouseModel.onMouseDown(ee); if (clickCount && !this.props.isActive) { this.props.onActivate(ee); } } _renderInput(isActive, selection) { return InvisibleInput.create({key: 1, isActive, selection}); } _renderCaret(isActive) { return React.cloneElement(this.props.caret || this._caret, {key: 0, isActive}); } render() { const isActive = this.props.isActive; const selection = this.props.selection; return React.DOM.div( { className: 'j0editor ' + (isActive ? 'active ' : '') + (this.props.className || ''), onMouseDown: this._onMouseDown }, this.props.children, this.props.selectionOverlays, TextSelectionView.create({ className: 'j0selections ' + (isActive? 'active' : ''), selection, anchorMarker: [], focusMarker: [this._renderInput(isActive, selection), this._renderCaret(isActive, selection)] }) ); } } TextEditorView.propTypes = { className: React.PropTypes.string, selection: React.PropTypes.object.isRequired, selectionOverlays: React.PropTypes.array, caret: React.PropTypes.element, isActive: React.PropTypes.bool.isRequired, onActivate: React.PropTypes.func.isRequired };
web/src/presentation/get-retro-properties.js
mgwalker/retros
import React from 'react'; import CategoryTime from './set-retro-category-time'; function displayTime(minutes) { const wholeMinutes = Math.floor(minutes); const seconds = Math.round((minutes - wholeMinutes) * 60); return `${wholeMinutes} minutes${seconds > 0 ? ` and ${seconds} seconds` : ''}`; } function GetRetroProperties(props) { return ( <div className="usa-grid"> <h1>Setup Retro Properties</h1> <div className="usa-grid"> <p> Now we need to setup the timing properties of your retro. You can specify a total length of time the retro should run and we&apos;ll automatically fill in the length of time to display each category and voting, or you can fill in those individual values yourself. This time is evenly divided for each category. Your retro cannot be shorter than {displayTime(props.minimumTime)}, so that participants can answer each category for at least one minute, and vote on each for at least 30 seconds. </p> <h2>Total retro time, in minutes:</h2> <p> <input type="number" min={props.minimumTime} step="1.0" value={props.totalTime} onChange={props.changeTotalTime}></input> </p> <button className="usa-button-big" onClick={props.acceptProperties}>Accept</button> Create a standup that runs for {displayTime(props.totalTime)} </div> <hr /> <div className="usa-grid"> <p> If you want finer-grained control, you can set the times for each category below. Note that answer times must be at least one minute and voting times must be at least 0.5 minutes (30 seconds). </p> {props.categories.map(c => <CategoryTime category={c} times={props.categoryTimes[c]} key={`retro_props_category_${c}`} onChangeSelfTime={props.changeCategorySelfTime(c)} onChangeVoteTime={props.changeCategoryVoteTime(c)} /> )} <button className="usa-button-big" onClick={props.acceptProperties}>Accept</button> Create a standup that runs for {displayTime(props.totalTime)} </div> </div> ); } GetRetroProperties.propTypes = { categories: React.PropTypes.array.isRequired, minimumTime: React.PropTypes.number.isRequired, totalTime: React.PropTypes.string.isRequired, categoryTimes: React.PropTypes.object.isRequired, changeTotalTime: React.PropTypes.func.isRequired, changeCategorySelfTime: React.PropTypes.func.isRequired, changeCategoryVoteTime: React.PropTypes.func.isRequired, acceptProperties: React.PropTypes.func.isRequired }; export default GetRetroProperties;
js/ClientApp.js
JoeMarion/react-netflix
import React from 'react' import { render } from 'react-dom' import '../public/style.css' const App = React.createClass({ render () { return ( <div className='app'> <div className='landing'> <h1>svideo</h1> <input type='text' placeholder='Search' /> <a>or Browse All</a> </div> </div> ) } }) render(<App />, document.getElementById('app'))
node-siebel-rest/siebel-claims-native/screens/AddClaim.js
Pravici/node-siebel
import React, { Component } from 'react'; import { StyleSheet, View, TouchableHighlight, Text, Image, ActivityIndicator, Button, } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import { MaterialIcons } from '@expo/vector-icons'; import { callPostApi } from '../utils/rest'; import myConfig from '../config/Config'; import colors from '../utils/colors'; import TouchableDetailListItem from '../components/TouchableDetailListItem'; export default class AddClaim extends Component { static navigationOptions = ({ navigation: { navigate } }) => ({ title: 'Add Accident Claim', headerLeft: ( <MaterialIcons name="menu" size={24} style={{ color: colors.black, marginLeft: 10 }} onPress={() => navigate('DrawerToggle')} /> ), }); state = { claim: [], error: false, adding: "false", lossDate:new Date(), }; async postNewClaim(url, data) { const jsondata = await callPostApi(url, data); console.log('json:', jsondata); return jsondata['Id']; } setDateOfIncident(selectedDate) { this.setState({lossDate: selectedDate}); console.log('lossDate', selectedDate); } getFormattedDate(date) { var mm = date.getMonth() + 1; var dd = date.getDate(); var yyyy = date.getFullYear(); return mm + '/' + dd +'/' + yyyy +' '+ date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); } async updateSiebel() { try { var url = `${myConfig.simUrl}/claims/addClaim/${myConfig.customer}`; //var url = `https://win-b1ejslvnv0l.siebel-pravici.com:9301/siebel/v1.0/data/Demo INS Claims/INS Claims/`; console.log(url); data = { "Id": "New claim", "Asset Id": "1-3H01", "Location Description": "parking lot Thom Thumb store facing Renner Rd", "Loss Date - Non UTC": this.getFormattedDate(this.state.lossDate), }; // simdata = { // claimType: 'accident', // accidentType: 'other car', // location: 'text field', // lossDate: '10/10/17', // reportedDate: '10/10/2017', // policyNumber: 'KM-VEH-005', // }; this.setState({adding: "adding",}); //const claim = callPostApi(url, data, this.postNewClaim); const claim = await this.postNewClaim(url, data); this.setState({claim: claim, error: false, adding: "true,"}); const { navigation: { navigate } } = this.props; navigate('ReviewClaims'); } catch (e) { this.setState({ error: e.message, adding: "false", }); } } render() { const { navigation: { navigate } } = this.props; const { adding, error } = this.state; return ( <View style={styles.container}> {adding == "adding" && <ActivityIndicator size="large" />} {error && <Text>{error}</Text>} {adding == "false" && !error && ( <View style={styles.container}> <TouchableDetailListItem icon="info" title="Accident Type " rightIcon="chevron-right" /> <TouchableDetailListItem icon="date-range" title="Date & Location" rightIcon="chevron-right" onPress={() => navigate('DatePicker', { show : true , returnData : this.setDateOfIncident.bind(this)})}/> <TouchableDetailListItem icon="camera" title="Pictures of the Incident" rightIcon="chevron-right" onPress = {() => navigate('PhotoPage', { claim: this.state.claimNumber })} /> <TouchableDetailListItem icon="verified-user" title="Contact Info" rightIcon="chevron-right" /> <TouchableDetailListItem icon="traffic" title="Other Driver's Info" rightIcon="chevron-right"/> <TouchableHighlight onPress={() => this.updateSiebel()} underlayColor={colors.grey} style={styles.touchContainer} > <View> <Text style={[styles.buttonStyle, styles.mediumText]}>Submit Claim</Text> </View> </TouchableHighlight> </View> )} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, touchContainer: { paddingLeft: 24, backgroundColor: 'steelblue', paddingTop: 10, }, buttonStyle: { height: 40, alignItems: 'center', }, mediumText: { textAlign: 'center', fontSize: 20, }, });
src/containers/Contact/Contact.js
Anshul-HL/blitz-windermere
import React, { Component } from 'react'; import { groupBy } from 'utils/extenders'; const addressList = [ { id: '1', title: 'Our Corporate Office', address: [ '3th floor, Bikaner Pinnacle,', 'No.1 Rhenius street,', 'Off Richmond Road,', 'Bangalore - 560025' ], city: 'Bangalore', landMark: 'Behind Cafe Coffee Day on Richmond Road' }, { id: '2', title: 'Gopalan Square', address: [ '4th floor, Gopalan Signature Mall,', 'Old Madras Road,', 'Bangalore - 560093' ], city: 'Bangalore' }, { id: '3', title: 'Yelahanka Square', address: [ 'Mukund Pandurangi,', '#1234, Mother Dairy Road,', 'Yelahanka Newtown,', 'Bangalore - 560064' ], city: 'Bangalore' }, { id: '4', title: 'Kanakapura Square', address: [ '#2054, 1st Main Road,', '1st Floor, SMLV Plaza', 'BCCHS Layout, Raghuvanahalli,', 'Kanakpura,', 'Bangalore' ], city: 'Bangalore' }, { id: '5', title: 'Chennai Square', address: [ 'Door #46,', 'Chennai - Bangalore Trunk Road,', 'Nazarethpet, Poonamallee,', 'Chennai - 600123' ], city: 'Chennai', }, { id: '6', title: 'Hyderabad Square', address: [ '8-2-699/4, Shop no.4,', '1st floor, K.R Towers,', 'Road no.12, Banjara Hills', 'Hyderabad - 500043' ], city: 'Hyderabad', }/* , { id: '6', title: 'Mumbai Showroom', address: [ '2nd Floor, Tirumala Platinum,', 'Near Gachibowli Flyover,', 'Gachibowli,', 'Hyderabad - 500032' ] }, { id: '7', title: 'Hyderabad Showroom', address: [ '2nd Floor, Tirumala Platinum,', 'Near Gachibowli Flyover,', 'Gachibowli,', 'Hyderabad - 500032' ] }, { id: '8', title: 'Hyderabad Showroom', address: [ '2nd Floor, Tirumala Platinum,', 'Near Gachibowli Flyover,', 'Gachibowli,', 'Hyderabad - 500032' ] }, { id: '9', title: 'Hyderabad Showroom', address: [ '2nd Floor, Tirumala Platinum,', 'Near Gachibowli Flyover,', 'Gachibowli,', 'Hyderabad - 500032' ] }, { id: '10', title: 'Hyderabad Showroom', address: [ '2nd Floor, Tirumala Platinum,', 'Near Gachibowli Flyover,', 'Gachibowli,', 'Hyderabad - 500032' ] }*/ ]; const showRoomTimings = { start: '11am', end: '7pm' }; export default class Contact extends Component { render() { const styles = require('./Contact.scss'); const addressGroups = groupBy(addressList, address => address.city); console.log(addressGroups); return ( <div className={styles.contactContainer}> <h2>Contact us</h2> <div className={styles.addressContainer + ' col-md-12 col-xs-12'}> <p><span className={styles.heading}>SHOWROOM HOURS</span> Open all days {showRoomTimings.start} - {showRoomTimings.end}</p> { addressGroups.map( group => { return ( <div className="col-md-12"> <h6 className={styles.heading}>{group.key}</h6> { group.data.map( address => { return ( <div key={address.id} className={ styles.addressCard + ' col-md-4 col-xs-12'} > <h6 className={styles.heading}>{address.title}</h6> {address.address.map((line) => { return (<p key={line}>{line}</p>); })} <p className={address.landMark ? '' : 'hidden'}><span className="bold">LandMark: </span>{address.landMark}</p> </div> ); }) } </div>); }) } </div> </div> ); } }
client/app/partials/app-nav-bar/index.js
nebulae-io/coteries
import React, { Component } from 'react'; import { IndexLink, Link } from 'react-router'; import cns from 'classnames'; import Flex from 'components/flex'; import styles from './style.scss'; function mapStateToProps(state) { return {}; } function mapDispatchToProps(dispatch) { return { todoActions: bindActionCreators(todoActionCreators, dispatch), counterActions: bindActionCreators(counterActionCreators, dispatch) }; } class AppNavBar extends Component { render() { let linkProps = { activeClassName: styles.activedNavItem, className: cns(styles.navItem, 'link link--flat') }; return ( <Flex className={styles.navBar} row justifyContent='space-between' {...this.props}> <Flex tag='ul' row> <IndexLink to='/' {...linkProps}>{__('terms.home')}</IndexLink> <Link to='/places' {...linkProps}>{__('terms.places')}</Link> <Link to='/events' {...linkProps}>{__('terms.events')}</Link> <Link to='/stuffs' {...linkProps}>{__('terms.stuffs')}</Link> </Flex> </Flex> ); } } export default AppNavBar;
node_modules/react-bootstrap/es/Alert.js
jkahrs595/website
import _Object$values from 'babel-runtime/core-js/object/values'; import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, bsStyles, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; import { State } from './utils/StyleConfig'; var propTypes = { onDismiss: React.PropTypes.func, closeLabel: React.PropTypes.string }; var defaultProps = { closeLabel: 'Close alert' }; var Alert = function (_React$Component) { _inherits(Alert, _React$Component); function Alert() { _classCallCheck(this, Alert); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Alert.prototype.renderDismissButton = function renderDismissButton(onDismiss) { return React.createElement( 'button', { type: 'button', className: 'close', onClick: onDismiss, 'aria-hidden': 'true', tabIndex: '-1' }, React.createElement( 'span', null, '\xD7' ) ); }; Alert.prototype.renderSrOnlyDismissButton = function renderSrOnlyDismissButton(onDismiss, closeLabel) { return React.createElement( 'button', { type: 'button', className: 'close sr-only', onClick: onDismiss }, closeLabel ); }; Alert.prototype.render = function render() { var _extends2; var _props = this.props; var onDismiss = _props.onDismiss; var closeLabel = _props.closeLabel; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['onDismiss', 'closeLabel', 'className', 'children']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var dismissable = !!onDismiss; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'dismissable')] = dismissable, _extends2)); return React.createElement( 'div', _extends({}, elementProps, { role: 'alert', className: classNames(className, classes) }), dismissable && this.renderDismissButton(onDismiss), children, dismissable && this.renderSrOnlyDismissButton(onDismiss, closeLabel) ); }; return Alert; }(React.Component); Alert.propTypes = propTypes; Alert.defaultProps = defaultProps; export default bsStyles(_Object$values(State), State.INFO, bsClass('alert', Alert));
client/src/Title.js
mit-teaching-systems-lab/swipe-right-for-cs
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import './Title.css'; import logoSrc from './img/swipe.gif'; import {Interactions} from './shared/data.js'; import Swipeable from './components/Swipeable.js'; import Delay from './components/Delay.js'; import SwipeCue from './components/SwipeCue.js'; class Title extends Component { constructor(props) { super(props); this.onSwipeRight = this.onSwipeRight.bind(this); } // prefetch image before animation starts componentDidMount() { const image = new Image(); image.src = logoSrc; } onSwipeRight() { const {onInteraction, onDone} = this.props; onInteraction(Interactions.play()); onDone(); } render() { const swipeHeight = 128; return ( <div className="Title"> <p className="Title-intro"> Swipe Right for CS! </p> <Delay wait={250}> <Swipeable style={{width: '100%'}} height={swipeHeight} onSwipeRight={this.onSwipeRight}> <div className="Title-swipe"> <SwipeCue style={{position: 'absolute', top: (swipeHeight/2)}} /> <img className="Title-logo" alt="Logo" src={logoSrc} height={128} width={128} /> <div>Swipe right to play!</div> </div> </Swipeable> </Delay> </div> ); } } Title.propTypes = { onInteraction: PropTypes.func.isRequired, onDone: PropTypes.func.isRequired }; export default Title;
docs/src/app/components/pages/components/DatePicker/ExampleInline.js
spiermar/material-ui
import React from 'react'; import DatePicker from 'material-ui/DatePicker'; /** * Inline Date Pickers are displayed below the input, rather than as a modal dialog. */ const DatePickerExampleInline = () => ( <div> <DatePicker hintText="Portrait Inline Dialog" container="inline" /> <DatePicker hintText="Landscape Inline Dialog" container="inline" mode="landscape" /> </div> ); export default DatePickerExampleInline;
bayty/src/components/LoginForm.js
Asmaklf/bayty
import React, { Component } from 'react'; import { Text } from 'react-native'; import { connect } from 'react-redux'; import { emailChanged, passwordChanged, loginUser } from '../actions'; import { Card, CardSection, Button, Input, Spinner } from './common'; class LoginForm extends Component { onEmailChange(text) { this.props.emailChanged(text); } onPasswordChange(text) { this.props.passwordChanged(text); } onButtonPress() { const { email, password } = this.props; this.props.loginUser({ email, password }); } renderButton() { if (this.props.loading) { return <Spinner size="large" />; } return ( <Button onPress={this.onButtonPress.bind(this)}> Login </Button> ); } render() { return ( <Card> <CardSection> <Input label="Email" placeholder="[email protected]" onChangeText={this.onEmailChange.bind(this)} value={this.props.email} /> </CardSection> <CardSection> <Input secureTextEntry label="Password" placeholder="password" onChangeText={this.onPasswordChange.bind(this)} value={this.props.password} /> </CardSection> <Text style={styles.errorTextStyle}> {this.props.error} </Text> <CardSection> {this.renderButton()} </CardSection> </Card> ); } } const mapStateToProps = state => { return { email: state.auth.email, password: state.auth.password, error: state.auth.error, loading: state.auth.loading }; }; const styles = { errorTextStyle: { fontSize: 20, alignSelf: 'center', color: 'red' } }; export default connect(mapStateToProps, { emailChanged, passwordChanged, loginUser })(LoginForm);
docs/src/Anchor.js
pandoraui/react-bootstrap
import React from 'react'; const Anchor = React.createClass({ propTypes: { id: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]) }, render() { return ( <a id={this.props.id} href={'#' + this.props.id} className="anchor"> <span className="anchor-icon">#</span> {this.props.children} </a> ); } }); export default Anchor;
app/components/dashboard/home/CustomTagCloud.js
mchlltt/mementoes
// Import dependencies and components. import React from 'react'; import {TagCloud} from 'react-tagcloud'; // Create and export component class. // I created this custom component because the default TagCloud refreshed anytime the page state changed. export default class CustomTagCloud extends TagCloud { constructor(props) { super(props); this.state = {}; } // This method was the main purpose/fix. It checks whether the tags themselves have actually updated. shouldComponentUpdate(nextProps) { return this.props.tags !== nextProps.tags; } render() { return ( <TagCloud tags={this.props.tags} maxSize={this.props.maxSize} minSize={this.props.minSize} colorOptions={this.props.colorOptions} onClick={this.props.onClick} /> ) } }
client/app/bundles/HelloWorld/components/general_components/table/sortable_table/table_sorting_mixin.js
ddmck/Empirical-Core
// This React mixin handles client-side sorting. // Use it ljke so: // Call defineSorting() in componentDidMount() of your component. // Call sortResults() when a sort changes (use as a handler function) // Call applySorting() on your data before displaying it in render(). import React from 'react' import _ from 'underscore' import naturalCmp from 'underscore.string/naturalCmp' export default { getInitialState: function() { return { currentSort: {}, sortConfig: {} }; }, // Sign = 1 or -1 depending on whether the sort is normal or reverse order numericSort: function(sign, fieldName, a, b) { return (a[fieldName] - b[fieldName]) * sign; }, // Sign = 1 or -1 depending on whether the sort is normal or reverse order naturalSort: function(sign, fieldName, a, b) { return s.naturalCmp(a[fieldName], b[fieldName]) * sign; }, // config = {field: string, sortFunc: function, ...} // currentSort = {field: string, direction: string ('asc' or 'desc')} defineSorting: function(config, currentSort) { // Convert string configuration to functions. _.each(config, function(value, key) { if (!_.isFunction(value)) { switch(value) { case 'numeric': config[key] = this.numericSort; break case 'natural': config[key] = this.naturalSort; break; default: throw "Sort function named '" + value + "' not recognized"; } } }.bind(this)); this.setState({ sortConfig: config, currentSort: currentSort }); }, applySorting: function(results) { var sortDirection = this.state.currentSort.direction, sortByFieldName = this.state.currentSort.field; if (!sortDirection && !sortByFieldName) { return results; } // Flip the sign of the return value to sort in reverse var sign = (sortDirection === 'asc' ? 1 : -1); var sortFunc = this.state.sortConfig[sortByFieldName]; if (!sortFunc) { throw "Sort function not defined for '" + sortByFieldName + "' field"; } // Partially apply arguments so that the new func has signature -> (a, b) var appliedSort = _.partial(sortFunc, sign, sortByFieldName); results.sort(appliedSort); return results; }, sortResults: function(after, sortByFieldName, sortDirection) { this.setState({ currentSort: { field: sortByFieldName, direction: sortDirection } }, after); } };
actor-apps/app-web/src/app/components/activity/GroupProfileMembers.react.js
fengchenlianlian/actor-platform
import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import DialogActionCreators from 'actions/DialogActionCreators'; import LoginStore from 'stores/LoginStore'; import AvatarItem from 'components/common/AvatarItem.react'; const GroupProfileMembers = React.createClass({ propTypes: { groupId: React.PropTypes.number, members: React.PropTypes.array.isRequired }, mixins: [PureRenderMixin], onClick(id) { DialogActionCreators.selectDialogPeerUser(id); }, onKickMemberClick(groupId, userId) { DialogActionCreators.kickMember(groupId, userId); }, render() { let groupId = this.props.groupId; let members = this.props.members; let myId = LoginStore.getMyId(); let membersList = _.map(members, (member, index) => { let controls; let canKick = member.canKick; if (canKick === true && member.peerInfo.peer.id !== myId) { controls = ( <div className="controls pull-right"> <a onClick={this.onKickMemberClick.bind(this, groupId, member.peerInfo.peer.id)}>Kick</a> </div> ); } return ( <li className="profile__list__item row" key={index}> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> <AvatarItem image={member.peerInfo.avatar} placeholder={member.peerInfo.placeholder} size="small" title={member.peerInfo.title}/> </a> <div className="col-xs"> <a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}> <span className="title"> {member.peerInfo.title} </span> </a> {controls} </div> </li> ); }, this); return ( <ul className="profile__list profile__list--members"> <li className="profile__list__item profile__list__item--header">{members.length} members</li> {membersList} </ul> ); } }); export default GroupProfileMembers;
src/components/rows/input/AnnualLeave.js
hikurangi/day-rate-calculator
import React from 'react'; import { TableRow, TableRowColumn } from '@material-ui/core/Table'; import TextField from '@material-ui/core/TextField'; const AnnualLeave = ({ handleChange }) => { return ( <TableRow> <TableRowColumn> <h3>Your total number of annual leave days</h3> </TableRowColumn> <TableRowColumn> <TextField name="annualLeave" type="number" hintText="Your total number of annual leave days" onChange={handleChange} /> </TableRowColumn> </TableRow> ); }; export default AnnualLeave;
src/index.js
datchley/react-scale-text
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import warn from 'warning'; import { generate as shortId } from 'shortid'; import shallowEqual from './shallow-equal'; import getFillSize from './get-fillsize'; import { getStyle, css } from './dom-utils'; class ScaleText extends Component { constructor(props) { super(props); this.state = { size: null }; this._resizing = false; this._invalidChild = false; this._mounted = false; this._handleResize = () => { if (!this._resizing) { requestAnimationFrame(this.handleResize.bind(this)); } this._resizing = true; }; } componentDidMount() { const { children } = this.props; this._mounted = true; this._invalidChild = React.Children.count(children) > 1; warn(!this._invalidChild, `'ScaleText' expects a single node as a child, but we found ${React.Children.count(children)} children instead. No scaling will be done on this subtree` ); if (this.shouldResize()) { this.resize(); window.addEventListener('resize', this._handleResize); } } componentDidUpdate(prevProps) { // compare children's props for change if (!shallowEqual(prevProps.children.props, this.props.children.props) || prevProps.children !== this.props.children || prevProps !== this.props) { this.resize(); } } componentWillUnmount() { if (!this.shouldResize()) { window.removeEventListener('resize', this._handleResize); } } shouldResize() { return !this._invalidChild; } handleResize() { this._resizing = false; this.resize(); } resize() { const { minFontSize, maxFontSize, widthOnly } = this.props; if (!this._mounted || !this._wrapper) return; if (this.ruler) { this.clearRuler(); } this.createRuler(); const fontSize = getFillSize( this.ruler, minFontSize || Number.NEGATIVE_INFINITY, maxFontSize || Number.POSITIVE_INFINITY, widthOnly ); this.setState({ size: parseFloat(fontSize, 10), complete: true }, () => { this.clearRuler(); }); } createRuler() { // Create copy of wrapper for sizing this.ruler = this._wrapper.cloneNode(true); this.ruler.id = shortId(); css(this.ruler, { position: 'absolute', top: '0px', left: 'calc(100vw * 2)', width: getStyle(this._wrapper, 'width'), height: getStyle(this._wrapper, 'height') }); document.body.appendChild(this.ruler); } clearRuler() { if (this.ruler) { document.body.removeChild(this.ruler); } this.ruler = null; } render() { const { size: fontSize } = this.state; const { children, widthOnly } = this.props; const overflowStyle = widthOnly ? { overflowY: 'visible', overflowX: 'hidden', height: 'auto' } : { overflow: 'hidden' }; const child = React.isValidElement(children) ? React.Children.only(children) : (<span>{children}</span>); const style = { fontSize: fontSize ? `${fontSize.toFixed(2)}px` : 'inherit', width: '100%', height: '100%', ...overflowStyle // overflow: 'hidden' }; const childProps = { fontSize: fontSize ? parseFloat(fontSize.toFixed(2)) : 'inherit' }; return ( <div className="scaletext-wrapper" ref={(c) => { this._wrapper = c; }} style={style} > { React.cloneElement(child, childProps) } </div> ); } } ScaleText.propTypes = { children: PropTypes.node.isRequired, minFontSize: PropTypes.number.isRequired, maxFontSize: PropTypes.number.isRequired, widthOnly: PropTypes.bool }; ScaleText.defaultProps = { minFontSize: Number.NEGATIVE_INFINITY, maxFontSize: Number.POSITIVE_INFINITY, widthOnly: false }; // export default ScaleText; module.exports = ScaleText;
examples/src/components/CustomRender.js
pedroseac/react-select
import React from 'react'; import Select from 'react-select'; var DisabledUpsellOptions = React.createClass({ displayName: 'DisabledUpsellOptions', propTypes: { label: React.PropTypes.string, }, getInitialState () { return {}; }, setValue (value) { this.setState({ value }); console.log('Support level selected:', value.label); }, renderLink: function() { return <a style={{ marginLeft: 5 }} href="/upgrade" target="_blank">Upgrade here!</a>; }, renderOption: function(option) { return <span style={{ color: option.color }}>{option.label} {option.link}</span>; }, renderValue: function(option) { return <strong style={{ color: option.color }}>{option.label}</strong>; }, render: function() { var options = [ { label: 'Basic customer support', value: 'basic', color: '#E31864' }, { label: 'Premium customer support', value: 'premium', color: '#6216A3' }, { label: 'Pro customer support', value: 'pro', disabled: true, link: this.renderLink() }, ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select placeholder="Select your support level" options={options} optionRenderer={this.renderOption} onChange={this.setValue} value={this.state.value} valueRenderer={this.renderValue} /> <div className="hint">This demonstates custom render methods and links in disabled options</div> </div> ); } }); module.exports = DisabledUpsellOptions;
packages/v4/src/content/extensions/extensions-data-list.js
patternfly/patternfly-org
import React from 'react'; import { DataList, DataListItem, DataListItemRow, DataListItemCells, DataListCell, Title } from '@patternfly/react-core'; export const ExtensionsDataList = (props) => ( <DataList aria-label="Community extensions"> {props.data.map(item => { const links = item.links.map((link, index) => { return ( <span key={index} className="pf-c-extensions__link"> <a href={link.href} target="_blank" rel="noopener noreferrer">{link.name}</a> </span> ); }); return ( <DataListItem aria-labelledby="simple-item1"> <DataListItemRow> <DataListItemCells dataListCells={[ <DataListCell key="primary content" width={2}> <Title headingLevel="h3">{item.component}</Title> <span className="pf-c-extensions__component-description">{item.description}</span> </DataListCell>, <DataListCell key="secondary content">{links}</DataListCell> ]} /> </DataListItemRow> </DataListItem> ) })} </DataList> );
www/components/add-poo.js
capaj/postuj-hovna
import React from 'react' import ImgUploader from './img-uploader' import GoogleMap from './google-map' import {photo} from '../services/moonridge' import backend from '../services/moonridge' export default class AddPoo extends React.Component { constructor(...props) { super(...props) this.state = {} } addImage = (imageData) => { this.setState({error: null, image: imageData}) } submit = () => { console.log('submit', this) this.setState({inProgress: true}) var imgBase64 = this.state.image var image = imgBase64.substr(imgBase64.indexOf(',') + 1) backend.rpc('savePhoto')(image).then(photoId => { const GPS = this.state.loc var toCreate = { loc: [GPS.lat, GPS.lng], photoIds: [photoId], type: 'poo' } return photo.create(toCreate).then(created => { location.hash = `/poo/${created._id}` }) }, err => { this.setState({error: err}) console.log('err', err) }) } addLoc = (GPS) => { this.setState({loc: GPS}) } render() { var submitBtn var state = this.state if (state.loc && state.image && !state.inProgress) { submitBtn = <div className='post button ok clickable' onClick={this.submit}> <span className='glyphicon glyphicon-ok'/> </div> } var alert if (state.error) { alert = <div className='alert'> {state.error} </div> } var map if (state.loc) { map = <GoogleMap center={state.loc} zoom={17} containerClass='small-map'></GoogleMap> } return <div className='container add-form'> <div className='post item'> {map} </div> <ImgUploader onGPSRead={this.addLoc} onImageRead={this.addImage} icon={'img/poo-plain.svg'}/> {submitBtn} {alert} </div> } } AddPoo.defaultProps = { zoom: 9 }
readable/src/containers/PostDetail.js
custertian/readable
import React from 'react' import {Link} from 'react-router-dom' import {connect} from 'react-redux' import { Button, Card, Layout, Menu, Breadcrumb, Input, Tree } from 'antd' const {TextArea} = Input; const {Header, Content, Footer} = Layout const TreeNode = Tree.TreeNode class PostDetail extends React.Component { onSelect = (selectedKeys, info) => { console.log('selected', selectedKeys, info); } render() { const {post, select} = this.props console.log(post) if (!post) { // this.loading = true return <div>Loading ...</div> } return ( <Layout className="layout"> <Header> <div className="logo"/> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']} style={{ lineHeight: '64px', fontSize: '20px' }}> <Menu.Item key="1">Readable[Detail]</Menu.Item> </Menu> </Header> <Content style={{ padding: '0 50px' }}> <Breadcrumb style={{ margin: '12px 0' }}> <Breadcrumb.Item> <Link to='/'>Home</Link> </Breadcrumb.Item> <Breadcrumb.Item> <Link to='/'>Posts</Link> </Breadcrumb.Item> <Breadcrumb.Item>detail</Breadcrumb.Item> </Breadcrumb> <div style={{ background: '#fff', padding: 24, minHeight: 280 }}> {post.map((post) => { if (post.id === select) { return ( <Card style={{ fontSize: 20 }} key={post.id}> <div> <p>Title: {post.title}</p> <p>Body: {post.body}</p> <p>timestamp: {post.timestamp}</p> <p>Vote score: {post.voteScore}</p> <p>Author: {post.author}</p> <p>comments number: </p> </div> </Card> ) } })} <div style={{ margin: '24px 0' }}> <TextArea rows={6} placeholder="请输入评论..." size="large"/> <Button type="primary" ghost style={{ margin: '24px 0', float: 'right' }}>comment</Button> </div> <Tree showLine defaultExpandedKeys={['0-0-0']} onSelect={this.onSelect}> <TreeNode title="parent 1" key="0-0"> <TreeNode title="parent 1-0" key="0-0-0"> <TreeNode title="leaf" key="0-0-0-0"/> <TreeNode title="leaf" key="0-0-0-1"/> <TreeNode title="leaf" key="0-0-0-2"/> </TreeNode> <TreeNode title="parent 1-1" key="0-0-1"> <TreeNode title="leaf" key="0-0-1-0"/> </TreeNode> <TreeNode title="parent 1-2" key="0-0-2"> <TreeNode title="leaf" key="0-0-2-0"/> <TreeNode title="leaf" key="0-0-2-1"/> </TreeNode> </TreeNode> </Tree> </div> </Content> <Footer style={{ textAlign: 'center' }}> Custer Tian ©2017 Created by Custer Tian </Footer> </Layout> ) } } const mapStateToProps = (state, ownProps) => { console.log('state', state) console.log('ownProps', ownProps.match.params.post_id) console.log('post', state.posts[ownProps.match.params.post_id]) return {post: state.posts, select: ownProps.match.params.post_id} } export default connect(mapStateToProps)(PostDetail)