path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
frontend/src/app/components/Header.js
dannycoates/testpilot
import React from 'react'; import { Link } from 'react-router'; import classnames from 'classnames'; import LayoutWrapper from './LayoutWrapper'; import RetireConfirmationDialog from './RetireConfirmationDialog'; export default class Header extends React.Component { constructor(props) { super(props); this.closeTimer = null; this.close = this.close.bind(this); this.dismissRetireDialog = this.dismissRetireDialog.bind(this); this.state = { showRetireDialog: false }; } shouldRenderSettingsMenu() { return this.props.hasAddon; } showSettingsMenu() { return this.state.showSettings; } renderSettingsMenu() { if (this.shouldRenderSettingsMenu()) { return ( <div id="settings"> <div className="settings-contain"> <div className={classnames(['button', 'outline', 'settings-button'], { active: this.showSettingsMenu() })} onClick={e => this.toggleSettings(e)} data-l10n-id="menuTitle">Settings</div> {this.showSettingsMenu() && <div className="settings-menu" onClick={e => this.settingsClick(e)}> <ul> <li><a onClick={e => this.wiki(e)} data-l10n-id="menuWiki" href="https://wiki.mozilla.org/Test_Pilot" target="_blank">Test Pilot Wiki</a></li> <li><a onClick={() => this.discuss()} data-l10n-id="menuDiscuss" href="https://discourse.mozilla-community.org/c/test-pilot" target="_blank">Discuss Test Pilot</a></li> <li><a onClick={e => this.fileIssue(e)} data-l10n-id="menuFileIssue" href="https://github.com/mozilla/testpilot/issues/new" target="_blank">File an Issue</a></li> <li><hr /></li> <li><a onClick={e => this.retire(e)} data-l10n-id="menuRetire">Uninstall Test Pilot</a></li> </ul> </div>} </div> </div> ); } return null; } dismissRetireDialog() { this.setState({ showRetireDialog: false }); } renderRetireDialog() { if (this.state.showRetireDialog) { return ( <RetireConfirmationDialog onDismiss={this.dismissRetireDialog} {...this.props} /> ); } return null; } render() { return ( <div> {this.renderRetireDialog()} <header id="main-header"> <LayoutWrapper flexModifier="row-between-top"> <h1> <Link to="/" className="wordmark" data-l10n-id="siteName">Firefox Test Pilot</Link> </h1> {this.renderSettingsMenu()} </LayoutWrapper> </header> </div> ); } // HACK: We want to close the settings menu on any click outside the menu. // However, a manually-attached event listener on document.body seems to fire // the 'close' event before any other clicks register inside the settings // menu. So, here's a kludge to schedule a menu close on any click, but // cancel if the click was inside the menu. Sounds backwards, but it works. componentDidMount() { document.body.addEventListener('click', this.close); } componentWillUnmount() { if (this.closeTimer) { clearTimeout(this.closeTimer); } document.body.removeEventListener('click', this.close); } close() { if (!this.state.showSettings) { return; } this.closeTimer = setTimeout(() => this.setState({ showSettings: false }), 10); } settingsClick() { if (this.closeTimer) { clearTimeout(this.closeTimer); } } toggleSettings(ev) { ev.stopPropagation(); this.props.sendToGA('event', { eventCategory: 'Menu Interactions', eventAction: 'drop-down menu', eventLabel: 'Toggle Menu' }); if (this.state.showSettings) { this.close(ev); } else { this.setState({ showSettings: true }); } } retire(evt) { evt.preventDefault(); this.props.sendToGA('event', { eventCategory: 'Menu Interactions', eventAction: 'drop-down menu', eventLabel: 'Retire' }); this.setState({ showRetireDialog: true }); this.close(); } discuss() { this.props.sendToGA('event', { eventCategory: 'Menu Interactions', eventAction: 'drop-down menu', eventLabel: 'Discuss' }); this.close(); } wiki() { this.props.sendToGA('event', { eventCategory: 'Menu Interactions', eventAction: 'drop-down menu', eventLabel: 'wiki' }); this.close(); } fileIssue() { this.props.sendToGA('event', { eventCategory: 'Menu Interactions', eventAction: 'drop-down menu', eventLabel: 'file issue' }); this.close(); } } Header.propTypes = { uninstallAddon: React.PropTypes.func.isRequired, sendToGA: React.PropTypes.func.isRequired, openWindow: React.PropTypes.func.isRequired, hasAddon: React.PropTypes.bool, forceHideSettings: React.PropTypes.bool };
src/routes/Home/components/HomeView.js
dmassaneiro/integracao-continua
import React from 'react' import DuckImage from '../assets/Duck.jpg' import './HomeView.scss' export const HomeView = () => ( <div> <h4>Welcome!</h4> <img alt='This is a duck, because Redux!' className='duck' src={DuckImage} /> </div> ) export default HomeView
src/components/Home/Shows/Views/Desktop/tpl.js
HopeUA/tv.hope.ua-react
/** * [IL] * Library Import */ import React from 'react'; import Slider from 'vendor/Slider/SliderComponent'; /** * [IS] * Style Import */ import Styles from './Styles/main.scss'; import Grids from 'theme/Grid.scss'; function Desktop() { const styles = { backgroundImage: 'url(https://cdn.hope.ua/media/shows/ALKU/episodes/02816/ALKU02816-cover.jpg)' }; const properties = { slider: Styles.slider, arrowLeft: Styles.arrowLeft, arrowRight: Styles.arrowRight, list: Styles.list, wrap: Styles.wrap, arrow: Styles.arrow }; return ( <section className={ Grids.container }> <section className={ Styles.showsComponent }> <h1 className={ Styles.title }>Популярные программы</h1> <Slider { ...properties }> <div className={ Styles.row }> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> </div> </Slider> </section> </section> ); } /** * [IE] * Export */ export default Desktop;
src/js/components/input_error_body.js
frig-js/frigging-bootstrap
import React from 'react' export default class InputErrorBody extends React.Component { static propTypes = { msg: React.PropTypes.string.isRequired, i: React.PropTypes.number, } static defaultProps = { i: 0, } render() { return ( <span className="help-block" key={`error-${this.props.i}`}> <i className="fa fa-exclamation-circle" key={`error-label-${this.props.i}`} ></i> {' '} {this.props.msg} </span> ) } }
admin/client/App/screens/Home/components/ListTile.js
xyzteam2016/keystone
import React from 'react'; import { Link } from 'react-router'; /** * Displays information about a list and lets you create a new one. */ var ListTile = React.createClass({ propTypes: { count: React.PropTypes.string, href: React.PropTypes.string, label: React.PropTypes.string, path: React.PropTypes.string, spinner: React.PropTypes.object, }, render () { var opts = { 'data-list-path': this.props.path, }; return ( <div className="dashboard-group__list" {...opts}> <span className="dashboard-group__list-inner"> <Link to={this.props.href} className="dashboard-group__list-tile"> <div className="dashboard-group__list-label">{this.props.label}</div> <div className="dashboard-group__list-count">{this.props.spinner || this.props.count}</div> </Link> {/* If we want to create a new list, we append ?create, which opens the create form on the new page! */} <Link to={this.props.href + '?create'} className="dashboard-group__list-create octicon octicon-plus" title="Create" tabIndex="-1" /> </span> </div> ); }, }); module.exports = ListTile;
client/components/Breakpoints.js
HelpAssistHer/help-assist-her
import React from 'react' import Responsive from 'react-responsive' const PHONE_MIN_BREAKPOINT = 320 const PHONE_MAX_BREAKPOINT = 439 const BIG_PHONE_MIN_BREAKPOINT = 440 const BIG_PHONE_MAX_BREAKPOINT = 699 const TABLET_MIN_BREAKPOINT = 700 const TABLET_MAX_BREAKPOINT = 1099 const DESKTOP_MIN_BREAKPOINT = 1100 const Desktop = (props) => ( <Responsive {...props} minWidth={DESKTOP_MIN_BREAKPOINT} /> ) const Tablet = (props) => ( <Responsive {...props} minWidth={TABLET_MIN_BREAKPOINT} maxWidth={TABLET_MAX_BREAKPOINT} /> ) const BigPhone = (props) => ( <Responsive {...props} minWidth={BIG_PHONE_MIN_BREAKPOINT} maxWidth={BIG_PHONE_MAX_BREAKPOINT} /> ) const Phone = (props) => ( <Responsive {...props} minWidth={PHONE_MIN_BREAKPOINT} maxWidth={PHONE_MAX_BREAKPOINT} /> ) export { Desktop, Tablet, BigPhone, Phone, DESKTOP_MIN_BREAKPOINT, TABLET_MIN_BREAKPOINT, BIG_PHONE_MIN_BREAKPOINT, PHONE_MIN_BREAKPOINT, }
src/schema/test.dataSchema.js
jiangxy/react-antd-admin
import React from 'react'; import {Icon} from 'antd'; // 定义某个表的dataSchema, 结构跟querySchema很相似, 见下面的例子 // 注意: 所有的key不能重复 // 这个配置不只决定了table的schema, 也包括用于新增/删除的表单的schema module.exports = [ { key: 'id', // 传递给后端的key title: 'ID', // 前端显示的名字 // 其实dataType对前端的意义不大, 更重要的是生成后端接口时要用到, 所以要和DB中的类型一致 // 对java而言, int/float/varchar/datetime会映射为Long/Double/String/Date dataType: 'int', // 数据类型, 目前可用的: int/float/varchar/datetime // 这一列是否是主键? // 如果不指定主键, 不能update/delete, 但可以insert // 如果指定了主键, insert/update时不能填写主键的值; // 只有int/varchar可以作为主键, 但是实际上主键一般都是自增id primary: true, // 可用的showType: normal/radio/select/checkbox/multiSelect/textarea/image/file/cascader showType: 'normal', // 默认是normal, 就是最普通的输入框 showInTable: true, // 这一列是否要在table中展示, 默认true disabled: false, // 表单中这一列是否禁止编辑, 默认false // 扩展接口, 决定了这一列渲染成什么样子 render: (text, record) => text, }, { key: 'name', title: '用户名', dataType: 'varchar', // 对于普通的input框, 可以设置addonBefore/addonAfter placeholder: '请输入用户名', addonBefore: (<Icon type="user"/>), addonAfter: '切克闹', defaultValue: 'foolbear', // 默认值, 只在insert时生效, update时不生效 }, { key: 'weight', title: '体重(千克)', dataType: 'int', min: 10, defaultValue: 70, // 默认值 disabled: true, showInForm: false, // 这一列是否要在表单中展示, 默认true. 这种列一般都是不需要用户输入的, DB就会给一个默认值那种 }, { key: 'gender', title: '性别', dataType: 'int', showType: 'radio', options: [{key: '1', value: '男'}, {key: '2', value: '女'}], defaultValue: '1', disabled: true, }, { key: 'marriage', title: '婚否', dataType: 'varchar', showType: 'select', options: [{key: 'yes', value: '已婚'}, {key: 'no', value: '未婚'}], // 对于dataSchema可以设置校验规则, querySchema不能设置 // 设置校验规则, 参考https://github.com/yiminghe/async-validator#rules validator: [{type: 'string', required: true, message: '必须选择婚否!'}], }, { key: 'interest', title: '兴趣爱好', dataType: 'int', showType: 'checkbox', options: [{key: '1', value: '吃饭'}, {key: '2', value: '睡觉'}, {key: '3', value: '打豆豆'}], defaultValue: ['1', '2'], validator: [{type: 'array', required: true, message: '请至少选择一项兴趣'}], width: 120, // 指定这一列的宽度 }, { key: 'good', title: '优点', dataType: 'varchar', showType: 'multiSelect', options: [{key: 'lan', value: '懒'}, {key: 'zhai', value: '宅'}], validator: [{type: 'array', required: true, message: '请选择优点'}], }, { key: 'pic1', title: '头像', dataType: 'varchar', showType: 'image', // 后端必须提供图片上传接口 showInTable: false, }, { key: 'desc', title: '个人简介', dataType: 'varchar', showType: 'textarea', // 用于编辑大段的文本 showInTable: false, defaultValue: '个人简介个人简介个人简介', validator: [{type: 'string', max: 20, message: '最长20个字符'}], }, { key: 'score', title: '分数', dataType: 'int', max: 99, min: 9, }, { key: 'gpa', title: 'GPA', dataType: 'float', max: 9.9, placeholder: '哈哈', width: 50, }, { key: 'birthday', title: '生日', // 对于日期类型要注意下, 在js端日期被表示为yyyy-MM-dd HH:mm:ss的字符串, 在java端日期被表示为java.util.Date对象 // fastjson反序列化时可以自动识别 // 序列化倒是不用特别配置, 看自己需求, fastjson会序列化为一个字符串, 前端原样展示 dataType: 'datetime', // 对于datetime而言, 配置showType是无意义的 placeholder: 'happy!', }, { key: 'xxday', title: 'xx日期', dataType: 'datetime', defaultValue: '2017-01-01 11:22:33', showInTable: false, showInForm: false, // 这个只是测试下...如果一列在table和form中都不出现, 那就不如直接去掉. // 另外showInForm=false时, 很多针对form的字段都没意义了, 比如defaultValue/placeholder/validator等等 }, ];
DataRepository.js
dcy0701/ReactNativeServer
'use strict'; import { AsyncStorage, } from 'react-native'; import React, { Component } from 'react'; var API_COVER_URL = "http://news-at.zhihu.com/api/4/start-image/1080*1776"; var KEY_COVER = '@Cover'; function parseDateFromYYYYMMdd(str) { if (!str) return new Date(); return new Date(str.slice(0, 4),str.slice(4, 6) - 1,str.slice(6, 8)); } Date.prototype.yyyymmdd = function() { var yyyy = this.getFullYear().toString(); var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based var dd = this.getDate().toString(); return yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0]); // padding }; function DataRepository() { // Singleton pattern if (typeof DataRepository.instance === 'object') { return DataRepository.instance; } DataRepository.instance = this; } DataRepository.prototype._safeStorage = function(key: string) { return new Promise((resolve, reject) => { AsyncStorage.getItem(key, (error, result) => { var retData = JSON.parse(result); if (error) { console.error(error); resolve(null); } else { resolve(retData); } }); }); }; DataRepository.prototype.getCover = function() { return this._safeStorage(KEY_COVER); } DataRepository.prototype.updateCover = function() { fetch(API_COVER_URL) .then((response) => response.json()) .then((responseData) => { AsyncStorage.setItem(KEY_COVER, JSON.stringify(responseData)); }) .catch((error) => { console.error(error); }) .done(); }; module.exports = DataRepository;
src/components/index.js
ctrl-alt-p/born-to-sell
import React from 'react'; import App from './app'; import CommentBox from './comment_box'; import CommentList from './comment_list'; export default App; export default CommentList; export default CommentBox;
docs/src/PropTable.js
herojobs/react-bootstrap
import merge from 'lodash/object/merge'; import React from 'react'; import Glyphicon from '../../src/Glyphicon'; import Label from '../../src/Label'; import Table from '../../src/Table'; let cleanDocletValue = str => str.trim().replace(/^\{/, '').replace(/\}$/, ''); let capitalize = str => str[0].toUpperCase() + str.substr(1); function getPropsData(component, metadata){ let componentData = metadata[component] || {}; let props = componentData.props || {}; if (componentData.composes) { componentData.composes.forEach(other => { if (other !== component) { props = merge({}, getPropsData(other, metadata), props); } }); } if (componentData.mixins) { componentData.mixins.forEach( other => { if (other !== component && componentData.composes.indexOf(other) === -1) { props = merge({}, getPropsData(other, metadata), props); } }); } return props; } const PropTable = React.createClass({ contextTypes: { metadata: React.PropTypes.object }, componentWillMount(){ this.propsData = getPropsData(this.props.component, this.context.metadata); }, render(){ let propsData = this.propsData; if ( !Object.keys(propsData).length){ return <span/>; } return ( <Table bordered striped className="prop-table"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> { this._renderRows(propsData) } </tbody> </Table> ); }, _renderRows(propsData){ return Object.keys(propsData) .sort() .filter(propName => propsData[propName].type && !propsData[propName].doclets.private ) .map(propName => { let propData = propsData[propName]; return ( <tr key={propName} className='prop-table-row'> <td> {propName} {this.renderRequiredLabel(propData)} </td> <td> <div>{this.getType(propData)}</div> </td> <td>{propData.defaultValue}</td> <td> { propData.doclets.deprecated && <div className='prop-desc-heading'> <strong className='text-danger'>{'Deprecated: ' + propData.doclets.deprecated + ' '}</strong> </div> } { this.renderControllableNote(propData, propName) } <div className='prop-desc' dangerouslySetInnerHTML={{__html: propData.descHtml }} /> </td> </tr> ); }); }, renderRequiredLabel(prop) { if (!prop.required) { return null; } return ( <Label>required</Label> ); }, renderControllableNote(prop, propName){ let controllable = prop.doclets.controllable; let isHandler = this.getDisplayTypeName(prop.type.name) === 'function'; if (!controllable) { return false; } let text = isHandler ? ( <span> controls <code>{controllable}</code> </span> ) : ( <span> controlled by: <code>{controllable}</code>, initial prop: <code>{'default' + capitalize(propName)}</code> </span> ); return ( <div className='prop-desc-heading'> <small> <em className='text-info'> <Glyphicon glyph='info-sign'/> &nbsp;{ text } </em> </small> </div> ); }, getType(prop) { let type = prop.type || {}; let name = this.getDisplayTypeName(type.name); let doclets = prop.doclets || {}; switch (name) { case 'object': return name; case 'union': return type.value.reduce((current, val, i, list) => { let item = this.getType({ type: val }); if (React.isValidElement(item)) { item = React.cloneElement(item, {key: i}); } current = current.concat(item); return i === (list.length - 1) ? current : current.concat(' | '); }, []); case 'array': let child = this.getType({ type: type.value }); return <span>{'array<'}{ child }{'>'}</span>; case 'enum': return this.renderEnum(type); case 'custom': return cleanDocletValue(doclets.type || name); default: return name; } }, getDisplayTypeName(typeName) { if (typeName === 'func') { return 'function'; } else if (typeName === 'bool') { return 'boolean'; } else { return typeName; } }, renderEnum(enumType) { const enumValues = enumType.value || []; const renderedEnumValues = []; enumValues.forEach(function renderEnumValue(enumValue, i) { if (i > 0) { renderedEnumValues.push( <span key={`${i}c`}>, </span> ); } renderedEnumValues.push( <code key={i}>{enumValue}</code> ); }); return ( <span>one of: {renderedEnumValues}</span> ); } }); export default PropTable;
src/components/LoggedInPage.js
KingCountySAR/database-frontend
import React from 'react'; import { withRouter } from 'react-router-dom'; import { CallbackComponent } from 'redux-oidc'; import userManager from '../userManager'; class CallbackPage extends React.Component { successCallback = () => { this.props.history.push(sessionStorage.redirect || '/'); } render() { return ( <CallbackComponent userManager={userManager} successCallback={this.successCallback} errorCallback={this.successCallback}> <div> Redirecting... </div> </CallbackComponent> ); } } export default withRouter(CallbackPage);
src/svg-icons/action/account-box.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAccountBox = (props) => ( <SvgIcon {...props}> <path d="M3 5v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H5c-1.11 0-2 .9-2 2zm12 4c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3zm-9 8c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6v-1z"/> </SvgIcon> ); ActionAccountBox = pure(ActionAccountBox); ActionAccountBox.displayName = 'ActionAccountBox'; ActionAccountBox.muiName = 'SvgIcon'; export default ActionAccountBox;
7.Middlewares/src/components/app.js
Branimir123/Learning-React
import React, { Component } from 'react'; import UserList from './user_list'; export default class App extends Component { render() { return ( <div> <UserList /> </div> ); } }
src/app/components/Home.js
maria-robobug/react-js-basics
import React from 'react'; export class Home extends React.Component { constructor (props) { super(); this.state = { age: props.initialAge, status: 0, homeLink: props.initialLinkName }; setTimeout(() => { this.setState({ status: 1 }); },3000); console.log('Constructor'); } componentWillMount () { console.log('Component will mount'); } componentDidMount () { console.log('Component did mount'); } componentWillReceiveProps (nextProps) { console.log('Component will receive props', nextProps); } shouldComponentUpdate (nextProps, nextState) { console.log('Should Component update', nextProps, nextState); return true; } componentWillUpdate (nextProps, nextState) { console.log('Component will update', nextProps, nextState); } componentDidUpdate (previousProps, previousState) { console.log('Component did update', previousProps, previousState); } componentWillUnmount () { console.log('Component will unmount'); } onMakeOlder () { this.setState({ age: this.state.age + 3 }); } onChangeLink () { this.props.changeLink(this.state.homeLink); } onHandleChange (event) { this.setState({ homeLink: event.target.value }); } render () { return ( <div> <p>Your name is {this.props.name}, your age is {this.state.age}</p> <p>Status: {this.state.status}</p> <hr/> <button onClick={() => this.onMakeOlder()} className="btn btn-primary">Make me older!</button> <hr/> <button onClick={this.props.greet} className="btn btn-primary">Greet</button> <hr/> <input type="text" value={this.state.homeLink} onChange={(event) => this.onHandleChange(event)} /> <button onClick={(newName) => this.onChangeLink(newName)} className="btn btn-primary">Change Header</button> </div> ); } } Home.propTypes = { name: React.PropTypes.string, initialAge: React.PropTypes.number, greet: React.PropTypes.func };
app/components/Journal.js
csreyes/TLCJournal
import React from 'react'; import {Link} from 'react-router'; import {Pager, PageItem} from 'react-bootstrap'; import moment from 'moment'; import JournalStore from '../stores/JournalStore' import JournalActions from '../actions/JournalActions'; // import HomeStore from '../stores/HomeStore' // import HomeActions from '../actions/HomeActions'; import JournalMainContainer from './JournalMainContainer'; class Journal extends React.Component { constructor(props) { super(props); this.state = JournalStore.getState(); } componentDidMount() { JournalStore.listen(this.onChange.bind(this)); } componentWillUnmount() { JournalStore.unlisten(this.onChange.bind(this)); } onChange(state) { this.setState(state) } updateDate(update) { JournalActions.updateDate(update); } render() { var weeklyQuote = 'Plan well and follow through. It\'ll take you places you didn\'t know you could go.' return ( <div className='journal-outer-container test'> <div className='journal-outer-container-header test'> <Pager className='journal-outer-container-header-pager test'> <PageItem onClick={this.updateDate.bind(this, -1)} className='journal-outer-container-header-page-item test' previous href='#'>&larr;</PageItem> <span className='journal-outer-container-header-current-date'>{this.state.formattedCurrentDate}</span> <PageItem onClick={this.updateDate.bind(this, 1)}className='journal-outer-container-header-page-item test' next href='#'>&rarr;</PageItem> </Pager> <h3 className='journal-outer-container-header-innertext'>TLC Journal</h3> </div> <JournalMainContainer /> <div className='journal-footer'> <span className='journal-footer-text'>{weeklyQuote}</span> </div> </div> ); } } export default Journal;
src/components/RefreshableListView.js
yogakurniawan/phoney-mobile
/* * Component Name: RefreshableListView * Author: Simar Singh (github/iSimar) * Description: This component is used to render a listview that can be * pulled down to refresh * Dependencies: * -> react-native-gifted-listview 0.0.15 (https://github.com/FaridSafi/react-native-gifted-listview) * * Properties: * -> renderRow * render function for rows or cells in the listview * -> onRefresh * used for filling the listview on ethier pull to refresh or pagination (load more), * it is called with 2 arugments page number and callback. see react-native-gifted-listview docs. * -> backgroundColor (optional) * default = '#FFFFFF', background color of the listview * -> loadMoreText (optional) * default = '+', text used at the end of the listview - pagination * -> renderHeader (optional) * rendering not sticky header of the listview * Example: * <RefreshableListView renderRow={(row)=>this.renderListViewRow(row)} * renderHeader={this.renderListViewHeader} * onRefresh={(page, callback)=>this.listViewOnRefresh(page, callback)} * backgroundColor={'#F6F6EF'} * loadMoreText={'Load More...'}/> */ import React from 'react'; import { Platform, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import GiftedListView from 'react-native-gifted-listview'; export default class RefreshableListView extends React.Component { static propTypes = { renderRow: React.PropTypes.func, backgroundColor: React.PropTypes.string, loadMoreText: React.PropTypes.string, renderHeader: React.PropTypes.func, onRefresh: React.PropTypes.func }; getInititalState() { const { renderRow, backgroundColor, loadMoreText, renderHeader } = this.props; return { renderRow, backgroundColor: backgroundColor ? backgroundColor : '#FFFFFF', loadMoreText: loadMoreText ? loadMoreText : 'Load More...', renderHeader: renderHeader ? renderHeader : null }; } onRefresh(page = 1, callback) { this.props.onRefresh(page, callback); } renderRow(row) { return this.state.renderRow(row); } renderPaginationWaitingView(callback) { return ( <TouchableOpacity style={styles.paginationView} onPress={callback}> <Text style={styles.loadMoreText}> {this.state.loadMoreText} </Text> </TouchableOpacity> ); } renderHeaderView() { if (this.state.renderHeader) { return this.props.renderHeader(); } return (null); } renderPaginationAllLoadedView() { return ( <View /> ); } render() { return ( <View style={[styles.container, { backgroundColor: this.state.backgroundColor }, this.props.style]}> <View style={styles.navBarSpace}> <GiftedListView rowView={this.renderRow} onFetch={this.onRefresh} paginationAllLoadedView={this.renderPaginationAllLoadedView} paginationWaitingView={this.renderPaginationWaitingView} headerView={this.renderHeaderView} PullToRefreshViewAndroidProps={{ colors: ['#F6F6EF'], progressBackgroundColor: '#FF6600' }} customStyles={{ refreshableView: { backgroundColor: this.state.backgroundColor, justifyContent: 'flex-end', paddingBottom: 12 }, paginationView: { backgroundColor: this.state.backgroundColor, height: 60 } }} /> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1 }, navBarSpace: { height: (Platform.OS !== 'android') ? 64 : 0 }, rowContainer: { paddingRight: 15, paddingLeft: 10, flexDirection: 'row' }, paginationView: { justifyContent: 'center', alignItems: 'center', paddingTop: 20, paddingBottom: 20 }, loadMoreText: { fontSize: 15, color: 'gray' } });
src/routes/admin/Admin.js
ben-miller/adddr.io
/** * adddr (https://www.adddr.io/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Admin.css'; class Admin extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1> {this.props.title} </h1> <p>...</p> </div> </div> ); } } export default withStyles(s)(Admin);
src/index.js
superpersonman/react-raf-parallax
import React from 'react'; var lastTime = 0, lastTimeSelected = 0, elementCache = []; export default React.createClass({ getDefaultProps() { return { perspective: 100, x: false, y: true, relativeToParent: true } }, componentDidMount() { this._raf = window.requestAnimationFrame(this.tick); }, componentWillUnmount() { window.cancelAnimationFrame(this._raf); }, tick(t) { // Cap updates to near 60fps if (t-lastTime < 1000/60) { window.requestAnimationFrame(this.tick); lastTime = t; return; } // Only update element cache every 500ms to avoid bottlenecks // caused by repeatedly selecting elements if (t-lastTimeSelected > 500) { elementCache = this.node.getElementsByClassName('parallax'); lastTimeSelected = t; } var depthElements = elementCache, yOffset = window.pageYOffset, xOffset = window.pageXOffset, viewportHeight = window.innerHeight, viewportWidth = window.innerWidth, i = depthElements.length - 1, el, elOffsetX, elOffsetY, depth, x, y, parent, parentRect; for (i; i >= 0; i--) { el = depthElements[i]; depth = el.getAttribute('data-parallax-depth'); elOffsetX = el.getAttribute('data-parallax-offset-x') || 0; elOffsetY = el.getAttribute('data-parallax-offset-y') || 0; parent = el.parentElement; if (this.props.relativeToParent && parent) { parentRect = parent.getBoundingClientRect(); y = this.props.y ? -parentRect.top * depth / this.props.perspective : 0; x = this.props.x ? -parentRect.left * depth / this.props.perspective : 0; } else { y = this.props.y ? yOffset * depth / this.props.perspective : 0; x = this.props.x ? xOffset * depth / this.props.perspective : 0; } x += +elOffsetX; y += +elOffsetY; el.style.transform = 'translate3d('+ x +'px,'+ y +'px, 0)'; } lastTime = t; window.requestAnimationFrame(this.tick); }, render() { return ( <div className='parallax' ref={(el) => {this.node = el}}> {this.props.children} </div> ); } });
dist/lib/carbon-fields/assets/js/fields/components/checkbox/index.js
ArtFever911/statrer-kit
/** * The external dependencies. */ import React from 'react'; import PropTypes from 'prop-types'; import { compose, withProps, withHandlers, setStatic } from 'recompose'; /** * The internal dependencies. */ import Field from 'fields/components/field'; import withStore from 'fields/decorators/with-store'; import withSetup from 'fields/decorators/with-setup'; import { TYPE_CHECKBOX } from 'fields/constants'; /** * Render a checkbox input field. * * @param {Object} props * @param {String} props.name * @param {Object} props.field * @param {Boolean} props.checked * @param {Function} props.handleChange * @return {React.Element} */ export const CheckboxField = ({ name, field, checked, handleChange }) => { return <Field field={field} showLabel={false} showRequiredLabel={false}> <label> <input type="checkbox" name={name} value={field.option_value} checked={checked} disabled={!field.ui.is_visible} onChange={handleChange} {...field.attributes} /> {field.option_label} { field.required ? <span className="carbon-required">*</span> : null } </label> </Field>; }; /** * Validate the props. * * @type {Object} */ CheckboxField.propTypes = { name: PropTypes.string, field: PropTypes.shape({ id: PropTypes.string, value: PropTypes.bool, option_value: PropTypes.string, attributes: PropTypes.object, }), checked: PropTypes.bool, handleChange: PropTypes.func, }; /** * The enhancer. * * @type {Function} */ export const enhance = compose( /** * Connect to the Redux store. */ withStore(), /** * Attach the setup hooks. */ withSetup(), /** * Pass some props to the component. */ withProps(({ field }) => ({ checked: field.value, })), /** * Pass some handlers to the component. */ withHandlers({ handleChange: ({ field, setFieldValue }) => ({ target }) => { setFieldValue(field.id, target.checked); }, }) ); export default setStatic('type', [ TYPE_CHECKBOX, ])(enhance(CheckboxField));
app/javascript/mastodon/features/public_timeline/index.js
primenumber/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { expandPublicTimeline } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import ColumnSettingsContainer from './containers/column_settings_container'; import { connectPublicStream } from '../../actions/streaming'; const messages = defineMessages({ title: { id: 'column.public', defaultMessage: 'Federated timeline' }, }); const mapStateToProps = (state, { columnId }) => { const uuid = columnId; const columns = state.getIn(['settings', 'columns']); const index = columns.findIndex(c => c.get('uuid') === uuid); const onlyMedia = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'public', 'other', 'onlyMedia']); const onlyRemote = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyRemote']) : state.getIn(['settings', 'public', 'other', 'onlyRemote']); const timelineState = state.getIn(['timelines', `public${onlyMedia ? ':media' : ''}`]); return { hasUnread: !!timelineState && timelineState.get('unread') > 0, onlyMedia, onlyRemote, }; }; export default @connect(mapStateToProps) @injectIntl class PublicTimeline extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static defaultProps = { onlyMedia: false, }; static propTypes = { dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, intl: PropTypes.object.isRequired, columnId: PropTypes.string, multiColumn: PropTypes.bool, hasUnread: PropTypes.bool, onlyMedia: PropTypes.bool, onlyRemote: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch, onlyMedia, onlyRemote } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn(onlyRemote ? 'REMOTE' : 'PUBLIC', { other: { onlyMedia, onlyRemote } })); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch, onlyMedia, onlyRemote } = this.props; dispatch(expandPublicTimeline({ onlyMedia, onlyRemote })); this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote })); } componentDidUpdate (prevProps) { if (prevProps.onlyMedia !== this.props.onlyMedia || prevProps.onlyRemote !== this.props.onlyRemote) { const { dispatch, onlyMedia, onlyRemote } = this.props; this.disconnect(); dispatch(expandPublicTimeline({ onlyMedia, onlyRemote })); this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote })); } } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } setRef = c => { this.column = c; } handleLoadMore = maxId => { const { dispatch, onlyMedia, onlyRemote } = this.props; dispatch(expandPublicTimeline({ maxId, onlyMedia, onlyRemote })); } render () { const { intl, shouldUpdateScroll, columnId, hasUnread, multiColumn, onlyMedia, onlyRemote } = this.props; const pinned = !!columnId; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='globe' active={hasUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <ColumnSettingsContainer columnId={columnId} /> </ColumnHeader> <StatusListContainer timelineId={`public${onlyRemote ? ':remote' : ''}${onlyMedia ? ':media' : ''}`} onLoadMore={this.handleLoadMore} trackScroll={!pinned} scrollKey={`public_timeline-${columnId}`} emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other servers to fill it up' />} shouldUpdateScroll={shouldUpdateScroll} bindToDocument={!multiColumn} /> </Column> ); } }
components/Html.js
hobinjk/illuminate
import React from 'react'; class Html extends React.Component { render() { return ( <html> <head> <meta charSet="utf-8" /> <title>{this.props.title}</title> <meta name="viewport" content="width=device-width, user-scalable=no" /> <link rel="stylesheet" href="/assets/style.css" /> </head> <body> <div id="app" dangerouslySetInnerHTML={{__html: this.props.markup}}></div> </body> <script dangerouslySetInnerHTML={{__html: this.props.state}}></script> <script src={'/public/js/' + this.props.clientFile}></script> </html> ); } } export default Html;
packages/react-events/src/FocusScope.js
VioletLife/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type { ReactResponderEvent, ReactResponderContext, } from 'shared/ReactTypes'; import React from 'react'; type FocusScopeProps = { autoFocus: Boolean, contain: Boolean, restoreFocus: Boolean, }; type FocusScopeState = { nodeToRestore: null | HTMLElement, currentFocusedNode: null | HTMLElement, }; const targetEventTypes = [{name: 'keydown', passive: false}]; const rootEventTypes = [{name: 'focus', passive: true}]; function focusElement(element: ?HTMLElement) { if (element != null) { try { element.focus(); } catch (err) {} } } function getFirstFocusableElement( context: ReactResponderContext, state: FocusScopeState, ): ?HTMLElement { const elements = context.getFocusableElementsInScope(); if (elements.length > 0) { return elements[0]; } } const FocusScopeResponder = { targetEventTypes, rootEventTypes, createInitialState(): FocusScopeState { return { nodeToRestore: null, currentFocusedNode: null, }; }, allowMultipleHostChildren: true, stopLocalPropagation: false, onEvent( event: ReactResponderEvent, context: ReactResponderContext, props: FocusScopeProps, state: FocusScopeState, ) { const {type, nativeEvent} = event; const hasOwnership = context.hasOwnership() || context.requestResponderOwnership(); if (!hasOwnership) { return; } if (type === 'keydown' && nativeEvent.key === 'Tab') { const focusedElement = context.getActiveDocument().activeElement; if ( focusedElement !== null && context.isTargetWithinEventComponent(focusedElement) ) { const {altkey, ctrlKey, metaKey, shiftKey} = (nativeEvent: any); // Skip if any of these keys are being pressed if (altkey || ctrlKey || metaKey) { return; } const elements = context.getFocusableElementsInScope(); const position = elements.indexOf(focusedElement); const lastPosition = elements.length - 1; let nextElement = null; if (shiftKey) { if (position === 0) { if (props.contain) { nextElement = elements[lastPosition]; } else { // Out of bounds context.releaseOwnership(); return; } } else { nextElement = elements[position - 1]; } } else { if (position === lastPosition) { if (props.contain) { nextElement = elements[0]; } else { // Out of bounds context.releaseOwnership(); return; } } else { nextElement = elements[position + 1]; } } // If this element is possibly inside the scope of another // FocusScope responder or is out of bounds, then we release ownership. if (nextElement !== null) { if (!context.isTargetWithinEventResponderScope(nextElement)) { context.releaseOwnership(); } focusElement(nextElement); state.currentFocusedNode = nextElement; ((nativeEvent: any): KeyboardEvent).preventDefault(); } } } }, onRootEvent( event: ReactResponderEvent, context: ReactResponderContext, props: FocusScopeProps, state: FocusScopeState, ) { const {target} = event; // Handle global focus containment if (props.contain) { if (!context.isTargetWithinEventComponent(target)) { const currentFocusedNode = state.currentFocusedNode; if (currentFocusedNode !== null) { focusElement(currentFocusedNode); } else if (props.autoFocus) { const firstElement = getFirstFocusableElement(context, state); focusElement(firstElement); } } } }, onMount( context: ReactResponderContext, props: FocusScopeProps, state: FocusScopeState, ): void { if (props.restoreFocus) { state.nodeToRestore = context.getActiveDocument().activeElement; } if (props.autoFocus) { const firstElement = getFirstFocusableElement(context, state); focusElement(firstElement); } }, onUnmount( context: ReactResponderContext, props: FocusScopeProps, state: FocusScopeState, ): void { if ( props.restoreFocus && state.nodeToRestore !== null && context.hasOwnership() ) { focusElement(state.nodeToRestore); } }, onOwnershipChange( context: ReactResponderContext, props: FocusScopeProps, state: FocusScopeState, ): void { if (!context.hasOwnership()) { state.currentFocusedNode = null; } }, }; export default React.unstable_createEventComponent( FocusScopeResponder, 'FocusScope', );
packages/material-ui-icons/src/EventBusy.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let EventBusy = props => <SvgIcon {...props}> <path d="M9.31 17l2.44-2.44L14.19 17l1.06-1.06-2.44-2.44 2.44-2.44L14.19 10l-2.44 2.44L9.31 10l-1.06 1.06 2.44 2.44-2.44 2.44L9.31 17zM19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11z" /> </SvgIcon>; EventBusy = pure(EventBusy); EventBusy.muiName = 'SvgIcon'; export default EventBusy;
components/HighlightGrid.js
RomainInnocent/tpdevops
/** * Created by Adrien on 30/06/2017. */ import React from 'react'; import {GridList, GridTile} from 'material-ui/GridList'; import IconButton from 'material-ui/IconButton'; import Subheader from 'material-ui/Subheader'; import StarBorder from 'material-ui/svg-icons/toggle/star-border'; import StartupCard from './StartupCard'; import fetch from 'isomorphic-unfetch' const styles = { root: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', }, gridList: { width: '100%', height: 'auto', overflowY: 'auto', } }; /** * A simple example of a scrollable `GridList` containing a [Subheader](/#/components/subheader). */ const HighlightGridList = (props) => ( <div style={styles.root}> {props.highlights.map((high) => ( <GridList cols={2} cellHeight="auto" style={styles.gridList} key={high.periode}> <Subheader>{high.periode}</Subheader> {high.startups.map((tile) => ( <GridTile cols={tile.size} rows={tile.size} key={tile.img}> <StartupCard title={tile.title} pretty={tile.pretty} author={tile.author} avatar={tile.avatar} subtitle={tile.subtitle} description={tile.description} website={tile.website} youtubeLink={tile.youtubeLink} _id={tile._id} img={tile.img} /> </GridTile> ))} </GridList> ))} </div> ); HighlightGridList.getInitialProps = async function (context) { const res = await fetch('/api/s/all') const data = await res.json() console.log(`Show data fetched. Count: ${data.length}`) return { shows: data } } export default HighlightGridList;
packages/showcase/plot/grid.js
uber/react-vis
// Copyright (c) 2016 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import {XYPlot, XAxis, YAxis, VerticalGridLines, LineSeries} from 'react-vis'; export default function Example() { return ( <XYPlot width={300} height={300}> <VerticalGridLines values={[2, 2.3, 2.7]} /> <XAxis /> <YAxis /> <LineSeries data={[ {x: 1, y: 10}, {x: 2, y: 5}, {x: 3, y: 15} ]} /> </XYPlot> ); }
src/containers/AddTodo.js
lingxiao-Zhu/react-redux-demo
/** * Created by larry on 2017/1/4. */ import React from 'react'; import { connect } from 'react-redux'; import { addTodo } from '../actions'; let AddTodo = ({ dispatch }) => { let input; return( <div> <form onSubmit={e=>{ e.preventDefault(); if(!input.value.trim()){ return } dispatch(addTodo(input.value)) input.value = '' }}> <input ref={node=>{input=node}}/> <button type="submit"> Add Todo </button> </form> </div> ) } AddTodo = connect()(AddTodo) export default AddTodo
humantest/App.js
gutenye/react-mc
/* eslint-disable */ import React from 'react' import '../docs/docs' import '../docs/docs.css' import { render } from 'react-dom' import { Button, Card, Dialog, Drawer, Elevation, Checkbox, Fab, FormField, GridList, IconToggle, LayoutGrid, LinearProgress, Menu, List, Radio, Select, Slider, Snackbar, Switch, Tabs, Toolbar, Textfield, } from '../src' const log = console.log.bind(console) const getPages = () => [ //MyButton, //MyCard, // MyDialog, //MyCheckbox, //MyPermanentDrawer, // MyPersistentDrawer, // MyTemporaryDrawer, //MyElevation, //MyFab, //MyFormField, //MyGridList, //MyIconToggle, //MyLayoutGrid, //MyLinearProgress, //MyList, // MyMenu, // MyRadio, // MySelect, // MySlider, // MySnackbar, // MySwitch, // MyTabs, MyToolbar, // MyTextfield, ] const MyButton = () => <Button>hello</Button> class MyCard extends React.Component { //{{{1 render() { return ( <Card> <Card.Primary> <Card.Title>Title</Card.Title> <Card.Subtitle>Subtitle</Card.Subtitle> </Card.Primary> <Card.SupportingText>hello world</Card.SupportingText> <Card.Actions> <Card.Action>Action 1</Card.Action> <Card.Action>Action 2</Card.Action> </Card.Actions> </Card> ) } } class MyDialog extends React.Component { state = { open: false, } render() { return ( <div> <button onClick={() => this.setState({ open: true })}> Open Dialog </button> <Dialog open={this.state.open} onClose={() => this.setState({ open: false })} onAccept={() => console.log('onAccept')} onCancel={() => console.log('onCancel')} > <Dialog.Surface> <Dialog.Header> <Dialog.Header.Title> Use Google's location service? </Dialog.Header.Title> </Dialog.Header> <Dialog.Body> Let Google help apps determine location. This means sending anonymous location data to Google, even when no apps are running. </Dialog.Body> <Dialog.Footer> <Dialog.Footer.Button cancel>Cancel</Dialog.Footer.Button> <Dialog.Footer.Button accept>Accept</Dialog.Footer.Button> </Dialog.Footer> </Dialog.Surface> <Dialog.Backdrop /> </Dialog> </div> ) } } class MyCheckbox extends React.Component { state = { checked: false, } render() { return ( <Checkbox checked={this.state.checked} onChange={e => this.setState({ checked: e.target.checked })} /> ) } } class MyPermanentDrawer extends React.Component { render() { return ( <div> <DemoDrawerToolbar fixed /> <Toolbar.FixedAdjust style={{ display: 'flex' }}> <Drawer.Permanent> <DemoDrawerContent /> </Drawer.Permanent> <main>Page content goes here</main> </Toolbar.FixedAdjust> </div> ) } } class MyPersistentDrawer extends React.Component { state = { open: false, } render() { return ( <div style={{ display: 'flex' }}> <Drawer.Persistent open={this.state.open} onOpen={() => log('onOpen')} onClose={() => log('onClose')} > <Drawer.Persistent.Drawer> <Drawer.Persistent.ToolbarSpacer /> <DemoDrawerContent /> </Drawer.Persistent.Drawer> </Drawer.Persistent> <div> <DemoDrawerToolbar menu onMenuClick={() => this.setState({ open: !this.state.open })} /> <main> <div>{JSON.stringify(this.state)}</div> <DemoParagraphs count={10} /> </main> </div> </div> ) } } class MyTemporaryDrawer extends React.Component { state = { open: false, } render() { return ( <div> <Drawer.Temporary open={this.state.open} onOpen={() => log('onOpen')} onClose={() => this.setState({ open: false })} > <Drawer.Temporary.Drawer> <Drawer.Temporary.Header> <Drawer.Temporary.HeaderContent> Header here </Drawer.Temporary.HeaderContent> </Drawer.Temporary.Header> <nav className="mdc-persistent-drawer__content mdc-list"> <a className="mdc-list-item mdc-persistent-drawer--selected" href="#" > <i className="material-icons mdc-list-item__start-detail" aria-hidden="true" > inbox </i>Inbox </a> <a className="mdc-list-item" href="#"> <i className="material-icons mdc-list-item__start-detail" aria-hidden="true" > star </i>Star </a> </nav> </Drawer.Temporary.Drawer> </Drawer.Temporary> <button onClick={() => this.setState({ open: !this.state.open })}> Toggle Drawer: {JSON.stringify(this.state.open)} </button> </div> ) } } class MyElevation extends React.Component { render() { return <Elevation z="20">hello</Elevation> } } class MyFab extends React.Component { render() { return ( <Fab className="material-icons"> <Fab.Icon>favorite</Fab.Icon> </Fab> ) } } class MyFormField extends React.Component { render() { return ( <FormField> <input type="checkbox" id="input" /> <label htmlFor="input">Input Label</label> </FormField> ) } } class MyGridList extends React.Component { render() { return ( <GridList> <GridList.Tiles> {[1, 2].map(v => ( <GridList.Tile key={v}> <GridList.Tile.Primary> <GridList.Tile.PrimaryContent src="//via.placeholder.com/300x300" /> </GridList.Tile.Primary> <GridList.Tile.Secondary> <GridList.Tile.Title>Title</GridList.Tile.Title> </GridList.Tile.Secondary> </GridList.Tile> ))} </GridList.Tiles> </GridList> ) } } class MyIconToggle extends React.Component { state = { on: true, } render() { return ( <div> <IconToggle on={this.state.on} onChange={e => this.setState({ on: e.detail.isOn })} className="material-icons" dataToggleOn={{ label: 'Remove from favorites', content: 'favorite' }} dataToggleOff={{ label: 'Add to favorites', content: 'favorite_border', }} > favorite_border </IconToggle> {JSON.stringify(this.state.on)} </div> ) } } class MyLayoutGrid extends React.Component { render() { return ( <LayoutGrid> <LayoutGrid.Inner> <LayoutGrid.Cell order="2"> a </LayoutGrid.Cell> <LayoutGrid.Cell order="1"> b </LayoutGrid.Cell> <LayoutGrid.Cell> c </LayoutGrid.Cell> </LayoutGrid.Inner> </LayoutGrid> ) } } class MyLinearProgress extends React.Component { render() { return ( <div> <p> <LinearProgress progress={0.5} /> Determinate </p> <p> <LinearProgress progress={0.5} indeterminate /> Indeterminate </p> <p> <LinearProgress progress={0.5} buffer={0.75} /> Buffer </p> <p> <LinearProgress progress={0.5} reversed /> Reversed </p> <p> <LinearProgress progress={0.5} indeterminate reversed /> Indeterminate Reversed </p> <p> <LinearProgress progress={0.5} buffer={0.75} reversed /> Buffer Reversed </p> <p> <LinearProgress progress={0.5} accent /> Secondary </p> </div> ) } } class MyList extends React.Component { render() { return ( <div> <List>{[1, 2].map(i => <List.Item key={i}>hello {i}</List.Item>)}</List> <List twoLine> {[1, 2].map(i => ( <List.Item key={i}> <List.Item.Text> Two-line item {i} <List.Item.Text.Secondary> Seconday Text </List.Item.Text.Secondary> </List.Item.Text> </List.Item> ))} </List> </div> ) } } class MyMenu extends React.Component { state = { open: false, } render() { return ( <div> <div>{JSON.stringify(this.state)}</div> <Menu.Simple open={this.state.open} onClose={() => this.setState({ open: false })} onSelected={e => log('onSelected', e.detail)} items={[ { text: 'Facebook', onClick: () => log('Facebook') }, { text: 'Google', onClick: () => log('Google') }, { text: 'Apple', disabled: true }, ]} /> <button onClick={() => this.setState({ open: !this.state.open })}> toggle menu </button> <button onClick={() => this.setState({ open: 0 })}> open with selectedIndex </button> </div> ) } } class MyRadio extends React.Component { state = { company: 'google', } render() { return ( <div> <Radio name="company" id="Radio1" value="facebook" checked={this.state.company === 'facebook'} onChange={e => this.setState({ company: e.target.value })} /> <label htmlFor="Radio1">Facebook</label> <Radio name="company" id="Radio2" value="google" checked={this.state.company === 'google'} onChange={e => this.setState({ company: e.target.value })} /> <label htmlFor="Radio2">Google</label> <div>{JSON.stringify(this.state)}</div> </div> ) } } class MySelect extends React.Component { state = { value: null, // value: 'google', // value: 'wrong', } render() { const items = [ { text: 'Facebook', value: 'facebook' }, { text: 'Google', value: 'google' }, { text: 'Apple', value: 'apple', disabled: true }, ] return ( <div> <Select value={this.state.value} onChange={e => this.setState({ value: e.detail.value })} placeholder="Select a company" items={items} /> <div>{JSON.stringify(this.state)}</div> </div> ) } } class MySlider extends React.Component { state = { value: 10, } render() { return ( <div> <Slider value={this.state.value} onChange={({ detail }) => this.setState({ value: detail.value })} /> {this.state.value} </div> ) } } class MySnackbar extends React.Component { render() { return ( <div> <Snackbar ref={v => (this.snackbar = v)} /> <div onClick={() => this.snackbar.show({ message: new Date(), actionText: 'undo', actionHandler: () => log('actionhandler'), })} > open snackbar </div> </div> ) } } class MySwitch extends React.Component { state = { checked: true, } render() { return ( <div> <label className="mdc-switch-label"> <Switch checked={this.state.checked} onChange={e => this.setState({ checked: e.target.checked })} /> on/off </label> {JSON.stringify(this.state.checked)} </div> ) } } class MyTabs extends React.Component { render() { const items = [ { text: 'Recents', icon: <i className="mdc-tab__icon material-icons">phone</i>, }, { text: 'Favorites', icon: <i className="mdc-tab__icon material-icons">favorite</i>, active: true, }, { text: 'Nearby', icon: <i className="mdc-tab__icon material-icons">person_pin</i>, }, ] return <Tabs indicator="primary" items={items} onChange={pd} /> } } class MyToolbar extends React.Component { render() { return <MyWaterfallFlexibleToolbar /> } } const MyWaterfallFlexibleToolbar = () => { const self = {} return ( <div style={{ width: 320 }}> <Toolbar fixed waterfall flexible flexibleDefaultBehavior ref={v => (self.toolbar = v)} > <Toolbar.Row> <Toolbar.Section align="start"> <Toolbar.Icon menu className="material-icons"> menu </Toolbar.Icon> <Toolbar.Title>Title</Toolbar.Title> </Toolbar.Section> <Toolbar.Section align="end"> <Toolbar.Icon className="material-icons"> file_download </Toolbar.Icon> <Toolbar.Icon className="material-icons">print</Toolbar.Icon> <Toolbar.Icon className="material-icons">more_vert</Toolbar.Icon> </Toolbar.Section> </Toolbar.Row> </Toolbar> <Toolbar.FixedAdjust ref={v => (self.toolbar.fixedAdjustElement = v)} style={{ minHeight: 1000 }} > <DemoParagraphs count={3} /> </Toolbar.FixedAdjust> </div> ) } class MyTextfield extends React.Component { render() { return <Textfield label="Name" helptext="name is required" persistent /> } } class App extends React.Component { render() { const pages = getPages() return <div>{pages.map((v, i) => React.createElement(v, { key: i }))}</div> } } render(<App />, document.querySelector('#app')) // vim: fdm=marker
src/UnmountClosed.js
nkbt/react-collapse
import React from 'react'; import PropTypes from 'prop-types'; import {Collapse} from './Collapse'; export class UnmountClosed extends React.PureComponent { static propTypes = { isOpened: PropTypes.bool.isRequired, onWork: PropTypes.func, onRest: PropTypes.func }; static defaultProps = { onWork: undefined, onRest: undefined }; constructor(props) { super(props); this.state = {isResting: true, isOpened: props.isOpened, isInitialRender: true}; } componentDidUpdate(prevProps) { const {isOpened} = this.props; if (prevProps.isOpened !== isOpened) { // eslint-disable-next-line react/no-did-update-set-state this.setState({isResting: false, isOpened, isInitialRender: false}); } } onWork = ({isOpened, ...rest}) => { this.setState({isResting: false, isOpened}); const {onWork} = this.props; if (onWork) { onWork({isOpened, ...rest}); } }; onRest = ({isOpened, ...rest}) => { this.setState({isResting: true, isOpened, isInitialRender: false}); const {onRest} = this.props; if (onRest) { onRest({isOpened, ...rest}); } }; getInitialStyle = () => { const {isOpened, isInitialRender} = this.state; if (isInitialRender) { return isOpened ? {height: 'auto', overflow: 'initial'} : {height: '0px', overflow: 'hidden'}; } return {height: '0px', overflow: 'hidden'}; }; render() { const {isResting, isOpened} = this.state; return isResting && !isOpened ? null : ( <Collapse {...this.props} initialStyle={this.getInitialStyle()} onWork={this.onWork} onRest={this.onRest} /> ); } }
client/components/layout/nav.js
LIYINGZHEN/meteor-react-redux-base
import React from 'react'; import {Link} from 'react-router'; export default (props) => ( <nav className="navbar navbar-default navbar-fixed-top"> <div className="container"> <div className="navbar-header"> <button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" className="navbar-toggle collapsed" type="button"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar" /> <span className="icon-bar" /> <span className="icon-bar" /> </button> <Link to="/" className="navbar-brand">{props.appName}</Link> </div> <div id="navbar" className="navbar-collapse navbar-left collapse"> <ul className="nav navbar-nav"> <li><Link to="/posts">新闻</Link></li> <li><Link to="/events">活动</Link></li> <li><Link to="/admin">管理员后台</Link></li> </ul> </div> <ul className="nav navbar-nav navbar-right hidden-xs"> <li className="dropdown"> <a className="dropdown-toggle" id="drop1" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> Language <span className="caret" /> </a> <ul className="dropdown-menu" aria-labelledby="drop1"> <li><a href="#" onClick={(e) => props.setLang(e, 'enUS')}>English</a></li> <li><a href="#" onClick={(e) => props.setLang(e, 'zhCN')}>中文</a></li> </ul> </li> </ul> </div> </nav> );
examples/ErrorMessage.js
jaredpalmer/formik
import React from 'react'; import { Formik, Field, Form, ErrorMessage } from 'formik'; import * as Yup from 'yup'; import { Debug } from './Debug'; // While you can use any validation library (or write you own), Formik // comes with special support for Yup by @jquense. It has a builder API like // React PropTypes / Hapi.js's Joi. You can define these inline or, you may want // to keep them separate so you can reuse schemas (e.g. address) across your application. const SignUpSchema = Yup.object().shape({ email: Yup.string().email('Invalid email address').required('Required'), firstName: Yup.string() .min(2, 'Must be longer than 2 characters') .max(20, 'Nice try, nobody has a first name that long') .required('Required'), lastName: Yup.string() .min(2, 'Must be longer than 2 characters') .max(20, 'Nice try, nobody has a last name that long') .required('Required'), }); // <ErrorMessage /> will ONLY render when a field has an error and has been touched. const SignUp = () => ( <div> <h1>Sign up</h1> <Formik initialValues={{ email: '', firstName: '', lastName: '', }} validationSchema={SignUpSchema} onSubmit={values => { setTimeout(() => { alert(JSON.stringify(values, null, 2)); }, 500); }} render={({ errors, touched }) => ( <Form> <label htmlFor="firstName">First Name</label> <Field name="firstName" placeholder="Jane" type="text" /> <ErrorMessage name="firstName" component="div" className="field-error" /> <label htmlFor="lastName">Last Name</label> <Field name="lastName" placeholder="Doe" type="text" /> <ErrorMessage name="firstName"> {(msg /** this is the same as the above */) => ( <div className="field-error">{msg}</div> )} </ErrorMessage> <label htmlFor="email">Email</label> <Field name="email" placeholder="[email protected]" type="email" /> {/* This will render a string */} <ErrorMessage name="email" className="field-error" /> <button type="submit">Submit</button> <Debug /> </Form> )} /> </div> ); export default SignUp;
webclient/userProfile/changePassword.js
souravDutta123/Cognitive-Assistant
import React from 'react'; class ChangePassword extends React.Component { constructor() { super(); this.state={ drawerMenu: [], } } componentDidMount() { } render() { const style={ textAlign: 'center', }; return( <div><h1 style={style}>ChangePassword :/</h1></div> ); } } export default ChangePassword;
src/svg-icons/notification/airline-seat-recline-normal.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatReclineNormal = (props) => ( <SvgIcon {...props}> <path d="M7.59 5.41c-.78-.78-.78-2.05 0-2.83.78-.78 2.05-.78 2.83 0 .78.78.78 2.05 0 2.83-.79.79-2.05.79-2.83 0zM6 16V7H4v9c0 2.76 2.24 5 5 5h6v-2H9c-1.66 0-3-1.34-3-3zm14 4.07L14.93 15H11.5v-3.68c1.4 1.15 3.6 2.16 5.5 2.16v-2.16c-1.66.02-3.61-.87-4.67-2.04l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C8.01 7 7 8.01 7 9.25V15c0 1.66 1.34 3 3 3h5.07l3.5 3.5L20 20.07z"/> </SvgIcon> ); NotificationAirlineSeatReclineNormal = pure(NotificationAirlineSeatReclineNormal); NotificationAirlineSeatReclineNormal.displayName = 'NotificationAirlineSeatReclineNormal'; NotificationAirlineSeatReclineNormal.muiName = 'SvgIcon'; export default NotificationAirlineSeatReclineNormal;
packages/wix-style-react/src/GenericModalLayout/GenericModalLayout.js
wix/wix-style-react
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import styles from './GenericModalLayout.scss'; export default class GenericModalLayout extends React.PureComponent { render() { const { dataHook, fullscreen, header, content, footer } = this.props; const containerClassNames = classNames(styles.container, { [styles.fullscreenContainer]: fullscreen, }); return ( <div data-hook={dataHook} className={containerClassNames} data-fullscreen={Boolean(fullscreen)} > <div>{header}</div> <div className={styles.content}>{content}</div> <div>{footer}</div> </div> ); } } GenericModalLayout.propTypes = { /** Applied as data-hook HTML attribute that can be used in the tests */ dataHook: PropTypes.string, /** Any node to be rendered */ header: PropTypes.node, /** Any node to be rendered */ content: PropTypes.node, /** Any node to be rendered */ footer: PropTypes.node, /** Is modal layout in fullscreen */ fullscreen: PropTypes.bool, }; GenericModalLayout.defaultProps = { fullscreen: false, }; GenericModalLayout.displayName = 'GenericModalLayout';
src/components/ForgotPassword/ForgotPasswordForm.js
folio-org/stripes-core
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Field, Form } from 'react-final-form'; import { FormattedMessage } from 'react-intl'; import { TextField, Button, Headline, Row, Col, } from '@folio/stripes-components'; import OrganizationLogo from '../OrganizationLogo'; import AuthErrorsContainer from '../AuthErrorsContainer'; import formStyles from './ForgotPasswordForm.css'; class ForgotPasswordForm extends Component { static propTypes = { onSubmit: PropTypes.func.isRequired, errors: PropTypes.arrayOf(PropTypes.object), }; static defaultProps = { errors: [] }; render() { const { errors, onSubmit } = this.props; return ( <Form onSubmit={onSubmit} render={({ handleSubmit, pristine }) => ( <div className={formStyles.wrap}> <div className={formStyles.centered}> <OrganizationLogo /> <form className={formStyles.form} data-form="forgot" onSubmit={handleSubmit} > <Headline size="xx-large" tag="h1" data-test-h1 > <FormattedMessage id="stripes-core.label.forgotPassword" /> </Headline> <Headline size="large" tag="p" weight="regular" faded data-test-p > <FormattedMessage id="stripes-core.label.forgotPasswordCallToAction" /> </Headline> <div className={formStyles.formGroup}> <Field id="input-email-or-phone" component={TextField} name="userInput" type="text" marginBottom0 fullWidth inputClass={formStyles.input} validationEnabled={false} hasClearIcon={false} autoComplete="on" autoCapitalize="none" autoFocus /> </div> <Button buttonStyle="primary" id="clickable-login" name="continue-button" type="submit" buttonClass={formStyles.submitButton} disabled={pristine} fullWidth marginBottom0 data-test-submit > <FormattedMessage id="stripes-core.button.continue" /> </Button> <Row center="xs"> <Col xs={12}> <div className={formStyles.authErrorsWrapper} data-test-errors > <AuthErrorsContainer errors={errors} data-test-container /> </div> </Col> </Row> </form> </div> </div> )} /> ); } } export default ForgotPasswordForm;
src/index.js
jonathanweiss/pixelboard
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, hashHistory } from 'react-router'; import App from './app.jsx'; import Clock from './apps/clock.jsx'; import FreeText from './apps/freetext.jsx'; import RandomPixels from './apps/random.jsx'; import Draw from './apps/draw.jsx'; ReactDOM.render( <Router history={hashHistory}> <Route path="/" component={App} /> <Route path="/clock" component={Clock} /> <Route path="/random" component={RandomPixels} /> <Route path="/freetext" component={FreeText} /> <Route path="/draw" component={Draw} /> </Router> , document.querySelector('#root')); export default App;
code/schritte/redux/7-redux-complete-app/src/main.js
st-he/react-workshop
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import { composeWithDevTools } from 'redux-devtools-extension'; import Layout from './components/Layout'; import { rootReducer } from './reducers'; import {loadGreetings} from './actions'; const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); // init store.dispatch(loadGreetings); const mountNode = document.getElementById('mount'); ReactDOM.render( <Provider store={store}> <Layout /> </Provider>, mountNode );
packages/react/src/components/organisms/HeaderSlim/index.js
massgov/mayflower
/** * HeaderSlim module. * @module @massds/mayflower-react/HeaderSlim * @requires module:@massds/mayflower-assets/scss/03-organisms/header-slim */ import React from 'react'; import PropTypes from 'prop-types'; const HeaderSlim = ({ skipNav, siteLogo, mainNav, utilityNav }) => ( <div className="ma__header_slim"> {skipNav} <div className="ma__header_slim__utility"> <div className="ma__header_slim__utility-container ma__container"> {utilityNav} </div> </div> <header className="ma__header_slim__header" id="header"> <div className="ma__header_slim__header-container ma__container"> <div className="ma__header_slim__logo">{siteLogo}</div> { mainNav && <div className="ma__header_slim__nav">{mainNav}</div> } </div> </header> </div> ); HeaderSlim.propTypes = { /** A render function that renders SiteLogo component. */ siteLogo: PropTypes.node.isRequired, /** A render function that renders Anchor link to skip to the main content and bypass the header navigations */ skipNav: PropTypes.node, /** A render function that renders Navigation items in the blue banner, above the header element */ mainNav: PropTypes.node, /** A render function that renders Navigation items in the header area */ utilityNav: PropTypes.node }; export default HeaderSlim;
app/packs/src/admin/converter/AdminApp.js
ComPlat/chemotion_ELN
import React, { Component } from 'react'; import { Button } from 'react-bootstrap'; import ConverterApi from '../../components/fetchers/ConverterFetcher'; import ProfileNewModal from './create/ProfileNewModal'; import ProfileList from './list/ProfileList'; import ProfileEdit from './edit/ProfileEdit'; import ProfileCreate from './create/ProfileCreate'; const initTable = (tableData) => { const header = {}; if (tableData) { // eslint-disable-next-line guard-for-in for (const key in tableData.options) { header[key] = tableData.options[key][0]; } } return { header, table: {} }; }; class AdminApp extends Component { constructor(props) { super(props); this.state = { status: 'list', clientId: '', selectedFile: null, profiles: [], tableData: null, columnList: null, headerOptions: [], error: false, isLoading: false, uploadModal: false, uploadType: '', errorMessage: '', title: '', description: '', tables: [], identifiers: [], firstRowIsHeader: [], currentIdentifier: '', currentIndex: -1, }; this.showImportView = this.showImportView.bind(this); this.showEditView = this.showEditView.bind(this); this.updateTitle = this.updateTitle.bind(this); this.updateDescription = this.updateDescription.bind(this); this.addTable = this.addTable.bind(this); this.updateTable = this.updateTable.bind(this); this.removeTable = this.removeTable.bind(this); this.addHeader = this.addHeader.bind(this); this.updateHeader = this.updateHeader.bind(this); this.removeHeader = this.removeHeader.bind(this); this.addOperation = this.addOperation.bind(this); this.updateOperation = this.updateOperation.bind(this); this.removeOperation = this.removeOperation.bind(this); this.addIdentifier = this.addIdentifier.bind(this); this.updateIdentifier = this.updateIdentifier.bind(this); this.removeIdentifier = this.removeIdentifier.bind(this); this.toggleFirstRowIsHeader = this.toggleFirstRowIsHeader.bind(this); this.updateFirstRowIsHeader = this.updateFirstRowIsHeader.bind(this); this.createProfile = this.createProfile.bind(this); this.updateProfile = this.updateProfile.bind(this); this.deleteProfile = this.deleteProfile.bind(this); this.downloadProfile = this.downloadProfile.bind(this); this.updateFile = this.updateFile.bind(this); this.uploadFile = this.uploadFile.bind(this); this.importFile = this.importFile.bind(this); this.dispatchView = this.dispatchView.bind(this); this.getTitleforStatus = this.getTitleforStatus.bind(this); this.showUploadModal = this.showUploadModal.bind(this); this.hideUploadModal = this.hideUploadModal.bind(this); this.showImportModal = this.showImportModal.bind(this); this.handleCreate = this.handleCreate.bind(this); this.handleUpload = this.handleUpload.bind(this); this.handleImport = this.handleImport.bind(this); this.backProfileList = this.backProfileList.bind(this); } componentDidMount() { ConverterApi.fetchProfiles() .then((profiles) => { if (profiles) this.setState({ profiles: profiles.profiles, clientId: profiles.client }); }); } getTitleforStatus() { if (this.state.status === 'list') { return `Profiles List [ ${this.state.clientId} ]`; } else if (this.state.status === 'edit') { return 'Update Profile'; } else if (this.state.status === 'import') { return 'Import Profile'; } return 'Create Profile'; } showImportView() { this.setState({ status: 'import' }); } showUploadModal() { this.setState({ uploadModal: true, uploadType: 'new' }); } showImportModal() { this.setState({ uploadModal: true, uploadType: 'import' }); } hideUploadModal() { this.setState({ uploadModal: false, uploadType:'' }); } showEditView(index, identifier) { const currentProfile = this.state.profiles[index]; this.setState({ status: 'edit', currentIdentifier: identifier, currentIndex: index, id: currentProfile.id, title: currentProfile.title, description: currentProfile.description, identifiers: currentProfile.identifiers, header: currentProfile.header, tables: currentProfile.tables, firstRowIsHeader: currentProfile.firstRowIsHeader }); } updateTitle(title) { this.setState({ title }); } updateDescription(description) { this.setState({ description }); } addTable() { const { tables, tableData } = this.state; tables.push(initTable(tableData)); this.setState({ tables }); } updateTable(index, key, value) { const tables = [...this.state.tables] if (index !== -1) { tables[index].table[key] = value // remove the column if tableIndex and columnIndex is null if (Object.values(tables[index].table[key]).every(value => (value === null || isNaN(value)))) { delete tables[index].table[key]; } this.setState({ tables }); } } removeTable(index) { const tables = [...this.state.tables]; tables.splice(index, 1); this.setState({ tables }); } addHeader(index) { const tables = [...this.state.tables] if (index !== -1) { const key = `HEADER${Object.keys(tables[index].header).length}`; tables[index].header[key] = ''; } this.setState({ tables }); } updateHeader(index, key, value, oldKey) { const tables = [...this.state.tables]; if (index !== -1) { if (oldKey === undefined) { tables[index].header[key] = value; } else { // create a new header to preserve the order tables[index].header = Object.keys(tables[index].header).reduce((agg, cur) => { if (cur == oldKey) { agg[key] = value; } else { agg[cur] = tables[index].header[cur]; } return agg; }, {}); } this.setState({ tables }); } } removeHeader(index, key) { const tables = [...this.state.tables]; delete tables[index].header[key]; this.setState({ tables }); } addOperation(index, key, type) { const tables = [...this.state.tables]; if (index !== -1) { const operation = { type, operator: '+' }; if (type == 'column') { operation['column'] = { tableIndex: null, columnIndex: null }; } if (tables[index].table[key] === undefined) { tables[index].table[key] = []; } tables[index].table[key].push(operation); this.setState({ tables }); } } updateOperation(index, key, opIndex, opKey, value) { const tables = [...this.state.tables]; if (index !== -1) { tables[index].table[key][opIndex][opKey] = value; this.setState({ tables }); } } removeOperation(index, key, opIndex) { const tables = [...this.state.tables]; if (index !== -1) { tables[index].table[key].splice(opIndex, 1); // remove operations if it is empty if (tables[index].table[key].length == 0) { delete tables[index].table[key]; } this.setState({ tables }); } } addIdentifier(type) { const { identifiers } = this.state let metadataKey = ''; let value = ''; if (type === 'metadata' && this.state.status == 'create') { metadataKey = Object.keys(this.state.tableData.metadata)[0]; value = this.state.tableData.metadata[metadataKey]; } const identifier = { type, tableIndex: 0, lineNumber: '', metadataKey, headerKey: '', value, isRegex: false }; identifiers.push(identifier); this.setState({ identifiers }); } updateIdentifier(index, data) { const identifiers = [...this.state.identifiers]; if (index !== -1) { const identifier = identifiers[index]; Object.assign(identifier, data); identifiers[index] = identifier; this.setState({ identifiers }); } } removeIdentifier(index) { const identifiers = [...this.state.identifiers]; if (index !== -1) { identifiers.splice(index, 1); this.setState({ identifiers }); } } updateFirstRowIsHeader(index, checked) { const firstRowIsHeader = [...this.state.firstRowIsHeader]; firstRowIsHeader[index] = checked; this.setState({ firstRowIsHeader }); } toggleFirstRowIsHeader(index) { const { tableData } = this.state; const table = tableData.data[index]; if (table.firstRowIsHeader) { table.firstRowIsHeader = false; table.columns = table._columns; table.rows.splice(0, 0, table._first); table._columns = null; table._first = null; } else { table.firstRowIsHeader = true; table._columns = table.columns; table._first = table.rows.shift(); table.columns = table._first.map((value, idx) => { const originalName = table._columns[idx].name; return { key: idx.toString(), name: value + ` (${originalName})` } }) } const firstRowIsHeader = tableData.data.map(_table => _table.firstRowIsHeader || false); this.setState({ tableData, firstRowIsHeader }); } handleImport(context) { const { uploadType } = this.state; if (uploadType === 'import') { this.handleUpload(context); } if (uploadType === 'new') { this.handleCreate(context); } } handleUpload(context) { const createProfile = (e) => { const profile = JSON.parse(e.target.result); ConverterApi.createProfile(profile) .then(() => { ConverterApi.fetchProfiles() .then((profiles) => { this.setState({ profiles: profiles.profiles, uploadModal: false, uploadType: '' }); }); }) .catch((errors) => { this.setState({ error: true, errorMessage: Object.values(errors).join(', '), isLoading: false }); }); }; const reader = new FileReader(); reader.readAsText(context); reader.onload = createProfile.bind(this); } handleCreate(context) { const { uploadType } = this.state; console.log(uploadType); let profile = context; if (uploadType === 'import') { console.log(context); profile = JSON.parse(context); } console.log(profile); ConverterApi.fetchTables(profile) .then((tableData) => { if (tableData.error) { // } else { // create a flat list of all columns const columnList = tableData.data.reduce((accumulator, table, tableIndex) => { const tableColumns = table.columns.map((tableColumn, columnIndex) => { return Object.assign({}, tableColumn, { label: `Table #${tableIndex} Column #${columnIndex}`, value: { tableIndex, columnIndex } }); }); return accumulator.concat(tableColumns); }, []); this.setState({ selectedFile: null, isLoading: false, tableData, columnList, headerOptions: tableData.options, tables: [initTable(tableData)], identifiers: [], firstRowIsHeader: tableData.data.map(table => false), error: false, status: 'create', errorMessage: '' }); } }).catch((errorMessage) => { console.log(errorMessage); }); this.hideUploadModal(); } backProfileList(event) { this.setState({ status: 'list', title: '', description: '', identifiers: [], header: {}, table: {}, currentIdentifier: '', currentIndex: -1, }); } createProfile(event) { event.preventDefault(); const { title, description, tables, identifiers, tableData, firstRowIsHeader } = this.state; const profile = { title, description, tables, identifiers, firstRowIsHeader }; ConverterApi.createProfile(profile) .then((data) => { const newProfiles = [...this.state.profiles]; newProfiles.push(data); this.setState({ profiles: newProfiles, status: 'list', title: '', description: '', identifiers: [], header: {}, table: {}, currentIdentifier: '', currentIndex: -1, showAlert: true }); // $('#modal').show() }) .catch(() => ({ errors: { path: 'File not found' } })); } updateProfile() { const { id, title, description, tables, identifiers, tableData, firstRowIsHeader } = this.state; const profile = { id, title, description, tables, identifiers, firstRowIsHeader }; ConverterApi.updateProfile(profile, this.state.currentIdentifier) .then((data) => { const newProfiles = [...this.state.profiles]; newProfiles[this.state.currentIndex] = data; this.setState({ profiles: newProfiles, status: 'list', title: '', description: '', identifiers: [], header: {}, table: {}, currentIdentifier: '', currentIndex: -1, showAlert: true }); }); } // deleteProfile() { deleteProfile(index, identifier) { ConverterApi.deleteProfile(identifier) .then(() => { const newProfiles = [...this.state.profiles]; if (index !== -1) { newProfiles.splice(index, 1); this.setState({ profiles: newProfiles, }); } }); } downloadProfile(index, identifier) { const a = document.createElement('a'); a.href = `data:application/json;charset=utf-8,${encodeURIComponent(JSON.stringify(this.state.profiles[index], null, 2))}`; a.download = `${identifier}.json`; document.body.appendChild(a); a.click(); document.body.removeChild(a); } updateFile(event) { this.setState({ selectedFile: event.target.files[0], loaded: 0, isLoading: false, error: false, errorMessage: '' }); } uploadFile() { const { selectedFile } = this.state; this.setState({ isLoading: true }); ConverterApi.fetchTables(selectedFile) .then((tableData) => { if (tableData) { // create a flat list of all columns const columnList = tableData.data.reduce((accumulator, table, tableIndex) => { const tableColumns = table.columns.map((tableColumn, columnIndex) => Object.assign({}, tableColumn, { label: `Table #${tableIndex} Column #${columnIndex}`, value: { tableIndex, columnIndex } })); return accumulator.concat(tableColumns); }, []); this.setState({ selectedFile: null, isLoading: false, tableData, columnList, headerOptions: tableData.options, tables: [initTable(tableData)], identifiers: [], firstRowIsHeader: tableData.data.map(() => false), error: false, errorMessage: '' }); } }) .catch(error => { if (error.status === 413) { this.setState({ error: true, errorMessage: 'The uploaded file is too large.', isLoading: false }) } else { error.text().then(errorMessage => { this.setState({ error: true, errorMessage: JSON.parse(errorMessage).error, isLoading: false }) }) } }) } importFile() { const { selectedFile } = this.state; this.setState({ isLoading: true }); const createProfile = e => { const profile = JSON.parse(e.target.result) ConverterApi.createProfile(profile) .then(data => { this.setState({ status: 'list', selectedFile: null, isLoading: false, error: false, errorMessage: '' }) }) .catch(errors => { this.setState({ error: true, errorMessage: Object.values(errors).join(', '), isLoading: false }) }) } const reader = new FileReader(); reader.readAsText(selectedFile); reader.onload = createProfile.bind(this); } dispatchView() { const { tableData, status, error, errorMessage, isLoading, selectedFile } = this.state; if (status === 'list') { return ( <ProfileList profiles={this.state.profiles} editProfile={this.showEditView} deleteProfile={this.deleteProfile} downloadProfile={this.downloadProfile} /> ); } else if (status === 'edit') { return ( <ProfileEdit id={this.state.id} title={this.state.title} description={this.state.description} tables={this.state.tables} identifiers={this.state.identifiers} firstRowIsHeader={this.state.firstRowIsHeader} updateTitle={this.updateTitle} updateDescription={this.updateDescription} addTable={this.addTable} updateTable={this.updateTable} removeTable={this.removeTable} addHeader={this.addHeader} updateHeader={this.updateHeader} removeHeader={this.removeHeader} addOperation={this.addOperation} updateOperation={this.updateOperation} removeOperation={this.removeOperation} addIdentifier={this.addIdentifier} updateIdentifier={this.updateIdentifier} removeIdentifier={this.removeIdentifier} updateFirstRowIsHeader={this.updateFirstRowIsHeader} updateProfile={this.updateProfile} backProfileList={this.backProfileList} /> ); } else if (status === 'create') { if (tableData) { return ( <ProfileCreate tableData={this.state.tableData} columnList={this.state.columnList} toggleFirstRowIsHeader={this.toggleFirstRowIsHeader} headerOptions={this.state.headerOptions} title={this.state.title} description={this.state.description} identifiers={this.state.identifiers} tables={this.state.tables} updateTitle={this.updateTitle} updateDescription={this.updateDescription} addTable={this.addTable} updateTable={this.updateTable} removeTable={this.removeTable} updateHeader={this.updateHeader} addOperation={this.addOperation} updateOperation={this.updateOperation} removeOperation={this.removeOperation} addIdentifier={this.addIdentifier} updateIdentifier={this.updateIdentifier} removeIdentifier={this.removeIdentifier} createProfile={this.createProfile} backProfileList={this.backProfileList} /> ); } } return (<span />); } render() { return ( <div> <header> <nav aria-label="breadcrumb"> {this.state.status === 'list' && <ol className="breadcrumb"> <li className="breadcrumb-item active" aria-current="page">Chemotion file converter admin</li> </ol> } {this.state.status === 'edit' && <ol className="breadcrumb"> <li className="breadcrumb-item" aria-current="page">Chemotion file converter admin</li> <li className="breadcrumb-item active" aria-current="page">Edit Profile: + {this.state.title}</li> </ol> } {this.state.status === 'create' && <ol className="breadcrumb"> <li className="breadcrumb-item" aria-current="page">Chemotion file converter admin</li> <li className="breadcrumb-item active" aria-current="page">Create Profile</li> </ol> } {this.state.status === 'import' && <ol className="breadcrumb"> <li className="breadcrumb-item" aria-current="page">Chemotion file converter admin</li> <li className="breadcrumb-item active" aria-current="page">Import Profile</li> </ol> } </nav> <div> {this.state.status === 'list' && <div className="float-right"> <Button bsStyle="info" bsSize="small" onClick={this.showImportModal}> Import profile&nbsp;<i className="fa fa-upload" aria-hidden="true" /> </Button>&nbsp;&nbsp; <Button bsStyle="primary" bsSize="small" onClick={this.showUploadModal}> Create new profile&nbsp;<i className="fa fa-plus" aria-hidden="true" /> </Button> </div> } <h2 className="mb-0">{this.getTitleforStatus()}</h2> </div> </header> <main> {this.dispatchView()} </main> <ProfileNewModal content="Profile" showModal={this.state.uploadModal} fnClose={this.hideUploadModal} fnCreate={this.handleImport} /> <div className="modal modal-backdrop" data-backdrop="static" id="modal" tabIndex="-1"> <div className="modal-dialog modal-dialog-centered"> <div className="modal-content"> <div className="modal-body"> <div className="alert alert-success" role="alert">Profile successfully created!</div> </div> <div className="modal-footer"> <a href="." className="btn btn-secondary">Back to profiles list</a> <a href="/" className="btn btn-primary">Upload file and use profile</a> </div> </div> </div> </div> </div> ); } } export default AdminApp;
src/boilerplate-layout/components/layout/elements/loading.js
joropeza/react-fullscreen-app-boilerplate
import React from 'react'; const Loading = () => ( <div> <p className="center" style={{ marginTop: 100, opacity: 0.5 }}> <i className="fa fa-cog fa-spin fa-5x" /> </p> </div> ); export default Loading;
src/routes/Counter/components/Counter.js
wookiecookie87/lunch_group_creator_with_reactjs
import React from 'react' import PropTypes from 'prop-types' export const Counter = ({ counter, increment, doubleAsync }) => ( <div style={{ margin: '0 auto' }} > <h2>Counter: {counter}</h2> <button className='btn btn-primary' onClick={increment}> Increment </button> {' '} <button className='btn btn-secondary' onClick={doubleAsync}> Double (Async) </button> </div> ) Counter.propTypes = { counter: PropTypes.number.isRequired, increment: PropTypes.func.isRequired, doubleAsync: PropTypes.func.isRequired, } export default Counter
js/components/common/AddLocationModal.js
a-omsk/Vegreact
import React from 'react'; import Modal from 'react-modal'; import AddLocationForm from './AddLocationForm'; const modalStyle = { overlay: { zIndex: 10, }, content: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '80%', width: '60%', margin: 'auto', }, }; const AddLocationModal = (props) => ( <Modal isOpen={props.opened} style={modalStyle} onRequestClose={props.closeHandler} > <AddLocationForm {...props} /> </Modal> ); AddLocationModal.propTypes = { opened: React.PropTypes.bool.isRequired, closeHandler: React.PropTypes.func.isRequired, }; export default AddLocationModal;
src/svg-icons/social/sentiment-satisfied.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialSentimentSatisfied = (props) => ( <SvgIcon {...props}> <circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-4c-1.48 0-2.75-.81-3.45-2H6.88c.8 2.05 2.79 3.5 5.12 3.5s4.32-1.45 5.12-3.5h-1.67c-.7 1.19-1.97 2-3.45 2z"/> </SvgIcon> ); SocialSentimentSatisfied = pure(SocialSentimentSatisfied); SocialSentimentSatisfied.displayName = 'SocialSentimentSatisfied'; SocialSentimentSatisfied.muiName = 'SvgIcon'; export default SocialSentimentSatisfied;
src/svg-icons/av/fiber-dvr.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvFiberDvr = (props) => ( <SvgIcon {...props}> <path d="M17.5 10.5h2v1h-2zm-13 0h2v3h-2zM21 3H3c-1.11 0-2 .89-2 2v14c0 1.1.89 2 2 2h18c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zM8 13.5c0 .85-.65 1.5-1.5 1.5H3V9h3.5c.85 0 1.5.65 1.5 1.5v3zm4.62 1.5h-1.5L9.37 9h1.5l1 3.43 1-3.43h1.5l-1.75 6zM21 11.5c0 .6-.4 1.15-.9 1.4L21 15h-1.5l-.85-2H17.5v2H16V9h3.5c.85 0 1.5.65 1.5 1.5v1z"/> </SvgIcon> ); AvFiberDvr = pure(AvFiberDvr); AvFiberDvr.displayName = 'AvFiberDvr'; AvFiberDvr.muiName = 'SvgIcon'; export default AvFiberDvr;
app/components/ConArticle.js
Toreant/monster_web
/** * Created by apache on 15-11-14. */ import React from 'react'; import ConList from './ConList'; class ConArticle extends React.Component { constructor(props) { super(props); } render() { let Result; if(this.props.params.domain !== undefined) { Result = ( <ConList tab={this.props.params.column || 'article'} domain={this.props.params.domain} /> ); } return ( <div> {Result} </div> ); } } export default ConArticle;
src/common/components/ErrorMessage.js
algernon/mad-tooter
// @flow /* The Mad Tooter -- A Mastodon client * Copyright (C) 2017 Gergely Nagy * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react'; import { connect } from 'react-redux'; import Snackbar from 'material-ui/Snackbar'; import { withStyles } from 'material-ui/styles'; const styles = theme => ({ snackbar: { bottom: theme.spacing.unit, right: 'auto', left: theme.spacing.unit, }, }); class ErrorMessage extends React.Component { handleRequestClose = () => { this.props.dispatch({type: 'HIDE_ERROR'}); } render() { const { show, message, classes, transient } = this.props; return ( <Snackbar open={show} message={<span>{message}</span>} onRequestClose={this.handleRequestClose} anchorOrigin={{ vertical: 'bottom', horizontal: 'left', }} autoHideDuration={transient ? 5000 : null} classes={{ anchorBottomLeft: classes.snackbar, }} /> ); } } const stateToProps = (state, props) => ({ message: state.getIn(["error", "message"]), show: state.getIn(["error", "show"]), transient: state.getIn(["error", "transient"]), }); export default connect(stateToProps)(withStyles(styles)(ErrorMessage));
plugins/Files/js/components/unlockwarning.js
NebulousLabs/New-Sia-UI
import PropTypes from 'prop-types' import React from 'react' const UnlockWarning = ({ onClick }) => ( <div className='allowance-dialog unlock-warning'> <h1 className='unlock-warning-head'> Your wallet must be unlocked and synchronized to buy storage. </h1> <div className='allowance-buttons'> <button onClick={onClick} className='allowance-button-accept'> OK </button> </div> </div> ) UnlockWarning.propTypes = { onClick: PropTypes.func.isRequired } export default UnlockWarning
src/app/components/forms/inputs/XEditable.js
backpackcoder/world-in-flames
import React from 'react' import 'X-editable/dist/bootstrap3-editable/js/bootstrap-editable.js' import _ from 'lodash' export default class XEditable extends React.Component { componentDidMount() { this.xEditable() } componentDidUpdate() { this.xEditable() } xEditable = ()=> { const element = $(this.refs.input); const props = this.props; const options = {...props}; // $log.log(initOptions); element.editable('destroy'); element.editable(options); element.on('save', (e, params) =>{ if (_.isFunction(this.props.onChange)) { this.props.onChange(params.newValue) } }); }; onClick = (e) => { e.preventDefault(); if (_.isFunction(this.props.onClick)) this.props.onClick(); } render() { const {children, ...props} = this.props; const id = props.id || _.uniqueId('x-editable'); return ( <a href="#" onClick={this.onClick} id={id} ref="input"> {children} </a> ) } }
src/svg-icons/social/sentiment-very-satisfied.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialSentimentVerySatisfied = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.47 2 12s4.47 10 9.99 10S22 17.53 22 12 17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-10.06L14.06 11l1.06-1.06L16.18 11l1.06-1.06-2.12-2.12zm-4.12 0L9.94 11 11 9.94 8.88 7.82 6.76 9.94 7.82 11zM12 17.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/> </SvgIcon> ); SocialSentimentVerySatisfied = pure(SocialSentimentVerySatisfied); SocialSentimentVerySatisfied.displayName = 'SocialSentimentVerySatisfied'; SocialSentimentVerySatisfied.muiName = 'SvgIcon'; export default SocialSentimentVerySatisfied;
packages/component/src/SendBox/Assets/MicrophoneIcon.js
billba/botchat
import React from 'react'; const MicrophoneIcon = () => ( <svg height={28} viewBox="0 0 34.75 46" width={28}> <path className="a" d="M29.75,23v6.36a7,7,0,0,1-.56,2.78,7.16,7.16,0,0,1-3.8,3.8,7,7,0,0,1-2.78.56H18.5v2.25H23V41H11.75v-2.25h4.5V36.5h-4.11a7,7,0,0,1-2.78-.56,7.16,7.16,0,0,1-3.8-3.8,7,7,0,0,1-.56-2.78V23h2.25v6.36a4.72,4.72,0,0,0,.39,1.9,4.78,4.78,0,0,0,2.6,2.6,4.72,4.72,0,0,0,1.9.39h10.47a4.72,4.72,0,0,0,1.9-.39,4.78,4.78,0,0,0,2.6-2.6,4.72,4.72,0,0,0,.39-1.9V23Zm-18,5.62a1.13,1.13,0,0,0,1.13,1.13h9a1.13,1.13,0,0,0,1.12-1.13V8.38a1.13,1.13,0,0,0-1.12-1.13h-9a1.13,1.13,0,0,0-1.13,1.13Zm1.13,3.38a3.41,3.41,0,0,1-1.32-.26,3.31,3.31,0,0,1-1.8-1.8,3.41,3.41,0,0,1-.26-1.32V8.38a3.41,3.41,0,0,1,.26-1.32,3.31,3.31,0,0,1,1.8-1.8,3.41,3.41,0,0,1,1.32-.26h9a3.4,3.4,0,0,1,1.31.26,3.31,3.31,0,0,1,1.8,1.8,3.41,3.41,0,0,1,.26,1.32v20.24a3.41,3.41,0,0,1-.26,1.32,3.31,3.31,0,0,1-1.8,1.8,3.4,3.4,0,0,1-1.31.26Z" /> </svg> ); export default MicrophoneIcon;
src/views/containers/pages/error_page/error_page.js
michaelBenin/react-ssr-spa
import React from 'react'; import PropTypes from 'prop-types'; import Footer from './../../../components/footer/footer'; function ErrorPage({ env, componentInfo, err }) { const isDevelopment = env === 'development'; if (isDevelopment) { console.error(err); // eslint-disable-line no-console console.error(err.stack); // eslint-disable-line no-console } return ( <div className="error-page"> <h1>Error Occurred.</h1> {isDevelopment ? ( <div> <h2>Error Message: {err.message}</h2> <h2>Error Stack: {JSON.stringify(err.stack, null, 2)}</h2> <h2>Component Info: {JSON.stringify(componentInfo, null, 2)}</h2> </div> ) : ( <p>We\'re sorry please try again later.</p> )} <Footer /> </div> ); } ErrorPage.propTypes = { err: PropTypes.shape({}), componentInfo: PropTypes.shape({}), env: PropTypes.string.isRequired }; ErrorPage.defaultProps = { err: {}, componentInfo: {} }; export default ErrorPage;
packages/material-ui-icons/src/FeaturedPlayList.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let FeaturedPlayList = props => <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 8H3V9h9v2zm0-4H3V5h9v2z" /> </SvgIcon>; FeaturedPlayList = pure(FeaturedPlayList); FeaturedPlayList.muiName = 'SvgIcon'; export default FeaturedPlayList;
react-ui/src/components/UpdateEmail/UpdateEmail.js
hokustalkshow/find-popular
import React, { Component } from 'react'; import ErrorAlert from '../ErrorAlert/ErrorAlert'; import SpinnerOnly from '../Spinner/SpinnerOnly'; class UpdateEmail extends Component { constructor(props) { super(props); this.state = { showEmailForm: false, newEmail: '', } } displayEmailForm = () => { this.setState({ showEmailForm: true, }); } hideEmailForm = () => { this.setState({ showEmailForm: false, }); } emailInput = (e) => { this.setState({ newEmail: e.target.value, }); } updateEmail = (e) => { e.preventDefault(); this.props.updateEmail(this.props.id, this.state.newEmail) this.hideEmailForm(); } viewOrUpdateEmail = () => { if (this.props.loading) { return <SpinnerOnly /> } if (!this.state.showEmailForm) { return ( <div> {this.props.email} <button onClick={this.displayEmailForm} className="btn btn-link">Change Email</button> </div> ); } return ( <form className="form-group" onSubmit={this.updateEmail}> <input className="form-control" type="email" placeholder="[email protected]" onChange={this.emailInput} /> <br /> <button className="btn btn-primary" type="submit">Submit</button>&nbsp; <button className="btn btn-default" onClick={this.hideEmailForm}>Cancel</button> <ErrorAlert errorMessage={this.props.errorMessage} /> </form> ); } render() { return ( <div> {this.viewOrUpdateEmail()} </div> ); } } export default UpdateEmail;
app/js/components/PITApp.js
makeing/PIT.react
import React from 'react'; import ProjectList from './Project/ProjectList'; import ProjectStore from '../stores/ProjectStore'; function getProjectState() { return { allProjects: ProjectStore.getAll() }; } export default class PITApp extends React.Component { constructor(props) { super(props); this.state = getProjectState(); } componentDidMount() { ProjectStore.addChangeListener(this._onChange); } componentWillUnmount() { ProjectStore.removeChangeListener(this._onChange); } render() { return ( ); } _onChange() { this.setState(getProjectState()); } }
src/js/components/nodes/NodesToolbar/NodesToolbarForm.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import { defineMessages, FormattedMessage, injectIntl } from 'react-intl'; import { Field, reduxForm } from 'redux-form'; import { FormGroup, MenuItem } from 'react-bootstrap'; import PropTypes from 'prop-types'; import React from 'react'; import DropdownSelect from '../../ui/reduxForm/DropdownSelect'; import { nodeColumnMessages } from '../messages'; import { SortDirectionInput } from '../../ui/Toolbar/ToolbarInputs'; const messages = defineMessages({ table: { id: 'ContentView.table', defaultMessage: 'Table view' }, list: { id: 'ContentView.list', defaultMessage: 'List view' }, sortDir: { id: 'NodesToolbarForm.sortDir', defaultMessage: 'Sort direction' } }); const NodesToolbarForm = ({ handleSubmit, intl }) => ( <form onSubmit={handleSubmit}> <FormGroup> <Field name="sortBy" component={DropdownSelect} format={value => intl.formatMessage(nodeColumnMessages[value])} > <MenuItem eventKey="name"> <FormattedMessage {...nodeColumnMessages.name} /> </MenuItem> <MenuItem eventKey="properties.cpu_arch"> <FormattedMessage {...nodeColumnMessages['properties.cpu_arch']} /> </MenuItem> <MenuItem eventKey="properties.cpus"> <FormattedMessage {...nodeColumnMessages['properties.cpus']} /> </MenuItem> <MenuItem eventKey="properties.local_gb"> <FormattedMessage {...nodeColumnMessages['properties.local_gb']} /> </MenuItem> <MenuItem eventKey="properties.memory_mb"> <FormattedMessage {...nodeColumnMessages['properties.memory_mb']} /> </MenuItem> <MenuItem eventKey="power_state"> <FormattedMessage {...nodeColumnMessages.power_state} /> </MenuItem> <MenuItem eventKey="provision_state"> <FormattedMessage {...nodeColumnMessages.provision_state} /> </MenuItem> </Field> <Field name="sortDir" title={intl.formatMessage(messages.sortDir)} component={SortDirectionInput} /> </FormGroup> {/* TODO(akrivoka): Hiding the view switcher for now, as the table view is buggy. Once the blueprint https://blueprints.launchpad.net/tripleo/+spec/ui-rework-nodestableview is implemented, we can show the view switcher again. */} {/* <FormGroup className="pull-right"> <Field name="contentView" component={ContentViewSelectorInput} options={{ list: { title: intl.formatMessage(messages.list), id: 'NodesToolbarForm__listView' }, table: { title: intl.formatMessage(messages.table), id: 'NodesToolbarForm__tableView' } }} /> </FormGroup> */} </form> ); NodesToolbarForm.propTypes = { children: PropTypes.node, handleSubmit: PropTypes.func.isRequired, intl: PropTypes.object.isRequired }; export default injectIntl( reduxForm({ form: 'nodesToolbar' })(NodesToolbarForm) );
tests/lib/rules/vars-on-top.js
bbondy/eslint
/** * @fileoverview Tests for vars-on-top rule. * @author Danny Fritz * @author Gyandeep Singh * @copyright 2014 Danny Fritz. All rights reserved. * @copyright 2014 Gyandeep Singh. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslint = require("../../../lib/eslint"), EslintTester = require("eslint-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var eslintTester = new EslintTester(eslint); eslintTester.addRuleTest("lib/rules/vars-on-top", { valid: [ [ "var first = 0;", "function foo() {", " first = 2;", "}" ].join("\n"), [ "function foo() {", "}" ].join("\n"), [ "function foo() {", " var first;", " if (true) {", " first = true;", " } else {", " first = 1;", " }", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " var third;", " var fourth = 1, fifth, sixth = third;", " var seventh;", " if (true) {", " third = true;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var i;", " for (i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), [ "function foo() {", " var outer;", " function inner() {", " var inner = 1;", " var outer = inner;", " }", " outer = 1;", "}" ].join("\n"), [ "function foo() {", " var first;", " //Hello", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " /*", " Hello Clarice", " */", " var second = 1;", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var first;", " first = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var second = 1;", " function bar(){", " var third;", " third = 5;", " }", " first = second;", "}" ].join("\n"), [ "function foo() {", " var first;", " var bar = function(){", " var third;", " third = 5;", " }", " first = 5;", "}" ].join("\n"), [ "function foo() {", " var first;", " first.onclick(function(){", " var third;", " third = 5;", " });", " first = 5;", "}" ].join("\n"), { code: [ "function foo() {", " var i = 0;", " for (let j = 0; j < 10; j++) {", " alert(j);", " }", " i = i + 1;", "}" ].join("\n"), ecmaFeatures: { blockBindings: true } }, "'use strict'; var x; f();", "'use strict'; 'directive'; var x; var y; f();", "function f() { 'use strict'; var x; f(); }", "function f() { 'use strict'; 'directive'; var x; var y; f(); }", {code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}, {code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }} ], invalid: [ { code: [ "var first = 0;", "function foo() {", " first = 2;", " second = 2;", "}", "var second = 0;" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " first = 1;", " first = 2;", " first = 3;", " first = 4;", " var second = 1;", " second = 2;", " first = second;", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first;", " if (true) {", " var second = true;", " }", " first = second;", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " for (var i = 0; i < 10; i++) {", " alert(i);", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " for (i = 0; i < first; i ++) {", " var second = i;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " switch (first) {", " case 10:", " var hello = 1;", " break;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " var hello = 1;", " } catch (e) {", " alert('error');", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " var i;", " try {", " asdf;", " } catch (e) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " while (first) {", " var hello = 1;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = 10;", " do {", " var hello = 1;", " } while (first == 10);", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " for (var item in first) {", " item++;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "function foo() {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: [ "var foo = () => {", " var first = [1,2,3];", " var item;", " for (item in first) {", " var hello = item;", " }", "}" ].join("\n"), ecmaFeatures: { arrowFunctions: true }, errors: [ { message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration" } ] }, { code: "'use strict'; 0; var x; f();", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "'use strict'; var x; 'directive'; var y; f();", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; 0; var x; f(); }", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] }, { code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }", errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}] } ] });
src/components/Clock.js
LBNL-UCB-STI/beam-viz
/* * A stateless css-clock component * Props: time (in seconds) */ import React from 'react'; import './Clock.scss'; const getHoursAngle = (time_in_seconds) => { const time_in_hours = time_in_seconds / (60 * 60); return time_in_hours * (360 / 12); } const getMinutesAngle = (time_in_seconds) => { const time_in_minutes = time_in_seconds / 60; return time_in_minutes * (360 / 60); } const Clock = ({ time }) => ( <div id='clock'> <div className='hours-container'> <div className='hours' style={{ transform: 'rotateZ(' + getHoursAngle(time) + 'deg)', WebkitTransform: 'rotateZ(' + getHoursAngle(time) + 'deg)', }} /> </div> <div className='minutes-container'> <div className='minutes' style={{ transform: 'rotateZ(' + getMinutesAngle(time) + 'deg)', }} /> </div> <div className='twstyle'>{parseInt(time)}</div> </div> ); export default Clock;
client/src/components/plugins/mention-highlighter.js
shamb0t/orbit
// Based on https://github.com/banyan/react-emoji import React from 'react'; import assign from 'object-assign'; let MentionHighlighter = () => { return { highlight(srcText, highlightText, options = {}) { if(typeof srcText !== 'string') return srcText; if(!srcText || !highlightText) return srcText; if(highlightText === '' || srcText === '') return srcText; const result = srcText.split(' ').map(word => { let match = word.startsWith(highlightText) || word.startsWith(highlightText + ":") || word.startsWith("@" + highlightText) || word.startsWith(highlightText + ","); if (match) { return React.createElement( 'span', assign({className: options.highlightClassName}, options), word + " " ); } else { return word + " "; } }); let r = []; let s = ''; result.forEach((e) => { if(typeof e === 'string') { s += e; } else { r.push(s); r.push(e); s = ''; } }); r.push(s); return r; } }; }; export default MentionHighlighter();
fields/types/geopoint/GeoPointColumn.js
xyzteam2016/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var GeoPointColumn = React.createClass({ displayName: 'GeoPointColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value || !value.length) return null; const formattedValue = `${value[1]}, ${value[0]}`; const formattedTitle = `Lat: ${value[1]} Lng: ${value[0]}`; return ( <ItemsTableValue title={formattedTitle} field={this.props.col.type}> {formattedValue} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = GeoPointColumn;
client/admin/import/ImportHistoryPage.stories.js
Sing-Li/Rocket.Chat
import React from 'react'; import ImportHistoryPage from './ImportHistoryPage'; export default { title: 'admin/import/ImportHistoryPage', component: ImportHistoryPage, }; export const _default = () => <ImportHistoryPage />;
src/layouts/Header.js
dash-/netjumpio-tabs-web
/// // Dependencies /// import React, { Component } from 'react'; import TabSetsLogo from '../elements/TabSetsLogo'; import ProfilePanelButton from '../profile/ProfilePanelButton'; /// // View /// class Header extends Component { render() { return ( <div className="app-header-container dark-theme"> <div className="app-header"> <TabSetsLogo /> <h3 className="title">TabSets</h3> <div className="extras"> <ProfilePanelButton /> </div> </div> <div className="app-header-spacer"></div> </div> ); } } Header.propTypes = {}; export default Header;
docs/src/app/components/pages/components/Paper/ExampleSimple.js
pradel/material-ui
import React from 'react'; import Paper from 'material-ui/Paper'; const style = { height: 100, width: 100, margin: 20, textAlign: 'center', display: 'inline-block', }; const PaperExampleSimple = () => ( <div> <Paper style={style} zDepth={1} /> <Paper style={style} zDepth={2} /> <Paper style={style} zDepth={3} /> <Paper style={style} zDepth={4} /> <Paper style={style} zDepth={5} /> </div> ); export default PaperExampleSimple;
examples/lists-and-named-requests/src/components/BooksList.js
jmeas/resourceful-redux
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { getStatus, getResources } from 'redux-resource'; class BooksList extends Component { render() { const { state } = this.props; const searchStatus = getStatus( state, 'books.requests.readUserBooks.status', true ); const latestStatus = getStatus( state, 'books.requests.readLatestBooks.status', true ); const userBooks = getResources(state.books, 'userBooks'); const latestBooks = getResources(state.books, 'latestBooks'); return ( <div style={{ display: 'flex' }}> <div style={{ width: '350px', marginRight: '50px' }}> <h2>Your Books</h2> {searchStatus.pending && 'Loading your books...'} {searchStatus.succeeded && ( <div> {userBooks.map(book => ( <div key={book.id}> <h3>{book.title}</h3> <div> {book.author} - {book.releaseYear} </div> </div> ))} </div> )} </div> <div style={{ width: '350px' }}> <h2>Recently Released</h2> {latestStatus.pending && 'Loading recently released books...'} {latestStatus.succeeded && ( <div> {latestBooks.map(book => ( <div key={book.id}> <h3>{book.title}</h3> <div> {book.author} - {book.releaseYear} </div> </div> ))} </div> )} </div> </div> ); } componentDidMount() { const { getUserBooks, getLatestBooks } = this.props; getUserBooks(); getLatestBooks(); } } BooksList.propTypes = { getUserBooks: PropTypes.func.isRequired, getLatestBooks: PropTypes.func.isRequired, state: PropTypes.shape({ books: PropTypes.shape({ resources: PropTypes.object.isRequired, meta: PropTypes.object.isRequired, requests: PropTypes.object.isRequired, lists: PropTypes.object.isRequired }) }).isRequired }; export default BooksList;
docs/src/app/components/pages/components/DropDownMenu/ExampleLongMenu.js
tan-jerene/material-ui
import React from 'react'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; const items = []; for (let i = 0; i < 100; i++ ) { items.push(<MenuItem value={i} key={i} primaryText={`Item ${i}`} />); } export default class DropDownMenuLongMenuExample extends React.Component { constructor(props) { super(props); this.state = {value: 10}; } handleChange = (event, index, value) => this.setState({value}); render() { return ( <DropDownMenu maxHeight={300} value={this.state.value} onChange={this.handleChange}> {items} </DropDownMenu> ); } }
app/components/Home.js
SumoCreations/SumoCreationsWeb
import React from 'react'; import { Parse } from 'parse'; export default class Home extends React.Component { handleSSO() { Parse.FacebookUtils.logIn(null, { success: function(user) { if (!user.existed()) { alert("User signed up and logged in through Facebook!"); } else { alert("User logged in through Facebook!"); } }, error: function(user, error) { alert("User cancelled the Facebook login or did not fully authorize."); } }); } render() { return ( <div className="home invisible"> <h2>Welcome Home!</h2> <a className="button" href="#">Anchor button</a> <button onClick={this.handleSSO.bind(this)}>Login w/ Facebook</button> </div> ); } };
actor-apps/app-web/src/app/components/common/Fold.React.js
Rogerlin2013/actor-platform
/* eslint-disable */ import React from 'react'; import classnames from 'classnames'; class Fold extends React.Component { static PropTypes = { icon: React.PropTypes.string, iconClassName: React.PropTypes.string, title: React.PropTypes.string.isRequired }; state = { isOpen: false }; constructor(props) { super(props); } render() { const { icon, iconClassName, title, iconElement } = this.props; const titleIconClassName = classnames('material-icons icon', iconClassName); const className = classnames({ 'fold': true, 'fold--open': this.state.isOpen }); let foldIcon; if (icon) { foldIcon = <i className={titleIconClassName}>{icon}</i>; } if (iconElement) { foldIcon = iconElement; } return ( <div className={className}> <div className="fold__title" onClick={this.onClick}> {foldIcon} {title} <i className="fold__indicator material-icons pull-right">arrow_drop_down</i> </div> <div className="fold__content"> {this.props.children} </div> </div> ); } onClick = () => { this.setState({isOpen: !this.state.isOpen}); }; } export default Fold;
src/components/Button.js
OpenCollective/frontend
import React from 'react'; import PropTypes from 'prop-types'; import colors from '../constants/colors'; import { Router } from '../server/pages'; import HashLink from 'react-scrollchor'; const star = '/static/images/icons/star.svg'; const icons = { star, }; class Button extends React.Component { static propTypes = { label: PropTypes.oneOfType([PropTypes.node, PropTypes.string]), disabled: PropTypes.bool, type: PropTypes.string, // e.g. type="submit" onClick: PropTypes.func, href: PropTypes.string, className: PropTypes.string, icon: PropTypes.string, style: PropTypes.object, }; constructor(props) { super(props); this.renderButton = this.renderButton.bind(this); this.onClick = this.onClick.bind(this); } async onClick(e) { const { type, href, onClick, disabled } = this.props; if (type === 'submit') return; e.preventDefault(); if (href && href.substr(0, 1) !== '#') { await Router.pushRoute(href); window.scrollTo(0, 0); document.body.focus(); } if (!onClick) return; return !disabled && onClick && onClick(); } renderButton() { return ( <button type={this.props.type} disabled={this.props.disabled} style={this.props.style} className={`Button ${this.props.className}`} onClick={this.onClick} > <style jsx> {` .Button { --webkit-appearance: none; font-size: 1.4rem; font-weight: 500; height: 3.6rem; border: 2px solid #45474d; border-radius: 500px; padding: 0 24px; color: #45474d; background-color: transparent; } .Button:hover { border: 2px solid #2e8ae6; } .bluewhite { border: 2px solid #cacbcc; color: #3399ff; } .Button:focus { outline: 0; } .Button:active { background-color: #297acc; border-color: #297acc; } .Button[disabled] { opacity: 0.24; } .Button[type='submit'] { height: 4rem; } div { display: flex; justify-content: center; align-items: center; width: 100%; height: 100%; border: 2px solid; line-height: 17px; border-color: ${colors.lightgray}; } img { height: 1.6rem; margin: 0 0.5rem; } .allcaps { text-transform: 'uppercase'; } .whiteblue, .whiteblue :global(a) { color: ${colors.blue}; background: white; } .whiteblue.small { width: 20rem; } .whiteblue:hover { box-shadow: 0 0 4px 0 rgba(63, 175, 240, 0.4); } .blue { color: white; border-color: ${colors.white}; background-color: ${colors.blue}; } .blue:hover { background-color: ${colors.blueHover}; } .blue:active { background-color: ${colors.blueActive}; border-color: ${colors.blueActive}; } .gray { color: ${colors.darkgray}; border-color: ${colors.lightgray}; background: ${colors.lightgray}; } .gray:hover { color: ${colors.gray}; } .Button :global(a) { display: block; width: 100%; height: 100%; text-align: center; line-height: 5.4rem; } .green { color: white; border-color: ${colors.green}; background: ${colors.green}; } .Button :global(span) { white-space: nowrap; } .darkBackground { color: #e3e4e6; } .ticket, :global(.EventPage .tier .Button) { width: 100%; border-radius: 0; height: 100%; border-color: #3385ff; text-transform: uppercase; font-weight: bold; font-size: 1.7rem; } .ticket, :global(.EventPage .tier .Button:hover) { border-color: #2e8ae6; } `} </style> <style jsx global> {` .mobileOnly .Button { padding: 0 16px; } `} </style> {this.props.icon && <img src={icons[this.props.icon]} />} {this.props.label && <span>{this.props.label}</span>} {this.props.children} </button> ); } render() { const { href } = this.props; if (href && href.substr(0, 1) === '#') { return <HashLink to={href}>{this.renderButton()}</HashLink>; } else { return this.renderButton(); } } } export default Button;
src/server.js
mdonthireddy/js_exp
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import 'babel-core/polyfill'; import path from 'path'; import express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import Router from './routes'; import Html from './components/Html'; const server = global.server = express(); server.set('port', (process.env.PORT || 5000)); server.use(express.static(path.join(__dirname, 'public'))); // // Register API middleware // ----------------------------------------------------------------------------- server.use('/api/content', require('./api/content')); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- server.get('*', async (req, res, next) => { try { let statusCode = 200; const data = { title: '', description: '', css: '', body: '' }; const css = []; const context = { onInsertCss: value => css.push(value), onSetTitle: value => data.title = value, onSetMeta: (key, value) => data[key] = value, onPageNotFound: () => statusCode = 404, }; await Router.dispatch({ path: req.path, context }, (state, component) => { data.body = ReactDOM.renderToString(component); data.css = css.join(''); }); const html = ReactDOM.renderToStaticMarkup(<Html {...data} />); res.status(statusCode).send('<!doctype html>\n' + html); } catch (err) { next(err); } }); // // Launch the server // ----------------------------------------------------------------------------- server.listen(server.get('port'), () => { /* eslint-disable no-console */ console.log('The server is running at http://localhost:' + server.get('port')); if (process.send) { process.send('online'); } });
packages/material-ui-icons/src/LabelOutline.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let LabelOutline = props => <SvgIcon {...props}> <path d="M17.63 5.84C17.27 5.33 16.67 5 16 5L5 5.01C3.9 5.01 3 5.9 3 7v10c0 1.1.9 1.99 2 1.99L16 19c.67 0 1.27-.33 1.63-.84L22 12l-4.37-6.16zM16 17H5V7h11l3.55 5L16 17z" /> </SvgIcon>; LabelOutline = pure(LabelOutline); LabelOutline.muiName = 'SvgIcon'; export default LabelOutline;
packages/react-ui-components/src/_lib/storyUtils.js
grebaldi/PackageFactory.Guevara
import React from 'react'; import PropTypes from 'prop-types'; /** * The StoryWrapper is a simple component which can be used to wrap stories * of the react-storybook lib. */ export const StoryWrapper = ({children, ...rest}) => ( <div style={{background: '#000', padding: '1rem', position: 'relative'}} {...rest} > {children} </div> ); StoryWrapper.propTypes = { children: PropTypes.node.isRequired };
src/utils/filters.js
halo-design/halo-optimus
import React from 'react' const listHasItem = (list, key, val) => { let hasIt = false list.map(item => { if (item[key] === val) { hasIt = true } }) return hasIt } export const checkBtnList = (menu, btnList, noDivider) => { const ableBtn = [] const divider = <span className='ant-divider' /> const size = btnList.length btnList.map((item, i) => { const btn = checkBtn(menu, item.item, item.button) if (btn) { ableBtn.push(btn) if (!noDivider && i !== size - 1) { ableBtn.push(divider) } } }) return ableBtn.length === 0 ? <span>无操作权限</span> : ableBtn.map((item, i) => <span key={i}>{item}</span>) } export const checkBtn = (menu, item, button) => { let menuItem = item if (item.length <= 4) { menuItem = menu.currentMenu + item } return listHasItem(menu.menuItemList, 'menuItemId', menuItem) ? button : null } export const groupList = (list, id, parentId, childName, conver) => { let groupList = [] let keyMap = {} list.map(item => { keyMap[item[id]] = conver ? conver(item) : item }) list.map(item => { if (!item[parentId] || !keyMap[item[parentId]]) { groupList.push(keyMap[item[id]]) } else if (keyMap[item[parentId]]) { if (!keyMap[item[parentId]][childName]) { keyMap[item[parentId]][childName] = [] } keyMap[item[parentId]][childName].push(keyMap[item[id]]) } }) return groupList } export const getNodeFromList = (id, list, idName, childName, conver) => { let node = null for (var el of list) { let chName = el[childName] if (el[idName] === id) { node = conver ? conver(el) : el } else if (chName && chName.length > 0) { node = getNodeFromList(id, chName, idName, childName, conver) if (node) { node = (conver ? conver(node) : node) } } } return node } export const isEmptyObject = obj => { let name for (name in obj) { return false } return true } export const formatDateTime = text => { return `${text.substring(0, 4)}/${text.substring(4, 6)}/${text.substring(6, 8)} ${text.substring(8, 10)}:${text.substring(10, 12)}` } export const str2json = str => { let paramsArr = str.split(',') let jsonArr = [] paramsArr.map(item => { let tmp = {} let li = item.split('=') let key = li[0] let val = li[1] if (!key) { key = '未知' } if (val) { tmp.key = key if (val.indexOf(':') > 0) { val = val.replace(/:/g, ', ') } tmp.value = val jsonArr.push(tmp) } else { jsonArr.push({ key: key, value: '暂无' }) } }) return jsonArr } export const releaseFilter = record => { switch (record) { case '1': return '白名单灰度' case '2': return '时间窗灰度' default: return '正式发布' } } export const enterpriseFilter = record => record === '0' ? '企业包' : '正式包' export const upgradeTypeFilter = record => record === '1' ? '单次提醒' : '多次提醒' export const releaseStatusFilter = record => record === '1' ? '发布中' : record === '2' ? '已结束' : '暂停' export const platformFilter = record => { switch (record) { case '0': return '平台无关' case '1': return 'Android' case '2': return 'IOS' default: return record } } export const operationFilter = record => { switch (record) { case '1': return '包含' case '2': return '不包含' case '3': return '范围内' case '4': return '范围外' default: return record } } export const resourceFilter = record => { switch (record) { case 'version': return '版本号' case 'city': return '城市' case 'mobileModel': return '机型' case 'netType': return '网络' case 'osVersion': return 'OS版本' default: return record } } export const whitelistIdsFilter = data => data.map(item => item.whiteListName) export const formatGreyConfigInfo = data => { const rules = JSON.parse(data).subRules return rules.map(item => ({ ruleElement: item.right, operation: item.operator, value: Array.isArray(item.left) ? item.left.join(', ') : isEmptyObject(item.left) ? '暂无' : `${item.left.upper} - ${item.left.lower}` })) } export const whiteListFilter = record => { switch (record) { case 'userid': return '用户白名单' default: return record } } export const businessFilter = record => { switch (record) { case 'hotpatch': return '热修复' case 'upgrade': return '升级' default: return record } }
src/DayColumn.js
intljusticemission/react-big-calendar
import PropTypes from 'prop-types' import React from 'react' import { findDOMNode } from 'react-dom' import clsx from 'clsx' import Selection, { getBoundsForNode, isEvent } from './Selection' import * as dates from './utils/dates' import * as TimeSlotUtils from './utils/TimeSlots' import { isSelected } from './utils/selection' import { notify } from './utils/helpers' import * as DayEventLayout from './utils/DayEventLayout' import TimeSlotGroup from './TimeSlotGroup' import TimeGridEvent from './TimeGridEvent' import { DayLayoutAlgorithmPropType } from './utils/propTypes' class DayColumn extends React.Component { state = { selecting: false, timeIndicatorPosition: null } intervalTriggered = false constructor(...args) { super(...args) this.slotMetrics = TimeSlotUtils.getSlotMetrics(this.props) } componentDidMount() { this.props.selectable && this._selectable() if (this.props.isNow) { this.setTimeIndicatorPositionUpdateInterval() } } componentWillUnmount() { this._teardownSelectable() this.clearTimeIndicatorInterval() } UNSAFE_componentWillReceiveProps(nextProps) { if (nextProps.selectable && !this.props.selectable) this._selectable() if (!nextProps.selectable && this.props.selectable) this._teardownSelectable() this.slotMetrics = this.slotMetrics.update(nextProps) } componentDidUpdate(prevProps, prevState) { const getNowChanged = !dates.eq( prevProps.getNow(), this.props.getNow(), 'minutes' ) if (prevProps.isNow !== this.props.isNow || getNowChanged) { this.clearTimeIndicatorInterval() if (this.props.isNow) { const tail = !getNowChanged && dates.eq(prevProps.date, this.props.date, 'minutes') && prevState.timeIndicatorPosition === this.state.timeIndicatorPosition this.setTimeIndicatorPositionUpdateInterval(tail) } } else if ( this.props.isNow && (!dates.eq(prevProps.min, this.props.min, 'minutes') || !dates.eq(prevProps.max, this.props.max, 'minutes')) ) { this.positionTimeIndicator() } } /** * @param tail {Boolean} - whether `positionTimeIndicator` call should be * deferred or called upon setting interval (`true` - if deferred); */ setTimeIndicatorPositionUpdateInterval(tail = false) { if (!this.intervalTriggered && !tail) { this.positionTimeIndicator() } this._timeIndicatorTimeout = window.setTimeout(() => { this.intervalTriggered = true this.positionTimeIndicator() this.setTimeIndicatorPositionUpdateInterval() }, 60000) } clearTimeIndicatorInterval() { this.intervalTriggered = false window.clearTimeout(this._timeIndicatorTimeout) } positionTimeIndicator() { const { min, max, getNow } = this.props const current = getNow() if (current >= min && current <= max) { const top = this.slotMetrics.getCurrentTimePosition(current) this.setState({ timeIndicatorPosition: top }) } else { this.clearTimeIndicatorInterval() } } render() { const { max, rtl, isNow, resource, accessors, localizer, getters: { dayProp, ...getters }, components: { eventContainerWrapper: EventContainer, ...components }, } = this.props let { slotMetrics } = this let { selecting, top, height, startDate, endDate } = this.state let selectDates = { start: startDate, end: endDate } const { className, style } = dayProp(max) return ( <div style={style} className={clsx( className, 'rbc-day-slot', 'rbc-time-column', isNow && 'rbc-now', isNow && 'rbc-today', // WHY selecting && 'rbc-slot-selecting' )} > {slotMetrics.groups.map((grp, idx) => ( <TimeSlotGroup key={idx} group={grp} resource={resource} getters={getters} components={components} /> ))} <EventContainer localizer={localizer} resource={resource} accessors={accessors} getters={getters} components={components} slotMetrics={slotMetrics} > <div className={clsx('rbc-events-container', rtl && 'rtl')}> {this.renderEvents()} </div> </EventContainer> {selecting && ( <div className="rbc-slot-selection" style={{ top, height }}> <span>{localizer.format(selectDates, 'selectRangeFormat')}</span> </div> )} {isNow && ( <div className="rbc-current-time-indicator" style={{ top: `${this.state.timeIndicatorPosition}%` }} /> )} </div> ) } renderEvents = () => { let { events, rtl, selected, accessors, localizer, getters, components, step, timeslots, dayLayoutAlgorithm, } = this.props const { slotMetrics } = this const { messages } = localizer let styledEvents = DayEventLayout.getStyledEvents({ events, accessors, slotMetrics, minimumStartDifference: Math.ceil((step * timeslots) / 2), dayLayoutAlgorithm, }) return styledEvents.map(({ event, style }, idx) => { let end = accessors.end(event) let start = accessors.start(event) let format = 'eventTimeRangeFormat' let label const startsBeforeDay = slotMetrics.startsBeforeDay(start) const startsAfterDay = slotMetrics.startsAfterDay(end) if (startsBeforeDay) format = 'eventTimeRangeEndFormat' else if (startsAfterDay) format = 'eventTimeRangeStartFormat' if (startsBeforeDay && startsAfterDay) label = messages.allDay else label = localizer.format({ start, end }, format) let continuesEarlier = startsBeforeDay || slotMetrics.startsBefore(start) let continuesLater = startsAfterDay || slotMetrics.startsAfter(end) return ( <TimeGridEvent style={style} event={event} label={label} key={'evt_' + idx} getters={getters} rtl={rtl} components={components} continuesEarlier={continuesEarlier} continuesLater={continuesLater} accessors={accessors} selected={isSelected(event, selected)} onClick={e => this._select(event, e)} onDoubleClick={e => this._doubleClick(event, e)} /> ) }) } _selectable = () => { let node = findDOMNode(this) let selector = (this._selector = new Selection(() => findDOMNode(this), { longPressThreshold: this.props.longPressThreshold, })) let maybeSelect = box => { let onSelecting = this.props.onSelecting let current = this.state || {} let state = selectionState(box) let { startDate: start, endDate: end } = state if (onSelecting) { if ( (dates.eq(current.startDate, start, 'minutes') && dates.eq(current.endDate, end, 'minutes')) || onSelecting({ start, end, resourceId: this.props.resource }) === false ) return } if ( this.state.start !== state.start || this.state.end !== state.end || this.state.selecting !== state.selecting ) { this.setState(state) } } let selectionState = point => { let currentSlot = this.slotMetrics.closestSlotFromPoint( point, getBoundsForNode(node) ) if (!this.state.selecting) { this._initialSlot = currentSlot } let initialSlot = this._initialSlot if (dates.lte(initialSlot, currentSlot)) { currentSlot = this.slotMetrics.nextSlot(currentSlot) } else if (dates.gt(initialSlot, currentSlot)) { initialSlot = this.slotMetrics.nextSlot(initialSlot) } const selectRange = this.slotMetrics.getRange( dates.min(initialSlot, currentSlot), dates.max(initialSlot, currentSlot) ) return { ...selectRange, selecting: true, top: `${selectRange.top}%`, height: `${selectRange.height}%`, } } let selectorClicksHandler = (box, actionType) => { if (!isEvent(findDOMNode(this), box)) { const { startDate, endDate } = selectionState(box) this._selectSlot({ startDate, endDate, action: actionType, box, }) } this.setState({ selecting: false }) } selector.on('selecting', maybeSelect) selector.on('selectStart', maybeSelect) selector.on('beforeSelect', box => { if (this.props.selectable !== 'ignoreEvents') return return !isEvent(findDOMNode(this), box) }) selector.on('click', box => selectorClicksHandler(box, 'click')) selector.on('doubleClick', box => selectorClicksHandler(box, 'doubleClick')) selector.on('select', bounds => { if (this.state.selecting) { this._selectSlot({ ...this.state, action: 'select', bounds }) this.setState({ selecting: false }) } }) selector.on('reset', () => { if (this.state.selecting) { this.setState({ selecting: false }) } }) } _teardownSelectable = () => { if (!this._selector) return this._selector.teardown() this._selector = null } _selectSlot = ({ startDate, endDate, action, bounds, box }) => { let current = startDate, slots = [] while (dates.lte(current, endDate)) { slots.push(current) current = new Date(+current + this.props.step * 60 * 1000) // using Date ensures not to create an endless loop the day DST begins } notify(this.props.onSelectSlot, { slots, start: startDate, end: endDate, resourceId: this.props.resource, action, bounds, box, }) } _select = (...args) => { notify(this.props.onSelectEvent, args) } _doubleClick = (...args) => { notify(this.props.onDoubleClickEvent, args) } } DayColumn.propTypes = { events: PropTypes.array.isRequired, step: PropTypes.number.isRequired, date: PropTypes.instanceOf(Date).isRequired, min: PropTypes.instanceOf(Date).isRequired, max: PropTypes.instanceOf(Date).isRequired, getNow: PropTypes.func.isRequired, isNow: PropTypes.bool, rtl: PropTypes.bool, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, showMultiDayTimes: PropTypes.bool, culture: PropTypes.string, timeslots: PropTypes.number, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), eventOffset: PropTypes.number, longPressThreshold: PropTypes.number, onSelecting: PropTypes.func, onSelectSlot: PropTypes.func.isRequired, onSelectEvent: PropTypes.func.isRequired, onDoubleClickEvent: PropTypes.func.isRequired, className: PropTypes.string, dragThroughEvents: PropTypes.bool, resource: PropTypes.any, dayLayoutAlgorithm: DayLayoutAlgorithmPropType, } DayColumn.defaultProps = { dragThroughEvents: true, timeslots: 2, } export default DayColumn
js/components/blankPage/index.js
phamngoclinh/PetOnline_vs2
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { AppRegistry, View, TextInput, ScrollView, Dimensions, AsyncStorage } from 'react-native'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Content, Text, Button, Icon, List, ListItem, Thumbnail, Spinner } from 'native-base'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; // For REALTIME Chatimport var petAppId = ''; window.navigator.userAgent = 'ReactNative'; import feathers from 'feathers/client' import hooks from 'feathers-hooks'; import socketio from 'feathers-socketio/client' import authentication from 'feathers-authentication/client'; var io = require('../../packages/socket.io-client/socket.io'); const PLACEHOLDER = '../../../images/avatarThumbnail.png'; const defaultAvatar = require('../../../images/avatarThumbnail.png'); const ScreenHeight = Dimensions.get("window").height; const ScreenWidth = Dimensions.get("window").width; const { popRoute, } = actions; const apiLink = 'http://210.211.118.178/PetsAPI/'; const petAlbum = 'http://210.211.118.178/PetsAPI/Images/PetThumbnails/'; const userAlbum = 'http://210.211.118.178/PetsAPI/Images/UserThumbnails/'; var user_Id = ''; var authToken = ''; var avatarThumbnail = ''; var coverThumbnail = ''; var my_email = ''; class UselessTextInput extends Component { render() { return ( <TextInput {...this.props} editable = {true} maxLength = {350} /> ); } } class BlankPage extends Component { static propTypes = { name: React.PropTypes.string, index: React.PropTypes.number, list: React.PropTypes.arrayOf(React.PropTypes.string), openDrawer: React.PropTypes.func, popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } constructor(props) { super(props); this.state = { text: '', messages: [], skip: 0, hasMoreMessages : false, loading: true, is_loading_data : false, user : null, username: '', email: '', phone : '' }; const options = {transports: ['websocket'], forceNew: true}; const socket = io('http://192.168.56.1:3030', options); this.featherAPI = feathers() .configure(socketio(socket, {timeout: 50000})) .configure(hooks()) // Use AsyncStorage to store our login toke .configure(authentication({ storage: AsyncStorage })); // this.formatMessage = this.formatMessage.bind(this); // this.loadMessages = this.loadMessages.bind(this); // this.deleteMessage = this.deleteMessage.bind(this); } componentDidMount() { let _this = this; AsyncStorage.getItem('AUTH_TOKEN').then((value) => { authToken = value; }); _this.getUserInformation(); AsyncStorage.getItem('PETAPP_ID').then((value) => { petAppId = value; }); this.featherAPI.io.on('connect', () => { console.log("Connect to Socket success"); this.featherAPI.service('messages').on('created', message => { const messages = this.state.messages; messages.push(_this.formatMessage(message)); _this.setState({messages}); }); AsyncStorage.getItem('USER_EMAIL').then((value) => { var loginInfo = { type: 'local', email: value, password: '123456', }; _this.featherAPI.authenticate(loginInfo).then((response) => { console.log(response); console.log('auth ok'); AsyncStorage.setItem('PETAPP_ID', response.data._id); petAppId = response.data._id; _this.loadMessages(); _this.setState({loading: false}); }).catch((error) => { console.log(error); console.log('auth fail'); _this.setState({loading: false}); alert("auth fail"); }); }) }); } componentWillMount() { } getUserInformation() { let _this = this; AsyncStorage.getItem('USER_ID').then((value) => { console.log("UserId in sidebar: ", value); // alert("UserId in sidebar: ", value); fetch('http://210.211.118.178/PetsAPI/api/userauthinfos/'+value, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Auth-Token': authToken } }) .then((response) => response.json()) .then((responseJson) => { my_email = responseJson.email, // Store the results in the state variable results and set loading to _this.setState({ user: responseJson, username: responseJson.firstName + " " + responseJson.lastName, email: responseJson.email, phone: responseJson.phone, is_loading_data: false }); avatarThumbnail = responseJson.avatarThumbnail; coverThumbnail = responseJson.coverThumbnail; if(avatarThumbnail == null || avatarThumbnail == '') { avatarThumbnail = '../../../images/avatar.png'; } if(coverThumbnail == null || coverThumbnail == '') { coverThumbnail = '../../../images/avatar.png'; } console.log("Get USER from server: ", responseJson); }) .catch((error) => { _this.setState({ loading: false }); console.error(error); }); }); } createMessage() { let _this = this; this.featherAPI.service('messages').create({ text: this.state.text }).then((result) => { _this.setState({text: ''}); console.log("Tin nhắn được khởi tạo từ App: ", result); }).catch((error) => { console.log("Lỗi. Không thể tạo tin nhắn"); }); } formatMessage(message) { return { id: message._id, name: message.sentBy._id === petAppId ? (this.state.username ? this.state.username : message.sentBy.email) : message.sentBy.email, text: message.text, position: message.sentBy._id === petAppId ? 'right' : 'left', // image: {uri: message.sentBy.avatar ? message.sentBy.avatar : PLACEHOLDER }, image: message.sentBy._id === petAppId ? (avatarThumbnail ? {uri: userAlbum + avatarThumbnail} : defaultAvatar) : defaultAvatar, date: message.createdAt }; } loadMessages() { let _this = this; const query = {query: {$sort: {updatedAt: -1}, $limit: 15}}; this.featherAPI.service('messages').find(query).then((response) => { console.log("Response: ", response); if(response.total > 0) { const messages = this.state.messages; result = response.data; console.log(response); result.forEach(function(message) { messages.push(_this.formatMessage(message)); }); messages.reverse(); _this.setState({messages}); } }).catch((error) => { console.log("error: ", error); }); } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { const { props: { name, index, list } } = this; return ( <Container style={styles.container}> <Header> <Button transparent onPress={() => this.popRoute()}> <Icon name="ios-arrow-back" /> </Button> <Title>{(name) ? this.props.name : 'PHÒNG TÁN GẪU'}</Title> <Button transparent onPress={this.props.openDrawer}> <Icon name="ios-menu" /> </Button> </Header> <Content> <View style={{flex:1, flexDirection: 'column', justifyContent: 'space-between', height: ScreenHeight - 80}}> <View style={{flex: 10, backgroundColor: '#FFFFFF'}}> <ScrollView ref='_scrollView' onContentSizeChange={(contentWidth, contentHeight) => { this.refs._scrollView.scrollTo({x: 0, y: contentHeight, animated: true}); }} style={{backgroundColor: '#ffffff'}} > <View style={styles.chatWrapper}> <List style={{paddingLeft: 0}}> { this.state.messages ? this.state.messages.map((message, index) => { return ( <ListItem key={message.id} style={{paddingLeft: 0, marginLeft: 0, borderBottomWidth: 0, marginBottom: 5, marginTop: 5, flexDirection: 'row'}}> { message.position === 'right' ? ( <Thumbnail source={message.image} style={{ alignSelf:'flex-end', marginTop: 5, width: 60, height: 60, borderRadius: 100, position: 'absolute', right: 0, top: 10 }} /> ) : (<Thumbnail source={message.image} style={{ alignSelf:'flex-start', marginTop: 5, width: 60, height: 60, borderRadius: 100, position: 'absolute', left: 0, top: 10 }} />) } { message.position === 'right' ? ( <Text note style={{alignSelf:'flex-end',marginRight: 65, marginBottom: 5}}>{ message.name }</Text> ) : ( <Text note style={{alignSelf:'flex-start',marginLeft: 60, marginBottom: 5}}>{ message.name }</Text> ) } { message.position === 'right' ? ( <Text note style={{ backgroundColor: '#0084ff', color:'#ffffff', fontSize: 15, padding: 10, borderTopRightRadius: 5, borderBottomRightRadius: 10, borderTopLeftRadius: 10, borderBottomLeftRadius: 10, alignSelf:'flex-end', marginRight: 65, maxWidth: ScreenWidth - 200, lineHeight: 20 }}> { message.text } </Text> ) : ( <Text note style={{ backgroundColor: '#f3f3f3', color:'#333333', fontSize: 15, padding: 10, borderTopLeftRadius: 5, borderBottomLeftRadius: 10, borderTopRightRadius: 10, borderBottomRightRadius: 10, alignSelf:'flex-start', marginLeft: 60, maxWidth: ScreenWidth - 200, lineHeight: 20 }}> { message.text } </Text> ) } </ListItem> ) }) : null } </List> </View> </ScrollView> </View> <View style={{flex: 2, borderTopWidth: 1, borderTopColor: '#cccccc'}}> <UselessTextInput placeholder="Soạn tin nhắn..." multiline = {true} numberOfLines = {4} onChangeText={(text) => this.setState({text})} value={this.state.text} style={{paddingLeft: 10, paddingRight: 10}}/> <View style={{flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 10, paddingRight: 10}}> <Button transparent><Icon name='ios-heart-outline' style={{fontSize: 25, color: '#333333'}}/></Button> <Button transparent><Icon name='ios-contact-outline' style={{fontSize: 25, color: '#333333'}}/></Button> <Button transparent><Icon name='ios-microphone-outline' style={{fontSize: 25, color: '#333333'}}/></Button> <Button transparent><Icon name='ios-photos-outline' style={{fontSize: 25, color: '#333333'}}/></Button> <Button transparent onPress = {() => this.createMessage()}><Icon name='ios-send-outline' style={{fontSize: 25, color: '#333333'}}/></Button> </View> </View> </View> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, name: state.user.name, index: state.list.selectedIndex, list: state.list.list, }); export default connect(mapStateToProps, bindAction)(BlankPage);
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-bootstrap/0.31.0/es/NavbarCollapse.js
JamieMason/npm-cache-benchmark
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 React from 'react'; import PropTypes from 'prop-types'; import Collapse from './Collapse'; import { prefix } from './utils/bootstrapUtils'; var contextTypes = { $bs_navbar: PropTypes.shape({ bsClass: PropTypes.string, expanded: PropTypes.bool }) }; var NavbarCollapse = function (_React$Component) { _inherits(NavbarCollapse, _React$Component); function NavbarCollapse() { _classCallCheck(this, NavbarCollapse); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } NavbarCollapse.prototype.render = function render() { var _props = this.props, children = _props.children, props = _objectWithoutProperties(_props, ['children']); var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' }; var bsClassName = prefix(navbarProps, 'collapse'); return React.createElement( Collapse, _extends({ 'in': navbarProps.expanded }, props), React.createElement( 'div', { className: bsClassName }, children ) ); }; return NavbarCollapse; }(React.Component); NavbarCollapse.contextTypes = contextTypes; export default NavbarCollapse;
src/Popover.js
mxc/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import CustomPropTypes from './utils/CustomPropTypes'; const Popover = React.createClass({ mixins: [ BootstrapMixin ], propTypes: { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: CustomPropTypes.isRequiredForA11y( React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]) ), /** * Sets the direction the Popover is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "left" position value for the Popover. */ positionLeft: React.PropTypes.number, /** * The "top" position value for the Popover. */ positionTop: React.PropTypes.number, /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * The "top" position value for the Popover arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * Title text */ title: React.PropTypes.node }, getDefaultProps() { return { placement: 'right' }; }, render() { const classes = { 'popover': true, [this.props.placement]: true }; const style = { 'left': this.props.positionLeft, 'top': this.props.positionTop, 'display': 'block', // we don't want to expose the `style` property ...this.props.style // eslint-disable-line react/prop-types }; const arrowStyle = { 'left': this.props.arrowOffsetLeft, 'top': this.props.arrowOffsetTop }; return ( <div role="tooltip" {...this.props} className={classNames(this.props.className, classes)} style={style} title={null}> <div className="arrow" style={arrowStyle} /> {this.props.title ? this.renderTitle() : null} <div className="popover-content"> {this.props.children} </div> </div> ); }, renderTitle() { return ( <h3 className="popover-title">{this.props.title}</h3> ); } }); export default Popover;
fields/components/columns/ArrayColumn.js
Yaska/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var ArrayColumn = React.createClass({ displayName: 'ArrayColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value || !value.length) return null; return value.join(', '); }, render () { return ( <ItemsTableCell> <ItemsTableValue field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = ArrayColumn;
packages/extra/src/LinearGradient.js
finnfiddle/number-picture
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import get from 'lodash.get'; import gradients from '../node_modules/uigradients/gradients.json'; import { types } from '@potion/util'; const GRADIENTS_HASH = gradients.reduce((acc, g) => ({ ...acc, [g.name.toLowerCase()]: g.colors, }), {}); const GRADIENT_NAMES = Object.keys(GRADIENTS_HASH); const randomGradientName = () => { const index = Math.floor(Math.random() * GRADIENT_NAMES.length); return GRADIENT_NAMES[index]; }; export default class LinearGradient extends Component { static propTypes = { components: PropTypes.shape({ linearGradient: PropTypes.node, stop: PropTypes.node, }), name: PropTypes.oneOf(GRADIENT_NAMES), colors: PropTypes.array, offsets: PropTypes.arrayOf(PropTypes.string), } static defaultProps = { offsets: [], }; static contextTypes = { components: types.components, } render() { const { name, colors, components, offsets, ...rest } = this.props; const finalColors = colors || GRADIENTS_HASH[name || randomGradientName()]; const numColors = finalColors.length; const the = { linearGradient: get(this, 'context.components.linearGradient') || get(components, 'linearGradient') || 'linearGradient', stop: get(this, 'context.components.stop') || get(components, 'stop') || 'stop', }; return ( <the.linearGradient {...rest}> { finalColors.map((color, i) => ( <the.stop key={color} stopColor={color} // offset={offsets[i]} offset={offsets[i] || `${(100 / numColors) * i}%`} /> )) } </the.linearGradient> ); } }
samples/apollo-client/src/index.js
johnberzy-bazinga/FSharp.Data.GraphQL
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import QueryRunner from './QueryRunner'; ReactDOM.render(<QueryRunner />, document.getElementById('root'));
examples/with-algolia-react-instantsearch/components/head.js
flybayer/next.js
import NextHead from 'next/head' import { string } from 'prop-types' import React from 'react' const defaultDescription = '' const defaultOGURL = '' const defaultOGImage = '' export const Head = (props) => ( <NextHead> <meta charSet="UTF-8" /> <title>{props.title || ''}</title> <meta name="description" content={props.description || defaultDescription} /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" sizes="192x192" href="/static/touch-icon.png" /> <link rel="apple-touch-icon" href="/static/touch-icon.png" /> <link rel="mask-icon" href="/static/favicon-mask.svg" color="#49B882" /> <meta property="og:url" content={props.url || defaultOGURL} /> <meta property="og:title" content={props.title || ''} /> <meta property="og:description" content={props.description || defaultDescription} /> <meta name="twitter:site" content={props.url || defaultOGURL} /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:image" content={props.ogImage || defaultOGImage} /> <meta property="og:image" content={props.ogImage || defaultOGImage} /> <meta property="og:image:width" content="1200" /> <meta property="og:image:height" content="630" /> <link rel="stylesheet" href="https://unpkg.com/[email protected]/style.min.css" /> <link rel="stylesheet" href="../static/instantsearch.css" /> </NextHead> ) Head.propTypes = { title: string, description: string, url: string, ogImage: string, } export default Head
packages/ringcentral-widgets-docs/src/app/pages/Components/SlideMenu/Demo.js
ringcentral/ringcentral-js-widget
import React from 'react'; // eslint-disable-next-line import SlideMenu from 'ringcentral-widgets/components/SlideMenu'; const props = {}; /** * A example of `SlideMenu` */ const SlideMenuDemo = () => <SlideMenu {...props} />; export default SlideMenuDemo;
src/components/Footer/Footer.js
kuao775/mandragora
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Footer.css'; import Link from '../Link'; class Footer extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <span className={s.text}>© Mandragora</span> <span className={s.spacer}>·</span> <Link className={s.link} to="/"> Home </Link> <span className={s.spacer}>·</span> <Link className={s.link} to="/admin"> Admin </Link> <span className={s.spacer}>·</span> </div> </div> ); } } export default withStyles(s)(Footer);
packages/mineral-ui-icons/src/IconNextWeek.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconNextWeek(props: IconProps) { const iconProps = { rtl: true, ...props }; return ( <Icon {...iconProps}> <g> <path d="M20 7h-4V5c0-.55-.22-1.05-.59-1.41C15.05 3.22 14.55 3 14 3h-4c-1.1 0-2 .9-2 2v2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zM10 5h4v2h-4V5zm1 13.5l-1-1 3-3-3-3 1-1 4 4-4 4z"/> </g> </Icon> ); } IconNextWeek.displayName = 'IconNextWeek'; IconNextWeek.category = 'content';
examples/todos-flow/src/components/TodoList.js
bvasko/redux
// @flow import React from 'react' import Todo from './Todo' import type { Todos, Id } from '../types' export type Props = { todos: Todos, onTodoClick: (id: Id) => void }; const TodoList = ({ todos, onTodoClick }: Props) => ( <ul> {todos.map(todo => <Todo key={todo.id} {...todo} onClick={() => onTodoClick(todo.id)} /> )} </ul> ) export default TodoList
src/components/MessageDialog/MessageDialog.js
austinknight/ui-components
import React from 'react'; import styled from 'styled-components'; import Modal from '../Modal' import ButtonBar from '../ButtonBar'; import { colors, fontSizes, typography, renderThemeIfPresentOrDefault, } from '../styles'; const Title = styled.div` width: 100%; color: ${renderThemeIfPresentOrDefault({ key: 'white90', defaultValue: colors.black87 })}; margin-bottom: 8px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: inline-block; ${typography.title} `; const ContentWrapper = styled.div` padding: 0 8px; `; const BodyDisplay = styled.div` margin-bottom: 20px; color: ${renderThemeIfPresentOrDefault({ key: 'white', defaultValue: colors.black60 })}; ${typography.body1} margin-top: ${(props) => { if (props.dialogTitle) { return '0'; } return '8px'; }}; p { ${typography.body1} } `; class MessageDialog extends React.Component { render() { const { dialogTitle, bodyElement, center, ...props } = this.props; const canRenderButtonBar = props.primaryActionText || props.secondaryActionText; return ( <Modal {...props}> <ContentWrapper> { dialogTitle && <Title className='MessageDialog__Title' title={dialogTitle}>{dialogTitle}</Title> } <BodyDisplay className='MessageDialog__BodyDisplay' dialogTitle={dialogTitle}> {bodyElement} </BodyDisplay> </ContentWrapper> {canRenderButtonBar && <ButtonBar className='MessageDialog__ButtonBar' {...this.props} /> } </Modal> ); } } export const StyledMessageDialog = styled(MessageDialog)` button { font-size: ${fontSizes.xSmall} } `; MessageDialog.defaultProps = { actionLoading: false, bodyElement: <div />, dialogTitle: '', isActionDisabled: false, }; export default MessageDialog;
20200300-js-spa-react-node-sql/client/src/components/UIHelpModal.js
DamienFremont/blog
import React from 'react'; import { FormattedMessage } from 'react-intl'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faCheck } from '@fortawesome/free-solid-svg-icons'; import { Button, Modal, ModalFooter } from 'reactstrap'; const UIHelpModal = (props) => { const settingsName = props.settingsName; const toggle = props.toggle; const isOpen = props.isOpen; const defaultChecked = localStorage.getItem(settingsName === false); function onChange(e) { localStorage.setItem(settingsName, e.target.checked); } return ( <Modal isOpen={isOpen} toggle={toggle} fade={true} centered={true}> {props.children} <ModalFooter className="d-flex justify-content-between"> <div className="custom-control custom-switch"> <input type="checkbox" className="custom-control-input" id="customSwitch1" defaultChecked={defaultChecked} onChange={onChange} /> <label className="custom-control-label" for="customSwitch1"> <FormattedMessage id="UIHelpModal.hide" /> </label> </div> <Button color="primary" onClick={toggle}> <FontAwesomeIcon icon={faCheck} />{' '} <FormattedMessage id="UIHelpModal.ok" /> </Button> </ModalFooter> </Modal> ); } export default UIHelpModal;
src/parser/shaman/elemental/modules/talents/MasterOfTheElements.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import { formatNumber, formatPercentage } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import SPELLS from 'common/SPELLS'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import SpellLink from 'common/SpellLink'; import { SELECTED_PLAYER } from 'parser/core/EventFilter'; import Events from 'parser/core/Events'; import SUGGESTION_IMPORTANCE from 'parser/core/ISSUE_IMPORTANCE'; const MASTER_OF_THE_ELEMENTS = { INCREASE: 0.2, DURATION: 15000, WINDOW_DURATION: 500, AFFECTED_DAMAGE: [ SPELLS.ICEFURY_TALENT, SPELLS.ICEFURY_OVERLOAD, SPELLS.FROST_SHOCK, SPELLS.LIGHTNING_BOLT, SPELLS.LIGHTNING_BOLT_OVERLOAD, SPELLS.CHAIN_LIGHTNING, SPELLS.CHAIN_LIGHTNING_OVERLOAD, SPELLS.ELEMENTAL_BLAST_TALENT, SPELLS.ELEMENTAL_BLAST_OVERLOAD, SPELLS.EARTH_SHOCK, ], AFFECTED_CASTS: [ SPELLS.EARTHQUAKE, SPELLS.ICEFURY_TALENT, SPELLS.FROST_SHOCK, SPELLS.ELEMENTAL_BLAST_TALENT, SPELLS.CHAIN_LIGHTNING, SPELLS.EARTH_SHOCK, SPELLS.LIGHTNING_BOLT, ], TALENTS: [ SPELLS.ICEFURY_TALENT.id, SPELLS.ELEMENTAL_BLAST_TALENT.id, ], }; class MasterOfTheElements extends Analyzer { moteBuffedAbilities = {}; moteActivationTimestamp = null; moteConsumptionTimestamp = null; damageGained = 0; bugCheckNecessary = false; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.MASTER_OF_THE_ELEMENTS_TALENT.id); for (const key in MASTER_OF_THE_ELEMENTS.AFFECTED_CASTS) { const spellid = MASTER_OF_THE_ELEMENTS.AFFECTED_CASTS[key].id; if((this.selectedCombatant.hasTalent(spellid)) || (!MASTER_OF_THE_ELEMENTS.TALENTS.includes(spellid))) { this.moteBuffedAbilities[spellid] = 0; } } this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(MASTER_OF_THE_ELEMENTS.AFFECTED_CASTS), this._onCast); this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.LAVA_BURST), this._onLvBCast); this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(MASTER_OF_THE_ELEMENTS.AFFECTED_DAMAGE), this._onDamage); } _onCast(event){ if(this.moteActivationTimestamp===null){ //the buff is a clusterfuck so we just track it manually return; } this.moteConsumptionTimestamp=event.timestamp; this.moteActivationTimestamp=null; event.meta = event.meta || {}; event.meta.isEnhancedCast = true; this.moteBuffedAbilities[event.ability.guid]++; } _onLvBCast(event){ this.moteActivationTimestamp = event.timestamp; this.bugCheckNecessary = true; } _onDamage(event){ if (event.timestamp<this.moteConsumptionTimestamp || event.timestamp>this.moteConsumptionTimestamp+MASTER_OF_THE_ELEMENTS.WINDOW_DURATION){ return; } this.damageGained += calculateEffectiveDamage(event, MASTER_OF_THE_ELEMENTS.INCREASE); } get damagePercent() { return this.owner.getPercentageOfTotalDamageDone(this.damageGained); } get damagePerSecond() { return this.damageGained / (this.owner.fightDuration / 1000); } get isBugged() { return this.bugCheckNecessary && (this.selectedCombatant.getBuffUptime(SPELLS.MASTER_OF_THE_ELEMENTS_BUFF.id) || 0) === 0; } get suggestionTresholds() { return { actual: this.isBugged, isEqual: true, style: 'boolean', }; } reverseEffectiveDamageDonePerSecond(number, increase){ return number*(1 + increase)/this.owner.fightDuration*1000; } suggestions(when){ when(this.suggestionTresholds) .addSuggestion((suggest) => { return suggest(<>Master Of the Elements bugged out and you lost out on at least {formatNumber(this.reverseEffectiveDamageDonePerSecond(this.damageGained,MASTER_OF_THE_ELEMENTS.INCREASE))} DPS. Consider getting this weakaura: <a href="https://wago.io/motecheck">MotE-Checker</a> to be notified when MotE goes belly up again.</>) .icon(SPELLS.MASTER_OF_THE_ELEMENTS_TALENT.icon) .staticImportance(SUGGESTION_IMPORTANCE.MAJOR); }); } statistic() { let value = `${formatPercentage(this.damagePercent)} %`; let label = `Contributed ${formatNumber(this.damagePerSecond)} DPS (${formatNumber(this.damageGained)} total damage, excluding EQ).`; if (this.isBugged) { value = `BUGGED`; label = `Master Of The Elements can bug out and not work sometimes. Check the Suggestions for more information.`; } return ( <StatisticBox position={STATISTIC_ORDER.OPTIONAL()} icon={<SpellIcon id={SPELLS.MASTER_OF_THE_ELEMENTS_TALENT.id} />} value={value} label={label} > <table className="table table-condensed"> <thead> <tr> <th>Ability</th> <th>Number of Buffed Casts</th> </tr> </thead> <tbody> {Object.keys(this.moteBuffedAbilities).map((e) => ( <tr key={e}> <th>{<SpellLink id={Number(e)} />}</th> <td>{this.moteBuffedAbilities[e]}</td> </tr> ))} </tbody> </table> </StatisticBox> ); } } export default MasterOfTheElements;
client/modules/Post/__tests__/components/PostListItem.spec.js
acguanacaste/liomysSalvini
import React from 'react'; import test from 'ava'; import sinon from 'sinon'; import PostListItem from '../../components/PostListItem/PostListItem'; import { mountWithIntl, shallowWithIntl } from '../../../../util/react-intl-test-helper'; const post = { name: 'Prashant', title: 'Hello Mern', slug: 'hello-mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'" }; const props = { post, onDelete: () => {}, }; test('renders properly', t => { const wrapper = shallowWithIntl( <PostListItem {...props} /> ); t.truthy(wrapper.hasClass('single-post')); t.is(wrapper.find('Link').first().prop('children'), post.title); t.regex(wrapper.find('.author-name').first().text(), new RegExp(post.name)); t.is(wrapper.find('.post-desc').first().text(), post.content); }); test('has correct props', t => { const wrapper = mountWithIntl( <PostListItem {...props} /> ); t.deepEqual(wrapper.prop('post'), props.post); t.is(wrapper.prop('onClick'), props.onClick); t.is(wrapper.prop('onDelete'), props.onDelete); }); test('calls onDelete', t => { const onDelete = sinon.spy(); const wrapper = shallowWithIntl( <PostListItem post={post} onDelete={onDelete} /> ); wrapper.find('.post-action > a').first().simulate('click'); t.truthy(onDelete.calledOnce); });
node_modules/react-router/es6/RouteUtils.js
jvstrpv/reactredux_2
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import React from 'react'; function isValidChild(object) { return object == null || React.isValidElement(object); } export function isReactChildren(object) { return isValidChild(object) || Array.isArray(object) && object.every(isValidChild); } function createRoute(defaultProps, props) { return _extends({}, defaultProps, props); } export function createRouteFromReactElement(element) { var type = element.type; var route = createRoute(type.defaultProps, element.props); if (route.children) { var childRoutes = createRoutesFromReactChildren(route.children, route); if (childRoutes.length) route.childRoutes = childRoutes; delete route.children; } return route; } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ export function createRoutesFromReactChildren(children, parentRoute) { var routes = []; React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { var route = element.type.createRouteFromReactElement(element, parentRoute); if (route) routes.push(route); } else { routes.push(createRouteFromReactElement(element)); } } }); return routes; } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ export function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes); } else if (routes && !Array.isArray(routes)) { routes = [routes]; } return routes; }
Libraries/Text/Text.js
rickbeerendonk/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Text * @flow */ 'use strict'; const ColorPropType = require('ColorPropType'); const EdgeInsetsPropType = require('EdgeInsetsPropType'); const NativeMethodsMixin = require('NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const PropTypes = require('prop-types'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheetPropType = require('StyleSheetPropType'); const TextStylePropTypes = require('TextStylePropTypes'); const Touchable = require('Touchable'); const createReactClass = require('create-react-class'); const createReactNativeComponentClass = require('createReactNativeComponentClass'); const mergeFast = require('mergeFast'); const processColor = require('processColor'); const stylePropType = StyleSheetPropType(TextStylePropTypes); const viewConfig = { validAttributes: mergeFast(ReactNativeViewAttributes.UIView, { isHighlighted: true, numberOfLines: true, ellipsizeMode: true, allowFontScaling: true, disabled: true, selectable: true, selectionColor: true, adjustsFontSizeToFit: true, minimumFontScale: true, textBreakStrategy: true, }), uiViewClassName: 'RCTText', }; /** * A React component for displaying text. * * `Text` supports nesting, styling, and touch handling. * * In the following example, the nested title and body text will inherit the * `fontFamily` from `styles.baseText`, but the title provides its own * additional styles. The title and body will stack on top of each other on * account of the literal newlines: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, Text, StyleSheet } from 'react-native'; * * export default class TextInANest extends Component { * constructor(props) { * super(props); * this.state = { * titleText: "Bird's Nest", * bodyText: 'This is not really a bird nest.' * }; * } * * render() { * return ( * <Text style={styles.baseText}> * <Text style={styles.titleText} onPress={this.onPressTitle}> * {this.state.titleText}{'\n'}{'\n'} * </Text> * <Text numberOfLines={5}> * {this.state.bodyText} * </Text> * </Text> * ); * } * } * * const styles = StyleSheet.create({ * baseText: { * fontFamily: 'Cochin', * }, * titleText: { * fontSize: 20, * fontWeight: 'bold', * }, * }); * * // skip this line if using Create React Native App * AppRegistry.registerComponent('TextInANest', () => TextInANest); * ``` * * ## Nested text * * Both iOS and Android allow you to display formatted text by annotating * ranges of a string with specific formatting like bold or colored text * (`NSAttributedString` on iOS, `SpannableString` on Android). In practice, * this is very tedious. For React Native, we decided to use web paradigm for * this where you can nest text to achieve the same effect. * * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, Text } from 'react-native'; * * export default class BoldAndBeautiful extends Component { * render() { * return ( * <Text style={{fontWeight: 'bold'}}> * I am bold * <Text style={{color: 'red'}}> * and red * </Text> * </Text> * ); * } * } * * // skip this line if using Create React Native App * AppRegistry.registerComponent('AwesomeProject', () => BoldAndBeautiful); * ``` * * Behind the scenes, React Native converts this to a flat `NSAttributedString` * or `SpannableString` that contains the following information: * * ```javascript * "I am bold and red" * 0-9: bold * 9-17: bold, red * ``` * * ## Nested views (iOS only) * * On iOS, you can nest views within your Text component. Here's an example: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, Text, View } from 'react-native'; * * export default class BlueIsCool extends Component { * render() { * return ( * <Text> * There is a blue square * <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> * in between my text. * </Text> * ); * } * } * * // skip this line if using Create React Native App * AppRegistry.registerComponent('AwesomeProject', () => BlueIsCool); * ``` * * > In order to use this feature, you must give the view a `width` and a `height`. * * ## Containers * * The `<Text>` element is special relative to layout: everything inside is no * longer using the flexbox layout but using text layout. This means that * elements inside of a `<Text>` are no longer rectangles, but wrap when they * see the end of the line. * * ```javascript * <Text> * <Text>First part and </Text> * <Text>second part</Text> * </Text> * // Text container: all the text flows as if it was one * // |First part | * // |and second | * // |part | * * <View> * <Text>First part and </Text> * <Text>second part</Text> * </View> * // View container: each text is its own block * // |First part | * // |and | * // |second part| * ``` * * ## Limited Style Inheritance * * On the web, the usual way to set a font family and size for the entire * document is to take advantage of inherited CSS properties like so: * * ```css * html { * font-family: 'lucida grande', tahoma, verdana, arial, sans-serif; * font-size: 11px; * color: #141823; * } * ``` * * All elements in the document will inherit this font unless they or one of * their parents specifies a new rule. * * In React Native, we are more strict about it: **you must wrap all the text * nodes inside of a `<Text>` component**. You cannot have a text node directly * under a `<View>`. * * * ```javascript * // BAD: will raise exception, can't have a text node as child of a <View> * <View> * Some text * </View> * * // GOOD * <View> * <Text> * Some text * </Text> * </View> * ``` * * You also lose the ability to set up a default font for an entire subtree. * The recommended way to use consistent fonts and sizes across your * application is to create a component `MyAppText` that includes them and use * this component across your app. You can also use this component to make more * specific components like `MyAppHeaderText` for other kinds of text. * * ```javascript * <View> * <MyAppText>Text styled with the default font for the entire application</MyAppText> * <MyAppHeaderText>Text styled as a header</MyAppHeaderText> * </View> * ``` * * Assuming that `MyAppText` is a component that simply renders out its * children into a `Text` component with styling, then `MyAppHeaderText` can be * defined as follows: * * ```javascript * class MyAppHeaderText extends Component { * render() { * return ( * <MyAppText> * <Text style={{fontSize: 20}}> * {this.props.children} * </Text> * </MyAppText> * ); * } * } * ``` * * Composing `MyAppText` in this way ensures that we get the styles from a * top-level component, but leaves us the ability to add / override them in * specific use cases. * * React Native still has the concept of style inheritance, but limited to text * subtrees. In this case, the second part will be both bold and red. * * ```javascript * <Text style={{fontWeight: 'bold'}}> * I am bold * <Text style={{color: 'red'}}> * and red * </Text> * </Text> * ``` * * We believe that this more constrained way to style text will yield better * apps: * * - (Developer) React components are designed with strong isolation in mind: * You should be able to drop a component anywhere in your application, * trusting that as long as the props are the same, it will look and behave the * same way. Text properties that could inherit from outside of the props would * break this isolation. * * - (Implementor) The implementation of React Native is also simplified. We do * not need to have a `fontFamily` field on every single element, and we do not * need to potentially traverse the tree up to the root every time we display a * text node. The style inheritance is only encoded inside of the native Text * component and doesn't leak to other components or the system itself. * */ const Text = createReactClass({ displayName: 'Text', propTypes: { /** * When `numberOfLines` is set, this prop defines how text will be truncated. * `numberOfLines` must be set in conjunction with this prop. * * This can be one of the following values: * * - `head` - The line is displayed so that the end fits in the container and the missing text * at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz" * - `middle` - The line is displayed so that the beginning and end fit in the container and the * missing text in the middle is indicated by an ellipsis glyph. "ab...yz" * - `tail` - The line is displayed so that the beginning fits in the container and the * missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..." * - `clip` - Lines are not drawn past the edge of the text container. * * The default is `tail`. * * > `clip` is working only for iOS */ ellipsizeMode: PropTypes.oneOf(['head', 'middle', 'tail', 'clip']), /** * Used to truncate the text with an ellipsis after computing the text * layout, including line wrapping, such that the total number of lines * does not exceed this number. * * This prop is commonly used with `ellipsizeMode`. */ numberOfLines: PropTypes.number, /** * Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced` * The default value is `highQuality`. * @platform android */ textBreakStrategy: PropTypes.oneOf(['simple', 'highQuality', 'balanced']), /** * Invoked on mount and layout changes with * * `{nativeEvent: {layout: {x, y, width, height}}}` */ onLayout: PropTypes.func, /** * This function is called on press. * * e.g., `onPress={() => console.log('1st')}` */ onPress: PropTypes.func, /** * This function is called on long press. * * e.g., `onLongPress={this.increaseSize}>` */ onLongPress: PropTypes.func, /** * When the scroll view is disabled, this defines how far your touch may * move off of the button, before deactivating the button. Once deactivated, * try moving it back and you'll see that the button is once again * reactivated! Move it back and forth several times while the scroll view * is disabled. Ensure you pass in a constant to reduce memory allocations. */ pressRetentionOffset: EdgeInsetsPropType, /** * Lets the user select text, to use the native copy and paste functionality. */ selectable: PropTypes.bool, /** * The highlight color of the text. * @platform android */ selectionColor: ColorPropType, /** * When `true`, no visual change is made when text is pressed down. By * default, a gray oval highlights the text on press down. * @platform ios */ suppressHighlighting: PropTypes.bool, style: stylePropType, /** * Used to locate this view in end-to-end tests. */ testID: PropTypes.string, /** * Used to locate this view from native code. */ nativeID: PropTypes.string, /** * Specifies whether fonts should scale to respect Text Size accessibility settings. The * default is `true`. */ allowFontScaling: PropTypes.bool, /** * When set to `true`, indicates that the view is an accessibility element. The default value * for a `Text` element is `true`. * * See the * [Accessibility guide](docs/accessibility.html#accessible-ios-android) * for more information. */ accessible: PropTypes.bool, /** * Specifies whether font should be scaled down automatically to fit given style constraints. * @platform ios */ adjustsFontSizeToFit: PropTypes.bool, /** * Specifies smallest possible scale a font can reach when adjustsFontSizeToFit is enabled. (values 0.01-1.0). * @platform ios */ minimumFontScale: PropTypes.number, /** * Specifies the disabled state of the text view for testing purposes * @platform android */ disabled: PropTypes.bool, }, getDefaultProps(): Object { return { accessible: true, allowFontScaling: true, ellipsizeMode: 'tail', }; }, getInitialState: function(): Object { return mergeFast(Touchable.Mixin.touchableGetInitialState(), { isHighlighted: false, }); }, mixins: [NativeMethodsMixin], viewConfig: viewConfig, getChildContext(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: PropTypes.bool }, contextTypes: { isInAParentText: PropTypes.bool }, /** * Only assigned if touch is needed. */ _handlers: (null: ?Object), _hasPressHandler(): boolean { return !!this.props.onPress || !!this.props.onLongPress; }, /** * These are assigned lazily the first time the responder is set to make plain * text nodes as cheap as possible. */ touchableHandleActivePressIn: (null: ?Function), touchableHandleActivePressOut: (null: ?Function), touchableHandlePress: (null: ?Function), touchableHandleLongPress: (null: ?Function), touchableGetPressRectOffset: (null: ?Function), render(): React.Element<any> { let newProps = this.props; if (this.props.onStartShouldSetResponder || this._hasPressHandler()) { if (!this._handlers) { this._handlers = { onStartShouldSetResponder: (): bool => { const shouldSetFromProps = this.props.onStartShouldSetResponder && // $FlowFixMe(>=0.41.0) this.props.onStartShouldSetResponder(); const setResponder = shouldSetFromProps || this._hasPressHandler(); if (setResponder && !this.touchableHandleActivePressIn) { // Attach and bind all the other handlers only the first time a touch // actually happens. for (const key in Touchable.Mixin) { if (typeof Touchable.Mixin[key] === 'function') { (this: any)[key] = Touchable.Mixin[key].bind(this); } } this.touchableHandleActivePressIn = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: true, }); }; this.touchableHandleActivePressOut = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: false, }); }; this.touchableHandlePress = (e: SyntheticEvent<>) => { this.props.onPress && this.props.onPress(e); }; this.touchableHandleLongPress = (e: SyntheticEvent<>) => { this.props.onLongPress && this.props.onLongPress(e); }; this.touchableGetPressRectOffset = function(): RectOffset { return this.props.pressRetentionOffset || PRESS_RECT_OFFSET; }; } return setResponder; }, onResponderGrant: function(e: SyntheticEvent<>, dispatchID: string) { this.touchableHandleResponderGrant(e, dispatchID); this.props.onResponderGrant && this.props.onResponderGrant.apply(this, arguments); }.bind(this), onResponderMove: function(e: SyntheticEvent<>) { this.touchableHandleResponderMove(e); this.props.onResponderMove && this.props.onResponderMove.apply(this, arguments); }.bind(this), onResponderRelease: function(e: SyntheticEvent<>) { this.touchableHandleResponderRelease(e); this.props.onResponderRelease && this.props.onResponderRelease.apply(this, arguments); }.bind(this), onResponderTerminate: function(e: SyntheticEvent<>) { this.touchableHandleResponderTerminate(e); this.props.onResponderTerminate && this.props.onResponderTerminate.apply(this, arguments); }.bind(this), onResponderTerminationRequest: function(): bool { // Allow touchable or props.onResponderTerminationRequest to deny // the request var allowTermination = this.touchableHandleResponderTerminationRequest(); if (allowTermination && this.props.onResponderTerminationRequest) { allowTermination = this.props.onResponderTerminationRequest.apply(this, arguments); } return allowTermination; }.bind(this), }; } newProps = { ...this.props, ...this._handlers, isHighlighted: this.state.isHighlighted, }; } if (newProps.selectionColor != null) { newProps = { ...newProps, selectionColor: processColor(newProps.selectionColor) }; } if (Touchable.TOUCH_TARGET_DEBUG && newProps.onPress) { newProps = { ...newProps, style: [this.props.style, {color: 'magenta'}], }; } if (this.context.isInAParentText) { return <RCTVirtualText {...newProps} />; } else { return <RCTText {...newProps} />; } }, }); type RectOffset = { top: number, left: number, right: number, bottom: number, } var PRESS_RECT_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; var RCTText = createReactNativeComponentClass( viewConfig.uiViewClassName, () => viewConfig ); var RCTVirtualText = RCTText; if (Platform.OS === 'android') { RCTVirtualText = createReactNativeComponentClass('RCTVirtualText', () => ({ validAttributes: mergeFast(ReactNativeViewAttributes.UIView, { isHighlighted: true, }), uiViewClassName: 'RCTVirtualText', })); } module.exports = Text;
App/Components/LandmarkList.js
quickresolve/CycleTheBay
"use strict"; import React, { Component } from 'react'; import { StyleSheet, Text, TouchableOpacity, ScrollView, Image, TabBarIOS, AlertIOS, ListView, View, AppActions, navigator } from 'react-native'; import Trail from './Trail' import Main from './Main' import Weather from './Weather' import Local from './Local' import navAnimations from '../Helper_Functions/navAnimations' class LandmarkList extends Component { constructor(props){ super(props); this.state = { dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), loaded: false, trail_id: this.props.trail_id, landmark_id: '', title: '', desc: '', img_url: '' }; } componentDidMount() { console.log(this.state.trail_id) var url = `http://pacific-meadow-80820.herokuapp.com/api/locations/${this.state.trail_id}/landmarks` this.fetchData(url); } fetchData(url) { fetch(url, {method: "GET"}) .then((response) => response.json()) .then((responseData) => { this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseData), loaded: true, }); }) .done(); } _handleLandmarkSelection(landmark){ var trail_id = this.state.trail_id console.log(trail_id) console.log(landmark.id) fetch('http://pacific-meadow-80820.herokuapp.com/api/locations/'+trail_id+'/landmarks/'+landmark.id) .then((response) => response.json()) .then(responseData => { this.props.navigator.push({ title: landmark.title, name: 'Landmark', passProps: { title: responseData.title, desc: responseData.desc, img_url: responseData.image_url }, }); }).done(); } render() { if (!this.state.loaded) { this.renderLoadingView(); } return( <View style={styles.container}> <View style={styles.header}> <Text style={styles.title}> Landmarks List </Text> </View> <ListView dataSource={this.state.dataSource} renderRow={this.renderLandmark.bind(this)} style={styles.listView} /> <View style={styles.footerNav}> <TouchableOpacity onPress={this._onHomeButton.bind(this)} style={styles.button} underlayColor="gray"> <Text style={styles.buttonText}>Home</Text> </TouchableOpacity> <TouchableOpacity onPress={this._onBackButton.bind(this)} style={styles.button} underlayColor="gray"> <Text style={styles.buttonText}>Back to Overview</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} underlayColor="gray"> <Text style={styles.blankButton}>blank</Text> </TouchableOpacity> </View> </View> ); } renderLoadingView() { return ( <View style={styles.container}> <Text> Loading landmarks... </Text> </View> ) } renderLandmark(landmark) { return ( <View> <Image source={{uri: landmark.image_url}} style={styles.image}> <TouchableOpacity style={styles.row} onPress={(this._handleLandmarkSelection.bind(this, landmark))} underlayColor="white"> <Text style={styles.landmark}> {landmark.title} </Text> </TouchableOpacity> </Image> </View> ); } _onHomeButton(){ this.props.navigator.popToTop() } _onBackButton(){ this.props.navigator.pop() } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'stretch' }, header: { flex: 1, justifyContent: 'center', alignItems: 'center' }, title: { fontSize: 20, marginTop: 25, }, landmark: { flex: 1, fontSize: 20, color: 'white', fontWeight: 'bold', justifyContent: 'center', }, listView: { flex: 10, marginTop: 20 }, row: { flex: 1, alignItems: 'stretch', margin: 20 }, image: { flex: 1, alignItems: 'stretch', marginBottom: 5, padding: 20, width: null, height: 175 }, button: { alignSelf: 'stretch', justifyContent: 'center', marginBottom: 20 }, buttonText:{ color: '#658D9F', fontSize: 18, justifyContent: 'center', alignItems: 'center' }, blankButton:{ color: '#d9d9d9', fontSize: 18, justifyContent: 'center', alignItems: 'center' }, footerNav: { flex: 0, flexDirection: 'row', alignSelf: 'stretch', justifyContent: 'space-between', paddingTop: 15, backgroundColor: '#d9d9d9', paddingLeft: 20, paddingRight: 20 } }); module.exports = LandmarkList;
packages/ringcentral-widgets/components/MultiCallAnswerButton/index.js
u9520107/ringcentral-js-widget
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import AnswerIcon from '../../assets/images/Answer.svg'; import HoldIcon from '../../assets/images/Hold.svg'; import EndIcon from '../../assets/images/End.svg'; import CircleButton from '../CircleButton'; import styles from './styles.scss'; export default function MultiCallAnswerButton(props) { const Icon = props.isEndOtherCall ? EndIcon : HoldIcon; const iconClassName = classnames( styles.button, props.isEndOtherCall ? styles.endButton : '' ); const text = props.title.split('\n').map((line, index) => ( <tspan dy={index ? '1.1em' : 0} x="250" key={line}> {line} </tspan> )); return ( <svg className={props.className} viewBox="0 0 500 600" width={props.width} height={props.height} x={props.x} y={props.y} > <CircleButton width="200" height="200" x={60} y={50} className={iconClassName} onClick={props.onClick} icon={Icon} /> <CircleButton width="250" height="250" x={200} y={110} className={classnames(styles.button, styles.answer)} showBorder={false} onClick={props.onClick} icon={AnswerIcon} /> <text className={styles.buttonTitle} x="250" y="500" textAnchor="middle" > {text} </text> </svg> ); } MultiCallAnswerButton.propTypes = { title: PropTypes.string.isRequired, className: PropTypes.string, onClick: PropTypes.func.isRequired, isEndOtherCall: PropTypes.bool, width: PropTypes.string, height: PropTypes.string, x: PropTypes.number, y: PropTypes.number, }; MultiCallAnswerButton.defaultProps = { className: null, isEndOtherCall: true, width: '100%', height: '100%', x: 0, y: 0, };
src/svg-icons/av/movie.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvMovie = (props) => ( <SvgIcon {...props}> <path d="M18 4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4z"/> </SvgIcon> ); AvMovie = pure(AvMovie); AvMovie.displayName = 'AvMovie'; AvMovie.muiName = 'SvgIcon'; export default AvMovie;
src/svg-icons/navigation/subdirectory-arrow-right.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationSubdirectoryArrowRight = (props) => ( <SvgIcon {...props}> <path d="M19 15l-6 6-1.42-1.42L15.17 16H4V4h2v10h9.17l-3.59-3.58L13 9l6 6z"/> </SvgIcon> ); NavigationSubdirectoryArrowRight = pure(NavigationSubdirectoryArrowRight); NavigationSubdirectoryArrowRight.displayName = 'NavigationSubdirectoryArrowRight'; NavigationSubdirectoryArrowRight.muiName = 'SvgIcon'; export default NavigationSubdirectoryArrowRight;
imports/ui/components/Transition/Slide.js
ShinyLeee/meteor-album-app
import PropTypes from 'prop-types'; import React from 'react'; import CSSTransition from 'react-transition-group/CSSTransition'; const SlideTransition = ({ children, ...props }) => ( <CSSTransition {...props} classNames="slide" timeout={300} appear > {children} </CSSTransition> ); SlideTransition.propTypes = { children: PropTypes.any.isRequired, }; export default SlideTransition;
packages/ringcentral-widgets/components/CopyToClipboard/index.js
ringcentral/ringcentral-js-widget
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { Button } from '../Button'; import styles from './styles.scss'; import i18n from './i18n'; class CopyToClipboard extends Component { executeCopy() { this.copyTextArea.focus(); this.copyTextArea.select(); try { const result = document.execCommand('copy'); if (result) { this.copyTextArea.blur(); if (typeof this.props.handleSuccess === 'function') this.props.handleSuccess(); } else if (typeof this.props.handleFailure === 'function') { this.props.handleFailure(); } } catch (e) { console.error(e); if (typeof this.props.handleFailure === 'function') { this.props.handleFailure(); } } } render() { const { currentLocale, buttonClassName, disabled, copiedText, buttonText, button: CustomButton, } = this.props; return ( <div className={styles.container}> <textarea className={styles.copyTextArea} ref={(ref) => { this.copyTextArea = ref; }} defaultValue={copiedText} /> {CustomButton ? ( <CustomButton {...this.props} executeCopy={() => this.executeCopy()} /> ) : ( <Button disabled={disabled} dataSign="copyToClipboard" className={classnames(styles.primaryButton, buttonClassName)} onClick={() => this.executeCopy()} > {buttonText || i18n.getString('copyToClipboard', currentLocale)} </Button> )} </div> ); } } CopyToClipboard.propTypes = { currentLocale: PropTypes.string.isRequired, handleSuccess: PropTypes.func, handleFailure: PropTypes.func, buttonClassName: PropTypes.string, disabled: PropTypes.bool, copiedText: PropTypes.string, buttonText: PropTypes.string, button: PropTypes.oneOfType([PropTypes.node, PropTypes.func]), }; CopyToClipboard.defaultProps = { handleSuccess: undefined, handleFailure: undefined, buttonClassName: undefined, disabled: undefined, copiedText: undefined, buttonText: undefined, button: undefined, }; export default CopyToClipboard;
node_modules/react-dnd/examples/_dustbin-interesting/index.js
asm-products/notello
'use strict'; import React from 'react'; import Container from './Container'; const DustbinSorted = React.createClass({ render() { return ( <div> <Container /> <hr /> <p> Several different dustbins can handle several types of items. Note that the last dustbin is special: it can handle files from your hard drive and URLs. </p> </div> ); } }); export default DustbinSorted;
static/src/components/StatsPanel.js
Firazenics/finalreckoningbot
// @flow import React from 'react'; import numeral from 'numeral'; import * as StatsActions from '../actions/StatsActions'; import Constants from '../Constants'; const BOTTOM_PADDING = 8; const StatsRow = ({icon, label, value}) => { return ( <div className="stats-row"> <img src={icon} /> <div className="label-value"> <div className="value">{numeral(value).format('0,0')}</div> <div className="label">{label}</div> </div> </div> ); }; type StatsPanelProps = { count: number, uniqueUsers: number, uniqueGuilds: number, uniqueChannels: number, secretCount: number, show: boolean, hasBeenShown: boolean, bottom: number }; const StatsPanel = ({ count, uniqueUsers, uniqueGuilds, uniqueChannels, secretCount, show, hasBeenShown, bottom }: StatsPanelProps) => { if (!hasBeenShown) { return <noscript />; } return ( <div className={`stats-panel crossfade ${show ? 'one' : 'one-reverse'}`} style={{bottom: bottom + BOTTOM_PADDING}}> <StatsRow icon={Constants.Image.ICON_PLAYS} label="Plays" value={count} /> <StatsRow icon={Constants.Image.ICON_USERS} label="Unique Users" value={uniqueUsers} /> <StatsRow icon={Constants.Image.ICON_SERVERS} label="Unique Servers" value={uniqueGuilds} /> <StatsRow icon={Constants.Image.ICON_CHANNELS} label="Unique Channels" value={uniqueChannels} /> <StatsRow icon={Constants.Image.ICON_SECERT} label="Secret Plays" value={secretCount} /> </div> ); }; export default StatsPanel;
2021/src/components/Typography/Text.js
sjamcsclub/jamhacks.ca
import React from 'react'; import styled from 'styled-components'; import { media } from '../../utils/media'; const Text = styled.p` color: ${(props) => props.dark ? props.theme.colors.text.dark.text : props.theme.colors.text.light.text}; &::selection { background: ${(props) => props.dark ? props.theme.colors.secondary.default : props.theme.colors.primary.default}; } font-size: 1.2rem; font-style: normal; font-weight: normal; line-height: 140%; font-family: ${(props) => props.theme.fonts.secondary}; ${media('md')` font-size: 1.1rem; `} ${media('sm')` font-size: 1rem; `} `; export default Text;
app/js/components/LoadingIndicator.js
niksoc/srmconnect
import React from 'react'; const LoadingIndicator = ()=>(<p>loading...</p>); export default LoadingIndicator;
packages/icons/src/dv/Fortran.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function DvFortran(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M7.314 38.048h2.954c1.637 0 3.246-.925 3.246-3.224V13.176c0-2.912-.97-3.224-3.987-3.224H7.5V6h33.186v14.362h-3.87c0-3.431-.392-5.939-1.373-7.81-1.08-2.08-3.292-2.6-7.167-2.6h-7.893v11.451h1.532c4.472 0 5.657-1.12 5.563-7.084h3.49v18.582h-3.49c-.312-5.98-.647-8.115-6.251-8.05h-.936v9.973c0 2.912 1.208 3.224 4.224 3.224h2.166V42H7.314v-3.952z" /> </IconBase> ); } export default DvFortran;
src/server.js
wework/react-redux-universal-hot-example
import Express from 'express'; import React from 'react'; import Location from 'react-router/lib/Location'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/create'; import api from './api/api'; import ApiClient from './helpers/ApiClient'; import universalRouter from './helpers/universalRouter'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; const pretty = new PrettyError(); const app = new Express(); const proxy = httpProxy.createProxyServer({ target: 'http://localhost:' + config.apiPort }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(require('serve-static')(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { let json; console.log('proxy error', error); if (!res.headersSent) { res.writeHead(500, {'content-type': 'application/json'}); } json = { error: 'proxy_error', reason: error.message }; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const store = createStore(client); const location = new Location(req.path, req.query); const hydrateOnClient = function() { res.send('<!doctype html>\n' + React.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={<div/>} store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } else { universalRouter(location, undefined, store) .then(({component, transition, isRedirect}) => { if (isRedirect) { res.redirect(transition.redirectInfo.pathname); return; } res.send('<!doctype html>\n' + React.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }) .catch((error) => { if (error.redirect) { res.redirect(error.redirect); return; } console.error('ROUTER ERROR:', pretty.render(error)); hydrateOnClient(); // let client render error page or re-request data }); } }); if (config.port) { app.listen(config.port, (err) => { if (err) { console.error(err); } else { api().then(() => { console.info('==> ✅ Server is listening'); console.info('==> 🌎 %s running on port %s, API on port %s', config.app.name, config.port, config.apiPort); console.info('----------\n==> 💻 Open http://localhost:%s in a browser to view the app.', config.port); }); } }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }